source: src/SymTab/ValidateType.cc @ 9feb34b

ADTast-experimental
Last change on this file since 9feb34b was 9feb34b, checked in by Andrew Beach <ajbeach@…>, 14 months ago

Moved toString and toCString to a new header. Updated includes. cassert was somehow getting instances of toString before but that stopped working so I embedded the new smaller include.

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