source: src/ResolvExpr/Unify.cc @ ab9c1b3

Last change on this file since ab9c1b3 was 2908f08, checked in by Andrew Beach <ajbeach@…>, 10 months ago

Most of ResolvExpr? was written before the new style standard. Some files updated, focus on headers.

  • Property mode set to 100644
File size: 23.6 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
[07de76b]11// Last Modified By : Peter A. Buhr
12// Last Modified On : Fri Dec 13 23:43:05 2019
13// Update Count     : 46
[a32b204]14//
[51b7345]15
[f474e91]16#include "Unify.h"
17
[d76c588]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
[54e41b3]25#include <vector>
[51b7345]26
[2890212]27#include "AST/Copy.hpp"
[f474e91]28#include "AST/Decl.hpp"
[54e41b3]29#include "AST/Node.hpp"
[f474e91]30#include "AST/Pass.hpp"
[2890212]31#include "AST/Print.hpp"
[54e41b3]32#include "AST/Type.hpp"
[d76c588]33#include "AST/TypeEnvironment.hpp"
[f02f546]34#include "Common/Eval.h"            // for eval
[5bf3976]35#include "CommonType.hpp"           // for commonType
[d76c588]36#include "FindOpenVars.h"           // for findOpenVars
[5bf3976]37#include "SpecCost.hpp"             // for SpecCost
[d76c588]38#include "Tuples/Tuples.h"          // for isTtype
[5bf3976]39#include "typeops.h"                // for flatten, occurs
[ea6332d]40
[f474e91]41namespace ast {
42        class SymbolTable;
43}
44
[1cbca6e]45// #define DEBUG
[51b7345]46
47namespace ResolvExpr {
48
[7870799]49        bool typesCompatible(
[251ce80]50                        const ast::Type * first, const ast::Type * second,
[d76c588]51                        const ast::TypeEnvironment & env ) {
[f474e91]52                ast::TypeEnvironment newEnv;
53                ast::OpenVarSet open, closed;
54                ast::AssertionSet need, have;
55
56                ast::ptr<ast::Type> newFirst{ first }, newSecond{ second };
57                env.apply( newFirst );
58                env.apply( newSecond );
59
[46da46b]60                // findOpenVars( newFirst, open, closed, need, have, FirstClosed );
61                findOpenVars( newSecond, open, closed, need, have, newEnv, FirstOpen );
[f474e91]62
[251ce80]63                return unifyExact(newFirst, newSecond, newEnv, need, have, open, noWiden() );
[d76c588]64        }
65
[7870799]66        bool typesCompatibleIgnoreQualifiers(
[251ce80]67                        const ast::Type * first, const ast::Type * second,
[d76c588]68                        const ast::TypeEnvironment & env ) {
[f474e91]69                ast::TypeEnvironment newEnv;
70                ast::OpenVarSet open;
71                ast::AssertionSet need, have;
[7870799]72
[2890212]73                ast::Type * newFirst  = shallowCopy( first  );
74                ast::Type * newSecond = shallowCopy( second );
[b729c01]75                if ( auto temp = dynamic_cast<const ast::EnumInstType *>(first) ) {
76                        if ( !dynamic_cast< const ast::EnumInstType * >( second ) ) {
77                                const ast::EnumDecl * baseEnum = dynamic_cast<const ast::EnumDecl *>(temp->base.get());
78                                if ( auto t = baseEnum->base.get() ) {
79                                        newFirst = ast::shallowCopy( t );
80                                }
81                        }
82                } else if ( auto temp = dynamic_cast<const ast::EnumInstType *>(second) ) {
83                        const ast::EnumDecl * baseEnum = dynamic_cast<const ast::EnumDecl *>(temp->base.get());
84                        if ( auto t = baseEnum->base.get() ) {
85                                newSecond = ast::shallowCopy( t );
86                        }
87                }
88
[2890212]89                newFirst ->qualifiers = {};
90                newSecond->qualifiers = {};
[f49b3fc]91                ast::ptr< ast::Type > t1_(newFirst );
92                ast::ptr< ast::Type > t2_(newSecond);
[f474e91]93
[c7f834e]94                ast::ptr< ast::Type > subFirst = env.apply(newFirst).node;
95                ast::ptr< ast::Type > subSecond = env.apply(newSecond).node;
96
[7870799]97                return unifyExact(
[c7f834e]98                        subFirst,
99                        subSecond,
[251ce80]100                        newEnv, need, have, open, noWiden() );
[d76c588]101        }
102
[ef1da0e2]103        namespace {
104                                /// Replaces ttype variables with their bound types.
105                /// If this isn't done when satifying ttype assertions, then argument lists can have
106                /// different size and structure when they should be compatible.
[0bd3faf]107                struct TtypeExpander : public ast::WithShortCircuiting, public ast::PureVisitor {
[ef1da0e2]108                        ast::TypeEnvironment & tenv;
109
[0bd3faf]110                        TtypeExpander( ast::TypeEnvironment & env ) : tenv( env ) {}
[ef1da0e2]111
112                        const ast::Type * postvisit( const ast::TypeInstType * typeInst ) {
113                                if ( const ast::EqvClass * clz = tenv.lookup( *typeInst ) ) {
114                                        // expand ttype parameter into its actual type
115                                        if ( clz->data.kind == ast::TypeDecl::Ttype && clz->bound ) {
116                                                return clz->bound;
117                                        }
118                                }
119                                return typeInst;
120                        }
121                };
122        }
[0bd46fd]123
[ef1da0e2]124        std::vector< ast::ptr< ast::Type > > flattenList(
125                const std::vector< ast::ptr< ast::Type > > & src, ast::TypeEnvironment & env
126        ) {
127                std::vector< ast::ptr< ast::Type > > dst;
128                dst.reserve( src.size() );
129                for ( const auto & d : src ) {
[0bd3faf]130                        ast::Pass<TtypeExpander> expander{ env };
[ef1da0e2]131                        // TtypeExpander pass is impure (may mutate nodes in place)
132                        // need to make nodes shared to prevent accidental mutation
133                        ast::ptr<ast::Type> dc = d->accept(expander);
134                        auto types = flatten( dc );
135                        for ( ast::ptr< ast::Type > & t : types ) {
136                                // outermost const, volatile, _Atomic qualifiers in parameters should not play
137                                // a role in the unification of function types, since they do not determine
138                                // whether a function is callable.
139                                // NOTE: **must** consider at least mutex qualifier, since functions can be
140                                // overloaded on outermost mutex and a mutex function has different
141                                // requirements than a non-mutex function
142                                remove_qualifiers( t, ast::CV::Const | ast::CV::Volatile | ast::CV::Atomic );
143                                dst.emplace_back( t );
144                        }
145                }
146                return dst;
147        }
148
[f02f546]149        // Unification of Expressions
150        //
151        // Boolean outcome (obvious):  Are they basically spelled the same?
152        // Side effect of binding variables (subtle):  if `sizeof(int)` ===_expr `sizeof(T)` then `int` ===_ty `T`
153        //
154        // Context:  if `float[VAREXPR1]` ===_ty `float[VAREXPR2]` then `VAREXPR1` ===_expr `VAREXPR2`
155        // where the VAREXPR are meant as notational metavariables representing the fact that unification always
156        // sees distinct ast::VariableExpr objects at these positions
157
158        static bool unify( const ast::Expr * e1, const ast::Expr * e2, ast::TypeEnvironment & env,
159                ast::AssertionSet & need, ast::AssertionSet & have, const ast::OpenVarSet & open,
160                WidenMode widen );
161
162        class UnifyExpr final : public ast::WithShortCircuiting {
163                const ast::Expr * e2;
164                ast::TypeEnvironment & tenv;
165                ast::AssertionSet & need;
166                ast::AssertionSet & have;
167                const ast::OpenVarSet & open;
168                WidenMode widen;
169        public:
170                bool result;
171
172        private:
173
174                void tryMatchOnStaticValue( const ast::Expr * e1 ) {
175                        Evaluation r1 = eval(e1);
176                        Evaluation r2 = eval(e2);
177
178                        if ( ! r1.hasKnownValue ) return;
179                        if ( ! r2.hasKnownValue ) return;
180
181                        if (r1.knownValue != r2.knownValue) return;
182
183                        visit_children = false;
184                        result = true;
185                }
186
187        public:
188
189                void previsit( const ast::Node * ) { assert(false); }
190
191                void previsit( const ast::Expr * e1 ) {
192                        tryMatchOnStaticValue( e1 );
193                        visit_children = false;
194                }
195
196                void previsit( const ast::CastExpr * e1 ) {
197                        tryMatchOnStaticValue( e1 );
198
199                        if (result) {
200                                assert (visit_children == false);
201                        } else {
202                                assert (visit_children == true);
203                                visit_children = false;
204
205                                auto e2c = dynamic_cast< const ast::CastExpr * >( e2 );
206                                if ( ! e2c ) return;
207
208                                // inspect casts' target types
209                                if ( ! unifyExact(
210                                        e1->result, e2c->result, tenv, need, have, open, widen ) ) return;
211
212                                // inspect casts' inner expressions
213                                result = unify( e1->arg, e2c->arg, tenv, need, have, open, widen );
214                        }
215                }
216
217                void previsit( const ast::VariableExpr * e1 ) {
218                        tryMatchOnStaticValue( e1 );
219
220                        if (result) {
221                                assert (visit_children == false);
222                        } else {
223                                assert (visit_children == true);
224                                visit_children = false;
225
226                                auto e2v = dynamic_cast< const ast::VariableExpr * >( e2 );
227                                if ( ! e2v ) return;
228
229                                assert(e1->var);
230                                assert(e2v->var);
231
232                                // conservative: variable exprs match if their declarations are represented by the same C++ AST object
233                                result = (e1->var == e2v->var);
234                        }
235                }
236
237                void previsit( const ast::SizeofExpr * e1 ) {
238                        tryMatchOnStaticValue( e1 );
239
240                        if (result) {
241                                assert (visit_children == false);
242                        } else {
243                                assert (visit_children == true);
244                                visit_children = false;
245
246                                auto e2so = dynamic_cast< const ast::SizeofExpr * >( e2 );
247                                if ( ! e2so ) return;
248
249                                assert((e1->type != nullptr) ^ (e1->expr != nullptr));
250                                assert((e2so->type != nullptr) ^ (e2so->expr != nullptr));
251                                if ( ! (e1->type && e2so->type) )  return;
252
253                                // expression unification calls type unification (mutual recursion)
254                                result = unifyExact( e1->type, e2so->type, tenv, need, have, open, widen );
255                        }
256                }
257
258                UnifyExpr( const ast::Expr * e2, ast::TypeEnvironment & env, ast::AssertionSet & need,
259                        ast::AssertionSet & have, const ast::OpenVarSet & open, WidenMode widen )
260                : e2( e2 ), tenv(env), need(need), have(have), open(open), widen(widen), result(false) {}
261        };
262
263        static bool unify( const ast::Expr * e1, const ast::Expr * e2, ast::TypeEnvironment & env,
264                ast::AssertionSet & need, ast::AssertionSet & have, const ast::OpenVarSet & open,
265                WidenMode widen ) {
266                assert( e1 && e2 );
267                return ast::Pass<UnifyExpr>::read( e1, e2, env, need, have, open, widen );
268        }
269
[0bd3faf]270        class Unify final : public ast::WithShortCircuiting {
[f474e91]271                const ast::Type * type2;
272                ast::TypeEnvironment & tenv;
273                ast::AssertionSet & need;
274                ast::AssertionSet & have;
275                const ast::OpenVarSet & open;
276                WidenMode widen;
277        public:
[c15085d]278                static size_t traceId;
[f474e91]279                bool result;
280
[0bd3faf]281                Unify(
[7870799]282                        const ast::Type * type2, ast::TypeEnvironment & env, ast::AssertionSet & need,
[251ce80]283                        ast::AssertionSet & have, const ast::OpenVarSet & open, WidenMode widen )
[7870799]284                : type2(type2), tenv(env), need(need), have(have), open(open), widen(widen),
[251ce80]285                result(false) {}
[f474e91]286
287                void previsit( const ast::Node * ) { visit_children = false; }
[7870799]288
[ee574a2]289                void postvisit( const ast::VoidType * ) {
[f474e91]290                        result = dynamic_cast< const ast::VoidType * >( type2 );
291                }
292
[ee574a2]293                void postvisit( const ast::BasicType * basic ) {
[f474e91]294                        if ( auto basic2 = dynamic_cast< const ast::BasicType * >( type2 ) ) {
295                                result = basic->kind == basic2->kind;
296                        }
297                }
298
[ee574a2]299                void postvisit( const ast::PointerType * pointer ) {
[f474e91]300                        if ( auto pointer2 = dynamic_cast< const ast::PointerType * >( type2 ) ) {
[7870799]301                                result = unifyExact(
302                                        pointer->base, pointer2->base, tenv, need, have, open,
[251ce80]303                                        noWiden());
[f474e91]304                        }
305                }
306
[ee574a2]307                void postvisit( const ast::ArrayType * array ) {
[f474e91]308                        auto array2 = dynamic_cast< const ast::ArrayType * >( type2 );
309                        if ( ! array2 ) return;
310
311                        if ( array->isVarLen != array2->isVarLen ) return;
[f02f546]312                        if ( (array->dimension != nullptr) != (array2->dimension != nullptr) ) return;
[f474e91]313
[f02f546]314                        if ( array->dimension ) {
315                                assert( array2->dimension );
316                                // type unification calls expression unification (mutual recursion)
317                                if ( ! unify(array->dimension, array2->dimension,
318                                    tenv, need, have, open, widen) ) return;
[f474e91]319                        }
320
[7870799]321                        result = unifyExact(
[251ce80]322                                array->base, array2->base, tenv, need, have, open, noWiden());
[f474e91]323                }
324
[ee574a2]325                void postvisit( const ast::ReferenceType * ref ) {
[f474e91]326                        if ( auto ref2 = dynamic_cast< const ast::ReferenceType * >( type2 ) ) {
[7870799]327                                result = unifyExact(
[251ce80]328                                        ref->base, ref2->base, tenv, need, have, open, noWiden());
[f474e91]329                        }
330                }
331
332        private:
333
334                template< typename Iter >
[954c954]335                static bool unifyTypeList(
[7870799]336                        Iter crnt1, Iter end1, Iter crnt2, Iter end2, ast::TypeEnvironment & env,
[251ce80]337                        ast::AssertionSet & need, ast::AssertionSet & have, const ast::OpenVarSet & open
[f474e91]338                ) {
339                        while ( crnt1 != end1 && crnt2 != end2 ) {
[954c954]340                                const ast::Type * t1 = *crnt1;
341                                const ast::Type * t2 = *crnt2;
[f474e91]342                                bool isTuple1 = Tuples::isTtype( t1 );
343                                bool isTuple2 = Tuples::isTtype( t2 );
344
345                                // assumes here that ttype *must* be last parameter
346                                if ( isTuple1 && ! isTuple2 ) {
347                                        // combine remainder of list2, then unify
[7870799]348                                        return unifyExact(
[954c954]349                                                t1, tupleFromTypes( crnt2, end2 ), env, need, have, open,
[251ce80]350                                                noWiden() );
[f474e91]351                                } else if ( ! isTuple1 && isTuple2 ) {
352                                        // combine remainder of list1, then unify
[7870799]353                                        return unifyExact(
[954c954]354                                                tupleFromTypes( crnt1, end1 ), t2, env, need, have, open,
[251ce80]355                                                noWiden() );
[f474e91]356                                }
357
[7870799]358                                if ( ! unifyExact(
[251ce80]359                                        t1, t2, env, need, have, open, noWiden() )
[f474e91]360                                ) return false;
361
362                                ++crnt1; ++crnt2;
363                        }
364
[7870799]365                        // May get to the end of one argument list before the other. This is only okay if the
[f474e91]366                        // other is a ttype
367                        if ( crnt1 != end1 ) {
368                                // try unifying empty tuple with ttype
[954c954]369                                const ast::Type * t1 = *crnt1;
[f474e91]370                                if ( ! Tuples::isTtype( t1 ) ) return false;
[7870799]371                                return unifyExact(
[954c954]372                                        t1, tupleFromTypes( crnt2, end2 ), env, need, have, open,
[251ce80]373                                        noWiden() );
[f474e91]374                        } else if ( crnt2 != end2 ) {
375                                // try unifying empty tuple with ttype
[954c954]376                                const ast::Type * t2 = *crnt2;
[f474e91]377                                if ( ! Tuples::isTtype( t2 ) ) return false;
[7870799]378                                return unifyExact(
[954c954]379                                        tupleFromTypes( crnt1, end1 ), t2, env, need, have, open,
[251ce80]380                                        noWiden() );
[f474e91]381                        }
382
383                        return true;
384                }
385
[954c954]386                static bool unifyTypeList(
387                        const std::vector< ast::ptr< ast::Type > > & list1,
388                        const std::vector< ast::ptr< ast::Type > > & list2,
[7870799]389                        ast::TypeEnvironment & env, ast::AssertionSet & need, ast::AssertionSet & have,
[251ce80]390                        const ast::OpenVarSet & open
[f474e91]391                ) {
[954c954]392                        return unifyTypeList(
[251ce80]393                                list1.begin(), list1.end(), list2.begin(), list2.end(), env, need, have, open);
[f474e91]394                }
395
[3e5dd913]396                static void markAssertionSet( ast::AssertionSet & assns, const ast::VariableExpr * assn ) {
[f474e91]397                        auto i = assns.find( assn );
398                        if ( i != assns.end() ) {
399                                i->second.isUsed = true;
400                        }
401                }
402
403                /// mark all assertions in `type` used in both `assn1` and `assn2`
[7870799]404                static void markAssertions(
405                        ast::AssertionSet & assn1, ast::AssertionSet & assn2,
[361bf01]406                        const ast::FunctionType * type
[f474e91]407                ) {
[3e5dd913]408                        for ( auto & assert : type->assertions ) {
409                                markAssertionSet( assn1, assert );
410                                markAssertionSet( assn2, assert );
[f474e91]411                        }
412                }
413
414        public:
[ee574a2]415                void postvisit( const ast::FunctionType * func ) {
[f474e91]416                        auto func2 = dynamic_cast< const ast::FunctionType * >( type2 );
417                        if ( ! func2 ) return;
418
419                        if ( func->isVarArgs != func2->isVarArgs ) return;
[7870799]420
421                        // Flatten the parameter lists for both functions so that tuple structure does not
[f474e91]422                        // affect unification. Does not actually mutate function parameters.
423                        auto params = flattenList( func->params, tenv );
424                        auto params2 = flattenList( func2->params, tenv );
425
[7870799]426                        // sizes don't have to match if ttypes are involved; need to be more precise w.r.t.
[f474e91]427                        // where the ttype is to prevent errors
[7870799]428                        if (
[f474e91]429                                ( params.size() != params2.size() || func->returns.size() != func2->returns.size() )
430                                && ! func->isTtype()
431                                && ! func2->isTtype()
432                        ) return;
433
[251ce80]434                        if ( ! unifyTypeList( params, params2, tenv, need, have, open ) ) return;
[954c954]435                        if ( ! unifyTypeList(
[251ce80]436                                func->returns, func2->returns, tenv, need, have, open ) ) return;
[7870799]437
[f474e91]438                        markAssertions( have, need, func );
439                        markAssertions( have, need, func2 );
440
441                        result = true;
442                }
[7870799]443
[f474e91]444        private:
[90ce35aa]445                // Returns: other, cast as XInstType
446                // Assigns this->result: whether types are compatible (up to generic parameters)
447                template< typename XInstType >
448                const XInstType * handleRefType( const XInstType * inst, const ast::Type * other ) {
[f474e91]449                        // check that the other type is compatible and named the same
[90ce35aa]450                        auto otherInst = dynamic_cast< const XInstType * >( other );
[24d6572]451                        if (otherInst && inst->name == otherInst->name) 
452                                this->result = otherInst;
[f474e91]453                        return otherInst;
454                }
455
456                /// Creates a tuple type based on a list of TypeExpr
457                template< typename Iter >
[7870799]458                static const ast::Type * tupleFromExprs(
[f474e91]459                        const ast::TypeExpr * param, Iter & crnt, Iter end, ast::CV::Qualifiers qs
460                ) {
461                        std::vector< ast::ptr< ast::Type > > types;
462                        do {
463                                types.emplace_back( param->type );
464
465                                ++crnt;
466                                if ( crnt == end ) break;
467                                param = strict_dynamic_cast< const ast::TypeExpr * >( crnt->get() );
468                        } while(true);
469
470                        return new ast::TupleType{ std::move(types), qs };
471                }
472
[90ce35aa]473                template< typename XInstType >
474                void handleGenericRefType( const XInstType * inst, const ast::Type * other ) {
[f474e91]475                        // check that other type is compatible and named the same
[90ce35aa]476                        const XInstType * otherInst = handleRefType( inst, other );
477                        if ( ! this->result ) return;
[7870799]478
[f474e91]479                        // check that parameters of types unify, if any
480                        const std::vector< ast::ptr< ast::Expr > > & params = inst->params;
[90ce35aa]481                        const std::vector< ast::ptr< ast::Expr > > & params2 = otherInst->params;
[f474e91]482
483                        auto it = params.begin();
484                        auto jt = params2.begin();
485                        for ( ; it != params.end() && jt != params2.end(); ++it, ++jt ) {
486                                auto param = strict_dynamic_cast< const ast::TypeExpr * >( it->get() );
487                                auto param2 = strict_dynamic_cast< const ast::TypeExpr * >( jt->get() );
488
489                                ast::ptr< ast::Type > pty = param->type;
490                                ast::ptr< ast::Type > pty2 = param2->type;
491
492                                bool isTuple = Tuples::isTtype( pty );
493                                bool isTuple2 = Tuples::isTtype( pty2 );
494
495                                if ( isTuple && isTuple2 ) {
496                                        ++it; ++jt;  // skip ttype parameters before break
[0bd46fd]497                                } else if ( isTuple ) {
[f474e91]498                                        // bundle remaining params into tuple
499                                        pty2 = tupleFromExprs( param2, jt, params2.end(), pty->qualifiers );
500                                        ++it;  // skip ttype parameter for break
501                                } else if ( isTuple2 ) {
502                                        // bundle remaining params into tuple
503                                        pty = tupleFromExprs( param, it, params.end(), pty2->qualifiers );
504                                        ++jt;  // skip ttype parameter for break
505                                }
506
[7870799]507                                if ( ! unifyExact(
[251ce80]508                                                pty, pty2, tenv, need, have, open, noWiden() ) ) {
[f474e91]509                                        result = false;
510                                        return;
511                                }
512
513                                // ttype parameter should be last
514                                if ( isTuple || isTuple2 ) break;
515                        }
516                        result = it == params.end() && jt == params2.end();
517                }
518
519        public:
[ee574a2]520                void postvisit( const ast::StructInstType * aggrType ) {
[f474e91]521                        handleGenericRefType( aggrType, type2 );
522                }
523
[ee574a2]524                void postvisit( const ast::UnionInstType * aggrType ) {
[f474e91]525                        handleGenericRefType( aggrType, type2 );
526                }
527
[ee574a2]528                void postvisit( const ast::EnumInstType * aggrType ) {
[f474e91]529                        handleRefType( aggrType, type2 );
530                }
531
[ee574a2]532                void postvisit( const ast::TraitInstType * aggrType ) {
[f474e91]533                        handleRefType( aggrType, type2 );
534                }
535
[ee574a2]536                void postvisit( const ast::TypeInstType * typeInst ) {
[46da46b]537                        // assert( open.find( *typeInst ) == open.end() );
[24d6572]538                        auto otherInst = dynamic_cast< const ast::TypeInstType * >( type2 );
[2908f08]539                        if ( otherInst && typeInst->name == otherInst->name ) {
[24d6572]540                                this->result = otherInst;
[2908f08]541                        }
[f474e91]542                }
543
544        private:
545                /// Creates a tuple type based on a list of Type
[0bd46fd]546
[7870799]547                static bool unifyList(
548                        const std::vector< ast::ptr< ast::Type > > & list1,
549                        const std::vector< ast::ptr< ast::Type > > & list2, ast::TypeEnvironment & env,
[251ce80]550                        ast::AssertionSet & need, ast::AssertionSet & have, const ast::OpenVarSet & open
[f474e91]551                ) {
552                        auto crnt1 = list1.begin();
553                        auto crnt2 = list2.begin();
554                        while ( crnt1 != list1.end() && crnt2 != list2.end() ) {
555                                const ast::Type * t1 = *crnt1;
556                                const ast::Type * t2 = *crnt2;
557                                bool isTuple1 = Tuples::isTtype( t1 );
558                                bool isTuple2 = Tuples::isTtype( t2 );
559
560                                // assumes ttype must be last parameter
561                                if ( isTuple1 && ! isTuple2 ) {
562                                        // combine entirety of list2, then unify
[7870799]563                                        return unifyExact(
564                                                t1, tupleFromTypes( list2 ), env, need, have, open,
[251ce80]565                                                noWiden() );
[f474e91]566                                } else if ( ! isTuple1 && isTuple2 ) {
567                                        // combine entirety of list1, then unify
568                                        return unifyExact(
[7870799]569                                                tupleFromTypes( list1 ), t2, env, need, have, open,
[251ce80]570                                                noWiden() );
[f474e91]571                                }
572
[7870799]573                                if ( ! unifyExact(
[251ce80]574                                        t1, t2, env, need, have, open, noWiden() )
[f474e91]575                                ) return false;
576
577                                ++crnt1; ++crnt2;
578                        }
579
580                        if ( crnt1 != list1.end() ) {
581                                // try unifying empty tuple type with ttype
582                                const ast::Type * t1 = *crnt1;
583                                if ( ! Tuples::isTtype( t1 ) ) return false;
[7870799]584                                // xxx - this doesn't generate an empty tuple, contrary to comment; both ported
[f474e91]585                                // from Rob's code
[7870799]586                                return unifyExact(
587                                                t1, tupleFromTypes( list2 ), env, need, have, open,
[251ce80]588                                                noWiden() );
[f474e91]589                        } else if ( crnt2 != list2.end() ) {
590                                // try unifying empty tuple with ttype
591                                const ast::Type * t2 = *crnt2;
592                                if ( ! Tuples::isTtype( t2 ) ) return false;
[7870799]593                                // xxx - this doesn't generate an empty tuple, contrary to comment; both ported
[f474e91]594                                // from Rob's code
595                                return unifyExact(
[7870799]596                                                tupleFromTypes( list1 ), t2, env, need, have, open,
[251ce80]597                                                noWiden() );
[f474e91]598                        }
599
600                        return true;
601                }
602
603        public:
[ee574a2]604                void postvisit( const ast::TupleType * tuple ) {
[f474e91]605                        auto tuple2 = dynamic_cast< const ast::TupleType * >( type2 );
606                        if ( ! tuple2 ) return;
607
[0bd3faf]608                        ast::Pass<TtypeExpander> expander{ tenv };
[ef9988b]609
[d3aa64f1]610                        const ast::Type * flat = tuple->accept( expander );
611                        const ast::Type * flat2 = tuple2->accept( expander );
[f474e91]612
613                        auto types = flatten( flat );
614                        auto types2 = flatten( flat2 );
615
[251ce80]616                        result = unifyList( types, types2, tenv, need, have, open );
[f474e91]617                }
618
[ee574a2]619                void postvisit( const ast::VarArgsType * ) {
[f474e91]620                        result = dynamic_cast< const ast::VarArgsType * >( type2 );
621                }
622
[ee574a2]623                void postvisit( const ast::ZeroType * ) {
[f474e91]624                        result = dynamic_cast< const ast::ZeroType * >( type2 );
625                }
626
[ee574a2]627                void postvisit( const ast::OneType * ) {
[f474e91]628                        result = dynamic_cast< const ast::OneType * >( type2 );
[7870799]629                }
[f474e91]630        };
631
[0bd3faf]632        // size_t Unify::traceId = Stats::Heap::new_stacktrace_id("Unify");
633
[7870799]634        bool unify(
635                        const ast::ptr<ast::Type> & type1, const ast::ptr<ast::Type> & type2,
636                        ast::TypeEnvironment & env, ast::AssertionSet & need, ast::AssertionSet & have,
[251ce80]637                        ast::OpenVarSet & open
[2773ab8]638        ) {
639                ast::ptr<ast::Type> common;
[251ce80]640                return unify( type1, type2, env, need, have, open, common );
[2773ab8]641        }
642
[7870799]643        bool unify(
644                        const ast::ptr<ast::Type> & type1, const ast::ptr<ast::Type> & type2,
645                        ast::TypeEnvironment & env, ast::AssertionSet & need, ast::AssertionSet & have,
[251ce80]646                        ast::OpenVarSet & open, ast::ptr<ast::Type> & common
[ee574a2]647        ) {
648                ast::OpenVarSet closed;
[46da46b]649                // findOpenVars( type1, open, closed, need, have, FirstClosed );
650                findOpenVars( type2, open, closed, need, have, env, FirstOpen );
[7870799]651                return unifyInexact(
[251ce80]652                        type1, type2, env, need, have, open, WidenMode{ true, true }, common );
[ee574a2]653        }
654
[7870799]655        bool unifyExact(
656                        const ast::Type * type1, const ast::Type * type2, ast::TypeEnvironment & env,
657                        ast::AssertionSet & need, ast::AssertionSet & have, const ast::OpenVarSet & open,
[251ce80]658                        WidenMode widen
[f474e91]659        ) {
660                if ( type1->qualifiers != type2->qualifiers ) return false;
661
662                auto var1 = dynamic_cast< const ast::TypeInstType * >( type1 );
663                auto var2 = dynamic_cast< const ast::TypeInstType * >( type2 );
[46da46b]664                bool isopen1 = var1 && env.lookup(*var1);
665                bool isopen2 = var2 && env.lookup(*var2);
[f474e91]666
[46da46b]667                if ( isopen1 && isopen2 ) {
668                        if ( var1->base->kind != var2->base->kind ) return false;
669                        return env.bindVarToVar(
670                                var1, var2, ast::TypeData{ var1->base->kind, var1->base->sized||var2->base->sized }, need, have,
[24d6572]671                                open, widen );
[46da46b]672                } else if ( isopen1 ) {
[24d6572]673                        return env.bindVar( var1, type2, ast::TypeData{var1->base}, need, have, open, widen );
[46da46b]674                } else if ( isopen2 ) {
[24d6572]675                        return env.bindVar( var2, type1, ast::TypeData{var2->base}, need, have, open, widen );
[8f31be6]676                } else {
[0bd3faf]677                        return ast::Pass<Unify>::read(
[251ce80]678                                type1, type2, env, need, have, open, widen );
[f474e91]679                }
680        }
681
[7870799]682        bool unifyInexact(
683                        const ast::ptr<ast::Type> & type1, const ast::ptr<ast::Type> & type2,
684                        ast::TypeEnvironment & env, ast::AssertionSet & need, ast::AssertionSet & have,
[251ce80]685                        const ast::OpenVarSet & open, WidenMode widen,
[7870799]686                        ast::ptr<ast::Type> & common
[f474e91]687        ) {
688                ast::CV::Qualifiers q1 = type1->qualifiers, q2 = type2->qualifiers;
[7870799]689
690                // force t1 and t2 to be cloned if their qualifiers must be stripped, so that type1 and
[f474e91]691                // type2 are left unchanged; calling convention forces type{1,2}->strong_ref >= 1
[2890212]692                ast::Type * t1 = shallowCopy(type1.get());
693                ast::Type * t2 = shallowCopy(type2.get());
694                t1->qualifiers = {};
695                t2->qualifiers = {};
[f49b3fc]696                ast::ptr< ast::Type > t1_(t1);
697                ast::ptr< ast::Type > t2_(t2);
[7870799]698
[251ce80]699                if ( unifyExact( t1, t2, env, need, have, open, widen ) ) {
[f474e91]700                        // if exact unification on unqualified types, try to merge qualifiers
701                        if ( q1 == q2 || ( ( q1 > q2 || widen.first ) && ( q2 > q1 || widen.second ) ) ) {
[2890212]702                                t1->qualifiers = q1 | q2;
703                                common = t1;
[f474e91]704                                return true;
705                        } else {
706                                return false;
707                        }
708
[251ce80]709                } else if (( common = commonType( t1, t2, env, need, have, open, widen ))) {
[f474e91]710                        // no exact unification, but common type
[2890212]711                        auto c = shallowCopy(common.get());
712                        c->qualifiers = q1 | q2;
713                        common = c;
[f474e91]714                        return true;
715                } else {
716                        return false;
717                }
718        }
719
[54e41b3]720        ast::ptr<ast::Type> extractResultType( const ast::FunctionType * func ) {
[4139e3d]721                if ( func->returns.empty() ) return new ast::VoidType{};
[954c954]722                if ( func->returns.size() == 1 ) return func->returns[0];
[4139e3d]723
724                std::vector<ast::ptr<ast::Type>> tys;
[954c954]725                for ( const auto & decl : func->returns ) {
726                        tys.emplace_back( decl );
[4139e3d]727                }
728                return new ast::TupleType{ std::move(tys) };
[54e41b3]729        }
[51b7345]730} // namespace ResolvExpr
[a32b204]731
732// Local Variables: //
733// tab-width: 4 //
734// mode: c++ //
735// compile-command: "make install" //
736// End: //
Note: See TracBrowser for help on using the repository browser.