• 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 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     bool isSharedLevel(int level)  { return level <= 1; }              // exclude all per-compile levels
isBuiltInLevel(int level)617     bool isBuiltInLevel(int level) { return level <= 2; }              // exclude user globals
isGlobalLevel(int level)618     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()); }
623 
setNoBuiltInRedeclarations()624     void setNoBuiltInRedeclarations() { noBuiltInRedeclarations = true; }
setSeparateNameSpaces()625     void setSeparateNameSpaces() { separateNameSpaces = true; }
626 
push()627     void push()
628     {
629         table.push_back(new TSymbolTableLevel);
630     }
631 
632     // Make a new symbol-table level to represent the scope introduced by a structure
633     // containing member functions, such that the member functions can find anonymous
634     // references to member variables.
635     //
636     // 'thisSymbol' should have a name of "" to trigger anonymous structure-member
637     // symbol finds.
pushThis(TSymbol & thisSymbol)638     void pushThis(TSymbol& thisSymbol)
639     {
640         assert(thisSymbol.getName().size() == 0);
641         table.push_back(new TSymbolTableLevel);
642         table.back()->setThisLevel();
643         insert(thisSymbol);
644     }
645 
pop(TPrecisionQualifier * p)646     void pop(TPrecisionQualifier *p)
647     {
648         table[currentLevel()]->getPreviousDefaultPrecisions(p);
649         delete table.back();
650         table.pop_back();
651     }
652 
653     //
654     // Insert a visible symbol into the symbol table so it can
655     // be found later by name.
656     //
657     // Returns false if the was a name collision.
658     //
insert(TSymbol & symbol)659     bool insert(TSymbol& symbol)
660     {
661         symbol.setUniqueId(++uniqueId);
662 
663         // make sure there isn't a function of this variable name
664         if (! separateNameSpaces && ! symbol.getAsFunction() && table[currentLevel()]->hasFunctionName(symbol.getName()))
665             return false;
666 
667         // check for not overloading or redefining a built-in function
668         if (noBuiltInRedeclarations) {
669             if (atGlobalLevel() && currentLevel() > 0) {
670                 if (table[0]->hasFunctionName(symbol.getName()))
671                     return false;
672                 if (currentLevel() > 1 && table[1]->hasFunctionName(symbol.getName()))
673                     return false;
674             }
675         }
676 
677         return table[currentLevel()]->insert(symbol, separateNameSpaces);
678     }
679 
680     // Add more members to an already inserted aggregate object
amend(TSymbol & symbol,int firstNewMember)681     bool amend(TSymbol& symbol, int firstNewMember)
682     {
683         // See insert() for comments on basic explanation of insert.
684         // This operates similarly, but more simply.
685         return table[currentLevel()]->amend(symbol, firstNewMember);
686     }
687 
688     //
689     // To allocate an internal temporary, which will need to be uniquely
690     // identified by the consumer of the AST, but never need to
691     // found by doing a symbol table search by name, hence allowed an
692     // arbitrary name in the symbol with no worry of collision.
693     //
makeInternalVariable(TSymbol & symbol)694     void makeInternalVariable(TSymbol& symbol)
695     {
696         symbol.setUniqueId(++uniqueId);
697     }
698 
699     //
700     // Copy a variable or anonymous member's structure from a shared level so that
701     // it can be added (soon after return) to the symbol table where it can be
702     // modified without impacting other users of the shared table.
703     //
copyUpDeferredInsert(TSymbol * shared)704     TSymbol* copyUpDeferredInsert(TSymbol* shared)
705     {
706         if (shared->getAsVariable()) {
707             TSymbol* copy = shared->clone();
708             copy->setUniqueId(shared->getUniqueId());
709             return copy;
710         } else {
711             const TAnonMember* anon = shared->getAsAnonMember();
712             assert(anon);
713             TVariable* container = anon->getAnonContainer().clone();
714             container->changeName(NewPoolTString(""));
715             container->setUniqueId(anon->getAnonContainer().getUniqueId());
716             return container;
717         }
718     }
719 
copyUp(TSymbol * shared)720     TSymbol* copyUp(TSymbol* shared)
721     {
722         TSymbol* copy = copyUpDeferredInsert(shared);
723         table[globalLevel]->insert(*copy, separateNameSpaces);
724         if (shared->getAsVariable())
725             return copy;
726         else {
727             // return the copy of the anonymous member
728             return table[globalLevel]->find(shared->getName());
729         }
730     }
731 
732     // Normal find of a symbol, that can optionally say whether the symbol was found
733     // at a built-in level or the current top-scope level.
734     TSymbol* find(const TString& name, bool* builtIn = 0, bool* currentScope = 0, int* thisDepthP = 0)
735     {
736         int level = currentLevel();
737         TSymbol* symbol;
738         int thisDepth = 0;
739         do {
740             if (table[level]->isThisLevel())
741                 ++thisDepth;
742             symbol = table[level]->find(name);
743             --level;
744         } while (symbol == nullptr && level >= 0);
745         level++;
746         if (builtIn)
747             *builtIn = isBuiltInLevel(level);
748         if (currentScope)
749             *currentScope = isGlobalLevel(currentLevel()) || level == currentLevel();  // consider shared levels as "current scope" WRT user globals
750         if (thisDepthP != nullptr) {
751             if (! table[level]->isThisLevel())
752                 thisDepth = 0;
753             *thisDepthP = thisDepth;
754         }
755 
756         return symbol;
757     }
758 
759     // Find of a symbol that returns how many layers deep of nested
760     // structures-with-member-functions ('this' scopes) deep the symbol was
761     // found in.
find(const TString & name,int & thisDepth)762     TSymbol* find(const TString& name, int& thisDepth)
763     {
764         int level = currentLevel();
765         TSymbol* symbol;
766         thisDepth = 0;
767         do {
768             if (table[level]->isThisLevel())
769                 ++thisDepth;
770             symbol = table[level]->find(name);
771             --level;
772         } while (symbol == 0 && level >= 0);
773 
774         if (! table[level + 1]->isThisLevel())
775             thisDepth = 0;
776 
777         return symbol;
778     }
779 
isFunctionNameVariable(const TString & name)780     bool isFunctionNameVariable(const TString& name) const
781     {
782         if (separateNameSpaces)
783             return false;
784 
785         int level = currentLevel();
786         do {
787             bool variable;
788             bool found = table[level]->findFunctionVariableName(name, variable);
789             if (found)
790                 return variable;
791             --level;
792         } while (level >= 0);
793 
794         return false;
795     }
796 
findFunctionNameList(const TString & name,TVector<const TFunction * > & list,bool & builtIn)797     void findFunctionNameList(const TString& name, TVector<const TFunction*>& list, bool& builtIn)
798     {
799         // For user levels, return the set found in the first scope with a match
800         builtIn = false;
801         int level = currentLevel();
802         do {
803             table[level]->findFunctionNameList(name, list);
804             --level;
805         } while (list.empty() && level >= globalLevel);
806 
807         if (! list.empty())
808             return;
809 
810         // Gather across all built-in levels; they don't hide each other
811         builtIn = true;
812         do {
813             table[level]->findFunctionNameList(name, list);
814             --level;
815         } while (level >= 0);
816     }
817 
relateToOperator(const char * name,TOperator op)818     void relateToOperator(const char* name, TOperator op)
819     {
820         for (unsigned int level = 0; level < table.size(); ++level)
821             table[level]->relateToOperator(name, op);
822     }
823 
setFunctionExtensions(const char * name,int num,const char * const extensions[])824     void setFunctionExtensions(const char* name, int num, const char* const extensions[])
825     {
826         for (unsigned int level = 0; level < table.size(); ++level)
827             table[level]->setFunctionExtensions(name, num, extensions);
828     }
829 
setVariableExtensions(const char * name,int numExts,const char * const extensions[])830     void setVariableExtensions(const char* name, int numExts, const char* const extensions[])
831     {
832         TSymbol* symbol = find(TString(name));
833         if (symbol == nullptr)
834             return;
835 
836         symbol->setExtensions(numExts, extensions);
837     }
838 
setVariableExtensions(const char * blockName,const char * name,int numExts,const char * const extensions[])839     void setVariableExtensions(const char* blockName, const char* name, int numExts, const char* const extensions[])
840     {
841         TSymbol* symbol = find(TString(blockName));
842         if (symbol == nullptr)
843             return;
844         TVariable* variable = symbol->getAsVariable();
845         assert(variable != nullptr);
846 
847         const TTypeList& structure = *variable->getAsVariable()->getType().getStruct();
848         for (int member = 0; member < (int)structure.size(); ++member) {
849             if (structure[member].type->getFieldName().compare(name) == 0) {
850                 variable->setMemberExtensions(member, numExts, extensions);
851                 return;
852             }
853         }
854     }
855 
getMaxSymbolId()856     int getMaxSymbolId() { return uniqueId; }
857 #if !defined(GLSLANG_WEB) && !defined(GLSLANG_ANGLE)
858     void dump(TInfoSink& infoSink, bool complete = false) const;
859 #endif
860     void copyTable(const TSymbolTable& copyOf);
861 
setPreviousDefaultPrecisions(TPrecisionQualifier * p)862     void setPreviousDefaultPrecisions(TPrecisionQualifier *p) { table[currentLevel()]->setPreviousDefaultPrecisions(p); }
863 
readOnly()864     void readOnly()
865     {
866         for (unsigned int level = 0; level < table.size(); ++level)
867             table[level]->readOnly();
868     }
869 
870 protected:
871     TSymbolTable(TSymbolTable&);
872     TSymbolTable& operator=(TSymbolTableLevel&);
873 
currentLevel()874     int currentLevel() const { return static_cast<int>(table.size()) - 1; }
875 
876     std::vector<TSymbolTableLevel*> table;
877     int uniqueId;     // for unique identification in code generation
878     bool noBuiltInRedeclarations;
879     bool separateNameSpaces;
880     unsigned int adoptedLevels;
881 };
882 
883 } // end namespace glslang
884 
885 #endif // _SYMBOL_TABLE_INCLUDED_
886