source: src/SymTab/ValidateType.cc @ eb5962a

ADTast-experimentalpthread-emulationqualifiedEnum
Last change on this file since eb5962a was 1df492a, checked in by JiadaL <j82liang@…>, 22 months ago

Convert TypeInstType? to PointerType? before resolution

  • Property mode set to 100644
File size: 17.0 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// ValidateType.cc -- Validate and normalize types.
8//
9// Author           : Andrew Beach
10// Created On       : Mon May 16 16:21:00 2022
11// Last Modified By : Andrew Beach
12// Last Modified On : Tue May 17 14:06:00 2022
13// Update Count     : 0
14//
15
16#include "ValidateType.h"
17
18#include "CodeGen/OperatorTable.h"
19#include "Common/PassVisitor.h"
20#include "SymTab/FixFunction.h"
21#include "SynTree/Declaration.h"
22#include "SynTree/Type.h"
23
24namespace SymTab {
25
26namespace {
27
28/// Replaces enum types by int, and function or array types in function
29/// parameter and return lists by appropriate pointers.
30struct EnumAndPointerDecay_old {
31        void previsit( EnumDecl * aggregateDecl );
32        void previsit( FunctionType * func );
33};
34
35void EnumAndPointerDecay_old::previsit( EnumDecl * enumDecl ) {
36        // Set the type of each member of the enumeration to be EnumConstant
37        for ( std::list< Declaration * >::iterator i = enumDecl->members.begin(); i != enumDecl->members.end(); ++i ) {
38                ObjectDecl * obj = dynamic_cast< ObjectDecl * >( * i );
39                assert( obj );
40                obj->set_type( new EnumInstType( Type::Qualifiers( Type::Const ), enumDecl->name ) );
41        } // for
42}
43
44template< typename DWTList >
45void fixFunctionList( DWTList & dwts, bool isVarArgs, FunctionType * func ) {
46        auto nvals = dwts.size();
47        bool containsVoid = false;
48        for ( auto & dwt : dwts ) {
49                // fix each DWT and record whether a void was found
50                containsVoid |= fixFunction( dwt );
51        }
52
53        // the only case in which "void" is valid is where it is the only one in the list
54        if ( containsVoid && ( nvals > 1 || isVarArgs ) ) {
55                SemanticError( func, "invalid type void in function type " );
56        }
57
58        // one void is the only thing in the list; remove it.
59        if ( containsVoid ) {
60                delete dwts.front();
61                dwts.clear();
62        }
63}
64
65void EnumAndPointerDecay_old::previsit( FunctionType * func ) {
66        // Fix up parameters and return types
67        fixFunctionList( func->parameters, func->isVarArgs, func );
68        fixFunctionList( func->returnVals, false, func );
69}
70
71/// Associates forward declarations of aggregates with their definitions
72struct LinkReferenceToTypes_old final : public WithIndexer, public WithGuards, public WithVisitorRef<LinkReferenceToTypes_old>, public WithShortCircuiting {
73        LinkReferenceToTypes_old( const Indexer * indexer );
74
75        void postvisit( TypeInstType * typeInst );
76
77        void postvisit( EnumInstType * enumInst );
78        void postvisit( StructInstType * structInst );
79        void postvisit( UnionInstType * unionInst );
80        void postvisit( TraitInstType * traitInst );
81        void previsit( QualifiedType * qualType );
82        void postvisit( QualifiedType * qualType );
83
84        void postvisit( EnumDecl * enumDecl );
85        void postvisit( StructDecl * structDecl );
86        void postvisit( UnionDecl * unionDecl );
87        void postvisit( TraitDecl * traitDecl );
88
89        void previsit( StructDecl * structDecl );
90        void previsit( UnionDecl * unionDecl );
91
92        void renameGenericParams( std::list< TypeDecl * > & params );
93
94private:
95        const Indexer * local_indexer;
96
97        typedef std::map< std::string, std::list< EnumInstType * > > ForwardEnumsType;
98        typedef std::map< std::string, std::list< StructInstType * > > ForwardStructsType;
99        typedef std::map< std::string, std::list< UnionInstType * > > ForwardUnionsType;
100        ForwardEnumsType forwardEnums;
101        ForwardStructsType forwardStructs;
102        ForwardUnionsType forwardUnions;
103        /// true if currently in a generic type body, so that type parameter instances can be renamed appropriately
104        bool inGeneric = false;
105};
106
107
108LinkReferenceToTypes_old::LinkReferenceToTypes_old( const Indexer * other_indexer ) : WithIndexer( false ) {
109        if ( other_indexer ) {
110                local_indexer = other_indexer;
111        } else {
112                local_indexer = &indexer;
113        } // if
114}
115
116void LinkReferenceToTypes_old::postvisit( EnumInstType * enumInst ) {
117        const EnumDecl * st = local_indexer->lookupEnum( enumInst->name );
118        // it's not a semantic error if the enum is not found, just an implicit forward declaration
119        if ( st ) {
120                enumInst->baseEnum = const_cast<EnumDecl *>(st); // Just linking in the node
121        } // if
122        if ( ! st || ! st->body ) {
123                // use of forward declaration
124                forwardEnums[ enumInst->name ].push_back( enumInst );
125        } // if
126}
127
128void LinkReferenceToTypes_old::postvisit( StructInstType * structInst ) {
129        const StructDecl * st = local_indexer->lookupStruct( structInst->name );
130        // it's not a semantic error if the struct is not found, just an implicit forward declaration
131        if ( st ) {
132                structInst->baseStruct = const_cast<StructDecl *>(st); // Just linking in the node
133        } // if
134        if ( ! st || ! st->body ) {
135                // use of forward declaration
136                forwardStructs[ structInst->name ].push_back( structInst );
137        } // if
138}
139
140void LinkReferenceToTypes_old::postvisit( UnionInstType * unionInst ) {
141        const UnionDecl * un = local_indexer->lookupUnion( unionInst->name );
142        // it's not a semantic error if the union is not found, just an implicit forward declaration
143        if ( un ) {
144                unionInst->baseUnion = const_cast<UnionDecl *>(un); // Just linking in the node
145        } // if
146        if ( ! un || ! un->body ) {
147                // use of forward declaration
148                forwardUnions[ unionInst->name ].push_back( unionInst );
149        } // if
150}
151
152void LinkReferenceToTypes_old::previsit( QualifiedType * ) {
153        visit_children = false;
154}
155
156void LinkReferenceToTypes_old::postvisit( QualifiedType * qualType ) {
157        // linking only makes sense for the 'oldest ancestor' of the qualified type
158        qualType->parent->accept( * visitor );
159}
160
161// expand assertions from trait instance, performing the appropriate type variable substitutions
162template< typename Iterator >
163void expandAssertions( TraitInstType * inst, Iterator out ) {
164        assertf( inst->baseTrait, "Trait instance not linked to base trait: %s", toCString( inst ) );
165        std::list< DeclarationWithType * > asserts;
166        for ( Declaration * decl : inst->baseTrait->members ) {
167                asserts.push_back( strict_dynamic_cast<DeclarationWithType *>( decl->clone() ) );
168        }
169        // substitute trait decl parameters for instance parameters
170        applySubstitution( inst->baseTrait->parameters.begin(), inst->baseTrait->parameters.end(), inst->parameters.begin(), asserts.begin(), asserts.end(), out );
171}
172
173void LinkReferenceToTypes_old::postvisit( TraitDecl * traitDecl ) {
174        if ( traitDecl->name == "sized" ) {
175                // "sized" is a special trait - flick the sized status on for the type variable
176                assertf( traitDecl->parameters.size() == 1, "Built-in trait 'sized' has incorrect number of parameters: %zd", traitDecl->parameters.size() );
177                TypeDecl * td = traitDecl->parameters.front();
178                td->set_sized( true );
179        }
180
181        // move assertions from type parameters into the body of the trait
182        for ( TypeDecl * td : traitDecl->parameters ) {
183                for ( DeclarationWithType * assert : td->assertions ) {
184                        if ( TraitInstType * inst = dynamic_cast< TraitInstType * >( assert->get_type() ) ) {
185                                expandAssertions( inst, back_inserter( traitDecl->members ) );
186                        } else {
187                                traitDecl->members.push_back( assert->clone() );
188                        }
189                }
190                deleteAll( td->assertions );
191                td->assertions.clear();
192        } // for
193}
194
195void LinkReferenceToTypes_old::postvisit( TraitInstType * traitInst ) {
196        // handle other traits
197        const TraitDecl * traitDecl = local_indexer->lookupTrait( traitInst->name );
198        if ( ! traitDecl ) {
199                SemanticError( traitInst->location, "use of undeclared trait " + traitInst->name );
200        } // if
201        if ( traitDecl->parameters.size() != traitInst->parameters.size() ) {
202                SemanticError( traitInst, "incorrect number of trait parameters: " );
203        } // if
204        traitInst->baseTrait = const_cast<TraitDecl *>(traitDecl); // Just linking in the node
205
206        // need to carry over the 'sized' status of each decl in the instance
207        for ( auto p : group_iterate( traitDecl->parameters, traitInst->parameters ) ) {
208                TypeExpr * expr = dynamic_cast< TypeExpr * >( std::get<1>(p) );
209                if ( ! expr ) {
210                        SemanticError( std::get<1>(p), "Expression parameters for trait instances are currently unsupported: " );
211                }
212                if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( expr->get_type() ) ) {
213                        TypeDecl * formalDecl = std::get<0>(p);
214                        TypeDecl * instDecl = inst->baseType;
215                        if ( formalDecl->get_sized() ) instDecl->set_sized( true );
216                }
217        }
218        // normalizeAssertions( traitInst->members );
219}
220
221void LinkReferenceToTypes_old::postvisit( EnumDecl * enumDecl ) {
222        // visit enum members first so that the types of self-referencing members are updated properly
223        // Replace the enum base; right now it works only for StructEnum
224        if ( enumDecl->base ) {
225                if ( const TypeInstType * base = dynamic_cast< TypeInstType * >(enumDecl->base) ) {
226                        if ( const StructDecl * decl = local_indexer->lookupStruct( base->name ) ) {
227                                enumDecl->base = new StructInstType( Type::Qualifiers(), const_cast< StructDecl * >( decl ) ); // Just linking in the node
228                        }
229                } else if ( const PointerType * ptr = dynamic_cast< PointerType * >(enumDecl->base) ) {
230                        if ( const TypeInstType * ptrBase = dynamic_cast< TypeInstType * >( ptr->base ) ) {
231                                if ( const StructDecl * decl = local_indexer->lookupStruct( ptrBase->name ) ) {
232                                        enumDecl->base = new PointerType( Type::Qualifiers(),
233                                                new StructInstType( Type::Qualifiers(), const_cast< StructDecl * >( decl ) ) );
234                                }
235                        }
236                }
237        }
238       
239        if ( enumDecl->body ) {
240                ForwardEnumsType::iterator fwds = forwardEnums.find( enumDecl->name );
241                if ( fwds != forwardEnums.end() ) {
242                        for ( std::list< EnumInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
243                                (* inst)->baseEnum = enumDecl;
244                        } // for
245                        forwardEnums.erase( fwds );
246                } // if
247        } // if
248}
249
250void LinkReferenceToTypes_old::renameGenericParams( std::list< TypeDecl * > & params ) {
251        // rename generic type parameters uniquely so that they do not conflict with user-defined function forall parameters, e.g.
252        //   forall(otype T)
253        //   struct Box {
254        //     T x;
255        //   };
256        //   forall(otype T)
257        //   void f(Box(T) b) {
258        //     ...
259        //   }
260        // The T in Box and the T in f are different, so internally the naming must reflect that.
261        GuardValue( inGeneric );
262        inGeneric = ! params.empty();
263        for ( TypeDecl * td : params ) {
264                td->name = "__" + td->name + "_generic_";
265        }
266}
267
268void LinkReferenceToTypes_old::previsit( StructDecl * structDecl ) {
269        renameGenericParams( structDecl->parameters );
270}
271
272void LinkReferenceToTypes_old::previsit( UnionDecl * unionDecl ) {
273        renameGenericParams( unionDecl->parameters );
274}
275
276void LinkReferenceToTypes_old::postvisit( StructDecl * structDecl ) {
277        // visit struct members first so that the types of self-referencing members are updated properly
278        // xxx - need to ensure that type parameters match up between forward declarations and definition (most importantly, number of type parameters and their def>
279        if ( structDecl->body ) {
280                ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->name );
281                if ( fwds != forwardStructs.end() ) {
282                        for ( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
283                                (* inst)->baseStruct = structDecl;
284                        } // for
285                        forwardStructs.erase( fwds );
286                } // if
287        } // if
288}
289
290void LinkReferenceToTypes_old::postvisit( UnionDecl * unionDecl ) {
291        if ( unionDecl->body ) {
292        ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->name );
293                if ( fwds != forwardUnions.end() ) {
294                        for ( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
295                                (* inst)->baseUnion = unionDecl;
296                        } // for
297                        forwardUnions.erase( fwds );
298                } // if
299        } // if
300}
301
302void LinkReferenceToTypes_old::postvisit( TypeInstType * typeInst ) {
303        // ensure generic parameter instances are renamed like the base type
304        if ( inGeneric && typeInst->baseType ) typeInst->name = typeInst->baseType->name;
305        if ( const NamedTypeDecl * namedTypeDecl = local_indexer->lookupType( typeInst->name ) ) {
306                if ( const TypeDecl * typeDecl = dynamic_cast< const TypeDecl * >( namedTypeDecl ) ) {
307                        typeInst->set_isFtype( typeDecl->kind == TypeDecl::Ftype );
308                } // if
309        } // if
310}
311
312/* // expand assertions from trait instance, performing the appropriate type variable substitutions
313template< typename Iterator >
314void expandAssertions( TraitInstType * inst, Iterator out ) {
315        assertf( inst->baseTrait, "Trait instance not linked to base trait: %s", toCString( inst ) );
316        std::list< DeclarationWithType * > asserts;
317        for ( Declaration * decl : inst->baseTrait->members ) {
318                asserts.push_back( strict_dynamic_cast<DeclarationWithType *>( decl->clone() ) );
319        }
320        // substitute trait decl parameters for instance parameters
321        applySubstitution( inst->baseTrait->parameters.begin(), inst->baseTrait->parameters.end(), inst->parameters.begin(), asserts.begin(), asserts.end(), out );
322}*/
323
324/// Replace all traits in assertion lists with their assertions.
325void expandTraits( std::list< TypeDecl * > & forall ) {
326        for ( TypeDecl * type : forall ) {
327                std::list< DeclarationWithType * > asserts;
328                asserts.splice( asserts.end(), type->assertions );
329                // expand trait instances into their members
330                for ( DeclarationWithType * assertion : asserts ) {
331                        if ( TraitInstType * traitInst = dynamic_cast< TraitInstType * >( assertion->get_type() ) ) {
332                                // expand trait instance into all of its members
333                                expandAssertions( traitInst, back_inserter( type->assertions ) );
334                                delete traitInst;
335                        } else {
336                                // pass other assertions through
337                                type->assertions.push_back( assertion );
338                        } // if
339                } // for
340        } // for
341}
342
343struct TraitExpander_old final {
344        void previsit( FunctionType * type ) {
345                expandTraits( type->forall );
346        }
347        void previsit( StructDecl * decl ) {
348                expandTraits( decl->parameters );
349        }
350        void previsit( UnionDecl * decl ) {
351                expandTraits( decl->parameters );
352        }
353};
354
355/*struct TraitExpander_old final {
356        void previsit( FunctionType * );
357        void previsit( StructDecl * );
358        void previsit( UnionDecl * );
359};
360
361void TraitExpander_old::previsit( FunctionType * ftype ) {
362        expandTraits( ftype->forall );
363}
364
365void TraitExpander_old::previsit( StructDecl * aggrDecl ) {
366        expandTraits( aggrDecl->parameters );
367}
368
369void TraitExpander_old::previsit( UnionDecl * aggrDecl ) {
370        expandTraits( aggrDecl->parameters );
371}*/
372
373/// Fix each function in the assertion list and check for invalid void type.
374void fixAssertions(
375                std::list< TypeDecl * > & forall, BaseSyntaxNode * node ) {
376        for ( TypeDecl * type : forall ) {
377                for ( DeclarationWithType *& assertion : type->assertions ) {
378                        bool isVoid = fixFunction( assertion );
379                        if ( isVoid ) {
380                                SemanticError( node, "invalid type void in assertion of function " );
381                        } // if
382                } // for
383        }
384}
385
386struct AssertionFixer_old final {
387        void previsit( FunctionType * type ) {
388                fixAssertions( type->forall, type );
389        }
390        void previsit( StructDecl * decl ) {
391                fixAssertions( decl->parameters, decl );
392        }
393        void previsit( UnionDecl * decl ) {
394                fixAssertions( decl->parameters, decl );
395        }
396};
397
398/*
399struct AssertionFixer_old final {
400        void previsit( FunctionType * );
401        void previsit( StructDecl * );
402        void previsit( UnionDecl * );
403};
404
405void AssertionFixer_old::previsit( FunctionType * ftype ) {
406        fixAssertions( ftype->forall, ftype );
407}
408
409void AssertionFixer_old::previsit( StructDecl * aggrDecl ) {
410        fixAssertions( aggrDecl->parameters, aggrDecl );
411}
412
413void AssertionFixer_old::previsit( UnionDecl * aggrDecl ) {
414        fixAssertions( aggrDecl->parameters, aggrDecl );
415}*/
416
417struct CheckOperatorTypes_old final {
418        void previsit( ObjectDecl * );
419};
420
421void CheckOperatorTypes_old::previsit( ObjectDecl * object ) {
422        // ensure that operator names only apply to functions or function pointers
423        if ( CodeGen::isOperator( object->name ) && ! dynamic_cast< FunctionType * >( object->type->stripDeclarator() ) ) {
424                SemanticError( object->location, toCString( "operator ", object->name.c_str(), " is not a function or function pointer." )  );
425        }
426}
427
428struct FixUniqueIds_old final {
429        void previsit( DeclarationWithType * decl ) {
430                decl->fixUniqueId();
431        }
432};
433
434//void FixUniqueIds_old::previsit( DeclarationWithType * decl ) {
435//      decl->fixUniqueId();
436//}
437
438
439} // namespace
440
441void validateType( Type *type, const Indexer *indexer ) {
442        PassVisitor<EnumAndPointerDecay_old> epc;
443        PassVisitor<LinkReferenceToTypes_old> lrt( indexer );
444        PassVisitor<TraitExpander_old> te;
445        PassVisitor<AssertionFixer_old> af;
446        PassVisitor<CheckOperatorTypes_old> cot;
447        PassVisitor<FixUniqueIds_old> fui;
448        type->accept( epc );
449        type->accept( lrt );
450        type->accept( te );
451        type->accept( af );
452        type->accept( cot );
453        type->accept( fui );
454}
455
456void decayEnumsAndPointers( std::list< Declaration * > & translationUnit ) {
457        PassVisitor<EnumAndPointerDecay_old> epc;
458        acceptAll( translationUnit, epc );
459}
460
461void linkReferenceToTypes( std::list< Declaration * > & translationUnit ) {
462        PassVisitor<LinkReferenceToTypes_old> lrt( nullptr );
463        acceptAll( translationUnit, lrt ); // must happen before autogen, because sized flag needs to propagate to generated functions
464}
465
466void decayForallPointers( std::list< Declaration * > & translationUnit ) {
467        PassVisitor<TraitExpander_old> te;
468        acceptAll( translationUnit, te );
469        PassVisitor<AssertionFixer_old> af;
470        acceptAll( translationUnit, af );
471        PassVisitor<CheckOperatorTypes_old> cot;
472        acceptAll( translationUnit, cot );
473        PassVisitor<FixUniqueIds_old> fui;
474        acceptAll( translationUnit, fui );
475}
476
477
478} // namespace SymTab
479
480// Local Variables: //
481// tab-width: 4 //
482// mode: c++ //
483// compile-command: "make install" //
484// End: //
Note: See TracBrowser for help on using the repository browser.