source: src/ResolvExpr/Unify.cc @ 3fe34ae

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 3fe34ae was 6c3a988f, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

fix inferred parameter data structures to correctly associate parameters with the entity that requested them, modify tuple specialization and unification to work with self-recursive assertions

  • Property mode set to 100644
File size: 29.8 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 );
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 >
491        std::unique_ptr<Type> combineTypes( Iterator begin, Iterator end ) {
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( (*begin)->get_type(), 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                for ( ; list1Begin != list1End && list2Begin != list2End; ++list1Begin, ++list2Begin ) {
503                        Type * t1 = (*list1Begin)->get_type();
504                        Type * t2 = (*list2Begin)->get_type();
505                        bool isTtype1 = Tuples::isTtype( t1 );
506                        bool isTtype2 = Tuples::isTtype( t2 );
507                        // xxx - assumes ttype must be last parameter
508                        // xxx - there may be a nice way to refactor this, but be careful because the argument positioning might matter in some cases.
509                        if ( isTtype1 && ! isTtype2 ) {
510                                // combine all of the things in list2, then unify
511                                return unifyExact( t1, combineTypes( list2Begin, list2End ).get(), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
512                        } else if ( isTtype2 && ! isTtype1 ) {
513                                // combine all of the things in list1, then unify
514                                return unifyExact( combineTypes( list1Begin, list1End ).get(), t2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
515                        } else if ( ! unifyExact( t1, t2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer ) ) {
516                                return false;
517                        } // if
518                } // for
519                // 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
520                if ( list1Begin != list1End ) {
521                        // try unifying empty tuple type with ttype
522                        Type * t1 = (*list1Begin)->get_type();
523                        if ( Tuples::isTtype( t1 ) ) {
524                                return unifyExact( t1, combineTypes( list2Begin, list2End ).get(), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
525                        } else return false;
526                } else if ( list2Begin != list2End ) {
527                        // try unifying empty tuple type with ttype
528                        Type * t2 = (*list2Begin)->get_type();
529                        if ( Tuples::isTtype( t2 ) ) {
530                                return unifyExact( combineTypes( list1Begin, list1End ).get(), t2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
531                        } else return false;
532                } else {
533                        return true;
534                } // if
535        }
536
537        /// Finds ttypes and replaces them with their expansion, if known.
538        /// This needs to be done so that satisfying ttype assertions is easier.
539        /// If this isn't done then argument lists can have wildly different
540        /// size and structure, when they should be compatible.
541        struct TtypeExpander : public Mutator {
542                TypeEnvironment & env;
543                TtypeExpander( TypeEnvironment & env ) : env( env ) {}
544                Type * mutate( TypeInstType * typeInst ) {
545                        EqvClass eqvClass;
546                        if ( env.lookup( typeInst->get_name(), eqvClass ) ) {
547                                if ( eqvClass.data.kind == TypeDecl::Ttype ) {
548                                        // expand ttype parameter into its actual type
549                                        if ( eqvClass.type ) {
550                                                delete typeInst;
551                                                return eqvClass.type->clone();
552                                        }
553                                }
554                        }
555                        return typeInst;
556                }
557        };
558
559        /// flattens a list of declarations, so that each tuple type has a single declaration.
560        /// makes use of TtypeExpander to ensure ttypes are flat as well.
561        void flattenList( std::list< DeclarationWithType * > src, std::list< DeclarationWithType * > & dst, TypeEnvironment & env ) {
562                dst.clear();
563                for ( DeclarationWithType * dcl : src ) {
564                        TtypeExpander expander( env );
565                        dcl->acceptMutator( expander );
566                        std::list< Type * > types;
567                        flatten( dcl->get_type(), back_inserter( types ) );
568                        for ( Type * t : types ) {
569                                dst.push_back( new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::C, nullptr, t, nullptr ) );
570                        }
571                        delete dcl;
572                }
573        }
574
575        void Unify::visit(FunctionType *functionType) {
576                FunctionType *otherFunction = dynamic_cast< FunctionType* >( type2 );
577                if ( otherFunction && functionType->get_isVarArgs() == otherFunction->get_isVarArgs() ) {
578                        // flatten the parameter lists for both functions so that tuple structure
579                        // doesn't affect unification. Must be a clone so that the types don't change.
580                        std::unique_ptr<FunctionType> flatFunc( functionType->clone() );
581                        std::unique_ptr<FunctionType> flatOther( otherFunction->clone() );
582                        flattenList( flatFunc->get_parameters(), flatFunc->get_parameters(), env );
583                        flattenList( flatOther->get_parameters(), flatOther->get_parameters(), env );
584
585                        // sizes don't have to match if ttypes are involved; need to be more precise wrt where the ttype is to prevent errors
586                        if ( (flatFunc->get_parameters().size() == flatOther->get_parameters().size() && flatFunc->get_returnVals().size() == flatOther->get_returnVals().size()) || flatFunc->isTtype() || flatOther->isTtype() ) {
587                                if ( unifyDeclList( flatFunc->get_parameters().begin(), flatFunc->get_parameters().end(), flatOther->get_parameters().begin(), flatOther->get_parameters().end(), env, needAssertions, haveAssertions, openVars, indexer ) ) {
588                                        if ( unifyDeclList( flatFunc->get_returnVals().begin(), flatFunc->get_returnVals().end(), flatOther->get_returnVals().begin(), flatOther->get_returnVals().end(), env, needAssertions, haveAssertions, openVars, indexer ) ) {
589
590                                                // the original types must be used in mark assertions, since pointer comparisons are used
591                                                markAssertions( haveAssertions, needAssertions, functionType );
592                                                markAssertions( haveAssertions, needAssertions, otherFunction );
593
594                                                result = true;
595                                        } // if
596                                } // if
597                        } // if
598                } // if
599        }
600
601        template< typename RefType >
602        void Unify::handleRefType( RefType *inst, Type *other ) {
603                // check that other type is compatible and named the same
604                RefType *otherStruct = dynamic_cast< RefType* >( other );
605                result = otherStruct && inst->get_name() == otherStruct->get_name();
606        }
607
608        template< typename RefType >
609        void Unify::handleGenericRefType( RefType *inst, Type *other ) {
610                // Check that other type is compatible and named the same
611                handleRefType( inst, other );
612                if ( ! result ) return;
613                // Check that parameters of types unify, if any
614                std::list< Expression* > params = inst->get_parameters();
615                std::list< Expression* > otherParams = ((RefType*)other)->get_parameters();
616
617                std::list< Expression* >::const_iterator it = params.begin(), jt = otherParams.begin();
618                for ( ; it != params.end() && jt != otherParams.end(); ++it, ++jt ) {
619                        TypeExpr *param = dynamic_cast< TypeExpr* >(*it);
620                        assert(param && "Aggregate parameters should be type expressions");
621                        TypeExpr *otherParam = dynamic_cast< TypeExpr* >(*jt);
622                        assert(otherParam && "Aggregate parameters should be type expressions");
623
624                        if ( ! unifyExact( param->get_type(), otherParam->get_type(), env, needAssertions, haveAssertions, openVars, WidenMode(false, false), indexer ) ) {
625                                result = false;
626                                return;
627                        }
628                }
629                result = ( it == params.end() && jt == otherParams.end() );
630        }
631
632        void Unify::visit(StructInstType *structInst) {
633                handleGenericRefType( structInst, type2 );
634        }
635
636        void Unify::visit(UnionInstType *unionInst) {
637                handleGenericRefType( unionInst, type2 );
638        }
639
640        void Unify::visit(EnumInstType *enumInst) {
641                handleRefType( enumInst, type2 );
642        }
643
644        void Unify::visit(TraitInstType *contextInst) {
645                handleRefType( contextInst, type2 );
646        }
647
648        void Unify::visit(TypeInstType *typeInst) {
649                assert( openVars.find( typeInst->get_name() ) == openVars.end() );
650                TypeInstType *otherInst = dynamic_cast< TypeInstType* >( type2 );
651                if ( otherInst && typeInst->get_name() == otherInst->get_name() ) {
652                        result = true;
653///   } else {
654///     NamedTypeDecl *nt = indexer.lookupType( typeInst->get_name() );
655///     if ( nt ) {
656///       TypeDecl *type = dynamic_cast< TypeDecl* >( nt );
657///       assert( type );
658///       if ( type->get_base() ) {
659///         result = unifyExact( type->get_base(), typeInst, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
660///       }
661///     }
662                } // if
663        }
664
665        template< typename Iterator1, typename Iterator2 >
666        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 ) {
667                for ( ; list1Begin != list1End && list2Begin != list2End; ++list1Begin, ++list2Begin ) {
668                        Type *commonType = 0;
669                        if ( ! unifyInexact( *list1Begin, *list2Begin, env, needAssertions, haveAssertions, openVars, widenMode, indexer, commonType ) ) {
670                                return false;
671                        }
672                        delete commonType;
673                } // for
674                if ( list1Begin != list1End || list2Begin != list2End ) {
675                        return false;
676                } else {
677                        return true;
678                } //if
679        }
680
681        void Unify::visit(TupleType *tupleType) {
682                if ( TupleType *otherTuple = dynamic_cast< TupleType* >( type2 ) ) {
683                        result = unifyList( tupleType->get_types().begin(), tupleType->get_types().end(), otherTuple->get_types().begin(), otherTuple->get_types().end(), env, needAssertions, haveAssertions, openVars, widenMode, indexer );
684                } // if
685        }
686
687        void Unify::visit(VarArgsType *varArgsType) {
688                result = dynamic_cast< VarArgsType* >( type2 );
689        }
690
691        void Unify::visit(ZeroType *zeroType) {
692                result = dynamic_cast< ZeroType* >( type2 );
693        }
694
695        void Unify::visit(OneType *oneType) {
696                result = dynamic_cast< OneType* >( type2 );
697        }
698
699        // xxx - compute once and store in the FunctionType?
700        Type * extractResultType( FunctionType * function ) {
701                if ( function->get_returnVals().size() == 0 ) {
702                        return new VoidType( Type::Qualifiers() );
703                } else if ( function->get_returnVals().size() == 1 ) {
704                        return function->get_returnVals().front()->get_type()->clone();
705                } else {
706                        TupleType * tupleType = new TupleType( Type::Qualifiers() );
707                        for ( DeclarationWithType * decl : function->get_returnVals() ) {
708                                tupleType->get_types().push_back( decl->get_type()->clone() );
709                        } // for
710                        return tupleType;
711                }
712        }
713} // namespace ResolvExpr
714
715// Local Variables: //
716// tab-width: 4 //
717// mode: c++ //
718// compile-command: "make install" //
719// End: //
Note: See TracBrowser for help on using the repository browser.