source: src/ResolvExpr/Unify.cc @ 8e18b8e

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

stop eagerly copying EqvClass? on lookup

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