source: src/ResolvExpr/TypeEnvironment.cc @ 0d070ca

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

Added flag to disable non-deteministic parts of the output when testing

  • Property mode set to 100644
File size: 16.4 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// TypeEnvironment.cc --
8//
9// Author           : Richard C. Bilson
10// Created On       : Sun May 17 12:19:47 2015
11// Last Modified By : Andrew Beach
12// Last Modified On : Fri Jun 18 14:27:00 2019
13// Update Count     : 5
14//
15
16#include <cassert>                     // for assert
17#include <algorithm>                   // for copy, set_intersection
18#include <iterator>                    // for ostream_iterator, insert_iterator
19#include <memory>                      // for unique_ptr
20#include <utility>                     // for pair, move
21
22#include "CompilationState.h"          // for deterministic_output
23#include "Common/utility.h"            // for maybeClone
24#include "SynTree/Type.h"              // for Type, FunctionType, Type::Fora...
25#include "SynTree/TypeSubstitution.h"  // for TypeSubstitution
26#include "Tuples/Tuples.h"             // for isTtype
27#include "TypeEnvironment.h"
28#include "typeops.h"                   // for occurs
29#include "Unify.h"                     // for unifyInexact
30
31namespace ResolvExpr {
32        void printAssertionSet( const AssertionSet &assertions, std::ostream &os, int indent ) {
33                for ( AssertionSet::const_iterator i = assertions.begin(); i != assertions.end(); ++i ) {
34                        i->first->print( os, indent );
35                        if ( i->second.isUsed ) {
36                                os << "(used)";
37                        } else {
38                                os << "(not used)";
39                        } // if
40                } // for
41        }
42
43        void printOpenVarSet( const OpenVarSet &openVars, std::ostream &os, int indent ) {
44                os << std::string( indent, ' ' );
45                for ( OpenVarSet::const_iterator i = openVars.begin(); i != openVars.end(); ++i ) {
46                        os << i->first << "(" << i->second << ") ";
47                } // for
48        }
49
50        void EqvClass::initialize( const EqvClass &src, EqvClass &dest ) {
51                initialize( src, dest, src.type );
52        }
53
54        void EqvClass::initialize( const EqvClass &src, EqvClass &dest, const Type *ty ) {
55                dest.vars = src.vars;
56                dest.type = maybeClone( ty );
57                dest.allowWidening = src.allowWidening;
58                dest.data = src.data;
59        }
60
61        EqvClass::EqvClass() : type( nullptr ), allowWidening( true ) {
62        }
63
64        EqvClass::EqvClass( const EqvClass &other ) {
65                initialize( other, *this );
66        }
67
68        EqvClass::EqvClass( const EqvClass &other, const Type *ty ) {
69                initialize( other, *this, ty );
70        }
71
72        EqvClass::EqvClass( EqvClass &&other )
73        : vars{std::move(other.vars)}, type{other.type},
74          allowWidening{std::move(other.allowWidening)}, data{std::move(other.data)} {
75                  other.type = nullptr;
76        }
77
78        EqvClass &EqvClass::operator=( const EqvClass &other ) {
79                if ( this == &other ) return *this;
80                delete type;
81                initialize( other, *this );
82                return *this;
83        }
84
85        EqvClass &EqvClass::operator=( EqvClass &&other ) {
86                if ( this == &other ) return *this;
87                delete type;
88
89                vars = std::move(other.vars);
90                type = other.type;
91                other.type = nullptr;
92                allowWidening = std::move(other.allowWidening);
93                data = std::move(other.data);
94
95                return *this;
96        }
97
98        EqvClass::~EqvClass() {
99                delete type;
100        }
101
102        void EqvClass::set_type( Type* ty ) {
103                if ( ty == type ) return;
104                delete type;
105                type = ty;
106        }
107
108        void EqvClass::print( std::ostream &os, Indenter indent ) const {
109                if( !deterministic_output ) {
110                        os << "( ";
111                        std::copy( vars.begin(), vars.end(), std::ostream_iterator< std::string >( os, " " ) );
112                        os << ")";
113                }
114                if ( type ) {
115                        os << " -> ";
116                        type->print( os, indent+1 );
117                } // if
118                if ( ! allowWidening ) {
119                        os << " (no widening)";
120                } // if
121                os << std::endl;
122        }
123
124        const EqvClass* TypeEnvironment::lookup( const std::string &var ) const {
125                for ( ClassList::const_iterator i = env.begin(); i != env.end(); ++i ) {
126                        if ( i->vars.find( var ) != i->vars.end() ) return &*i;
127                } // for
128                return nullptr;
129        }
130
131        /// Removes any class from env that intersects eqvClass
132        void filterOverlappingClasses( std::list<EqvClass> &env, const EqvClass &eqvClass ) {
133                for ( auto i = env.begin(); i != env.end(); ) {
134                        auto next = i;
135                        ++next;
136                        std::set<std::string> intersection;
137                        std::set_intersection( i->vars.begin(), i->vars.end(), eqvClass.vars.begin(), eqvClass.vars.end(),
138                                std::inserter( intersection, intersection.begin() ) );
139                        if ( ! intersection.empty() ) { env.erase( i ); }
140                        i = next;
141                }
142        }
143
144        void TypeEnvironment::add( EqvClass &&eqvClass ) {
145                filterOverlappingClasses( env, eqvClass );
146                env.push_back( std::move(eqvClass) );
147        }
148
149        void TypeEnvironment::add( const Type::ForallList &tyDecls ) {
150                for ( Type::ForallList::const_iterator i = tyDecls.begin(); i != tyDecls.end(); ++i ) {
151                        EqvClass newClass;
152                        newClass.vars.insert( (*i)->get_name() );
153                        newClass.data = TypeDecl::Data{ (*i) };
154                        env.push_back( std::move(newClass) );
155                } // for
156        }
157
158        void TypeEnvironment::add( const TypeSubstitution & sub ) {
159                EqvClass newClass;
160                for ( auto p : sub ) {
161                        newClass.vars.insert( p.first );
162                        newClass.type = p.second->clone();
163                        newClass.allowWidening = false;
164                        // Minimal assumptions. Not technically correct, but might be good enough, and
165                        // is the best we can do at the moment since information is lost in the
166                        // transition to TypeSubstitution
167                        newClass.data = TypeDecl::Data{ TypeDecl::Dtype, false };
168                        add( std::move(newClass) );
169                }
170        }
171
172        void TypeEnvironment::makeSubstitution( TypeSubstitution &sub ) const {
173                for ( ClassList::const_iterator theClass = env.begin(); theClass != env.end(); ++theClass ) {
174                        for ( std::set< std::string >::const_iterator theVar = theClass->vars.begin(); theVar != theClass->vars.end(); ++theVar ) {
175                                if ( theClass->type ) {
176                                        sub.add( *theVar, theClass->type );
177                                } else if ( theVar != theClass->vars.begin() ) {
178                                        TypeInstType *newTypeInst = new TypeInstType( Type::Qualifiers(), *theClass->vars.begin(), theClass->data.kind == TypeDecl::Ftype );
179                                        sub.add( *theVar, newTypeInst );
180                                        delete newTypeInst;
181                                } // if
182                        } // for
183                } // for
184                sub.normalize();
185        }
186
187        void TypeEnvironment::print( std::ostream &os, Indenter indent ) const {
188                for ( const EqvClass & theClass : env ) {
189                        theClass.print( os, indent );
190                } // for
191        }
192
193        TypeEnvironment::ClassList::iterator TypeEnvironment::internal_lookup( const std::string &var ) {
194                for ( ClassList::iterator i = env.begin(); i != env.end(); ++i ) {
195                        if ( i->vars.count( var ) ) return i;
196                } // for
197                return env.end();
198        }
199
200        void TypeEnvironment::simpleCombine( const TypeEnvironment &second ) {
201                env.insert( env.end(), second.env.begin(), second.env.end() );
202        }
203
204        // xxx -- this should maybe be worrying about iterator invalidation (see resolv-proto)
205        bool TypeEnvironment::mergeBound( EqvClass& to, const EqvClass& from, OpenVarSet& openVars, const SymTab::Indexer& indexer ) {
206                if ( from.type ) {
207                        if ( to.type ) {
208                                // attempt to unify bound types
209                                std::unique_ptr<Type> toType{ to.type->clone() }, fromType{ from.type->clone() };
210                                WidenMode widen{ to.allowWidening, from.allowWidening };
211                                Type* common = nullptr;
212                                AssertionSet need, have;
213                                if ( unifyInexact( toType.get(), fromType.get(), *this, need, have, openVars, widen, indexer, common ) ) {
214                                        // unifies, set common type if necessary
215                                        if ( common ) {
216                                                common->get_qualifiers() = Type::Qualifiers{};
217                                                to.set_type( common );
218                                        }
219                                } else return false; // cannot unify
220                        } else {
221                                to.type = from.type->clone();
222                        }
223                }
224
225                // unify widening if matches
226                to.allowWidening &= from.allowWidening;
227                return true;
228        }
229
230        // xxx -- this should maybe be worrying about iterator invalidation (see resolv-proto)
231        bool TypeEnvironment::mergeClasses( TypeEnvironment::ClassList::iterator to, TypeEnvironment::ClassList::iterator from, OpenVarSet& openVars, const SymTab::Indexer& indexer ) {
232                EqvClass& r = *to;
233                EqvClass& s = *from;
234
235                // ensure bounds match
236                if ( ! mergeBound( r, s, openVars, indexer ) ) return false;
237
238                // check safely bindable
239                if ( r.type && occursIn( r.type, s.vars.begin(), s.vars.end(), *this ) ) return false;
240
241                // merge classes in
242                r.vars.insert( s.vars.begin(), s.vars.end() );
243                r.allowWidening &= s.allowWidening;
244                env.erase( from );
245
246                return true;
247        }
248
249        bool TypeEnvironment::combine( const TypeEnvironment& o, OpenVarSet& openVars, const SymTab::Indexer& indexer ) {
250                // short-circuit easy cases
251                if ( o.isEmpty() ) return true;
252                if ( isEmpty() ) {
253                        simpleCombine( o );
254                        return true;
255                }
256
257                // merge classes
258                for ( auto ct = o.env.begin(); ct != o.env.end(); ++ct ) {
259                        const EqvClass& c = *ct;
260
261                        // typeclass in local environment bound to c
262                        auto rt = env.end();
263
264                        // look for first existing bound variable
265                        auto vt = c.vars.begin();
266                        for ( ; vt != c.vars.end(); ++vt ) {
267                                rt = internal_lookup( *vt );
268                                if ( rt != env.end() ) break;
269                        }
270
271                        if ( rt != env.end() ) {  // c needs to be merged into *rt
272                                EqvClass& r = *rt;
273                                // merge bindings
274                                if ( ! mergeBound( r, c, openVars, indexer ) ) return false;
275                                // merge previous unbound variables into this class, checking occurs if needed
276                                if ( r.type ) for ( auto ut = c.vars.begin(); ut != vt; ++ut ) {
277                                        if ( occurs( r.type, *ut, *this ) ) return false;
278                                        r.vars.insert( *ut );
279                                } else { r.vars.insert( c.vars.begin(), vt ); }
280                                // merge subsequent variables into this class (skipping *vt, already there)
281                                while ( ++vt != c.vars.end() ) {
282                                        auto st = internal_lookup( *vt );
283                                        if ( st == env.end() ) {
284                                                // unbound, safe to add if passes occurs
285                                                if ( r.type && occurs( r.type, *vt, *this ) ) return false;
286                                                r.vars.insert( *vt );
287                                        } else if ( st != rt ) {
288                                                // bound, but not to the same class
289                                                if ( ! mergeClasses( rt, st, openVars, indexer ) ) return false;
290                                        }   // ignore bound into the same class
291                                }
292                        } else {  // no variables in c bound; just copy up
293                                env.push_back( c );
294                        }
295                }
296
297                // merged all classes
298                return true;
299        }
300
301        void TypeEnvironment::extractOpenVars( OpenVarSet &openVars ) const {
302                for ( ClassList::const_iterator eqvClass = env.begin(); eqvClass != env.end(); ++eqvClass ) {
303                        for ( std::set< std::string >::const_iterator var = eqvClass->vars.begin(); var != eqvClass->vars.end(); ++var ) {
304                                openVars[ *var ] = eqvClass->data;
305                        } // for
306                } // for
307        }
308
309        void TypeEnvironment::addActual( const TypeEnvironment& actualEnv, OpenVarSet& openVars ) {
310                for ( const EqvClass& c : actualEnv ) {
311                        EqvClass c2 = c;
312                        c2.allowWidening = false;
313                        for ( const std::string& var : c2.vars ) {
314                                openVars[ var ] = c2.data;
315                        }
316                        env.push_back( std::move(c2) );
317                }
318        }
319
320        bool isFtype( const Type * type ) {
321                if ( dynamic_cast< const FunctionType * >( type ) ) {
322                        return true;
323                } else if ( const TypeInstType *typeInst = dynamic_cast< const TypeInstType * >( type ) ) {
324                        return typeInst->get_isFtype();
325                } // if
326                return false;
327        }
328
329        bool tyVarCompatible( const TypeDecl::Data & data, const Type * type ) {
330                switch ( data.kind ) {
331                  case TypeDecl::Dtype:
332                        // to bind to an object type variable, the type must not be a function type.
333                        // if the type variable is specified to be a complete type then the incoming
334                        // type must also be complete
335                        // xxx - should this also check that type is not a tuple type and that it's not a ttype?
336                        return ! isFtype( type ) && (! data.isComplete || type->isComplete() );
337                  case TypeDecl::Ftype:
338                        return isFtype( type );
339                  case TypeDecl::Ttype:
340                        // ttype unifies with any tuple type
341                        return dynamic_cast< const TupleType * >( type ) || Tuples::isTtype( type );
342                  default:
343                        assertf(false, "Unhandled tyvar kind: %d", data.kind);
344                } // switch
345                return false;
346        }
347
348        bool TypeEnvironment::bindVar( const TypeInstType *typeInst, Type *bindTo, const TypeDecl::Data & data, AssertionSet &need, AssertionSet &have, const OpenVarSet &openVars, WidenMode widen, const SymTab::Indexer &indexer ) {
349
350                // remove references from other, so that type variables can only bind to value types
351                bindTo = bindTo->stripReferences();
352                OpenVarSet::const_iterator tyvar = openVars.find( typeInst->get_name() );
353                assert( tyvar != openVars.end() );
354                if ( ! tyVarCompatible( tyvar->second, bindTo ) ) {
355                        return false;
356                } // if
357                if ( occurs( bindTo, typeInst->get_name(), *this ) ) {
358                        return false;
359                } // if
360                auto curClass = internal_lookup( typeInst->get_name() );
361                if ( curClass != env.end() ) {
362                        if ( curClass->type ) {
363                                Type *common = 0;
364                                // attempt to unify equivalence class type (which has qualifiers stripped, so they must be restored) with the type to bind to
365                                std::unique_ptr< Type > newType( curClass->type->clone() );
366                                newType->tq = typeInst->tq;
367                                if ( unifyInexact( newType.get(), bindTo, *this, need, have, openVars, widen & WidenMode( curClass->allowWidening, true ), indexer, common ) ) {
368                                        if ( common ) {
369                                                common->get_qualifiers() = Type::Qualifiers{};
370                                                curClass->set_type( common );
371                                        } // if
372                                } else return false;
373                        } else {
374                                Type* newType = bindTo->clone();
375                                newType->get_qualifiers() = Type::Qualifiers{};
376                                curClass->set_type( newType );
377                                curClass->allowWidening = widen.first && widen.second;
378                        } // if
379                } else {
380                        EqvClass newClass;
381                        newClass.vars.insert( typeInst->get_name() );
382                        newClass.type = bindTo->clone();
383                        newClass.type->get_qualifiers() = Type::Qualifiers();
384                        newClass.allowWidening = widen.first && widen.second;
385                        newClass.data = data;
386                        env.push_back( std::move(newClass) );
387                } // if
388                return true;
389        }
390
391        bool TypeEnvironment::bindVarToVar( const TypeInstType * var1, const TypeInstType * var2,
392                        TypeDecl::Data && data, AssertionSet &need, AssertionSet &have,
393                        const OpenVarSet &openVars, WidenMode widen, const SymTab::Indexer &indexer ) {
394
395                auto class1 = internal_lookup( var1->get_name() );
396                auto class2 = internal_lookup( var2->get_name() );
397
398                // exit early if variables already bound together
399                if ( class1 != env.end() && class1 == class2 ) {
400                        class1->allowWidening &= widen;
401                        return true;
402                }
403
404                bool widen1 = false, widen2 = false;
405                const Type *type1 = nullptr, *type2 = nullptr;
406
407                // check for existing bindings, perform occurs check
408                if ( class1 != env.end() ) {
409                        if ( class1->type ) {
410                                if ( occurs( class1->type, var2->get_name(), *this ) ) return false;
411                                type1 = class1->type;
412                        } // if
413                        widen1 = widen.first && class1->allowWidening;
414                } // if
415                if ( class2 != env.end() ) {
416                        if ( class2->type ) {
417                                if ( occurs( class2->type, var1->get_name(), *this ) ) return false;
418                                type2 = class2->type;
419                        } // if
420                        widen2 = widen.second && class2->allowWidening;
421                } // if
422
423                if ( type1 && type2 ) {
424                        // both classes bound, merge if bound types can be unified
425                        std::unique_ptr<Type> newType1{ type1->clone() }, newType2{ type2->clone() };
426                        WidenMode newWidenMode{ widen1, widen2 };
427                        Type *common = 0;
428                        if ( unifyInexact( newType1.get(), newType2.get(), *this, need, have, openVars, newWidenMode, indexer, common ) ) {
429                                class1->vars.insert( class2->vars.begin(), class2->vars.end() );
430                                class1->allowWidening = widen1 && widen2;
431                                if ( common ) {
432                                        common->get_qualifiers() = Type::Qualifiers{};
433                                        class1->set_type( common );
434                                }
435                                class1->data.isComplete |= data.isComplete;
436                                env.erase( class2 );
437                        } else return false;
438                } else if ( class1 != env.end() && class2 != env.end() ) {
439                        // both classes exist, at least one unbound, merge unconditionally
440                        if ( type1 ) {
441                                class1->vars.insert( class2->vars.begin(), class2->vars.end() );
442                                class1->allowWidening = widen1;
443                                class1->data.isComplete |= data.isComplete;
444                                env.erase( class2 );
445                        } else {
446                                class2->vars.insert( class1->vars.begin(), class1->vars.end() );
447                                class2->allowWidening = widen2;
448                                class2->data.isComplete |= data.isComplete;
449                                env.erase( class1 );
450                        } // if
451                } else if ( class1 != env.end() ) {
452                        // var2 unbound, add to class1
453                        class1->vars.insert( var2->get_name() );
454                        class1->allowWidening = widen1;
455                        class1->data.isComplete |= data.isComplete;
456                } else if ( class2 != env.end() ) {
457                        // var1 unbound, add to class2
458                        class2->vars.insert( var1->get_name() );
459                        class2->allowWidening = widen2;
460                        class2->data.isComplete |= data.isComplete;
461                } else {
462                        // neither var bound, create new class
463                        EqvClass newClass;
464                        newClass.vars.insert( var1->get_name() );
465                        newClass.vars.insert( var2->get_name() );
466                        newClass.allowWidening = widen1 && widen2;
467                        newClass.data = data;
468                        env.push_back( std::move(newClass) );
469                } // if
470                return true;
471        }
472
473        void TypeEnvironment::forbidWidening() {
474                for ( EqvClass& c : env ) c.allowWidening = false;
475        }
476
477        std::ostream & operator<<( std::ostream & out, const TypeEnvironment & env ) {
478                env.print( out );
479                return out;
480        }
481} // namespace ResolvExpr
482
483// Local Variables: //
484// tab-width: 4 //
485// mode: c++ //
486// compile-command: "make install" //
487// End: //
Note: See TracBrowser for help on using the repository browser.