minor improvements to formating
[platform/upstream/glslang.git] / glslang / MachineIndependent / SymbolTable.cpp
1 //
2 // Copyright (C) 2002-2005  3Dlabs Inc. Ltd.
3 // Copyright (C) 2012-2013 LunarG, Inc.
4 // Copyright (C) 2017 ARM Limited.
5 // Copyright (C) 2015-2018 Google, Inc.
6 //
7 // All rights reserved.
8 //
9 // Redistribution and use in source and binary forms, with or without
10 // modification, are permitted provided that the following conditions
11 // are met:
12 //
13 //    Redistributions of source code must retain the above copyright
14 //    notice, this list of conditions and the following disclaimer.
15 //
16 //    Redistributions in binary form must reproduce the above
17 //    copyright notice, this list of conditions and the following
18 //    disclaimer in the documentation and/or other materials provided
19 //    with the distribution.
20 //
21 //    Neither the name of 3Dlabs Inc. Ltd. nor the names of its
22 //    contributors may be used to endorse or promote products derived
23 //    from this software without specific prior written permission.
24 //
25 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
28 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
29 // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
30 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
31 // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
32 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
33 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 // POSSIBILITY OF SUCH DAMAGE.
37 //
38
39 //
40 // Symbol table for parsing.  Most functionality and main ideas
41 // are documented in the header file.
42 //
43
44 #include "SymbolTable.h"
45
46 namespace glslang {
47
48 //
49 // TType helper function needs a place to live.
50 //
51
52 //
53 // Recursively generate mangled names.
54 //
55 void TType::buildMangledName(TString& mangledName) const
56 {
57     if (isMatrix())
58         mangledName += 'm';
59     else if (isVector())
60         mangledName += 'v';
61
62     switch (basicType) {
63     case EbtFloat:              mangledName += 'f';      break;
64     case EbtDouble:             mangledName += 'd';      break;
65     case EbtFloat16:            mangledName += "f16";    break;
66     case EbtInt:                mangledName += 'i';      break;
67     case EbtUint:               mangledName += 'u';      break;
68     case EbtInt8:               mangledName += "i8";     break;
69     case EbtUint8:              mangledName += "u8";     break;
70     case EbtInt16:              mangledName += "i16";    break;
71     case EbtUint16:             mangledName += "u16";    break;
72     case EbtInt64:              mangledName += "i64";    break;
73     case EbtUint64:             mangledName += "u64";    break;
74     case EbtBool:               mangledName += 'b';      break;
75     case EbtAtomicUint:         mangledName += "au";     break;
76 #ifdef NV_EXTENSIONS
77     case EbtAccStructNV:        mangledName += "asnv";   break;
78 #endif
79     case EbtSampler:
80         switch (sampler.type) {
81 #ifdef AMD_EXTENSIONS
82         case EbtFloat16: mangledName += "f16"; break;
83 #endif
84         case EbtInt:   mangledName += "i"; break;
85         case EbtUint:  mangledName += "u"; break;
86         default: break; // some compilers want this
87         }
88         if (sampler.image)
89             mangledName += "I";  // a normal image
90         else if (sampler.sampler)
91             mangledName += "p";  // a "pure" sampler
92         else if (!sampler.combined)
93             mangledName += "t";  // a "pure" texture
94         else
95             mangledName += "s";  // traditional combined sampler
96         if (sampler.arrayed)
97             mangledName += "A";
98         if (sampler.shadow)
99             mangledName += "S";
100         if (sampler.external)
101             mangledName += "E";
102         if (sampler.yuv)
103             mangledName += "Y";
104         switch (sampler.dim) {
105         case Esd1D:       mangledName += "1";  break;
106         case Esd2D:       mangledName += "2";  break;
107         case Esd3D:       mangledName += "3";  break;
108         case EsdCube:     mangledName += "C";  break;
109         case EsdRect:     mangledName += "R2"; break;
110         case EsdBuffer:   mangledName += "B";  break;
111         case EsdSubpass:  mangledName += "P";  break;
112         default: break; // some compilers want this
113         }
114
115         if (sampler.hasReturnStruct()) {
116             // Name mangle for sampler return struct uses struct table index.
117             mangledName += "-tx-struct";
118
119             char text[16]; // plenty enough space for the small integers.
120             snprintf(text, sizeof(text), "%d-", sampler.structReturnIndex);
121             mangledName += text;
122         } else {
123             switch (sampler.getVectorSize()) {
124             case 1: mangledName += "1"; break;
125             case 2: mangledName += "2"; break;
126             case 3: mangledName += "3"; break;
127             case 4: break; // default to prior name mangle behavior
128             }
129         }
130
131         if (sampler.ms)
132             mangledName += "M";
133         break;
134     case EbtStruct:
135     case EbtBlock:
136         if (basicType == EbtStruct)
137             mangledName += "struct-";
138         else
139             mangledName += "block-";
140         if (typeName)
141             mangledName += *typeName;
142         for (unsigned int i = 0; i < structure->size(); ++i) {
143             mangledName += '-';
144             (*structure)[i].type->buildMangledName(mangledName);
145         }
146     default:
147         break;
148     }
149
150     if (getVectorSize() > 0)
151         mangledName += static_cast<char>('0' + getVectorSize());
152     else {
153         mangledName += static_cast<char>('0' + getMatrixCols());
154         mangledName += static_cast<char>('0' + getMatrixRows());
155     }
156
157     if (arraySizes) {
158         const int maxSize = 11;
159         char buf[maxSize];
160         for (int i = 0; i < arraySizes->getNumDims(); ++i) {
161             if (arraySizes->getDimNode(i)) {
162                 if (arraySizes->getDimNode(i)->getAsSymbolNode())
163                     snprintf(buf, maxSize, "s%d", arraySizes->getDimNode(i)->getAsSymbolNode()->getId());
164                 else
165                     snprintf(buf, maxSize, "s%p", arraySizes->getDimNode(i));
166             } else
167                 snprintf(buf, maxSize, "%d", arraySizes->getDimSize(i));
168             mangledName += '[';
169             mangledName += buf;
170             mangledName += ']';
171         }
172     }
173 }
174
175 //
176 // Dump functions.
177 //
178
179 void TSymbol::dumpExtensions(TInfoSink &infoSink) const
180 {
181     int numExtensions = getNumExtensions();
182     if (numExtensions)
183     {
184         infoSink.debug << " <";
185         for (int i = 0; i < numExtensions; i++)
186         {
187             infoSink.debug << getExtensions()[i] << ",";
188         }
189         infoSink.debug << ">";
190     }
191 }
192
193 void TVariable::dump(TInfoSink &infoSink, bool complete) const
194 {
195     if (complete)
196     {
197         infoSink.debug << getName().c_str() << ": " << type.getCompleteString();
198         dumpExtensions(infoSink);
199     } else
200     {
201         infoSink.debug << getName().c_str() << ": " << type.getStorageQualifierString() << " "
202                        << type.getBasicTypeString();
203         if (type.isArray())
204         {
205             infoSink.debug << "[0]";
206         }
207     }
208
209     infoSink.debug << "\n";
210 }
211
212 void TFunction::dump(TInfoSink &infoSink, bool complete) const
213 {
214     if (complete)
215     {
216         infoSink.debug << getName().c_str() << ": " << returnType.getCompleteString() << " " << getName().c_str()
217                        << "(";
218         int numParams = getParamCount();
219         for (int i = 0; i < numParams; i++)
220         {
221             const TParameter &param = parameters[i];
222             infoSink.debug << param.type->getCompleteString() << " "
223                            << (param.name ? param.name->c_str() : "") << (i < numParams - 1 ? "," : "");
224         }
225         infoSink.debug << ")";
226         dumpExtensions(infoSink);
227     } else
228     {
229         infoSink.debug << getName().c_str() << ": " << returnType.getBasicTypeString() << " "
230                        << getMangledName().c_str() << "n";
231     }
232
233     infoSink.debug << "\n";
234 }
235
236 void TAnonMember::dump(TInfoSink &TInfoSink, bool complete) const
237 {
238     TInfoSink.debug << "anonymous member " << getMemberNumber() << " of " << getAnonContainer().getName().c_str()
239                     << "\n";
240 }
241
242 void TSymbolTableLevel::dump(TInfoSink &infoSink, bool complete) const
243 {
244     tLevel::const_iterator it;
245     for (it = level.begin(); it != level.end(); ++it)
246         (*it).second->dump(infoSink, complete);
247 }
248
249 void TSymbolTable::dump(TInfoSink &infoSink, bool complete) const
250 {
251     for (int level = currentLevel(); level >= 0; --level) {
252         infoSink.debug << "LEVEL " << level << "\n";
253         table[level]->dump(infoSink, complete);
254     }
255 }
256
257 //
258 // Functions have buried pointers to delete.
259 //
260 TFunction::~TFunction()
261 {
262     for (TParamList::iterator i = parameters.begin(); i != parameters.end(); ++i)
263         delete (*i).type;
264 }
265
266 //
267 // Symbol table levels are a map of pointers to symbols that have to be deleted.
268 //
269 TSymbolTableLevel::~TSymbolTableLevel()
270 {
271     for (tLevel::iterator it = level.begin(); it != level.end(); ++it)
272         delete (*it).second;
273
274     delete [] defaultPrecision;
275 }
276
277 //
278 // Change all function entries in the table with the non-mangled name
279 // to be related to the provided built-in operation.
280 //
281 void TSymbolTableLevel::relateToOperator(const char* name, TOperator op)
282 {
283     tLevel::const_iterator candidate = level.lower_bound(name);
284     while (candidate != level.end()) {
285         const TString& candidateName = (*candidate).first;
286         TString::size_type parenAt = candidateName.find_first_of('(');
287         if (parenAt != candidateName.npos && candidateName.compare(0, parenAt, name) == 0) {
288             TFunction* function = (*candidate).second->getAsFunction();
289             function->relateToOperator(op);
290         } else
291             break;
292         ++candidate;
293     }
294 }
295
296 // Make all function overloads of the given name require an extension(s).
297 // Should only be used for a version/profile that actually needs the extension(s).
298 void TSymbolTableLevel::setFunctionExtensions(const char* name, int num, const char* const extensions[])
299 {
300     tLevel::const_iterator candidate = level.lower_bound(name);
301     while (candidate != level.end()) {
302         const TString& candidateName = (*candidate).first;
303         TString::size_type parenAt = candidateName.find_first_of('(');
304         if (parenAt != candidateName.npos && candidateName.compare(0, parenAt, name) == 0) {
305             TSymbol* symbol = candidate->second;
306             symbol->setExtensions(num, extensions);
307         } else
308             break;
309         ++candidate;
310     }
311 }
312
313 //
314 // Make all symbols in this table level read only.
315 //
316 void TSymbolTableLevel::readOnly()
317 {
318     for (tLevel::iterator it = level.begin(); it != level.end(); ++it)
319         (*it).second->makeReadOnly();
320 }
321
322 //
323 // Copy a symbol, but the copy is writable; call readOnly() afterward if that's not desired.
324 //
325 TSymbol::TSymbol(const TSymbol& copyOf)
326 {
327     name = NewPoolTString(copyOf.name->c_str());
328     uniqueId = copyOf.uniqueId;
329     writable = true;
330 }
331
332 TVariable::TVariable(const TVariable& copyOf) : TSymbol(copyOf)
333 {
334     type.deepCopy(copyOf.type);
335     userType = copyOf.userType;
336
337     // we don't support specialization-constant subtrees in cloned tables, only extensions
338     constSubtree = nullptr;
339     extensions = nullptr;
340     memberExtensions = nullptr;
341     if (copyOf.getNumExtensions() > 0)
342         setExtensions(copyOf.getNumExtensions(), copyOf.getExtensions());
343     if (copyOf.hasMemberExtensions()) {
344         for (int m = 0; m < (int)copyOf.type.getStruct()->size(); ++m) {
345             if (copyOf.getNumMemberExtensions(m) > 0)
346                 setMemberExtensions(m, copyOf.getNumMemberExtensions(m), copyOf.getMemberExtensions(m));
347         }
348     }
349
350     if (! copyOf.constArray.empty()) {
351         assert(! copyOf.type.isStruct());
352         TConstUnionArray newArray(copyOf.constArray, 0, copyOf.constArray.size());
353         constArray = newArray;
354     }
355 }
356
357 TVariable* TVariable::clone() const
358 {
359     TVariable *variable = new TVariable(*this);
360
361     return variable;
362 }
363
364 TFunction::TFunction(const TFunction& copyOf) : TSymbol(copyOf)
365 {
366     for (unsigned int i = 0; i < copyOf.parameters.size(); ++i) {
367         TParameter param;
368         parameters.push_back(param);
369         parameters.back().copyParam(copyOf.parameters[i]);
370     }
371
372     extensions = nullptr;
373     if (copyOf.getNumExtensions() > 0)
374         setExtensions(copyOf.getNumExtensions(), copyOf.getExtensions());
375     returnType.deepCopy(copyOf.returnType);
376     mangledName = copyOf.mangledName;
377     op = copyOf.op;
378     defined = copyOf.defined;
379     prototyped = copyOf.prototyped;
380     implicitThis = copyOf.implicitThis;
381     illegalImplicitThis = copyOf.illegalImplicitThis;
382     defaultParamCount = copyOf.defaultParamCount;
383 }
384
385 TFunction* TFunction::clone() const
386 {
387     TFunction *function = new TFunction(*this);
388
389     return function;
390 }
391
392 TAnonMember* TAnonMember::clone() const
393 {
394     // Anonymous members of a given block should be cloned at a higher level,
395     // where they can all be assured to still end up pointing to a single
396     // copy of the original container.
397     assert(0);
398
399     return 0;
400 }
401
402 TSymbolTableLevel* TSymbolTableLevel::clone() const
403 {
404     TSymbolTableLevel *symTableLevel = new TSymbolTableLevel();
405     symTableLevel->anonId = anonId;
406     symTableLevel->thisLevel = thisLevel;
407     std::vector<bool> containerCopied(anonId, false);
408     tLevel::const_iterator iter;
409     for (iter = level.begin(); iter != level.end(); ++iter) {
410         const TAnonMember* anon = iter->second->getAsAnonMember();
411         if (anon) {
412             // Insert all the anonymous members of this same container at once,
413             // avoid inserting the remaining members in the future, once this has been done,
414             // allowing them to all be part of the same new container.
415             if (! containerCopied[anon->getAnonId()]) {
416                 TVariable* container = anon->getAnonContainer().clone();
417                 container->changeName(NewPoolTString(""));
418                 // insert the container and all its members
419                 symTableLevel->insert(*container, false);
420                 containerCopied[anon->getAnonId()] = true;
421             }
422         } else
423             symTableLevel->insert(*iter->second->clone(), false);
424     }
425
426     return symTableLevel;
427 }
428
429 void TSymbolTable::copyTable(const TSymbolTable& copyOf)
430 {
431     assert(adoptedLevels == copyOf.adoptedLevels);
432
433     uniqueId = copyOf.uniqueId;
434     noBuiltInRedeclarations = copyOf.noBuiltInRedeclarations;
435     separateNameSpaces = copyOf.separateNameSpaces;
436     for (unsigned int i = copyOf.adoptedLevels; i < copyOf.table.size(); ++i)
437         table.push_back(copyOf.table[i]->clone());
438 }
439
440 } // end namespace glslang