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 typedef TVector<const char*> TExtensionList;
83 
84 class TSymbol {
85 public:
POOL_ALLOCATOR_NEW_DELETE(GetThreadPoolAllocator ())86     POOL_ALLOCATOR_NEW_DELETE(GetThreadPoolAllocator())
87     explicit TSymbol(const TString *n) :  name(n), extensions(0), writable(true) { }
88     virtual TSymbol* clone() const = 0;
~TSymbol()89     virtual ~TSymbol() { }  // rely on all symbol owned memory coming from the pool
90 
getName()91     virtual const TString& getName() const { return *name; }
changeName(const TString * newName)92     virtual void changeName(const TString* newName) { name = newName; }
addPrefix(const char * prefix)93     virtual void addPrefix(const char* prefix)
94     {
95         TString newName(prefix);
96         newName.append(*name);
97         changeName(NewPoolTString(newName.c_str()));
98     }
getMangledName()99     virtual const TString& getMangledName() const { return getName(); }
getAsFunction()100     virtual TFunction* getAsFunction() { return 0; }
getAsFunction()101     virtual const TFunction* getAsFunction() const { return 0; }
getAsVariable()102     virtual TVariable* getAsVariable() { return 0; }
getAsVariable()103     virtual const TVariable* getAsVariable() const { return 0; }
getAsAnonMember()104     virtual const TAnonMember* getAsAnonMember() const { return 0; }
105     virtual const TType& getType() const = 0;
106     virtual TType& getWritableType() = 0;
setUniqueId(int id)107     virtual void setUniqueId(int id) { uniqueId = id; }
getUniqueId()108     virtual int getUniqueId() const { return uniqueId; }
setExtensions(int numExts,const char * const exts[])109     virtual void setExtensions(int numExts, const char* const exts[])
110     {
111         assert(extensions == 0);
112         assert(numExts > 0);
113         extensions = NewPoolObject(extensions);
114         for (int e = 0; e < numExts; ++e)
115             extensions->push_back(exts[e]);
116     }
getNumExtensions()117     virtual int getNumExtensions() const { return extensions == nullptr ? 0 : (int)extensions->size(); }
getExtensions()118     virtual const char** getExtensions() const { return extensions->data(); }
119 
120 #if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
121     virtual void dump(TInfoSink& infoSink, bool complete = false) const = 0;
122     void dumpExtensions(TInfoSink& infoSink) const;
123 #endif
124 
isReadOnly()125     virtual bool isReadOnly() const { return ! writable; }
makeReadOnly()126     virtual void makeReadOnly() { writable = false; }
127 
128 protected:
129     explicit TSymbol(const TSymbol&);
130     TSymbol& operator=(const TSymbol&);
131 
132     const TString *name;
133     unsigned int uniqueId;      // For cross-scope comparing during code generation
134 
135     // For tracking what extensions must be present
136     // (don't use if correct version/profile is present).
137     TExtensionList* extensions; // an array of pointers to existing constant char strings
138 
139     //
140     // N.B.: Non-const functions that will be generally used should assert on this,
141     // to avoid overwriting shared symbol-table information.
142     //
143     bool writable;
144 };
145 
146 //
147 // Variable class, meaning a symbol that's not a function.
148 //
149 // There could be a separate class hierarchy for Constant variables;
150 // Only one of int, bool, or float, (or none) is correct for
151 // any particular use, but it's easy to do this way, and doesn't
152 // seem worth having separate classes, and "getConst" can't simply return
153 // different values for different types polymorphically, so this is
154 // just simple and pragmatic.
155 //
156 class TVariable : public TSymbol {
157 public:
158     TVariable(const TString *name, const TType& t, bool uT = false )
TSymbol(name)159         : TSymbol(name),
160           userType(uT),
161           constSubtree(nullptr),
162           memberExtensions(nullptr),
163           anonId(-1)
164         { type.shallowCopy(t); }
165     virtual TVariable* clone() const;
~TVariable()166     virtual ~TVariable() { }
167 
getAsVariable()168     virtual TVariable* getAsVariable() { return this; }
getAsVariable()169     virtual const TVariable* getAsVariable() const { return this; }
getType()170     virtual const TType& getType() const { return type; }
getWritableType()171     virtual TType& getWritableType() { assert(writable); return type; }
isUserType()172     virtual bool isUserType() const { return userType; }
getConstArray()173     virtual const TConstUnionArray& getConstArray() const { return constArray; }
getWritableConstArray()174     virtual TConstUnionArray& getWritableConstArray() { assert(writable); return constArray; }
setConstArray(const TConstUnionArray & array)175     virtual void setConstArray(const TConstUnionArray& array) { constArray = array; }
setConstSubtree(TIntermTyped * subtree)176     virtual void setConstSubtree(TIntermTyped* subtree) { constSubtree = subtree; }
getConstSubtree()177     virtual TIntermTyped* getConstSubtree() const { return constSubtree; }
setAnonId(int i)178     virtual void setAnonId(int i) { anonId = i; }
getAnonId()179     virtual int getAnonId() const { return anonId; }
180 
setMemberExtensions(int member,int numExts,const char * const exts[])181     virtual void setMemberExtensions(int member, int numExts, const char* const exts[])
182     {
183         assert(type.isStruct());
184         assert(numExts > 0);
185         if (memberExtensions == nullptr) {
186             memberExtensions = NewPoolObject(memberExtensions);
187             memberExtensions->resize(type.getStruct()->size());
188         }
189         for (int e = 0; e < numExts; ++e)
190             (*memberExtensions)[member].push_back(exts[e]);
191     }
hasMemberExtensions()192     virtual bool hasMemberExtensions() const { return memberExtensions != nullptr; }
getNumMemberExtensions(int member)193     virtual int getNumMemberExtensions(int member) const
194     {
195         return memberExtensions == nullptr ? 0 : (int)(*memberExtensions)[member].size();
196     }
getMemberExtensions(int member)197     virtual const char** getMemberExtensions(int member) const { return (*memberExtensions)[member].data(); }
198 
199 #if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
200     virtual void dump(TInfoSink& infoSink, bool complete = false) const;
201 #endif
202 
203 protected:
204     explicit TVariable(const TVariable&);
205     TVariable& operator=(const TVariable&);
206 
207     TType type;
208     bool userType;
209 
210     // we are assuming that Pool Allocator will free the memory allocated to unionArray
211     // when this object is destroyed
212 
213     TConstUnionArray constArray;               // for compile-time constant value
214     TIntermTyped* constSubtree;                // for specialization constant computation
215     TVector<TExtensionList>* memberExtensions; // per-member extension list, allocated only when needed
216     int anonId; // the ID used for anonymous blocks: TODO: see if uniqueId could serve a dual purpose
217 };
218 
219 //
220 // The function sub-class of symbols and the parser will need to
221 // share this definition of a function parameter.
222 //
223 struct TParameter {
224     TString *name;
225     TType* type;
226     TIntermTyped* defaultValue;
copyParamTParameter227     void copyParam(const TParameter& param)
228     {
229         if (param.name)
230             name = NewPoolTString(param.name->c_str());
231         else
232             name = 0;
233         type = param.type->clone();
234         defaultValue = param.defaultValue;
235     }
getDeclaredBuiltInTParameter236     TBuiltInVariable getDeclaredBuiltIn() const { return type->getQualifier().declaredBuiltIn; }
237 };
238 
239 //
240 // The function sub-class of a symbol.
241 //
242 class TFunction : public TSymbol {
243 public:
TFunction(TOperator o)244     explicit TFunction(TOperator o) :
245         TSymbol(0),
246         op(o),
247         defined(false), prototyped(false), implicitThis(false), illegalImplicitThis(false), defaultParamCount(0) { }
248     TFunction(const TString *name, const TType& retType, TOperator tOp = EOpNull) :
TSymbol(name)249         TSymbol(name),
250         mangledName(*name + '('),
251         op(tOp),
252         defined(false), prototyped(false), implicitThis(false), illegalImplicitThis(false), defaultParamCount(0)
253     {
254         returnType.shallowCopy(retType);
255         declaredBuiltIn = retType.getQualifier().builtIn;
256     }
257     virtual TFunction* clone() const override;
258     virtual ~TFunction();
259 
getAsFunction()260     virtual TFunction* getAsFunction() override { return this; }
getAsFunction()261     virtual const TFunction* getAsFunction() const override { return this; }
262 
263     // Install 'p' as the (non-'this') last parameter.
264     // Non-'this' parameters are reflected in both the list of parameters and the
265     // mangled name.
addParameter(TParameter & p)266     virtual void addParameter(TParameter& p)
267     {
268         assert(writable);
269         parameters.push_back(p);
270         p.type->appendMangledName(mangledName);
271 
272         if (p.defaultValue != nullptr)
273             defaultParamCount++;
274     }
275 
276     // Install 'this' as the first parameter.
277     // 'this' is reflected in the list of parameters, but not the mangled name.
addThisParameter(TType & type,const char * name)278     virtual void addThisParameter(TType& type, const char* name)
279     {
280         TParameter p = { NewPoolTString(name), new TType, nullptr };
281         p.type->shallowCopy(type);
282         parameters.insert(parameters.begin(), p);
283     }
284 
addPrefix(const char * prefix)285     virtual void addPrefix(const char* prefix) override
286     {
287         TSymbol::addPrefix(prefix);
288         mangledName.insert(0, prefix);
289     }
290 
removePrefix(const TString & prefix)291     virtual void removePrefix(const TString& prefix)
292     {
293         assert(mangledName.compare(0, prefix.size(), prefix) == 0);
294         mangledName.erase(0, prefix.size());
295     }
296 
getMangledName()297     virtual const TString& getMangledName() const override { return mangledName; }
getType()298     virtual const TType& getType() const override { return returnType; }
getDeclaredBuiltInType()299     virtual TBuiltInVariable getDeclaredBuiltInType() const { return declaredBuiltIn; }
getWritableType()300     virtual TType& getWritableType() override { return returnType; }
relateToOperator(TOperator o)301     virtual void relateToOperator(TOperator o) { assert(writable); op = o; }
getBuiltInOp()302     virtual TOperator getBuiltInOp() const { return op; }
setDefined()303     virtual void setDefined() { assert(writable); defined = true; }
isDefined()304     virtual bool isDefined() const { return defined; }
setPrototyped()305     virtual void setPrototyped() { assert(writable); prototyped = true; }
isPrototyped()306     virtual bool isPrototyped() const { return prototyped; }
setImplicitThis()307     virtual void setImplicitThis() { assert(writable); implicitThis = true; }
hasImplicitThis()308     virtual bool hasImplicitThis() const { return implicitThis; }
setIllegalImplicitThis()309     virtual void setIllegalImplicitThis() { assert(writable); illegalImplicitThis = true; }
hasIllegalImplicitThis()310     virtual bool hasIllegalImplicitThis() const { return illegalImplicitThis; }
311 
312     // Return total number of parameters
getParamCount()313     virtual int getParamCount() const { return static_cast<int>(parameters.size()); }
314     // Return number of parameters with default values.
getDefaultParamCount()315     virtual int getDefaultParamCount() const { return defaultParamCount; }
316     // Return number of fixed parameters (without default values)
getFixedParamCount()317     virtual int getFixedParamCount() const { return getParamCount() - getDefaultParamCount(); }
318 
319     virtual TParameter& operator[](int i) { assert(writable); return parameters[i]; }
320     virtual const TParameter& operator[](int i) const { return parameters[i]; }
321 
322 #if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
323     virtual void dump(TInfoSink& infoSink, bool complete = false) const override;
324 #endif
325 
326 protected:
327     explicit TFunction(const TFunction&);
328     TFunction& operator=(const TFunction&);
329 
330     typedef TVector<TParameter> TParamList;
331     TParamList parameters;
332     TType returnType;
333     TBuiltInVariable declaredBuiltIn;
334 
335     TString mangledName;
336     TOperator op;
337     bool defined;
338     bool prototyped;
339     bool implicitThis;         // True if this function is allowed to see all members of 'this'
340     bool illegalImplicitThis;  // True if this function is not supposed to have access to dynamic members of 'this',
341                                // even if it finds member variables in the symbol table.
342                                // This is important for a static member function that has member variables in scope,
343                                // but is not allowed to use them, or see hidden symbols instead.
344     int  defaultParamCount;
345 };
346 
347 //
348 // Members of anonymous blocks are a kind of TSymbol.  They are not hidden in
349 // the symbol table behind a container; rather they are visible and point to
350 // their anonymous container.  (The anonymous container is found through the
351 // member, not the other way around.)
352 //
353 class TAnonMember : public TSymbol {
354 public:
TAnonMember(const TString * n,unsigned int m,TVariable & a,int an)355     TAnonMember(const TString* n, unsigned int m, TVariable& a, int an) : TSymbol(n), anonContainer(a), memberNumber(m), anonId(an) { }
356     virtual TAnonMember* clone() const override;
~TAnonMember()357     virtual ~TAnonMember() { }
358 
getAsAnonMember()359     virtual const TAnonMember* getAsAnonMember() const override { return this; }
getAnonContainer()360     virtual const TVariable& getAnonContainer() const { return anonContainer; }
getMemberNumber()361     virtual unsigned int getMemberNumber() const { return memberNumber; }
362 
getType()363     virtual const TType& getType() const override
364     {
365         const TTypeList& types = *anonContainer.getType().getStruct();
366         return *types[memberNumber].type;
367     }
368 
getWritableType()369     virtual TType& getWritableType() override
370     {
371         assert(writable);
372         const TTypeList& types = *anonContainer.getType().getStruct();
373         return *types[memberNumber].type;
374     }
375 
setExtensions(int numExts,const char * const exts[])376     virtual void setExtensions(int numExts, const char* const exts[]) override
377     {
378         anonContainer.setMemberExtensions(memberNumber, numExts, exts);
379     }
getNumExtensions()380     virtual int getNumExtensions() const override { return anonContainer.getNumMemberExtensions(memberNumber); }
getExtensions()381     virtual const char** getExtensions() const override { return anonContainer.getMemberExtensions(memberNumber); }
382 
getAnonId()383     virtual int getAnonId() const { return anonId; }
384 #if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
385     virtual void dump(TInfoSink& infoSink, bool complete = false) const override;
386 #endif
387 
388 protected:
389     explicit TAnonMember(const TAnonMember&);
390     TAnonMember& operator=(const TAnonMember&);
391 
392     TVariable& anonContainer;
393     unsigned int memberNumber;
394     int anonId;
395 };
396 
397 class TSymbolTableLevel {
398 public:
POOL_ALLOCATOR_NEW_DELETE(GetThreadPoolAllocator ())399     POOL_ALLOCATOR_NEW_DELETE(GetThreadPoolAllocator())
400     TSymbolTableLevel() : defaultPrecision(0), anonId(0), thisLevel(false) { }
401     ~TSymbolTableLevel();
402 
insert(TSymbol & symbol,bool separateNameSpaces)403     bool insert(TSymbol& symbol, bool separateNameSpaces)
404     {
405         //
406         // returning true means symbol was added to the table with no semantic errors
407         //
408         const TString& name = symbol.getName();
409         if (name == "") {
410             symbol.getAsVariable()->setAnonId(anonId++);
411             // An empty name means an anonymous container, exposing its members to the external scope.
412             // Give it a name and insert its members in the symbol table, pointing to the container.
413             char buf[20];
414             snprintf(buf, 20, "%s%d", AnonymousPrefix, symbol.getAsVariable()->getAnonId());
415             symbol.changeName(NewPoolTString(buf));
416 
417             return insertAnonymousMembers(symbol, 0);
418         } else {
419             // Check for redefinition errors:
420             // - STL itself will tell us if there is a direct name collision, with name mangling, at this level
421             // - additionally, check for function-redefining-variable name collisions
422             const TString& insertName = symbol.getMangledName();
423             if (symbol.getAsFunction()) {
424                 // make sure there isn't a variable of this name
425                 if (! separateNameSpaces && level.find(name) != level.end())
426                     return false;
427 
428                 // insert, and whatever happens is okay
429                 level.insert(tLevelPair(insertName, &symbol));
430 
431                 return true;
432             } else
433                 return level.insert(tLevelPair(insertName, &symbol)).second;
434         }
435     }
436 
437     // Add more members to an already inserted aggregate object
amend(TSymbol & symbol,int firstNewMember)438     bool amend(TSymbol& symbol, int firstNewMember)
439     {
440         // See insert() for comments on basic explanation of insert.
441         // This operates similarly, but more simply.
442         // Only supporting amend of anonymous blocks so far.
443         if (IsAnonymous(symbol.getName()))
444             return insertAnonymousMembers(symbol, firstNewMember);
445         else
446             return false;
447     }
448 
insertAnonymousMembers(TSymbol & symbol,int firstMember)449     bool insertAnonymousMembers(TSymbol& symbol, int firstMember)
450     {
451         const TTypeList& types = *symbol.getAsVariable()->getType().getStruct();
452         for (unsigned int m = firstMember; m < types.size(); ++m) {
453             TAnonMember* member = new TAnonMember(&types[m].type->getFieldName(), m, *symbol.getAsVariable(), symbol.getAsVariable()->getAnonId());
454             if (! level.insert(tLevelPair(member->getMangledName(), member)).second)
455                 return false;
456         }
457 
458         return true;
459     }
460 
find(const TString & name)461     TSymbol* find(const TString& name) const
462     {
463         tLevel::const_iterator it = level.find(name);
464         if (it == level.end())
465             return 0;
466         else
467             return (*it).second;
468     }
469 
findFunctionNameList(const TString & name,TVector<const TFunction * > & list)470     void findFunctionNameList(const TString& name, TVector<const TFunction*>& list)
471     {
472         size_t parenAt = name.find_first_of('(');
473         TString base(name, 0, parenAt + 1);
474 
475         tLevel::const_iterator begin = level.lower_bound(base);
476         base[parenAt] = ')';  // assume ')' is lexically after '('
477         tLevel::const_iterator end = level.upper_bound(base);
478         for (tLevel::const_iterator it = begin; it != end; ++it)
479             list.push_back(it->second->getAsFunction());
480     }
481 
482     // See if there is already a function in the table having the given non-function-style name.
hasFunctionName(const TString & name)483     bool hasFunctionName(const TString& name) const
484     {
485         tLevel::const_iterator candidate = level.lower_bound(name);
486         if (candidate != level.end()) {
487             const TString& candidateName = (*candidate).first;
488             TString::size_type parenAt = candidateName.find_first_of('(');
489             if (parenAt != candidateName.npos && candidateName.compare(0, parenAt, name) == 0)
490 
491                 return true;
492         }
493 
494         return false;
495     }
496 
497     // See if there is a variable at this level having the given non-function-style name.
498     // Return true if name is found, and set variable to true if the name was a variable.
findFunctionVariableName(const TString & name,bool & variable)499     bool findFunctionVariableName(const TString& name, bool& variable) const
500     {
501         tLevel::const_iterator candidate = level.lower_bound(name);
502         if (candidate != level.end()) {
503             const TString& candidateName = (*candidate).first;
504             TString::size_type parenAt = candidateName.find_first_of('(');
505             if (parenAt == candidateName.npos) {
506                 // not a mangled name
507                 if (candidateName == name) {
508                     // found a variable name match
509                     variable = true;
510                     return true;
511                 }
512             } else {
513                 // a mangled name
514                 if (candidateName.compare(0, parenAt, name) == 0) {
515                     // found a function name match
516                     variable = false;
517                     return true;
518                 }
519             }
520         }
521 
522         return false;
523     }
524 
525     // Use this to do a lazy 'push' of precision defaults the first time
526     // a precision statement is seen in a new scope.  Leave it at 0 for
527     // when no push was needed.  Thus, it is not the current defaults,
528     // it is what to restore the defaults to when popping a level.
setPreviousDefaultPrecisions(const TPrecisionQualifier * p)529     void setPreviousDefaultPrecisions(const TPrecisionQualifier *p)
530     {
531         // can call multiple times at one scope, will only latch on first call,
532         // as we're tracking the previous scope's values, not the current values
533         if (defaultPrecision != 0)
534             return;
535 
536         defaultPrecision = new TPrecisionQualifier[EbtNumTypes];
537         for (int t = 0; t < EbtNumTypes; ++t)
538             defaultPrecision[t] = p[t];
539     }
540 
getPreviousDefaultPrecisions(TPrecisionQualifier * p)541     void getPreviousDefaultPrecisions(TPrecisionQualifier *p)
542     {
543         // can be called for table level pops that didn't set the
544         // defaults
545         if (defaultPrecision == 0 || p == 0)
546             return;
547 
548         for (int t = 0; t < EbtNumTypes; ++t)
549             p[t] = defaultPrecision[t];
550     }
551 
552     void relateToOperator(const char* name, TOperator op);
553     void setFunctionExtensions(const char* name, int num, const char* const extensions[]);
554 #if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
555     void dump(TInfoSink& infoSink, bool complete = false) const;
556 #endif
557     TSymbolTableLevel* clone() const;
558     void readOnly();
559 
setThisLevel()560     void setThisLevel() { thisLevel = true; }
isThisLevel()561     bool isThisLevel() const { return thisLevel; }
562 
563 protected:
564     explicit TSymbolTableLevel(TSymbolTableLevel&);
565     TSymbolTableLevel& operator=(TSymbolTableLevel&);
566 
567     typedef std::map<TString, TSymbol*, std::less<TString>, pool_allocator<std::pair<const TString, TSymbol*> > > tLevel;
568     typedef const tLevel::value_type tLevelPair;
569     typedef std::pair<tLevel::iterator, bool> tInsertResult;
570 
571     tLevel level;  // named mappings
572     TPrecisionQualifier *defaultPrecision;
573     int anonId;
574     bool thisLevel;  // True if this level of the symbol table is a structure scope containing member function
575                      // that are supposed to see anonymous access to member variables.
576 };
577 
578 class TSymbolTable {
579 public:
TSymbolTable()580     TSymbolTable() : uniqueId(0), noBuiltInRedeclarations(false), separateNameSpaces(false), adoptedLevels(0)
581     {
582         //
583         // This symbol table cannot be used until push() is called.
584         //
585     }
~TSymbolTable()586     ~TSymbolTable()
587     {
588         // this can be called explicitly; safest to code it so it can be called multiple times
589 
590         // don't deallocate levels passed in from elsewhere
591         while (table.size() > adoptedLevels)
592             pop(0);
593     }
594 
adoptLevels(TSymbolTable & symTable)595     void adoptLevels(TSymbolTable& symTable)
596     {
597         for (unsigned int level = 0; level < symTable.table.size(); ++level) {
598             table.push_back(symTable.table[level]);
599             ++adoptedLevels;
600         }
601         uniqueId = symTable.uniqueId;
602         noBuiltInRedeclarations = symTable.noBuiltInRedeclarations;
603         separateNameSpaces = symTable.separateNameSpaces;
604     }
605 
606     //
607     // While level adopting is generic, the methods below enact a the following
608     // convention for levels:
609     //   0: common built-ins shared across all stages, all compiles, only one copy for all symbol tables
610     //   1: per-stage built-ins, shared across all compiles, but a different copy per stage
611     //   2: built-ins specific to a compile, like resources that are context-dependent, or redeclared built-ins
612     //   3: user-shader globals
613     //
614 protected:
615     static const int globalLevel = 3;
isSharedLevel(int level)616     static bool isSharedLevel(int level)  { return level <= 1; }            // exclude all per-compile levels
isBuiltInLevel(int level)617     static bool isBuiltInLevel(int level) { return level <= 2; }            // exclude user globals
isGlobalLevel(int level)618     static bool isGlobalLevel(int level)  { return level <= globalLevel; }  // include user globals
619 public:
isEmpty()620     bool isEmpty() { return table.size() == 0; }
atBuiltInLevel()621     bool atBuiltInLevel() { return isBuiltInLevel(currentLevel()); }
atGlobalLevel()622     bool atGlobalLevel()  { return isGlobalLevel(currentLevel()); }
isBuiltInSymbol(int uniqueId)623     static bool isBuiltInSymbol(int uniqueId) {
624         int level = uniqueId >> LevelFlagBitOffset;
625         return isBuiltInLevel(level);
626     }
setNoBuiltInRedeclarations()627     void setNoBuiltInRedeclarations() { noBuiltInRedeclarations = true; }
setSeparateNameSpaces()628     void setSeparateNameSpaces() { separateNameSpaces = true; }
629 
push()630     void push()
631     {
632         table.push_back(new TSymbolTableLevel);
633         updateUniqueIdLevelFlag();
634     }
635 
636     // Make a new symbol-table level to represent the scope introduced by a structure
637     // containing member functions, such that the member functions can find anonymous
638     // references to member variables.
639     //
640     // 'thisSymbol' should have a name of "" to trigger anonymous structure-member
641     // symbol finds.
pushThis(TSymbol & thisSymbol)642     void pushThis(TSymbol& thisSymbol)
643     {
644         assert(thisSymbol.getName().size() == 0);
645         table.push_back(new TSymbolTableLevel);
646         updateUniqueIdLevelFlag();
647         table.back()->setThisLevel();
648         insert(thisSymbol);
649     }
650 
pop(TPrecisionQualifier * p)651     void pop(TPrecisionQualifier *p)
652     {
653         table[currentLevel()]->getPreviousDefaultPrecisions(p);
654         delete table.back();
655         table.pop_back();
656         updateUniqueIdLevelFlag();
657     }
658 
659     //
660     // Insert a visible symbol into the symbol table so it can
661     // be found later by name.
662     //
663     // Returns false if the was a name collision.
664     //
insert(TSymbol & symbol)665     bool insert(TSymbol& symbol)
666     {
667         symbol.setUniqueId(++uniqueId);
668 
669         // make sure there isn't a function of this variable name
670         if (! separateNameSpaces && ! symbol.getAsFunction() && table[currentLevel()]->hasFunctionName(symbol.getName()))
671             return false;
672 
673         // check for not overloading or redefining a built-in function
674         if (noBuiltInRedeclarations) {
675             if (atGlobalLevel() && currentLevel() > 0) {
676                 if (table[0]->hasFunctionName(symbol.getName()))
677                     return false;
678                 if (currentLevel() > 1 && table[1]->hasFunctionName(symbol.getName()))
679                     return false;
680             }
681         }
682 
683         return table[currentLevel()]->insert(symbol, separateNameSpaces);
684     }
685 
686     // Add more members to an already inserted aggregate object
amend(TSymbol & symbol,int firstNewMember)687     bool amend(TSymbol& symbol, int firstNewMember)
688     {
689         // See insert() for comments on basic explanation of insert.
690         // This operates similarly, but more simply.
691         return table[currentLevel()]->amend(symbol, firstNewMember);
692     }
693 
694     //
695     // To allocate an internal temporary, which will need to be uniquely
696     // identified by the consumer of the AST, but never need to
697     // found by doing a symbol table search by name, hence allowed an
698     // arbitrary name in the symbol with no worry of collision.
699     //
makeInternalVariable(TSymbol & symbol)700     void makeInternalVariable(TSymbol& symbol)
701     {
702         symbol.setUniqueId(++uniqueId);
703     }
704 
705     //
706     // Copy a variable or anonymous member's structure from a shared level so that
707     // it can be added (soon after return) to the symbol table where it can be
708     // modified without impacting other users of the shared table.
709     //
copyUpDeferredInsert(TSymbol * shared)710     TSymbol* copyUpDeferredInsert(TSymbol* shared)
711     {
712         if (shared->getAsVariable()) {
713             TSymbol* copy = shared->clone();
714             copy->setUniqueId(shared->getUniqueId());
715             return copy;
716         } else {
717             const TAnonMember* anon = shared->getAsAnonMember();
718             assert(anon);
719             TVariable* container = anon->getAnonContainer().clone();
720             container->changeName(NewPoolTString(""));
721             container->setUniqueId(anon->getAnonContainer().getUniqueId());
722             return container;
723         }
724     }
725 
copyUp(TSymbol * shared)726     TSymbol* copyUp(TSymbol* shared)
727     {
728         TSymbol* copy = copyUpDeferredInsert(shared);
729         table[globalLevel]->insert(*copy, separateNameSpaces);
730         if (shared->getAsVariable())
731             return copy;
732         else {
733             // return the copy of the anonymous member
734             return table[globalLevel]->find(shared->getName());
735         }
736     }
737 
738     // Normal find of a symbol, that can optionally say whether the symbol was found
739     // at a built-in level or the current top-scope level.
740     TSymbol* find(const TString& name, bool* builtIn = 0, bool* currentScope = 0, int* thisDepthP = 0)
741     {
742         int level = currentLevel();
743         TSymbol* symbol;
744         int thisDepth = 0;
745         do {
746             if (table[level]->isThisLevel())
747                 ++thisDepth;
748             symbol = table[level]->find(name);
749             --level;
750         } while (symbol == nullptr && level >= 0);
751         level++;
752         if (builtIn)
753             *builtIn = isBuiltInLevel(level);
754         if (currentScope)
755             *currentScope = isGlobalLevel(currentLevel()) || level == currentLevel();  // consider shared levels as "current scope" WRT user globals
756         if (thisDepthP != nullptr) {
757             if (! table[level]->isThisLevel())
758                 thisDepth = 0;
759             *thisDepthP = thisDepth;
760         }
761 
762         return symbol;
763     }
764 
765     // Find of a symbol that returns how many layers deep of nested
766     // structures-with-member-functions ('this' scopes) deep the symbol was
767     // found in.
find(const TString & name,int & thisDepth)768     TSymbol* find(const TString& name, int& thisDepth)
769     {
770         int level = currentLevel();
771         TSymbol* symbol;
772         thisDepth = 0;
773         do {
774             if (table[level]->isThisLevel())
775                 ++thisDepth;
776             symbol = table[level]->find(name);
777             --level;
778         } while (symbol == 0 && level >= 0);
779 
780         if (! table[level + 1]->isThisLevel())
781             thisDepth = 0;
782 
783         return symbol;
784     }
785 
isFunctionNameVariable(const TString & name)786     bool isFunctionNameVariable(const TString& name) const
787     {
788         if (separateNameSpaces)
789             return false;
790 
791         int level = currentLevel();
792         do {
793             bool variable;
794             bool found = table[level]->findFunctionVariableName(name, variable);
795             if (found)
796                 return variable;
797             --level;
798         } while (level >= 0);
799 
800         return false;
801     }
802 
findFunctionNameList(const TString & name,TVector<const TFunction * > & list,bool & builtIn)803     void findFunctionNameList(const TString& name, TVector<const TFunction*>& list, bool& builtIn)
804     {
805         // For user levels, return the set found in the first scope with a match
806         builtIn = false;
807         int level = currentLevel();
808         do {
809             table[level]->findFunctionNameList(name, list);
810             --level;
811         } while (list.empty() && level >= globalLevel);
812 
813         if (! list.empty())
814             return;
815 
816         // Gather across all built-in levels; they don't hide each other
817         builtIn = true;
818         do {
819             table[level]->findFunctionNameList(name, list);
820             --level;
821         } while (level >= 0);
822     }
823 
relateToOperator(const char * name,TOperator op)824     void relateToOperator(const char* name, TOperator op)
825     {
826         for (unsigned int level = 0; level < table.size(); ++level)
827             table[level]->relateToOperator(name, op);
828     }
829 
setFunctionExtensions(const char * name,int num,const char * const extensions[])830     void setFunctionExtensions(const char* name, int num, const char* const extensions[])
831     {
832         for (unsigned int level = 0; level < table.size(); ++level)
833             table[level]->setFunctionExtensions(name, num, extensions);
834     }
835 
setVariableExtensions(const char * name,int numExts,const char * const extensions[])836     void setVariableExtensions(const char* name, int numExts, const char* const extensions[])
837     {
838         TSymbol* symbol = find(TString(name));
839         if (symbol == nullptr)
840             return;
841 
842         symbol->setExtensions(numExts, extensions);
843     }
844 
setVariableExtensions(const char * blockName,const char * name,int numExts,const char * const extensions[])845     void setVariableExtensions(const char* blockName, const char* name, int numExts, const char* const extensions[])
846     {
847         TSymbol* symbol = find(TString(blockName));
848         if (symbol == nullptr)
849             return;
850         TVariable* variable = symbol->getAsVariable();
851         assert(variable != nullptr);
852 
853         const TTypeList& structure = *variable->getAsVariable()->getType().getStruct();
854         for (int member = 0; member < (int)structure.size(); ++member) {
855             if (structure[member].type->getFieldName().compare(name) == 0) {
856                 variable->setMemberExtensions(member, numExts, extensions);
857                 return;
858             }
859         }
860     }
861 
getMaxSymbolId()862     int getMaxSymbolId() { return uniqueId; }
863 #if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
864     void dump(TInfoSink& infoSink, bool complete = false) const;
865 #endif
866     void copyTable(const TSymbolTable& copyOf);
867 
setPreviousDefaultPrecisions(TPrecisionQualifier * p)868     void setPreviousDefaultPrecisions(TPrecisionQualifier *p) { table[currentLevel()]->setPreviousDefaultPrecisions(p); }
869 
readOnly()870     void readOnly()
871     {
872         for (unsigned int level = 0; level < table.size(); ++level)
873             table[level]->readOnly();
874     }
875 
876     // Add current level in the high-bits of unique id
updateUniqueIdLevelFlag()877     void updateUniqueIdLevelFlag() {
878         // clamp level to avoid overflow
879         uint32_t level = currentLevel() > 7 ? 7 : currentLevel();
880         uniqueId &= ((1 << LevelFlagBitOffset) - 1);
881         uniqueId |= (level << LevelFlagBitOffset);
882     }
883 
884 protected:
885     TSymbolTable(TSymbolTable&);
886     TSymbolTable& operator=(TSymbolTableLevel&);
887 
currentLevel()888     int currentLevel() const { return static_cast<int>(table.size()) - 1; }
889     static const uint32_t LevelFlagBitOffset = 28;
890     std::vector<TSymbolTableLevel*> table;
891     int uniqueId;     // for unique identification in code generation
892     bool noBuiltInRedeclarations;
893     bool separateNameSpaces;
894     unsigned int adoptedLevels;
895 };
896 
897 } // end namespace glslang
898 
899 #endif // _SYMBOL_TABLE_INCLUDED_
900