source: src/ResolvExpr/Unify.cc@ 1ed958c3

new-env with_gc
Last change on this file since 1ed958c3 was eba74ba, checked in by Aaron Moss <a3moss@…>, 7 years ago

Merge remote-tracking branch 'origin/master' into with_gc

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