source: src/ResolvExpr/Unify.cc @ 4a3386b4

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 4a3386b4 was f3b0a07, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

allow ttypes contained in tuple types to unify, refactor and simplify Specialize pass

  • Property mode set to 100644
File size: 31.7 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// Unify.cc --
8//
9// Author           : Richard C. Bilson
10// Created On       : Sun May 17 12:27:10 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Wed Mar  2 17:37:05 2016
13// Update Count     : 37
14//
15
16#include <set>
17#include <memory>
18
19#include "Unify.h"
20#include "TypeEnvironment.h"
21#include "typeops.h"
22#include "FindOpenVars.h"
23#include "SynTree/Visitor.h"
24#include "SynTree/Type.h"
25#include "SynTree/Declaration.h"
26#include "SymTab/Indexer.h"
27#include "Common/utility.h"
28#include "Tuples/Tuples.h"
29
30// #define DEBUG
31
32namespace ResolvExpr {
33
34        class Unify : public Visitor {
35          public:
36                Unify( Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widenMode, const SymTab::Indexer &indexer );
37
38                bool get_result() const { return result; }
39          private:
40                virtual void visit(VoidType *voidType);
41                virtual void visit(BasicType *basicType);
42                virtual void visit(PointerType *pointerType);
43                virtual void visit(ArrayType *arrayType);
44                virtual void visit(FunctionType *functionType);
45                virtual void visit(StructInstType *aggregateUseType);
46                virtual void visit(UnionInstType *aggregateUseType);
47                virtual void visit(EnumInstType *aggregateUseType);
48                virtual void visit(TraitInstType *aggregateUseType);
49                virtual void visit(TypeInstType *aggregateUseType);
50                virtual void visit(TupleType *tupleType);
51                virtual void visit(VarArgsType *varArgsType);
52                virtual void visit(ZeroType *zeroType);
53                virtual void visit(OneType *oneType);
54
55                template< typename RefType > void handleRefType( RefType *inst, Type *other );
56                template< typename RefType > void handleGenericRefType( RefType *inst, Type *other );
57
58                bool result;
59                Type *type2;                            // inherited
60                TypeEnvironment &env;
61                AssertionSet &needAssertions;
62                AssertionSet &haveAssertions;
63                const OpenVarSet &openVars;
64                WidenMode widenMode;
65                const SymTab::Indexer &indexer;
66        };
67
68        /// Attempts an inexact unification of type1 and type2.
69        /// Returns false if no such unification; if the types can be unified, sets common (unless they unify exactly and have identical type qualifiers)
70        bool unifyInexact( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widenMode, const SymTab::Indexer &indexer, Type *&common );
71        bool unifyExact( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widenMode, const SymTab::Indexer &indexer );
72
73        bool typesCompatible( Type *first, Type *second, const SymTab::Indexer &indexer, const TypeEnvironment &env ) {
74                TypeEnvironment newEnv;
75                OpenVarSet openVars, closedVars; // added closedVars
76                AssertionSet needAssertions, haveAssertions;
77                Type *newFirst = first->clone(), *newSecond = second->clone();
78                env.apply( newFirst );
79                env.apply( newSecond );
80
81                // do we need to do this? Seems like we do, types should be able to be compatible if they
82                // have free variables that can unify
83                findOpenVars( newFirst, openVars, closedVars, needAssertions, haveAssertions, false );
84                findOpenVars( newSecond, openVars, closedVars, needAssertions, haveAssertions, true );
85
86                bool result = unifyExact( newFirst, newSecond, newEnv, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
87                delete newFirst;
88                delete newSecond;
89                return result;
90        }
91
92        bool typesCompatibleIgnoreQualifiers( Type *first, Type *second, const SymTab::Indexer &indexer, const TypeEnvironment &env ) {
93                TypeEnvironment newEnv;
94                OpenVarSet openVars;
95                AssertionSet needAssertions, haveAssertions;
96                Type *newFirst = first->clone(), *newSecond = second->clone();
97                env.apply( newFirst );
98                env.apply( newSecond );
99                newFirst->get_qualifiers() = Type::Qualifiers();
100                newSecond->get_qualifiers() = Type::Qualifiers();
101///   std::cerr << "first is ";
102///   first->print( std::cerr );
103///   std::cerr << std::endl << "second is ";
104///   second->print( std::cerr );
105///   std::cerr << std::endl << "newFirst is ";
106///   newFirst->print( std::cerr );
107///   std::cerr << std::endl << "newSecond is ";
108///   newSecond->print( std::cerr );
109///   std::cerr << std::endl;
110                bool result = unifyExact( newFirst, newSecond, newEnv, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
111                delete newFirst;
112                delete newSecond;
113                return result;
114        }
115
116        bool isFtype( Type *type, const SymTab::Indexer &indexer ) {
117                if ( dynamic_cast< FunctionType* >( type ) ) {
118                        return true;
119                } else if ( TypeInstType *typeInst = dynamic_cast< TypeInstType* >( type ) ) {
120                        return typeInst->get_isFtype();
121                } // if
122                return false;
123        }
124
125        struct CompleteTypeChecker : public Visitor {
126                virtual void visit( VoidType *basicType ) { status = false; }
127                virtual void visit( BasicType *basicType ) {}
128                virtual void visit( PointerType *pointerType ) {}
129                virtual void visit( ArrayType *arrayType ) { status = ! arrayType->get_isVarLen(); }
130                virtual void visit( FunctionType *functionType ) {}
131                virtual void visit( StructInstType *aggregateUseType ) { status = aggregateUseType->get_baseStruct()->has_body(); }
132                virtual void visit( UnionInstType *aggregateUseType ) { status = aggregateUseType->get_baseUnion()->has_body(); }
133                // xxx - enum inst does not currently contain a pointer to base, this should be fixed.
134                virtual void visit( EnumInstType *aggregateUseType ) { /* status = aggregateUseType->get_baseEnum()->hasBody(); */ }
135                virtual void visit( TraitInstType *aggregateUseType ) { assert( false ); }
136                virtual void visit( TypeInstType *aggregateUseType ) { status = aggregateUseType->get_baseType()->isComplete(); }
137                virtual void visit( TupleType *tupleType ) {} // xxx - not sure if this is right, might need to recursively check complete-ness
138                virtual void visit( TypeofType *typeofType ) { assert( false ); }
139                virtual void visit( AttrType *attrType ) { assert( false ); } // xxx - not sure what to do here
140                virtual void visit( VarArgsType *varArgsType ){} // xxx - is this right?
141                virtual void visit( ZeroType *zeroType ) {}
142                virtual void visit( OneType *oneType ) {}
143                bool status = true;
144        };
145        bool isComplete( Type * type ) {
146                CompleteTypeChecker checker;
147                assert( type );
148                type->accept( checker );
149                return checker.status;
150        }
151
152        bool tyVarCompatible( const TypeDecl::Data & data, Type *type, const SymTab::Indexer &indexer ) {
153                switch ( data.kind ) {
154                  case TypeDecl::Any:
155                  case TypeDecl::Dtype:
156                        // to bind to an object type variable, the type must not be a function type.
157                        // if the type variable is specified to be a complete type then the incoming
158                        // type must also be complete
159                        // xxx - should this also check that type is not a tuple type and that it's not a ttype?
160                        return ! isFtype( type, indexer ) && (! data.isComplete || isComplete( type ));
161                  case TypeDecl::Ftype:
162                        return isFtype( type, indexer );
163                        case TypeDecl::Ttype:
164                        // ttype unifies with any tuple type
165                        return dynamic_cast< TupleType * >( type ) || Tuples::isTtype( type );
166                } // switch
167                return false;
168        }
169
170        bool bindVar( TypeInstType *typeInst, Type *other, const TypeDecl::Data & data, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widenMode, const SymTab::Indexer &indexer ) {
171                OpenVarSet::const_iterator tyvar = openVars.find( typeInst->get_name() );
172                assert( tyvar != openVars.end() );
173                if ( ! tyVarCompatible( tyvar->second, other, indexer ) ) {
174                        return false;
175                } // if
176                if ( occurs( other, typeInst->get_name(), env ) ) {
177                        return false;
178                } // if
179                EqvClass curClass;
180                if ( env.lookup( typeInst->get_name(), curClass ) ) {
181                        if ( curClass.type ) {
182                                Type *common = 0;
183                                // attempt to unify equivalence class type (which has qualifiers stripped, so they must be restored) with the type to bind to
184                                std::auto_ptr< Type > newType( curClass.type->clone() );
185                                newType->get_qualifiers() = typeInst->get_qualifiers();
186                                if ( unifyInexact( newType.get(), other, env, needAssertions, haveAssertions, openVars, widenMode & WidenMode( curClass.allowWidening, true ), indexer, common ) ) {
187                                        if ( common ) {
188                                                common->get_qualifiers() = Type::Qualifiers();
189                                                delete curClass.type;
190                                                curClass.type = common;
191                                                env.add( curClass );
192                                        } // if
193                                        return true;
194                                } else {
195                                        return false;
196                                } // if
197                        } else {
198                                curClass.type = other->clone();
199                                curClass.type->get_qualifiers() = Type::Qualifiers();
200                                curClass.allowWidening = widenMode.widenFirst && widenMode.widenSecond;
201                                env.add( curClass );
202                        } // if
203                } else {
204                        EqvClass newClass;
205                        newClass.vars.insert( typeInst->get_name() );
206                        newClass.type = other->clone();
207                        newClass.type->get_qualifiers() = Type::Qualifiers();
208                        newClass.allowWidening = widenMode.widenFirst && widenMode.widenSecond;
209                        newClass.data = data;
210                        env.add( newClass );
211                } // if
212                return true;
213        }
214
215        bool bindVarToVar( TypeInstType *var1, TypeInstType *var2, const TypeDecl::Data & data, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widenMode, const SymTab::Indexer &indexer ) {
216                bool result = true;
217                EqvClass class1, class2;
218                bool hasClass1 = false, hasClass2 = false;
219                bool widen1 = false, widen2 = false;
220                Type *type1 = 0, *type2 = 0;
221
222                if ( env.lookup( var1->get_name(), class1 ) ) {
223                        hasClass1 = true;
224                        if ( class1.type ) {
225                                if ( occurs( class1.type, var2->get_name(), env ) ) {
226                                        return false;
227                                } // if
228                                type1 = class1.type->clone();
229                        } // if
230                        widen1 = widenMode.widenFirst && class1.allowWidening;
231                } // if
232                if ( env.lookup( var2->get_name(), class2 ) ) {
233                        hasClass2 = true;
234                        if ( class2.type ) {
235                                if ( occurs( class2.type, var1->get_name(), env ) ) {
236                                        return false;
237                                } // if
238                                type2 = class2.type->clone();
239                        } // if
240                        widen2 = widenMode.widenSecond && class2.allowWidening;
241                } // if
242
243                if ( type1 && type2 ) {
244//    std::cerr << "has type1 && type2" << std::endl;
245                        WidenMode newWidenMode ( widen1, widen2 );
246                        Type *common = 0;
247                        if ( unifyInexact( type1, type2, env, needAssertions, haveAssertions, openVars, newWidenMode, indexer, common ) ) {
248                                class1.vars.insert( class2.vars.begin(), class2.vars.end() );
249                                class1.allowWidening = widen1 && widen2;
250                                if ( common ) {
251                                        common->get_qualifiers() = Type::Qualifiers();
252                                        delete class1.type;
253                                        class1.type = common;
254                                } // if
255                                env.add( class1 );
256                        } else {
257                                result = false;
258                        } // if
259                } else if ( hasClass1 && hasClass2 ) {
260                        if ( type1 ) {
261                                class1.vars.insert( class2.vars.begin(), class2.vars.end() );
262                                class1.allowWidening = widen1;
263                                env.add( class1 );
264                        } else {
265                                class2.vars.insert( class1.vars.begin(), class1.vars.end() );
266                                class2.allowWidening = widen2;
267                                env.add( class2 );
268                        } // if
269                } else if ( hasClass1 ) {
270                        class1.vars.insert( var2->get_name() );
271                        class1.allowWidening = widen1;
272                        env.add( class1 );
273                } else if ( hasClass2 ) {
274                        class2.vars.insert( var1->get_name() );
275                        class2.allowWidening = widen2;
276                        env.add( class2 );
277                } else {
278                        EqvClass newClass;
279                        newClass.vars.insert( var1->get_name() );
280                        newClass.vars.insert( var2->get_name() );
281                        newClass.allowWidening = widen1 && widen2;
282                        newClass.data = data;
283                        env.add( newClass );
284                } // if
285                delete type1;
286                delete type2;
287                return result;
288        }
289
290        bool unify( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, OpenVarSet &openVars, const SymTab::Indexer &indexer ) {
291                OpenVarSet closedVars;
292                findOpenVars( type1, openVars, closedVars, needAssertions, haveAssertions, false );
293                findOpenVars( type2, openVars, closedVars, needAssertions, haveAssertions, true );
294                Type *commonType = 0;
295                if ( unifyInexact( type1, type2, env, needAssertions, haveAssertions, openVars, WidenMode( true, true ), indexer, commonType ) ) {
296                        if ( commonType ) {
297                                delete commonType;
298                        } // if
299                        return true;
300                } else {
301                        return false;
302                } // if
303        }
304
305        bool unify( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, OpenVarSet &openVars, const SymTab::Indexer &indexer, Type *&commonType ) {
306                OpenVarSet closedVars;
307                findOpenVars( type1, openVars, closedVars, needAssertions, haveAssertions, false );
308                findOpenVars( type2, openVars, closedVars, needAssertions, haveAssertions, true );
309                return unifyInexact( type1, type2, env, needAssertions, haveAssertions, openVars, WidenMode( true, true ), indexer, commonType );
310        }
311
312        bool unifyExact( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widenMode, const SymTab::Indexer &indexer ) {
313#ifdef DEBUG
314                TypeEnvironment debugEnv( env );
315#endif
316                if ( type1->get_qualifiers() != type2->get_qualifiers() ) {
317                        return false;
318                }
319
320                bool result;
321                TypeInstType *var1 = dynamic_cast< TypeInstType* >( type1 );
322                TypeInstType *var2 = dynamic_cast< TypeInstType* >( type2 );
323                OpenVarSet::const_iterator entry1, entry2;
324                if ( var1 ) {
325                        entry1 = openVars.find( var1->get_name() );
326                } // if
327                if ( var2 ) {
328                        entry2 = openVars.find( var2->get_name() );
329                } // if
330                bool isopen1 = var1 && ( entry1 != openVars.end() );
331                bool isopen2 = var2 && ( entry2 != openVars.end() );
332
333                if ( isopen1 && isopen2 && entry1->second == entry2->second ) {
334                        result = bindVarToVar( var1, var2, entry1->second, env, needAssertions, haveAssertions, openVars, widenMode, indexer );
335                } else if ( isopen1 ) {
336                        result = bindVar( var1, type2, entry1->second, env, needAssertions, haveAssertions, openVars, widenMode, indexer );
337                } else if ( isopen2 ) {
338                        result = bindVar( var2, type1, entry2->second, env, needAssertions, haveAssertions, openVars, widenMode, indexer );
339                } else {
340                        Unify comparator( type2, env, needAssertions, haveAssertions, openVars, widenMode, indexer );
341                        type1->accept( comparator );
342                        result = comparator.get_result();
343                } // if
344#ifdef DEBUG
345                std::cerr << "============ unifyExact" << std::endl;
346                std::cerr << "type1 is ";
347                type1->print( std::cerr );
348                std::cerr << std::endl << "type2 is ";
349                type2->print( std::cerr );
350                std::cerr << std::endl << "openVars are ";
351                printOpenVarSet( openVars, std::cerr, 8 );
352                std::cerr << std::endl << "input env is " << std::endl;
353                debugEnv.print( std::cerr, 8 );
354                std::cerr << std::endl << "result env is " << std::endl;
355                env.print( std::cerr, 8 );
356                std::cerr << "result is " << result << std::endl;
357#endif
358                return result;
359        }
360
361        bool unifyExact( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, OpenVarSet &openVars, const SymTab::Indexer &indexer ) {
362                return unifyExact( type1, type2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
363        }
364
365        bool unifyInexact( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widenMode, const SymTab::Indexer &indexer, Type *&common ) {
366                Type::Qualifiers tq1 = type1->get_qualifiers(), tq2 = type2->get_qualifiers();
367                type1->get_qualifiers() = Type::Qualifiers();
368                type2->get_qualifiers() = Type::Qualifiers();
369                bool result;
370#ifdef DEBUG
371                std::cerr << "unifyInexact type 1 is ";
372                type1->print( std::cerr );
373                std::cerr << "type 2 is ";
374                type2->print( std::cerr );
375                std::cerr << std::endl;
376#endif
377                if ( ! unifyExact( type1, type2, env, needAssertions, haveAssertions, openVars, widenMode, indexer ) ) {
378#ifdef DEBUG
379                        std::cerr << "unifyInexact: no exact unification found" << std::endl;
380#endif
381                        if ( ( common = commonType( type1, type2, widenMode.widenFirst, widenMode.widenSecond, indexer, env, openVars ) ) ) {
382                                common->get_qualifiers() = tq1 + tq2;
383#ifdef DEBUG
384                                std::cerr << "unifyInexact: common type is ";
385                                common->print( std::cerr );
386                                std::cerr << std::endl;
387#endif
388                                result = true;
389                        } else {
390#ifdef DEBUG
391                                std::cerr << "unifyInexact: no common type found" << std::endl;
392#endif
393                                result = false;
394                        } // if
395                } else {
396                        if ( tq1 != tq2 ) {
397                                if ( ( tq1 > tq2 || widenMode.widenFirst ) && ( tq2 > tq1 || widenMode.widenSecond ) ) {
398                                        common = type1->clone();
399                                        common->get_qualifiers() = tq1 + tq2;
400                                        result = true;
401                                } else {
402                                        result = false;
403                                } // if
404                        } else {
405                                result = true;
406                        } // if
407                } // if
408                type1->get_qualifiers() = tq1;
409                type2->get_qualifiers() = tq2;
410                return result;
411        }
412
413        Unify::Unify( Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widenMode, const SymTab::Indexer &indexer )
414                : result( false ), type2( type2 ), env( env ), needAssertions( needAssertions ), haveAssertions( haveAssertions ), openVars( openVars ), widenMode( widenMode ), indexer( indexer ) {
415        }
416
417        void Unify::visit(VoidType *voidType) {
418                result = dynamic_cast< VoidType* >( type2 );
419        }
420
421        void Unify::visit(BasicType *basicType) {
422                if ( BasicType *otherBasic = dynamic_cast< BasicType* >( type2 ) ) {
423                        result = basicType->get_kind() == otherBasic->get_kind();
424                } // if
425        }
426
427        void markAssertionSet( AssertionSet &assertions, DeclarationWithType *assert ) {
428///   std::cerr << "assertion set is" << std::endl;
429///   printAssertionSet( assertions, std::cerr, 8 );
430///   std::cerr << "looking for ";
431///   assert->print( std::cerr );
432///   std::cerr << std::endl;
433                AssertionSet::iterator i = assertions.find( assert );
434                if ( i != assertions.end() ) {
435///     std::cerr << "found it!" << std::endl;
436                        i->second.isUsed = true;
437                } // if
438        }
439
440        void markAssertions( AssertionSet &assertion1, AssertionSet &assertion2, Type *type ) {
441                for ( std::list< TypeDecl* >::const_iterator tyvar = type->get_forall().begin(); tyvar != type->get_forall().end(); ++tyvar ) {
442                        for ( std::list< DeclarationWithType* >::const_iterator assert = (*tyvar)->get_assertions().begin(); assert != (*tyvar)->get_assertions().end(); ++assert ) {
443                                markAssertionSet( assertion1, *assert );
444                                markAssertionSet( assertion2, *assert );
445                        } // for
446                } // for
447        }
448
449        void Unify::visit(PointerType *pointerType) {
450                if ( PointerType *otherPointer = dynamic_cast< PointerType* >( type2 ) ) {
451                        result = unifyExact( pointerType->get_base(), otherPointer->get_base(), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
452                        markAssertions( haveAssertions, needAssertions, pointerType );
453                        markAssertions( haveAssertions, needAssertions, otherPointer );
454                } // if
455        }
456
457        void Unify::visit(ArrayType *arrayType) {
458                ArrayType *otherArray = dynamic_cast< ArrayType* >( type2 );
459                // to unify, array types must both be VLA or both not VLA
460                // and must both have a dimension expression or not have a dimension
461                if ( otherArray && arrayType->get_isVarLen() == otherArray->get_isVarLen() ) {
462
463                        // not positive this is correct in all cases, but it's needed for typedefs
464                        if ( arrayType->get_isVarLen() || otherArray->get_isVarLen() ) {
465                                return;
466                        }
467
468                        if ( ! arrayType->get_isVarLen() && ! otherArray->get_isVarLen() &&
469                                arrayType->get_dimension() != 0 && otherArray->get_dimension() != 0 ) {
470                                ConstantExpr * ce1 = dynamic_cast< ConstantExpr * >( arrayType->get_dimension() );
471                                ConstantExpr * ce2 = dynamic_cast< ConstantExpr * >( otherArray->get_dimension() );
472                                // see C11 Reference Manual 6.7.6.2.6
473                                // two array types with size specifiers that are integer constant expressions are
474                                // compatible if both size specifiers have the same constant value
475                                if ( ce1 && ce2 ) {
476                                        Constant * c1 = ce1->get_constant();
477                                        Constant * c2 = ce2->get_constant();
478
479                                        if ( c1->get_value() != c2->get_value() ) {
480                                                // does not unify if the dimension is different
481                                                return;
482                                        }
483                                }
484                        }
485
486                        result = unifyExact( arrayType->get_base(), otherArray->get_base(), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
487                } // if
488        }
489
490        template< typename Iterator, typename Func >
491        std::unique_ptr<Type> combineTypes( Iterator begin, Iterator end, Func & toType ) {
492                std::list< Type * > types;
493                for ( ; begin != end; ++begin ) {
494                        // it's guaranteed that a ttype variable will be bound to a flat tuple, so ensure that this results in a flat tuple
495                        flatten( toType( *begin ), back_inserter( types ) );
496                }
497                return std::unique_ptr<Type>( new TupleType( Type::Qualifiers(), types ) );
498        }
499
500        template< typename Iterator1, typename Iterator2 >
501        bool unifyDeclList( Iterator1 list1Begin, Iterator1 list1End, Iterator2 list2Begin, Iterator2 list2End, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, const SymTab::Indexer &indexer ) {
502                auto get_type = [](DeclarationWithType * dwt){ return dwt->get_type(); };
503                for ( ; list1Begin != list1End && list2Begin != list2End; ++list1Begin, ++list2Begin ) {
504                        Type * t1 = (*list1Begin)->get_type();
505                        Type * t2 = (*list2Begin)->get_type();
506                        bool isTtype1 = Tuples::isTtype( t1 );
507                        bool isTtype2 = Tuples::isTtype( t2 );
508                        // xxx - assumes ttype must be last parameter
509                        // xxx - there may be a nice way to refactor this, but be careful because the argument positioning might matter in some cases.
510                        if ( isTtype1 && ! isTtype2 ) {
511                                // combine all of the things in list2, then unify
512                                return unifyExact( t1, combineTypes( list2Begin, list2End, get_type ).get(), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
513                        } else if ( isTtype2 && ! isTtype1 ) {
514                                // combine all of the things in list1, then unify
515                                return unifyExact( combineTypes( list1Begin, list1End, get_type ).get(), t2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
516                        } else if ( ! unifyExact( t1, t2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer ) ) {
517                                return false;
518                        } // if
519                } // for
520                // may get to the end of one argument list before the end of the other. This is only okay when the other is a ttype
521                if ( list1Begin != list1End ) {
522                        // try unifying empty tuple type with ttype
523                        Type * t1 = (*list1Begin)->get_type();
524                        if ( Tuples::isTtype( t1 ) ) {
525                                return unifyExact( t1, combineTypes( list2Begin, list2End, get_type ).get(), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
526                        } else return false;
527                } else if ( list2Begin != list2End ) {
528                        // try unifying empty tuple type with ttype
529                        Type * t2 = (*list2Begin)->get_type();
530                        if ( Tuples::isTtype( t2 ) ) {
531                                return unifyExact( combineTypes( list1Begin, list1End, get_type ).get(), t2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
532                        } else return false;
533                } else {
534                        return true;
535                } // if
536        }
537
538        /// Finds ttypes and replaces them with their expansion, if known.
539        /// This needs to be done so that satisfying ttype assertions is easier.
540        /// If this isn't done then argument lists can have wildly different
541        /// size and structure, when they should be compatible.
542        struct TtypeExpander : public Mutator {
543                TypeEnvironment & env;
544                TtypeExpander( TypeEnvironment & env ) : env( env ) {}
545                Type * mutate( TypeInstType * typeInst ) {
546                        EqvClass eqvClass;
547                        if ( env.lookup( typeInst->get_name(), eqvClass ) ) {
548                                if ( eqvClass.data.kind == TypeDecl::Ttype ) {
549                                        // expand ttype parameter into its actual type
550                                        if ( eqvClass.type ) {
551                                                delete typeInst;
552                                                return eqvClass.type->clone();
553                                        }
554                                }
555                        }
556                        return typeInst;
557                }
558        };
559
560        /// flattens a list of declarations, so that each tuple type has a single declaration.
561        /// makes use of TtypeExpander to ensure ttypes are flat as well.
562        void flattenList( std::list< DeclarationWithType * > src, std::list< DeclarationWithType * > & dst, TypeEnvironment & env ) {
563                dst.clear();
564                for ( DeclarationWithType * dcl : src ) {
565                        TtypeExpander expander( env );
566                        dcl->acceptMutator( expander );
567                        std::list< Type * > types;
568                        flatten( dcl->get_type(), back_inserter( types ) );
569                        for ( Type * t : types ) {
570                                dst.push_back( new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::C, nullptr, t, nullptr ) );
571                        }
572                        delete dcl;
573                }
574        }
575
576        void Unify::visit(FunctionType *functionType) {
577                FunctionType *otherFunction = dynamic_cast< FunctionType* >( type2 );
578                if ( otherFunction && functionType->get_isVarArgs() == otherFunction->get_isVarArgs() ) {
579                        // flatten the parameter lists for both functions so that tuple structure
580                        // doesn't affect unification. Must be a clone so that the types don't change.
581                        std::unique_ptr<FunctionType> flatFunc( functionType->clone() );
582                        std::unique_ptr<FunctionType> flatOther( otherFunction->clone() );
583                        flattenList( flatFunc->get_parameters(), flatFunc->get_parameters(), env );
584                        flattenList( flatOther->get_parameters(), flatOther->get_parameters(), env );
585
586                        // sizes don't have to match if ttypes are involved; need to be more precise wrt where the ttype is to prevent errors
587                        if ( (flatFunc->get_parameters().size() == flatOther->get_parameters().size() && flatFunc->get_returnVals().size() == flatOther->get_returnVals().size()) || flatFunc->isTtype() || flatOther->isTtype() ) {
588                                if ( unifyDeclList( flatFunc->get_parameters().begin(), flatFunc->get_parameters().end(), flatOther->get_parameters().begin(), flatOther->get_parameters().end(), env, needAssertions, haveAssertions, openVars, indexer ) ) {
589                                        if ( unifyDeclList( flatFunc->get_returnVals().begin(), flatFunc->get_returnVals().end(), flatOther->get_returnVals().begin(), flatOther->get_returnVals().end(), env, needAssertions, haveAssertions, openVars, indexer ) ) {
590
591                                                // the original types must be used in mark assertions, since pointer comparisons are used
592                                                markAssertions( haveAssertions, needAssertions, functionType );
593                                                markAssertions( haveAssertions, needAssertions, otherFunction );
594
595                                                result = true;
596                                        } // if
597                                } // if
598                        } // if
599                } // if
600        }
601
602        template< typename RefType >
603        void Unify::handleRefType( RefType *inst, Type *other ) {
604                // check that other type is compatible and named the same
605                RefType *otherStruct = dynamic_cast< RefType* >( other );
606                result = otherStruct && inst->get_name() == otherStruct->get_name();
607        }
608
609        template< typename RefType >
610        void Unify::handleGenericRefType( RefType *inst, Type *other ) {
611                // Check that other type is compatible and named the same
612                handleRefType( inst, other );
613                if ( ! result ) return;
614                // Check that parameters of types unify, if any
615                std::list< Expression* > params = inst->get_parameters();
616                std::list< Expression* > otherParams = ((RefType*)other)->get_parameters();
617
618                std::list< Expression* >::const_iterator it = params.begin(), jt = otherParams.begin();
619                for ( ; it != params.end() && jt != otherParams.end(); ++it, ++jt ) {
620                        TypeExpr *param = dynamic_cast< TypeExpr* >(*it);
621                        assert(param && "Aggregate parameters should be type expressions");
622                        TypeExpr *otherParam = dynamic_cast< TypeExpr* >(*jt);
623                        assert(otherParam && "Aggregate parameters should be type expressions");
624
625                        if ( ! unifyExact( param->get_type(), otherParam->get_type(), env, needAssertions, haveAssertions, openVars, WidenMode(false, false), indexer ) ) {
626                                result = false;
627                                return;
628                        }
629                }
630                result = ( it == params.end() && jt == otherParams.end() );
631        }
632
633        void Unify::visit(StructInstType *structInst) {
634                handleGenericRefType( structInst, type2 );
635        }
636
637        void Unify::visit(UnionInstType *unionInst) {
638                handleGenericRefType( unionInst, type2 );
639        }
640
641        void Unify::visit(EnumInstType *enumInst) {
642                handleRefType( enumInst, type2 );
643        }
644
645        void Unify::visit(TraitInstType *contextInst) {
646                handleRefType( contextInst, type2 );
647        }
648
649        void Unify::visit(TypeInstType *typeInst) {
650                assert( openVars.find( typeInst->get_name() ) == openVars.end() );
651                TypeInstType *otherInst = dynamic_cast< TypeInstType* >( type2 );
652                if ( otherInst && typeInst->get_name() == otherInst->get_name() ) {
653                        result = true;
654///   } else {
655///     NamedTypeDecl *nt = indexer.lookupType( typeInst->get_name() );
656///     if ( nt ) {
657///       TypeDecl *type = dynamic_cast< TypeDecl* >( nt );
658///       assert( type );
659///       if ( type->get_base() ) {
660///         result = unifyExact( type->get_base(), typeInst, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
661///       }
662///     }
663                } // if
664        }
665
666        template< typename Iterator1, typename Iterator2 >
667        bool unifyList( Iterator1 list1Begin, Iterator1 list1End, Iterator2 list2Begin, Iterator2 list2End, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widenMode, const SymTab::Indexer &indexer ) {
668                auto get_type = [](Type * t) { return t; };
669                for ( ; list1Begin != list1End && list2Begin != list2End; ++list1Begin, ++list2Begin ) {
670                        Type * t1 = *list1Begin;
671                        Type * t2 = *list2Begin;
672                        bool isTtype1 = Tuples::isTtype( t1 );
673                        bool isTtype2 = Tuples::isTtype( t2 );
674                        // xxx - assumes ttype must be last parameter
675                        // xxx - there may be a nice way to refactor this, but be careful because the argument positioning might matter in some cases.
676                        if ( isTtype1 && ! isTtype2 ) {
677                                // combine all of the things in list2, then unify
678                                return unifyExact( t1, combineTypes( list2Begin, list2End, get_type ).get(), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
679                        } else if ( isTtype2 && ! isTtype1 ) {
680                                // combine all of the things in list1, then unify
681                                return unifyExact( combineTypes( list1Begin, list1End, get_type ).get(), t2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
682                        } else if ( ! unifyExact( t1, t2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer ) ) {
683                                return false;
684                        } // if
685
686                } // for
687                if ( list1Begin != list1End ) {
688                        // try unifying empty tuple type with ttype
689                        Type * t1 = *list1Begin;
690                        if ( Tuples::isTtype( t1 ) ) {
691                                return unifyExact( t1, combineTypes( list2Begin, list2End, get_type ).get(), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
692                        } else return false;
693                } else if ( list2Begin != list2End ) {
694                        // try unifying empty tuple type with ttype
695                        Type * t2 = *list2Begin;
696                        if ( Tuples::isTtype( t2 ) ) {
697                                return unifyExact( combineTypes( list1Begin, list1End, get_type ).get(), t2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
698                        } else return false;
699                } else {
700                        return true;
701                } // if
702        }
703
704        void Unify::visit(TupleType *tupleType) {
705                if ( TupleType *otherTuple = dynamic_cast< TupleType* >( type2 ) ) {
706                        std::unique_ptr<TupleType> flat1( tupleType->clone() );
707                        std::unique_ptr<TupleType> flat2( otherTuple->clone() );
708                        std::list<Type *> types1, types2;
709
710                        TtypeExpander expander( env );
711                        flat1->acceptMutator( expander );
712                        flat2->acceptMutator( expander );
713
714                        flatten( flat1.get(), back_inserter( types1 ) );
715                        flatten( flat2.get(), back_inserter( types2 ) );
716
717                        result = unifyList( types1.begin(), types1.end(), types2.begin(), types2.end(), env, needAssertions, haveAssertions, openVars, widenMode, indexer );
718                } // if
719        }
720
721        void Unify::visit(VarArgsType *varArgsType) {
722                result = dynamic_cast< VarArgsType* >( type2 );
723        }
724
725        void Unify::visit(ZeroType *zeroType) {
726                result = dynamic_cast< ZeroType* >( type2 );
727        }
728
729        void Unify::visit(OneType *oneType) {
730                result = dynamic_cast< OneType* >( type2 );
731        }
732
733        // xxx - compute once and store in the FunctionType?
734        Type * extractResultType( FunctionType * function ) {
735                if ( function->get_returnVals().size() == 0 ) {
736                        return new VoidType( Type::Qualifiers() );
737                } else if ( function->get_returnVals().size() == 1 ) {
738                        return function->get_returnVals().front()->get_type()->clone();
739                } else {
740                        TupleType * tupleType = new TupleType( Type::Qualifiers() );
741                        for ( DeclarationWithType * decl : function->get_returnVals() ) {
742                                tupleType->get_types().push_back( decl->get_type()->clone() );
743                        } // for
744                        return tupleType;
745                }
746        }
747} // namespace ResolvExpr
748
749// Local Variables: //
750// tab-width: 4 //
751// mode: c++ //
752// compile-command: "make install" //
753// End: //
Note: See TracBrowser for help on using the repository browser.