2 //Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
3 //Copyright (C) 2013 LunarG, Inc.
7 //Redistribution and use in source and binary forms, with or without
8 //modification, are permitted provided that the following conditions
11 // Redistributions of source code must retain the above copyright
12 // notice, this list of conditions and the following disclaimer.
14 // Redistributions in binary form must reproduce the above
15 // copyright notice, this list of conditions and the following
16 // disclaimer in the documentation and/or other materials provided
17 // with the distribution.
19 // Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20 // contributors may be used to endorse or promote products derived
21 // from this software without specific prior written permission.
23 //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 //"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 //LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26 //FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27 //COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28 //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29 //BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30 //LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31 //CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 //LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33 //ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34 //POSSIBILITY OF SUCH DAMAGE.
37 #ifndef _SYMBOL_TABLE_INCLUDED_
38 #define _SYMBOL_TABLE_INCLUDED_
41 // Symbol table for parsing. Has these design characteristics:
43 // * Same symbol table can be used to compile many shaders, to preserve
44 // effort of creating and loading with the large numbers of built-in
47 // --> This requires a copy mechanism, so initial pools used to create
48 // the shared information can be popped. Done through "clone"
51 // * Name mangling will be used to give each function a unique name
52 // so that symbol table lookups are never ambiguous. This allows
53 // a simpler symbol table structure.
55 // * Pushing and popping of scope, so symbol table will really be a stack
56 // of symbol tables. Searched from the top, with new inserts going into
59 // * Constants: Compile time constant symbols will keep their values
60 // in the symbol table. The parser can substitute constants at parse
61 // time, including doing constant folding and constant propagation.
63 // * No temporaries: Temporaries made from operations (+, --, .xy, etc.)
64 // are tracked in the intermediate representation, not the symbol table.
67 #include "../Include/Common.h"
68 #include "../Include/intermediate.h"
69 #include "../Include/InfoSink.h"
74 // Symbol base class. (Can build functions or variables out of these...)
83 POOL_ALLOCATOR_NEW_DELETE(GetThreadPoolAllocator())
84 explicit TSymbol(const TString *n) : name(n), numExtensions(0), extensions(0), writable(true) { }
85 virtual TSymbol* clone() const = 0;
86 virtual ~TSymbol() { } // rely on all symbol owned memory coming from the pool
88 virtual const TString& getName() const { return *name; }
89 virtual void changeName(const TString* newName) { name = newName; }
90 virtual const TString& getMangledName() const { return getName(); }
91 virtual TFunction* getAsFunction() { return 0; }
92 virtual const TFunction* getAsFunction() const { return 0; }
93 virtual TVariable* getAsVariable() { return 0; }
94 virtual const TVariable* getAsVariable() const { return 0; }
95 virtual const TAnonMember* getAsAnonMember() const { return 0; }
96 virtual const TType& getType() const = 0;
97 virtual TType& getWritableType() = 0;
98 virtual void setUniqueId(int id) { uniqueId = id; }
99 virtual int getUniqueId() const { return uniqueId; }
100 virtual void setExtensions(int num, const char* const exts[])
102 assert(extensions == 0);
105 extensions = NewPoolObject(exts[0], num);
106 for (int e = 0; e < num; ++e)
107 extensions[e] = exts[e];
109 virtual int getNumExtensions() const { return numExtensions; }
110 virtual const char** getExtensions() const { return extensions; }
111 virtual void dump(TInfoSink &infoSink) const = 0;
113 virtual bool isReadOnly() const { return ! writable; }
114 virtual void makeReadOnly() { writable = false; }
117 explicit TSymbol(const TSymbol&);
118 TSymbol& operator=(const TSymbol&);
121 unsigned int uniqueId; // For cross-scope comparing during code generation
123 // For tracking what extensions must be present
124 // (don't use if correct version/profile is present).
126 const char** extensions; // an array of pointers to existing constant char strings
129 // N.B.: Non-const functions that will be generally used should assert on this,
130 // to avoid overwriting shared symbol-table information.
136 // Variable class, meaning a symbol that's not a function.
138 // There could be a separate class heirarchy for Constant variables;
139 // Only one of int, bool, or float, (or none) is correct for
140 // any particular use, but it's easy to do this way, and doesn't
141 // seem worth having separate classes, and "getConst" can't simply return
142 // different values for different types polymorphically, so this is
143 // just simple and pragmatic.
145 class TVariable : public TSymbol {
147 TVariable(const TString *name, const TType& t, bool uT = false ) : TSymbol(name), userType(uT) { type.shallowCopy(t); }
148 virtual TVariable* clone() const;
149 virtual ~TVariable() { }
151 virtual TVariable* getAsVariable() { return this; }
152 virtual const TVariable* getAsVariable() const { return this; }
153 virtual const TType& getType() const { return type; }
154 virtual TType& getWritableType() { assert(writable); return type; }
155 virtual bool isUserType() const { return userType; }
156 virtual const TConstUnionArray& getConstArray() const { return unionArray; }
157 virtual void setConstArray(const TConstUnionArray& constArray) { unionArray = constArray; }
159 virtual void dump(TInfoSink &infoSink) const;
162 explicit TVariable(const TVariable&);
163 TVariable& operator=(const TVariable&);
167 // we are assuming that Pool Allocator will free the memory allocated to unionArray
168 // when this object is destroyed
169 TConstUnionArray unionArray;
173 // The function sub-class of symbols and the parser will need to
174 // share this definition of a function parameter.
179 void copyParam(const TParameter& param)
182 name = NewPoolTString(param.name->c_str());
185 type = param.type->clone();
190 // The function sub-class of a symbol.
192 class TFunction : public TSymbol {
194 explicit TFunction(TOperator o) :
197 defined(false), prototyped(false) { }
198 TFunction(const TString *name, const TType& retType, TOperator tOp = EOpNull) :
200 mangledName(*name + '('),
202 defined(false), prototyped(false) { returnType.shallowCopy(retType); }
203 virtual TFunction* clone() const;
204 virtual ~TFunction();
206 virtual TFunction* getAsFunction() { return this; }
207 virtual const TFunction* getAsFunction() const { return this; }
209 virtual void addParameter(TParameter& p)
212 parameters.push_back(p);
213 p.type->appendMangledName(mangledName);
216 virtual const TString& getMangledName() const { return mangledName; }
217 virtual const TType& getType() const { return returnType; }
218 virtual TType& getWritableType() { return returnType; }
219 virtual void relateToOperator(TOperator o) { assert(writable); op = o; }
220 virtual TOperator getBuiltInOp() const { return op; }
221 virtual void setDefined() { assert(writable); defined = true; }
222 virtual bool isDefined() const { return defined; }
223 virtual void setPrototyped() { assert(writable); prototyped = true; }
224 virtual bool isPrototyped() const { return prototyped; }
226 virtual int getParamCount() const { return static_cast<int>(parameters.size()); }
227 virtual TParameter& operator[](int i) { assert(writable); return parameters[i]; }
228 virtual const TParameter& operator[](int i) const { return parameters[i]; }
230 virtual void dump(TInfoSink &infoSink) const;
233 explicit TFunction(const TFunction&);
234 TFunction& operator=(const TFunction&);
236 typedef TVector<TParameter> TParamList;
237 TParamList parameters;
245 class TAnonMember : public TSymbol {
247 TAnonMember(const TString* n, unsigned int m, const TVariable& a, int an) : TSymbol(n), anonContainer(a), memberNumber(m), anonId(an) { }
248 virtual TAnonMember* clone() const;
249 virtual ~TAnonMember() { }
251 virtual const TAnonMember* getAsAnonMember() const { return this; }
252 virtual const TVariable& getAnonContainer() const { return anonContainer; }
253 virtual unsigned int getMemberNumber() const { return memberNumber; }
255 virtual const TType& getType() const
257 const TTypeList& types = *anonContainer.getType().getStruct();
258 return *types[memberNumber].type;
261 virtual TType& getWritableType()
264 const TTypeList& types = *anonContainer.getType().getStruct();
265 return *types[memberNumber].type;
268 virtual int getAnonId() const { return anonId; }
269 virtual void dump(TInfoSink &infoSink) const;
272 explicit TAnonMember(const TAnonMember&);
273 TAnonMember& operator=(const TAnonMember&);
275 const TVariable& anonContainer;
276 unsigned int memberNumber;
280 class TSymbolTableLevel {
282 POOL_ALLOCATOR_NEW_DELETE(GetThreadPoolAllocator())
283 TSymbolTableLevel() : defaultPrecision(0), anonId(0) { }
284 ~TSymbolTableLevel();
286 bool insert(TSymbol& symbol, bool separateNameSpaces)
289 // returning true means symbol was added to the table with no semantic errors
291 tInsertResult result;
292 const TString& name = symbol.getName();
294 // An empty name means an anonymous container, exposing its members to the external scope.
295 // Give it a name and insert its members in the symbol table, pointing to the container.
297 snprintf(buf, 20, "%s%d", AnonymousPrefix, anonId);
298 symbol.changeName(NewPoolTString(buf));
301 const TTypeList& types = *symbol.getAsVariable()->getType().getStruct();
302 for (unsigned int m = 0; m < types.size(); ++m) {
303 TAnonMember* member = new TAnonMember(&types[m].type->getFieldName(), m, *symbol.getAsVariable(), anonId);
304 result = level.insert(tLevelPair(member->getMangledName(), member));
313 // Check for redefinition errors:
314 // - STL itself will tell us if there is a direct name collision, with name mangling, at this level
315 // - additionally, check for function-redefining-variable name collisions
316 const TString& insertName = symbol.getMangledName();
317 if (symbol.getAsFunction()) {
318 // make sure there isn't a variable of this name
319 if (! separateNameSpaces && level.find(name) != level.end())
322 // insert, and whatever happens is okay
323 level.insert(tLevelPair(insertName, &symbol));
327 result = level.insert(tLevelPair(insertName, &symbol));
329 return result.second;
334 TSymbol* find(const TString& name) const
336 tLevel::const_iterator it = level.find(name);
337 if (it == level.end())
343 void findFunctionNameList(const TString& name, TVector<TFunction*>& list)
345 size_t parenAt = name.find_first_of('(');
346 TString base(name, 0, parenAt + 1);
348 tLevel::const_iterator begin = level.lower_bound(base);
349 base[parenAt] = ')'; // assume ')' is lexically after '('
350 tLevel::const_iterator end = level.upper_bound(base);
351 for (tLevel::const_iterator it = begin; it != end; ++it)
352 list.push_back(it->second->getAsFunction());
355 // See if there is already a function in the table having the given non-function-style name.
356 bool hasFunctionName(const TString& name) const
358 tLevel::const_iterator candidate = level.lower_bound(name);
359 if (candidate != level.end()) {
360 const TString& candidateName = (*candidate).first;
361 TString::size_type parenAt = candidateName.find_first_of('(');
362 if (parenAt != candidateName.npos && candidateName.compare(0, parenAt, name) == 0)
370 // See if there is a variable at this level having the given non-function-style name.
371 // Return true if name is found, and set variable to true if the name was a variable.
372 bool findFunctionVariableName(const TString& name, bool& variable) const
374 tLevel::const_iterator candidate = level.lower_bound(name);
375 if (candidate != level.end()) {
376 const TString& candidateName = (*candidate).first;
377 TString::size_type parenAt = candidateName.find_first_of('(');
378 if (parenAt == candidateName.npos) {
379 // not a mangled name
380 if (candidateName == name) {
381 // found a variable name match
387 if (candidateName.compare(0, parenAt, name) == 0) {
388 // found a function name match
398 // Use this to do a lazy 'push' of precision defaults the first time
399 // a precision statement is seen in a new scope. Leave it at 0 for
400 // when no push was needed. Thus, it is not the current defaults,
401 // it is what to restore the defaults to when popping a level.
402 void setPreviousDefaultPrecisions(const TPrecisionQualifier *p)
404 // can call multiple times at one scope, will only latch on first call,
405 // as we're tracking the previous scope's values, not the current values
406 if (defaultPrecision != 0)
409 defaultPrecision = new TPrecisionQualifier[EbtNumTypes];
410 for (int t = 0; t < EbtNumTypes; ++t)
411 defaultPrecision[t] = p[t];
414 void getPreviousDefaultPrecisions(TPrecisionQualifier *p)
416 // can be called for table level pops that didn't set the
418 if (defaultPrecision == 0 || p == 0)
421 for (int t = 0; t < EbtNumTypes; ++t)
422 p[t] = defaultPrecision[t];
425 void relateToOperator(const char* name, TOperator op);
426 void setFunctionExtensions(const char* name, int num, const char* const extensions[]);
427 void dump(TInfoSink &infoSink) const;
428 TSymbolTableLevel* clone() const;
432 explicit TSymbolTableLevel(TSymbolTableLevel&);
433 TSymbolTableLevel& operator=(TSymbolTableLevel&);
435 typedef std::map<TString, TSymbol*, std::less<TString>, pool_allocator<std::pair<const TString, TSymbol*> > > tLevel;
436 typedef const tLevel::value_type tLevelPair;
437 typedef std::pair<tLevel::iterator, bool> tInsertResult;
439 tLevel level; // named mappings
440 TPrecisionQualifier *defaultPrecision;
446 TSymbolTable() : uniqueId(0), noBuiltInRedeclarations(false), separateNameSpaces(false), adoptedLevels(0)
449 // This symbol table cannot be used until push() is called.
454 // this can be called explicitly; safest to code it so it can be called multiple times
456 // don't deallocate levels passed in from elsewhere
457 while (table.size() > adoptedLevels)
461 void adoptLevels(TSymbolTable& symTable)
463 for (unsigned int level = 0; level < symTable.table.size(); ++level) {
464 table.push_back(symTable.table[level]);
467 uniqueId = symTable.uniqueId;
468 noBuiltInRedeclarations = symTable.noBuiltInRedeclarations;
469 separateNameSpaces = symTable.separateNameSpaces;
473 // While level adopting is generic, the methods below enact a the following
474 // convention for levels:
475 // 0: common built-ins shared across all stages, all compiles, only one copy for all symbol tables
476 // 1: per-stage built-ins, shared across all compiles, but a different copy per stage
477 // 2: built-ins specific to a compile, like resources that are context-dependent, or redeclared built-ins
478 // 3: user-shader globals
481 static const int globalLevel = 3;
482 bool isSharedLevel(int level) { return level <= 1; } // exclude all per-compile levels
483 bool isBuiltInLevel(int level) { return level <= 2; } // exclude user globals
484 bool isGlobalLevel(int level) { return level <= globalLevel; } // include user globals
486 bool isEmpty() { return table.size() == 0; }
487 bool atBuiltInLevel() { return isBuiltInLevel(currentLevel()); }
488 bool atGlobalLevel() { return isGlobalLevel(currentLevel()); }
490 void setNoBuiltInRedeclarations() { noBuiltInRedeclarations = true; }
491 void setSeparateNameSpaces() { separateNameSpaces = true; }
495 table.push_back(new TSymbolTableLevel);
498 void pop(TPrecisionQualifier *p)
500 table[currentLevel()]->getPreviousDefaultPrecisions(p);
506 // Insert a visible symbol into the symbol table so it can
507 // be found later by name.
509 // Returns false if the was a name collision.
511 bool insert(TSymbol& symbol)
513 symbol.setUniqueId(++uniqueId);
515 // make sure there isn't a function of this variable name
516 if (! separateNameSpaces && ! symbol.getAsFunction() && table[currentLevel()]->hasFunctionName(symbol.getName()))
519 // check for not overloading or redefining a built-in function
520 if (noBuiltInRedeclarations) {
521 if (atGlobalLevel() && currentLevel() > 0) {
522 if (table[0]->hasFunctionName(symbol.getName()))
524 if (currentLevel() > 1 && table[1]->hasFunctionName(symbol.getName()))
529 return table[currentLevel()]->insert(symbol, separateNameSpaces);
533 // To allocate an internal temporary, which will need to be uniquely
534 // identified by the consumer of the AST, but never need to
535 // found by doing a symbol table search by name, hence allowed an
536 // arbitrary name in the symbol with no worry of collision.
538 void makeInternalVariable(TSymbol& symbol)
540 symbol.setUniqueId(++uniqueId);
544 // Copy a variable or anonymous member's structure from a shared level so that
545 // it can be added (soon after return) to the symbol table where it can be
546 // modified without impacting other users of the shared table.
548 TSymbol* copyUpDeferredInsert(TSymbol* shared)
550 if (shared->getAsVariable()) {
551 TSymbol* copy = shared->clone();
552 copy->setUniqueId(shared->getUniqueId());
555 const TAnonMember* anon = shared->getAsAnonMember();
557 TVariable* container = anon->getAnonContainer().clone();
558 container->changeName(NewPoolTString(""));
559 container->setUniqueId(anon->getAnonContainer().getUniqueId());
564 TSymbol* copyUp(TSymbol* shared)
566 TSymbol* copy = copyUpDeferredInsert(shared);
567 table[globalLevel]->insert(*copy, separateNameSpaces);
568 if (shared->getAsVariable())
571 // return the copy of the anonymous member
572 return table[globalLevel]->find(shared->getName());
576 TSymbol* find(const TString& name, bool* builtIn = 0, bool *currentScope = 0)
578 int level = currentLevel();
581 symbol = table[level]->find(name);
583 } while (symbol == 0 && level >= 0);
586 *builtIn = isBuiltInLevel(level);
588 *currentScope = isGlobalLevel(currentLevel()) || level == currentLevel(); // consider shared levels as "current scope" WRT user globals
593 bool isFunctionNameVariable(const TString& name) const
595 if (separateNameSpaces)
598 int level = currentLevel();
601 bool found = table[level]->findFunctionVariableName(name, variable);
605 } while (level >= 0);
610 void findFunctionNameList(const TString& name, TVector<TFunction*>& list, bool& builtIn)
612 // For user levels, return the set found in the first scope with a match
614 int level = currentLevel();
616 table[level]->findFunctionNameList(name, list);
618 } while (list.empty() && level >= globalLevel);
623 // Gather across all built-in levels; they don't hide each other
626 table[level]->findFunctionNameList(name, list);
628 } while (level >= 0);
631 void relateToOperator(const char* name, TOperator op)
633 for (unsigned int level = 0; level < table.size(); ++level)
634 table[level]->relateToOperator(name, op);
637 void setFunctionExtensions(const char* name, int num, const char* const extensions[])
639 for (unsigned int level = 0; level < table.size(); ++level)
640 table[level]->setFunctionExtensions(name, num, extensions);
643 void setVariableExtensions(const char* name, int num, const char* const extensions[])
645 TSymbol* symbol = find(TString(name));
647 symbol->setExtensions(num, extensions);
650 int getMaxSymbolId() { return uniqueId; }
651 void dump(TInfoSink &infoSink) const;
652 void copyTable(const TSymbolTable& copyOf);
654 void setPreviousDefaultPrecisions(TPrecisionQualifier *p) { table[currentLevel()]->setPreviousDefaultPrecisions(p); }
658 for (unsigned int level = 0; level < table.size(); ++level)
659 table[level]->readOnly();
663 TSymbolTable(TSymbolTable&);
664 TSymbolTable& operator=(TSymbolTableLevel&);
666 int currentLevel() const { return static_cast<int>(table.size()) - 1; }
668 std::vector<TSymbolTableLevel*> table;
669 int uniqueId; // for unique identification in code generation
670 bool noBuiltInRedeclarations;
671 bool separateNameSpaces;
672 unsigned int adoptedLevels;
675 } // end namespace glslang
677 #endif // _SYMBOL_TABLE_INCLUDED_