source: src/ResolvExpr/Unify.cc @ 0bd3faf

Last change on this file since 0bd3faf was 0bd3faf, checked in by Andrew Beach <ajbeach@…>, 7 months ago

Removed forward declarations missed in the BaseSyntaxNode? removal. Removed code and modified names to support two versions of the ast.

  • Property mode set to 100644
File size: 23.8 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// Unify.cc --
8//
9// Author           : Richard C. Bilson
10// Created On       : Sun May 17 12:27:10 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : 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/Eval.h"            // for eval
35#include "CommonType.hpp"           // for commonType
36#include "FindOpenVars.h"           // for findOpenVars
37#include "SpecCost.hpp"             // for SpecCost
38#include "Tuples/Tuples.h"          // for isTtype
39#include "typeops.h"                // for flatten, occurs
40
41namespace ast {
42        class SymbolTable;
43}
44
45// #define DEBUG
46
47namespace ResolvExpr {
48
49        bool typesCompatible(
50                        const ast::Type * first, const ast::Type * second,
51                        const ast::TypeEnvironment & env ) {
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
60                // findOpenVars( newFirst, open, closed, need, have, FirstClosed );
61                findOpenVars( newSecond, open, closed, need, have, newEnv, FirstOpen );
62
63                return unifyExact(newFirst, newSecond, newEnv, need, have, open, noWiden() );
64        }
65
66        bool typesCompatibleIgnoreQualifiers(
67                        const ast::Type * first, const ast::Type * second,
68                        const ast::TypeEnvironment & env ) {
69                ast::TypeEnvironment newEnv;
70                ast::OpenVarSet open;
71                ast::AssertionSet need, have;
72
73                ast::Type * newFirst  = shallowCopy( first  );
74                ast::Type * newSecond = shallowCopy( second );
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
89                newFirst ->qualifiers = {};
90                newSecond->qualifiers = {};
91                ast::ptr< ast::Type > t1_(newFirst );
92                ast::ptr< ast::Type > t2_(newSecond);
93
94                ast::ptr< ast::Type > subFirst = env.apply(newFirst).node;
95                ast::ptr< ast::Type > subSecond = env.apply(newSecond).node;
96
97                return unifyExact(
98                        subFirst,
99                        subSecond,
100                        newEnv, need, have, open, noWiden() );
101        }
102
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.
107                struct TtypeExpander : public ast::WithShortCircuiting, public ast::PureVisitor {
108                        ast::TypeEnvironment & tenv;
109
110                        TtypeExpander( ast::TypeEnvironment & env ) : tenv( env ) {}
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        }
123
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 ) {
130                        ast::Pass<TtypeExpander> expander{ env };
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
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
270        class Unify final : public ast::WithShortCircuiting {
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:
278                static size_t traceId;
279                bool result;
280
281                Unify(
282                        const ast::Type * type2, ast::TypeEnvironment & env, ast::AssertionSet & need,
283                        ast::AssertionSet & have, const ast::OpenVarSet & open, WidenMode widen )
284                : type2(type2), tenv(env), need(need), have(have), open(open), widen(widen),
285                result(false) {}
286
287                void previsit( const ast::Node * ) { visit_children = false; }
288
289                void postvisit( const ast::VoidType * ) {
290                        result = dynamic_cast< const ast::VoidType * >( type2 );
291                }
292
293                void postvisit( const ast::BasicType * basic ) {
294                        if ( auto basic2 = dynamic_cast< const ast::BasicType * >( type2 ) ) {
295                                result = basic->kind == basic2->kind;
296                        }
297                }
298
299                void postvisit( const ast::PointerType * pointer ) {
300                        if ( auto pointer2 = dynamic_cast< const ast::PointerType * >( type2 ) ) {
301                                result = unifyExact(
302                                        pointer->base, pointer2->base, tenv, need, have, open,
303                                        noWiden());
304                        }
305                }
306
307                void postvisit( const ast::ArrayType * array ) {
308                        auto array2 = dynamic_cast< const ast::ArrayType * >( type2 );
309                        if ( ! array2 ) return;
310
311                        if ( array->isVarLen != array2->isVarLen ) return;
312                        if ( (array->dimension != nullptr) != (array2->dimension != nullptr) ) return;
313
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;
319                        }
320
321                        result = unifyExact(
322                                array->base, array2->base, tenv, need, have, open, noWiden());
323                }
324
325                void postvisit( const ast::ReferenceType * ref ) {
326                        if ( auto ref2 = dynamic_cast< const ast::ReferenceType * >( type2 ) ) {
327                                result = unifyExact(
328                                        ref->base, ref2->base, tenv, need, have, open, noWiden());
329                        }
330                }
331
332        private:
333
334                template< typename Iter >
335                static bool unifyTypeList(
336                        Iter crnt1, Iter end1, Iter crnt2, Iter end2, ast::TypeEnvironment & env,
337                        ast::AssertionSet & need, ast::AssertionSet & have, const ast::OpenVarSet & open
338                ) {
339                        while ( crnt1 != end1 && crnt2 != end2 ) {
340                                const ast::Type * t1 = *crnt1;
341                                const ast::Type * t2 = *crnt2;
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
348                                        return unifyExact(
349                                                t1, tupleFromTypes( crnt2, end2 ), env, need, have, open,
350                                                noWiden() );
351                                } else if ( ! isTuple1 && isTuple2 ) {
352                                        // combine remainder of list1, then unify
353                                        return unifyExact(
354                                                tupleFromTypes( crnt1, end1 ), t2, env, need, have, open,
355                                                noWiden() );
356                                }
357
358                                if ( ! unifyExact(
359                                        t1, t2, env, need, have, open, noWiden() )
360                                ) return false;
361
362                                ++crnt1; ++crnt2;
363                        }
364
365                        // May get to the end of one argument list before the other. This is only okay if the
366                        // other is a ttype
367                        if ( crnt1 != end1 ) {
368                                // try unifying empty tuple with ttype
369                                const ast::Type * t1 = *crnt1;
370                                if ( ! Tuples::isTtype( t1 ) ) return false;
371                                return unifyExact(
372                                        t1, tupleFromTypes( crnt2, end2 ), env, need, have, open,
373                                        noWiden() );
374                        } else if ( crnt2 != end2 ) {
375                                // try unifying empty tuple with ttype
376                                const ast::Type * t2 = *crnt2;
377                                if ( ! Tuples::isTtype( t2 ) ) return false;
378                                return unifyExact(
379                                        tupleFromTypes( crnt1, end1 ), t2, env, need, have, open,
380                                        noWiden() );
381                        }
382
383                        return true;
384                }
385
386                static bool unifyTypeList(
387                        const std::vector< ast::ptr< ast::Type > > & list1,
388                        const std::vector< ast::ptr< ast::Type > > & list2,
389                        ast::TypeEnvironment & env, ast::AssertionSet & need, ast::AssertionSet & have,
390                        const ast::OpenVarSet & open
391                ) {
392                        return unifyTypeList(
393                                list1.begin(), list1.end(), list2.begin(), list2.end(), env, need, have, open);
394                }
395
396                static void markAssertionSet( ast::AssertionSet & assns, const ast::VariableExpr * assn ) {
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`
404                static void markAssertions(
405                        ast::AssertionSet & assn1, ast::AssertionSet & assn2,
406                        const ast::FunctionType * type
407                ) {
408                        for ( auto & assert : type->assertions ) {
409                                markAssertionSet( assn1, assert );
410                                markAssertionSet( assn2, assert );
411                        }
412                }
413
414        public:
415                void postvisit( const ast::FunctionType * func ) {
416                        auto func2 = dynamic_cast< const ast::FunctionType * >( type2 );
417                        if ( ! func2 ) return;
418
419                        if ( func->isVarArgs != func2->isVarArgs ) return;
420
421                        // Flatten the parameter lists for both functions so that tuple structure does not
422                        // affect unification. Does not actually mutate function parameters.
423                        auto params = flattenList( func->params, tenv );
424                        auto params2 = flattenList( func2->params, tenv );
425
426                        // sizes don't have to match if ttypes are involved; need to be more precise w.r.t.
427                        // where the ttype is to prevent errors
428                        if (
429                                ( params.size() != params2.size() || func->returns.size() != func2->returns.size() )
430                                && ! func->isTtype()
431                                && ! func2->isTtype()
432                        ) return;
433
434                        if ( ! unifyTypeList( params, params2, tenv, need, have, open ) ) return;
435                        if ( ! unifyTypeList(
436                                func->returns, func2->returns, tenv, need, have, open ) ) return;
437
438                        markAssertions( have, need, func );
439                        markAssertions( have, need, func2 );
440
441                        result = true;
442                }
443
444        private:
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 ) {
449                        // check that the other type is compatible and named the same
450                        auto otherInst = dynamic_cast< const XInstType * >( other );
451                        if (otherInst && inst->name == otherInst->name) 
452                                this->result = otherInst;
453                        return otherInst;
454                }
455
456                /// Creates a tuple type based on a list of TypeExpr
457                template< typename Iter >
458                static const ast::Type * tupleFromExprs(
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
473                template< typename XInstType >
474                void handleGenericRefType( const XInstType * inst, const ast::Type * other ) {
475                        // check that other type is compatible and named the same
476                        const XInstType * otherInst = handleRefType( inst, other );
477                        if ( ! this->result ) return;
478
479                        // check that parameters of types unify, if any
480                        const std::vector< ast::ptr< ast::Expr > > & params = inst->params;
481                        const std::vector< ast::ptr< ast::Expr > > & params2 = otherInst->params;
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
497                                } else if ( isTuple ) {
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
507                                if ( ! unifyExact(
508                                                pty, pty2, tenv, need, have, open, noWiden() ) ) {
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:
520                void postvisit( const ast::StructInstType * aggrType ) {
521                        handleGenericRefType( aggrType, type2 );
522                }
523
524                void postvisit( const ast::UnionInstType * aggrType ) {
525                        handleGenericRefType( aggrType, type2 );
526                }
527
528                void postvisit( const ast::EnumInstType * aggrType ) {
529                        handleRefType( aggrType, type2 );
530                }
531
532                void postvisit( const ast::TraitInstType * aggrType ) {
533                        handleRefType( aggrType, type2 );
534                }
535
536                void postvisit( const ast::TypeInstType * typeInst ) {
537                        // assert( open.find( *typeInst ) == open.end() );
538                        auto otherInst = dynamic_cast< const ast::TypeInstType * >( type2 );
539                        if (otherInst && typeInst->name == otherInst->name) 
540                                this->result = otherInst;
541                        // return otherInst;
542                }
543
544        private:
545                /// Creates a tuple type based on a list of Type
546
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,
550                        ast::AssertionSet & need, ast::AssertionSet & have, const ast::OpenVarSet & open
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
563                                        return unifyExact(
564                                                t1, tupleFromTypes( list2 ), env, need, have, open,
565                                                noWiden() );
566                                } else if ( ! isTuple1 && isTuple2 ) {
567                                        // combine entirety of list1, then unify
568                                        return unifyExact(
569                                                tupleFromTypes( list1 ), t2, env, need, have, open,
570                                                noWiden() );
571                                }
572
573                                if ( ! unifyExact(
574                                        t1, t2, env, need, have, open, noWiden() )
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;
584                                // xxx - this doesn't generate an empty tuple, contrary to comment; both ported
585                                // from Rob's code
586                                return unifyExact(
587                                                t1, tupleFromTypes( list2 ), env, need, have, open,
588                                                noWiden() );
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;
593                                // xxx - this doesn't generate an empty tuple, contrary to comment; both ported
594                                // from Rob's code
595                                return unifyExact(
596                                                tupleFromTypes( list1 ), t2, env, need, have, open,
597                                                noWiden() );
598                        }
599
600                        return true;
601                }
602
603        public:
604                void postvisit( const ast::TupleType * tuple ) {
605                        auto tuple2 = dynamic_cast< const ast::TupleType * >( type2 );
606                        if ( ! tuple2 ) return;
607
608                        ast::Pass<TtypeExpander> expander{ tenv };
609
610                        const ast::Type * flat = tuple->accept( expander );
611                        const ast::Type * flat2 = tuple2->accept( expander );
612
613                        auto types = flatten( flat );
614                        auto types2 = flatten( flat2 );
615
616                        result = unifyList( types, types2, tenv, need, have, open );
617                }
618
619                void postvisit( const ast::VarArgsType * ) {
620                        result = dynamic_cast< const ast::VarArgsType * >( type2 );
621                }
622
623                void postvisit( const ast::ZeroType * ) {
624                        result = dynamic_cast< const ast::ZeroType * >( type2 );
625                }
626
627                void postvisit( const ast::OneType * ) {
628                        result = dynamic_cast< const ast::OneType * >( type2 );
629                }
630
631          private:
632                template< typename RefType > void handleRefType( RefType *inst, Type *other );
633                template< typename RefType > void handleGenericRefType( RefType *inst, Type *other );
634        };
635
636        // size_t Unify::traceId = Stats::Heap::new_stacktrace_id("Unify");
637
638        bool unify(
639                        const ast::ptr<ast::Type> & type1, const ast::ptr<ast::Type> & type2,
640                        ast::TypeEnvironment & env, ast::AssertionSet & need, ast::AssertionSet & have,
641                        ast::OpenVarSet & open
642        ) {
643                ast::ptr<ast::Type> common;
644                return unify( type1, type2, env, need, have, open, common );
645        }
646
647        bool unify(
648                        const ast::ptr<ast::Type> & type1, const ast::ptr<ast::Type> & type2,
649                        ast::TypeEnvironment & env, ast::AssertionSet & need, ast::AssertionSet & have,
650                        ast::OpenVarSet & open, ast::ptr<ast::Type> & common
651        ) {
652                ast::OpenVarSet closed;
653                // findOpenVars( type1, open, closed, need, have, FirstClosed );
654                findOpenVars( type2, open, closed, need, have, env, FirstOpen );
655                return unifyInexact(
656                        type1, type2, env, need, have, open, WidenMode{ true, true }, common );
657        }
658
659        bool unifyExact(
660                        const ast::Type * type1, const ast::Type * type2, ast::TypeEnvironment & env,
661                        ast::AssertionSet & need, ast::AssertionSet & have, const ast::OpenVarSet & open,
662                        WidenMode widen
663        ) {
664                if ( type1->qualifiers != type2->qualifiers ) return false;
665
666                auto var1 = dynamic_cast< const ast::TypeInstType * >( type1 );
667                auto var2 = dynamic_cast< const ast::TypeInstType * >( type2 );
668                bool isopen1 = var1 && env.lookup(*var1);
669                bool isopen2 = var2 && env.lookup(*var2);
670
671                if ( isopen1 && isopen2 ) {
672                        if ( var1->base->kind != var2->base->kind ) return false;
673                        return env.bindVarToVar(
674                                var1, var2, ast::TypeData{ var1->base->kind, var1->base->sized||var2->base->sized }, need, have,
675                                open, widen );
676                } else if ( isopen1 ) {
677                        return env.bindVar( var1, type2, ast::TypeData{var1->base}, need, have, open, widen );
678                } else if ( isopen2 ) {
679                        return env.bindVar( var2, type1, ast::TypeData{var2->base}, need, have, open, widen );
680                } else {
681                        return ast::Pass<Unify>::read(
682                                type1, type2, env, need, have, open, widen );
683                }
684        }
685
686        bool unifyInexact(
687                        const ast::ptr<ast::Type> & type1, const ast::ptr<ast::Type> & type2,
688                        ast::TypeEnvironment & env, ast::AssertionSet & need, ast::AssertionSet & have,
689                        const ast::OpenVarSet & open, WidenMode widen,
690                        ast::ptr<ast::Type> & common
691        ) {
692                ast::CV::Qualifiers q1 = type1->qualifiers, q2 = type2->qualifiers;
693
694                // force t1 and t2 to be cloned if their qualifiers must be stripped, so that type1 and
695                // type2 are left unchanged; calling convention forces type{1,2}->strong_ref >= 1
696                ast::Type * t1 = shallowCopy(type1.get());
697                ast::Type * t2 = shallowCopy(type2.get());
698                t1->qualifiers = {};
699                t2->qualifiers = {};
700                ast::ptr< ast::Type > t1_(t1);
701                ast::ptr< ast::Type > t2_(t2);
702
703                if ( unifyExact( t1, t2, env, need, have, open, widen ) ) {
704                        // if exact unification on unqualified types, try to merge qualifiers
705                        if ( q1 == q2 || ( ( q1 > q2 || widen.first ) && ( q2 > q1 || widen.second ) ) ) {
706                                t1->qualifiers = q1 | q2;
707                                common = t1;
708                                return true;
709                        } else {
710                                return false;
711                        }
712
713                } else if (( common = commonType( t1, t2, env, need, have, open, widen ))) {
714                        // no exact unification, but common type
715                        auto c = shallowCopy(common.get());
716                        c->qualifiers = q1 | q2;
717                        common = c;
718                        return true;
719                } else {
720                        return false;
721                }
722        }
723
724        ast::ptr<ast::Type> extractResultType( const ast::FunctionType * func ) {
725                if ( func->returns.empty() ) return new ast::VoidType{};
726                if ( func->returns.size() == 1 ) return func->returns[0];
727
728                std::vector<ast::ptr<ast::Type>> tys;
729                for ( const auto & decl : func->returns ) {
730                        tys.emplace_back( decl );
731                }
732                return new ast::TupleType{ std::move(tys) };
733        }
734} // namespace ResolvExpr
735
736// Local Variables: //
737// tab-width: 4 //
738// mode: c++ //
739// compile-command: "make install" //
740// End: //
Note: See TracBrowser for help on using the repository browser.