OSDN Git Service

Moved function creation code from glslang.y to TParseContext.
[android-x86/external-swiftshader.git] / src / OpenGL / compiler / ParseHelper.cpp
1 //
2 // Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
5 //
6
7 #include "ParseHelper.h"
8
9 #include <stdarg.h>
10 #include <stdio.h>
11
12 #include "glslang.h"
13 #include "preprocessor/SourceLocation.h"
14 #include "ValidateGlobalInitializer.h"
15 #include "ValidateSwitch.h"
16
17 ///////////////////////////////////////////////////////////////////////
18 //
19 // Sub- vector and matrix fields
20 //
21 ////////////////////////////////////////////////////////////////////////
22
23 //
24 // Look at a '.' field selector string and change it into offsets
25 // for a vector.
26 //
27 bool TParseContext::parseVectorFields(const TString& compString, int vecSize, TVectorFields& fields, const TSourceLoc &line)
28 {
29     fields.num = (int) compString.size();
30     if (fields.num > 4) {
31         error(line, "illegal vector field selection", compString.c_str());
32         return false;
33     }
34
35     enum {
36         exyzw,
37         ergba,
38         estpq
39     } fieldSet[4];
40
41     for (int i = 0; i < fields.num; ++i) {
42         switch (compString[i])  {
43         case 'x':
44             fields.offsets[i] = 0;
45             fieldSet[i] = exyzw;
46             break;
47         case 'r':
48             fields.offsets[i] = 0;
49             fieldSet[i] = ergba;
50             break;
51         case 's':
52             fields.offsets[i] = 0;
53             fieldSet[i] = estpq;
54             break;
55         case 'y':
56             fields.offsets[i] = 1;
57             fieldSet[i] = exyzw;
58             break;
59         case 'g':
60             fields.offsets[i] = 1;
61             fieldSet[i] = ergba;
62             break;
63         case 't':
64             fields.offsets[i] = 1;
65             fieldSet[i] = estpq;
66             break;
67         case 'z':
68             fields.offsets[i] = 2;
69             fieldSet[i] = exyzw;
70             break;
71         case 'b':
72             fields.offsets[i] = 2;
73             fieldSet[i] = ergba;
74             break;
75         case 'p':
76             fields.offsets[i] = 2;
77             fieldSet[i] = estpq;
78             break;
79         case 'w':
80             fields.offsets[i] = 3;
81             fieldSet[i] = exyzw;
82             break;
83         case 'a':
84             fields.offsets[i] = 3;
85             fieldSet[i] = ergba;
86             break;
87         case 'q':
88             fields.offsets[i] = 3;
89             fieldSet[i] = estpq;
90             break;
91         default:
92             error(line, "illegal vector field selection", compString.c_str());
93             return false;
94         }
95     }
96
97     for (int i = 0; i < fields.num; ++i) {
98         if (fields.offsets[i] >= vecSize) {
99             error(line, "vector field selection out of range",  compString.c_str());
100             return false;
101         }
102
103         if (i > 0) {
104             if (fieldSet[i] != fieldSet[i-1]) {
105                 error(line, "illegal - vector component fields not from the same set", compString.c_str());
106                 return false;
107             }
108         }
109     }
110
111     return true;
112 }
113
114
115 //
116 // Look at a '.' field selector string and change it into offsets
117 // for a matrix.
118 //
119 bool TParseContext::parseMatrixFields(const TString& compString, int matCols, int matRows, TMatrixFields& fields, const TSourceLoc &line)
120 {
121     fields.wholeRow = false;
122     fields.wholeCol = false;
123     fields.row = -1;
124     fields.col = -1;
125
126     if (compString.size() != 2) {
127         error(line, "illegal length of matrix field selection", compString.c_str());
128         return false;
129     }
130
131     if (compString[0] == '_') {
132         if (compString[1] < '0' || compString[1] > '3') {
133             error(line, "illegal matrix field selection", compString.c_str());
134             return false;
135         }
136         fields.wholeCol = true;
137         fields.col = compString[1] - '0';
138     } else if (compString[1] == '_') {
139         if (compString[0] < '0' || compString[0] > '3') {
140             error(line, "illegal matrix field selection", compString.c_str());
141             return false;
142         }
143         fields.wholeRow = true;
144         fields.row = compString[0] - '0';
145     } else {
146         if (compString[0] < '0' || compString[0] > '3' ||
147             compString[1] < '0' || compString[1] > '3') {
148             error(line, "illegal matrix field selection", compString.c_str());
149             return false;
150         }
151         fields.row = compString[0] - '0';
152         fields.col = compString[1] - '0';
153     }
154
155     if (fields.row >= matRows || fields.col >= matCols) {
156         error(line, "matrix field selection out of range", compString.c_str());
157         return false;
158     }
159
160     return true;
161 }
162
163 ///////////////////////////////////////////////////////////////////////
164 //
165 // Errors
166 //
167 ////////////////////////////////////////////////////////////////////////
168
169 //
170 // Track whether errors have occurred.
171 //
172 void TParseContext::recover()
173 {
174 }
175
176 //
177 // Used by flex/bison to output all syntax and parsing errors.
178 //
179 void TParseContext::error(const TSourceLoc& loc,
180                           const char* reason, const char* token,
181                           const char* extraInfo)
182 {
183     pp::SourceLocation srcLoc;
184     DecodeSourceLoc(loc, &srcLoc.file, &srcLoc.line);
185     mDiagnostics.writeInfo(pp::Diagnostics::PP_ERROR,
186                            srcLoc, reason, token, extraInfo);
187
188 }
189
190 void TParseContext::warning(const TSourceLoc& loc,
191                             const char* reason, const char* token,
192                             const char* extraInfo) {
193     pp::SourceLocation srcLoc;
194     DecodeSourceLoc(loc, &srcLoc.file, &srcLoc.line);
195     mDiagnostics.writeInfo(pp::Diagnostics::PP_WARNING,
196                            srcLoc, reason, token, extraInfo);
197 }
198
199 void TParseContext::trace(const char* str)
200 {
201     mDiagnostics.writeDebug(str);
202 }
203
204 //
205 // Same error message for all places assignments don't work.
206 //
207 void TParseContext::assignError(const TSourceLoc &line, const char* op, TString left, TString right)
208 {
209     std::stringstream extraInfoStream;
210     extraInfoStream << "cannot convert from '" << right << "' to '" << left << "'";
211     std::string extraInfo = extraInfoStream.str();
212     error(line, "", op, extraInfo.c_str());
213 }
214
215 //
216 // Same error message for all places unary operations don't work.
217 //
218 void TParseContext::unaryOpError(const TSourceLoc &line, const char* op, TString operand)
219 {
220     std::stringstream extraInfoStream;
221     extraInfoStream << "no operation '" << op << "' exists that takes an operand of type " << operand
222                     << " (or there is no acceptable conversion)";
223     std::string extraInfo = extraInfoStream.str();
224     error(line, " wrong operand type", op, extraInfo.c_str());
225 }
226
227 //
228 // Same error message for all binary operations don't work.
229 //
230 void TParseContext::binaryOpError(const TSourceLoc &line, const char* op, TString left, TString right)
231 {
232     std::stringstream extraInfoStream;
233     extraInfoStream << "no operation '" << op << "' exists that takes a left-hand operand of type '" << left 
234                     << "' and a right operand of type '" << right << "' (or there is no acceptable conversion)";
235     std::string extraInfo = extraInfoStream.str();
236     error(line, " wrong operand types ", op, extraInfo.c_str());
237 }
238
239 bool TParseContext::precisionErrorCheck(const TSourceLoc &line, TPrecision precision, TBasicType type){
240     if (!mChecksPrecisionErrors)
241         return false;
242     switch( type ){
243     case EbtFloat:
244         if( precision == EbpUndefined ){
245             error( line, "No precision specified for (float)", "" );
246             return true;
247         }
248         break;
249     case EbtInt:
250         if( precision == EbpUndefined ){
251             error( line, "No precision specified (int)", "" );
252             return true;
253         }
254         break;
255     default:
256         return false;
257     }
258     return false;
259 }
260
261 //
262 // Both test and if necessary, spit out an error, to see if the node is really
263 // an l-value that can be operated on this way.
264 //
265 // Returns true if the was an error.
266 //
267 bool TParseContext::lValueErrorCheck(const TSourceLoc &line, const char* op, TIntermTyped* node)
268 {
269     TIntermSymbol* symNode = node->getAsSymbolNode();
270     TIntermBinary* binaryNode = node->getAsBinaryNode();
271
272     if (binaryNode) {
273         bool errorReturn;
274
275         switch(binaryNode->getOp()) {
276         case EOpIndexDirect:
277         case EOpIndexIndirect:
278         case EOpIndexDirectStruct:
279             return lValueErrorCheck(line, op, binaryNode->getLeft());
280         case EOpVectorSwizzle:
281             errorReturn = lValueErrorCheck(line, op, binaryNode->getLeft());
282             if (!errorReturn) {
283                 int offset[4] = {0,0,0,0};
284
285                 TIntermTyped* rightNode = binaryNode->getRight();
286                 TIntermAggregate *aggrNode = rightNode->getAsAggregate();
287
288                 for (TIntermSequence::iterator p = aggrNode->getSequence().begin();
289                                                p != aggrNode->getSequence().end(); p++) {
290                     int value = (*p)->getAsTyped()->getAsConstantUnion()->getIConst(0);
291                     offset[value]++;
292                     if (offset[value] > 1) {
293                         error(line, " l-value of swizzle cannot have duplicate components", op);
294
295                         return true;
296                     }
297                 }
298             }
299
300             return errorReturn;
301         default:
302             break;
303         }
304         error(line, " l-value required", op);
305
306         return true;
307     }
308
309
310     const char* symbol = 0;
311     if (symNode != 0)
312         symbol = symNode->getSymbol().c_str();
313
314     const char* message = 0;
315     switch (node->getQualifier()) {
316     case EvqConstExpr:      message = "can't modify a const";        break;
317     case EvqConstReadOnly:  message = "can't modify a const";        break;
318     case EvqAttribute:      message = "can't modify an attribute";   break;
319     case EvqFragmentIn:     message = "can't modify an input";       break;
320     case EvqVertexIn:       message = "can't modify an input";       break;
321     case EvqUniform:        message = "can't modify a uniform";      break;
322     case EvqSmoothIn:
323     case EvqFlatIn:
324     case EvqCentroidIn:
325     case EvqVaryingIn:      message = "can't modify a varying";      break;
326     case EvqInput:          message = "can't modify an input";       break;
327     case EvqFragCoord:      message = "can't modify gl_FragCoord";   break;
328     case EvqFrontFacing:    message = "can't modify gl_FrontFacing"; break;
329     case EvqPointCoord:     message = "can't modify gl_PointCoord";  break;
330     case EvqInstanceID:     message = "can't modify gl_InstanceID";  break;
331     default:
332
333         //
334         // Type that can't be written to?
335         //
336         if(IsSampler(node->getBasicType()))
337         {
338             message = "can't modify a sampler";
339         }
340         else if(node->getBasicType() == EbtVoid)
341         {
342             message = "can't modify void";
343         }
344     }
345
346     if (message == 0 && binaryNode == 0 && symNode == 0) {
347         error(line, " l-value required", op);
348
349         return true;
350     }
351
352
353     //
354     // Everything else is okay, no error.
355     //
356     if (message == 0)
357         return false;
358
359     //
360     // If we get here, we have an error and a message.
361     //
362     if (symNode) {
363         std::stringstream extraInfoStream;
364         extraInfoStream << "\"" << symbol << "\" (" << message << ")";
365         std::string extraInfo = extraInfoStream.str();
366         error(line, " l-value required", op, extraInfo.c_str());
367     }
368     else {
369         std::stringstream extraInfoStream;
370         extraInfoStream << "(" << message << ")";
371         std::string extraInfo = extraInfoStream.str();
372         error(line, " l-value required", op, extraInfo.c_str());
373     }
374
375     return true;
376 }
377
378 //
379 // Both test, and if necessary spit out an error, to see if the node is really
380 // a constant.
381 //
382 // Returns true if the was an error.
383 //
384 bool TParseContext::constErrorCheck(TIntermTyped* node)
385 {
386     if (node->getQualifier() == EvqConstExpr)
387         return false;
388
389     error(node->getLine(), "constant expression required", "");
390
391     return true;
392 }
393
394 //
395 // Both test, and if necessary spit out an error, to see if the node is really
396 // an integer.
397 //
398 // Returns true if the was an error.
399 //
400 bool TParseContext::integerErrorCheck(TIntermTyped* node, const char* token)
401 {
402     if (node->isScalarInt())
403         return false;
404
405     error(node->getLine(), "integer expression required", token);
406
407     return true;
408 }
409
410 //
411 // Both test, and if necessary spit out an error, to see if we are currently
412 // globally scoped.
413 //
414 // Returns true if the was an error.
415 //
416 bool TParseContext::globalErrorCheck(const TSourceLoc &line, bool global, const char* token)
417 {
418     if (global)
419         return false;
420
421     error(line, "only allowed at global scope", token);
422
423     return true;
424 }
425
426 //
427 // For now, keep it simple:  if it starts "gl_", it's reserved, independent
428 // of scope.  Except, if the symbol table is at the built-in push-level,
429 // which is when we are parsing built-ins.
430 // Also checks for "webgl_" and "_webgl_" reserved identifiers if parsing a
431 // webgl shader.
432 //
433 // Returns true if there was an error.
434 //
435 bool TParseContext::reservedErrorCheck(const TSourceLoc &line, const TString& identifier)
436 {
437     static const char* reservedErrMsg = "reserved built-in name";
438     if (!symbolTable.atBuiltInLevel()) {
439         if (identifier.compare(0, 3, "gl_") == 0) {
440             error(line, reservedErrMsg, "gl_");
441             return true;
442         }
443         if (identifier.find("__") != TString::npos) {
444             error(line, "identifiers containing two consecutive underscores (__) are reserved as possible future keywords", identifier.c_str());
445             return true;
446         }
447     }
448
449     return false;
450 }
451
452 //
453 // Make sure there is enough data provided to the constructor to build
454 // something of the type of the constructor.  Also returns the type of
455 // the constructor.
456 //
457 // Returns true if there was an error in construction.
458 //
459 bool TParseContext::constructorErrorCheck(const TSourceLoc &line, TIntermNode* node, TFunction& function, TOperator op, TType* type)
460 {
461     *type = function.getReturnType();
462
463     bool constructingMatrix = false;
464     switch(op) {
465     case EOpConstructMat2:
466     case EOpConstructMat2x3:
467     case EOpConstructMat2x4:
468     case EOpConstructMat3x2:
469     case EOpConstructMat3:
470     case EOpConstructMat3x4:
471     case EOpConstructMat4x2:
472     case EOpConstructMat4x3:
473     case EOpConstructMat4:
474         constructingMatrix = true;
475         break;
476     default:
477         break;
478     }
479
480     //
481     // Note: It's okay to have too many components available, but not okay to have unused
482     // arguments.  'full' will go to true when enough args have been seen.  If we loop
483     // again, there is an extra argument, so 'overfull' will become true.
484     //
485
486     int size = 0;
487     bool constType = true;
488     bool full = false;
489     bool overFull = false;
490     bool matrixInMatrix = false;
491     bool arrayArg = false;
492     for (size_t i = 0; i < function.getParamCount(); ++i) {
493         const TParameter& param = function.getParam(i);
494         size += param.type->getObjectSize();
495
496         if (constructingMatrix && param.type->isMatrix())
497             matrixInMatrix = true;
498         if (full)
499             overFull = true;
500         if (op != EOpConstructStruct && !type->isArray() && size >= type->getObjectSize())
501             full = true;
502         if (param.type->getQualifier() != EvqConstExpr)
503             constType = false;
504         if (param.type->isArray())
505             arrayArg = true;
506     }
507
508     if (constType)
509         type->setQualifier(EvqConstExpr);
510
511     if(type->isArray()) {
512         if(type->getArraySize() == 0) {
513             type->setArraySize(function.getParamCount());
514         } else if(type->getArraySize() != function.getParamCount()) {
515             error(line, "array constructor needs one argument per array element", "constructor");
516             return true;
517         }
518     }
519
520     if (arrayArg && op != EOpConstructStruct) {
521         error(line, "constructing from a non-dereferenced array", "constructor");
522         return true;
523     }
524
525     if (matrixInMatrix && !type->isArray()) {
526         if (function.getParamCount() != 1) {
527           error(line, "constructing matrix from matrix can only take one argument", "constructor");
528           return true;
529         }
530     }
531
532     if (overFull) {
533         error(line, "too many arguments", "constructor");
534         return true;
535     }
536
537     if (op == EOpConstructStruct && !type->isArray() && int(type->getStruct()->fields().size()) != function.getParamCount()) {
538         error(line, "Number of constructor parameters does not match the number of structure fields", "constructor");
539         return true;
540     }
541
542     if (!type->isMatrix() || !matrixInMatrix) {
543         if ((op != EOpConstructStruct && size != 1 && size < type->getObjectSize()) ||
544             (op == EOpConstructStruct && size < type->getObjectSize())) {
545             error(line, "not enough data provided for construction", "constructor");
546             return true;
547         }
548     }
549
550     TIntermTyped *typed = node ? node->getAsTyped() : 0;
551     if (typed == 0) {
552         error(line, "constructor argument does not have a type", "constructor");
553         return true;
554     }
555     if (op != EOpConstructStruct && IsSampler(typed->getBasicType())) {
556         error(line, "cannot convert a sampler", "constructor");
557         return true;
558     }
559     if (typed->getBasicType() == EbtVoid) {
560         error(line, "cannot convert a void", "constructor");
561         return true;
562     }
563
564     return false;
565 }
566
567 // This function checks to see if a void variable has been declared and raise an error message for such a case
568 //
569 // returns true in case of an error
570 //
571 bool TParseContext::voidErrorCheck(const TSourceLoc &line, const TString& identifier, const TBasicType& type)
572 {
573     if(type == EbtVoid) {
574         error(line, "illegal use of type 'void'", identifier.c_str());
575         return true;
576     }
577
578     return false;
579 }
580
581 // This function checks to see if the node (for the expression) contains a scalar boolean expression or not
582 //
583 // returns true in case of an error
584 //
585 bool TParseContext::boolErrorCheck(const TSourceLoc &line, const TIntermTyped* type)
586 {
587     if (type->getBasicType() != EbtBool || type->isArray() || type->isMatrix() || type->isVector()) {
588         error(line, "boolean expression expected", "");
589         return true;
590     }
591
592     return false;
593 }
594
595 // This function checks to see if the node (for the expression) contains a scalar boolean expression or not
596 //
597 // returns true in case of an error
598 //
599 bool TParseContext::boolErrorCheck(const TSourceLoc &line, const TPublicType& pType)
600 {
601     if (pType.type != EbtBool || pType.array || (pType.primarySize > 1) || (pType.secondarySize > 1)) {
602         error(line, "boolean expression expected", "");
603         return true;
604     }
605
606     return false;
607 }
608
609 bool TParseContext::samplerErrorCheck(const TSourceLoc &line, const TPublicType& pType, const char* reason)
610 {
611     if (pType.type == EbtStruct) {
612         if (containsSampler(*pType.userDef)) {
613             error(line, reason, getBasicString(pType.type), "(structure contains a sampler)");
614
615             return true;
616         }
617
618         return false;
619     } else if (IsSampler(pType.type)) {
620         error(line, reason, getBasicString(pType.type));
621
622         return true;
623     }
624
625     return false;
626 }
627
628 bool TParseContext::structQualifierErrorCheck(const TSourceLoc &line, const TPublicType& pType)
629 {
630         switch(pType.qualifier)
631         {
632         case EvqVaryingOut:
633         case EvqSmooth:
634         case EvqFlat:
635         case EvqCentroidOut:
636         case EvqVaryingIn:
637         case EvqSmoothIn:
638         case EvqFlatIn:
639         case EvqCentroidIn:
640         case EvqAttribute:
641         case EvqVertexIn:
642         case EvqFragmentOut:
643                 if(pType.type == EbtStruct)
644                 {
645                         error(line, "cannot be used with a structure", getQualifierString(pType.qualifier));
646
647                         return true;
648                 }
649                 break;
650         default:
651                 break;
652         }
653
654     if (pType.qualifier != EvqUniform && samplerErrorCheck(line, pType, "samplers must be uniform"))
655         return true;
656
657         // check for layout qualifier issues
658         const TLayoutQualifier layoutQualifier = pType.layoutQualifier;
659
660         if (pType.qualifier != EvqVertexIn && pType.qualifier != EvqFragmentOut &&
661             layoutLocationErrorCheck(line, pType.layoutQualifier))
662         {
663                 return true;
664         }
665
666     return false;
667 }
668
669 // These checks are common for all declarations starting a declarator list, and declarators that follow an empty
670 // declaration.
671 //
672 bool TParseContext::singleDeclarationErrorCheck(const TPublicType &publicType, const TSourceLoc &identifierLocation)
673 {
674         switch(publicType.qualifier)
675         {
676         case EvqVaryingIn:
677         case EvqVaryingOut:
678         case EvqAttribute:
679         case EvqVertexIn:
680         case EvqFragmentOut:
681                 if(publicType.type == EbtStruct)
682                 {
683                         error(identifierLocation, "cannot be used with a structure",
684                                 getQualifierString(publicType.qualifier));
685                         return true;
686                 }
687
688         default: break;
689         }
690
691         if(publicType.qualifier != EvqUniform && samplerErrorCheck(identifierLocation, publicType,
692                 "samplers must be uniform"))
693         {
694                 return true;
695         }
696
697         // check for layout qualifier issues
698         const TLayoutQualifier layoutQualifier = publicType.layoutQualifier;
699
700         if(layoutQualifier.matrixPacking != EmpUnspecified)
701         {
702                 error(identifierLocation, "layout qualifier", getMatrixPackingString(layoutQualifier.matrixPacking),
703                         "only valid for interface blocks");
704                 return true;
705         }
706
707         if(layoutQualifier.blockStorage != EbsUnspecified)
708         {
709                 error(identifierLocation, "layout qualifier", getBlockStorageString(layoutQualifier.blockStorage),
710                         "only valid for interface blocks");
711                 return true;
712         }
713
714         if(publicType.qualifier != EvqVertexIn && publicType.qualifier != EvqFragmentOut &&
715                 layoutLocationErrorCheck(identifierLocation, publicType.layoutQualifier))
716         {
717                 return true;
718         }
719
720         return false;
721 }
722
723 bool TParseContext::layoutLocationErrorCheck(const TSourceLoc &location, const TLayoutQualifier &layoutQualifier)
724 {
725         if(layoutQualifier.location != -1)
726         {
727                 error(location, "invalid layout qualifier:", "location", "only valid on program inputs and outputs");
728                 return true;
729         }
730
731         return false;
732 }
733
734 bool TParseContext::locationDeclaratorListCheck(const TSourceLoc& line, const TPublicType &pType)
735 {
736         if(pType.layoutQualifier.location != -1)
737         {
738                 error(line, "location must only be specified for a single input or output variable", "location");
739                 return true;
740         }
741
742         return false;
743 }
744
745 bool TParseContext::parameterSamplerErrorCheck(const TSourceLoc &line, TQualifier qualifier, const TType& type)
746 {
747     if ((qualifier == EvqOut || qualifier == EvqInOut) &&
748              type.getBasicType() != EbtStruct && IsSampler(type.getBasicType())) {
749         error(line, "samplers cannot be output parameters", type.getBasicString());
750         return true;
751     }
752
753     return false;
754 }
755
756 bool TParseContext::containsSampler(TType& type)
757 {
758     if (IsSampler(type.getBasicType()))
759         return true;
760
761     if (type.getBasicType() == EbtStruct) {
762         const TFieldList& fields = type.getStruct()->fields();
763         for(unsigned int i = 0; i < fields.size(); ++i) {
764             if (containsSampler(*fields[i]->type()))
765                 return true;
766         }
767     }
768
769     return false;
770 }
771
772 //
773 // Do size checking for an array type's size.
774 //
775 // Returns true if there was an error.
776 //
777 bool TParseContext::arraySizeErrorCheck(const TSourceLoc &line, TIntermTyped* expr, int& size)
778 {
779     TIntermConstantUnion* constant = expr->getAsConstantUnion();
780
781     if (constant == 0 || !constant->isScalarInt())
782     {
783         error(line, "array size must be a constant integer expression", "");
784         return true;
785     }
786
787     if (constant->getBasicType() == EbtUInt)
788     {
789         unsigned int uintSize = constant->getUConst(0);
790         if (uintSize > static_cast<unsigned int>(std::numeric_limits<int>::max()))
791         {
792             error(line, "array size too large", "");
793             size = 1;
794             return true;
795         }
796
797         size = static_cast<int>(uintSize);
798     }
799     else
800     {
801         size = constant->getIConst(0);
802
803         if (size <= 0)
804         {
805             error(line, "array size must be a positive integer", "");
806             size = 1;
807             return true;
808         }
809     }
810
811     return false;
812 }
813
814 //
815 // See if this qualifier can be an array.
816 //
817 // Returns true if there is an error.
818 //
819 bool TParseContext::arrayQualifierErrorCheck(const TSourceLoc &line, TPublicType type)
820 {
821     if ((type.qualifier == EvqAttribute) || (type.qualifier == EvqVertexIn) || (type.qualifier == EvqConstExpr)) {
822         error(line, "cannot declare arrays of this qualifier", TType(type).getCompleteString().c_str());
823         return true;
824     }
825
826     return false;
827 }
828
829 //
830 // See if this type can be an array.
831 //
832 // Returns true if there is an error.
833 //
834 bool TParseContext::arrayTypeErrorCheck(const TSourceLoc &line, TPublicType type)
835 {
836     //
837     // Can the type be an array?
838     //
839     if (type.array) {
840         error(line, "cannot declare arrays of arrays", TType(type).getCompleteString().c_str());
841         return true;
842     }
843
844     return false;
845 }
846
847 bool TParseContext::arraySetMaxSize(TIntermSymbol *node, TType* type, int size, bool updateFlag, const TSourceLoc &line)
848 {
849     bool builtIn = false;
850     TSymbol* symbol = symbolTable.find(node->getSymbol(), mShaderVersion, &builtIn);
851     if (symbol == 0) {
852         error(line, " undeclared identifier", node->getSymbol().c_str());
853         return true;
854     }
855     TVariable* variable = static_cast<TVariable*>(symbol);
856
857     type->setArrayInformationType(variable->getArrayInformationType());
858     variable->updateArrayInformationType(type);
859
860     // special casing to test index value of gl_FragData. If the accessed index is >= gl_MaxDrawBuffers
861     // its an error
862     if (node->getSymbol() == "gl_FragData") {
863         TSymbol* fragData = symbolTable.find("gl_MaxDrawBuffers", mShaderVersion, &builtIn);
864         ASSERT(fragData);
865
866         int fragDataValue = static_cast<TVariable*>(fragData)->getConstPointer()[0].getIConst();
867         if (fragDataValue <= size) {
868             error(line, "", "[", "gl_FragData can only have a max array size of up to gl_MaxDrawBuffers");
869             return true;
870         }
871     }
872
873     // we dont want to update the maxArraySize when this flag is not set, we just want to include this
874     // node type in the chain of node types so that its updated when a higher maxArraySize comes in.
875     if (!updateFlag)
876         return false;
877
878     size++;
879     variable->getType().setMaxArraySize(size);
880     type->setMaxArraySize(size);
881     TType* tt = type;
882
883     while(tt->getArrayInformationType() != 0) {
884         tt = tt->getArrayInformationType();
885         tt->setMaxArraySize(size);
886     }
887
888     return false;
889 }
890
891 //
892 // Enforce non-initializer type/qualifier rules.
893 //
894 // Returns true if there was an error.
895 //
896 bool TParseContext::nonInitConstErrorCheck(const TSourceLoc &line, TString& identifier, TPublicType& type, bool array)
897 {
898     if (type.qualifier == EvqConstExpr)
899     {
900         // Make the qualifier make sense.
901         type.qualifier = EvqTemporary;
902
903         if (array)
904         {
905             error(line, "arrays may not be declared constant since they cannot be initialized", identifier.c_str());
906         }
907         else if (type.isStructureContainingArrays())
908         {
909             error(line, "structures containing arrays may not be declared constant since they cannot be initialized", identifier.c_str());
910         }
911         else
912         {
913             error(line, "variables with qualifier 'const' must be initialized", identifier.c_str());
914         }
915
916         return true;
917     }
918
919     return false;
920 }
921
922 //
923 // Do semantic checking for a variable declaration that has no initializer,
924 // and update the symbol table.
925 //
926 // Returns true if there was an error.
927 //
928 bool TParseContext::nonInitErrorCheck(const TSourceLoc &line, const TString& identifier, TPublicType& type)
929 {
930         if(type.qualifier == EvqConstExpr)
931         {
932                 // Make the qualifier make sense.
933                 type.qualifier = EvqTemporary;
934
935                 // Generate informative error messages for ESSL1.
936                 // In ESSL3 arrays and structures containing arrays can be constant.
937                 if(mShaderVersion < 300 && type.isStructureContainingArrays())
938                 {
939                         error(line,
940                                 "structures containing arrays may not be declared constant since they cannot be initialized",
941                                 identifier.c_str());
942                 }
943                 else
944                 {
945                         error(line, "variables with qualifier 'const' must be initialized", identifier.c_str());
946                 }
947
948                 return true;
949         }
950         if(type.isUnsizedArray())
951         {
952                 error(line, "implicitly sized arrays need to be initialized", identifier.c_str());
953                 return true;
954         }
955         return false;
956 }
957
958 // Do some simple checks that are shared between all variable declarations,
959 // and update the symbol table.
960 //
961 // Returns true if declaring the variable succeeded.
962 //
963 bool TParseContext::declareVariable(const TSourceLoc &line, const TString &identifier, const TType &type,
964         TVariable **variable)
965 {
966         ASSERT((*variable) == nullptr);
967
968         // gl_LastFragData may be redeclared with a new precision qualifier
969         if(type.isArray() && identifier.compare(0, 15, "gl_LastFragData") == 0)
970         {
971                 const TVariable *maxDrawBuffers =
972                         static_cast<const TVariable *>(symbolTable.findBuiltIn("gl_MaxDrawBuffers", mShaderVersion));
973                 if(type.getArraySize() != maxDrawBuffers->getConstPointer()->getIConst())
974                 {
975                         error(line, "redeclaration of gl_LastFragData with size != gl_MaxDrawBuffers", identifier.c_str());
976                         return false;
977                 }
978         }
979
980         if(reservedErrorCheck(line, identifier))
981                 return false;
982
983         (*variable) = new TVariable(&identifier, type);
984         if(!symbolTable.declare(**variable))
985         {
986                 error(line, "redefinition", identifier.c_str());
987                 delete (*variable);
988                 (*variable) = nullptr;
989                 return false;
990         }
991
992         if(voidErrorCheck(line, identifier, type.getBasicType()))
993                 return false;
994
995         return true;
996 }
997
998 bool TParseContext::paramErrorCheck(const TSourceLoc &line, TQualifier qualifier, TQualifier paramQualifier, TType* type)
999 {
1000     if (qualifier != EvqConstReadOnly && qualifier != EvqTemporary) {
1001         error(line, "qualifier not allowed on function parameter", getQualifierString(qualifier));
1002         return true;
1003     }
1004     if (qualifier == EvqConstReadOnly && paramQualifier != EvqIn) {
1005         error(line, "qualifier not allowed with ", getQualifierString(qualifier), getQualifierString(paramQualifier));
1006         return true;
1007     }
1008
1009     if (qualifier == EvqConstReadOnly)
1010         type->setQualifier(EvqConstReadOnly);
1011     else
1012         type->setQualifier(paramQualifier);
1013
1014     return false;
1015 }
1016
1017 bool TParseContext::extensionErrorCheck(const TSourceLoc &line, const TString& extension)
1018 {
1019     const TExtensionBehavior& extBehavior = extensionBehavior();
1020     TExtensionBehavior::const_iterator iter = extBehavior.find(extension.c_str());
1021     if (iter == extBehavior.end()) {
1022         error(line, "extension", extension.c_str(), "is not supported");
1023         return true;
1024     }
1025     // In GLSL ES, an extension's default behavior is "disable".
1026     if (iter->second == EBhDisable || iter->second == EBhUndefined) {
1027         error(line, "extension", extension.c_str(), "is disabled");
1028         return true;
1029     }
1030     if (iter->second == EBhWarn) {
1031         warning(line, "extension", extension.c_str(), "is being used");
1032         return false;
1033     }
1034
1035     return false;
1036 }
1037
1038 bool TParseContext::functionCallLValueErrorCheck(const TFunction *fnCandidate, TIntermAggregate *aggregate)
1039 {
1040         for(size_t i = 0; i < fnCandidate->getParamCount(); ++i)
1041         {
1042                 TQualifier qual = fnCandidate->getParam(i).type->getQualifier();
1043                 if(qual == EvqOut || qual == EvqInOut)
1044                 {
1045                         TIntermTyped *node = (aggregate->getSequence())[i]->getAsTyped();
1046                         if(lValueErrorCheck(node->getLine(), "assign", node))
1047                         {
1048                                 error(node->getLine(),
1049                                         "Constant value cannot be passed for 'out' or 'inout' parameters.", "Error");
1050                                 recover();
1051                                 return true;
1052                         }
1053                 }
1054         }
1055         return false;
1056 }
1057
1058 bool TParseContext::supportsExtension(const char* extension)
1059 {
1060     const TExtensionBehavior& extbehavior = extensionBehavior();
1061     TExtensionBehavior::const_iterator iter = extbehavior.find(extension);
1062     return (iter != extbehavior.end());
1063 }
1064
1065 void TParseContext::handleExtensionDirective(const TSourceLoc &line, const char* extName, const char* behavior)
1066 {
1067     pp::SourceLocation loc;
1068     DecodeSourceLoc(line, &loc.file, &loc.line);
1069     mDirectiveHandler.handleExtension(loc, extName, behavior);
1070 }
1071
1072 void TParseContext::handlePragmaDirective(const TSourceLoc &line, const char* name, const char* value)
1073 {
1074     pp::SourceLocation loc;
1075     DecodeSourceLoc(line, &loc.file, &loc.line);
1076     mDirectiveHandler.handlePragma(loc, name, value);
1077 }
1078
1079 /////////////////////////////////////////////////////////////////////////////////
1080 //
1081 // Non-Errors.
1082 //
1083 /////////////////////////////////////////////////////////////////////////////////
1084
1085 const TVariable *TParseContext::getNamedVariable(const TSourceLoc &location,
1086         const TString *name,
1087         const TSymbol *symbol)
1088 {
1089         const TVariable *variable = NULL;
1090
1091         if(!symbol)
1092         {
1093                 error(location, "undeclared identifier", name->c_str());
1094                 recover();
1095         }
1096         else if(!symbol->isVariable())
1097         {
1098                 error(location, "variable expected", name->c_str());
1099                 recover();
1100         }
1101         else
1102         {
1103                 variable = static_cast<const TVariable*>(symbol);
1104
1105                 if(symbolTable.findBuiltIn(variable->getName(), mShaderVersion))
1106                 {
1107                         recover();
1108                 }
1109
1110                 // Reject shaders using both gl_FragData and gl_FragColor
1111                 TQualifier qualifier = variable->getType().getQualifier();
1112                 if(qualifier == EvqFragData)
1113                 {
1114                         mUsesFragData = true;
1115                 }
1116                 else if(qualifier == EvqFragColor)
1117                 {
1118                         mUsesFragColor = true;
1119                 }
1120
1121                 // This validation is not quite correct - it's only an error to write to
1122                 // both FragData and FragColor. For simplicity, and because users shouldn't
1123                 // be rewarded for reading from undefined varaibles, return an error
1124                 // if they are both referenced, rather than assigned.
1125                 if(mUsesFragData && mUsesFragColor)
1126                 {
1127                         error(location, "cannot use both gl_FragData and gl_FragColor", name->c_str());
1128                         recover();
1129                 }
1130         }
1131
1132         if(!variable)
1133         {
1134                 TType type(EbtFloat, EbpUndefined);
1135                 TVariable *fakeVariable = new TVariable(name, type);
1136                 symbolTable.declare(*fakeVariable);
1137                 variable = fakeVariable;
1138         }
1139
1140         return variable;
1141 }
1142
1143 //
1144 // Look up a function name in the symbol table, and make sure it is a function.
1145 //
1146 // Return the function symbol if found, otherwise 0.
1147 //
1148 const TFunction* TParseContext::findFunction(const TSourceLoc &line, TFunction* call, bool *builtIn)
1149 {
1150     // First find by unmangled name to check whether the function name has been
1151     // hidden by a variable name or struct typename.
1152     const TSymbol* symbol = symbolTable.find(call->getName(), mShaderVersion, builtIn);
1153     if (symbol == 0) {
1154         symbol = symbolTable.find(call->getMangledName(), mShaderVersion, builtIn);
1155     }
1156
1157     if (symbol == 0) {
1158         error(line, "no matching overloaded function found", call->getName().c_str());
1159         return 0;
1160     }
1161
1162     if (!symbol->isFunction()) {
1163         error(line, "function name expected", call->getName().c_str());
1164         return 0;
1165     }
1166
1167     return static_cast<const TFunction*>(symbol);
1168 }
1169
1170 //
1171 // Initializers show up in several places in the grammar.  Have one set of
1172 // code to handle them here.
1173 //
1174 bool TParseContext::executeInitializer(const TSourceLoc& line, const TString& identifier, const TPublicType& pType,
1175                                        TIntermTyped *initializer, TIntermNode **intermNode)
1176 {
1177         ASSERT(intermNode != nullptr);
1178         TType type = TType(pType);
1179
1180         TVariable *variable = nullptr;
1181         if(type.isArray() && (type.getArraySize() == 0))
1182         {
1183                 type.setArraySize(initializer->getArraySize());
1184         }
1185         if(!declareVariable(line, identifier, type, &variable))
1186         {
1187                 return true;
1188         }
1189
1190         bool globalInitWarning = false;
1191         if(symbolTable.atGlobalLevel() && !ValidateGlobalInitializer(initializer, this, &globalInitWarning))
1192         {
1193                 // Error message does not completely match behavior with ESSL 1.00, but
1194                 // we want to steer developers towards only using constant expressions.
1195                 error(line, "global variable initializers must be constant expressions", "=");
1196                 return true;
1197         }
1198         if(globalInitWarning)
1199         {
1200                 warning(line, "global variable initializers should be constant expressions "
1201                         "(uniforms and globals are allowed in global initializers for legacy compatibility)", "=");
1202     }
1203
1204     //
1205     // identifier must be of type constant, a global, or a temporary
1206     //
1207     TQualifier qualifier = variable->getType().getQualifier();
1208     if ((qualifier != EvqTemporary) && (qualifier != EvqGlobal) && (qualifier != EvqConstExpr)) {
1209         error(line, " cannot initialize this type of qualifier ", variable->getType().getQualifierString());
1210         return true;
1211     }
1212     //
1213     // test for and propagate constant
1214     //
1215
1216     if (qualifier == EvqConstExpr) {
1217         if (qualifier != initializer->getType().getQualifier()) {
1218             std::stringstream extraInfoStream;
1219             extraInfoStream << "'" << variable->getType().getCompleteString() << "'";
1220             std::string extraInfo = extraInfoStream.str();
1221             error(line, " assigning non-constant to", "=", extraInfo.c_str());
1222             variable->getType().setQualifier(EvqTemporary);
1223             return true;
1224         }
1225         if (type != initializer->getType()) {
1226             error(line, " non-matching types for const initializer ",
1227                 variable->getType().getQualifierString());
1228             variable->getType().setQualifier(EvqTemporary);
1229             return true;
1230         }
1231         if (initializer->getAsConstantUnion()) {
1232             variable->shareConstPointer(initializer->getAsConstantUnion()->getUnionArrayPointer());
1233         } else if (initializer->getAsSymbolNode()) {
1234             const TSymbol* symbol = symbolTable.find(initializer->getAsSymbolNode()->getSymbol(), 0);
1235             const TVariable* tVar = static_cast<const TVariable*>(symbol);
1236
1237             ConstantUnion* constArray = tVar->getConstPointer();
1238             variable->shareConstPointer(constArray);
1239         } else {
1240             std::stringstream extraInfoStream;
1241             extraInfoStream << "'" << variable->getType().getCompleteString() << "'";
1242             std::string extraInfo = extraInfoStream.str();
1243             error(line, " cannot assign to", "=", extraInfo.c_str());
1244             variable->getType().setQualifier(EvqTemporary);
1245             return true;
1246         }
1247     }
1248
1249     if (qualifier != EvqConstExpr) {
1250         TIntermSymbol* intermSymbol = intermediate.addSymbol(variable->getUniqueId(), variable->getName(), variable->getType(), line);
1251         *intermNode = createAssign(EOpInitialize, intermSymbol, initializer, line);
1252         if(*intermNode == nullptr) {
1253             assignError(line, "=", intermSymbol->getCompleteString(), initializer->getCompleteString());
1254             return true;
1255         }
1256     } else
1257         *intermNode = nullptr;
1258
1259     return false;
1260 }
1261
1262 bool TParseContext::areAllChildConst(TIntermAggregate* aggrNode)
1263 {
1264     ASSERT(aggrNode != NULL);
1265     if (!aggrNode->isConstructor())
1266         return false;
1267
1268     bool allConstant = true;
1269
1270     // check if all the child nodes are constants so that they can be inserted into
1271     // the parent node
1272     TIntermSequence &sequence = aggrNode->getSequence() ;
1273     for (TIntermSequence::iterator p = sequence.begin(); p != sequence.end(); ++p) {
1274         if (!(*p)->getAsTyped()->getAsConstantUnion())
1275             return false;
1276     }
1277
1278     return allConstant;
1279 }
1280
1281 TPublicType TParseContext::addFullySpecifiedType(TQualifier qualifier, bool invariant, TLayoutQualifier layoutQualifier, const TPublicType &typeSpecifier)
1282 {
1283         TPublicType returnType = typeSpecifier;
1284         returnType.qualifier = qualifier;
1285         returnType.invariant = invariant;
1286         returnType.layoutQualifier = layoutQualifier;
1287
1288         if(typeSpecifier.array)
1289         {
1290                 error(typeSpecifier.line, "not supported", "first-class array");
1291                 recover();
1292                 returnType.clearArrayness();
1293         }
1294
1295         if(mShaderVersion < 300)
1296         {
1297                 if(qualifier == EvqAttribute && (typeSpecifier.type == EbtBool || typeSpecifier.type == EbtInt))
1298                 {
1299                         error(typeSpecifier.line, "cannot be bool or int", getQualifierString(qualifier));
1300                         recover();
1301                 }
1302
1303                 if((qualifier == EvqVaryingIn || qualifier == EvqVaryingOut) &&
1304                         (typeSpecifier.type == EbtBool || typeSpecifier.type == EbtInt))
1305                 {
1306                         error(typeSpecifier.line, "cannot be bool or int", getQualifierString(qualifier));
1307                         recover();
1308                 }
1309         }
1310         else
1311         {
1312                 switch(qualifier)
1313                 {
1314                 case EvqSmoothIn:
1315                 case EvqSmoothOut:
1316                 case EvqVertexOut:
1317                 case EvqFragmentIn:
1318                 case EvqCentroidOut:
1319                 case EvqCentroidIn:
1320                         if(typeSpecifier.type == EbtBool)
1321                         {
1322                                 error(typeSpecifier.line, "cannot be bool", getQualifierString(qualifier));
1323                                 recover();
1324                         }
1325                         if(typeSpecifier.type == EbtInt || typeSpecifier.type == EbtUInt)
1326                         {
1327                                 error(typeSpecifier.line, "must use 'flat' interpolation here", getQualifierString(qualifier));
1328                                 recover();
1329                         }
1330                         break;
1331
1332                 case EvqVertexIn:
1333                 case EvqFragmentOut:
1334                 case EvqFlatIn:
1335                 case EvqFlatOut:
1336                         if(typeSpecifier.type == EbtBool)
1337                         {
1338                                 error(typeSpecifier.line, "cannot be bool", getQualifierString(qualifier));
1339                                 recover();
1340                         }
1341                         break;
1342
1343                 default: break;
1344                 }
1345         }
1346
1347         return returnType;
1348 }
1349
1350 TIntermAggregate *TParseContext::parseSingleDeclaration(TPublicType &publicType,
1351         const TSourceLoc &identifierOrTypeLocation,
1352         const TString &identifier)
1353 {
1354         TIntermSymbol *symbol = intermediate.addSymbol(0, identifier, TType(publicType), identifierOrTypeLocation);
1355
1356         bool emptyDeclaration = (identifier == "");
1357
1358         mDeferredSingleDeclarationErrorCheck = emptyDeclaration;
1359
1360         if(emptyDeclaration)
1361         {
1362                 if(publicType.isUnsizedArray())
1363                 {
1364                         // ESSL3 spec section 4.1.9: Array declaration which leaves the size unspecified is an error.
1365                         // It is assumed that this applies to empty declarations as well.
1366                         error(identifierOrTypeLocation, "empty array declaration needs to specify a size", identifier.c_str());
1367                 }
1368         }
1369         else
1370         {
1371                 if(singleDeclarationErrorCheck(publicType, identifierOrTypeLocation))
1372                         recover();
1373
1374                 if(nonInitErrorCheck(identifierOrTypeLocation, identifier, publicType))
1375                         recover();
1376
1377                 TVariable *variable = nullptr;
1378                 if(!declareVariable(identifierOrTypeLocation, identifier, TType(publicType), &variable))
1379                         recover();
1380
1381                 if(variable && symbol)
1382                         symbol->setId(variable->getUniqueId());
1383         }
1384
1385         return intermediate.makeAggregate(symbol, identifierOrTypeLocation);
1386 }
1387
1388 TIntermAggregate *TParseContext::parseSingleArrayDeclaration(TPublicType &publicType,
1389         const TSourceLoc &identifierLocation,
1390         const TString &identifier,
1391         const TSourceLoc &indexLocation,
1392         TIntermTyped *indexExpression)
1393 {
1394         mDeferredSingleDeclarationErrorCheck = false;
1395
1396         if(singleDeclarationErrorCheck(publicType, identifierLocation))
1397                 recover();
1398
1399         if(nonInitErrorCheck(identifierLocation, identifier, publicType))
1400                 recover();
1401
1402         if(arrayTypeErrorCheck(indexLocation, publicType) || arrayQualifierErrorCheck(indexLocation, publicType))
1403         {
1404                 recover();
1405         }
1406
1407         TType arrayType(publicType);
1408
1409         int size;
1410         if(arraySizeErrorCheck(identifierLocation, indexExpression, size))
1411         {
1412                 recover();
1413         }
1414         // Make the type an array even if size check failed.
1415         // This ensures useless error messages regarding the variable's non-arrayness won't follow.
1416         arrayType.setArraySize(size);
1417
1418         TVariable *variable = nullptr;
1419         if(!declareVariable(identifierLocation, identifier, arrayType, &variable))
1420                 recover();
1421
1422         TIntermSymbol *symbol = intermediate.addSymbol(0, identifier, arrayType, identifierLocation);
1423         if(variable && symbol)
1424                 symbol->setId(variable->getUniqueId());
1425
1426         return intermediate.makeAggregate(symbol, identifierLocation);
1427 }
1428
1429 TIntermAggregate *TParseContext::parseSingleInitDeclaration(const TPublicType &publicType,
1430         const TSourceLoc &identifierLocation,
1431         const TString &identifier,
1432         const TSourceLoc &initLocation,
1433         TIntermTyped *initializer)
1434 {
1435         mDeferredSingleDeclarationErrorCheck = false;
1436
1437         if(singleDeclarationErrorCheck(publicType, identifierLocation))
1438                 recover();
1439
1440         TIntermNode *intermNode = nullptr;
1441         if(!executeInitializer(identifierLocation, identifier, publicType, initializer, &intermNode))
1442         {
1443                 //
1444                 // Build intermediate representation
1445                 //
1446                 return intermNode ? intermediate.makeAggregate(intermNode, initLocation) : nullptr;
1447         }
1448         else
1449         {
1450                 recover();
1451                 return nullptr;
1452         }
1453 }
1454
1455 TIntermAggregate *TParseContext::parseSingleArrayInitDeclaration(TPublicType &publicType,
1456         const TSourceLoc &identifierLocation,
1457         const TString &identifier,
1458         const TSourceLoc &indexLocation,
1459         TIntermTyped *indexExpression,
1460         const TSourceLoc &initLocation,
1461         TIntermTyped *initializer)
1462 {
1463         mDeferredSingleDeclarationErrorCheck = false;
1464
1465         if(singleDeclarationErrorCheck(publicType, identifierLocation))
1466                 recover();
1467
1468         if(arrayTypeErrorCheck(indexLocation, publicType) || arrayQualifierErrorCheck(indexLocation, publicType))
1469         {
1470                 recover();
1471         }
1472
1473         TPublicType arrayType(publicType);
1474
1475         int size = 0;
1476         // If indexExpression is nullptr, then the array will eventually get its size implicitly from the initializer.
1477         if(indexExpression != nullptr && arraySizeErrorCheck(identifierLocation, indexExpression, size))
1478         {
1479                 recover();
1480         }
1481         // Make the type an array even if size check failed.
1482         // This ensures useless error messages regarding the variable's non-arrayness won't follow.
1483         arrayType.setArray(true, size);
1484
1485         // initNode will correspond to the whole of "type b[n] = initializer".
1486         TIntermNode *initNode = nullptr;
1487         if(!executeInitializer(identifierLocation, identifier, arrayType, initializer, &initNode))
1488         {
1489                 return initNode ? intermediate.makeAggregate(initNode, initLocation) : nullptr;
1490         }
1491         else
1492         {
1493                 recover();
1494                 return nullptr;
1495         }
1496 }
1497
1498 TIntermAggregate *TParseContext::parseInvariantDeclaration(const TSourceLoc &invariantLoc,
1499         const TSourceLoc &identifierLoc,
1500         const TString *identifier,
1501         const TSymbol *symbol)
1502 {
1503         // invariant declaration
1504         if(globalErrorCheck(invariantLoc, symbolTable.atGlobalLevel(), "invariant varying"))
1505         {
1506                 recover();
1507         }
1508
1509         if(!symbol)
1510         {
1511                 error(identifierLoc, "undeclared identifier declared as invariant", identifier->c_str());
1512                 recover();
1513                 return nullptr;
1514         }
1515         else
1516         {
1517                 const TString kGlFrontFacing("gl_FrontFacing");
1518                 if(*identifier == kGlFrontFacing)
1519                 {
1520                         error(identifierLoc, "identifier should not be declared as invariant", identifier->c_str());
1521                         recover();
1522                         return nullptr;
1523                 }
1524                 symbolTable.addInvariantVarying(std::string(identifier->c_str()));
1525                 const TVariable *variable = getNamedVariable(identifierLoc, identifier, symbol);
1526                 ASSERT(variable);
1527                 const TType &type = variable->getType();
1528                 TIntermSymbol *intermSymbol = intermediate.addSymbol(variable->getUniqueId(),
1529                         *identifier, type, identifierLoc);
1530
1531                 TIntermAggregate *aggregate = intermediate.makeAggregate(intermSymbol, identifierLoc);
1532                 aggregate->setOp(EOpInvariantDeclaration);
1533                 return aggregate;
1534         }
1535 }
1536
1537 TIntermAggregate *TParseContext::parseDeclarator(TPublicType &publicType, TIntermAggregate *aggregateDeclaration,
1538         const TSourceLoc &identifierLocation, const TString &identifier)
1539 {
1540         // If the declaration starting this declarator list was empty (example: int,), some checks were not performed.
1541         if(mDeferredSingleDeclarationErrorCheck)
1542         {
1543                 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1544                         recover();
1545                 mDeferredSingleDeclarationErrorCheck = false;
1546         }
1547
1548         if(locationDeclaratorListCheck(identifierLocation, publicType))
1549                 recover();
1550
1551         if(nonInitErrorCheck(identifierLocation, identifier, publicType))
1552                 recover();
1553
1554         TVariable *variable = nullptr;
1555         if(!declareVariable(identifierLocation, identifier, TType(publicType), &variable))
1556                 recover();
1557
1558         TIntermSymbol *symbol = intermediate.addSymbol(0, identifier, TType(publicType), identifierLocation);
1559         if(variable && symbol)
1560                 symbol->setId(variable->getUniqueId());
1561
1562         return intermediate.growAggregate(aggregateDeclaration, symbol, identifierLocation);
1563 }
1564
1565 TIntermAggregate *TParseContext::parseArrayDeclarator(TPublicType &publicType, TIntermAggregate *aggregateDeclaration,
1566         const TSourceLoc &identifierLocation, const TString &identifier,
1567         const TSourceLoc &arrayLocation, TIntermTyped *indexExpression)
1568 {
1569         // If the declaration starting this declarator list was empty (example: int,), some checks were not performed.
1570         if(mDeferredSingleDeclarationErrorCheck)
1571         {
1572                 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1573                         recover();
1574                 mDeferredSingleDeclarationErrorCheck = false;
1575         }
1576
1577         if(locationDeclaratorListCheck(identifierLocation, publicType))
1578                 recover();
1579
1580         if(nonInitErrorCheck(identifierLocation, identifier, publicType))
1581                 recover();
1582
1583         if(arrayTypeErrorCheck(arrayLocation, publicType) || arrayQualifierErrorCheck(arrayLocation, publicType))
1584         {
1585                 recover();
1586         }
1587         else
1588         {
1589                 TType arrayType = TType(publicType);
1590                 int size;
1591                 if(arraySizeErrorCheck(arrayLocation, indexExpression, size))
1592                 {
1593                         recover();
1594                 }
1595                 arrayType.setArraySize(size);
1596
1597                 TVariable *variable = nullptr;
1598                 if(!declareVariable(identifierLocation, identifier, arrayType, &variable))
1599                         recover();
1600
1601                 TIntermSymbol *symbol = intermediate.addSymbol(0, identifier, arrayType, identifierLocation);
1602                 if(variable && symbol)
1603                         symbol->setId(variable->getUniqueId());
1604
1605                 return intermediate.growAggregate(aggregateDeclaration, symbol, identifierLocation);
1606         }
1607
1608         return nullptr;
1609 }
1610
1611 TIntermAggregate *TParseContext::parseInitDeclarator(const TPublicType &publicType, TIntermAggregate *aggregateDeclaration,
1612         const TSourceLoc &identifierLocation, const TString &identifier,
1613         const TSourceLoc &initLocation, TIntermTyped *initializer)
1614 {
1615         // If the declaration starting this declarator list was empty (example: int,), some checks were not performed.
1616         if(mDeferredSingleDeclarationErrorCheck)
1617         {
1618                 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1619                         recover();
1620                 mDeferredSingleDeclarationErrorCheck = false;
1621         }
1622
1623         if(locationDeclaratorListCheck(identifierLocation, publicType))
1624                 recover();
1625
1626         TIntermNode *intermNode = nullptr;
1627         if(!executeInitializer(identifierLocation, identifier, publicType, initializer, &intermNode))
1628         {
1629                 //
1630                 // build the intermediate representation
1631                 //
1632                 if(intermNode)
1633                 {
1634                         return intermediate.growAggregate(aggregateDeclaration, intermNode, initLocation);
1635                 }
1636                 else
1637                 {
1638                         return aggregateDeclaration;
1639                 }
1640         }
1641         else
1642         {
1643                 recover();
1644                 return nullptr;
1645         }
1646 }
1647
1648 TIntermAggregate *TParseContext::parseArrayInitDeclarator(const TPublicType &publicType,
1649         TIntermAggregate *aggregateDeclaration,
1650         const TSourceLoc &identifierLocation,
1651         const TString &identifier,
1652         const TSourceLoc &indexLocation,
1653         TIntermTyped *indexExpression,
1654         const TSourceLoc &initLocation, TIntermTyped *initializer)
1655 {
1656         // If the declaration starting this declarator list was empty (example: int,), some checks were not performed.
1657         if(mDeferredSingleDeclarationErrorCheck)
1658         {
1659                 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1660                         recover();
1661                 mDeferredSingleDeclarationErrorCheck = false;
1662         }
1663
1664         if(locationDeclaratorListCheck(identifierLocation, publicType))
1665                 recover();
1666
1667         if(arrayTypeErrorCheck(indexLocation, publicType) || arrayQualifierErrorCheck(indexLocation, publicType))
1668         {
1669                 recover();
1670         }
1671
1672         TPublicType arrayType(publicType);
1673
1674         int size = 0;
1675         // If indexExpression is nullptr, then the array will eventually get its size implicitly from the initializer.
1676         if(indexExpression != nullptr && arraySizeErrorCheck(identifierLocation, indexExpression, size))
1677         {
1678                 recover();
1679         }
1680         // Make the type an array even if size check failed.
1681         // This ensures useless error messages regarding the variable's non-arrayness won't follow.
1682         arrayType.setArray(true, size);
1683
1684         // initNode will correspond to the whole of "b[n] = initializer".
1685         TIntermNode *initNode = nullptr;
1686         if(!executeInitializer(identifierLocation, identifier, arrayType, initializer, &initNode))
1687         {
1688                 if(initNode)
1689                 {
1690                         return intermediate.growAggregate(aggregateDeclaration, initNode, initLocation);
1691                 }
1692                 else
1693                 {
1694                         return aggregateDeclaration;
1695                 }
1696         }
1697         else
1698         {
1699                 recover();
1700                 return nullptr;
1701         }
1702 }
1703
1704 void TParseContext::parseGlobalLayoutQualifier(const TPublicType &typeQualifier)
1705 {
1706         if(mShaderVersion < 300)
1707         {
1708                 error(typeQualifier.line, "layout qualifiers supported in GLSL ES 3.00 only", "layout");
1709                 recover();
1710                 return;
1711         }
1712
1713         if(typeQualifier.qualifier != EvqUniform)
1714         {
1715                 error(typeQualifier.line, "invalid qualifier:", getQualifierString(typeQualifier.qualifier), "global layout must be uniform");
1716                 recover();
1717                 return;
1718         }
1719
1720         const TLayoutQualifier layoutQualifier = typeQualifier.layoutQualifier;
1721         ASSERT(!layoutQualifier.isEmpty());
1722
1723         if(layoutLocationErrorCheck(typeQualifier.line, typeQualifier.layoutQualifier))
1724         {
1725                 recover();
1726                 return;
1727         }
1728
1729         if(layoutQualifier.matrixPacking != EmpUnspecified)
1730         {
1731                 mDefaultMatrixPacking = layoutQualifier.matrixPacking;
1732         }
1733
1734         if(layoutQualifier.blockStorage != EbsUnspecified)
1735         {
1736                 mDefaultBlockStorage = layoutQualifier.blockStorage;
1737         }
1738 }
1739
1740 TFunction *TParseContext::addConstructorFunc(const TPublicType &publicTypeIn)
1741 {
1742         TPublicType publicType = publicTypeIn;
1743         TOperator op = EOpNull;
1744         if(publicType.userDef)
1745         {
1746                 op = EOpConstructStruct;
1747         }
1748         else
1749         {
1750                 switch(publicType.type)
1751                 {
1752                 case EbtFloat:\r
1753                         if(publicType.isMatrix())\r
1754                         {\r
1755                                 switch(publicType.getCols())\r
1756                                 {\r
1757                                 case 2:\r
1758                                         switch(publicType.getRows())\r
1759                                         {\r
1760                                         case 2: op = EOpConstructMat2;  break;\r
1761                                         case 3: op = EOpConstructMat2x3;  break;\r
1762                                         case 4: op = EOpConstructMat2x4;  break;\r
1763                                         }\r
1764                                         break;\r
1765                                 case 3:\r
1766                                         switch(publicType.getRows())\r
1767                                         {\r
1768                                         case 2: op = EOpConstructMat3x2;  break;\r
1769                                         case 3: op = EOpConstructMat3;  break;\r
1770                                         case 4: op = EOpConstructMat3x4;  break;\r
1771                                         }\r
1772                                         break;\r
1773                                 case 4:\r
1774                                         switch(publicType.getRows())\r
1775                                         {\r
1776                                         case 2: op = EOpConstructMat4x2;  break;\r
1777                                         case 3: op = EOpConstructMat4x3;  break;\r
1778                                         case 4: op = EOpConstructMat4;  break;\r
1779                                         }\r
1780                                         break;\r
1781                                 }\r
1782                         }\r
1783                         else\r
1784                         {\r
1785                                 switch(publicType.getNominalSize())\r
1786                                 {\r
1787                                 case 1: op = EOpConstructFloat; break;\r
1788                                 case 2: op = EOpConstructVec2;  break;\r
1789                                 case 3: op = EOpConstructVec3;  break;\r
1790                                 case 4: op = EOpConstructVec4;  break;\r
1791                                 }\r
1792                         }\r
1793                         break;
1794
1795                 case EbtInt:
1796                         switch(publicType.getNominalSize())
1797                         {
1798                         case 1: op = EOpConstructInt;   break;
1799                         case 2: op = EOpConstructIVec2; break;
1800                         case 3: op = EOpConstructIVec3; break;
1801                         case 4: op = EOpConstructIVec4; break;
1802                         }
1803                         break;
1804
1805                 case EbtUInt:
1806                         switch(publicType.getNominalSize())
1807                         {
1808                         case 1: op = EOpConstructUInt;  break;
1809                         case 2: op = EOpConstructUVec2; break;
1810                         case 3: op = EOpConstructUVec3; break;
1811                         case 4: op = EOpConstructUVec4; break;
1812                         }
1813                         break;
1814
1815                 case EbtBool:
1816                         switch(publicType.getNominalSize())
1817                         {
1818                         case 1: op = EOpConstructBool;  break;
1819                         case 2: op = EOpConstructBVec2; break;
1820                         case 3: op = EOpConstructBVec3; break;
1821                         case 4: op = EOpConstructBVec4; break;
1822                         }
1823                         break;
1824
1825                 default: break;
1826                 }
1827
1828                 if(op == EOpNull)
1829                 {
1830                         error(publicType.line, "cannot construct this type", getBasicString(publicType.type));
1831                         recover();
1832                         publicType.type = EbtFloat;
1833                         op = EOpConstructFloat;
1834                 }
1835         }
1836
1837         TString tempString;
1838         TType type(publicType);
1839         return new TFunction(&tempString, type, op);
1840 }
1841
1842 // This function is used to test for the correctness of the parameters passed to various constructor functions
1843 // and also convert them to the right datatype if it is allowed and required.
1844 //
1845 // Returns 0 for an error or the constructed node (aggregate or typed) for no error.
1846 //
1847 TIntermTyped* TParseContext::addConstructor(TIntermNode* arguments, const TType* type, TOperator op, TFunction* fnCall, const TSourceLoc &line)
1848 {
1849     TIntermAggregate *aggregateArguments = arguments->getAsAggregate();
1850
1851     if(!aggregateArguments)
1852     {
1853         aggregateArguments = new TIntermAggregate;
1854         aggregateArguments->getSequence().push_back(arguments);
1855     }
1856
1857     if(op == EOpConstructStruct)
1858     {
1859         const TFieldList &fields = type->getStruct()->fields();
1860         TIntermSequence &args = aggregateArguments->getSequence();
1861
1862         for(size_t i = 0; i < fields.size(); i++)
1863         {
1864             if(args[i]->getAsTyped()->getType() != *fields[i]->type())
1865             {
1866                 error(line, "Structure constructor arguments do not match structure fields", "Error");
1867                 recover();
1868
1869                 return 0;
1870             }
1871         }
1872     }
1873
1874     // Turn the argument list itself into a constructor
1875     TIntermTyped *constructor = intermediate.setAggregateOperator(aggregateArguments, op, line);
1876     TIntermTyped *constConstructor = foldConstConstructor(constructor->getAsAggregate(), *type);
1877     if(constConstructor)
1878     {
1879         return constConstructor;
1880     }
1881
1882     return constructor;
1883 }
1884
1885 TIntermTyped* TParseContext::foldConstConstructor(TIntermAggregate* aggrNode, const TType& type)
1886 {
1887     bool canBeFolded = areAllChildConst(aggrNode);
1888     aggrNode->setType(type);
1889     if (canBeFolded) {
1890         bool returnVal = false;
1891         ConstantUnion* unionArray = new ConstantUnion[type.getObjectSize()];
1892         if (aggrNode->getSequence().size() == 1)  {
1893             returnVal = intermediate.parseConstTree(aggrNode->getLine(), aggrNode, unionArray, aggrNode->getOp(), type, true);
1894         }
1895         else {
1896             returnVal = intermediate.parseConstTree(aggrNode->getLine(), aggrNode, unionArray, aggrNode->getOp(), type);
1897         }
1898         if (returnVal)
1899             return 0;
1900
1901         return intermediate.addConstantUnion(unionArray, type, aggrNode->getLine());
1902     }
1903
1904     return 0;
1905 }
1906
1907 //
1908 // This function returns the tree representation for the vector field(s) being accessed from contant vector.
1909 // If only one component of vector is accessed (v.x or v[0] where v is a contant vector), then a contant node is
1910 // returned, else an aggregate node is returned (for v.xy). The input to this function could either be the symbol
1911 // node or it could be the intermediate tree representation of accessing fields in a constant structure or column of 
1912 // a constant matrix.
1913 //
1914 TIntermTyped* TParseContext::addConstVectorNode(TVectorFields& fields, TIntermTyped* node, const TSourceLoc &line)
1915 {
1916     TIntermTyped* typedNode;
1917     TIntermConstantUnion* tempConstantNode = node->getAsConstantUnion();
1918
1919     ConstantUnion *unionArray;
1920     if (tempConstantNode) {
1921         unionArray = tempConstantNode->getUnionArrayPointer();
1922
1923         if (!unionArray) {
1924             return node;
1925         }
1926     } else { // The node has to be either a symbol node or an aggregate node or a tempConstant node, else, its an error
1927         error(line, "Cannot offset into the vector", "Error");
1928         recover();
1929
1930         return 0;
1931     }
1932
1933     ConstantUnion* constArray = new ConstantUnion[fields.num];
1934
1935     for (int i = 0; i < fields.num; i++) {
1936         if (fields.offsets[i] >= node->getType().getObjectSize()) {
1937             std::stringstream extraInfoStream;
1938             extraInfoStream << "vector field selection out of range '" << fields.offsets[i] << "'";
1939             std::string extraInfo = extraInfoStream.str();
1940             error(line, "", "[", extraInfo.c_str());
1941             recover();
1942             fields.offsets[i] = 0;
1943         }
1944
1945         constArray[i] = unionArray[fields.offsets[i]];
1946
1947     }
1948     typedNode = intermediate.addConstantUnion(constArray, node->getType(), line);
1949     return typedNode;
1950 }
1951
1952 //
1953 // This function returns the column being accessed from a constant matrix. The values are retrieved from
1954 // the symbol table and parse-tree is built for a vector (each column of a matrix is a vector). The input
1955 // to the function could either be a symbol node (m[0] where m is a constant matrix)that represents a
1956 // constant matrix or it could be the tree representation of the constant matrix (s.m1[0] where s is a constant structure)
1957 //
1958 TIntermTyped* TParseContext::addConstMatrixNode(int index, TIntermTyped* node, const TSourceLoc &line)
1959 {
1960     TIntermTyped* typedNode;
1961     TIntermConstantUnion* tempConstantNode = node->getAsConstantUnion();
1962
1963     if (index >= node->getType().getNominalSize()) {
1964         std::stringstream extraInfoStream;
1965         extraInfoStream << "matrix field selection out of range '" << index << "'";
1966         std::string extraInfo = extraInfoStream.str();
1967         error(line, "", "[", extraInfo.c_str());
1968         recover();
1969         index = 0;
1970     }
1971
1972     if (tempConstantNode) {
1973          ConstantUnion* unionArray = tempConstantNode->getUnionArrayPointer();
1974          int size = tempConstantNode->getType().getNominalSize();
1975          typedNode = intermediate.addConstantUnion(&unionArray[size*index], tempConstantNode->getType(), line);
1976     } else {
1977         error(line, "Cannot offset into the matrix", "Error");
1978         recover();
1979
1980         return 0;
1981     }
1982
1983     return typedNode;
1984 }
1985
1986
1987 //
1988 // This function returns an element of an array accessed from a constant array. The values are retrieved from
1989 // the symbol table and parse-tree is built for the type of the element. The input
1990 // to the function could either be a symbol node (a[0] where a is a constant array)that represents a
1991 // constant array or it could be the tree representation of the constant array (s.a1[0] where s is a constant structure)
1992 //
1993 TIntermTyped* TParseContext::addConstArrayNode(int index, TIntermTyped* node, const TSourceLoc &line)
1994 {
1995     TIntermTyped* typedNode;
1996     TIntermConstantUnion* tempConstantNode = node->getAsConstantUnion();
1997     TType arrayElementType = node->getType();
1998     arrayElementType.clearArrayness();
1999
2000     if (index >= node->getType().getArraySize()) {
2001         std::stringstream extraInfoStream;
2002         extraInfoStream << "array field selection out of range '" << index << "'";
2003         std::string extraInfo = extraInfoStream.str();
2004         error(line, "", "[", extraInfo.c_str());
2005         recover();
2006         index = 0;
2007     }
2008
2009     int arrayElementSize = arrayElementType.getObjectSize();
2010
2011     if (tempConstantNode) {
2012          ConstantUnion* unionArray = tempConstantNode->getUnionArrayPointer();
2013          typedNode = intermediate.addConstantUnion(&unionArray[arrayElementSize * index], tempConstantNode->getType(), line);
2014     } else {
2015         error(line, "Cannot offset into the array", "Error");
2016         recover();
2017
2018         return 0;
2019     }
2020
2021     return typedNode;
2022 }
2023
2024
2025 //
2026 // This function returns the value of a particular field inside a constant structure from the symbol table.
2027 // If there is an embedded/nested struct, it appropriately calls addConstStructNested or addConstStructFromAggr
2028 // function and returns the parse-tree with the values of the embedded/nested struct.
2029 //
2030 TIntermTyped* TParseContext::addConstStruct(const TString& identifier, TIntermTyped* node, const TSourceLoc &line)
2031 {
2032     const TFieldList &fields = node->getType().getStruct()->fields();
2033     TIntermTyped *typedNode;
2034     int instanceSize = 0;
2035     unsigned int index = 0;
2036     TIntermConstantUnion *tempConstantNode = node->getAsConstantUnion();
2037
2038     for ( index = 0; index < fields.size(); ++index) {
2039         if (fields[index]->name() == identifier) {
2040             break;
2041         } else {
2042             instanceSize += fields[index]->type()->getObjectSize();
2043         }
2044     }
2045
2046     if (tempConstantNode) {
2047          ConstantUnion* constArray = tempConstantNode->getUnionArrayPointer();
2048
2049          typedNode = intermediate.addConstantUnion(constArray+instanceSize, tempConstantNode->getType(), line); // type will be changed in the calling function
2050     } else {
2051         error(line, "Cannot offset into the structure", "Error");
2052         recover();
2053
2054         return 0;
2055     }
2056
2057     return typedNode;
2058 }
2059
2060 //
2061 // Interface/uniform blocks
2062 //
2063 TIntermAggregate* TParseContext::addInterfaceBlock(const TPublicType& typeQualifier, const TSourceLoc& nameLine, const TString& blockName, TFieldList* fieldList,
2064                                                    const TString* instanceName, const TSourceLoc& instanceLine, TIntermTyped* arrayIndex, const TSourceLoc& arrayIndexLine)
2065 {
2066         if(reservedErrorCheck(nameLine, blockName))
2067                 recover();
2068
2069         if(typeQualifier.qualifier != EvqUniform)
2070         {
2071                 error(typeQualifier.line, "invalid qualifier:", getQualifierString(typeQualifier.qualifier), "interface blocks must be uniform");
2072                 recover();
2073         }
2074
2075         TLayoutQualifier blockLayoutQualifier = typeQualifier.layoutQualifier;
2076         if(layoutLocationErrorCheck(typeQualifier.line, blockLayoutQualifier))
2077         {
2078                 recover();
2079         }
2080
2081         if(blockLayoutQualifier.matrixPacking == EmpUnspecified)
2082         {
2083                 blockLayoutQualifier.matrixPacking = mDefaultMatrixPacking;
2084         }
2085
2086         if(blockLayoutQualifier.blockStorage == EbsUnspecified)
2087         {
2088                 blockLayoutQualifier.blockStorage = mDefaultBlockStorage;
2089         }
2090
2091         TSymbol* blockNameSymbol = new TSymbol(&blockName);
2092         if(!symbolTable.declare(*blockNameSymbol)) {
2093                 error(nameLine, "redefinition", blockName.c_str(), "interface block name");
2094                 recover();
2095         }
2096
2097         // check for sampler types and apply layout qualifiers
2098         for(size_t memberIndex = 0; memberIndex < fieldList->size(); ++memberIndex) {
2099                 TField* field = (*fieldList)[memberIndex];
2100                 TType* fieldType = field->type();
2101                 if(IsSampler(fieldType->getBasicType())) {
2102                         error(field->line(), "unsupported type", fieldType->getBasicString(), "sampler types are not allowed in interface blocks");
2103                         recover();
2104                 }
2105
2106                 const TQualifier qualifier = fieldType->getQualifier();
2107                 switch(qualifier)
2108                 {
2109                 case EvqGlobal:
2110                 case EvqUniform:
2111                         break;
2112                 default:
2113                         error(field->line(), "invalid qualifier on interface block member", getQualifierString(qualifier));
2114                         recover();
2115                         break;
2116                 }
2117
2118                 // check layout qualifiers
2119                 TLayoutQualifier fieldLayoutQualifier = fieldType->getLayoutQualifier();
2120                 if(layoutLocationErrorCheck(field->line(), fieldLayoutQualifier))
2121                 {
2122                         recover();
2123                 }
2124
2125                 if(fieldLayoutQualifier.blockStorage != EbsUnspecified)
2126                 {
2127                         error(field->line(), "invalid layout qualifier:", getBlockStorageString(fieldLayoutQualifier.blockStorage), "cannot be used here");
2128                         recover();
2129                 }
2130
2131                 if(fieldLayoutQualifier.matrixPacking == EmpUnspecified)
2132                 {
2133                         fieldLayoutQualifier.matrixPacking = blockLayoutQualifier.matrixPacking;
2134                 }
2135                 else if(!fieldType->isMatrix())
2136                 {
2137                         error(field->line(), "invalid layout qualifier:", getMatrixPackingString(fieldLayoutQualifier.matrixPacking), "can only be used on matrix types");
2138                         recover();
2139                 }
2140
2141                 fieldType->setLayoutQualifier(fieldLayoutQualifier);
2142         }
2143
2144         // add array index
2145         int arraySize = 0;
2146         if(arrayIndex != NULL)
2147         {
2148                 if(arraySizeErrorCheck(arrayIndexLine, arrayIndex, arraySize))
2149                         recover();
2150         }
2151
2152         TInterfaceBlock* interfaceBlock = new TInterfaceBlock(&blockName, fieldList, instanceName, arraySize, blockLayoutQualifier);
2153         TType interfaceBlockType(interfaceBlock, typeQualifier.qualifier, blockLayoutQualifier, arraySize);
2154
2155         TString symbolName = "";
2156         int symbolId = 0;
2157
2158         if(!instanceName)
2159         {
2160                 // define symbols for the members of the interface block
2161                 for(size_t memberIndex = 0; memberIndex < fieldList->size(); ++memberIndex)
2162                 {
2163                         TField* field = (*fieldList)[memberIndex];
2164                         TType* fieldType = field->type();
2165
2166                         // set parent pointer of the field variable
2167                         fieldType->setInterfaceBlock(interfaceBlock);
2168
2169                         TVariable* fieldVariable = new TVariable(&field->name(), *fieldType);
2170                         fieldVariable->setQualifier(typeQualifier.qualifier);
2171
2172                         if(!symbolTable.declare(*fieldVariable)) {
2173                                 error(field->line(), "redefinition", field->name().c_str(), "interface block member name");
2174                                 recover();
2175                         }
2176                 }
2177         }
2178         else
2179         {
2180                 // add a symbol for this interface block
2181                 TVariable* instanceTypeDef = new TVariable(instanceName, interfaceBlockType, false);
2182                 instanceTypeDef->setQualifier(typeQualifier.qualifier);
2183
2184                 if(!symbolTable.declare(*instanceTypeDef)) {
2185                         error(instanceLine, "redefinition", instanceName->c_str(), "interface block instance name");
2186                         recover();
2187                 }
2188
2189                 symbolId = instanceTypeDef->getUniqueId();
2190                 symbolName = instanceTypeDef->getName();
2191         }
2192
2193         TIntermAggregate *aggregate = intermediate.makeAggregate(intermediate.addSymbol(symbolId, symbolName, interfaceBlockType, typeQualifier.line), nameLine);
2194         aggregate->setOp(EOpDeclaration);
2195
2196         exitStructDeclaration();
2197         return aggregate;
2198 }
2199
2200 //
2201 // Parse an array index expression
2202 //
2203 TIntermTyped *TParseContext::addIndexExpression(TIntermTyped *baseExpression, const TSourceLoc &location, TIntermTyped *indexExpression)
2204 {
2205         TIntermTyped *indexedExpression = NULL;
2206
2207         if(!baseExpression->isArray() && !baseExpression->isMatrix() && !baseExpression->isVector())
2208         {
2209                 if(baseExpression->getAsSymbolNode())
2210                 {
2211                         error(location, " left of '[' is not of type array, matrix, or vector ",
2212                                 baseExpression->getAsSymbolNode()->getSymbol().c_str());
2213                 }
2214                 else
2215                 {
2216                         error(location, " left of '[' is not of type array, matrix, or vector ", "expression");
2217                 }
2218                 recover();
2219         }
2220
2221         TIntermConstantUnion *indexConstantUnion = indexExpression->getAsConstantUnion();
2222
2223         if(indexExpression->getQualifier() == EvqConstExpr && indexConstantUnion)
2224         {
2225                 int index = indexConstantUnion->getIConst(0);
2226                 if(index < 0)
2227                 {
2228                         std::stringstream infoStream;
2229                         infoStream << index;
2230                         std::string info = infoStream.str();
2231                         error(location, "negative index", info.c_str());
2232                         recover();
2233                         index = 0;
2234                 }
2235                 if(baseExpression->getType().getQualifier() == EvqConstExpr)
2236                 {
2237                         if(baseExpression->isArray())
2238                         {
2239                                 // constant folding for arrays
2240                                 indexedExpression = addConstArrayNode(index, baseExpression, location);
2241                         }
2242                         else if(baseExpression->isVector())
2243                         {
2244                                 // constant folding for vectors
2245                                 TVectorFields fields;
2246                                 fields.num = 1;
2247                                 fields.offsets[0] = index; // need to do it this way because v.xy sends fields integer array
2248                                 indexedExpression = addConstVectorNode(fields, baseExpression, location);
2249                         }
2250                         else if(baseExpression->isMatrix())
2251                         {
2252                                 // constant folding for matrices
2253                                 indexedExpression = addConstMatrixNode(index, baseExpression, location);
2254                         }
2255                 }
2256                 else
2257                 {
2258                         int safeIndex = -1;
2259
2260                         if(baseExpression->isArray())
2261                         {
2262                                 if(index >= baseExpression->getType().getArraySize())
2263                                 {
2264                                         std::stringstream extraInfoStream;
2265                                         extraInfoStream << "array index out of range '" << index << "'";
2266                                         std::string extraInfo = extraInfoStream.str();
2267                                         error(location, "", "[", extraInfo.c_str());
2268                                         recover();
2269                                         safeIndex = baseExpression->getType().getArraySize() - 1;
2270                                 }
2271                         }
2272                         else if((baseExpression->isVector() || baseExpression->isMatrix()) &&
2273                                 baseExpression->getType().getNominalSize() <= index)
2274                         {
2275                                 std::stringstream extraInfoStream;
2276                                 extraInfoStream << "field selection out of range '" << index << "'";
2277                                 std::string extraInfo = extraInfoStream.str();
2278                                 error(location, "", "[", extraInfo.c_str());
2279                                 recover();
2280                                 safeIndex = baseExpression->getType().getNominalSize() - 1;
2281                         }
2282
2283                         // Don't modify the data of the previous constant union, because it can point
2284                         // to builtins, like gl_MaxDrawBuffers. Instead use a new sanitized object.
2285                         if(safeIndex != -1)
2286                         {
2287                                 ConstantUnion *safeConstantUnion = new ConstantUnion();
2288                                 safeConstantUnion->setIConst(safeIndex);
2289                                 indexConstantUnion->replaceConstantUnion(safeConstantUnion);
2290                         }
2291
2292                         indexedExpression = intermediate.addIndex(EOpIndexDirect, baseExpression, indexExpression, location);
2293                 }
2294         }
2295         else
2296         {
2297                 if(baseExpression->isInterfaceBlock())
2298                 {
2299                         error(location, "",
2300                                 "[", "array indexes for interface blocks arrays must be constant integral expressions");
2301                         recover();
2302                 }
2303                 else if(baseExpression->getQualifier() == EvqFragmentOut)
2304                 {
2305                         error(location, "", "[", "array indexes for fragment outputs must be constant integral expressions");
2306                         recover();
2307                 }
2308
2309                 indexedExpression = intermediate.addIndex(EOpIndexIndirect, baseExpression, indexExpression, location);
2310         }
2311
2312         if(indexedExpression == 0)
2313         {
2314                 ConstantUnion *unionArray = new ConstantUnion[1];
2315                 unionArray->setFConst(0.0f);
2316                 indexedExpression = intermediate.addConstantUnion(unionArray, TType(EbtFloat, EbpHigh, EvqConstExpr), location);
2317         }
2318         else if(baseExpression->isArray())
2319         {
2320                 const TType &baseType = baseExpression->getType();
2321                 if(baseType.getStruct())
2322                 {
2323                         TType copyOfType(baseType.getStruct());
2324                         indexedExpression->setType(copyOfType);
2325                 }
2326                 else if(baseType.isInterfaceBlock())
2327                 {
2328                         TType copyOfType(baseType.getInterfaceBlock(), baseType.getQualifier(), baseType.getLayoutQualifier(), 0);
2329                         indexedExpression->setType(copyOfType);
2330                 }
2331                 else
2332                 {
2333                         indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(),
2334                                 EvqTemporary, static_cast<unsigned char>(baseExpression->getNominalSize()),
2335                                 static_cast<unsigned char>(baseExpression->getSecondarySize())));
2336                 }
2337
2338                 if(baseExpression->getType().getQualifier() == EvqConstExpr)
2339                 {
2340                         indexedExpression->getTypePointer()->setQualifier(EvqConstExpr);
2341                 }
2342         }
2343         else if(baseExpression->isMatrix())
2344         {
2345                 TQualifier qualifier = baseExpression->getType().getQualifier() == EvqConstExpr ? EvqConstExpr : EvqTemporary;
2346                 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(),
2347                         qualifier, static_cast<unsigned char>(baseExpression->getSecondarySize())));
2348         }
2349         else if(baseExpression->isVector())
2350         {
2351                 TQualifier qualifier = baseExpression->getType().getQualifier() == EvqConstExpr ? EvqConstExpr : EvqTemporary;
2352                 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(), qualifier));
2353         }
2354         else
2355         {
2356                 indexedExpression->setType(baseExpression->getType());
2357         }
2358
2359         return indexedExpression;
2360 }
2361
2362 TIntermTyped *TParseContext::addFieldSelectionExpression(TIntermTyped *baseExpression, const TSourceLoc &dotLocation,
2363         const TString &fieldString, const TSourceLoc &fieldLocation)
2364 {
2365         TIntermTyped *indexedExpression = NULL;
2366
2367         if(baseExpression->isArray())
2368         {
2369                 error(fieldLocation, "cannot apply dot operator to an array", ".");
2370                 recover();
2371         }
2372
2373         if(baseExpression->isVector())
2374         {
2375                 TVectorFields fields;
2376                 if(!parseVectorFields(fieldString, baseExpression->getNominalSize(), fields, fieldLocation))
2377                 {
2378                         fields.num = 1;
2379                         fields.offsets[0] = 0;
2380                         recover();
2381                 }
2382
2383                 if(baseExpression->getType().getQualifier() == EvqConstExpr)
2384                 {
2385                         // constant folding for vector fields
2386                         indexedExpression = addConstVectorNode(fields, baseExpression, fieldLocation);
2387                         if(indexedExpression == 0)
2388                         {
2389                                 recover();
2390                                 indexedExpression = baseExpression;
2391                         }
2392                         else
2393                         {
2394                                 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(),
2395                                         EvqConstExpr, (unsigned char)(fieldString).size()));
2396                         }
2397                 }
2398                 else
2399                 {
2400                         TString vectorString = fieldString;
2401                         TIntermTyped *index = intermediate.addSwizzle(fields, fieldLocation);
2402                         indexedExpression = intermediate.addIndex(EOpVectorSwizzle, baseExpression, index, dotLocation);
2403                         indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(),
2404                                 EvqTemporary, (unsigned char)vectorString.size()));
2405                 }
2406         }
2407         else if(baseExpression->isMatrix())
2408         {
2409                 TMatrixFields fields;
2410                 if(!parseMatrixFields(fieldString, baseExpression->getNominalSize(), baseExpression->getSecondarySize(), fields, fieldLocation))
2411                 {
2412                         fields.wholeRow = false;
2413                         fields.wholeCol = false;
2414                         fields.row = 0;
2415                         fields.col = 0;
2416                         recover();
2417                 }
2418
2419                 if(fields.wholeRow || fields.wholeCol)
2420                 {
2421                         error(dotLocation, " non-scalar fields not implemented yet", ".");
2422                         recover();
2423                         ConstantUnion *unionArray = new ConstantUnion[1];
2424                         unionArray->setIConst(0);
2425                         TIntermTyped *index = intermediate.addConstantUnion(unionArray, TType(EbtInt, EbpUndefined, EvqConstExpr),
2426                                 fieldLocation);
2427                         indexedExpression = intermediate.addIndex(EOpIndexDirect, baseExpression, index, dotLocation);
2428                         indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(),
2429                                 EvqTemporary, static_cast<unsigned char>(baseExpression->getNominalSize()),
2430                                 static_cast<unsigned char>(baseExpression->getSecondarySize())));
2431                 }
2432                 else
2433                 {
2434                         ConstantUnion *unionArray = new ConstantUnion[1];
2435                         unionArray->setIConst(fields.col * baseExpression->getSecondarySize() + fields.row);
2436                         TIntermTyped *index = intermediate.addConstantUnion(unionArray, TType(EbtInt, EbpUndefined, EvqConstExpr),
2437                                 fieldLocation);
2438                         indexedExpression = intermediate.addIndex(EOpIndexDirect, baseExpression, index, dotLocation);
2439                         indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision()));
2440                 }
2441         }
2442         else if(baseExpression->getBasicType() == EbtStruct)
2443         {
2444                 bool fieldFound = false;
2445                 const TFieldList &fields = baseExpression->getType().getStruct()->fields();
2446                 if(fields.empty())
2447                 {
2448                         error(dotLocation, "structure has no fields", "Internal Error");
2449                         recover();
2450                         indexedExpression = baseExpression;
2451                 }
2452                 else
2453                 {
2454                         unsigned int i;
2455                         for(i = 0; i < fields.size(); ++i)
2456                         {
2457                                 if(fields[i]->name() == fieldString)
2458                                 {
2459                                         fieldFound = true;
2460                                         break;
2461                                 }
2462                         }
2463                         if(fieldFound)
2464                         {
2465                                 if(baseExpression->getType().getQualifier() == EvqConstExpr)
2466                                 {
2467                                         indexedExpression = addConstStruct(fieldString, baseExpression, dotLocation);
2468                                         if(indexedExpression == 0)
2469                                         {
2470                                                 recover();
2471                                                 indexedExpression = baseExpression;
2472                                         }
2473                                         else
2474                                         {
2475                                                 indexedExpression->setType(*fields[i]->type());
2476                                                 // change the qualifier of the return type, not of the structure field
2477                                                 // as the structure definition is shared between various structures.
2478                                                 indexedExpression->getTypePointer()->setQualifier(EvqConstExpr);
2479                                         }
2480                                 }
2481                                 else
2482                                 {
2483                                         ConstantUnion *unionArray = new ConstantUnion[1];
2484                                         unionArray->setIConst(i);
2485                                         TIntermTyped *index = intermediate.addConstantUnion(unionArray, *fields[i]->type(), fieldLocation);
2486                                         indexedExpression = intermediate.addIndex(EOpIndexDirectStruct, baseExpression, index, dotLocation);
2487                                         indexedExpression->setType(*fields[i]->type());
2488                                 }
2489                         }
2490                         else
2491                         {
2492                                 error(dotLocation, " no such field in structure", fieldString.c_str());
2493                                 recover();
2494                                 indexedExpression = baseExpression;
2495                         }
2496                 }
2497         }
2498         else if(baseExpression->isInterfaceBlock())
2499         {
2500                 bool fieldFound = false;
2501                 const TFieldList &fields = baseExpression->getType().getInterfaceBlock()->fields();
2502                 if(fields.empty())
2503                 {
2504                         error(dotLocation, "interface block has no fields", "Internal Error");
2505                         recover();
2506                         indexedExpression = baseExpression;
2507                 }
2508                 else
2509                 {
2510                         unsigned int i;
2511                         for(i = 0; i < fields.size(); ++i)
2512                         {
2513                                 if(fields[i]->name() == fieldString)
2514                                 {
2515                                         fieldFound = true;
2516                                         break;
2517                                 }
2518                         }
2519                         if(fieldFound)
2520                         {
2521                                 ConstantUnion *unionArray = new ConstantUnion[1];
2522                                 unionArray->setIConst(i);
2523                                 TIntermTyped *index = intermediate.addConstantUnion(unionArray, *fields[i]->type(), fieldLocation);
2524                                 indexedExpression = intermediate.addIndex(EOpIndexDirectInterfaceBlock, baseExpression, index,
2525                                         dotLocation);
2526                                 indexedExpression->setType(*fields[i]->type());
2527                         }
2528                         else
2529                         {
2530                                 error(dotLocation, " no such field in interface block", fieldString.c_str());
2531                                 recover();
2532                                 indexedExpression = baseExpression;
2533                         }
2534                 }
2535         }
2536         else
2537         {
2538                 if(mShaderVersion < 300)
2539                 {
2540                         error(dotLocation, " field selection requires structure, vector, or matrix on left hand side",
2541                                 fieldString.c_str());
2542                 }
2543                 else
2544                 {
2545                         error(dotLocation,
2546                                 " field selection requires structure, vector, matrix, or interface block on left hand side",
2547                                 fieldString.c_str());
2548                 }
2549                 recover();
2550                 indexedExpression = baseExpression;
2551         }
2552
2553         return indexedExpression;
2554 }
2555
2556 TLayoutQualifier TParseContext::parseLayoutQualifier(const TString &qualifierType, const TSourceLoc& qualifierTypeLine)
2557 {
2558     TLayoutQualifier qualifier;
2559
2560     qualifier.location = -1;
2561         qualifier.matrixPacking = EmpUnspecified;
2562         qualifier.blockStorage = EbsUnspecified;
2563
2564         if(qualifierType == "shared")
2565         {
2566                 qualifier.blockStorage = EbsShared;
2567         }
2568         else if(qualifierType == "packed")
2569         {
2570                 qualifier.blockStorage = EbsPacked;
2571         }
2572         else if(qualifierType == "std140")
2573         {
2574                 qualifier.blockStorage = EbsStd140;
2575         }
2576         else if(qualifierType == "row_major")
2577         {
2578                 qualifier.matrixPacking = EmpRowMajor;
2579         }
2580         else if(qualifierType == "column_major")
2581         {
2582                 qualifier.matrixPacking = EmpColumnMajor;
2583         }
2584         else if(qualifierType == "location")
2585     {
2586         error(qualifierTypeLine, "invalid layout qualifier", qualifierType.c_str(), "location requires an argument");
2587         recover();
2588     }
2589     else
2590     {
2591         error(qualifierTypeLine, "invalid layout qualifier", qualifierType.c_str());
2592         recover();
2593     }
2594
2595     return qualifier;
2596 }
2597
2598 TLayoutQualifier TParseContext::parseLayoutQualifier(const TString &qualifierType, const TSourceLoc& qualifierTypeLine, const TString &intValueString, int intValue, const TSourceLoc& intValueLine)
2599 {
2600     TLayoutQualifier qualifier;
2601
2602     qualifier.location = -1;
2603     qualifier.matrixPacking = EmpUnspecified;
2604     qualifier.blockStorage = EbsUnspecified;
2605
2606     if (qualifierType != "location")
2607     {
2608         error(qualifierTypeLine, "invalid layout qualifier", qualifierType.c_str(), "only location may have arguments");
2609         recover();
2610     }
2611     else
2612     {
2613         // must check that location is non-negative
2614         if (intValue < 0)
2615         {
2616             error(intValueLine, "out of range:", intValueString.c_str(), "location must be non-negative");
2617             recover();
2618         }
2619         else
2620         {
2621             qualifier.location = intValue;
2622         }
2623     }
2624
2625     return qualifier;
2626 }
2627
2628 TLayoutQualifier TParseContext::joinLayoutQualifiers(TLayoutQualifier leftQualifier, TLayoutQualifier rightQualifier)
2629 {
2630     TLayoutQualifier joinedQualifier = leftQualifier;
2631
2632     if (rightQualifier.location != -1)
2633     {
2634         joinedQualifier.location = rightQualifier.location;
2635     }
2636         if(rightQualifier.matrixPacking != EmpUnspecified)
2637         {
2638                 joinedQualifier.matrixPacking = rightQualifier.matrixPacking;
2639         }
2640         if(rightQualifier.blockStorage != EbsUnspecified)
2641         {
2642                 joinedQualifier.blockStorage = rightQualifier.blockStorage;
2643         }
2644
2645     return joinedQualifier;
2646 }
2647
2648
2649 TPublicType TParseContext::joinInterpolationQualifiers(const TSourceLoc &interpolationLoc, TQualifier interpolationQualifier,
2650         const TSourceLoc &storageLoc, TQualifier storageQualifier)
2651 {
2652         TQualifier mergedQualifier = EvqSmoothIn;
2653
2654         if(storageQualifier == EvqFragmentIn) {
2655                 if(interpolationQualifier == EvqSmooth)
2656                         mergedQualifier = EvqSmoothIn;
2657                 else if(interpolationQualifier == EvqFlat)
2658                         mergedQualifier = EvqFlatIn;
2659                 else UNREACHABLE(interpolationQualifier);
2660         }
2661         else if(storageQualifier == EvqCentroidIn) {
2662                 if(interpolationQualifier == EvqSmooth)
2663                         mergedQualifier = EvqCentroidIn;
2664                 else if(interpolationQualifier == EvqFlat)
2665                         mergedQualifier = EvqFlatIn;
2666                 else UNREACHABLE(interpolationQualifier);
2667         }
2668         else if(storageQualifier == EvqVertexOut) {
2669                 if(interpolationQualifier == EvqSmooth)
2670                         mergedQualifier = EvqSmoothOut;
2671                 else if(interpolationQualifier == EvqFlat)
2672                         mergedQualifier = EvqFlatOut;
2673                 else UNREACHABLE(interpolationQualifier);
2674         }
2675         else if(storageQualifier == EvqCentroidOut) {
2676                 if(interpolationQualifier == EvqSmooth)
2677                         mergedQualifier = EvqCentroidOut;
2678                 else if(interpolationQualifier == EvqFlat)
2679                         mergedQualifier = EvqFlatOut;
2680                 else UNREACHABLE(interpolationQualifier);
2681         }
2682         else {
2683                 error(interpolationLoc, "interpolation qualifier requires a fragment 'in' or vertex 'out' storage qualifier", getQualifierString(interpolationQualifier));
2684                 recover();
2685
2686                 mergedQualifier = storageQualifier;
2687         }
2688
2689         TPublicType type;
2690         type.setBasic(EbtVoid, mergedQualifier, storageLoc);
2691         return type;
2692 }
2693
2694 TFieldList *TParseContext::addStructDeclaratorList(const TPublicType &typeSpecifier, TFieldList *fieldList)
2695 {
2696         if(voidErrorCheck(typeSpecifier.line, (*fieldList)[0]->name(), typeSpecifier.type))
2697         {
2698                 recover();
2699         }
2700
2701         for(unsigned int i = 0; i < fieldList->size(); ++i)
2702         {
2703                 //
2704                 // Careful not to replace already known aspects of type, like array-ness
2705                 //
2706                 TType *type = (*fieldList)[i]->type();
2707                 type->setBasicType(typeSpecifier.type);
2708                 type->setNominalSize(typeSpecifier.primarySize);
2709                 type->setSecondarySize(typeSpecifier.secondarySize);
2710                 type->setPrecision(typeSpecifier.precision);
2711                 type->setQualifier(typeSpecifier.qualifier);
2712                 type->setLayoutQualifier(typeSpecifier.layoutQualifier);
2713
2714                 // don't allow arrays of arrays
2715                 if(type->isArray())
2716                 {
2717                         if(arrayTypeErrorCheck(typeSpecifier.line, typeSpecifier))
2718                                 recover();
2719                 }
2720                 if(typeSpecifier.array)
2721                         type->setArraySize(typeSpecifier.arraySize);
2722                 if(typeSpecifier.userDef)
2723                 {
2724                         type->setStruct(typeSpecifier.userDef->getStruct());
2725                 }
2726
2727                 if(structNestingErrorCheck(typeSpecifier.line, *(*fieldList)[i]))
2728                 {
2729                         recover();
2730                 }
2731         }
2732
2733         return fieldList;
2734 }
2735
2736 TPublicType TParseContext::addStructure(const TSourceLoc &structLine, const TSourceLoc &nameLine,
2737         const TString *structName, TFieldList *fieldList)
2738 {
2739         TStructure *structure = new TStructure(structName, fieldList);
2740         TType *structureType = new TType(structure);
2741
2742         // Store a bool in the struct if we're at global scope, to allow us to
2743         // skip the local struct scoping workaround in HLSL.
2744         structure->setUniqueId(TSymbolTableLevel::nextUniqueId());
2745         structure->setAtGlobalScope(symbolTable.atGlobalLevel());
2746
2747         if(!structName->empty())
2748         {
2749                 if(reservedErrorCheck(nameLine, *structName))
2750                 {
2751                         recover();
2752                 }
2753                 TVariable *userTypeDef = new TVariable(structName, *structureType, true);
2754                 if(!symbolTable.declare(*userTypeDef))
2755                 {
2756                         error(nameLine, "redefinition", structName->c_str(), "struct");
2757                         recover();
2758                 }
2759         }
2760
2761         // ensure we do not specify any storage qualifiers on the struct members
2762         for(unsigned int typeListIndex = 0; typeListIndex < fieldList->size(); typeListIndex++)
2763         {
2764                 const TField &field = *(*fieldList)[typeListIndex];
2765                 const TQualifier qualifier = field.type()->getQualifier();
2766                 switch(qualifier)
2767                 {
2768                 case EvqGlobal:
2769                 case EvqTemporary:
2770                         break;
2771                 default:
2772                         error(field.line(), "invalid qualifier on struct member", getQualifierString(qualifier));
2773                         recover();
2774                         break;
2775                 }
2776         }
2777
2778         TPublicType publicType;
2779         publicType.setBasic(EbtStruct, EvqTemporary, structLine);
2780         publicType.userDef = structureType;
2781         exitStructDeclaration();
2782
2783         return publicType;
2784 }
2785
2786 bool TParseContext::enterStructDeclaration(const TSourceLoc &line, const TString& identifier)
2787 {
2788     ++mStructNestingLevel;
2789
2790     // Embedded structure definitions are not supported per GLSL ES spec.
2791     // They aren't allowed in GLSL either, but we need to detect this here
2792     // so we don't rely on the GLSL compiler to catch it.
2793     if (mStructNestingLevel > 1) {
2794         error(line, "", "Embedded struct definitions are not allowed");
2795         return true;
2796     }
2797
2798     return false;
2799 }
2800
2801 void TParseContext::exitStructDeclaration()
2802 {
2803     --mStructNestingLevel;
2804 }
2805
2806 bool TParseContext::structNestingErrorCheck(const TSourceLoc &line, const TField &field)
2807 {
2808         static const int kWebGLMaxStructNesting = 4;
2809
2810         if(field.type()->getBasicType() != EbtStruct)
2811         {
2812                 return false;
2813         }
2814
2815         // We're already inside a structure definition at this point, so add
2816         // one to the field's struct nesting.
2817         if(1 + field.type()->getDeepestStructNesting() > kWebGLMaxStructNesting)
2818         {
2819                 std::stringstream reasonStream;
2820                 reasonStream << "Reference of struct type "
2821                         << field.type()->getStruct()->name().c_str()
2822                         << " exceeds maximum allowed nesting level of "
2823                         << kWebGLMaxStructNesting;
2824                 std::string reason = reasonStream.str();
2825                 error(line, reason.c_str(), field.name().c_str(), "");
2826                 return true;
2827         }
2828
2829         return false;
2830 }
2831
2832 TIntermTyped *TParseContext::createUnaryMath(TOperator op, TIntermTyped *child, const TSourceLoc &loc, const TType *funcReturnType)
2833 {
2834         if(child == nullptr)
2835         {
2836                 return nullptr;
2837         }
2838
2839         switch(op)
2840         {
2841         case EOpLogicalNot:
2842                 if(child->getBasicType() != EbtBool ||
2843                         child->isMatrix() ||
2844                         child->isArray() ||
2845                         child->isVector())
2846                 {
2847                         return nullptr;
2848                 }
2849                 break;
2850         case EOpBitwiseNot:
2851                 if((child->getBasicType() != EbtInt && child->getBasicType() != EbtUInt) ||
2852                         child->isMatrix() ||
2853                         child->isArray())
2854                 {
2855                         return nullptr;
2856                 }
2857                 break;
2858         case EOpPostIncrement:
2859         case EOpPreIncrement:
2860         case EOpPostDecrement:
2861         case EOpPreDecrement:
2862         case EOpNegative:
2863                 if(child->getBasicType() == EbtStruct ||
2864                         child->getBasicType() == EbtBool ||
2865                         child->isArray())
2866                 {
2867                         return nullptr;
2868                 }
2869                 // Operators for built-ins are already type checked against their prototype.
2870         default:
2871                 break;
2872         }
2873
2874         return intermediate.addUnaryMath(op, child, loc); // FIXME , funcReturnType);
2875 }
2876
2877 TIntermTyped *TParseContext::addUnaryMath(TOperator op, TIntermTyped *child, const TSourceLoc &loc)
2878 {
2879         TIntermTyped *node = createUnaryMath(op, child, loc, nullptr);
2880         if(node == nullptr)
2881         {
2882                 unaryOpError(loc, getOperatorString(op), child->getCompleteString());
2883                 recover();
2884                 return child;
2885         }
2886         return node;
2887 }
2888
2889 TIntermTyped *TParseContext::addUnaryMathLValue(TOperator op, TIntermTyped *child, const TSourceLoc &loc)
2890 {
2891         if(lValueErrorCheck(loc, getOperatorString(op), child))
2892                 recover();
2893         return addUnaryMath(op, child, loc);
2894 }
2895
2896 bool TParseContext::binaryOpCommonCheck(TOperator op, TIntermTyped *left, TIntermTyped *right, const TSourceLoc &loc)
2897 {
2898         if(left->isArray() || right->isArray())
2899         {
2900                 if(mShaderVersion < 300)
2901                 {
2902                         error(loc, "Invalid operation for arrays", getOperatorString(op));
2903                         return false;
2904                 }
2905
2906                 if(left->isArray() != right->isArray())
2907                 {
2908                         error(loc, "array / non-array mismatch", getOperatorString(op));
2909                         return false;
2910                 }
2911
2912                 switch(op)
2913                 {
2914                 case EOpEqual:
2915                 case EOpNotEqual:
2916                 case EOpAssign:
2917                 case EOpInitialize:
2918                         break;
2919                 default:
2920                         error(loc, "Invalid operation for arrays", getOperatorString(op));
2921                         return false;
2922                 }
2923                 // At this point, size of implicitly sized arrays should be resolved.
2924                 if(left->getArraySize() != right->getArraySize())
2925                 {
2926                         error(loc, "array size mismatch", getOperatorString(op));
2927                         return false;
2928                 }
2929         }
2930
2931         // Check ops which require integer / ivec parameters
2932         bool isBitShift = false;
2933         switch(op)
2934         {
2935         case EOpBitShiftLeft:
2936         case EOpBitShiftRight:
2937         case EOpBitShiftLeftAssign:
2938         case EOpBitShiftRightAssign:
2939                 // Unsigned can be bit-shifted by signed and vice versa, but we need to
2940                 // check that the basic type is an integer type.
2941                 isBitShift = true;
2942                 if(!IsInteger(left->getBasicType()) || !IsInteger(right->getBasicType()))
2943                 {
2944                         return false;
2945                 }
2946                 break;
2947         case EOpBitwiseAnd:
2948         case EOpBitwiseXor:
2949         case EOpBitwiseOr:
2950         case EOpBitwiseAndAssign:
2951         case EOpBitwiseXorAssign:
2952         case EOpBitwiseOrAssign:
2953                 // It is enough to check the type of only one operand, since later it
2954                 // is checked that the operand types match.
2955                 if(!IsInteger(left->getBasicType()))
2956                 {
2957                         return false;
2958                 }
2959                 break;
2960         default:
2961                 break;
2962         }
2963
2964         // GLSL ES 1.00 and 3.00 do not support implicit type casting.
2965         // So the basic type should usually match.
2966         if(!isBitShift && left->getBasicType() != right->getBasicType())
2967         {
2968                 return false;
2969         }
2970
2971         // Check that type sizes match exactly on ops that require that.
2972         // Also check restrictions for structs that contain arrays or samplers.
2973         switch(op)
2974         {
2975         case EOpAssign:
2976         case EOpInitialize:
2977         case EOpEqual:
2978         case EOpNotEqual:
2979                 // ESSL 1.00 sections 5.7, 5.8, 5.9
2980                 if(mShaderVersion < 300 && left->getType().isStructureContainingArrays())
2981                 {
2982                         error(loc, "undefined operation for structs containing arrays", getOperatorString(op));
2983                         return false;
2984                 }
2985                 // Samplers as l-values are disallowed also in ESSL 3.00, see section 4.1.7,
2986                 // we interpret the spec so that this extends to structs containing samplers,
2987                 // similarly to ESSL 1.00 spec.
2988                 if((mShaderVersion < 300 || op == EOpAssign || op == EOpInitialize) &&
2989                         left->getType().isStructureContainingSamplers())
2990                 {
2991                         error(loc, "undefined operation for structs containing samplers", getOperatorString(op));
2992                         return false;
2993                 }
2994         case EOpLessThan:
2995         case EOpGreaterThan:
2996         case EOpLessThanEqual:
2997         case EOpGreaterThanEqual:
2998                 if((left->getNominalSize() != right->getNominalSize()) ||
2999                         (left->getSecondarySize() != right->getSecondarySize()))
3000                 {
3001                         return false;
3002                 }
3003         default:
3004                 break;
3005         }
3006
3007         return true;
3008 }
3009
3010 TIntermSwitch *TParseContext::addSwitch(TIntermTyped *init, TIntermAggregate *statementList, const TSourceLoc &loc)
3011 {
3012         TBasicType switchType = init->getBasicType();
3013         if((switchType != EbtInt && switchType != EbtUInt) ||
3014            init->isMatrix() ||
3015            init->isArray() ||
3016            init->isVector())
3017         {
3018                 error(init->getLine(), "init-expression in a switch statement must be a scalar integer", "switch");
3019                 recover();
3020                 return nullptr;
3021         }
3022
3023         if(statementList)
3024         {
3025                 if(!ValidateSwitch::validate(switchType, this, statementList, loc))
3026                 {
3027                         recover();
3028                         return nullptr;
3029                 }
3030         }
3031
3032         TIntermSwitch *node = intermediate.addSwitch(init, statementList, loc);
3033         if(node == nullptr)
3034         {
3035                 error(loc, "erroneous switch statement", "switch");
3036                 recover();
3037                 return nullptr;
3038         }
3039         return node;
3040 }
3041
3042 TIntermCase *TParseContext::addCase(TIntermTyped *condition, const TSourceLoc &loc)
3043 {
3044         if(mSwitchNestingLevel == 0)
3045         {
3046                 error(loc, "case labels need to be inside switch statements", "case");
3047                 recover();
3048                 return nullptr;
3049         }
3050         if(condition == nullptr)
3051         {
3052                 error(loc, "case label must have a condition", "case");
3053                 recover();
3054                 return nullptr;
3055         }
3056         if((condition->getBasicType() != EbtInt && condition->getBasicType() != EbtUInt) ||
3057            condition->isMatrix() ||
3058            condition->isArray() ||
3059            condition->isVector())
3060         {
3061                 error(condition->getLine(), "case label must be a scalar integer", "case");
3062                 recover();
3063         }
3064         TIntermConstantUnion *conditionConst = condition->getAsConstantUnion();
3065         if(conditionConst == nullptr)
3066         {
3067                 error(condition->getLine(), "case label must be constant", "case");
3068                 recover();
3069         }
3070         TIntermCase *node = intermediate.addCase(condition, loc);
3071         if(node == nullptr)
3072         {
3073                 error(loc, "erroneous case statement", "case");
3074                 recover();
3075                 return nullptr;
3076         }
3077         return node;
3078 }
3079
3080 TIntermCase *TParseContext::addDefault(const TSourceLoc &loc)
3081 {
3082         if(mSwitchNestingLevel == 0)
3083         {
3084                 error(loc, "default labels need to be inside switch statements", "default");
3085                 recover();
3086                 return nullptr;
3087         }
3088         TIntermCase *node = intermediate.addCase(nullptr, loc);
3089         if(node == nullptr)
3090         {
3091                 error(loc, "erroneous default statement", "default");
3092                 recover();
3093                 return nullptr;
3094         }
3095         return node;
3096 }
3097 TIntermTyped *TParseContext::createAssign(TOperator op, TIntermTyped *left, TIntermTyped *right, const TSourceLoc &loc)
3098 {
3099         if(binaryOpCommonCheck(op, left, right, loc))
3100         {
3101                 return intermediate.addAssign(op, left, right, loc);
3102         }
3103         return nullptr;
3104 }
3105
3106 TIntermTyped *TParseContext::addAssign(TOperator op, TIntermTyped *left, TIntermTyped *right, const TSourceLoc &loc)
3107 {
3108         TIntermTyped *node = createAssign(op, left, right, loc);
3109         if(node == nullptr)
3110         {
3111                 assignError(loc, "assign", left->getCompleteString(), right->getCompleteString());
3112                 recover();
3113                 return left;
3114         }
3115         return node;
3116 }
3117
3118 TIntermTyped *TParseContext::addBinaryMathInternal(TOperator op, TIntermTyped *left, TIntermTyped *right,
3119         const TSourceLoc &loc)
3120 {
3121         if(!binaryOpCommonCheck(op, left, right, loc))
3122                 return nullptr;
3123
3124         switch(op)
3125         {
3126         case EOpEqual:
3127         case EOpNotEqual:
3128                 break;
3129         case EOpLessThan:
3130         case EOpGreaterThan:
3131         case EOpLessThanEqual:
3132         case EOpGreaterThanEqual:
3133                 ASSERT(!left->isArray() && !right->isArray());
3134                 if(left->isMatrix() || left->isVector() ||
3135                         left->getBasicType() == EbtStruct)
3136                 {
3137                         return nullptr;
3138                 }
3139                 break;
3140         case EOpLogicalOr:
3141         case EOpLogicalXor:
3142         case EOpLogicalAnd:
3143                 ASSERT(!left->isArray() && !right->isArray());
3144                 if(left->getBasicType() != EbtBool ||
3145                         left->isMatrix() || left->isVector())
3146                 {
3147                         return nullptr;
3148                 }
3149                 break;
3150         case EOpAdd:
3151         case EOpSub:
3152         case EOpDiv:
3153         case EOpMul:
3154                 ASSERT(!left->isArray() && !right->isArray());
3155                 if(left->getBasicType() == EbtStruct || left->getBasicType() == EbtBool)
3156                 {
3157                         return nullptr;
3158                 }
3159                 break;
3160         case EOpIMod:
3161                 ASSERT(!left->isArray() && !right->isArray());
3162                 // Note that this is only for the % operator, not for mod()
3163                 if(left->getBasicType() == EbtStruct || left->getBasicType() == EbtBool || left->getBasicType() == EbtFloat)
3164                 {
3165                         return nullptr;
3166                 }
3167                 break;
3168                 // Note that for bitwise ops, type checking is done in promote() to
3169                 // share code between ops and compound assignment
3170         default:
3171                 break;
3172         }
3173
3174         return intermediate.addBinaryMath(op, left, right, loc);
3175 }
3176
3177 TIntermTyped *TParseContext::addBinaryMath(TOperator op, TIntermTyped *left, TIntermTyped *right, const TSourceLoc &loc)
3178 {
3179         TIntermTyped *node = addBinaryMathInternal(op, left, right, loc);
3180         if(node == 0)
3181         {
3182                 binaryOpError(loc, getOperatorString(op), left->getCompleteString(), right->getCompleteString());
3183                 recover();
3184                 return left;
3185         }
3186         return node;
3187 }
3188
3189 TIntermTyped *TParseContext::addBinaryMathBooleanResult(TOperator op, TIntermTyped *left, TIntermTyped *right, const TSourceLoc &loc)
3190 {
3191         TIntermTyped *node = addBinaryMathInternal(op, left, right, loc);
3192         if(node == 0)
3193         {
3194                 binaryOpError(loc, getOperatorString(op), left->getCompleteString(), right->getCompleteString());
3195                 recover();
3196                 ConstantUnion *unionArray = new ConstantUnion[1];
3197                 unionArray->setBConst(false);
3198                 return intermediate.addConstantUnion(unionArray, TType(EbtBool, EbpUndefined, EvqConstExpr), loc);
3199         }
3200         return node;
3201 }
3202
3203 TIntermBranch *TParseContext::addBranch(TOperator op, const TSourceLoc &loc)
3204 {
3205         switch(op)
3206         {
3207         case EOpContinue:
3208                 if(mLoopNestingLevel <= 0)
3209                 {
3210                         error(loc, "continue statement only allowed in loops", "");
3211                         recover();
3212                 }
3213                 break;
3214         case EOpBreak:
3215                 if(mLoopNestingLevel <= 0 && mSwitchNestingLevel <= 0)
3216                 {
3217                         error(loc, "break statement only allowed in loops and switch statements", "");
3218                         recover();
3219                 }
3220                 break;
3221         case EOpReturn:
3222                 if(mCurrentFunctionType->getBasicType() != EbtVoid)
3223                 {
3224                         error(loc, "non-void function must return a value", "return");
3225                         recover();
3226                 }
3227                 break;
3228         default:
3229                 // No checks for discard
3230                 break;
3231         }
3232         return intermediate.addBranch(op, loc);
3233 }
3234
3235 TIntermBranch *TParseContext::addBranch(TOperator op, TIntermTyped *returnValue, const TSourceLoc &loc)
3236 {
3237         ASSERT(op == EOpReturn);
3238         mFunctionReturnsValue = true;
3239         if(mCurrentFunctionType->getBasicType() == EbtVoid)
3240         {
3241                 error(loc, "void function cannot return a value", "return");
3242                 recover();
3243         }
3244         else if(*mCurrentFunctionType != returnValue->getType())
3245         {
3246                 error(loc, "function return is not matching type:", "return");
3247                 recover();
3248         }
3249         return intermediate.addBranch(op, returnValue, loc);
3250 }
3251
3252 TIntermTyped *TParseContext::addFunctionCallOrMethod(TFunction *fnCall, TIntermNode *paramNode, TIntermNode *thisNode, const TSourceLoc &loc, bool *fatalError)
3253 {
3254         *fatalError = false;
3255         TOperator op = fnCall->getBuiltInOp();
3256         TIntermTyped *callNode = nullptr;
3257
3258         if(thisNode != nullptr)
3259         {
3260                 ConstantUnion *unionArray = new ConstantUnion[1];
3261                 int arraySize = 0;
3262                 TIntermTyped *typedThis = thisNode->getAsTyped();
3263                 if(fnCall->getName() != "length")
3264                 {
3265                         error(loc, "invalid method", fnCall->getName().c_str());
3266                         recover();
3267                 }
3268                 else if(paramNode != nullptr)
3269                 {
3270                         error(loc, "method takes no parameters", "length");
3271                         recover();
3272                 }
3273                 else if(typedThis == nullptr || !typedThis->isArray())
3274                 {
3275                         error(loc, "length can only be called on arrays", "length");
3276                         recover();
3277                 }
3278                 else
3279                 {
3280                         arraySize = typedThis->getArraySize();
3281                         if(typedThis->getAsSymbolNode() == nullptr)
3282                         {
3283                                 // This code path can be hit with expressions like these:
3284                                 // (a = b).length()
3285                                 // (func()).length()
3286                                 // (int[3](0, 1, 2)).length()
3287                                 // ESSL 3.00 section 5.9 defines expressions so that this is not actually a valid expression.
3288                                 // It allows "An array name with the length method applied" in contrast to GLSL 4.4 spec section 5.9
3289                                 // which allows "An array, vector or matrix expression with the length method applied".
3290                                 error(loc, "length can only be called on array names, not on array expressions", "length");
3291                                 recover();
3292                         }
3293                 }
3294                 unionArray->setIConst(arraySize);
3295                 callNode = intermediate.addConstantUnion(unionArray, TType(EbtInt, EbpUndefined, EvqConstExpr), loc);
3296         }
3297         else if(op != EOpNull)
3298         {
3299                 //
3300                 // Then this should be a constructor.
3301                 // Don't go through the symbol table for constructors.
3302                 // Their parameters will be verified algorithmically.
3303                 //
3304                 TType type(EbtVoid, EbpUndefined);  // use this to get the type back
3305                 if(!constructorErrorCheck(loc, paramNode, *fnCall, op, &type))
3306                 {
3307                         //
3308                         // It's a constructor, of type 'type'.
3309                         //
3310                         callNode = addConstructor(paramNode, &type, op, fnCall, loc);
3311                 }
3312
3313                 if(callNode == nullptr)
3314                 {
3315                         recover();
3316                         callNode = intermediate.setAggregateOperator(nullptr, op, loc);
3317                 }
3318                 callNode->setType(type);
3319         }
3320         else
3321         {
3322                 //
3323                 // Not a constructor.  Find it in the symbol table.
3324                 //
3325                 const TFunction *fnCandidate;
3326                 bool builtIn;
3327                 fnCandidate = findFunction(loc, fnCall, &builtIn);
3328                 if(fnCandidate)
3329                 {
3330                         //
3331                         // A declared function.
3332                         //
3333                         if(builtIn && !fnCandidate->getExtension().empty() &&
3334                                 extensionErrorCheck(loc, fnCandidate->getExtension()))
3335                         {
3336                                 recover();
3337                         }
3338                         op = fnCandidate->getBuiltInOp();
3339                         if(builtIn && op != EOpNull)
3340                         {
3341                                 //
3342                                 // A function call mapped to a built-in operation.
3343                                 //
3344                                 if(fnCandidate->getParamCount() == 1)
3345                                 {
3346                                         //
3347                                         // Treat it like a built-in unary operator.
3348                                         //
3349                                         callNode = createUnaryMath(op, paramNode->getAsTyped(), loc, &fnCandidate->getReturnType());
3350                                         if(callNode == nullptr)
3351                                         {
3352                                                 std::stringstream extraInfoStream;
3353                                                 extraInfoStream << "built in unary operator function.  Type: "
3354                                                         << static_cast<TIntermTyped*>(paramNode)->getCompleteString();
3355                                                 std::string extraInfo = extraInfoStream.str();
3356                                                 error(paramNode->getLine(), " wrong operand type", "Internal Error", extraInfo.c_str());
3357                                                 *fatalError = true;
3358                                                 return nullptr;
3359                                         }
3360                                 }
3361                                 else
3362                                 {
3363                                         TIntermAggregate *aggregate = intermediate.setAggregateOperator(paramNode, op, loc);
3364                                         aggregate->setType(fnCandidate->getReturnType());
3365
3366                                         // Some built-in functions have out parameters too.
3367                                         functionCallLValueErrorCheck(fnCandidate, aggregate);
3368
3369                                         callNode = aggregate;
3370                                 }
3371                         }
3372                         else
3373                         {
3374                                 // This is a real function call
3375
3376                                 TIntermAggregate *aggregate = intermediate.setAggregateOperator(paramNode, EOpFunctionCall, loc);
3377                                 aggregate->setType(fnCandidate->getReturnType());
3378
3379                                 // this is how we know whether the given function is a builtIn function or a user defined function
3380                                 // if builtIn == false, it's a userDefined -> could be an overloaded builtIn function also
3381                                 // if builtIn == true, it's definitely a builtIn function with EOpNull
3382                                 if(!builtIn)
3383                                         aggregate->setUserDefined();
3384                                 aggregate->setName(fnCandidate->getMangledName());
3385
3386                                 callNode = aggregate;
3387
3388                                 functionCallLValueErrorCheck(fnCandidate, aggregate);
3389                         }
3390                         callNode->setType(fnCandidate->getReturnType());
3391                 }
3392                 else
3393                 {
3394                         // error message was put out by findFunction()
3395                         // Put on a dummy node for error recovery
3396                         ConstantUnion *unionArray = new ConstantUnion[1];
3397                         unionArray->setFConst(0.0f);
3398                         callNode = intermediate.addConstantUnion(unionArray, TType(EbtFloat, EbpUndefined, EvqConstExpr), loc);
3399                         recover();
3400                 }
3401         }
3402         delete fnCall;
3403         return callNode;
3404 }
3405
3406 //
3407 // Parse an array of strings using yyparse.
3408 //
3409 // Returns 0 for success.
3410 //
3411 int PaParseStrings(int count, const char* const string[], const int length[],
3412                    TParseContext* context) {
3413     if ((count == 0) || (string == NULL))
3414         return 1;
3415
3416     if (glslang_initialize(context))
3417         return 1;
3418
3419     int error = glslang_scan(count, string, length, context);
3420     if (!error)
3421         error = glslang_parse(context);
3422
3423     glslang_finalize(context);
3424
3425     return (error == 0) && (context->numErrors() == 0) ? 0 : 1;
3426 }
3427
3428
3429