source: src/ResolvExpr/Unify.cc@ b60f9d9

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

stop eagerly copying EqvClass on lookup

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