OSDN Git Service

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