source: src/ResolvExpr/Unify.cc @ e068c8a

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since e068c8a was 7030dab, checked in by Thierry Delisle <tdelisle@…>, 4 years ago

Merge branch 'master' into new-ast

  • Property mode set to 100644
File size: 48.0 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 : Fri Dec 13 23:43:05 2019
13// Update Count     : 46
14//
15
16#include "Unify.h"
17
18#include <cassert>                  // for assertf, assert
19#include <iterator>                 // for back_insert_iterator, back_inserter
20#include <map>                      // for _Rb_tree_const_iterator, _Rb_tree_i...
21#include <memory>                   // for unique_ptr
22#include <set>                      // for set
23#include <string>                   // for string, operator==, operator!=, bas...
24#include <utility>                  // for pair, move
25#include <vector>
26
27#include "AST/Copy.hpp"
28#include "AST/Decl.hpp"
29#include "AST/Node.hpp"
30#include "AST/Pass.hpp"
31#include "AST/Print.hpp"
32#include "AST/Type.hpp"
33#include "AST/TypeEnvironment.hpp"
34#include "Common/PassVisitor.h"     // for PassVisitor
35#include "FindOpenVars.h"           // for findOpenVars
36#include "SynTree/LinkageSpec.h"    // for C
37#include "SynTree/Constant.h"       // for Constant
38#include "SynTree/Declaration.h"    // for TypeDecl, TypeDecl::Data, Declarati...
39#include "SynTree/Expression.h"     // for TypeExpr, Expression, ConstantExpr
40#include "SynTree/Mutator.h"        // for Mutator
41#include "SynTree/Type.h"           // for Type, TypeInstType, FunctionType
42#include "SynTree/Visitor.h"        // for Visitor
43#include "Tuples/Tuples.h"          // for isTtype
44#include "TypeEnvironment.h"        // for EqvClass, AssertionSet, OpenVarSet
45#include "typeops.h"                // for flatten, occurs, commonType
46
47namespace ast {
48        class SymbolTable;
49}
50
51namespace SymTab {
52class Indexer;
53}  // namespace SymTab
54
55// #define DEBUG
56
57namespace ResolvExpr {
58
59        struct Unify_old : public WithShortCircuiting {
60                Unify_old( Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widen, const SymTab::Indexer &indexer );
61
62                bool get_result() const { return result; }
63
64                void previsit( BaseSyntaxNode * ) { visit_children = false; }
65
66                void postvisit( VoidType * voidType );
67                void postvisit( BasicType * basicType );
68                void postvisit( PointerType * pointerType );
69                void postvisit( ArrayType * arrayType );
70                void postvisit( ReferenceType * refType );
71                void postvisit( FunctionType * functionType );
72                void postvisit( StructInstType * aggregateUseType );
73                void postvisit( UnionInstType * aggregateUseType );
74                void postvisit( EnumInstType * aggregateUseType );
75                void postvisit( TraitInstType * aggregateUseType );
76                void postvisit( TypeInstType * aggregateUseType );
77                void postvisit( TupleType * tupleType );
78                void postvisit( VarArgsType * varArgsType );
79                void postvisit( ZeroType * zeroType );
80                void postvisit( OneType * oneType );
81
82          private:
83                template< typename RefType > void handleRefType( RefType *inst, Type *other );
84                template< typename RefType > void handleGenericRefType( RefType *inst, Type *other );
85
86                bool result;
87                Type *type2;                            // inherited
88                TypeEnvironment &env;
89                AssertionSet &needAssertions;
90                AssertionSet &haveAssertions;
91                const OpenVarSet &openVars;
92                WidenMode widen;
93                const SymTab::Indexer &indexer;
94        };
95
96        /// Attempts an inexact unification of type1 and type2.
97        /// Returns false if no such unification; if the types can be unified, sets common (unless they unify exactly and have identical type qualifiers)
98        bool unifyInexact( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widen, const SymTab::Indexer &indexer, Type *&common );
99        bool unifyExact( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widen, const SymTab::Indexer &indexer );
100
101        bool unifyExact(
102                const ast::Type * type1, const ast::Type * type2, ast::TypeEnvironment & env,
103                ast::AssertionSet & need, ast::AssertionSet & have, const ast::OpenVarSet & open,
104                WidenMode widen, const ast::SymbolTable & symtab );
105
106        bool typesCompatible( const Type * first, const Type * second, const SymTab::Indexer & indexer, const TypeEnvironment & env ) {
107                TypeEnvironment newEnv;
108                OpenVarSet openVars, closedVars; // added closedVars
109                AssertionSet needAssertions, haveAssertions;
110                Type * newFirst = first->clone(), * newSecond = second->clone();
111                env.apply( newFirst );
112                env.apply( newSecond );
113
114                // do we need to do this? Seems like we do, types should be able to be compatible if they
115                // have free variables that can unify
116                findOpenVars( newFirst, openVars, closedVars, needAssertions, haveAssertions, false );
117                findOpenVars( newSecond, openVars, closedVars, needAssertions, haveAssertions, true );
118
119                bool result = unifyExact( newFirst, newSecond, newEnv, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
120                delete newFirst;
121                delete newSecond;
122                return result;
123        }
124
125        bool typesCompatible(
126                        const ast::Type * first, const ast::Type * second, const ast::SymbolTable & symtab,
127                        const ast::TypeEnvironment & env ) {
128                ast::TypeEnvironment newEnv;
129                ast::OpenVarSet open, closed;
130                ast::AssertionSet need, have;
131
132                ast::ptr<ast::Type> newFirst{ first }, newSecond{ second };
133                env.apply( newFirst );
134                env.apply( newSecond );
135
136                findOpenVars( newFirst, open, closed, need, have, FirstClosed );
137                findOpenVars( newSecond, open, closed, need, have, FirstOpen );
138
139                return unifyExact(newFirst, newSecond, newEnv, need, have, open, noWiden(), symtab );
140        }
141
142        bool typesCompatibleIgnoreQualifiers( const Type * first, const Type * second, const SymTab::Indexer &indexer, const TypeEnvironment &env ) {
143                TypeEnvironment newEnv;
144                OpenVarSet openVars;
145                AssertionSet needAssertions, haveAssertions;
146                Type *newFirst = first->clone(), *newSecond = second->clone();
147                env.apply( newFirst );
148                env.apply( newSecond );
149                newFirst->get_qualifiers() = Type::Qualifiers();
150                newSecond->get_qualifiers() = Type::Qualifiers();
151
152                bool result = unifyExact( newFirst, newSecond, newEnv, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
153                delete newFirst;
154                delete newSecond;
155                return result;
156        }
157
158        bool typesCompatibleIgnoreQualifiers(
159                        const ast::Type * first, const ast::Type * second, const ast::SymbolTable & symtab,
160                        const ast::TypeEnvironment & env ) {
161                ast::TypeEnvironment newEnv;
162                ast::OpenVarSet open;
163                ast::AssertionSet need, have;
164
165                ast::Type * newFirst  = shallowCopy( first  );
166                ast::Type * newSecond = shallowCopy( second );
167                newFirst ->qualifiers = {};
168                newSecond->qualifiers = {};
169                ast::ptr< ast::Type > t1_(newFirst );
170                ast::ptr< ast::Type > t2_(newSecond);
171
172                return unifyExact(
173                        env.apply( newFirst  ).node,
174                        env.apply( newSecond ).node,
175                        newEnv, need, have, open, noWiden(), symtab );
176        }
177
178        bool unify( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, OpenVarSet &openVars, const SymTab::Indexer &indexer ) {
179                OpenVarSet closedVars;
180                findOpenVars( type1, openVars, closedVars, needAssertions, haveAssertions, false );
181                findOpenVars( type2, openVars, closedVars, needAssertions, haveAssertions, true );
182                Type *commonType = 0;
183                if ( unifyInexact( type1, type2, env, needAssertions, haveAssertions, openVars, WidenMode( true, true ), indexer, commonType ) ) {
184                        if ( commonType ) {
185                                delete commonType;
186                        } // if
187                        return true;
188                } else {
189                        return false;
190                } // if
191        }
192
193        bool unify( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, OpenVarSet &openVars, const SymTab::Indexer &indexer, Type *&commonType ) {
194                OpenVarSet closedVars;
195                findOpenVars( type1, openVars, closedVars, needAssertions, haveAssertions, false );
196                findOpenVars( type2, openVars, closedVars, needAssertions, haveAssertions, true );
197                return unifyInexact( type1, type2, env, needAssertions, haveAssertions, openVars, WidenMode( true, true ), indexer, commonType );
198        }
199
200        bool unifyExact( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widen, const SymTab::Indexer &indexer ) {
201#ifdef DEBUG
202                TypeEnvironment debugEnv( env );
203#endif
204                if ( type1->get_qualifiers() != type2->get_qualifiers() ) {
205                        return false;
206                }
207
208                bool result;
209                TypeInstType *var1 = dynamic_cast< TypeInstType* >( type1 );
210                TypeInstType *var2 = dynamic_cast< TypeInstType* >( type2 );
211                OpenVarSet::const_iterator entry1, entry2;
212                if ( var1 ) {
213                        entry1 = openVars.find( var1->get_name() );
214                } // if
215                if ( var2 ) {
216                        entry2 = openVars.find( var2->get_name() );
217                } // if
218                bool isopen1 = var1 && ( entry1 != openVars.end() );
219                bool isopen2 = var2 && ( entry2 != openVars.end() );
220
221                if ( isopen1 && isopen2 ) {
222                        if ( entry1->second.kind != entry2->second.kind ) {
223                                result = false;
224                        } else {
225                                result = env.bindVarToVar(
226                                        var1, var2, TypeDecl::Data{ entry1->second, entry2->second }, needAssertions,
227                                        haveAssertions, openVars, widen, indexer );
228                        }
229                } else if ( isopen1 ) {
230                        result = env.bindVar( var1, type2, entry1->second, needAssertions, haveAssertions, openVars, widen, indexer );
231                } else if ( isopen2 ) { // TODO: swap widen values in call, since type positions are flipped?
232                        result = env.bindVar( var2, type1, entry2->second, needAssertions, haveAssertions, openVars, widen, indexer );
233                } else {
234                        PassVisitor<Unify_old> comparator( type2, env, needAssertions, haveAssertions, openVars, widen, indexer );
235                        type1->accept( comparator );
236                        result = comparator.pass.get_result();
237                } // if
238#ifdef DEBUG
239                std::cerr << "============ unifyExact" << std::endl;
240                std::cerr << "type1 is ";
241                type1->print( std::cerr );
242                std::cerr << std::endl << "type2 is ";
243                type2->print( std::cerr );
244                std::cerr << std::endl << "openVars are ";
245                printOpenVarSet( openVars, std::cerr, 8 );
246                std::cerr << std::endl << "input env is " << std::endl;
247                debugEnv.print( std::cerr, 8 );
248                std::cerr << std::endl << "result env is " << std::endl;
249                env.print( std::cerr, 8 );
250                std::cerr << "result is " << result << std::endl;
251#endif
252                return result;
253        }
254
255        bool unifyExact( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, OpenVarSet &openVars, const SymTab::Indexer &indexer ) {
256                return unifyExact( type1, type2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
257        }
258
259        bool unifyInexact( Type *type1, Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widen, const SymTab::Indexer &indexer, Type *&common ) {
260                Type::Qualifiers tq1 = type1->get_qualifiers(), tq2 = type2->get_qualifiers();
261                type1->get_qualifiers() = Type::Qualifiers();
262                type2->get_qualifiers() = Type::Qualifiers();
263                bool result;
264#ifdef DEBUG
265                std::cerr << "unifyInexact type 1 is ";
266                type1->print( std::cerr );
267                std::cerr << " type 2 is ";
268                type2->print( std::cerr );
269                std::cerr << std::endl;
270#endif
271                if ( ! unifyExact( type1, type2, env, needAssertions, haveAssertions, openVars, widen, indexer ) ) {
272#ifdef DEBUG
273                        std::cerr << "unifyInexact: no exact unification found" << std::endl;
274#endif
275                        if ( ( common = commonType( type1, type2, widen.first, widen.second, indexer, env, openVars ) ) ) {
276                                common->tq = tq1.unify( tq2 );
277#ifdef DEBUG
278                                std::cerr << "unifyInexact: common type is ";
279                                common->print( std::cerr );
280                                std::cerr << std::endl;
281#endif
282                                result = true;
283                        } else {
284#ifdef DEBUG
285                                std::cerr << "unifyInexact: no common type found" << std::endl;
286#endif
287                                result = false;
288                        } // if
289                } else {
290                        if ( tq1 != tq2 ) {
291                                if ( ( tq1 > tq2 || widen.first ) && ( tq2 > tq1 || widen.second ) ) {
292                                        common = type1->clone();
293                                        common->tq = tq1.unify( tq2 );
294                                        result = true;
295                                } else {
296                                        result = false;
297                                } // if
298                        } else {
299                                common = type1->clone();
300                                common->tq = tq1.unify( tq2 );
301                                result = true;
302                        } // if
303                } // if
304                type1->get_qualifiers() = tq1;
305                type2->get_qualifiers() = tq2;
306                return result;
307        }
308
309        Unify_old::Unify_old( Type *type2, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, WidenMode widen, const SymTab::Indexer &indexer )
310                : result( false ), type2( type2 ), env( env ), needAssertions( needAssertions ), haveAssertions( haveAssertions ), openVars( openVars ), widen( widen ), indexer( indexer ) {
311        }
312
313        void Unify_old::postvisit( __attribute__((unused)) VoidType *voidType) {
314                result = dynamic_cast< VoidType* >( type2 );
315        }
316
317        void Unify_old::postvisit(BasicType *basicType) {
318                if ( BasicType *otherBasic = dynamic_cast< BasicType* >( type2 ) ) {
319                        result = basicType->get_kind() == otherBasic->get_kind();
320                } // if
321        }
322
323        void markAssertionSet( AssertionSet &assertions, DeclarationWithType *assert ) {
324                AssertionSet::iterator i = assertions.find( assert );
325                if ( i != assertions.end() ) {
326                        i->second.isUsed = true;
327                } // if
328        }
329
330        void markAssertions( AssertionSet &assertion1, AssertionSet &assertion2, Type *type ) {
331                for ( std::list< TypeDecl* >::const_iterator tyvar = type->get_forall().begin(); tyvar != type->get_forall().end(); ++tyvar ) {
332                        for ( std::list< DeclarationWithType* >::const_iterator assert = (*tyvar)->get_assertions().begin(); assert != (*tyvar)->get_assertions().end(); ++assert ) {
333                                markAssertionSet( assertion1, *assert );
334                                markAssertionSet( assertion2, *assert );
335                        } // for
336                } // for
337        }
338
339        void Unify_old::postvisit(PointerType *pointerType) {
340                if ( PointerType *otherPointer = dynamic_cast< PointerType* >( type2 ) ) {
341                        result = unifyExact( pointerType->get_base(), otherPointer->get_base(), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
342                        markAssertions( haveAssertions, needAssertions, pointerType );
343                        markAssertions( haveAssertions, needAssertions, otherPointer );
344                } // if
345        }
346
347        void Unify_old::postvisit(ReferenceType *refType) {
348                if ( ReferenceType *otherRef = dynamic_cast< ReferenceType* >( type2 ) ) {
349                        result = unifyExact( refType->get_base(), otherRef->get_base(), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
350                        markAssertions( haveAssertions, needAssertions, refType );
351                        markAssertions( haveAssertions, needAssertions, otherRef );
352                } // if
353        }
354
355        void Unify_old::postvisit(ArrayType *arrayType) {
356                ArrayType *otherArray = dynamic_cast< ArrayType* >( type2 );
357                // to unify, array types must both be VLA or both not VLA
358                // and must both have a dimension expression or not have a dimension
359                if ( otherArray && arrayType->get_isVarLen() == otherArray->get_isVarLen() ) {
360
361                        if ( ! arrayType->get_isVarLen() && ! otherArray->get_isVarLen() &&
362                                arrayType->get_dimension() != 0 && otherArray->get_dimension() != 0 ) {
363                                ConstantExpr * ce1 = dynamic_cast< ConstantExpr * >( arrayType->get_dimension() );
364                                ConstantExpr * ce2 = dynamic_cast< ConstantExpr * >( otherArray->get_dimension() );
365                                // see C11 Reference Manual 6.7.6.2.6
366                                // two array types with size specifiers that are integer constant expressions are
367                                // compatible if both size specifiers have the same constant value
368                                if ( ce1 && ce2 ) {
369                                        Constant * c1 = ce1->get_constant();
370                                        Constant * c2 = ce2->get_constant();
371
372                                        if ( c1->get_value() != c2->get_value() ) {
373                                                // does not unify if the dimension is different
374                                                return;
375                                        }
376                                }
377                        }
378
379                        result = unifyExact( arrayType->get_base(), otherArray->get_base(), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
380                } // if
381        }
382
383        template< typename Iterator, typename Func >
384        std::unique_ptr<Type> combineTypes( Iterator begin, Iterator end, Func & toType ) {
385                std::list< Type * > types;
386                for ( ; begin != end; ++begin ) {
387                        // it's guaranteed that a ttype variable will be bound to a flat tuple, so ensure that this results in a flat tuple
388                        flatten( toType( *begin ), back_inserter( types ) );
389                }
390                return std::unique_ptr<Type>( new TupleType( Type::Qualifiers(), types ) );
391        }
392
393        template< typename Iterator1, typename Iterator2 >
394        bool unifyDeclList( Iterator1 list1Begin, Iterator1 list1End, Iterator2 list2Begin, Iterator2 list2End, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, const SymTab::Indexer &indexer ) {
395                auto get_type = [](DeclarationWithType * dwt){ return dwt->get_type(); };
396                for ( ; list1Begin != list1End && list2Begin != list2End; ++list1Begin, ++list2Begin ) {
397                        Type * t1 = (*list1Begin)->get_type();
398                        Type * t2 = (*list2Begin)->get_type();
399                        bool isTtype1 = Tuples::isTtype( t1 );
400                        bool isTtype2 = Tuples::isTtype( t2 );
401                        // xxx - assumes ttype must be last parameter
402                        // xxx - there may be a nice way to refactor this, but be careful because the argument positioning might matter in some cases.
403                        if ( isTtype1 && ! isTtype2 ) {
404                                // combine all of the things in list2, then unify
405                                return unifyExact( t1, combineTypes( list2Begin, list2End, get_type ).get(), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
406                        } else if ( isTtype2 && ! isTtype1 ) {
407                                // combine all of the things in list1, then unify
408                                return unifyExact( combineTypes( list1Begin, list1End, get_type ).get(), t2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
409                        } else if ( ! unifyExact( t1, t2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer ) ) {
410                                return false;
411                        } // if
412                } // for
413                // 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
414                if ( list1Begin != list1End ) {
415                        // try unifying empty tuple type with ttype
416                        Type * t1 = (*list1Begin)->get_type();
417                        if ( Tuples::isTtype( t1 ) ) {
418                                return unifyExact( t1, combineTypes( list2Begin, list2End, get_type ).get(), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
419                        } else return false;
420                } else if ( list2Begin != list2End ) {
421                        // try unifying empty tuple type with ttype
422                        Type * t2 = (*list2Begin)->get_type();
423                        if ( Tuples::isTtype( t2 ) ) {
424                                return unifyExact( combineTypes( list1Begin, list1End, get_type ).get(), t2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
425                        } else return false;
426                } else {
427                        return true;
428                } // if
429        }
430
431        /// Finds ttypes and replaces them with their expansion, if known.
432        /// This needs to be done so that satisfying ttype assertions is easier.
433        /// If this isn't done then argument lists can have wildly different
434        /// size and structure, when they should be compatible.
435        struct TtypeExpander_old : public WithShortCircuiting {
436                TypeEnvironment & tenv;
437                TtypeExpander_old( TypeEnvironment & tenv ) : tenv( tenv ) {}
438                void premutate( TypeInstType * ) { visit_children = false; }
439                Type * postmutate( TypeInstType * typeInst ) {
440                        if ( const EqvClass *eqvClass = tenv.lookup( typeInst->get_name() ) ) {
441                                // expand ttype parameter into its actual type
442                                if ( eqvClass->data.kind == TypeDecl::Ttype && eqvClass->type ) {
443                                        delete typeInst;
444                                        return eqvClass->type->clone();
445                                }
446                        }
447                        return typeInst;
448                }
449        };
450
451        /// flattens a list of declarations, so that each tuple type has a single declaration.
452        /// makes use of TtypeExpander to ensure ttypes are flat as well.
453        void flattenList( std::list< DeclarationWithType * > src, std::list< DeclarationWithType * > & dst, TypeEnvironment & env ) {
454                dst.clear();
455                for ( DeclarationWithType * dcl : src ) {
456                        PassVisitor<TtypeExpander_old> expander( env );
457                        dcl->acceptMutator( expander );
458                        std::list< Type * > types;
459                        flatten( dcl->get_type(), back_inserter( types ) );
460                        for ( Type * t : types ) {
461                                // 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.
462                                // 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.
463                                t->get_qualifiers() -= Type::Qualifiers(Type::Const | Type::Volatile | Type::Atomic);
464
465                                dst.push_back( new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::C, nullptr, t, nullptr ) );
466                        }
467                        delete dcl;
468                }
469        }
470
471        void Unify_old::postvisit(FunctionType *functionType) {
472                FunctionType *otherFunction = dynamic_cast< FunctionType* >( type2 );
473                if ( otherFunction && functionType->get_isVarArgs() == otherFunction->get_isVarArgs() ) {
474                        // flatten the parameter lists for both functions so that tuple structure
475                        // doesn't affect unification. Must be a clone so that the types don't change.
476                        std::unique_ptr<FunctionType> flatFunc( functionType->clone() );
477                        std::unique_ptr<FunctionType> flatOther( otherFunction->clone() );
478                        flattenList( flatFunc->get_parameters(), flatFunc->get_parameters(), env );
479                        flattenList( flatOther->get_parameters(), flatOther->get_parameters(), env );
480
481                        // sizes don't have to match if ttypes are involved; need to be more precise wrt where the ttype is to prevent errors
482                        if (
483                                        (flatFunc->parameters.size() == flatOther->parameters.size() &&
484                                                flatFunc->returnVals.size() == flatOther->returnVals.size())
485                                        || flatFunc->isTtype()
486                                        || flatOther->isTtype()
487                        ) {
488                                if ( unifyDeclList( flatFunc->parameters.begin(), flatFunc->parameters.end(), flatOther->parameters.begin(), flatOther->parameters.end(), env, needAssertions, haveAssertions, openVars, indexer ) ) {
489                                        if ( unifyDeclList( flatFunc->returnVals.begin(), flatFunc->returnVals.end(), flatOther->returnVals.begin(), flatOther->returnVals.end(), env, needAssertions, haveAssertions, openVars, indexer ) ) {
490
491                                                // the original types must be used in mark assertions, since pointer comparisons are used
492                                                markAssertions( haveAssertions, needAssertions, functionType );
493                                                markAssertions( haveAssertions, needAssertions, otherFunction );
494
495                                                result = true;
496                                        } // if
497                                } // if
498                        } // if
499                } // if
500        }
501
502        template< typename RefType >
503        void Unify_old::handleRefType( RefType *inst, Type *other ) {
504                // check that other type is compatible and named the same
505                RefType *otherStruct = dynamic_cast< RefType* >( other );
506                result = otherStruct && inst->name == otherStruct->name;
507        }
508
509        template< typename RefType >
510        void Unify_old::handleGenericRefType( RefType *inst, Type *other ) {
511                // Check that other type is compatible and named the same
512                handleRefType( inst, other );
513                if ( ! result ) return;
514                // Check that parameters of types unify, if any
515                std::list< Expression* > params = inst->parameters;
516                std::list< Expression* > otherParams = ((RefType*)other)->parameters;
517
518                std::list< Expression* >::const_iterator it = params.begin(), jt = otherParams.begin();
519                for ( ; it != params.end() && jt != otherParams.end(); ++it, ++jt ) {
520                        TypeExpr *param = dynamic_cast< TypeExpr* >(*it);
521                        assertf(param, "Aggregate parameters should be type expressions");
522                        TypeExpr *otherParam = dynamic_cast< TypeExpr* >(*jt);
523                        assertf(otherParam, "Aggregate parameters should be type expressions");
524
525                        Type* paramTy = param->get_type();
526                        Type* otherParamTy = otherParam->get_type();
527
528                        bool tupleParam = Tuples::isTtype( paramTy );
529                        bool otherTupleParam = Tuples::isTtype( otherParamTy );
530
531                        if ( tupleParam && otherTupleParam ) {
532                                ++it; ++jt;  // skip ttype parameters for break
533                        } else if ( tupleParam ) {
534                                // bundle other parameters into tuple to match
535                                std::list< Type * > binderTypes;
536
537                                do {
538                                        binderTypes.push_back( otherParam->get_type()->clone() );
539                                        ++jt;
540
541                                        if ( jt == otherParams.end() ) break;
542
543                                        otherParam = dynamic_cast< TypeExpr* >(*jt);
544                                        assertf(otherParam, "Aggregate parameters should be type expressions");
545                                } while (true);
546
547                                otherParamTy = new TupleType{ paramTy->get_qualifiers(), binderTypes };
548                                ++it;  // skip ttype parameter for break
549                        } else if ( otherTupleParam ) {
550                                // bundle parameters into tuple to match other
551                                std::list< Type * > binderTypes;
552
553                                do {
554                                        binderTypes.push_back( param->get_type()->clone() );
555                                        ++it;
556
557                                        if ( it == params.end() ) break;
558
559                                        param = dynamic_cast< TypeExpr* >(*it);
560                                        assertf(param, "Aggregate parameters should be type expressions");
561                                } while (true);
562
563                                paramTy = new TupleType{ otherParamTy->get_qualifiers(), binderTypes };
564                                ++jt;  // skip ttype parameter for break
565                        }
566
567                        if ( ! unifyExact( paramTy, otherParamTy, env, needAssertions, haveAssertions, openVars, WidenMode(false, false), indexer ) ) {
568                                result = false;
569                                return;
570                        }
571
572                        // ttype parameter should be last
573                        if ( tupleParam || otherTupleParam ) break;
574                }
575                result = ( it == params.end() && jt == otherParams.end() );
576        }
577
578        void Unify_old::postvisit(StructInstType *structInst) {
579                handleGenericRefType( structInst, type2 );
580        }
581
582        void Unify_old::postvisit(UnionInstType *unionInst) {
583                handleGenericRefType( unionInst, type2 );
584        }
585
586        void Unify_old::postvisit(EnumInstType *enumInst) {
587                handleRefType( enumInst, type2 );
588        }
589
590        void Unify_old::postvisit(TraitInstType *contextInst) {
591                handleRefType( contextInst, type2 );
592        }
593
594        void Unify_old::postvisit(TypeInstType *typeInst) {
595                assert( openVars.find( typeInst->get_name() ) == openVars.end() );
596                TypeInstType *otherInst = dynamic_cast< TypeInstType* >( type2 );
597                if ( otherInst && typeInst->get_name() == otherInst->get_name() ) {
598                        result = true;
599///   } else {
600///     NamedTypeDecl *nt = indexer.lookupType( typeInst->get_name() );
601///     if ( nt ) {
602///       TypeDecl *type = dynamic_cast< TypeDecl* >( nt );
603///       assert( type );
604///       if ( type->get_base() ) {
605///         result = unifyExact( type->get_base(), typeInst, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
606///       }
607///     }
608                } // if
609        }
610
611        template< typename Iterator1, typename Iterator2 >
612        bool unifyList( Iterator1 list1Begin, Iterator1 list1End, Iterator2 list2Begin, Iterator2 list2End, TypeEnvironment &env, AssertionSet &needAssertions, AssertionSet &haveAssertions, const OpenVarSet &openVars, const SymTab::Indexer &indexer ) {
613                auto get_type = [](Type * t) { return t; };
614                for ( ; list1Begin != list1End && list2Begin != list2End; ++list1Begin, ++list2Begin ) {
615                        Type * t1 = *list1Begin;
616                        Type * t2 = *list2Begin;
617                        bool isTtype1 = Tuples::isTtype( t1 );
618                        bool isTtype2 = Tuples::isTtype( t2 );
619                        // xxx - assumes ttype must be last parameter
620                        // xxx - there may be a nice way to refactor this, but be careful because the argument positioning might matter in some cases.
621                        if ( isTtype1 && ! isTtype2 ) {
622                                // combine all of the things in list2, then unify
623                                return unifyExact( t1, combineTypes( list2Begin, list2End, get_type ).get(), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
624                        } else if ( isTtype2 && ! isTtype1 ) {
625                                // combine all of the things in list1, then unify
626                                return unifyExact( combineTypes( list1Begin, list1End, get_type ).get(), t2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
627                        } else if ( ! unifyExact( t1, t2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer ) ) {
628                                return false;
629                        } // if
630
631                } // for
632                if ( list1Begin != list1End ) {
633                        // try unifying empty tuple type with ttype
634                        Type * t1 = *list1Begin;
635                        if ( Tuples::isTtype( t1 ) ) {
636                                return unifyExact( t1, combineTypes( list2Begin, list2End, get_type ).get(), env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
637                        } else return false;
638                } else if ( list2Begin != list2End ) {
639                        // try unifying empty tuple type with ttype
640                        Type * t2 = *list2Begin;
641                        if ( Tuples::isTtype( t2 ) ) {
642                                return unifyExact( combineTypes( list1Begin, list1End, get_type ).get(), t2, env, needAssertions, haveAssertions, openVars, WidenMode( false, false ), indexer );
643                        } else return false;
644                } else {
645                        return true;
646                } // if
647        }
648
649        void Unify_old::postvisit(TupleType *tupleType) {
650                if ( TupleType *otherTuple = dynamic_cast< TupleType* >( type2 ) ) {
651                        std::unique_ptr<TupleType> flat1( tupleType->clone() );
652                        std::unique_ptr<TupleType> flat2( otherTuple->clone() );
653                        std::list<Type *> types1, types2;
654
655                        PassVisitor<TtypeExpander_old> expander( env );
656                        flat1->acceptMutator( expander );
657                        flat2->acceptMutator( expander );
658
659                        flatten( flat1.get(), back_inserter( types1 ) );
660                        flatten( flat2.get(), back_inserter( types2 ) );
661
662                        result = unifyList( types1.begin(), types1.end(), types2.begin(), types2.end(), env, needAssertions, haveAssertions, openVars, indexer );
663                } // if
664        }
665
666        void Unify_old::postvisit( __attribute__((unused)) VarArgsType *varArgsType ) {
667                result = dynamic_cast< VarArgsType* >( type2 );
668        }
669
670        void Unify_old::postvisit( __attribute__((unused)) ZeroType *zeroType ) {
671                result = dynamic_cast< ZeroType* >( type2 );
672        }
673
674        void Unify_old::postvisit( __attribute__((unused)) OneType *oneType ) {
675                result = dynamic_cast< OneType* >( type2 );
676        }
677
678        Type * extractResultType( FunctionType * function ) {
679                if ( function->get_returnVals().size() == 0 ) {
680                        return new VoidType( Type::Qualifiers() );
681                } else if ( function->get_returnVals().size() == 1 ) {
682                        return function->get_returnVals().front()->get_type()->clone();
683                } else {
684                        std::list< Type * > types;
685                        for ( DeclarationWithType * decl : function->get_returnVals() ) {
686                                types.push_back( decl->get_type()->clone() );
687                        } // for
688                        return new TupleType( Type::Qualifiers(), types );
689                }
690        }
691
692        class Unify_new final : public ast::WithShortCircuiting {
693                const ast::Type * type2;
694                ast::TypeEnvironment & tenv;
695                ast::AssertionSet & need;
696                ast::AssertionSet & have;
697                const ast::OpenVarSet & open;
698                WidenMode widen;
699                const ast::SymbolTable & symtab;
700        public:
701                bool result;
702
703                Unify_new(
704                        const ast::Type * type2, ast::TypeEnvironment & env, ast::AssertionSet & need,
705                        ast::AssertionSet & have, const ast::OpenVarSet & open, WidenMode widen,
706                        const ast::SymbolTable & symtab )
707                : type2(type2), tenv(env), need(need), have(have), open(open), widen(widen),
708                  symtab(symtab), result(false) {}
709
710                void previsit( const ast::Node * ) { visit_children = false; }
711
712                void postvisit( const ast::VoidType * ) {
713                        result = dynamic_cast< const ast::VoidType * >( type2 );
714                }
715
716                void postvisit( const ast::BasicType * basic ) {
717                        if ( auto basic2 = dynamic_cast< const ast::BasicType * >( type2 ) ) {
718                                result = basic->kind == basic2->kind;
719                        }
720                }
721
722                void postvisit( const ast::PointerType * pointer ) {
723                        if ( auto pointer2 = dynamic_cast< const ast::PointerType * >( type2 ) ) {
724                                result = unifyExact(
725                                        pointer->base, pointer2->base, tenv, need, have, open,
726                                        noWiden(), symtab );
727                        }
728                }
729
730                void postvisit( const ast::ArrayType * array ) {
731                        auto array2 = dynamic_cast< const ast::ArrayType * >( type2 );
732                        if ( ! array2 ) return;
733
734                        // to unify, array types must both be VLA or both not VLA and both must have a
735                        // dimension expression or not have a dimension
736                        if ( array->isVarLen != array2->isVarLen ) return;
737                        if ( ! array->isVarLen && ! array2->isVarLen
738                                        && array->dimension && array2->dimension ) {
739                                auto ce1 = array->dimension.as< ast::ConstantExpr >();
740                                auto ce2 = array2->dimension.as< ast::ConstantExpr >();
741
742                                // see C11 Reference Manual 6.7.6.2.6
743                                // two array types with size specifiers that are integer constant expressions are
744                                // compatible if both size specifiers have the same constant value
745                                if ( ce1 && ce2 && ce1->intValue() != ce2->intValue() ) return;
746                        }
747
748                        result = unifyExact(
749                                array->base, array2->base, tenv, need, have, open, noWiden(),
750                                symtab );
751                }
752
753                void postvisit( const ast::ReferenceType * ref ) {
754                        if ( auto ref2 = dynamic_cast< const ast::ReferenceType * >( type2 ) ) {
755                                result = unifyExact(
756                                        ref->base, ref2->base, tenv, need, have, open, noWiden(),
757                                        symtab );
758                        }
759                }
760
761        private:
762                /// Replaces ttype variables with their bound types.
763                /// If this isn't done when satifying ttype assertions, then argument lists can have
764                /// different size and structure when they should be compatible.
765                struct TtypeExpander_new : public ast::WithShortCircuiting {
766                        ast::TypeEnvironment & tenv;
767
768                        TtypeExpander_new( ast::TypeEnvironment & env ) : tenv( env ) {}
769
770                        const ast::Type * postvisit( const ast::TypeInstType * typeInst ) {
771                                if ( const ast::EqvClass * clz = tenv.lookup( typeInst->name ) ) {
772                                        // expand ttype parameter into its actual type
773                                        if ( clz->data.kind == ast::TypeDecl::Ttype && clz->bound ) {
774                                                return clz->bound;
775                                        }
776                                }
777                                return typeInst;
778                        }
779                };
780
781                /// returns flattened version of `src`
782                static std::vector< ast::ptr< ast::DeclWithType > > flattenList(
783                        const std::vector< ast::ptr< ast::DeclWithType > > & src, ast::TypeEnvironment & env
784                ) {
785                        std::vector< ast::ptr< ast::DeclWithType > > dst;
786                        dst.reserve( src.size() );
787                        for ( const ast::DeclWithType * d : src ) {
788                                ast::Pass<TtypeExpander_new> expander{ env };
789                                d = d->accept( expander );
790                                auto types = flatten( d->get_type() );
791                                for ( ast::ptr< ast::Type > & t : types ) {
792                                        // outermost const, volatile, _Atomic qualifiers in parameters should not play
793                                        // a role in the unification of function types, since they do not determine
794                                        // whether a function is callable.
795                                        // NOTE: **must** consider at least mutex qualifier, since functions can be
796                                        // overloaded on outermost mutex and a mutex function has different
797                                        // requirements than a non-mutex function
798                                        remove_qualifiers( t, ast::CV::Const | ast::CV::Volatile | ast::CV::Atomic );
799                                        dst.emplace_back( new ast::ObjectDecl{ d->location, "", t } );
800                                }
801                        }
802                        return dst;
803                }
804
805                /// Creates a tuple type based on a list of DeclWithType
806                template< typename Iter >
807                static ast::ptr< ast::Type > tupleFromDecls( Iter crnt, Iter end ) {
808                        std::vector< ast::ptr< ast::Type > > types;
809                        while ( crnt != end ) {
810                                // it is guaranteed that a ttype variable will be bound to a flat tuple, so ensure
811                                // that this results in a flat tuple
812                                flatten( (*crnt)->get_type(), types );
813
814                                ++crnt;
815                        }
816
817                        return { new ast::TupleType{ std::move(types) } };
818                }
819
820                template< typename Iter >
821                static bool unifyDeclList(
822                        Iter crnt1, Iter end1, Iter crnt2, Iter end2, ast::TypeEnvironment & env,
823                        ast::AssertionSet & need, ast::AssertionSet & have, const ast::OpenVarSet & open,
824                        const ast::SymbolTable & symtab
825                ) {
826                        while ( crnt1 != end1 && crnt2 != end2 ) {
827                                const ast::Type * t1 = (*crnt1)->get_type();
828                                const ast::Type * t2 = (*crnt2)->get_type();
829                                bool isTuple1 = Tuples::isTtype( t1 );
830                                bool isTuple2 = Tuples::isTtype( t2 );
831
832                                // assumes here that ttype *must* be last parameter
833                                if ( isTuple1 && ! isTuple2 ) {
834                                        // combine remainder of list2, then unify
835                                        return unifyExact(
836                                                t1, tupleFromDecls( crnt2, end2 ), env, need, have, open,
837                                                noWiden(), symtab );
838                                } else if ( ! isTuple1 && isTuple2 ) {
839                                        // combine remainder of list1, then unify
840                                        return unifyExact(
841                                                tupleFromDecls( crnt1, end1 ), t2, env, need, have, open,
842                                                noWiden(), symtab );
843                                }
844
845                                if ( ! unifyExact(
846                                        t1, t2, env, need, have, open, noWiden(), symtab )
847                                ) return false;
848
849                                ++crnt1; ++crnt2;
850                        }
851
852                        // May get to the end of one argument list before the other. This is only okay if the
853                        // other is a ttype
854                        if ( crnt1 != end1 ) {
855                                // try unifying empty tuple with ttype
856                                const ast::Type * t1 = (*crnt1)->get_type();
857                                if ( ! Tuples::isTtype( t1 ) ) return false;
858                                return unifyExact(
859                                        t1, tupleFromDecls( crnt2, end2 ), env, need, have, open,
860                                        noWiden(), symtab );
861                        } else if ( crnt2 != end2 ) {
862                                // try unifying empty tuple with ttype
863                                const ast::Type * t2 = (*crnt2)->get_type();
864                                if ( ! Tuples::isTtype( t2 ) ) return false;
865                                return unifyExact(
866                                        tupleFromDecls( crnt1, end1 ), t2, env, need, have, open,
867                                        noWiden(), symtab );
868                        }
869
870                        return true;
871                }
872
873                static bool unifyDeclList(
874                        const std::vector< ast::ptr< ast::DeclWithType > > & list1,
875                        const std::vector< ast::ptr< ast::DeclWithType > > & list2,
876                        ast::TypeEnvironment & env, ast::AssertionSet & need, ast::AssertionSet & have,
877                        const ast::OpenVarSet & open, const ast::SymbolTable & symtab
878                ) {
879                        return unifyDeclList(
880                                list1.begin(), list1.end(), list2.begin(), list2.end(), env, need, have, open,
881                                symtab );
882                }
883
884                static void markAssertionSet( ast::AssertionSet & assns, const ast::DeclWithType * assn ) {
885                        auto i = assns.find( assn );
886                        if ( i != assns.end() ) {
887                                i->second.isUsed = true;
888                        }
889                }
890
891                /// mark all assertions in `type` used in both `assn1` and `assn2`
892                static void markAssertions(
893                        ast::AssertionSet & assn1, ast::AssertionSet & assn2,
894                        const ast::ParameterizedType * type
895                ) {
896                        for ( const auto & tyvar : type->forall ) {
897                                for ( const ast::DeclWithType * assert : tyvar->assertions ) {
898                                        markAssertionSet( assn1, assert );
899                                        markAssertionSet( assn2, assert );
900                                }
901                        }
902                }
903
904        public:
905                void postvisit( const ast::FunctionType * func ) {
906                        auto func2 = dynamic_cast< const ast::FunctionType * >( type2 );
907                        if ( ! func2 ) return;
908
909                        if ( func->isVarArgs != func2->isVarArgs ) return;
910
911                        // Flatten the parameter lists for both functions so that tuple structure does not
912                        // affect unification. Does not actually mutate function parameters.
913                        auto params = flattenList( func->params, tenv );
914                        auto params2 = flattenList( func2->params, tenv );
915
916                        // sizes don't have to match if ttypes are involved; need to be more precise w.r.t.
917                        // where the ttype is to prevent errors
918                        if (
919                                ( params.size() != params2.size() || func->returns.size() != func2->returns.size() )
920                                && ! func->isTtype()
921                                && ! func2->isTtype()
922                        ) return;
923
924                        if ( ! unifyDeclList( params, params2, tenv, need, have, open, symtab ) ) return;
925                        if ( ! unifyDeclList(
926                                func->returns, func2->returns, tenv, need, have, open, symtab ) ) return;
927
928                        markAssertions( have, need, func );
929                        markAssertions( have, need, func2 );
930
931                        result = true;
932                }
933
934        private:
935                // Returns: other, cast as XInstType
936                // Assigns this->result: whether types are compatible (up to generic parameters)
937                template< typename XInstType >
938                const XInstType * handleRefType( const XInstType * inst, const ast::Type * other ) {
939                        // check that the other type is compatible and named the same
940                        auto otherInst = dynamic_cast< const XInstType * >( other );
941                        this->result = otherInst && inst->name == otherInst->name;
942                        return otherInst;
943                }
944
945                /// Creates a tuple type based on a list of TypeExpr
946                template< typename Iter >
947                static const ast::Type * tupleFromExprs(
948                        const ast::TypeExpr * param, Iter & crnt, Iter end, ast::CV::Qualifiers qs
949                ) {
950                        std::vector< ast::ptr< ast::Type > > types;
951                        do {
952                                types.emplace_back( param->type );
953
954                                ++crnt;
955                                if ( crnt == end ) break;
956                                param = strict_dynamic_cast< const ast::TypeExpr * >( crnt->get() );
957                        } while(true);
958
959                        return new ast::TupleType{ std::move(types), qs };
960                }
961
962                template< typename XInstType >
963                void handleGenericRefType( const XInstType * inst, const ast::Type * other ) {
964                        // check that other type is compatible and named the same
965                        const XInstType * otherInst = handleRefType( inst, other );
966                        if ( ! this->result ) return;
967
968                        // check that parameters of types unify, if any
969                        const std::vector< ast::ptr< ast::Expr > > & params = inst->params;
970                        const std::vector< ast::ptr< ast::Expr > > & params2 = otherInst->params;
971
972                        auto it = params.begin();
973                        auto jt = params2.begin();
974                        for ( ; it != params.end() && jt != params2.end(); ++it, ++jt ) {
975                                auto param = strict_dynamic_cast< const ast::TypeExpr * >( it->get() );
976                                auto param2 = strict_dynamic_cast< const ast::TypeExpr * >( jt->get() );
977
978                                ast::ptr< ast::Type > pty = param->type;
979                                ast::ptr< ast::Type > pty2 = param2->type;
980
981                                bool isTuple = Tuples::isTtype( pty );
982                                bool isTuple2 = Tuples::isTtype( pty2 );
983
984                                if ( isTuple && isTuple2 ) {
985                                        ++it; ++jt;  // skip ttype parameters before break
986                                } else if ( isTuple ) {
987                                        // bundle remaining params into tuple
988                                        pty2 = tupleFromExprs( param2, jt, params2.end(), pty->qualifiers );
989                                        ++it;  // skip ttype parameter for break
990                                } else if ( isTuple2 ) {
991                                        // bundle remaining params into tuple
992                                        pty = tupleFromExprs( param, it, params.end(), pty2->qualifiers );
993                                        ++jt;  // skip ttype parameter for break
994                                }
995
996                                if ( ! unifyExact(
997                                                pty, pty2, tenv, need, have, open, noWiden(), symtab ) ) {
998                                        result = false;
999                                        return;
1000                                }
1001
1002                                // ttype parameter should be last
1003                                if ( isTuple || isTuple2 ) break;
1004                        }
1005                        result = it == params.end() && jt == params2.end();
1006                }
1007
1008        public:
1009                void postvisit( const ast::StructInstType * aggrType ) {
1010                        handleGenericRefType( aggrType, type2 );
1011                }
1012
1013                void postvisit( const ast::UnionInstType * aggrType ) {
1014                        handleGenericRefType( aggrType, type2 );
1015                }
1016
1017                void postvisit( const ast::EnumInstType * aggrType ) {
1018                        handleRefType( aggrType, type2 );
1019                }
1020
1021                void postvisit( const ast::TraitInstType * aggrType ) {
1022                        handleRefType( aggrType, type2 );
1023                }
1024
1025                void postvisit( const ast::TypeInstType * typeInst ) {
1026                        assert( open.find( typeInst->name ) == open.end() );
1027                        handleRefType( typeInst, type2 );
1028                }
1029
1030        private:
1031                /// Creates a tuple type based on a list of Type
1032                static ast::ptr< ast::Type > tupleFromTypes(
1033                        const std::vector< ast::ptr< ast::Type > > & tys
1034                ) {
1035                        std::vector< ast::ptr< ast::Type > > out;
1036                        for ( const ast::Type * ty : tys ) {
1037                                // it is guaranteed that a ttype variable will be bound to a flat tuple, so ensure
1038                                // that this results in a flat tuple
1039                                flatten( ty, out );
1040                        }
1041
1042                        return { new ast::TupleType{ std::move(out) } };
1043                }
1044
1045                static bool unifyList(
1046                        const std::vector< ast::ptr< ast::Type > > & list1,
1047                        const std::vector< ast::ptr< ast::Type > > & list2, ast::TypeEnvironment & env,
1048                        ast::AssertionSet & need, ast::AssertionSet & have, const ast::OpenVarSet & open,
1049                        const ast::SymbolTable & symtab
1050                ) {
1051                        auto crnt1 = list1.begin();
1052                        auto crnt2 = list2.begin();
1053                        while ( crnt1 != list1.end() && crnt2 != list2.end() ) {
1054                                const ast::Type * t1 = *crnt1;
1055                                const ast::Type * t2 = *crnt2;
1056                                bool isTuple1 = Tuples::isTtype( t1 );
1057                                bool isTuple2 = Tuples::isTtype( t2 );
1058
1059                                // assumes ttype must be last parameter
1060                                if ( isTuple1 && ! isTuple2 ) {
1061                                        // combine entirety of list2, then unify
1062                                        return unifyExact(
1063                                                t1, tupleFromTypes( list2 ), env, need, have, open,
1064                                                noWiden(), symtab );
1065                                } else if ( ! isTuple1 && isTuple2 ) {
1066                                        // combine entirety of list1, then unify
1067                                        return unifyExact(
1068                                                tupleFromTypes( list1 ), t2, env, need, have, open,
1069                                                noWiden(), symtab );
1070                                }
1071
1072                                if ( ! unifyExact(
1073                                        t1, t2, env, need, have, open, noWiden(), symtab )
1074                                ) return false;
1075
1076                                ++crnt1; ++crnt2;
1077                        }
1078
1079                        if ( crnt1 != list1.end() ) {
1080                                // try unifying empty tuple type with ttype
1081                                const ast::Type * t1 = *crnt1;
1082                                if ( ! Tuples::isTtype( t1 ) ) return false;
1083                                // xxx - this doesn't generate an empty tuple, contrary to comment; both ported
1084                                // from Rob's code
1085                                return unifyExact(
1086                                                t1, tupleFromTypes( list2 ), env, need, have, open,
1087                                                noWiden(), symtab );
1088                        } else if ( crnt2 != list2.end() ) {
1089                                // try unifying empty tuple with ttype
1090                                const ast::Type * t2 = *crnt2;
1091                                if ( ! Tuples::isTtype( t2 ) ) return false;
1092                                // xxx - this doesn't generate an empty tuple, contrary to comment; both ported
1093                                // from Rob's code
1094                                return unifyExact(
1095                                                tupleFromTypes( list1 ), t2, env, need, have, open,
1096                                                noWiden(), symtab );
1097                        }
1098
1099                        return true;
1100                }
1101
1102        public:
1103                void postvisit( const ast::TupleType * tuple ) {
1104                        auto tuple2 = dynamic_cast< const ast::TupleType * >( type2 );
1105                        if ( ! tuple2 ) return;
1106
1107                        ast::Pass<TtypeExpander_new> expander{ tenv };
1108                        const ast::Type * flat = tuple->accept( expander );
1109                        const ast::Type * flat2 = tuple2->accept( expander );
1110
1111                        auto types = flatten( flat );
1112                        auto types2 = flatten( flat2 );
1113
1114                        result = unifyList( types, types2, tenv, need, have, open, symtab );
1115                }
1116
1117                void postvisit( const ast::VarArgsType * ) {
1118                        result = dynamic_cast< const ast::VarArgsType * >( type2 );
1119                }
1120
1121                void postvisit( const ast::ZeroType * ) {
1122                        result = dynamic_cast< const ast::ZeroType * >( type2 );
1123                }
1124
1125                void postvisit( const ast::OneType * ) {
1126                        result = dynamic_cast< const ast::OneType * >( type2 );
1127                }
1128
1129          private:
1130                template< typename RefType > void handleRefType( RefType *inst, Type *other );
1131                template< typename RefType > void handleGenericRefType( RefType *inst, Type *other );
1132        };
1133
1134        bool unify(
1135                        const ast::ptr<ast::Type> & type1, const ast::ptr<ast::Type> & type2,
1136                        ast::TypeEnvironment & env, ast::AssertionSet & need, ast::AssertionSet & have,
1137                        ast::OpenVarSet & open, const ast::SymbolTable & symtab
1138        ) {
1139                ast::ptr<ast::Type> common;
1140                return unify( type1, type2, env, need, have, open, symtab, common );
1141        }
1142
1143        bool unify(
1144                        const ast::ptr<ast::Type> & type1, const ast::ptr<ast::Type> & type2,
1145                        ast::TypeEnvironment & env, ast::AssertionSet & need, ast::AssertionSet & have,
1146                        ast::OpenVarSet & open, const ast::SymbolTable & symtab, ast::ptr<ast::Type> & common
1147        ) {
1148                ast::OpenVarSet closed;
1149                findOpenVars( type1, open, closed, need, have, FirstClosed );
1150                findOpenVars( type2, open, closed, need, have, FirstOpen );
1151                return unifyInexact(
1152                        type1, type2, env, need, have, open, WidenMode{ true, true }, symtab, common );
1153        }
1154
1155        bool unifyExact(
1156                        const ast::Type * type1, const ast::Type * type2, ast::TypeEnvironment & env,
1157                        ast::AssertionSet & need, ast::AssertionSet & have, const ast::OpenVarSet & open,
1158                        WidenMode widen, const ast::SymbolTable & symtab
1159        ) {
1160                if ( type1->qualifiers != type2->qualifiers ) return false;
1161
1162                auto var1 = dynamic_cast< const ast::TypeInstType * >( type1 );
1163                auto var2 = dynamic_cast< const ast::TypeInstType * >( type2 );
1164                ast::OpenVarSet::const_iterator
1165                        entry1 = var1 ? open.find( var1->name ) : open.end(),
1166                        entry2 = var2 ? open.find( var2->name ) : open.end();
1167                bool isopen1 = entry1 != open.end();
1168                bool isopen2 = entry2 != open.end();
1169
1170                if ( isopen1 && isopen2 ) {
1171                        if ( entry1->second.kind != entry2->second.kind ) return false;
1172                        return env.bindVarToVar(
1173                                var1, var2, ast::TypeDecl::Data{ entry1->second, entry2->second }, need, have,
1174                                open, widen, symtab );
1175                } else if ( isopen1 ) {
1176                        return env.bindVar( var1, type2, entry1->second, need, have, open, widen, symtab );
1177                } else if ( isopen2 ) {
1178                        return env.bindVar( var2, type1, entry2->second, need, have, open, widen, symtab );
1179                } else {
1180                        ast::Pass<Unify_new> comparator{ type2, env, need, have, open, widen, symtab };
1181                        type1->accept( comparator );
1182                        return comparator.pass.result;
1183                }
1184        }
1185
1186        bool unifyInexact(
1187                        const ast::ptr<ast::Type> & type1, const ast::ptr<ast::Type> & type2,
1188                        ast::TypeEnvironment & env, ast::AssertionSet & need, ast::AssertionSet & have,
1189                        const ast::OpenVarSet & open, WidenMode widen, const ast::SymbolTable & symtab,
1190                        ast::ptr<ast::Type> & common
1191        ) {
1192                ast::CV::Qualifiers q1 = type1->qualifiers, q2 = type2->qualifiers;
1193
1194                // force t1 and t2 to be cloned if their qualifiers must be stripped, so that type1 and
1195                // type2 are left unchanged; calling convention forces type{1,2}->strong_ref >= 1
1196                ast::Type * t1 = shallowCopy(type1.get());
1197                ast::Type * t2 = shallowCopy(type2.get());
1198                t1->qualifiers = {};
1199                t2->qualifiers = {};
1200                ast::ptr< ast::Type > t1_(t1);
1201                ast::ptr< ast::Type > t2_(t2);
1202
1203                if ( unifyExact( t1, t2, env, need, have, open, widen, symtab ) ) {
1204                        // if exact unification on unqualified types, try to merge qualifiers
1205                        if ( q1 == q2 || ( ( q1 > q2 || widen.first ) && ( q2 > q1 || widen.second ) ) ) {
1206                                t1->qualifiers = q1 | q2;
1207                                common = t1;
1208                                return true;
1209                        } else {
1210                                return false;
1211                        }
1212
1213                } else if (( common = commonType( t1, t2, widen, symtab, env, open ) )) {
1214                        // no exact unification, but common type
1215                        auto c = shallowCopy(common.get());
1216                        c->qualifiers = q1 | q2;
1217                        common = c;
1218                        return true;
1219                } else {
1220                        return false;
1221                }
1222        }
1223
1224        ast::ptr<ast::Type> extractResultType( const ast::FunctionType * func ) {
1225                if ( func->returns.empty() ) return new ast::VoidType{};
1226                if ( func->returns.size() == 1 ) return func->returns[0]->get_type();
1227
1228                std::vector<ast::ptr<ast::Type>> tys;
1229                for ( const ast::DeclWithType * decl : func->returns ) {
1230                        tys.emplace_back( decl->get_type() );
1231                }
1232                return new ast::TupleType{ std::move(tys) };
1233        }
1234} // namespace ResolvExpr
1235
1236// Local Variables: //
1237// tab-width: 4 //
1238// mode: c++ //
1239// compile-command: "make install" //
1240// End: //
Note: See TracBrowser for help on using the repository browser.