source: src/SymTab/Indexer.cc @ 8bafacc

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 8bafacc was 6d49ea3, checked in by Peter A. Buhr <pabuhr@…>, 7 years ago

second attempt, add declarations into if conditional

  • Property mode set to 100644
File size: 35.7 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// Indexer.cc --
8//
9// Author           : Richard C. Bilson
10// Created On       : Sun May 17 21:37:33 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Thu Aug 17 16:08:40 2017
13// Update Count     : 20
14//
15
16#include "Indexer.h"
17
18#include <cassert>                 // for assert, safe_dynamic_cast
19#include <iostream>                // for operator<<, basic_ostream, ostream
20#include <string>                  // for string, operator<<, operator!=
21#include <unordered_map>           // for operator!=, unordered_map<>::const...
22#include <unordered_set>           // for unordered_set
23#include <utility>                 // for pair, make_pair, move
24
25#include "Common/SemanticError.h"  // for SemanticError
26#include "Common/utility.h"        // for cloneAll
27#include "InitTweak/InitTweak.h"   // for isConstructor, isCopyFunction, isC...
28#include "Mangler.h"               // for Mangler
29#include "Parser/LinkageSpec.h"    // for isMangled, isOverridable, Spec
30#include "ResolvExpr/typeops.h"    // for typesCompatible
31#include "SynTree/Constant.h"      // for Constant
32#include "SynTree/Declaration.h"   // for DeclarationWithType, FunctionDecl
33#include "SynTree/Expression.h"    // for Expression, ImplicitCopyCtorExpr
34#include "SynTree/Initializer.h"   // for Initializer
35#include "SynTree/Statement.h"     // for CompoundStmt, Statement, ForStmt (...
36#include "SynTree/Type.h"          // for Type, StructInstType, UnionInstType
37
38#define debugPrint(x) if ( doDebug ) { std::cout << x; }
39
40namespace SymTab {
41        struct NewScope {
42                NewScope( SymTab::Indexer & indexer ) : indexer( indexer ) { indexer.enterScope(); }
43                ~NewScope() { indexer.leaveScope(); }
44                SymTab::Indexer & indexer;
45        };
46
47        template< typename TreeType, typename VisitorType >
48        inline void acceptNewScope( TreeType *tree, VisitorType &visitor ) {
49                visitor.enterScope();
50                maybeAccept( tree, visitor );
51                visitor.leaveScope();
52        }
53
54        typedef std::unordered_map< std::string, DeclarationWithType* > MangleTable;
55        typedef std::unordered_map< std::string, MangleTable > IdTable;
56        typedef std::unordered_map< std::string, NamedTypeDecl* > TypeTable;
57        typedef std::unordered_map< std::string, StructDecl* > StructTable;
58        typedef std::unordered_map< std::string, EnumDecl* > EnumTable;
59        typedef std::unordered_map< std::string, UnionDecl* > UnionTable;
60        typedef std::unordered_map< std::string, TraitDecl* > TraitTable;
61
62        void dump( const IdTable &table, std::ostream &os ) {
63                for ( IdTable::const_iterator id = table.begin(); id != table.end(); ++id ) {
64                        for ( MangleTable::const_iterator mangle = id->second.begin(); mangle != id->second.end(); ++mangle ) {
65                                os << mangle->second << std::endl;
66                        }
67                }
68        }
69
70        template< typename Decl >
71        void dump( const std::unordered_map< std::string, Decl* > &table, std::ostream &os ) {
72                for ( typename std::unordered_map< std::string, Decl* >::const_iterator it = table.begin(); it != table.end(); ++it ) {
73                        os << it->second << std::endl;
74                } // for
75        }
76
77        struct Indexer::Impl {
78                Impl( unsigned long _scope ) : refCount(1), scope( _scope ), size( 0 ), base(),
79                                idTable(), typeTable(), structTable(), enumTable(), unionTable(), traitTable() {}
80                Impl( unsigned long _scope, Indexer &&_base ) : refCount(1), scope( _scope ), size( 0 ), base( _base ),
81                                idTable(), typeTable(), structTable(), enumTable(), unionTable(), traitTable() {}
82                unsigned long refCount;   ///< Number of references to these tables
83                unsigned long scope;      ///< Scope these tables are associated with
84                unsigned long size;       ///< Number of elements stored in this table
85                const Indexer base;       ///< Base indexer this extends
86
87                IdTable idTable;          ///< Identifier namespace
88                TypeTable typeTable;      ///< Type namespace
89                StructTable structTable;  ///< Struct namespace
90                EnumTable enumTable;      ///< Enum namespace
91                UnionTable unionTable;    ///< Union namespace
92                TraitTable traitTable;    ///< Trait namespace
93        };
94
95        Indexer::Impl *Indexer::newRef( Indexer::Impl *toClone ) {
96                if ( ! toClone ) return 0;
97
98                // shorten the search chain by skipping empty links
99                Indexer::Impl *ret = toClone->size == 0 ? toClone->base.tables : toClone;
100                if ( ret ) { ++ret->refCount; }
101
102                return ret;
103        }
104
105        void Indexer::deleteRef( Indexer::Impl *toFree ) {
106                if ( ! toFree ) return;
107
108                if ( --toFree->refCount == 0 ) delete toFree;
109        }
110
111        void Indexer::removeSpecialOverrides( const std::string &id, std::list< DeclarationWithType * > & out ) const {
112                // only need to perform this step for constructors, destructors, and assignment functions
113                if ( ! InitTweak::isCtorDtorAssign( id ) ) return;
114
115                // helpful data structure
116                struct ValueType {
117                        struct DeclBall {
118                                FunctionDecl * decl;
119                                bool isUserDefinedFunc; // properties for this particular decl
120                                bool isDefaultCtor;
121                                bool isDtor;
122                                bool isCopyFunc;
123                        };
124                        // properties for this type
125                        bool existsUserDefinedFunc = false;    // any user-defined function found
126                        bool existsUserDefinedCtor = false;    // any user-defined constructor found
127                        bool existsUserDefinedDtor = false;    // any user-defined destructor found
128                        bool existsUserDefinedCopyFunc = false;    // user-defined copy ctor found
129                        bool existsUserDefinedDefaultCtor = false; // user-defined default ctor found
130                        std::list< DeclBall > decls;
131
132                        // another FunctionDecl for the current type was found - determine
133                        // if it has special properties and update data structure accordingly
134                        ValueType & operator+=( FunctionDecl * function ) {
135                                bool isUserDefinedFunc = ! LinkageSpec::isOverridable( function->get_linkage() );
136                                bool isDefaultCtor = InitTweak::isDefaultConstructor( function );
137                                bool isDtor = InitTweak::isDestructor( function );
138                                bool isCopyFunc = InitTweak::isCopyFunction( function, function->get_name() );
139                                decls.push_back( DeclBall{ function, isUserDefinedFunc, isDefaultCtor, isDtor, isCopyFunc } );
140                                existsUserDefinedFunc = existsUserDefinedFunc || isUserDefinedFunc;
141                                existsUserDefinedCtor = existsUserDefinedCtor || (isUserDefinedFunc && InitTweak::isConstructor( function->get_name() ) );
142                                existsUserDefinedDtor = existsUserDefinedDtor || (isUserDefinedFunc && isDtor);
143                                existsUserDefinedCopyFunc = existsUserDefinedCopyFunc || (isUserDefinedFunc && isCopyFunc);
144                                existsUserDefinedDefaultCtor = existsUserDefinedDefaultCtor || (isUserDefinedFunc && isDefaultCtor);
145                                return *this;
146                        }
147                }; // ValueType
148
149                std::list< DeclarationWithType * > copy;
150                copy.splice( copy.end(), out );
151
152                // organize discovered declarations by type
153                std::unordered_map< std::string, ValueType > funcMap;
154                for ( DeclarationWithType * decl : copy ) {
155                        if ( FunctionDecl * function = dynamic_cast< FunctionDecl * >( decl ) ) {
156                                std::list< DeclarationWithType * > & params = function->get_functionType()->get_parameters();
157                                assert( ! params.empty() );
158                                // use base type of pointer, so that qualifiers on the pointer type aren't considered.
159                                Type * base = safe_dynamic_cast< PointerType * >( params.front()->get_type() )->get_base();
160                                funcMap[ Mangler::mangle( base ) ] += function;
161                        } else {
162                                out.push_back( decl );
163                        }
164                }
165
166                // if a type contains user defined ctor/dtor/assign, then special rules trigger, which determine
167                // the set of ctor/dtor/assign that are seen by the requester. In particular, if the user defines
168                // a default ctor, then the generated default ctor should never be seen, likewise for copy ctor
169                // and dtor. If the user defines any ctor/dtor, then no generated field ctors should be seen.
170                // If the user defines any ctor then the generated default ctor should not be seen (intrinsic default
171                // ctor must be overridden exactly).
172                for ( std::pair< const std::string, ValueType > & pair : funcMap ) {
173                        ValueType & val = pair.second;
174                        for ( ValueType::DeclBall ball : val.decls ) {
175                                bool noUserDefinedFunc = ! val.existsUserDefinedFunc;
176                                bool isUserDefinedFunc = ball.isUserDefinedFunc;
177                                bool isAcceptableDefaultCtor = (! val.existsUserDefinedCtor || (! val.existsUserDefinedDefaultCtor && ball.decl->get_linkage() == LinkageSpec::Intrinsic)) && ball.isDefaultCtor; // allow default constructors only when no user-defined constructors exist, except in the case of intrinsics, which require exact overrides
178                                bool isAcceptableCopyFunc = ! val.existsUserDefinedCopyFunc && ball.isCopyFunc; // handles copy ctor and assignment operator
179                                bool isAcceptableDtor = ! val.existsUserDefinedDtor && ball.isDtor;
180                                if ( noUserDefinedFunc || isUserDefinedFunc || isAcceptableDefaultCtor || isAcceptableCopyFunc || isAcceptableDtor ) {
181                                        // decl conforms to the rules described above, so it should be seen by the requester
182                                        out.push_back( ball.decl );
183                                }
184                        }
185                }
186        }
187
188        void Indexer::makeWritable() {
189                if ( ! tables ) {
190                        // create indexer if not yet set
191                        tables = new Indexer::Impl( scope );
192                } else if ( tables->refCount > 1 || tables->scope != scope ) {
193                        // make this indexer the base of a fresh indexer at the current scope
194                        tables = new Indexer::Impl( scope, std::move( *this ) );
195                }
196        }
197
198        Indexer::Indexer( bool _doDebug ) : tables( 0 ), scope( 0 ), doDebug( _doDebug ) {}
199
200        Indexer::Indexer( const Indexer &that ) : tables( newRef( that.tables ) ), scope( that.scope ), doDebug( that.doDebug ) {}
201
202        Indexer::Indexer( Indexer &&that ) : tables( that.tables ), scope( that.scope ), doDebug( that.doDebug ) {
203                that.tables = 0;
204        }
205
206        Indexer::~Indexer() {
207                deleteRef( tables );
208        }
209
210        Indexer& Indexer::operator= ( const Indexer &that ) {
211                deleteRef( tables );
212
213                tables = newRef( that.tables );
214                scope = that.scope;
215                doDebug = that.doDebug;
216
217                return *this;
218        }
219
220        Indexer& Indexer::operator= ( Indexer &&that ) {
221                deleteRef( tables );
222
223                tables = that.tables;
224                scope = that.scope;
225                doDebug = that.doDebug;
226
227                that.tables = 0;
228
229                return *this;
230        }
231
232        void Indexer::visit( ObjectDecl *objectDecl ) {
233                enterScope();
234                maybeAccept( objectDecl->get_type(), *this );
235                leaveScope();
236                maybeAccept( objectDecl->get_init(), *this );
237                maybeAccept( objectDecl->get_bitfieldWidth(), *this );
238                if ( objectDecl->get_name() != "" ) {
239                        debugPrint( "Adding object " << objectDecl->get_name() << std::endl );
240                        addId( objectDecl );
241                } // if
242        }
243
244        void Indexer::visit( FunctionDecl *functionDecl ) {
245                if ( functionDecl->get_name() == "" ) return;
246                debugPrint( "Adding function " << functionDecl->get_name() << std::endl );
247                addId( functionDecl );
248                enterScope();
249                maybeAccept( functionDecl->get_functionType(), *this );
250                maybeAccept( functionDecl->get_statements(), *this );
251                leaveScope();
252        }
253
254
255// A NOTE ON THE ORDER OF TRAVERSAL
256//
257// Types and typedefs have their base types visited before they are added to the type table.  This is ok, since there is
258// no such thing as a recursive type or typedef.
259//
260//             typedef struct { T *x; } T; // never allowed
261//
262// for structs/unions, it is possible to have recursion, so the decl should be added as if it's incomplete to begin, the
263// members are traversed, and then the complete type should be added (assuming the type is completed by this particular
264// declaration).
265//
266//             struct T { struct T *x; }; // allowed
267//
268// It is important to add the complete type to the symbol table *after* the members/base has been traversed, since that
269// traversal may modify the definition of the type and these modifications should be visible when the symbol table is
270// queried later in this pass.
271//
272// TODO: figure out whether recursive contexts are sensible/possible/reasonable.
273
274
275        void Indexer::visit( TypeDecl *typeDecl ) {
276                // see A NOTE ON THE ORDER OF TRAVERSAL, above
277                // note that assertions come after the type is added to the symtab, since they are not part of the type proper
278                // and may depend on the type itself
279                enterScope();
280                acceptAll( typeDecl->get_parameters(), *this );
281                maybeAccept( typeDecl->get_base(), *this );
282                leaveScope();
283                debugPrint( "Adding type " << typeDecl->get_name() << std::endl );
284                addType( typeDecl );
285                acceptAll( typeDecl->get_assertions(), *this );
286                acceptNewScope( typeDecl->get_init(), *this );
287        }
288
289        void Indexer::visit( TypedefDecl *typeDecl ) {
290                enterScope();
291                acceptAll( typeDecl->get_parameters(), *this );
292                maybeAccept( typeDecl->get_base(), *this );
293                leaveScope();
294                debugPrint( "Adding typedef " << typeDecl->get_name() << std::endl );
295                addType( typeDecl );
296        }
297
298        void Indexer::visit( StructDecl *aggregateDecl ) {
299                // make up a forward declaration and add it before processing the members
300                // needs to be on the heap because addStruct saves the pointer
301                StructDecl &fwdDecl = *new StructDecl( aggregateDecl->get_name() );
302                cloneAll( aggregateDecl->get_parameters(), fwdDecl.get_parameters() );
303                debugPrint( "Adding fwd decl for struct " << fwdDecl.get_name() << std::endl );
304                addStruct( &fwdDecl );
305
306                enterScope();
307                acceptAll( aggregateDecl->get_parameters(), *this );
308                acceptAll( aggregateDecl->get_members(), *this );
309                leaveScope();
310
311                debugPrint( "Adding struct " << aggregateDecl->get_name() << std::endl );
312                // this addition replaces the forward declaration
313                addStruct( aggregateDecl );
314        }
315
316        void Indexer::visit( UnionDecl *aggregateDecl ) {
317                // make up a forward declaration and add it before processing the members
318                UnionDecl fwdDecl( aggregateDecl->get_name() );
319                cloneAll( aggregateDecl->get_parameters(), fwdDecl.get_parameters() );
320                debugPrint( "Adding fwd decl for union " << fwdDecl.get_name() << std::endl );
321                addUnion( &fwdDecl );
322
323                enterScope();
324                acceptAll( aggregateDecl->get_parameters(), *this );
325                acceptAll( aggregateDecl->get_members(), *this );
326                leaveScope();
327
328                debugPrint( "Adding union " << aggregateDecl->get_name() << std::endl );
329                addUnion( aggregateDecl );
330        }
331
332        void Indexer::visit( EnumDecl *aggregateDecl ) {
333                debugPrint( "Adding enum " << aggregateDecl->get_name() << std::endl );
334                addEnum( aggregateDecl );
335                // unlike structs, contexts, and unions, enums inject their members into the global scope
336                acceptAll( aggregateDecl->get_members(), *this );
337        }
338
339        void Indexer::visit( TraitDecl *aggregateDecl ) {
340                enterScope();
341                acceptAll( aggregateDecl->get_parameters(), *this );
342                acceptAll( aggregateDecl->get_members(), *this );
343                leaveScope();
344
345                debugPrint( "Adding context " << aggregateDecl->get_name() << std::endl );
346                addTrait( aggregateDecl );
347        }
348
349        void Indexer::visit( CompoundStmt *compoundStmt ) {
350                enterScope();
351                acceptAll( compoundStmt->get_kids(), *this );
352                leaveScope();
353        }
354
355        void Indexer::visit( IfStmt *ifStmt ) {
356            // for statements introduce a level of scope
357            enterScope();
358            Visitor::visit( ifStmt );
359            leaveScope();
360        }
361
362        void Indexer::visit( ForStmt *forStmt ) {
363            // for statements introduce a level of scope
364            enterScope();
365            Visitor::visit( forStmt );
366            leaveScope();
367        }
368
369        void Indexer::visit( CatchStmt *catchStmt ) {
370                // catch statements introduce a level of scope (for the caught exception)
371                enterScope();
372                Visitor::visit( catchStmt );
373                leaveScope();
374        }
375
376        void Indexer::visit( ApplicationExpr *applicationExpr ) {
377                acceptNewScope( applicationExpr->get_result(), *this );
378                maybeAccept( applicationExpr->get_function(), *this );
379                acceptAll( applicationExpr->get_args(), *this );
380        }
381
382        void Indexer::visit( UntypedExpr *untypedExpr ) {
383                acceptNewScope( untypedExpr->get_result(), *this );
384                acceptAll( untypedExpr->get_args(), *this );
385        }
386
387        void Indexer::visit( NameExpr *nameExpr ) {
388                acceptNewScope( nameExpr->get_result(), *this );
389        }
390
391        void Indexer::visit( AddressExpr *addressExpr ) {
392                acceptNewScope( addressExpr->get_result(), *this );
393                maybeAccept( addressExpr->get_arg(), *this );
394        }
395
396        void Indexer::visit( LabelAddressExpr *labAddressExpr ) {
397                acceptNewScope( labAddressExpr->get_result(), *this );
398                maybeAccept( labAddressExpr->get_arg(), *this );
399        }
400
401        void Indexer::visit( CastExpr *castExpr ) {
402                acceptNewScope( castExpr->get_result(), *this );
403                maybeAccept( castExpr->get_arg(), *this );
404        }
405
406        void Indexer::visit( UntypedMemberExpr *memberExpr ) {
407                acceptNewScope( memberExpr->get_result(), *this );
408                maybeAccept( memberExpr->get_aggregate(), *this );
409        }
410
411        void Indexer::visit( MemberExpr *memberExpr ) {
412                acceptNewScope( memberExpr->get_result(), *this );
413                maybeAccept( memberExpr->get_aggregate(), *this );
414        }
415
416        void Indexer::visit( VariableExpr *variableExpr ) {
417                acceptNewScope( variableExpr->get_result(), *this );
418        }
419
420        void Indexer::visit( ConstantExpr *constantExpr ) {
421                acceptNewScope( constantExpr->get_result(), *this );
422                maybeAccept( constantExpr->get_constant(), *this );
423        }
424
425        void Indexer::visit( SizeofExpr *sizeofExpr ) {
426                acceptNewScope( sizeofExpr->get_result(), *this );
427                if ( sizeofExpr->get_isType() ) {
428                        maybeAccept( sizeofExpr->get_type(), *this );
429                } else {
430                        maybeAccept( sizeofExpr->get_expr(), *this );
431                }
432        }
433
434        void Indexer::visit( AlignofExpr *alignofExpr ) {
435                acceptNewScope( alignofExpr->get_result(), *this );
436                if ( alignofExpr->get_isType() ) {
437                        maybeAccept( alignofExpr->get_type(), *this );
438                } else {
439                        maybeAccept( alignofExpr->get_expr(), *this );
440                }
441        }
442
443        void Indexer::visit( UntypedOffsetofExpr *offsetofExpr ) {
444                acceptNewScope( offsetofExpr->get_result(), *this );
445                maybeAccept( offsetofExpr->get_type(), *this );
446        }
447
448        void Indexer::visit( OffsetofExpr *offsetofExpr ) {
449                acceptNewScope( offsetofExpr->get_result(), *this );
450                maybeAccept( offsetofExpr->get_type(), *this );
451                maybeAccept( offsetofExpr->get_member(), *this );
452        }
453
454        void Indexer::visit( OffsetPackExpr *offsetPackExpr ) {
455                acceptNewScope( offsetPackExpr->get_result(), *this );
456                maybeAccept( offsetPackExpr->get_type(), *this );
457        }
458
459        void Indexer::visit( AttrExpr *attrExpr ) {
460                acceptNewScope( attrExpr->get_result(), *this );
461                if ( attrExpr->get_isType() ) {
462                        maybeAccept( attrExpr->get_type(), *this );
463                } else {
464                        maybeAccept( attrExpr->get_expr(), *this );
465                }
466        }
467
468        void Indexer::visit( LogicalExpr *logicalExpr ) {
469                acceptNewScope( logicalExpr->get_result(), *this );
470                maybeAccept( logicalExpr->get_arg1(), *this );
471                maybeAccept( logicalExpr->get_arg2(), *this );
472        }
473
474        void Indexer::visit( ConditionalExpr *conditionalExpr ) {
475                acceptNewScope( conditionalExpr->get_result(), *this );
476                maybeAccept( conditionalExpr->get_arg1(), *this );
477                maybeAccept( conditionalExpr->get_arg2(), *this );
478                maybeAccept( conditionalExpr->get_arg3(), *this );
479        }
480
481        void Indexer::visit( CommaExpr *commaExpr ) {
482                acceptNewScope( commaExpr->get_result(), *this );
483                maybeAccept( commaExpr->get_arg1(), *this );
484                maybeAccept( commaExpr->get_arg2(), *this );
485        }
486
487        void Indexer::visit( TypeExpr *typeExpr ) {
488                acceptNewScope( typeExpr->get_result(), *this );
489                maybeAccept( typeExpr->get_type(), *this );
490        }
491
492        void Indexer::visit( AsmExpr *asmExpr ) {
493                maybeAccept( asmExpr->get_inout(), *this );
494                maybeAccept( asmExpr->get_constraint(), *this );
495                maybeAccept( asmExpr->get_operand(), *this );
496        }
497
498        void Indexer::visit( ImplicitCopyCtorExpr *impCpCtorExpr ) {
499                acceptNewScope( impCpCtorExpr->get_result(), *this );
500                maybeAccept( impCpCtorExpr->get_callExpr(), *this );
501                acceptAll( impCpCtorExpr->get_tempDecls(), *this );
502                acceptAll( impCpCtorExpr->get_returnDecls(), *this );
503                acceptAll( impCpCtorExpr->get_dtors(), *this );
504        }
505
506        void Indexer::visit( ConstructorExpr * ctorExpr ) {
507                acceptNewScope( ctorExpr->get_result(), *this );
508                maybeAccept( ctorExpr->get_callExpr(), *this );
509        }
510
511        void Indexer::visit( CompoundLiteralExpr *compLitExpr ) {
512                acceptNewScope( compLitExpr->get_result(), *this );
513                maybeAccept( compLitExpr->get_initializer(), *this );
514        }
515
516        void Indexer::visit( RangeExpr *rangeExpr ) {
517                maybeAccept( rangeExpr->get_low(), *this );
518                maybeAccept( rangeExpr->get_high(), *this );
519        }
520
521        void Indexer::visit( UntypedTupleExpr *tupleExpr ) {
522                acceptNewScope( tupleExpr->get_result(), *this );
523                acceptAll( tupleExpr->get_exprs(), *this );
524        }
525
526        void Indexer::visit( TupleExpr *tupleExpr ) {
527                acceptNewScope( tupleExpr->get_result(), *this );
528                acceptAll( tupleExpr->get_exprs(), *this );
529        }
530
531        void Indexer::visit( TupleIndexExpr *tupleExpr ) {
532                acceptNewScope( tupleExpr->get_result(), *this );
533                maybeAccept( tupleExpr->get_tuple(), *this );
534        }
535
536        void Indexer::visit( TupleAssignExpr *tupleExpr ) {
537                acceptNewScope( tupleExpr->get_result(), *this );
538                maybeAccept( tupleExpr->get_stmtExpr(), *this );
539        }
540
541        void Indexer::visit( StmtExpr *stmtExpr ) {
542                acceptNewScope( stmtExpr->get_result(), *this );
543                maybeAccept( stmtExpr->get_statements(), *this );
544                acceptAll( stmtExpr->get_returnDecls(), *this );
545                acceptAll( stmtExpr->get_dtors(), *this );
546        }
547
548        void Indexer::visit( UniqueExpr *uniqueExpr ) {
549                acceptNewScope( uniqueExpr->get_result(), *this );
550                maybeAccept( uniqueExpr->get_expr(), *this );
551        }
552
553
554        void Indexer::visit( TraitInstType *contextInst ) {
555                acceptAll( contextInst->get_parameters(), *this );
556                acceptAll( contextInst->get_members(), *this );
557        }
558
559        void Indexer::visit( StructInstType *structInst ) {
560                if ( ! lookupStruct( structInst->get_name() ) ) {
561                        debugPrint( "Adding struct " << structInst->get_name() << " from implicit forward declaration" << std::endl );
562                        addStruct( structInst->get_name() );
563                }
564                enterScope();
565                acceptAll( structInst->get_parameters(), *this );
566                leaveScope();
567        }
568
569        void Indexer::visit( UnionInstType *unionInst ) {
570                if ( ! lookupUnion( unionInst->get_name() ) ) {
571                        debugPrint( "Adding union " << unionInst->get_name() << " from implicit forward declaration" << std::endl );
572                        addUnion( unionInst->get_name() );
573                }
574                enterScope();
575                acceptAll( unionInst->get_parameters(), *this );
576                leaveScope();
577        }
578
579        void Indexer::lookupId( const std::string &id, std::list< DeclarationWithType* > &out ) const {
580                std::unordered_set< std::string > foundMangleNames;
581
582                Indexer::Impl *searchTables = tables;
583                while ( searchTables ) {
584
585                        IdTable::const_iterator decls = searchTables->idTable.find( id );
586                        if ( decls != searchTables->idTable.end() ) {
587                                const MangleTable &mangleTable = decls->second;
588                                for ( MangleTable::const_iterator decl = mangleTable.begin(); decl != mangleTable.end(); ++decl ) {
589                                        // mark the mangled name as found, skipping this insertion if a declaration for that name has already been found
590                                        if ( foundMangleNames.insert( decl->first ).second == false ) continue;
591
592                                        out.push_back( decl->second );
593                                }
594                        }
595
596                        // get declarations from base indexers
597                        searchTables = searchTables->base.tables;
598                }
599
600                // some special functions, e.g. constructors and destructors
601                // remove autogenerated functions when they are defined so that
602                // they can never be matched
603                removeSpecialOverrides( id, out );
604        }
605
606        NamedTypeDecl *Indexer::lookupType( const std::string &id ) const {
607                if ( ! tables ) return 0;
608
609                TypeTable::const_iterator ret = tables->typeTable.find( id );
610                return ret != tables->typeTable.end() ? ret->second : tables->base.lookupType( id );
611        }
612
613        StructDecl *Indexer::lookupStruct( const std::string &id ) const {
614                if ( ! tables ) return 0;
615
616                StructTable::const_iterator ret = tables->structTable.find( id );
617                return ret != tables->structTable.end() ? ret->second : tables->base.lookupStruct( id );
618        }
619
620        EnumDecl *Indexer::lookupEnum( const std::string &id ) const {
621                if ( ! tables ) return 0;
622
623                EnumTable::const_iterator ret = tables->enumTable.find( id );
624                return ret != tables->enumTable.end() ? ret->second : tables->base.lookupEnum( id );
625        }
626
627        UnionDecl *Indexer::lookupUnion( const std::string &id ) const {
628                if ( ! tables ) return 0;
629
630                UnionTable::const_iterator ret = tables->unionTable.find( id );
631                return ret != tables->unionTable.end() ? ret->second : tables->base.lookupUnion( id );
632        }
633
634        TraitDecl *Indexer::lookupTrait( const std::string &id ) const {
635                if ( ! tables ) return 0;
636
637                TraitTable::const_iterator ret = tables->traitTable.find( id );
638                return ret != tables->traitTable.end() ? ret->second : tables->base.lookupTrait( id );
639        }
640
641        DeclarationWithType *Indexer::lookupIdAtScope( const std::string &id, const std::string &mangleName, unsigned long scope ) const {
642                if ( ! tables ) return 0;
643                if ( tables->scope < scope ) return 0;
644
645                IdTable::const_iterator decls = tables->idTable.find( id );
646                if ( decls != tables->idTable.end() ) {
647                        const MangleTable &mangleTable = decls->second;
648                        MangleTable::const_iterator decl = mangleTable.find( mangleName );
649                        if ( decl != mangleTable.end() ) return decl->second;
650                }
651
652                return tables->base.lookupIdAtScope( id, mangleName, scope );
653        }
654
655        bool Indexer::hasIncompatibleCDecl( const std::string &id, const std::string &mangleName, unsigned long scope ) const {
656                if ( ! tables ) return false;
657                if ( tables->scope < scope ) return false;
658
659                IdTable::const_iterator decls = tables->idTable.find( id );
660                if ( decls != tables->idTable.end() ) {
661                        const MangleTable &mangleTable = decls->second;
662                        for ( MangleTable::const_iterator decl = mangleTable.begin(); decl != mangleTable.end(); ++decl ) {
663                                // check for C decls with the same name, skipping those with a compatible type (by mangleName)
664                                if ( ! LinkageSpec::isMangled( decl->second->get_linkage() ) && decl->first != mangleName ) return true;
665                        }
666                }
667
668                return tables->base.hasIncompatibleCDecl( id, mangleName, scope );
669        }
670
671        bool Indexer::hasCompatibleCDecl( const std::string &id, const std::string &mangleName, unsigned long scope ) const {
672                if ( ! tables ) return false;
673                if ( tables->scope < scope ) return false;
674
675                IdTable::const_iterator decls = tables->idTable.find( id );
676                if ( decls != tables->idTable.end() ) {
677                        const MangleTable &mangleTable = decls->second;
678                        for ( MangleTable::const_iterator decl = mangleTable.begin(); decl != mangleTable.end(); ++decl ) {
679                                // check for C decls with the same name, skipping
680                                // those with an incompatible type (by mangleName)
681                                if ( ! LinkageSpec::isMangled( decl->second->get_linkage() ) && decl->first == mangleName ) return true;
682                        }
683                }
684
685                return tables->base.hasCompatibleCDecl( id, mangleName, scope );
686        }
687
688        NamedTypeDecl *Indexer::lookupTypeAtScope( const std::string &id, unsigned long scope ) const {
689                if ( ! tables ) return 0;
690                if ( tables->scope < scope ) return 0;
691
692                TypeTable::const_iterator ret = tables->typeTable.find( id );
693                return ret != tables->typeTable.end() ? ret->second : tables->base.lookupTypeAtScope( id, scope );
694        }
695
696        StructDecl *Indexer::lookupStructAtScope( const std::string &id, unsigned long scope ) const {
697                if ( ! tables ) return 0;
698                if ( tables->scope < scope ) return 0;
699
700                StructTable::const_iterator ret = tables->structTable.find( id );
701                return ret != tables->structTable.end() ? ret->second : tables->base.lookupStructAtScope( id, scope );
702        }
703
704        EnumDecl *Indexer::lookupEnumAtScope( const std::string &id, unsigned long scope ) const {
705                if ( ! tables ) return 0;
706                if ( tables->scope < scope ) return 0;
707
708                EnumTable::const_iterator ret = tables->enumTable.find( id );
709                return ret != tables->enumTable.end() ? ret->second : tables->base.lookupEnumAtScope( id, scope );
710        }
711
712        UnionDecl *Indexer::lookupUnionAtScope( const std::string &id, unsigned long scope ) const {
713                if ( ! tables ) return 0;
714                if ( tables->scope < scope ) return 0;
715
716                UnionTable::const_iterator ret = tables->unionTable.find( id );
717                return ret != tables->unionTable.end() ? ret->second : tables->base.lookupUnionAtScope( id, scope );
718        }
719
720        TraitDecl *Indexer::lookupTraitAtScope( const std::string &id, unsigned long scope ) const {
721                if ( ! tables ) return 0;
722                if ( tables->scope < scope ) return 0;
723
724                TraitTable::const_iterator ret = tables->traitTable.find( id );
725                return ret != tables->traitTable.end() ? ret->second : tables->base.lookupTraitAtScope( id, scope );
726        }
727
728        bool addedIdConflicts( DeclarationWithType *existing, DeclarationWithType *added ) {
729                // if we're giving the same name mangling to things of different types then there is something wrong
730                assert( (dynamic_cast<ObjectDecl*>( added ) && dynamic_cast<ObjectDecl*>( existing ) )
731                        || (dynamic_cast<FunctionDecl*>( added ) && dynamic_cast<FunctionDecl*>( existing ) ) );
732
733                if ( LinkageSpec::isOverridable( existing->get_linkage() ) ) {
734                        // new definition shadows the autogenerated one, even at the same scope
735                        return false;
736                } else if ( LinkageSpec::isMangled( added->get_linkage() ) || ResolvExpr::typesCompatible( added->get_type(), existing->get_type(), Indexer() ) ) {
737                        // typesCompatible doesn't really do the right thing here. When checking compatibility of function types,
738                        // we should ignore outermost pointer qualifiers, except _Atomic?
739                        FunctionDecl *newentry = dynamic_cast< FunctionDecl* >( added );
740                        FunctionDecl *oldentry = dynamic_cast< FunctionDecl* >( existing );
741                        if ( newentry && oldentry ) {
742                                if ( newentry->get_statements() && oldentry->get_statements() ) {
743                                        throw SemanticError( "duplicate function definition for ", added );
744                                } // if
745                        } else {
746                                // two objects with the same mangled name defined in the same scope.
747                                // both objects must be marked extern or both must be intrinsic for this to be okay
748                                // xxx - perhaps it's actually if either is intrinsic then this is okay?
749                                //       might also need to be same storage class?
750                                ObjectDecl *newobj = dynamic_cast< ObjectDecl* >( added );
751                                ObjectDecl *oldobj = dynamic_cast< ObjectDecl* >( existing );
752                                if ( ! newobj->get_storageClasses().is_extern && ! oldobj->get_storageClasses().is_extern ) {
753                                        throw SemanticError( "duplicate object definition for ", added );
754                                } // if
755                        } // if
756                } else {
757                        throw SemanticError( "duplicate definition for ", added );
758                } // if
759
760                return true;
761        }
762
763        void Indexer::addId( DeclarationWithType *decl ) {
764                makeWritable();
765
766                const std::string &name = decl->get_name();
767                std::string mangleName;
768                if ( LinkageSpec::isOverridable( decl->get_linkage() ) ) {
769                        // mangle the name without including the appropriate suffix, so overridable routines are placed into the
770                        // same "bucket" as their user defined versions.
771                        mangleName = Mangler::mangle( decl, false );
772                } else {
773                        mangleName = Mangler::mangle( decl );
774                } // if
775
776                // this ensures that no two declarations with the same unmangled name at the same scope both have C linkage
777                if ( ! LinkageSpec::isMangled( decl->get_linkage() ) ) {
778                        // NOTE this is broken in Richard's original code in such a way that it never triggers (it
779                        // doesn't check decls that have the same manglename, and all C-linkage decls are defined to
780                        // have their name as their manglename, hence the error can never trigger).
781                        // The code here is closer to correct, but name mangling would have to be completely
782                        // isomorphic to C type-compatibility, which it may not be.
783                        if ( hasIncompatibleCDecl( name, mangleName, scope ) ) {
784                                throw SemanticError( "conflicting overload of C function ", decl );
785                        }
786                } else {
787                        // Check that a Cforall declaration doesn't overload any C declaration
788                        if ( hasCompatibleCDecl( name, mangleName, scope ) ) {
789                                throw SemanticError( "Cforall declaration hides C function ", decl );
790                        }
791                }
792
793                // Skip repeat declarations of the same identifier
794                DeclarationWithType *existing = lookupIdAtScope( name, mangleName, scope );
795                if ( existing && addedIdConflicts( existing, decl ) ) return;
796
797                // add to indexer
798                tables->idTable[ name ][ mangleName ] = decl;
799                ++tables->size;
800        }
801
802        bool addedTypeConflicts( NamedTypeDecl *existing, NamedTypeDecl *added ) {
803                if ( existing->get_base() == 0 ) {
804                        return false;
805                } else if ( added->get_base() == 0 ) {
806                        return true;
807                } else {
808                        throw SemanticError( "redeclaration of ", added );
809                }
810        }
811
812        void Indexer::addType( NamedTypeDecl *decl ) {
813                makeWritable();
814
815                const std::string &id = decl->get_name();
816                TypeTable::iterator existing = tables->typeTable.find( id );
817                if ( existing == tables->typeTable.end() ) {
818                        NamedTypeDecl *parent = tables->base.lookupTypeAtScope( id, scope );
819                        if ( ! parent || ! addedTypeConflicts( parent, decl ) ) {
820                                tables->typeTable.insert( existing, std::make_pair( id, decl ) );
821                                ++tables->size;
822                        }
823                } else {
824                        if ( ! addedTypeConflicts( existing->second, decl ) ) {
825                                existing->second = decl;
826                        }
827                }
828        }
829
830        bool addedDeclConflicts( AggregateDecl *existing, AggregateDecl *added ) {
831                if ( existing->get_members().empty() ) {
832                        return false;
833                } else if ( ! added->get_members().empty() ) {
834                        throw SemanticError( "redeclaration of ", added );
835                } // if
836                return true;
837        }
838
839        void Indexer::addStruct( const std::string &id ) {
840                addStruct( new StructDecl( id ) );
841        }
842
843        void Indexer::addStruct( StructDecl *decl ) {
844                makeWritable();
845
846                const std::string &id = decl->get_name();
847                StructTable::iterator existing = tables->structTable.find( id );
848                if ( existing == tables->structTable.end() ) {
849                        StructDecl *parent = tables->base.lookupStructAtScope( id, scope );
850                        if ( ! parent || ! addedDeclConflicts( parent, decl ) ) {
851                                tables->structTable.insert( existing, std::make_pair( id, decl ) );
852                                ++tables->size;
853                        }
854                } else {
855                        if ( ! addedDeclConflicts( existing->second, decl ) ) {
856                                existing->second = decl;
857                        }
858                }
859        }
860
861        void Indexer::addEnum( EnumDecl *decl ) {
862                makeWritable();
863
864                const std::string &id = decl->get_name();
865                EnumTable::iterator existing = tables->enumTable.find( id );
866                if ( existing == tables->enumTable.end() ) {
867                        EnumDecl *parent = tables->base.lookupEnumAtScope( id, scope );
868                        if ( ! parent || ! addedDeclConflicts( parent, decl ) ) {
869                                tables->enumTable.insert( existing, std::make_pair( id, decl ) );
870                                ++tables->size;
871                        }
872                } else {
873                        if ( ! addedDeclConflicts( existing->second, decl ) ) {
874                                existing->second = decl;
875                        }
876                }
877        }
878
879        void Indexer::addUnion( const std::string &id ) {
880                addUnion( new UnionDecl( id ) );
881        }
882
883        void Indexer::addUnion( UnionDecl *decl ) {
884                makeWritable();
885
886                const std::string &id = decl->get_name();
887                UnionTable::iterator existing = tables->unionTable.find( id );
888                if ( existing == tables->unionTable.end() ) {
889                        UnionDecl *parent = tables->base.lookupUnionAtScope( id, scope );
890                        if ( ! parent || ! addedDeclConflicts( parent, decl ) ) {
891                                tables->unionTable.insert( existing, std::make_pair( id, decl ) );
892                                ++tables->size;
893                        }
894                } else {
895                        if ( ! addedDeclConflicts( existing->second, decl ) ) {
896                                existing->second = decl;
897                        }
898                }
899        }
900
901        void Indexer::addTrait( TraitDecl *decl ) {
902                makeWritable();
903
904                const std::string &id = decl->get_name();
905                TraitTable::iterator existing = tables->traitTable.find( id );
906                if ( existing == tables->traitTable.end() ) {
907                        TraitDecl *parent = tables->base.lookupTraitAtScope( id, scope );
908                        if ( ! parent || ! addedDeclConflicts( parent, decl ) ) {
909                                tables->traitTable.insert( existing, std::make_pair( id, decl ) );
910                                ++tables->size;
911                        }
912                } else {
913                        if ( ! addedDeclConflicts( existing->second, decl ) ) {
914                                existing->second = decl;
915                        }
916                }
917        }
918
919        void Indexer::enterScope() {
920                ++scope;
921
922                if ( doDebug ) {
923                        std::cout << "--- Entering scope " << scope << std::endl;
924                }
925        }
926
927        void Indexer::leaveScope() {
928                using std::cout;
929
930                assert( scope > 0 && "cannot leave initial scope" );
931                --scope;
932
933                while ( tables && tables->scope > scope ) {
934                        if ( doDebug ) {
935                                cout << "--- Leaving scope " << tables->scope << " containing" << std::endl;
936                                dump( tables->idTable, cout );
937                                dump( tables->typeTable, cout );
938                                dump( tables->structTable, cout );
939                                dump( tables->enumTable, cout );
940                                dump( tables->unionTable, cout );
941                                dump( tables->traitTable, cout );
942                        }
943
944                        // swap tables for base table until we find one at an appropriate scope
945                        Indexer::Impl *base = newRef( tables->base.tables );
946                        deleteRef( tables );
947                        tables = base;
948                }
949        }
950
951        void Indexer::print( std::ostream &os, int indent ) const {
952            using std::cerr;
953
954                if ( tables ) {
955                        os << "--- scope " << tables->scope << " ---" << std::endl;
956
957                        os << "===idTable===" << std::endl;
958                        dump( tables->idTable, os );
959                        os << "===typeTable===" << std::endl;
960                        dump( tables->typeTable, os );
961                        os << "===structTable===" << std::endl;
962                        dump( tables->structTable, os );
963                        os << "===enumTable===" << std::endl;
964                        dump( tables->enumTable, os );
965                        os << "===unionTable===" << std::endl;
966                        dump( tables->unionTable, os );
967                        os << "===contextTable===" << std::endl;
968                        dump( tables->traitTable, os );
969
970                        tables->base.print( os, indent );
971                } else {
972                        os << "--- end ---" << std::endl;
973                }
974
975        }
976} // namespace SymTab
977
978// Local Variables: //
979// tab-width: 4 //
980// mode: c++ //
981// compile-command: "make install" //
982// End: //
Note: See TracBrowser for help on using the repository browser.