• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // Copyright (C) 2002-2005  3Dlabs Inc. Ltd.
3 // Copyright (C) 2013 LunarG, Inc.
4 // Copyright (C) 2015-2018 Google, Inc.
5 //
6 // All rights reserved.
7 //
8 // Redistribution and use in source and binary forms, with or without
9 // modification, are permitted provided that the following conditions
10 // are met:
11 //
12 //    Redistributions of source code must retain the above copyright
13 //    notice, this list of conditions and the following disclaimer.
14 //
15 //    Redistributions in binary form must reproduce the above
16 //    copyright notice, this list of conditions and the following
17 //    disclaimer in the documentation and/or other materials provided
18 //    with the distribution.
19 //
20 //    Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21 //    contributors may be used to endorse or promote products derived
22 //    from this software without specific prior written permission.
23 //
24 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28 // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30 // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35 // POSSIBILITY OF SUCH DAMAGE.
36 //
37 
38 #ifndef _SYMBOL_TABLE_INCLUDED_
39 #define _SYMBOL_TABLE_INCLUDED_
40 
41 //
42 // Symbol table for parsing.  Has these design characteristics:
43 //
44 // * Same symbol table can be used to compile many shaders, to preserve
45 //   effort of creating and loading with the large numbers of built-in
46 //   symbols.
47 //
48 // -->  This requires a copy mechanism, so initial pools used to create
49 //   the shared information can be popped.  Done through "clone"
50 //   methods.
51 //
52 // * Name mangling will be used to give each function a unique name
53 //   so that symbol table lookups are never ambiguous.  This allows
54 //   a simpler symbol table structure.
55 //
56 // * Pushing and popping of scope, so symbol table will really be a stack
57 //   of symbol tables.  Searched from the top, with new inserts going into
58 //   the top.
59 //
60 // * Constants:  Compile time constant symbols will keep their values
61 //   in the symbol table.  The parser can substitute constants at parse
62 //   time, including doing constant folding and constant propagation.
63 //
64 // * No temporaries:  Temporaries made from operations (+, --, .xy, etc.)
65 //   are tracked in the intermediate representation, not the symbol table.
66 //
67 
68 #include "../Include/Common.h"
69 #include "../Include/intermediate.h"
70 #include "../Include/InfoSink.h"
71 
72 namespace glslang {
73 
74 //
75 // Symbol base class.  (Can build functions or variables out of these...)
76 //
77 
78 class TVariable;
79 class TFunction;
80 class TAnonMember;
81 
82 class TSymbol {
83 public:
POOL_ALLOCATOR_NEW_DELETE(GetThreadPoolAllocator ())84     POOL_ALLOCATOR_NEW_DELETE(GetThreadPoolAllocator())
85     explicit TSymbol(const TString *n) :  name(n), numExtensions(0), extensions(0), writable(true) { }
86     virtual TSymbol* clone() const = 0;
~TSymbol()87     virtual ~TSymbol() { }  // rely on all symbol owned memory coming from the pool
88 
getName()89     virtual const TString& getName() const { return *name; }
changeName(const TString * newName)90     virtual void changeName(const TString* newName) { name = newName; }
addPrefix(const char * prefix)91     virtual void addPrefix(const char* prefix)
92     {
93         TString newName(prefix);
94         newName.append(*name);
95         changeName(NewPoolTString(newName.c_str()));
96     }
getMangledName()97     virtual const TString& getMangledName() const { return getName(); }
getAsFunction()98     virtual TFunction* getAsFunction() { return 0; }
getAsFunction()99     virtual const TFunction* getAsFunction() const { return 0; }
getAsVariable()100     virtual TVariable* getAsVariable() { return 0; }
getAsVariable()101     virtual const TVariable* getAsVariable() const { return 0; }
getAsAnonMember()102     virtual const TAnonMember* getAsAnonMember() const { return 0; }
103     virtual const TType& getType() const = 0;
104     virtual TType& getWritableType() = 0;
setUniqueId(int id)105     virtual void setUniqueId(int id) { uniqueId = id; }
getUniqueId()106     virtual int getUniqueId() const { return uniqueId; }
setExtensions(int num,const char * const exts[])107     virtual void setExtensions(int num, const char* const exts[])
108     {
109         assert(extensions == 0);
110         assert(num > 0);
111         numExtensions = num;
112         extensions = NewPoolObject(exts[0], num);
113         for (int e = 0; e < num; ++e)
114             extensions[e] = exts[e];
115     }
getNumExtensions()116     virtual int getNumExtensions() const { return numExtensions; }
getExtensions()117     virtual const char** getExtensions() const { return extensions; }
118     virtual void dump(TInfoSink &infoSink) const = 0;
119 
isReadOnly()120     virtual bool isReadOnly() const { return ! writable; }
makeReadOnly()121     virtual void makeReadOnly() { writable = false; }
122 
123 protected:
124     explicit TSymbol(const TSymbol&);
125     TSymbol& operator=(const TSymbol&);
126 
127     const TString *name;
128     unsigned int uniqueId;      // For cross-scope comparing during code generation
129 
130     // For tracking what extensions must be present
131     // (don't use if correct version/profile is present).
132     int numExtensions;
133     const char** extensions; // an array of pointers to existing constant char strings
134 
135     //
136     // N.B.: Non-const functions that will be generally used should assert on this,
137     // to avoid overwriting shared symbol-table information.
138     //
139     bool writable;
140 };
141 
142 //
143 // Variable class, meaning a symbol that's not a function.
144 //
145 // There could be a separate class hierarchy for Constant variables;
146 // Only one of int, bool, or float, (or none) is correct for
147 // any particular use, but it's easy to do this way, and doesn't
148 // seem worth having separate classes, and "getConst" can't simply return
149 // different values for different types polymorphically, so this is
150 // just simple and pragmatic.
151 //
152 class TVariable : public TSymbol {
153 public:
154     TVariable(const TString *name, const TType& t, bool uT = false )
TSymbol(name)155         : TSymbol(name),
156           userType(uT),
157           constSubtree(nullptr),
158           anonId(-1) { type.shallowCopy(t); }
159     virtual TVariable* clone() const;
~TVariable()160     virtual ~TVariable() { }
161 
getAsVariable()162     virtual TVariable* getAsVariable() { return this; }
getAsVariable()163     virtual const TVariable* getAsVariable() const { return this; }
getType()164     virtual const TType& getType() const { return type; }
getWritableType()165     virtual TType& getWritableType() { assert(writable); return type; }
isUserType()166     virtual bool isUserType() const { return userType; }
getConstArray()167     virtual const TConstUnionArray& getConstArray() const { return constArray; }
getWritableConstArray()168     virtual TConstUnionArray& getWritableConstArray() { assert(writable); return constArray; }
setConstArray(const TConstUnionArray & array)169     virtual void setConstArray(const TConstUnionArray& array) { constArray = array; }
setConstSubtree(TIntermTyped * subtree)170     virtual void setConstSubtree(TIntermTyped* subtree) { constSubtree = subtree; }
getConstSubtree()171     virtual TIntermTyped* getConstSubtree() const { return constSubtree; }
setAnonId(int i)172     virtual void setAnonId(int i) { anonId = i; }
getAnonId()173     virtual int getAnonId() const { return anonId; }
174 
175     virtual void dump(TInfoSink &infoSink) const;
176 
177 protected:
178     explicit TVariable(const TVariable&);
179     TVariable& operator=(const TVariable&);
180 
181     TType type;
182     bool userType;
183     // we are assuming that Pool Allocator will free the memory allocated to unionArray
184     // when this object is destroyed
185 
186     // TODO: these two should be a union
187     // A variable could be a compile-time constant, or a specialization
188     // constant, or neither, but never both.
189     TConstUnionArray constArray;  // for compile-time constant value
190     TIntermTyped* constSubtree;   // for specialization constant computation
191     int anonId;                   // the ID used for anonymous blocks: TODO: see if uniqueId could serve a dual purpose
192 };
193 
194 //
195 // The function sub-class of symbols and the parser will need to
196 // share this definition of a function parameter.
197 //
198 struct TParameter {
199     TString *name;
200     TType* type;
201     TIntermTyped* defaultValue;
copyParamTParameter202     void copyParam(const TParameter& param)
203     {
204         if (param.name)
205             name = NewPoolTString(param.name->c_str());
206         else
207             name = 0;
208         type = param.type->clone();
209         defaultValue = param.defaultValue;
210     }
getDeclaredBuiltInTParameter211     TBuiltInVariable getDeclaredBuiltIn() const { return type->getQualifier().declaredBuiltIn; }
212 };
213 
214 //
215 // The function sub-class of a symbol.
216 //
217 class TFunction : public TSymbol {
218 public:
TFunction(TOperator o)219     explicit TFunction(TOperator o) :
220         TSymbol(0),
221         op(o),
222         defined(false), prototyped(false), implicitThis(false), illegalImplicitThis(false), defaultParamCount(0) { }
223     TFunction(const TString *name, const TType& retType, TOperator tOp = EOpNull) :
TSymbol(name)224         TSymbol(name),
225         mangledName(*name + '('),
226         op(tOp),
227         defined(false), prototyped(false), implicitThis(false), illegalImplicitThis(false), defaultParamCount(0)
228     {
229         returnType.shallowCopy(retType);
230         declaredBuiltIn = retType.getQualifier().builtIn;
231     }
232     virtual TFunction* clone() const override;
233     virtual ~TFunction();
234 
getAsFunction()235     virtual TFunction* getAsFunction() override { return this; }
getAsFunction()236     virtual const TFunction* getAsFunction() const override { return this; }
237 
238     // Install 'p' as the (non-'this') last parameter.
239     // Non-'this' parameters are reflected in both the list of parameters and the
240     // mangled name.
addParameter(TParameter & p)241     virtual void addParameter(TParameter& p)
242     {
243         assert(writable);
244         parameters.push_back(p);
245         p.type->appendMangledName(mangledName);
246 
247         if (p.defaultValue != nullptr)
248             defaultParamCount++;
249     }
250 
251     // Install 'this' as the first parameter.
252     // 'this' is reflected in the list of parameters, but not the mangled name.
addThisParameter(TType & type,const char * name)253     virtual void addThisParameter(TType& type, const char* name)
254     {
255         TParameter p = { NewPoolTString(name), new TType, nullptr };
256         p.type->shallowCopy(type);
257         parameters.insert(parameters.begin(), p);
258     }
259 
addPrefix(const char * prefix)260     virtual void addPrefix(const char* prefix) override
261     {
262         TSymbol::addPrefix(prefix);
263         mangledName.insert(0, prefix);
264     }
265 
removePrefix(const TString & prefix)266     virtual void removePrefix(const TString& prefix)
267     {
268         assert(mangledName.compare(0, prefix.size(), prefix) == 0);
269         mangledName.erase(0, prefix.size());
270     }
271 
getMangledName()272     virtual const TString& getMangledName() const override { return mangledName; }
getType()273     virtual const TType& getType() const override { return returnType; }
getDeclaredBuiltInType()274     virtual TBuiltInVariable getDeclaredBuiltInType() const { return declaredBuiltIn; }
getWritableType()275     virtual TType& getWritableType() override { return returnType; }
relateToOperator(TOperator o)276     virtual void relateToOperator(TOperator o) { assert(writable); op = o; }
getBuiltInOp()277     virtual TOperator getBuiltInOp() const { return op; }
setDefined()278     virtual void setDefined() { assert(writable); defined = true; }
isDefined()279     virtual bool isDefined() const { return defined; }
setPrototyped()280     virtual void setPrototyped() { assert(writable); prototyped = true; }
isPrototyped()281     virtual bool isPrototyped() const { return prototyped; }
setImplicitThis()282     virtual void setImplicitThis() { assert(writable); implicitThis = true; }
hasImplicitThis()283     virtual bool hasImplicitThis() const { return implicitThis; }
setIllegalImplicitThis()284     virtual void setIllegalImplicitThis() { assert(writable); illegalImplicitThis = true; }
hasIllegalImplicitThis()285     virtual bool hasIllegalImplicitThis() const { return illegalImplicitThis; }
286 
287     // Return total number of parameters
getParamCount()288     virtual int getParamCount() const { return static_cast<int>(parameters.size()); }
289     // Return number of parameters with default values.
getDefaultParamCount()290     virtual int getDefaultParamCount() const { return defaultParamCount; }
291     // Return number of fixed parameters (without default values)
getFixedParamCount()292     virtual int getFixedParamCount() const { return getParamCount() - getDefaultParamCount(); }
293 
294     virtual TParameter& operator[](int i) { assert(writable); return parameters[i]; }
295     virtual const TParameter& operator[](int i) const { return parameters[i]; }
296 
297     virtual void dump(TInfoSink &infoSink) const override;
298 
299 protected:
300     explicit TFunction(const TFunction&);
301     TFunction& operator=(const TFunction&);
302 
303     typedef TVector<TParameter> TParamList;
304     TParamList parameters;
305     TType returnType;
306     TBuiltInVariable declaredBuiltIn;
307 
308     TString mangledName;
309     TOperator op;
310     bool defined;
311     bool prototyped;
312     bool implicitThis;         // True if this function is allowed to see all members of 'this'
313     bool illegalImplicitThis;  // True if this function is not supposed to have access to dynamic members of 'this',
314                                // even if it finds member variables in the symbol table.
315                                // This is important for a static member function that has member variables in scope,
316                                // but is not allowed to use them, or see hidden symbols instead.
317     int  defaultParamCount;
318 };
319 
320 //
321 // Members of anonymous blocks are a kind of TSymbol.  They are not hidden in
322 // the symbol table behind a container; rather they are visible and point to
323 // their anonymous container.  (The anonymous container is found through the
324 // member, not the other way around.)
325 //
326 class TAnonMember : public TSymbol {
327 public:
TAnonMember(const TString * n,unsigned int m,const TVariable & a,int an)328     TAnonMember(const TString* n, unsigned int m, const TVariable& a, int an) : TSymbol(n), anonContainer(a), memberNumber(m), anonId(an) { }
329     virtual TAnonMember* clone() const;
~TAnonMember()330     virtual ~TAnonMember() { }
331 
getAsAnonMember()332     virtual const TAnonMember* getAsAnonMember() const { return this; }
getAnonContainer()333     virtual const TVariable& getAnonContainer() const { return anonContainer; }
getMemberNumber()334     virtual unsigned int getMemberNumber() const { return memberNumber; }
335 
getType()336     virtual const TType& getType() const
337     {
338         const TTypeList& types = *anonContainer.getType().getStruct();
339         return *types[memberNumber].type;
340     }
341 
getWritableType()342     virtual TType& getWritableType()
343     {
344         assert(writable);
345         const TTypeList& types = *anonContainer.getType().getStruct();
346         return *types[memberNumber].type;
347     }
348 
getAnonId()349     virtual int getAnonId() const { return anonId; }
350     virtual void dump(TInfoSink &infoSink) const;
351 
352 protected:
353     explicit TAnonMember(const TAnonMember&);
354     TAnonMember& operator=(const TAnonMember&);
355 
356     const TVariable& anonContainer;
357     unsigned int memberNumber;
358     int anonId;
359 };
360 
361 class TSymbolTableLevel {
362 public:
POOL_ALLOCATOR_NEW_DELETE(GetThreadPoolAllocator ())363     POOL_ALLOCATOR_NEW_DELETE(GetThreadPoolAllocator())
364     TSymbolTableLevel() : defaultPrecision(0), anonId(0), thisLevel(false) { }
365     ~TSymbolTableLevel();
366 
insert(TSymbol & symbol,bool separateNameSpaces)367     bool insert(TSymbol& symbol, bool separateNameSpaces)
368     {
369         //
370         // returning true means symbol was added to the table with no semantic errors
371         //
372         const TString& name = symbol.getName();
373         if (name == "") {
374             symbol.getAsVariable()->setAnonId(anonId++);
375             // An empty name means an anonymous container, exposing its members to the external scope.
376             // Give it a name and insert its members in the symbol table, pointing to the container.
377             char buf[20];
378             snprintf(buf, 20, "%s%d", AnonymousPrefix, symbol.getAsVariable()->getAnonId());
379             symbol.changeName(NewPoolTString(buf));
380 
381             return insertAnonymousMembers(symbol, 0);
382         } else {
383             // Check for redefinition errors:
384             // - STL itself will tell us if there is a direct name collision, with name mangling, at this level
385             // - additionally, check for function-redefining-variable name collisions
386             const TString& insertName = symbol.getMangledName();
387             if (symbol.getAsFunction()) {
388                 // make sure there isn't a variable of this name
389                 if (! separateNameSpaces && level.find(name) != level.end())
390                     return false;
391 
392                 // insert, and whatever happens is okay
393                 level.insert(tLevelPair(insertName, &symbol));
394 
395                 return true;
396             } else
397                 return level.insert(tLevelPair(insertName, &symbol)).second;
398         }
399     }
400 
401     // Add more members to an already inserted aggregate object
amend(TSymbol & symbol,int firstNewMember)402     bool amend(TSymbol& symbol, int firstNewMember)
403     {
404         // See insert() for comments on basic explanation of insert.
405         // This operates similarly, but more simply.
406         // Only supporting amend of anonymous blocks so far.
407         if (IsAnonymous(symbol.getName()))
408             return insertAnonymousMembers(symbol, firstNewMember);
409         else
410             return false;
411     }
412 
insertAnonymousMembers(TSymbol & symbol,int firstMember)413     bool insertAnonymousMembers(TSymbol& symbol, int firstMember)
414     {
415         const TTypeList& types = *symbol.getAsVariable()->getType().getStruct();
416         for (unsigned int m = firstMember; m < types.size(); ++m) {
417             TAnonMember* member = new TAnonMember(&types[m].type->getFieldName(), m, *symbol.getAsVariable(), symbol.getAsVariable()->getAnonId());
418             if (! level.insert(tLevelPair(member->getMangledName(), member)).second)
419                 return false;
420         }
421 
422         return true;
423     }
424 
find(const TString & name)425     TSymbol* find(const TString& name) const
426     {
427         tLevel::const_iterator it = level.find(name);
428         if (it == level.end())
429             return 0;
430         else
431             return (*it).second;
432     }
433 
findFunctionNameList(const TString & name,TVector<const TFunction * > & list)434     void findFunctionNameList(const TString& name, TVector<const TFunction*>& list)
435     {
436         size_t parenAt = name.find_first_of('(');
437         TString base(name, 0, parenAt + 1);
438 
439         tLevel::const_iterator begin = level.lower_bound(base);
440         base[parenAt] = ')';  // assume ')' is lexically after '('
441         tLevel::const_iterator end = level.upper_bound(base);
442         for (tLevel::const_iterator it = begin; it != end; ++it)
443             list.push_back(it->second->getAsFunction());
444     }
445 
446     // See if there is already a function in the table having the given non-function-style name.
hasFunctionName(const TString & name)447     bool hasFunctionName(const TString& name) const
448     {
449         tLevel::const_iterator candidate = level.lower_bound(name);
450         if (candidate != level.end()) {
451             const TString& candidateName = (*candidate).first;
452             TString::size_type parenAt = candidateName.find_first_of('(');
453             if (parenAt != candidateName.npos && candidateName.compare(0, parenAt, name) == 0)
454 
455                 return true;
456         }
457 
458         return false;
459     }
460 
461     // See if there is a variable at this level having the given non-function-style name.
462     // Return true if name is found, and set variable to true if the name was a variable.
findFunctionVariableName(const TString & name,bool & variable)463     bool findFunctionVariableName(const TString& name, bool& variable) const
464     {
465         tLevel::const_iterator candidate = level.lower_bound(name);
466         if (candidate != level.end()) {
467             const TString& candidateName = (*candidate).first;
468             TString::size_type parenAt = candidateName.find_first_of('(');
469             if (parenAt == candidateName.npos) {
470                 // not a mangled name
471                 if (candidateName == name) {
472                     // found a variable name match
473                     variable = true;
474                     return true;
475                 }
476             } else {
477                 // a mangled name
478                 if (candidateName.compare(0, parenAt, name) == 0) {
479                     // found a function name match
480                     variable = false;
481                     return true;
482                 }
483             }
484         }
485 
486         return false;
487     }
488 
489     // Use this to do a lazy 'push' of precision defaults the first time
490     // a precision statement is seen in a new scope.  Leave it at 0 for
491     // when no push was needed.  Thus, it is not the current defaults,
492     // it is what to restore the defaults to when popping a level.
setPreviousDefaultPrecisions(const TPrecisionQualifier * p)493     void setPreviousDefaultPrecisions(const TPrecisionQualifier *p)
494     {
495         // can call multiple times at one scope, will only latch on first call,
496         // as we're tracking the previous scope's values, not the current values
497         if (defaultPrecision != 0)
498             return;
499 
500         defaultPrecision = new TPrecisionQualifier[EbtNumTypes];
501         for (int t = 0; t < EbtNumTypes; ++t)
502             defaultPrecision[t] = p[t];
503     }
504 
getPreviousDefaultPrecisions(TPrecisionQualifier * p)505     void getPreviousDefaultPrecisions(TPrecisionQualifier *p)
506     {
507         // can be called for table level pops that didn't set the
508         // defaults
509         if (defaultPrecision == 0 || p == 0)
510             return;
511 
512         for (int t = 0; t < EbtNumTypes; ++t)
513             p[t] = defaultPrecision[t];
514     }
515 
516     void relateToOperator(const char* name, TOperator op);
517     void setFunctionExtensions(const char* name, int num, const char* const extensions[]);
518     void dump(TInfoSink &infoSink) const;
519     TSymbolTableLevel* clone() const;
520     void readOnly();
521 
setThisLevel()522     void setThisLevel() { thisLevel = true; }
isThisLevel()523     bool isThisLevel() const { return thisLevel; }
524 
525 protected:
526     explicit TSymbolTableLevel(TSymbolTableLevel&);
527     TSymbolTableLevel& operator=(TSymbolTableLevel&);
528 
529     typedef std::map<TString, TSymbol*, std::less<TString>, pool_allocator<std::pair<const TString, TSymbol*> > > tLevel;
530     typedef const tLevel::value_type tLevelPair;
531     typedef std::pair<tLevel::iterator, bool> tInsertResult;
532 
533     tLevel level;  // named mappings
534     TPrecisionQualifier *defaultPrecision;
535     int anonId;
536     bool thisLevel;  // True if this level of the symbol table is a structure scope containing member function
537                      // that are supposed to see anonymous access to member variables.
538 };
539 
540 class TSymbolTable {
541 public:
TSymbolTable()542     TSymbolTable() : uniqueId(0), noBuiltInRedeclarations(false), separateNameSpaces(false), adoptedLevels(0)
543     {
544         //
545         // This symbol table cannot be used until push() is called.
546         //
547     }
~TSymbolTable()548     ~TSymbolTable()
549     {
550         // this can be called explicitly; safest to code it so it can be called multiple times
551 
552         // don't deallocate levels passed in from elsewhere
553         while (table.size() > adoptedLevels)
554             pop(0);
555     }
556 
adoptLevels(TSymbolTable & symTable)557     void adoptLevels(TSymbolTable& symTable)
558     {
559         for (unsigned int level = 0; level < symTable.table.size(); ++level) {
560             table.push_back(symTable.table[level]);
561             ++adoptedLevels;
562         }
563         uniqueId = symTable.uniqueId;
564         noBuiltInRedeclarations = symTable.noBuiltInRedeclarations;
565         separateNameSpaces = symTable.separateNameSpaces;
566     }
567 
568     //
569     // While level adopting is generic, the methods below enact a the following
570     // convention for levels:
571     //   0: common built-ins shared across all stages, all compiles, only one copy for all symbol tables
572     //   1: per-stage built-ins, shared across all compiles, but a different copy per stage
573     //   2: built-ins specific to a compile, like resources that are context-dependent, or redeclared built-ins
574     //   3: user-shader globals
575     //
576 protected:
577     static const int globalLevel = 3;
isSharedLevel(int level)578     bool isSharedLevel(int level)  { return level <= 1; }              // exclude all per-compile levels
isBuiltInLevel(int level)579     bool isBuiltInLevel(int level) { return level <= 2; }              // exclude user globals
isGlobalLevel(int level)580     bool isGlobalLevel(int level)  { return level <= globalLevel; }    // include user globals
581 public:
isEmpty()582     bool isEmpty() { return table.size() == 0; }
atBuiltInLevel()583     bool atBuiltInLevel() { return isBuiltInLevel(currentLevel()); }
atGlobalLevel()584     bool atGlobalLevel()  { return isGlobalLevel(currentLevel()); }
585 
setNoBuiltInRedeclarations()586     void setNoBuiltInRedeclarations() { noBuiltInRedeclarations = true; }
setSeparateNameSpaces()587     void setSeparateNameSpaces() { separateNameSpaces = true; }
588 
push()589     void push()
590     {
591         table.push_back(new TSymbolTableLevel);
592     }
593 
594     // Make a new symbol-table level to represent the scope introduced by a structure
595     // containing member functions, such that the member functions can find anonymous
596     // references to member variables.
597     //
598     // 'thisSymbol' should have a name of "" to trigger anonymous structure-member
599     // symbol finds.
pushThis(TSymbol & thisSymbol)600     void pushThis(TSymbol& thisSymbol)
601     {
602         assert(thisSymbol.getName().size() == 0);
603         table.push_back(new TSymbolTableLevel);
604         table.back()->setThisLevel();
605         insert(thisSymbol);
606     }
607 
pop(TPrecisionQualifier * p)608     void pop(TPrecisionQualifier *p)
609     {
610         table[currentLevel()]->getPreviousDefaultPrecisions(p);
611         delete table.back();
612         table.pop_back();
613     }
614 
615     //
616     // Insert a visible symbol into the symbol table so it can
617     // be found later by name.
618     //
619     // Returns false if the was a name collision.
620     //
insert(TSymbol & symbol)621     bool insert(TSymbol& symbol)
622     {
623         symbol.setUniqueId(++uniqueId);
624 
625         // make sure there isn't a function of this variable name
626         if (! separateNameSpaces && ! symbol.getAsFunction() && table[currentLevel()]->hasFunctionName(symbol.getName()))
627             return false;
628 
629         // check for not overloading or redefining a built-in function
630         if (noBuiltInRedeclarations) {
631             if (atGlobalLevel() && currentLevel() > 0) {
632                 if (table[0]->hasFunctionName(symbol.getName()))
633                     return false;
634                 if (currentLevel() > 1 && table[1]->hasFunctionName(symbol.getName()))
635                     return false;
636             }
637         }
638 
639         return table[currentLevel()]->insert(symbol, separateNameSpaces);
640     }
641 
642     // Add more members to an already inserted aggregate object
amend(TSymbol & symbol,int firstNewMember)643     bool amend(TSymbol& symbol, int firstNewMember)
644     {
645         // See insert() for comments on basic explanation of insert.
646         // This operates similarly, but more simply.
647         return table[currentLevel()]->amend(symbol, firstNewMember);
648     }
649 
650     //
651     // To allocate an internal temporary, which will need to be uniquely
652     // identified by the consumer of the AST, but never need to
653     // found by doing a symbol table search by name, hence allowed an
654     // arbitrary name in the symbol with no worry of collision.
655     //
makeInternalVariable(TSymbol & symbol)656     void makeInternalVariable(TSymbol& symbol)
657     {
658         symbol.setUniqueId(++uniqueId);
659     }
660 
661     //
662     // Copy a variable or anonymous member's structure from a shared level so that
663     // it can be added (soon after return) to the symbol table where it can be
664     // modified without impacting other users of the shared table.
665     //
copyUpDeferredInsert(TSymbol * shared)666     TSymbol* copyUpDeferredInsert(TSymbol* shared)
667     {
668         if (shared->getAsVariable()) {
669             TSymbol* copy = shared->clone();
670             copy->setUniqueId(shared->getUniqueId());
671             return copy;
672         } else {
673             const TAnonMember* anon = shared->getAsAnonMember();
674             assert(anon);
675             TVariable* container = anon->getAnonContainer().clone();
676             container->changeName(NewPoolTString(""));
677             container->setUniqueId(anon->getAnonContainer().getUniqueId());
678             return container;
679         }
680     }
681 
copyUp(TSymbol * shared)682     TSymbol* copyUp(TSymbol* shared)
683     {
684         TSymbol* copy = copyUpDeferredInsert(shared);
685         table[globalLevel]->insert(*copy, separateNameSpaces);
686         if (shared->getAsVariable())
687             return copy;
688         else {
689             // return the copy of the anonymous member
690             return table[globalLevel]->find(shared->getName());
691         }
692     }
693 
694     // Normal find of a symbol, that can optionally say whether the symbol was found
695     // at a built-in level or the current top-scope level.
696     TSymbol* find(const TString& name, bool* builtIn = 0, bool* currentScope = 0, int* thisDepthP = 0)
697     {
698         int level = currentLevel();
699         TSymbol* symbol;
700         int thisDepth = 0;
701         do {
702             if (table[level]->isThisLevel())
703                 ++thisDepth;
704             symbol = table[level]->find(name);
705             --level;
706         } while (symbol == nullptr && level >= 0);
707         level++;
708         if (builtIn)
709             *builtIn = isBuiltInLevel(level);
710         if (currentScope)
711             *currentScope = isGlobalLevel(currentLevel()) || level == currentLevel();  // consider shared levels as "current scope" WRT user globals
712         if (thisDepthP != nullptr) {
713             if (! table[level]->isThisLevel())
714                 thisDepth = 0;
715             *thisDepthP = thisDepth;
716         }
717 
718         return symbol;
719     }
720 
721     // Find of a symbol that returns how many layers deep of nested
722     // structures-with-member-functions ('this' scopes) deep the symbol was
723     // found in.
find(const TString & name,int & thisDepth)724     TSymbol* find(const TString& name, int& thisDepth)
725     {
726         int level = currentLevel();
727         TSymbol* symbol;
728         thisDepth = 0;
729         do {
730             if (table[level]->isThisLevel())
731                 ++thisDepth;
732             symbol = table[level]->find(name);
733             --level;
734         } while (symbol == 0 && level >= 0);
735 
736         if (! table[level + 1]->isThisLevel())
737             thisDepth = 0;
738 
739         return symbol;
740     }
741 
isFunctionNameVariable(const TString & name)742     bool isFunctionNameVariable(const TString& name) const
743     {
744         if (separateNameSpaces)
745             return false;
746 
747         int level = currentLevel();
748         do {
749             bool variable;
750             bool found = table[level]->findFunctionVariableName(name, variable);
751             if (found)
752                 return variable;
753             --level;
754         } while (level >= 0);
755 
756         return false;
757     }
758 
findFunctionNameList(const TString & name,TVector<const TFunction * > & list,bool & builtIn)759     void findFunctionNameList(const TString& name, TVector<const TFunction*>& list, bool& builtIn)
760     {
761         // For user levels, return the set found in the first scope with a match
762         builtIn = false;
763         int level = currentLevel();
764         do {
765             table[level]->findFunctionNameList(name, list);
766             --level;
767         } while (list.empty() && level >= globalLevel);
768 
769         if (! list.empty())
770             return;
771 
772         // Gather across all built-in levels; they don't hide each other
773         builtIn = true;
774         do {
775             table[level]->findFunctionNameList(name, list);
776             --level;
777         } while (level >= 0);
778     }
779 
relateToOperator(const char * name,TOperator op)780     void relateToOperator(const char* name, TOperator op)
781     {
782         for (unsigned int level = 0; level < table.size(); ++level)
783             table[level]->relateToOperator(name, op);
784     }
785 
setFunctionExtensions(const char * name,int num,const char * const extensions[])786     void setFunctionExtensions(const char* name, int num, const char* const extensions[])
787     {
788         for (unsigned int level = 0; level < table.size(); ++level)
789             table[level]->setFunctionExtensions(name, num, extensions);
790     }
791 
setVariableExtensions(const char * name,int num,const char * const extensions[])792     void setVariableExtensions(const char* name, int num, const char* const extensions[])
793     {
794         TSymbol* symbol = find(TString(name));
795         if (symbol)
796             symbol->setExtensions(num, extensions);
797     }
798 
getMaxSymbolId()799     int getMaxSymbolId() { return uniqueId; }
800     void dump(TInfoSink &infoSink) const;
801     void copyTable(const TSymbolTable& copyOf);
802 
setPreviousDefaultPrecisions(TPrecisionQualifier * p)803     void setPreviousDefaultPrecisions(TPrecisionQualifier *p) { table[currentLevel()]->setPreviousDefaultPrecisions(p); }
804 
readOnly()805     void readOnly()
806     {
807         for (unsigned int level = 0; level < table.size(); ++level)
808             table[level]->readOnly();
809     }
810 
811 protected:
812     TSymbolTable(TSymbolTable&);
813     TSymbolTable& operator=(TSymbolTableLevel&);
814 
currentLevel()815     int currentLevel() const { return static_cast<int>(table.size()) - 1; }
816 
817     std::vector<TSymbolTableLevel*> table;
818     int uniqueId;     // for unique identification in code generation
819     bool noBuiltInRedeclarations;
820     bool separateNameSpaces;
821     unsigned int adoptedLevels;
822 };
823 
824 } // end namespace glslang
825 
826 #endif // _SYMBOL_TABLE_INCLUDED_
827