source: src/ResolvExpr/Unify.cc @ 28f3a19

new-envwith_gc
Last change on this file since 28f3a19 was 28f3a19, checked in by Aaron Moss <a3moss@…>, 6 years ago

Merge branch 'master' into with_gc

  • Property mode set to 100644
File size: 27.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 : Aaron B. Moss
12// Last Modified On : Mon Jun 18 11:58:00 2018
13// Update Count     : 43
14//
15
16#include <cassert>                // for assertf, assert
17#include <iterator>               // for back_insert_iterator, back_inserter
18#include <map>                    // for _Rb_tree_const_iterator, _Rb_tree_i...
19#include <set>                    // for set
20#include <string>                 // for string, operator==, operator!=, bas...
21#include <utility>                // for pair, move
22
23#include "Common/PassVisitor.h"   // for PassVisitor
24#include "FindOpenVars.h"         // for findOpenVars
25#include "Parser/LinkageSpec.h"   // for C
26#include "SynTree/Constant.h"     // for Constant
27#include "SynTree/Declaration.h"  // for TypeDecl, TypeDecl::Data, Declarati...
28#include "SynTree/Expression.h"   // for TypeExpr, Expression, ConstantExpr
29#include "SynTree/Mutator.h"      // for Mutator
30#include "SynTree/Type.h"         // for Type, TypeInstType, FunctionType
31#include "SynTree/Visitor.h"      // for Visitor
32#include "Tuples/Tuples.h"        // for isTtype
33#include "TypeEnvironment.h"      // for EqvClass, AssertionSet, OpenVarSet
34#include "Unify.h"
35#include "typeops.h"              // for flatten, occurs, commonType
36
37namespace SymTab {
38class Indexer;
39}  // namespace SymTab
40
41// #define DEBUG
42
43namespace ResolvExpr {
44
45        struct Unify : public WithShortCircuiting {
46                Unify( Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widenMode, const SymTab::Indexer &indexer );
47
48                bool get_result() const { return result; }
49
50                void previsit( BaseSyntaxNode * ) { visit_children = false; }
51
52                void postvisit( VoidType * voidType );
53                void postvisit( BasicType * basicType );
54                void postvisit( PointerType * pointerType );
55                void postvisit( ArrayType * arrayType );
56                void postvisit( ReferenceType * refType );
57                void postvisit( FunctionType * functionType );
58                void postvisit( StructInstType * aggregateUseType );
59                void postvisit( UnionInstType * aggregateUseType );
60                void postvisit( EnumInstType * aggregateUseType );
61                void postvisit( TraitInstType * aggregateUseType );
62                void postvisit( TypeInstType * aggregateUseType );
63                void postvisit( TupleType * tupleType );
64                void postvisit( VarArgsType * varArgsType );
65                void postvisit( ZeroType * zeroType );
66                void postvisit( OneType * oneType );
67
68          private:
69                template< typename RefType > void handleRefType( RefType *inst, Type *other );
70                template< typename RefType > void handleGenericRefType( RefType *inst, Type *other );
71
72                bool result;
73                Type *type2;                            // inherited
74                TypeEnvironment &env;
75                AssertionSet &needAssertions;
76                AssertionSet &haveAssertions;
77                const OpenVarSet &openVars;
78                WidenMode widenMode;
79                const SymTab::Indexer &indexer;
80        };
81
82        /// Attempts an inexact unification of type1 and type2.
83        /// Returns false if no such unification; if the types can be unified, sets common (unless they unify exactly and have identical type qualifiers)
84        bool unifyInexact( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widenMode, const SymTab::Indexer &indexer, Type *&common );
85        bool unifyExact( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widenMode, const SymTab::Indexer &indexer );
86
87        bool typesCompatible( Type *first, Type *second, const SymTab::Indexer &indexer, const TypeEnvironment &env ) {
88                TypeEnvironment newEnv;
89                OpenVarSet openVars, closedVars; // added closedVars
90                AssertionSet needAssertions, haveAssertions;
91                Type *newFirst = first->clone(), *newSecond = second->clone();
92                env.apply( newFirst );
93                env.apply( newSecond );
94
95                // do we need to do this? Seems like we do, types should be able to be compatible if they
96                // have free variables that can unify
97                findOpenVars( newFirst, openVars, closedVars, needAssertions, haveAssertions, false );
98                findOpenVars( newSecond, openVars, closedVars, needAssertions, haveAssertions, true );
99
100                return unifyExact( newFirst, newSecond, newEnv, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
101        }
102
103        bool typesCompatibleIgnoreQualifiers( Type *first, Type *second, const SymTab::Indexer &indexer, const TypeEnvironment &env ) {
104                TypeEnvironment newEnv;
105                OpenVarSet openVars;
106                AssertionSet needAssertions, haveAssertions;
107                Type *newFirst = first->clone(), *newSecond = second->clone();
108                env.apply( newFirst );
109                env.apply( newSecond );
110                newFirst->get_qualifiers() = Type::Qualifiers();
111                newSecond->get_qualifiers() = Type::Qualifiers();
112///   std::cerr << "first is ";
113///   first->print( std::cerr );
114///   std::cerr << std::endl << "second is ";
115///   second->print( std::cerr );
116///   std::cerr << std::endl << "newFirst is ";
117///   newFirst->print( std::cerr );
118///   std::cerr << std::endl << "newSecond is ";
119///   newSecond->print( std::cerr );
120///   std::cerr << std::endl;
121                return unifyExact( newFirst, newSecond, newEnv, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
122        }
123
124        bool unify( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, OpenVarSet &openVars, const SymTab::Indexer &indexer ) {
125                OpenVarSet closedVars;
126                findOpenVars( type1, openVars, closedVars, needAssertions, haveAssertions, false );
127                findOpenVars( type2, openVars, closedVars, needAssertions, haveAssertions, true );
128                Type *commonType = 0;
129                return unifyInexact( type1, type2, env, needAssertions, haveAssertions, openVars, WidenMode( true, true ), indexer, commonType );
130        }
131
132        bool unify( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, OpenVarSet &openVars, const SymTab::Indexer &indexer, Type *&commonType ) {
133                OpenVarSet closedVars;
134                findOpenVars( type1, openVars, closedVars, needAssertions, haveAssertions, false );
135                findOpenVars( type2, openVars, closedVars, needAssertions, haveAssertions, true );
136                return unifyInexact( type1, type2, env, needAssertions, haveAssertions, openVars, WidenMode( true, true ), indexer, commonType );
137        }
138
139        bool unifyExact( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widenMode, const SymTab::Indexer &indexer ) {
140#ifdef DEBUG
141                TypeEnvironment debugEnv( env );
142#endif
143                if ( type1->get_qualifiers() != type2->get_qualifiers() ) {
144                        return false;
145                }
146
147                bool result;
148                TypeInstType *var1 = dynamic_cast< TypeInstType* >( type1 );
149                TypeInstType *var2 = dynamic_cast< TypeInstType* >( type2 );
150                OpenVarSet::const_iterator entry1, entry2;
151                if ( var1 ) {
152                        entry1 = openVars.find( var1->get_name() );
153                } // if
154                if ( var2 ) {
155                        entry2 = openVars.find( var2->get_name() );
156                } // if
157                bool isopen1 = var1 && ( entry1 != openVars.end() );
158                bool isopen2 = var2 && ( entry2 != openVars.end() );
159
160                if ( isopen1 && isopen2 && entry1->second == entry2->second ) {
161                        result = env.bindVarToVar( var1, var2, entry1->second, needAssertions, haveAssertions, openVars, widenMode, indexer );
162                } else if ( isopen1 ) {
163                        result = env.bindVar( var1, type2, entry1->second, needAssertions, haveAssertions, openVars, widenMode, indexer );
164                } else if ( isopen2 ) { // TODO: swap widenMode values in call, since type positions are flipped?
165                        result = env.bindVar( var2, type1, entry2->second, needAssertions, haveAssertions, openVars, widenMode, indexer );
166                } else {
167                        PassVisitor<Unify> comparator( type2, env, needAssertions, haveAssertions, openVars, widenMode, indexer );
168                        type1->accept( comparator );
169                        result = comparator.pass.get_result();
170                } // if
171#ifdef DEBUG
172                std::cerr << "============ unifyExact" << std::endl;
173                std::cerr << "type1 is ";
174                type1->print( std::cerr );
175                std::cerr << std::endl << "type2 is ";
176                type2->print( std::cerr );
177                std::cerr << std::endl << "openVars are ";
178                printOpenVarSet( openVars, std::cerr, 8 );
179                std::cerr << std::endl << "input env is " << std::endl;
180                debugEnv.print( std::cerr, 8 );
181                std::cerr << std::endl << "result env is " << std::endl;
182                env.print( std::cerr, 8 );
183                std::cerr << "result is " << result << std::endl;
184#endif
185                return result;
186        }
187
188        bool unifyExact( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, OpenVarSet &openVars, const SymTab::Indexer &indexer ) {
189                return unifyExact( type1, type2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
190        }
191
192        bool unifyInexact( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widenMode, const SymTab::Indexer &indexer, Type *&common ) {
193                Type::Qualifiers tq1 = type1->get_qualifiers(), tq2 = type2->get_qualifiers();
194                type1->get_qualifiers() = Type::Qualifiers();
195                type2->get_qualifiers() = Type::Qualifiers();
196                bool result;
197#ifdef DEBUG
198                std::cerr << "unifyInexact type 1 is ";
199                type1->print( std::cerr );
200                std::cerr << " type 2 is ";
201                type2->print( std::cerr );
202                std::cerr << std::endl;
203#endif
204                if ( ! unifyExact( type1, type2, env, needAssertions, haveAssertions, openVars, widenMode, indexer ) ) {
205#ifdef DEBUG
206                        std::cerr << "unifyInexact: no exact unification found" << std::endl;
207#endif
208                        if ( ( common = commonType( type1, type2, widenMode.widenFirst, widenMode.widenSecond, indexer, env, openVars ) ) ) {
209                                common->get_qualifiers() = tq1 | tq2;
210#ifdef DEBUG
211                                std::cerr << "unifyInexact: common type is ";
212                                common->print( std::cerr );
213                                std::cerr << std::endl;
214#endif
215                                result = true;
216                        } else {
217#ifdef DEBUG
218                                std::cerr << "unifyInexact: no common type found" << std::endl;
219#endif
220                                result = false;
221                        } // if
222                } else {
223                        if ( tq1 != tq2 ) {
224                                if ( ( tq1 > tq2 || widenMode.widenFirst ) && ( tq2 > tq1 || widenMode.widenSecond ) ) {
225                                        common = type1->clone();
226                                        common->get_qualifiers() = tq1 | tq2;
227                                        result = true;
228                                } else {
229                                        result = false;
230                                } // if
231                        } else {
232                                common = type1->clone();
233                                common->get_qualifiers() = tq1 | tq2;
234                                result = true;
235                        } // if
236                } // if
237                type1->get_qualifiers() = tq1;
238                type2->get_qualifiers() = tq2;
239                return result;
240        }
241
242        Unify::Unify( Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widenMode, const SymTab::Indexer &indexer )
243                : result( false ), type2( type2 ), env( env ), needAssertions( needAssertions ), haveAssertions( haveAssertions ), openVars( openVars ), widenMode( widenMode ), indexer( indexer ) {
244        }
245
246        void Unify::postvisit( __attribute__((unused)) VoidType *voidType) {
247                result = dynamic_cast< VoidType* >( type2 );
248        }
249
250        void Unify::postvisit(BasicType *basicType) {
251                if ( BasicType *otherBasic = dynamic_cast< BasicType* >( type2 ) ) {
252                        result = basicType->get_kind() == otherBasic->get_kind();
253                } // if
254        }
255
256        void markAssertionSet( AssertionSet &assertions, DeclarationWithType *assert ) {
257///   std::cerr << "assertion set is" << std::endl;
258///   printAssertionSet( assertions, std::cerr, 8 );
259///   std::cerr << "looking for ";
260///   assert->print( std::cerr );
261///   std::cerr << std::endl;
262                AssertionSet::iterator i = assertions.find( assert );
263                if ( i != assertions.end() ) {
264///     std::cerr << "found it!" << std::endl;
265                        i->second.isUsed = true;
266                } // if
267        }
268
269        void markAssertions( AssertionSet &assertion1, AssertionSet &assertion2, Type *type ) {
270                for ( std::list< TypeDecl* >::const_iterator tyvar = type->get_forall().begin(); tyvar != type->get_forall().end(); ++tyvar ) {
271                        for ( std::list< DeclarationWithType* >::const_iterator assert = (*tyvar)->get_assertions().begin(); assert != (*tyvar)->get_assertions().end(); ++assert ) {
272                                markAssertionSet( assertion1, *assert );
273                                markAssertionSet( assertion2, *assert );
274                        } // for
275                } // for
276        }
277
278        void Unify::postvisit(PointerType *pointerType) {
279                if ( PointerType *otherPointer = dynamic_cast< PointerType* >( type2 ) ) {
280                        result = unifyExact( pointerType->get_base(), otherPointer->get_base(), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
281                        markAssertions( haveAssertions, needAssertions, pointerType );
282                        markAssertions( haveAssertions, needAssertions, otherPointer );
283                } // if
284        }
285
286        void Unify::postvisit(ReferenceType *refType) {
287                if ( ReferenceType *otherRef = dynamic_cast< ReferenceType* >( type2 ) ) {
288                        result = unifyExact( refType->get_base(), otherRef->get_base(), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
289                        markAssertions( haveAssertions, needAssertions, refType );
290                        markAssertions( haveAssertions, needAssertions, otherRef );
291                } // if
292        }
293
294        void Unify::postvisit(ArrayType *arrayType) {
295                ArrayType *otherArray = dynamic_cast< ArrayType* >( type2 );
296                // to unify, array types must both be VLA or both not VLA
297                // and must both have a dimension expression or not have a dimension
298                if ( otherArray && arrayType->get_isVarLen() == otherArray->get_isVarLen() ) {
299
300                        if ( ! arrayType->get_isVarLen() && ! otherArray->get_isVarLen() &&
301                                arrayType->get_dimension() != 0 && otherArray->get_dimension() != 0 ) {
302                                ConstantExpr * ce1 = dynamic_cast< ConstantExpr * >( arrayType->get_dimension() );
303                                ConstantExpr * ce2 = dynamic_cast< ConstantExpr * >( otherArray->get_dimension() );
304                                // see C11 Reference Manual 6.7.6.2.6
305                                // two array types with size specifiers that are integer constant expressions are
306                                // compatible if both size specifiers have the same constant value
307                                if ( ce1 && ce2 ) {
308                                        Constant * c1 = ce1->get_constant();
309                                        Constant * c2 = ce2->get_constant();
310
311                                        if ( c1->get_value() != c2->get_value() ) {
312                                                // does not unify if the dimension is different
313                                                return;
314                                        }
315                                }
316                        }
317
318                        result = unifyExact( arrayType->get_base(), otherArray->get_base(), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
319                } // if
320        }
321
322        template< typename Iterator, typename Func >
323        Type* combineTypes( Iterator begin, Iterator end, Func & toType ) {
324                std::list< Type * > types;
325                for ( ; begin != end; ++begin ) {
326                        // it's guaranteed that a ttype variable will be bound to a flat tuple, so ensure that this results in a flat tuple
327                        flatten( toType( *begin ), back_inserter( types ) );
328                }
329                return new TupleType{ Type::Qualifiers(), types };
330        }
331
332        template< typename Iterator1, typename Iterator2 >
333        bool unifyDeclList( Iterator1 list1Begin, Iterator1 list1End, Iterator2 list2Begin, Iterator2 list2End, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, const SymTab::Indexer &indexer ) {
334                auto get_type = [](DeclarationWithType * dwt){ return dwt->get_type(); };
335                for ( ; list1Begin != list1End && list2Begin != list2End; ++list1Begin, ++list2Begin ) {
336                        Type * t1 = (*list1Begin)->get_type();
337                        Type * t2 = (*list2Begin)->get_type();
338                        bool isTtype1 = Tuples::isTtype( t1 );
339                        bool isTtype2 = Tuples::isTtype( t2 );
340                        // xxx - assumes ttype must be last parameter
341                        // xxx - there may be a nice way to refactor this, but be careful because the argument positioning might matter in some cases.
342                        if ( isTtype1 && ! isTtype2 ) {
343                                // combine all of the things in list2, then unify
344                                return unifyExact( t1, combineTypes( list2Begin, list2End, get_type ), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
345                        } else if ( isTtype2 && ! isTtype1 ) {
346                                // combine all of the things in list1, then unify
347                                return unifyExact( combineTypes( list1Begin, list1End, get_type ), t2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
348                        } else if ( ! unifyExact( t1, t2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer ) ) {
349                                return false;
350                        } // if
351                } // for
352                // 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
353                if ( list1Begin != list1End ) {
354                        // try unifying empty tuple type with ttype
355                        Type * t1 = (*list1Begin)->get_type();
356                        if ( Tuples::isTtype( t1 ) ) {
357                                return unifyExact( t1, combineTypes( list2Begin, list2End, get_type ), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
358                        } else return false;
359                } else if ( list2Begin != list2End ) {
360                        // try unifying empty tuple type with ttype
361                        Type * t2 = (*list2Begin)->get_type();
362                        if ( Tuples::isTtype( t2 ) ) {
363                                return unifyExact( combineTypes( list1Begin, list1End, get_type ), t2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
364                        } else return false;
365                } else {
366                        return true;
367                } // if
368        }
369
370        /// Finds ttypes and replaces them with their expansion, if known.
371        /// This needs to be done so that satisfying ttype assertions is easier.
372        /// If this isn't done then argument lists can have wildly different
373        /// size and structure, when they should be compatible.
374        struct TtypeExpander : public WithShortCircuiting {
375                TypeEnvironment & tenv;
376                TtypeExpander( TypeEnvironment & tenv ) : tenv( tenv ) {}
377                void premutate( TypeInstType * ) { visit_children = false; }
378                Type * postmutate( TypeInstType * typeInst ) {
379                        if ( const EqvClass *eqvClass = tenv.lookup( typeInst->get_name() ) ) {
380                                // expand ttype parameter into its actual type
381                                if ( eqvClass->data.kind == TypeDecl::Ttype && eqvClass->type ) {
382                                        return eqvClass->type->clone();
383                                }
384                        }
385                        return typeInst;
386                }
387        };
388
389        /// flattens a list of declarations, so that each tuple type has a single declaration.
390        /// makes use of TtypeExpander to ensure ttypes are flat as well.
391        void flattenList( std::list< DeclarationWithType * > src, std::list< DeclarationWithType * > & dst, TypeEnvironment & env ) {
392                dst.clear();
393                for ( DeclarationWithType * dcl : src ) {
394                        PassVisitor<TtypeExpander> expander( env );
395                        dcl->acceptMutator( expander );
396                        std::list< Type * > types;
397                        flatten( dcl->get_type(), back_inserter( types ) );
398                        for ( Type * t : types ) {
399                                // outermost const, volatile, _Atomic qualifiers in parameters should not play a role in the unification of function types, since they do not determine whether a function is callable.
400                                // Note: MUST consider at least mutex qualifier, since functions can be overloaded on outermost mutex and a mutex function has different requirements than a non-mutex function.
401                                t->get_qualifiers() -= Type::Qualifiers(Type::Const | Type::Volatile | Type::Atomic);
402
403                                dst.push_back( new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::C, nullptr, t, nullptr ) );
404                        }
405                }
406        }
407
408        void Unify::postvisit(FunctionType *functionType) {
409                FunctionType *otherFunction = dynamic_cast< FunctionType* >( type2 );
410                if ( otherFunction && functionType->get_isVarArgs() == otherFunction->get_isVarArgs() ) {
411                        // flatten the parameter lists for both functions so that tuple structure
412                        // doesn't affect unification. Must be a clone so that the types don't change.
413                        FunctionType* flatFunc = functionType->clone();
414                        FunctionType* flatOther = otherFunction->clone();
415                        flattenList( flatFunc->get_parameters(), flatFunc->get_parameters(), env );
416                        flattenList( flatOther->get_parameters(), flatOther->get_parameters(), env );
417
418                        // sizes don't have to match if ttypes are involved; need to be more precise wrt where the ttype is to prevent errors
419                        if ( (flatFunc->parameters.size() == flatOther->parameters.size() && flatFunc->returnVals.size() == flatOther->returnVals.size()) || flatFunc->isTtype() || flatOther->isTtype() ) {
420                                if ( unifyDeclList( flatFunc->parameters.begin(), flatFunc->parameters.end(), flatOther->parameters.begin(), flatOther->parameters.end(), env, needAssertions, haveAssertions, openVars, indexer ) ) {
421                                        if ( unifyDeclList( flatFunc->returnVals.begin(), flatFunc->returnVals.end(), flatOther->returnVals.begin(), flatOther->returnVals.end(), env, needAssertions, haveAssertions, openVars, indexer ) ) {
422
423                                                // the original types must be used in mark assertions, since pointer comparisons are used
424                                                markAssertions( haveAssertions, needAssertions, functionType );
425                                                markAssertions( haveAssertions, needAssertions, otherFunction );
426
427                                                result = true;
428                                        } // if
429                                } // if
430                        } // if
431                } // if
432        }
433
434        template< typename RefType >
435        void Unify::handleRefType( RefType *inst, Type *other ) {
436                // check that other type is compatible and named the same
437                RefType *otherStruct = dynamic_cast< RefType* >( other );
438                result = otherStruct && inst->name == otherStruct->name;
439        }
440
441        template< typename RefType >
442        void Unify::handleGenericRefType( RefType *inst, Type *other ) {
443                // Check that other type is compatible and named the same
444                handleRefType( inst, other );
445                if ( ! result ) return;
446                // Check that parameters of types unify, if any
447                std::list< Expression* > params = inst->parameters;
448                std::list< Expression* > otherParams = ((RefType*)other)->parameters;
449
450                std::list< Expression* >::const_iterator it = params.begin(), jt = otherParams.begin();
451                for ( ; it != params.end() && jt != otherParams.end(); ++it, ++jt ) {
452                        TypeExpr *param = dynamic_cast< TypeExpr* >(*it);
453                        assertf(param, "Aggregate parameters should be type expressions");
454                        TypeExpr *otherParam = dynamic_cast< TypeExpr* >(*jt);
455                        assertf(otherParam, "Aggregate parameters should be type expressions");
456
457                        Type* paramTy = param->get_type();
458                        Type* otherParamTy = otherParam->get_type();
459
460                        bool tupleParam = Tuples::isTtype( paramTy );
461                        bool otherTupleParam = Tuples::isTtype( otherParamTy );
462
463                        if ( tupleParam && otherTupleParam ) {
464                                ++it; ++jt;  // skip ttype parameters for break
465                        } else if ( tupleParam ) {
466                                // bundle other parameters into tuple to match
467                                std::list< Type * > binderTypes;
468
469                                do {
470                                        binderTypes.push_back( otherParam->get_type()->clone() );
471                                        ++jt;
472
473                                        if ( jt == otherParams.end() ) break;
474
475                                        otherParam = dynamic_cast< TypeExpr* >(*jt);
476                                        assertf(otherParam, "Aggregate parameters should be type expressions");
477                                } while (true);
478
479                                otherParamTy = new TupleType{ paramTy->get_qualifiers(), binderTypes };
480                                ++it;  // skip ttype parameter for break
481                        } else if ( otherTupleParam ) {
482                                // bundle parameters into tuple to match other
483                                std::list< Type * > binderTypes;
484
485                                do {
486                                        binderTypes.push_back( param->get_type()->clone() );
487                                        ++it;
488
489                                        if ( it == params.end() ) break;
490
491                                        param = dynamic_cast< TypeExpr* >(*it);
492                                        assertf(param, "Aggregate parameters should be type expressions");
493                                } while (true);
494
495                                paramTy = new TupleType{ otherParamTy->get_qualifiers(), binderTypes };
496                                ++jt;  // skip ttype parameter for break
497                        }
498
499                        if ( ! unifyExact( paramTy, otherParamTy, env, needAssertions, haveAssertions, openVars, WidenMode(false, false), indexer ) ) {
500                                result = false;
501                                return;
502                        }
503
504                        // ttype parameter should be last
505                        if ( tupleParam || otherTupleParam ) break;
506                }
507                result = ( it == params.end() && jt == otherParams.end() );
508        }
509
510        void Unify::postvisit(StructInstType *structInst) {
511                handleGenericRefType( structInst, type2 );
512        }
513
514        void Unify::postvisit(UnionInstType *unionInst) {
515                handleGenericRefType( unionInst, type2 );
516        }
517
518        void Unify::postvisit(EnumInstType *enumInst) {
519                handleRefType( enumInst, type2 );
520        }
521
522        void Unify::postvisit(TraitInstType *contextInst) {
523                handleRefType( contextInst, type2 );
524        }
525
526        void Unify::postvisit(TypeInstType *typeInst) {
527                assert( openVars.find( typeInst->get_name() ) == openVars.end() );
528                TypeInstType *otherInst = dynamic_cast< TypeInstType* >( type2 );
529                if ( otherInst && typeInst->get_name() == otherInst->get_name() ) {
530                        result = true;
531///   } else {
532///     NamedTypeDecl *nt = indexer.lookupType( typeInst->get_name() );
533///     if ( nt ) {
534///       TypeDecl *type = dynamic_cast< TypeDecl* >( nt );
535///       assert( type );
536///       if ( type->get_base() ) {
537///         result = unifyExact( type->get_base(), typeInst, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
538///       }
539///     }
540                } // if
541        }
542
543        template< typename Iterator1, typename Iterator2 >
544        bool unifyList( Iterator1 list1Begin, Iterator1 list1End, Iterator2 list2Begin, Iterator2 list2End, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, const SymTab::Indexer &indexer ) {
545                auto get_type = [](Type * t) { return t; };
546                for ( ; list1Begin != list1End && list2Begin != list2End; ++list1Begin, ++list2Begin ) {
547                        Type * t1 = *list1Begin;
548                        Type * t2 = *list2Begin;
549                        bool isTtype1 = Tuples::isTtype( t1 );
550                        bool isTtype2 = Tuples::isTtype( t2 );
551                        // xxx - assumes ttype must be last parameter
552                        // xxx - there may be a nice way to refactor this, but be careful because the argument positioning might matter in some cases.
553                        if ( isTtype1 && ! isTtype2 ) {
554                                // combine all of the things in list2, then unify
555                                return unifyExact( t1, combineTypes( list2Begin, list2End, get_type ), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
556                        } else if ( isTtype2 && ! isTtype1 ) {
557                                // combine all of the things in list1, then unify
558                                return unifyExact( combineTypes( list1Begin, list1End, get_type ), t2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
559                        } else if ( ! unifyExact( t1, t2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer ) ) {
560                                return false;
561                        } // if
562
563                } // for
564                if ( list1Begin != list1End ) {
565                        // try unifying empty tuple type with ttype
566                        Type * t1 = *list1Begin;
567                        if ( Tuples::isTtype( t1 ) ) {
568                                return unifyExact( t1, combineTypes( list2Begin, list2End, get_type ), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
569                        } else return false;
570                } else if ( list2Begin != list2End ) {
571                        // try unifying empty tuple type with ttype
572                        Type * t2 = *list2Begin;
573                        if ( Tuples::isTtype( t2 ) ) {
574                                return unifyExact( combineTypes( list1Begin, list1End, get_type ), t2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
575                        } else return false;
576                } else {
577                        return true;
578                } // if
579        }
580
581        void Unify::postvisit(TupleType *tupleType) {
582                if ( TupleType *otherTuple = dynamic_cast< TupleType* >( type2 ) ) {
583                        TupleType* flat1 = tupleType->clone();
584                        TupleType* flat2 = otherTuple->clone();
585                        std::list<Type *> types1, types2;
586
587                        PassVisitor<TtypeExpander> expander( env );
588                        flat1->acceptMutator( expander );
589                        flat2->acceptMutator( expander );
590
591                        flatten( flat1, back_inserter( types1 ) );
592                        flatten( flat2, back_inserter( types2 ) );
593
594                        result = unifyList( types1.begin(), types1.end(), types2.begin(), types2.end(), env, needAssertions, haveAssertions, openVars, indexer );
595                } // if
596        }
597
598        void Unify::postvisit( __attribute__((unused)) VarArgsType *varArgsType ) {
599                result = dynamic_cast< VarArgsType* >( type2 );
600        }
601
602        void Unify::postvisit( __attribute__((unused)) ZeroType *zeroType ) {
603                result = dynamic_cast< ZeroType* >( type2 );
604        }
605
606        void Unify::postvisit( __attribute__((unused)) OneType *oneType ) {
607                result = dynamic_cast< OneType* >( type2 );
608        }
609
610        // xxx - compute once and store in the FunctionType?
611        Type * extractResultType( FunctionType * function ) {
612                if ( function->get_returnVals().size() == 0 ) {
613                        return new VoidType( Type::Qualifiers() );
614                } else if ( function->get_returnVals().size() == 1 ) {
615                        return function->get_returnVals().front()->get_type()->clone();
616                } else {
617                        std::list< Type * > types;
618                        for ( DeclarationWithType * decl : function->get_returnVals() ) {
619                                types.push_back( decl->get_type()->clone() );
620                        } // for
621                        return new TupleType( Type::Qualifiers(), types );
622                }
623        }
624} // namespace ResolvExpr
625
626// Local Variables: //
627// tab-width: 4 //
628// mode: c++ //
629// compile-command: "make install" //
630// End: //
Note: See TracBrowser for help on using the repository browser.