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.
7 #include "ParseHelper.h"
13 #include "preprocessor/SourceLocation.h"
14 #include "ValidateGlobalInitializer.h"
15 #include "ValidateSwitch.h"
17 ///////////////////////////////////////////////////////////////////////
19 // Sub- vector and matrix fields
21 ////////////////////////////////////////////////////////////////////////
24 // Look at a '.' field selector string and change it into offsets
27 bool TParseContext::parseVectorFields(const TString& compString, int vecSize, TVectorFields& fields, const TSourceLoc &line)
29 fields.num = (int) compString.size();
31 error(line, "illegal vector field selection", compString.c_str());
41 for (int i = 0; i < fields.num; ++i) {
42 switch (compString[i]) {
44 fields.offsets[i] = 0;
48 fields.offsets[i] = 0;
52 fields.offsets[i] = 0;
56 fields.offsets[i] = 1;
60 fields.offsets[i] = 1;
64 fields.offsets[i] = 1;
68 fields.offsets[i] = 2;
72 fields.offsets[i] = 2;
76 fields.offsets[i] = 2;
80 fields.offsets[i] = 3;
84 fields.offsets[i] = 3;
88 fields.offsets[i] = 3;
92 error(line, "illegal vector field selection", compString.c_str());
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());
104 if (fieldSet[i] != fieldSet[i-1]) {
105 error(line, "illegal - vector component fields not from the same set", compString.c_str());
116 // Look at a '.' field selector string and change it into offsets
119 bool TParseContext::parseMatrixFields(const TString& compString, int matCols, int matRows, TMatrixFields& fields, const TSourceLoc &line)
121 fields.wholeRow = false;
122 fields.wholeCol = false;
126 if (compString.size() != 2) {
127 error(line, "illegal length of matrix field selection", compString.c_str());
131 if (compString[0] == '_') {
132 if (compString[1] < '0' || compString[1] > '3') {
133 error(line, "illegal matrix field selection", compString.c_str());
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());
143 fields.wholeRow = true;
144 fields.row = compString[0] - '0';
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());
151 fields.row = compString[0] - '0';
152 fields.col = compString[1] - '0';
155 if (fields.row >= matRows || fields.col >= matCols) {
156 error(line, "matrix field selection out of range", compString.c_str());
163 ///////////////////////////////////////////////////////////////////////
167 ////////////////////////////////////////////////////////////////////////
170 // Track whether errors have occurred.
172 void TParseContext::recover()
177 // Used by flex/bison to output all syntax and parsing errors.
179 void TParseContext::error(const TSourceLoc& loc,
180 const char* reason, const char* token,
181 const char* extraInfo)
183 pp::SourceLocation srcLoc;
184 DecodeSourceLoc(loc, &srcLoc.file, &srcLoc.line);
185 mDiagnostics.writeInfo(pp::Diagnostics::PP_ERROR,
186 srcLoc, reason, token, extraInfo);
190 void TParseContext::warning(const TSourceLoc& loc,
191 const char* reason, const char* token,
192 const char* extraInfo) {
193 pp::SourceLocation srcLoc;
194 DecodeSourceLoc(loc, &srcLoc.file, &srcLoc.line);
195 mDiagnostics.writeInfo(pp::Diagnostics::PP_WARNING,
196 srcLoc, reason, token, extraInfo);
199 void TParseContext::trace(const char* str)
201 mDiagnostics.writeDebug(str);
205 // Same error message for all places assignments don't work.
207 void TParseContext::assignError(const TSourceLoc &line, const char* op, TString left, TString right)
209 std::stringstream extraInfoStream;
210 extraInfoStream << "cannot convert from '" << right << "' to '" << left << "'";
211 std::string extraInfo = extraInfoStream.str();
212 error(line, "", op, extraInfo.c_str());
216 // Same error message for all places unary operations don't work.
218 void TParseContext::unaryOpError(const TSourceLoc &line, const char* op, TString operand)
220 std::stringstream extraInfoStream;
221 extraInfoStream << "no operation '" << op << "' exists that takes an operand of type " << operand
222 << " (or there is no acceptable conversion)";
223 std::string extraInfo = extraInfoStream.str();
224 error(line, " wrong operand type", op, extraInfo.c_str());
228 // Same error message for all binary operations don't work.
230 void TParseContext::binaryOpError(const TSourceLoc &line, const char* op, TString left, TString right)
232 std::stringstream extraInfoStream;
233 extraInfoStream << "no operation '" << op << "' exists that takes a left-hand operand of type '" << left
234 << "' and a right operand of type '" << right << "' (or there is no acceptable conversion)";
235 std::string extraInfo = extraInfoStream.str();
236 error(line, " wrong operand types ", op, extraInfo.c_str());
239 bool TParseContext::precisionErrorCheck(const TSourceLoc &line, TPrecision precision, TBasicType type){
240 if (!mChecksPrecisionErrors)
244 if( precision == EbpUndefined ){
245 error( line, "No precision specified for (float)", "" );
250 if( precision == EbpUndefined ){
251 error( line, "No precision specified (int)", "" );
262 // Both test and if necessary, spit out an error, to see if the node is really
263 // an l-value that can be operated on this way.
265 // Returns true if the was an error.
267 bool TParseContext::lValueErrorCheck(const TSourceLoc &line, const char* op, TIntermTyped* node)
269 TIntermSymbol* symNode = node->getAsSymbolNode();
270 TIntermBinary* binaryNode = node->getAsBinaryNode();
275 switch(binaryNode->getOp()) {
277 case EOpIndexIndirect:
278 case EOpIndexDirectStruct:
279 return lValueErrorCheck(line, op, binaryNode->getLeft());
280 case EOpVectorSwizzle:
281 errorReturn = lValueErrorCheck(line, op, binaryNode->getLeft());
283 int offset[4] = {0,0,0,0};
285 TIntermTyped* rightNode = binaryNode->getRight();
286 TIntermAggregate *aggrNode = rightNode->getAsAggregate();
288 for (TIntermSequence::iterator p = aggrNode->getSequence().begin();
289 p != aggrNode->getSequence().end(); p++) {
290 int value = (*p)->getAsTyped()->getAsConstantUnion()->getIConst(0);
292 if (offset[value] > 1) {
293 error(line, " l-value of swizzle cannot have duplicate components", op);
304 error(line, " l-value required", op);
310 const char* symbol = 0;
312 symbol = symNode->getSymbol().c_str();
314 const char* message = 0;
315 switch (node->getQualifier()) {
316 case EvqConstExpr: message = "can't modify a const"; break;
317 case EvqConstReadOnly: message = "can't modify a const"; break;
318 case EvqAttribute: message = "can't modify an attribute"; break;
319 case EvqFragmentIn: message = "can't modify an input"; break;
320 case EvqVertexIn: message = "can't modify an input"; break;
321 case EvqUniform: message = "can't modify a uniform"; break;
325 case EvqVaryingIn: message = "can't modify a varying"; break;
326 case EvqInput: message = "can't modify an input"; break;
327 case EvqFragCoord: message = "can't modify gl_FragCoord"; break;
328 case EvqFrontFacing: message = "can't modify gl_FrontFacing"; break;
329 case EvqPointCoord: message = "can't modify gl_PointCoord"; break;
330 case EvqInstanceID: message = "can't modify gl_InstanceID"; break;
334 // Type that can't be written to?
336 if(IsSampler(node->getBasicType()))
338 message = "can't modify a sampler";
340 else if(node->getBasicType() == EbtVoid)
342 message = "can't modify void";
346 if (message == 0 && binaryNode == 0 && symNode == 0) {
347 error(line, " l-value required", op);
354 // Everything else is okay, no error.
360 // If we get here, we have an error and a message.
363 std::stringstream extraInfoStream;
364 extraInfoStream << "\"" << symbol << "\" (" << message << ")";
365 std::string extraInfo = extraInfoStream.str();
366 error(line, " l-value required", op, extraInfo.c_str());
369 std::stringstream extraInfoStream;
370 extraInfoStream << "(" << message << ")";
371 std::string extraInfo = extraInfoStream.str();
372 error(line, " l-value required", op, extraInfo.c_str());
379 // Both test, and if necessary spit out an error, to see if the node is really
382 // Returns true if the was an error.
384 bool TParseContext::constErrorCheck(TIntermTyped* node)
386 if (node->getQualifier() == EvqConstExpr)
389 error(node->getLine(), "constant expression required", "");
395 // Both test, and if necessary spit out an error, to see if the node is really
398 // Returns true if the was an error.
400 bool TParseContext::integerErrorCheck(TIntermTyped* node, const char* token)
402 if (node->isScalarInt())
405 error(node->getLine(), "integer expression required", token);
411 // Both test, and if necessary spit out an error, to see if we are currently
414 // Returns true if the was an error.
416 bool TParseContext::globalErrorCheck(const TSourceLoc &line, bool global, const char* token)
421 error(line, "only allowed at global scope", token);
427 // For now, keep it simple: if it starts "gl_", it's reserved, independent
428 // of scope. Except, if the symbol table is at the built-in push-level,
429 // which is when we are parsing built-ins.
430 // Also checks for "webgl_" and "_webgl_" reserved identifiers if parsing a
433 // Returns true if there was an error.
435 bool TParseContext::reservedErrorCheck(const TSourceLoc &line, const TString& identifier)
437 static const char* reservedErrMsg = "reserved built-in name";
438 if (!symbolTable.atBuiltInLevel()) {
439 if (identifier.compare(0, 3, "gl_") == 0) {
440 error(line, reservedErrMsg, "gl_");
443 if (identifier.find("__") != TString::npos) {
444 error(line, "identifiers containing two consecutive underscores (__) are reserved as possible future keywords", identifier.c_str());
453 // Make sure there is enough data provided to the constructor to build
454 // something of the type of the constructor. Also returns the type of
457 // Returns true if there was an error in construction.
459 bool TParseContext::constructorErrorCheck(const TSourceLoc &line, TIntermNode* node, TFunction& function, TOperator op, TType* type)
461 *type = function.getReturnType();
463 bool constructingMatrix = false;
465 case EOpConstructMat2:
466 case EOpConstructMat2x3:
467 case EOpConstructMat2x4:
468 case EOpConstructMat3x2:
469 case EOpConstructMat3:
470 case EOpConstructMat3x4:
471 case EOpConstructMat4x2:
472 case EOpConstructMat4x3:
473 case EOpConstructMat4:
474 constructingMatrix = true;
481 // Note: It's okay to have too many components available, but not okay to have unused
482 // arguments. 'full' will go to true when enough args have been seen. If we loop
483 // again, there is an extra argument, so 'overfull' will become true.
487 bool constType = true;
489 bool overFull = false;
490 bool matrixInMatrix = false;
491 bool arrayArg = false;
492 for (size_t i = 0; i < function.getParamCount(); ++i) {
493 const TParameter& param = function.getParam(i);
494 size += param.type->getObjectSize();
496 if (constructingMatrix && param.type->isMatrix())
497 matrixInMatrix = true;
500 if (op != EOpConstructStruct && !type->isArray() && size >= type->getObjectSize())
502 if (param.type->getQualifier() != EvqConstExpr)
504 if (param.type->isArray())
509 type->setQualifier(EvqConstExpr);
511 if(type->isArray()) {
512 if(type->getArraySize() == 0) {
513 type->setArraySize(function.getParamCount());
514 } else if(type->getArraySize() != function.getParamCount()) {
515 error(line, "array constructor needs one argument per array element", "constructor");
520 if (arrayArg && op != EOpConstructStruct) {
521 error(line, "constructing from a non-dereferenced array", "constructor");
525 if (matrixInMatrix && !type->isArray()) {
526 if (function.getParamCount() != 1) {
527 error(line, "constructing matrix from matrix can only take one argument", "constructor");
533 error(line, "too many arguments", "constructor");
537 if (op == EOpConstructStruct && !type->isArray() && int(type->getStruct()->fields().size()) != function.getParamCount()) {
538 error(line, "Number of constructor parameters does not match the number of structure fields", "constructor");
542 if (!type->isMatrix() || !matrixInMatrix) {
543 if ((op != EOpConstructStruct && size != 1 && size < type->getObjectSize()) ||
544 (op == EOpConstructStruct && size < type->getObjectSize())) {
545 error(line, "not enough data provided for construction", "constructor");
550 TIntermTyped *typed = node ? node->getAsTyped() : 0;
552 error(line, "constructor argument does not have a type", "constructor");
555 if (op != EOpConstructStruct && IsSampler(typed->getBasicType())) {
556 error(line, "cannot convert a sampler", "constructor");
559 if (typed->getBasicType() == EbtVoid) {
560 error(line, "cannot convert a void", "constructor");
567 // This function checks to see if a void variable has been declared and raise an error message for such a case
569 // returns true in case of an error
571 bool TParseContext::voidErrorCheck(const TSourceLoc &line, const TString& identifier, const TBasicType& type)
573 if(type == EbtVoid) {
574 error(line, "illegal use of type 'void'", identifier.c_str());
581 // This function checks to see if the node (for the expression) contains a scalar boolean expression or not
583 // returns true in case of an error
585 bool TParseContext::boolErrorCheck(const TSourceLoc &line, const TIntermTyped* type)
587 if (type->getBasicType() != EbtBool || type->isArray() || type->isMatrix() || type->isVector()) {
588 error(line, "boolean expression expected", "");
595 // This function checks to see if the node (for the expression) contains a scalar boolean expression or not
597 // returns true in case of an error
599 bool TParseContext::boolErrorCheck(const TSourceLoc &line, const TPublicType& pType)
601 if (pType.type != EbtBool || pType.array || (pType.primarySize > 1) || (pType.secondarySize > 1)) {
602 error(line, "boolean expression expected", "");
609 bool TParseContext::samplerErrorCheck(const TSourceLoc &line, const TPublicType& pType, const char* reason)
611 if (pType.type == EbtStruct) {
612 if (containsSampler(*pType.userDef)) {
613 error(line, reason, getBasicString(pType.type), "(structure contains a sampler)");
619 } else if (IsSampler(pType.type)) {
620 error(line, reason, getBasicString(pType.type));
628 bool TParseContext::structQualifierErrorCheck(const TSourceLoc &line, const TPublicType& pType)
630 switch(pType.qualifier)
643 if(pType.type == EbtStruct)
645 error(line, "cannot be used with a structure", getQualifierString(pType.qualifier));
654 if (pType.qualifier != EvqUniform && samplerErrorCheck(line, pType, "samplers must be uniform"))
657 // check for layout qualifier issues
658 const TLayoutQualifier layoutQualifier = pType.layoutQualifier;
660 if (pType.qualifier != EvqVertexIn && pType.qualifier != EvqFragmentOut &&
661 layoutLocationErrorCheck(line, pType.layoutQualifier))
669 // These checks are common for all declarations starting a declarator list, and declarators that follow an empty
672 bool TParseContext::singleDeclarationErrorCheck(const TPublicType &publicType, const TSourceLoc &identifierLocation)
674 switch(publicType.qualifier)
681 if(publicType.type == EbtStruct)
683 error(identifierLocation, "cannot be used with a structure",
684 getQualifierString(publicType.qualifier));
691 if(publicType.qualifier != EvqUniform && samplerErrorCheck(identifierLocation, publicType,
692 "samplers must be uniform"))
697 // check for layout qualifier issues
698 const TLayoutQualifier layoutQualifier = publicType.layoutQualifier;
700 if(layoutQualifier.matrixPacking != EmpUnspecified)
702 error(identifierLocation, "layout qualifier", getMatrixPackingString(layoutQualifier.matrixPacking),
703 "only valid for interface blocks");
707 if(layoutQualifier.blockStorage != EbsUnspecified)
709 error(identifierLocation, "layout qualifier", getBlockStorageString(layoutQualifier.blockStorage),
710 "only valid for interface blocks");
714 if(publicType.qualifier != EvqVertexIn && publicType.qualifier != EvqFragmentOut &&
715 layoutLocationErrorCheck(identifierLocation, publicType.layoutQualifier))
723 bool TParseContext::layoutLocationErrorCheck(const TSourceLoc &location, const TLayoutQualifier &layoutQualifier)
725 if(layoutQualifier.location != -1)
727 error(location, "invalid layout qualifier:", "location", "only valid on program inputs and outputs");
734 bool TParseContext::locationDeclaratorListCheck(const TSourceLoc& line, const TPublicType &pType)
736 if(pType.layoutQualifier.location != -1)
738 error(line, "location must only be specified for a single input or output variable", "location");
745 bool TParseContext::parameterSamplerErrorCheck(const TSourceLoc &line, TQualifier qualifier, const TType& type)
747 if ((qualifier == EvqOut || qualifier == EvqInOut) &&
748 type.getBasicType() != EbtStruct && IsSampler(type.getBasicType())) {
749 error(line, "samplers cannot be output parameters", type.getBasicString());
756 bool TParseContext::containsSampler(TType& type)
758 if (IsSampler(type.getBasicType()))
761 if (type.getBasicType() == EbtStruct) {
762 const TFieldList& fields = type.getStruct()->fields();
763 for(unsigned int i = 0; i < fields.size(); ++i) {
764 if (containsSampler(*fields[i]->type()))
773 // Do size checking for an array type's size.
775 // Returns true if there was an error.
777 bool TParseContext::arraySizeErrorCheck(const TSourceLoc &line, TIntermTyped* expr, int& size)
779 TIntermConstantUnion* constant = expr->getAsConstantUnion();
781 if (constant == 0 || !constant->isScalarInt())
783 error(line, "array size must be a constant integer expression", "");
787 if (constant->getBasicType() == EbtUInt)
789 unsigned int uintSize = constant->getUConst(0);
790 if (uintSize > static_cast<unsigned int>(std::numeric_limits<int>::max()))
792 error(line, "array size too large", "");
797 size = static_cast<int>(uintSize);
801 size = constant->getIConst(0);
805 error(line, "array size must be a positive integer", "");
815 // See if this qualifier can be an array.
817 // Returns true if there is an error.
819 bool TParseContext::arrayQualifierErrorCheck(const TSourceLoc &line, TPublicType type)
821 if ((type.qualifier == EvqAttribute) || (type.qualifier == EvqVertexIn) || (type.qualifier == EvqConstExpr)) {
822 error(line, "cannot declare arrays of this qualifier", TType(type).getCompleteString().c_str());
830 // See if this type can be an array.
832 // Returns true if there is an error.
834 bool TParseContext::arrayTypeErrorCheck(const TSourceLoc &line, TPublicType type)
837 // Can the type be an array?
840 error(line, "cannot declare arrays of arrays", TType(type).getCompleteString().c_str());
847 bool TParseContext::arraySetMaxSize(TIntermSymbol *node, TType* type, int size, bool updateFlag, const TSourceLoc &line)
849 bool builtIn = false;
850 TSymbol* symbol = symbolTable.find(node->getSymbol(), mShaderVersion, &builtIn);
852 error(line, " undeclared identifier", node->getSymbol().c_str());
855 TVariable* variable = static_cast<TVariable*>(symbol);
857 type->setArrayInformationType(variable->getArrayInformationType());
858 variable->updateArrayInformationType(type);
860 // special casing to test index value of gl_FragData. If the accessed index is >= gl_MaxDrawBuffers
862 if (node->getSymbol() == "gl_FragData") {
863 TSymbol* fragData = symbolTable.find("gl_MaxDrawBuffers", mShaderVersion, &builtIn);
866 int fragDataValue = static_cast<TVariable*>(fragData)->getConstPointer()[0].getIConst();
867 if (fragDataValue <= size) {
868 error(line, "", "[", "gl_FragData can only have a max array size of up to gl_MaxDrawBuffers");
873 // we dont want to update the maxArraySize when this flag is not set, we just want to include this
874 // node type in the chain of node types so that its updated when a higher maxArraySize comes in.
879 variable->getType().setMaxArraySize(size);
880 type->setMaxArraySize(size);
883 while(tt->getArrayInformationType() != 0) {
884 tt = tt->getArrayInformationType();
885 tt->setMaxArraySize(size);
892 // Enforce non-initializer type/qualifier rules.
894 // Returns true if there was an error.
896 bool TParseContext::nonInitConstErrorCheck(const TSourceLoc &line, TString& identifier, TPublicType& type, bool array)
898 if (type.qualifier == EvqConstExpr)
900 // Make the qualifier make sense.
901 type.qualifier = EvqTemporary;
905 error(line, "arrays may not be declared constant since they cannot be initialized", identifier.c_str());
907 else if (type.isStructureContainingArrays())
909 error(line, "structures containing arrays may not be declared constant since they cannot be initialized", identifier.c_str());
913 error(line, "variables with qualifier 'const' must be initialized", identifier.c_str());
923 // Do semantic checking for a variable declaration that has no initializer,
924 // and update the symbol table.
926 // Returns true if there was an error.
928 bool TParseContext::nonInitErrorCheck(const TSourceLoc &line, const TString& identifier, TPublicType& type)
930 if(type.qualifier == EvqConstExpr)
932 // Make the qualifier make sense.
933 type.qualifier = EvqTemporary;
935 // Generate informative error messages for ESSL1.
936 // In ESSL3 arrays and structures containing arrays can be constant.
937 if(mShaderVersion < 300 && type.isStructureContainingArrays())
940 "structures containing arrays may not be declared constant since they cannot be initialized",
945 error(line, "variables with qualifier 'const' must be initialized", identifier.c_str());
950 if(type.isUnsizedArray())
952 error(line, "implicitly sized arrays need to be initialized", identifier.c_str());
958 // Do some simple checks that are shared between all variable declarations,
959 // and update the symbol table.
961 // Returns true if declaring the variable succeeded.
963 bool TParseContext::declareVariable(const TSourceLoc &line, const TString &identifier, const TType &type,
964 TVariable **variable)
966 ASSERT((*variable) == nullptr);
968 // gl_LastFragData may be redeclared with a new precision qualifier
969 if(type.isArray() && identifier.compare(0, 15, "gl_LastFragData") == 0)
971 const TVariable *maxDrawBuffers =
972 static_cast<const TVariable *>(symbolTable.findBuiltIn("gl_MaxDrawBuffers", mShaderVersion));
973 if(type.getArraySize() != maxDrawBuffers->getConstPointer()->getIConst())
975 error(line, "redeclaration of gl_LastFragData with size != gl_MaxDrawBuffers", identifier.c_str());
980 if(reservedErrorCheck(line, identifier))
983 (*variable) = new TVariable(&identifier, type);
984 if(!symbolTable.declare(**variable))
986 error(line, "redefinition", identifier.c_str());
988 (*variable) = nullptr;
992 if(voidErrorCheck(line, identifier, type.getBasicType()))
998 bool TParseContext::paramErrorCheck(const TSourceLoc &line, TQualifier qualifier, TQualifier paramQualifier, TType* type)
1000 if (qualifier != EvqConstReadOnly && qualifier != EvqTemporary) {
1001 error(line, "qualifier not allowed on function parameter", getQualifierString(qualifier));
1004 if (qualifier == EvqConstReadOnly && paramQualifier != EvqIn) {
1005 error(line, "qualifier not allowed with ", getQualifierString(qualifier), getQualifierString(paramQualifier));
1009 if (qualifier == EvqConstReadOnly)
1010 type->setQualifier(EvqConstReadOnly);
1012 type->setQualifier(paramQualifier);
1017 bool TParseContext::extensionErrorCheck(const TSourceLoc &line, const TString& extension)
1019 const TExtensionBehavior& extBehavior = extensionBehavior();
1020 TExtensionBehavior::const_iterator iter = extBehavior.find(extension.c_str());
1021 if (iter == extBehavior.end()) {
1022 error(line, "extension", extension.c_str(), "is not supported");
1025 // In GLSL ES, an extension's default behavior is "disable".
1026 if (iter->second == EBhDisable || iter->second == EBhUndefined) {
1027 error(line, "extension", extension.c_str(), "is disabled");
1030 if (iter->second == EBhWarn) {
1031 warning(line, "extension", extension.c_str(), "is being used");
1038 bool TParseContext::functionCallLValueErrorCheck(const TFunction *fnCandidate, TIntermAggregate *aggregate)
1040 for(size_t i = 0; i < fnCandidate->getParamCount(); ++i)
1042 TQualifier qual = fnCandidate->getParam(i).type->getQualifier();
1043 if(qual == EvqOut || qual == EvqInOut)
1045 TIntermTyped *node = (aggregate->getSequence())[i]->getAsTyped();
1046 if(lValueErrorCheck(node->getLine(), "assign", node))
1048 error(node->getLine(),
1049 "Constant value cannot be passed for 'out' or 'inout' parameters.", "Error");
1058 bool TParseContext::supportsExtension(const char* extension)
1060 const TExtensionBehavior& extbehavior = extensionBehavior();
1061 TExtensionBehavior::const_iterator iter = extbehavior.find(extension);
1062 return (iter != extbehavior.end());
1065 void TParseContext::handleExtensionDirective(const TSourceLoc &line, const char* extName, const char* behavior)
1067 pp::SourceLocation loc;
1068 DecodeSourceLoc(line, &loc.file, &loc.line);
1069 mDirectiveHandler.handleExtension(loc, extName, behavior);
1072 void TParseContext::handlePragmaDirective(const TSourceLoc &line, const char* name, const char* value)
1074 pp::SourceLocation loc;
1075 DecodeSourceLoc(line, &loc.file, &loc.line);
1076 mDirectiveHandler.handlePragma(loc, name, value);
1079 /////////////////////////////////////////////////////////////////////////////////
1083 /////////////////////////////////////////////////////////////////////////////////
1085 const TVariable *TParseContext::getNamedVariable(const TSourceLoc &location,
1086 const TString *name,
1087 const TSymbol *symbol)
1089 const TVariable *variable = NULL;
1093 error(location, "undeclared identifier", name->c_str());
1096 else if(!symbol->isVariable())
1098 error(location, "variable expected", name->c_str());
1103 variable = static_cast<const TVariable*>(symbol);
1105 if(symbolTable.findBuiltIn(variable->getName(), mShaderVersion))
1110 // Reject shaders using both gl_FragData and gl_FragColor
1111 TQualifier qualifier = variable->getType().getQualifier();
1112 if(qualifier == EvqFragData)
1114 mUsesFragData = true;
1116 else if(qualifier == EvqFragColor)
1118 mUsesFragColor = true;
1121 // This validation is not quite correct - it's only an error to write to
1122 // both FragData and FragColor. For simplicity, and because users shouldn't
1123 // be rewarded for reading from undefined varaibles, return an error
1124 // if they are both referenced, rather than assigned.
1125 if(mUsesFragData && mUsesFragColor)
1127 error(location, "cannot use both gl_FragData and gl_FragColor", name->c_str());
1134 TType type(EbtFloat, EbpUndefined);
1135 TVariable *fakeVariable = new TVariable(name, type);
1136 symbolTable.declare(*fakeVariable);
1137 variable = fakeVariable;
1144 // Look up a function name in the symbol table, and make sure it is a function.
1146 // Return the function symbol if found, otherwise 0.
1148 const TFunction* TParseContext::findFunction(const TSourceLoc &line, TFunction* call, bool *builtIn)
1150 // First find by unmangled name to check whether the function name has been
1151 // hidden by a variable name or struct typename.
1152 const TSymbol* symbol = symbolTable.find(call->getName(), mShaderVersion, builtIn);
1154 symbol = symbolTable.find(call->getMangledName(), mShaderVersion, builtIn);
1158 error(line, "no matching overloaded function found", call->getName().c_str());
1162 if (!symbol->isFunction()) {
1163 error(line, "function name expected", call->getName().c_str());
1167 return static_cast<const TFunction*>(symbol);
1171 // Initializers show up in several places in the grammar. Have one set of
1172 // code to handle them here.
1174 bool TParseContext::executeInitializer(const TSourceLoc& line, const TString& identifier, const TPublicType& pType,
1175 TIntermTyped *initializer, TIntermNode **intermNode)
1177 ASSERT(intermNode != nullptr);
1178 TType type = TType(pType);
1180 TVariable *variable = nullptr;
1181 if(type.isArray() && (type.getArraySize() == 0))
1183 type.setArraySize(initializer->getArraySize());
1185 if(!declareVariable(line, identifier, type, &variable))
1190 bool globalInitWarning = false;
1191 if(symbolTable.atGlobalLevel() && !ValidateGlobalInitializer(initializer, this, &globalInitWarning))
1193 // Error message does not completely match behavior with ESSL 1.00, but
1194 // we want to steer developers towards only using constant expressions.
1195 error(line, "global variable initializers must be constant expressions", "=");
1198 if(globalInitWarning)
1200 warning(line, "global variable initializers should be constant expressions "
1201 "(uniforms and globals are allowed in global initializers for legacy compatibility)", "=");
1205 // identifier must be of type constant, a global, or a temporary
1207 TQualifier qualifier = variable->getType().getQualifier();
1208 if ((qualifier != EvqTemporary) && (qualifier != EvqGlobal) && (qualifier != EvqConstExpr)) {
1209 error(line, " cannot initialize this type of qualifier ", variable->getType().getQualifierString());
1213 // test for and propagate constant
1216 if (qualifier == EvqConstExpr) {
1217 if (qualifier != initializer->getType().getQualifier()) {
1218 std::stringstream extraInfoStream;
1219 extraInfoStream << "'" << variable->getType().getCompleteString() << "'";
1220 std::string extraInfo = extraInfoStream.str();
1221 error(line, " assigning non-constant to", "=", extraInfo.c_str());
1222 variable->getType().setQualifier(EvqTemporary);
1225 if (type != initializer->getType()) {
1226 error(line, " non-matching types for const initializer ",
1227 variable->getType().getQualifierString());
1228 variable->getType().setQualifier(EvqTemporary);
1231 if (initializer->getAsConstantUnion()) {
1232 variable->shareConstPointer(initializer->getAsConstantUnion()->getUnionArrayPointer());
1233 } else if (initializer->getAsSymbolNode()) {
1234 const TSymbol* symbol = symbolTable.find(initializer->getAsSymbolNode()->getSymbol(), 0);
1235 const TVariable* tVar = static_cast<const TVariable*>(symbol);
1237 ConstantUnion* constArray = tVar->getConstPointer();
1238 variable->shareConstPointer(constArray);
1240 std::stringstream extraInfoStream;
1241 extraInfoStream << "'" << variable->getType().getCompleteString() << "'";
1242 std::string extraInfo = extraInfoStream.str();
1243 error(line, " cannot assign to", "=", extraInfo.c_str());
1244 variable->getType().setQualifier(EvqTemporary);
1249 if (qualifier != EvqConstExpr) {
1250 TIntermSymbol* intermSymbol = intermediate.addSymbol(variable->getUniqueId(), variable->getName(), variable->getType(), line);
1251 *intermNode = createAssign(EOpInitialize, intermSymbol, initializer, line);
1252 if(*intermNode == nullptr) {
1253 assignError(line, "=", intermSymbol->getCompleteString(), initializer->getCompleteString());
1257 *intermNode = nullptr;
1262 bool TParseContext::areAllChildConst(TIntermAggregate* aggrNode)
1264 ASSERT(aggrNode != NULL);
1265 if (!aggrNode->isConstructor())
1268 bool allConstant = true;
1270 // check if all the child nodes are constants so that they can be inserted into
1272 TIntermSequence &sequence = aggrNode->getSequence() ;
1273 for (TIntermSequence::iterator p = sequence.begin(); p != sequence.end(); ++p) {
1274 if (!(*p)->getAsTyped()->getAsConstantUnion())
1281 TPublicType TParseContext::addFullySpecifiedType(TQualifier qualifier, bool invariant, TLayoutQualifier layoutQualifier, const TPublicType &typeSpecifier)
1283 TPublicType returnType = typeSpecifier;
1284 returnType.qualifier = qualifier;
1285 returnType.invariant = invariant;
1286 returnType.layoutQualifier = layoutQualifier;
1288 if(typeSpecifier.array)
1290 error(typeSpecifier.line, "not supported", "first-class array");
1292 returnType.clearArrayness();
1295 if(mShaderVersion < 300)
1297 if(qualifier == EvqAttribute && (typeSpecifier.type == EbtBool || typeSpecifier.type == EbtInt))
1299 error(typeSpecifier.line, "cannot be bool or int", getQualifierString(qualifier));
1303 if((qualifier == EvqVaryingIn || qualifier == EvqVaryingOut) &&
1304 (typeSpecifier.type == EbtBool || typeSpecifier.type == EbtInt))
1306 error(typeSpecifier.line, "cannot be bool or int", getQualifierString(qualifier));
1318 case EvqCentroidOut:
1320 if(typeSpecifier.type == EbtBool)
1322 error(typeSpecifier.line, "cannot be bool", getQualifierString(qualifier));
1325 if(typeSpecifier.type == EbtInt || typeSpecifier.type == EbtUInt)
1327 error(typeSpecifier.line, "must use 'flat' interpolation here", getQualifierString(qualifier));
1333 case EvqFragmentOut:
1336 if(typeSpecifier.type == EbtBool)
1338 error(typeSpecifier.line, "cannot be bool", getQualifierString(qualifier));
1350 TIntermAggregate *TParseContext::parseSingleDeclaration(TPublicType &publicType,
1351 const TSourceLoc &identifierOrTypeLocation,
1352 const TString &identifier)
1354 TIntermSymbol *symbol = intermediate.addSymbol(0, identifier, TType(publicType), identifierOrTypeLocation);
1356 bool emptyDeclaration = (identifier == "");
1358 mDeferredSingleDeclarationErrorCheck = emptyDeclaration;
1360 if(emptyDeclaration)
1362 if(publicType.isUnsizedArray())
1364 // ESSL3 spec section 4.1.9: Array declaration which leaves the size unspecified is an error.
1365 // It is assumed that this applies to empty declarations as well.
1366 error(identifierOrTypeLocation, "empty array declaration needs to specify a size", identifier.c_str());
1371 if(singleDeclarationErrorCheck(publicType, identifierOrTypeLocation))
1374 if(nonInitErrorCheck(identifierOrTypeLocation, identifier, publicType))
1377 TVariable *variable = nullptr;
1378 if(!declareVariable(identifierOrTypeLocation, identifier, TType(publicType), &variable))
1381 if(variable && symbol)
1382 symbol->setId(variable->getUniqueId());
1385 return intermediate.makeAggregate(symbol, identifierOrTypeLocation);
1388 TIntermAggregate *TParseContext::parseSingleArrayDeclaration(TPublicType &publicType,
1389 const TSourceLoc &identifierLocation,
1390 const TString &identifier,
1391 const TSourceLoc &indexLocation,
1392 TIntermTyped *indexExpression)
1394 mDeferredSingleDeclarationErrorCheck = false;
1396 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1399 if(nonInitErrorCheck(identifierLocation, identifier, publicType))
1402 if(arrayTypeErrorCheck(indexLocation, publicType) || arrayQualifierErrorCheck(indexLocation, publicType))
1407 TType arrayType(publicType);
1410 if(arraySizeErrorCheck(identifierLocation, indexExpression, size))
1414 // Make the type an array even if size check failed.
1415 // This ensures useless error messages regarding the variable's non-arrayness won't follow.
1416 arrayType.setArraySize(size);
1418 TVariable *variable = nullptr;
1419 if(!declareVariable(identifierLocation, identifier, arrayType, &variable))
1422 TIntermSymbol *symbol = intermediate.addSymbol(0, identifier, arrayType, identifierLocation);
1423 if(variable && symbol)
1424 symbol->setId(variable->getUniqueId());
1426 return intermediate.makeAggregate(symbol, identifierLocation);
1429 TIntermAggregate *TParseContext::parseSingleInitDeclaration(const TPublicType &publicType,
1430 const TSourceLoc &identifierLocation,
1431 const TString &identifier,
1432 const TSourceLoc &initLocation,
1433 TIntermTyped *initializer)
1435 mDeferredSingleDeclarationErrorCheck = false;
1437 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1440 TIntermNode *intermNode = nullptr;
1441 if(!executeInitializer(identifierLocation, identifier, publicType, initializer, &intermNode))
1444 // Build intermediate representation
1446 return intermNode ? intermediate.makeAggregate(intermNode, initLocation) : nullptr;
1455 TIntermAggregate *TParseContext::parseSingleArrayInitDeclaration(TPublicType &publicType,
1456 const TSourceLoc &identifierLocation,
1457 const TString &identifier,
1458 const TSourceLoc &indexLocation,
1459 TIntermTyped *indexExpression,
1460 const TSourceLoc &initLocation,
1461 TIntermTyped *initializer)
1463 mDeferredSingleDeclarationErrorCheck = false;
1465 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1468 if(arrayTypeErrorCheck(indexLocation, publicType) || arrayQualifierErrorCheck(indexLocation, publicType))
1473 TPublicType arrayType(publicType);
1476 // If indexExpression is nullptr, then the array will eventually get its size implicitly from the initializer.
1477 if(indexExpression != nullptr && arraySizeErrorCheck(identifierLocation, indexExpression, size))
1481 // Make the type an array even if size check failed.
1482 // This ensures useless error messages regarding the variable's non-arrayness won't follow.
1483 arrayType.setArray(true, size);
1485 // initNode will correspond to the whole of "type b[n] = initializer".
1486 TIntermNode *initNode = nullptr;
1487 if(!executeInitializer(identifierLocation, identifier, arrayType, initializer, &initNode))
1489 return initNode ? intermediate.makeAggregate(initNode, initLocation) : nullptr;
1498 TIntermAggregate *TParseContext::parseInvariantDeclaration(const TSourceLoc &invariantLoc,
1499 const TSourceLoc &identifierLoc,
1500 const TString *identifier,
1501 const TSymbol *symbol)
1503 // invariant declaration
1504 if(globalErrorCheck(invariantLoc, symbolTable.atGlobalLevel(), "invariant varying"))
1511 error(identifierLoc, "undeclared identifier declared as invariant", identifier->c_str());
1517 const TString kGlFrontFacing("gl_FrontFacing");
1518 if(*identifier == kGlFrontFacing)
1520 error(identifierLoc, "identifier should not be declared as invariant", identifier->c_str());
1524 symbolTable.addInvariantVarying(std::string(identifier->c_str()));
1525 const TVariable *variable = getNamedVariable(identifierLoc, identifier, symbol);
1527 const TType &type = variable->getType();
1528 TIntermSymbol *intermSymbol = intermediate.addSymbol(variable->getUniqueId(),
1529 *identifier, type, identifierLoc);
1531 TIntermAggregate *aggregate = intermediate.makeAggregate(intermSymbol, identifierLoc);
1532 aggregate->setOp(EOpInvariantDeclaration);
1537 TIntermAggregate *TParseContext::parseDeclarator(TPublicType &publicType, TIntermAggregate *aggregateDeclaration,
1538 const TSourceLoc &identifierLocation, const TString &identifier)
1540 // If the declaration starting this declarator list was empty (example: int,), some checks were not performed.
1541 if(mDeferredSingleDeclarationErrorCheck)
1543 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1545 mDeferredSingleDeclarationErrorCheck = false;
1548 if(locationDeclaratorListCheck(identifierLocation, publicType))
1551 if(nonInitErrorCheck(identifierLocation, identifier, publicType))
1554 TVariable *variable = nullptr;
1555 if(!declareVariable(identifierLocation, identifier, TType(publicType), &variable))
1558 TIntermSymbol *symbol = intermediate.addSymbol(0, identifier, TType(publicType), identifierLocation);
1559 if(variable && symbol)
1560 symbol->setId(variable->getUniqueId());
1562 return intermediate.growAggregate(aggregateDeclaration, symbol, identifierLocation);
1565 TIntermAggregate *TParseContext::parseArrayDeclarator(TPublicType &publicType, TIntermAggregate *aggregateDeclaration,
1566 const TSourceLoc &identifierLocation, const TString &identifier,
1567 const TSourceLoc &arrayLocation, TIntermTyped *indexExpression)
1569 // If the declaration starting this declarator list was empty (example: int,), some checks were not performed.
1570 if(mDeferredSingleDeclarationErrorCheck)
1572 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1574 mDeferredSingleDeclarationErrorCheck = false;
1577 if(locationDeclaratorListCheck(identifierLocation, publicType))
1580 if(nonInitErrorCheck(identifierLocation, identifier, publicType))
1583 if(arrayTypeErrorCheck(arrayLocation, publicType) || arrayQualifierErrorCheck(arrayLocation, publicType))
1589 TType arrayType = TType(publicType);
1591 if(arraySizeErrorCheck(arrayLocation, indexExpression, size))
1595 arrayType.setArraySize(size);
1597 TVariable *variable = nullptr;
1598 if(!declareVariable(identifierLocation, identifier, arrayType, &variable))
1601 TIntermSymbol *symbol = intermediate.addSymbol(0, identifier, arrayType, identifierLocation);
1602 if(variable && symbol)
1603 symbol->setId(variable->getUniqueId());
1605 return intermediate.growAggregate(aggregateDeclaration, symbol, identifierLocation);
1611 TIntermAggregate *TParseContext::parseInitDeclarator(const TPublicType &publicType, TIntermAggregate *aggregateDeclaration,
1612 const TSourceLoc &identifierLocation, const TString &identifier,
1613 const TSourceLoc &initLocation, TIntermTyped *initializer)
1615 // If the declaration starting this declarator list was empty (example: int,), some checks were not performed.
1616 if(mDeferredSingleDeclarationErrorCheck)
1618 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1620 mDeferredSingleDeclarationErrorCheck = false;
1623 if(locationDeclaratorListCheck(identifierLocation, publicType))
1626 TIntermNode *intermNode = nullptr;
1627 if(!executeInitializer(identifierLocation, identifier, publicType, initializer, &intermNode))
1630 // build the intermediate representation
1634 return intermediate.growAggregate(aggregateDeclaration, intermNode, initLocation);
1638 return aggregateDeclaration;
1648 TIntermAggregate *TParseContext::parseArrayInitDeclarator(const TPublicType &publicType,
1649 TIntermAggregate *aggregateDeclaration,
1650 const TSourceLoc &identifierLocation,
1651 const TString &identifier,
1652 const TSourceLoc &indexLocation,
1653 TIntermTyped *indexExpression,
1654 const TSourceLoc &initLocation, TIntermTyped *initializer)
1656 // If the declaration starting this declarator list was empty (example: int,), some checks were not performed.
1657 if(mDeferredSingleDeclarationErrorCheck)
1659 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1661 mDeferredSingleDeclarationErrorCheck = false;
1664 if(locationDeclaratorListCheck(identifierLocation, publicType))
1667 if(arrayTypeErrorCheck(indexLocation, publicType) || arrayQualifierErrorCheck(indexLocation, publicType))
1672 TPublicType arrayType(publicType);
1675 // If indexExpression is nullptr, then the array will eventually get its size implicitly from the initializer.
1676 if(indexExpression != nullptr && arraySizeErrorCheck(identifierLocation, indexExpression, size))
1680 // Make the type an array even if size check failed.
1681 // This ensures useless error messages regarding the variable's non-arrayness won't follow.
1682 arrayType.setArray(true, size);
1684 // initNode will correspond to the whole of "b[n] = initializer".
1685 TIntermNode *initNode = nullptr;
1686 if(!executeInitializer(identifierLocation, identifier, arrayType, initializer, &initNode))
1690 return intermediate.growAggregate(aggregateDeclaration, initNode, initLocation);
1694 return aggregateDeclaration;
1704 void TParseContext::parseGlobalLayoutQualifier(const TPublicType &typeQualifier)
1706 if(mShaderVersion < 300)
1708 error(typeQualifier.line, "layout qualifiers supported in GLSL ES 3.00 only", "layout");
1713 if(typeQualifier.qualifier != EvqUniform)
1715 error(typeQualifier.line, "invalid qualifier:", getQualifierString(typeQualifier.qualifier), "global layout must be uniform");
1720 const TLayoutQualifier layoutQualifier = typeQualifier.layoutQualifier;
1721 ASSERT(!layoutQualifier.isEmpty());
1723 if(layoutLocationErrorCheck(typeQualifier.line, typeQualifier.layoutQualifier))
1729 if(layoutQualifier.matrixPacking != EmpUnspecified)
1731 mDefaultMatrixPacking = layoutQualifier.matrixPacking;
1734 if(layoutQualifier.blockStorage != EbsUnspecified)
1736 mDefaultBlockStorage = layoutQualifier.blockStorage;
1740 TFunction *TParseContext::addConstructorFunc(const TPublicType &publicTypeIn)
1742 TPublicType publicType = publicTypeIn;
1743 TOperator op = EOpNull;
1744 if(publicType.userDef)
1746 op = EOpConstructStruct;
1750 switch(publicType.type)
1753 if(publicType.isMatrix())
\r
1755 switch(publicType.getCols())
\r
1758 switch(publicType.getRows())
\r
1760 case 2: op = EOpConstructMat2; break;
\r
1761 case 3: op = EOpConstructMat2x3; break;
\r
1762 case 4: op = EOpConstructMat2x4; break;
\r
1766 switch(publicType.getRows())
\r
1768 case 2: op = EOpConstructMat3x2; break;
\r
1769 case 3: op = EOpConstructMat3; break;
\r
1770 case 4: op = EOpConstructMat3x4; break;
\r
1774 switch(publicType.getRows())
\r
1776 case 2: op = EOpConstructMat4x2; break;
\r
1777 case 3: op = EOpConstructMat4x3; break;
\r
1778 case 4: op = EOpConstructMat4; break;
\r
1785 switch(publicType.getNominalSize())
\r
1787 case 1: op = EOpConstructFloat; break;
\r
1788 case 2: op = EOpConstructVec2; break;
\r
1789 case 3: op = EOpConstructVec3; break;
\r
1790 case 4: op = EOpConstructVec4; break;
\r
1796 switch(publicType.getNominalSize())
1798 case 1: op = EOpConstructInt; break;
1799 case 2: op = EOpConstructIVec2; break;
1800 case 3: op = EOpConstructIVec3; break;
1801 case 4: op = EOpConstructIVec4; break;
1806 switch(publicType.getNominalSize())
1808 case 1: op = EOpConstructUInt; break;
1809 case 2: op = EOpConstructUVec2; break;
1810 case 3: op = EOpConstructUVec3; break;
1811 case 4: op = EOpConstructUVec4; break;
1816 switch(publicType.getNominalSize())
1818 case 1: op = EOpConstructBool; break;
1819 case 2: op = EOpConstructBVec2; break;
1820 case 3: op = EOpConstructBVec3; break;
1821 case 4: op = EOpConstructBVec4; break;
1830 error(publicType.line, "cannot construct this type", getBasicString(publicType.type));
1832 publicType.type = EbtFloat;
1833 op = EOpConstructFloat;
1838 TType type(publicType);
1839 return new TFunction(&tempString, type, op);
1842 // This function is used to test for the correctness of the parameters passed to various constructor functions
1843 // and also convert them to the right datatype if it is allowed and required.
1845 // Returns 0 for an error or the constructed node (aggregate or typed) for no error.
1847 TIntermTyped* TParseContext::addConstructor(TIntermNode* arguments, const TType* type, TOperator op, TFunction* fnCall, const TSourceLoc &line)
1849 TIntermAggregate *aggregateArguments = arguments->getAsAggregate();
1851 if(!aggregateArguments)
1853 aggregateArguments = new TIntermAggregate;
1854 aggregateArguments->getSequence().push_back(arguments);
1857 if(op == EOpConstructStruct)
1859 const TFieldList &fields = type->getStruct()->fields();
1860 TIntermSequence &args = aggregateArguments->getSequence();
1862 for(size_t i = 0; i < fields.size(); i++)
1864 if(args[i]->getAsTyped()->getType() != *fields[i]->type())
1866 error(line, "Structure constructor arguments do not match structure fields", "Error");
1874 // Turn the argument list itself into a constructor
1875 TIntermTyped *constructor = intermediate.setAggregateOperator(aggregateArguments, op, line);
1876 TIntermTyped *constConstructor = foldConstConstructor(constructor->getAsAggregate(), *type);
1877 if(constConstructor)
1879 return constConstructor;
1885 TIntermTyped* TParseContext::foldConstConstructor(TIntermAggregate* aggrNode, const TType& type)
1887 bool canBeFolded = areAllChildConst(aggrNode);
1888 aggrNode->setType(type);
1890 bool returnVal = false;
1891 ConstantUnion* unionArray = new ConstantUnion[type.getObjectSize()];
1892 if (aggrNode->getSequence().size() == 1) {
1893 returnVal = intermediate.parseConstTree(aggrNode->getLine(), aggrNode, unionArray, aggrNode->getOp(), type, true);
1896 returnVal = intermediate.parseConstTree(aggrNode->getLine(), aggrNode, unionArray, aggrNode->getOp(), type);
1901 return intermediate.addConstantUnion(unionArray, type, aggrNode->getLine());
1908 // This function returns the tree representation for the vector field(s) being accessed from contant vector.
1909 // If only one component of vector is accessed (v.x or v[0] where v is a contant vector), then a contant node is
1910 // returned, else an aggregate node is returned (for v.xy). The input to this function could either be the symbol
1911 // node or it could be the intermediate tree representation of accessing fields in a constant structure or column of
1912 // a constant matrix.
1914 TIntermTyped* TParseContext::addConstVectorNode(TVectorFields& fields, TIntermTyped* node, const TSourceLoc &line)
1916 TIntermTyped* typedNode;
1917 TIntermConstantUnion* tempConstantNode = node->getAsConstantUnion();
1919 ConstantUnion *unionArray;
1920 if (tempConstantNode) {
1921 unionArray = tempConstantNode->getUnionArrayPointer();
1926 } else { // The node has to be either a symbol node or an aggregate node or a tempConstant node, else, its an error
1927 error(line, "Cannot offset into the vector", "Error");
1933 ConstantUnion* constArray = new ConstantUnion[fields.num];
1935 for (int i = 0; i < fields.num; i++) {
1936 if (fields.offsets[i] >= node->getType().getObjectSize()) {
1937 std::stringstream extraInfoStream;
1938 extraInfoStream << "vector field selection out of range '" << fields.offsets[i] << "'";
1939 std::string extraInfo = extraInfoStream.str();
1940 error(line, "", "[", extraInfo.c_str());
1942 fields.offsets[i] = 0;
1945 constArray[i] = unionArray[fields.offsets[i]];
1948 typedNode = intermediate.addConstantUnion(constArray, node->getType(), line);
1953 // This function returns the column being accessed from a constant matrix. The values are retrieved from
1954 // the symbol table and parse-tree is built for a vector (each column of a matrix is a vector). The input
1955 // to the function could either be a symbol node (m[0] where m is a constant matrix)that represents a
1956 // constant matrix or it could be the tree representation of the constant matrix (s.m1[0] where s is a constant structure)
1958 TIntermTyped* TParseContext::addConstMatrixNode(int index, TIntermTyped* node, const TSourceLoc &line)
1960 TIntermTyped* typedNode;
1961 TIntermConstantUnion* tempConstantNode = node->getAsConstantUnion();
1963 if (index >= node->getType().getNominalSize()) {
1964 std::stringstream extraInfoStream;
1965 extraInfoStream << "matrix field selection out of range '" << index << "'";
1966 std::string extraInfo = extraInfoStream.str();
1967 error(line, "", "[", extraInfo.c_str());
1972 if (tempConstantNode) {
1973 ConstantUnion* unionArray = tempConstantNode->getUnionArrayPointer();
1974 int size = tempConstantNode->getType().getNominalSize();
1975 typedNode = intermediate.addConstantUnion(&unionArray[size*index], tempConstantNode->getType(), line);
1977 error(line, "Cannot offset into the matrix", "Error");
1988 // This function returns an element of an array accessed from a constant array. The values are retrieved from
1989 // the symbol table and parse-tree is built for the type of the element. The input
1990 // to the function could either be a symbol node (a[0] where a is a constant array)that represents a
1991 // constant array or it could be the tree representation of the constant array (s.a1[0] where s is a constant structure)
1993 TIntermTyped* TParseContext::addConstArrayNode(int index, TIntermTyped* node, const TSourceLoc &line)
1995 TIntermTyped* typedNode;
1996 TIntermConstantUnion* tempConstantNode = node->getAsConstantUnion();
1997 TType arrayElementType = node->getType();
1998 arrayElementType.clearArrayness();
2000 if (index >= node->getType().getArraySize()) {
2001 std::stringstream extraInfoStream;
2002 extraInfoStream << "array field selection out of range '" << index << "'";
2003 std::string extraInfo = extraInfoStream.str();
2004 error(line, "", "[", extraInfo.c_str());
2009 int arrayElementSize = arrayElementType.getObjectSize();
2011 if (tempConstantNode) {
2012 ConstantUnion* unionArray = tempConstantNode->getUnionArrayPointer();
2013 typedNode = intermediate.addConstantUnion(&unionArray[arrayElementSize * index], tempConstantNode->getType(), line);
2015 error(line, "Cannot offset into the array", "Error");
2026 // This function returns the value of a particular field inside a constant structure from the symbol table.
2027 // If there is an embedded/nested struct, it appropriately calls addConstStructNested or addConstStructFromAggr
2028 // function and returns the parse-tree with the values of the embedded/nested struct.
2030 TIntermTyped* TParseContext::addConstStruct(const TString& identifier, TIntermTyped* node, const TSourceLoc &line)
2032 const TFieldList &fields = node->getType().getStruct()->fields();
2033 TIntermTyped *typedNode;
2034 int instanceSize = 0;
2035 unsigned int index = 0;
2036 TIntermConstantUnion *tempConstantNode = node->getAsConstantUnion();
2038 for ( index = 0; index < fields.size(); ++index) {
2039 if (fields[index]->name() == identifier) {
2042 instanceSize += fields[index]->type()->getObjectSize();
2046 if (tempConstantNode) {
2047 ConstantUnion* constArray = tempConstantNode->getUnionArrayPointer();
2049 typedNode = intermediate.addConstantUnion(constArray+instanceSize, tempConstantNode->getType(), line); // type will be changed in the calling function
2051 error(line, "Cannot offset into the structure", "Error");
2061 // Interface/uniform blocks
2063 TIntermAggregate* TParseContext::addInterfaceBlock(const TPublicType& typeQualifier, const TSourceLoc& nameLine, const TString& blockName, TFieldList* fieldList,
2064 const TString* instanceName, const TSourceLoc& instanceLine, TIntermTyped* arrayIndex, const TSourceLoc& arrayIndexLine)
2066 if(reservedErrorCheck(nameLine, blockName))
2069 if(typeQualifier.qualifier != EvqUniform)
2071 error(typeQualifier.line, "invalid qualifier:", getQualifierString(typeQualifier.qualifier), "interface blocks must be uniform");
2075 TLayoutQualifier blockLayoutQualifier = typeQualifier.layoutQualifier;
2076 if(layoutLocationErrorCheck(typeQualifier.line, blockLayoutQualifier))
2081 if(blockLayoutQualifier.matrixPacking == EmpUnspecified)
2083 blockLayoutQualifier.matrixPacking = mDefaultMatrixPacking;
2086 if(blockLayoutQualifier.blockStorage == EbsUnspecified)
2088 blockLayoutQualifier.blockStorage = mDefaultBlockStorage;
2091 TSymbol* blockNameSymbol = new TSymbol(&blockName);
2092 if(!symbolTable.declare(*blockNameSymbol)) {
2093 error(nameLine, "redefinition", blockName.c_str(), "interface block name");
2097 // check for sampler types and apply layout qualifiers
2098 for(size_t memberIndex = 0; memberIndex < fieldList->size(); ++memberIndex) {
2099 TField* field = (*fieldList)[memberIndex];
2100 TType* fieldType = field->type();
2101 if(IsSampler(fieldType->getBasicType())) {
2102 error(field->line(), "unsupported type", fieldType->getBasicString(), "sampler types are not allowed in interface blocks");
2106 const TQualifier qualifier = fieldType->getQualifier();
2113 error(field->line(), "invalid qualifier on interface block member", getQualifierString(qualifier));
2118 // check layout qualifiers
2119 TLayoutQualifier fieldLayoutQualifier = fieldType->getLayoutQualifier();
2120 if(layoutLocationErrorCheck(field->line(), fieldLayoutQualifier))
2125 if(fieldLayoutQualifier.blockStorage != EbsUnspecified)
2127 error(field->line(), "invalid layout qualifier:", getBlockStorageString(fieldLayoutQualifier.blockStorage), "cannot be used here");
2131 if(fieldLayoutQualifier.matrixPacking == EmpUnspecified)
2133 fieldLayoutQualifier.matrixPacking = blockLayoutQualifier.matrixPacking;
2135 else if(!fieldType->isMatrix())
2137 error(field->line(), "invalid layout qualifier:", getMatrixPackingString(fieldLayoutQualifier.matrixPacking), "can only be used on matrix types");
2141 fieldType->setLayoutQualifier(fieldLayoutQualifier);
2146 if(arrayIndex != NULL)
2148 if(arraySizeErrorCheck(arrayIndexLine, arrayIndex, arraySize))
2152 TInterfaceBlock* interfaceBlock = new TInterfaceBlock(&blockName, fieldList, instanceName, arraySize, blockLayoutQualifier);
2153 TType interfaceBlockType(interfaceBlock, typeQualifier.qualifier, blockLayoutQualifier, arraySize);
2155 TString symbolName = "";
2160 // define symbols for the members of the interface block
2161 for(size_t memberIndex = 0; memberIndex < fieldList->size(); ++memberIndex)
2163 TField* field = (*fieldList)[memberIndex];
2164 TType* fieldType = field->type();
2166 // set parent pointer of the field variable
2167 fieldType->setInterfaceBlock(interfaceBlock);
2169 TVariable* fieldVariable = new TVariable(&field->name(), *fieldType);
2170 fieldVariable->setQualifier(typeQualifier.qualifier);
2172 if(!symbolTable.declare(*fieldVariable)) {
2173 error(field->line(), "redefinition", field->name().c_str(), "interface block member name");
2180 // add a symbol for this interface block
2181 TVariable* instanceTypeDef = new TVariable(instanceName, interfaceBlockType, false);
2182 instanceTypeDef->setQualifier(typeQualifier.qualifier);
2184 if(!symbolTable.declare(*instanceTypeDef)) {
2185 error(instanceLine, "redefinition", instanceName->c_str(), "interface block instance name");
2189 symbolId = instanceTypeDef->getUniqueId();
2190 symbolName = instanceTypeDef->getName();
2193 TIntermAggregate *aggregate = intermediate.makeAggregate(intermediate.addSymbol(symbolId, symbolName, interfaceBlockType, typeQualifier.line), nameLine);
2194 aggregate->setOp(EOpDeclaration);
2196 exitStructDeclaration();
2201 // Parse an array index expression
2203 TIntermTyped *TParseContext::addIndexExpression(TIntermTyped *baseExpression, const TSourceLoc &location, TIntermTyped *indexExpression)
2205 TIntermTyped *indexedExpression = NULL;
2207 if(!baseExpression->isArray() && !baseExpression->isMatrix() && !baseExpression->isVector())
2209 if(baseExpression->getAsSymbolNode())
2211 error(location, " left of '[' is not of type array, matrix, or vector ",
2212 baseExpression->getAsSymbolNode()->getSymbol().c_str());
2216 error(location, " left of '[' is not of type array, matrix, or vector ", "expression");
2221 TIntermConstantUnion *indexConstantUnion = indexExpression->getAsConstantUnion();
2223 if(indexExpression->getQualifier() == EvqConstExpr && indexConstantUnion)
2225 int index = indexConstantUnion->getIConst(0);
2228 std::stringstream infoStream;
2229 infoStream << index;
2230 std::string info = infoStream.str();
2231 error(location, "negative index", info.c_str());
2235 if(baseExpression->getType().getQualifier() == EvqConstExpr)
2237 if(baseExpression->isArray())
2239 // constant folding for arrays
2240 indexedExpression = addConstArrayNode(index, baseExpression, location);
2242 else if(baseExpression->isVector())
2244 // constant folding for vectors
2245 TVectorFields fields;
2247 fields.offsets[0] = index; // need to do it this way because v.xy sends fields integer array
2248 indexedExpression = addConstVectorNode(fields, baseExpression, location);
2250 else if(baseExpression->isMatrix())
2252 // constant folding for matrices
2253 indexedExpression = addConstMatrixNode(index, baseExpression, location);
2260 if(baseExpression->isArray())
2262 if(index >= baseExpression->getType().getArraySize())
2264 std::stringstream extraInfoStream;
2265 extraInfoStream << "array index out of range '" << index << "'";
2266 std::string extraInfo = extraInfoStream.str();
2267 error(location, "", "[", extraInfo.c_str());
2269 safeIndex = baseExpression->getType().getArraySize() - 1;
2272 else if((baseExpression->isVector() || baseExpression->isMatrix()) &&
2273 baseExpression->getType().getNominalSize() <= index)
2275 std::stringstream extraInfoStream;
2276 extraInfoStream << "field selection out of range '" << index << "'";
2277 std::string extraInfo = extraInfoStream.str();
2278 error(location, "", "[", extraInfo.c_str());
2280 safeIndex = baseExpression->getType().getNominalSize() - 1;
2283 // Don't modify the data of the previous constant union, because it can point
2284 // to builtins, like gl_MaxDrawBuffers. Instead use a new sanitized object.
2287 ConstantUnion *safeConstantUnion = new ConstantUnion();
2288 safeConstantUnion->setIConst(safeIndex);
2289 indexConstantUnion->replaceConstantUnion(safeConstantUnion);
2292 indexedExpression = intermediate.addIndex(EOpIndexDirect, baseExpression, indexExpression, location);
2297 if(baseExpression->isInterfaceBlock())
2300 "[", "array indexes for interface blocks arrays must be constant integral expressions");
2303 else if(baseExpression->getQualifier() == EvqFragmentOut)
2305 error(location, "", "[", "array indexes for fragment outputs must be constant integral expressions");
2309 indexedExpression = intermediate.addIndex(EOpIndexIndirect, baseExpression, indexExpression, location);
2312 if(indexedExpression == 0)
2314 ConstantUnion *unionArray = new ConstantUnion[1];
2315 unionArray->setFConst(0.0f);
2316 indexedExpression = intermediate.addConstantUnion(unionArray, TType(EbtFloat, EbpHigh, EvqConstExpr), location);
2318 else if(baseExpression->isArray())
2320 const TType &baseType = baseExpression->getType();
2321 if(baseType.getStruct())
2323 TType copyOfType(baseType.getStruct());
2324 indexedExpression->setType(copyOfType);
2326 else if(baseType.isInterfaceBlock())
2328 TType copyOfType(baseType.getInterfaceBlock(), baseType.getQualifier(), baseType.getLayoutQualifier(), 0);
2329 indexedExpression->setType(copyOfType);
2333 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(),
2334 EvqTemporary, static_cast<unsigned char>(baseExpression->getNominalSize()),
2335 static_cast<unsigned char>(baseExpression->getSecondarySize())));
2338 if(baseExpression->getType().getQualifier() == EvqConstExpr)
2340 indexedExpression->getTypePointer()->setQualifier(EvqConstExpr);
2343 else if(baseExpression->isMatrix())
2345 TQualifier qualifier = baseExpression->getType().getQualifier() == EvqConstExpr ? EvqConstExpr : EvqTemporary;
2346 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(),
2347 qualifier, static_cast<unsigned char>(baseExpression->getSecondarySize())));
2349 else if(baseExpression->isVector())
2351 TQualifier qualifier = baseExpression->getType().getQualifier() == EvqConstExpr ? EvqConstExpr : EvqTemporary;
2352 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(), qualifier));
2356 indexedExpression->setType(baseExpression->getType());
2359 return indexedExpression;
2362 TIntermTyped *TParseContext::addFieldSelectionExpression(TIntermTyped *baseExpression, const TSourceLoc &dotLocation,
2363 const TString &fieldString, const TSourceLoc &fieldLocation)
2365 TIntermTyped *indexedExpression = NULL;
2367 if(baseExpression->isArray())
2369 error(fieldLocation, "cannot apply dot operator to an array", ".");
2373 if(baseExpression->isVector())
2375 TVectorFields fields;
2376 if(!parseVectorFields(fieldString, baseExpression->getNominalSize(), fields, fieldLocation))
2379 fields.offsets[0] = 0;
2383 if(baseExpression->getType().getQualifier() == EvqConstExpr)
2385 // constant folding for vector fields
2386 indexedExpression = addConstVectorNode(fields, baseExpression, fieldLocation);
2387 if(indexedExpression == 0)
2390 indexedExpression = baseExpression;
2394 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(),
2395 EvqConstExpr, (unsigned char)(fieldString).size()));
2400 TString vectorString = fieldString;
2401 TIntermTyped *index = intermediate.addSwizzle(fields, fieldLocation);
2402 indexedExpression = intermediate.addIndex(EOpVectorSwizzle, baseExpression, index, dotLocation);
2403 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(),
2404 EvqTemporary, (unsigned char)vectorString.size()));
2407 else if(baseExpression->isMatrix())
2409 TMatrixFields fields;
2410 if(!parseMatrixFields(fieldString, baseExpression->getNominalSize(), baseExpression->getSecondarySize(), fields, fieldLocation))
2412 fields.wholeRow = false;
2413 fields.wholeCol = false;
2419 if(fields.wholeRow || fields.wholeCol)
2421 error(dotLocation, " non-scalar fields not implemented yet", ".");
2423 ConstantUnion *unionArray = new ConstantUnion[1];
2424 unionArray->setIConst(0);
2425 TIntermTyped *index = intermediate.addConstantUnion(unionArray, TType(EbtInt, EbpUndefined, EvqConstExpr),
2427 indexedExpression = intermediate.addIndex(EOpIndexDirect, baseExpression, index, dotLocation);
2428 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(),
2429 EvqTemporary, static_cast<unsigned char>(baseExpression->getNominalSize()),
2430 static_cast<unsigned char>(baseExpression->getSecondarySize())));
2434 ConstantUnion *unionArray = new ConstantUnion[1];
2435 unionArray->setIConst(fields.col * baseExpression->getSecondarySize() + fields.row);
2436 TIntermTyped *index = intermediate.addConstantUnion(unionArray, TType(EbtInt, EbpUndefined, EvqConstExpr),
2438 indexedExpression = intermediate.addIndex(EOpIndexDirect, baseExpression, index, dotLocation);
2439 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision()));
2442 else if(baseExpression->getBasicType() == EbtStruct)
2444 bool fieldFound = false;
2445 const TFieldList &fields = baseExpression->getType().getStruct()->fields();
2448 error(dotLocation, "structure has no fields", "Internal Error");
2450 indexedExpression = baseExpression;
2455 for(i = 0; i < fields.size(); ++i)
2457 if(fields[i]->name() == fieldString)
2465 if(baseExpression->getType().getQualifier() == EvqConstExpr)
2467 indexedExpression = addConstStruct(fieldString, baseExpression, dotLocation);
2468 if(indexedExpression == 0)
2471 indexedExpression = baseExpression;
2475 indexedExpression->setType(*fields[i]->type());
2476 // change the qualifier of the return type, not of the structure field
2477 // as the structure definition is shared between various structures.
2478 indexedExpression->getTypePointer()->setQualifier(EvqConstExpr);
2483 ConstantUnion *unionArray = new ConstantUnion[1];
2484 unionArray->setIConst(i);
2485 TIntermTyped *index = intermediate.addConstantUnion(unionArray, *fields[i]->type(), fieldLocation);
2486 indexedExpression = intermediate.addIndex(EOpIndexDirectStruct, baseExpression, index, dotLocation);
2487 indexedExpression->setType(*fields[i]->type());
2492 error(dotLocation, " no such field in structure", fieldString.c_str());
2494 indexedExpression = baseExpression;
2498 else if(baseExpression->isInterfaceBlock())
2500 bool fieldFound = false;
2501 const TFieldList &fields = baseExpression->getType().getInterfaceBlock()->fields();
2504 error(dotLocation, "interface block has no fields", "Internal Error");
2506 indexedExpression = baseExpression;
2511 for(i = 0; i < fields.size(); ++i)
2513 if(fields[i]->name() == fieldString)
2521 ConstantUnion *unionArray = new ConstantUnion[1];
2522 unionArray->setIConst(i);
2523 TIntermTyped *index = intermediate.addConstantUnion(unionArray, *fields[i]->type(), fieldLocation);
2524 indexedExpression = intermediate.addIndex(EOpIndexDirectInterfaceBlock, baseExpression, index,
2526 indexedExpression->setType(*fields[i]->type());
2530 error(dotLocation, " no such field in interface block", fieldString.c_str());
2532 indexedExpression = baseExpression;
2538 if(mShaderVersion < 300)
2540 error(dotLocation, " field selection requires structure, vector, or matrix on left hand side",
2541 fieldString.c_str());
2546 " field selection requires structure, vector, matrix, or interface block on left hand side",
2547 fieldString.c_str());
2550 indexedExpression = baseExpression;
2553 return indexedExpression;
2556 TLayoutQualifier TParseContext::parseLayoutQualifier(const TString &qualifierType, const TSourceLoc& qualifierTypeLine)
2558 TLayoutQualifier qualifier;
2560 qualifier.location = -1;
2561 qualifier.matrixPacking = EmpUnspecified;
2562 qualifier.blockStorage = EbsUnspecified;
2564 if(qualifierType == "shared")
2566 qualifier.blockStorage = EbsShared;
2568 else if(qualifierType == "packed")
2570 qualifier.blockStorage = EbsPacked;
2572 else if(qualifierType == "std140")
2574 qualifier.blockStorage = EbsStd140;
2576 else if(qualifierType == "row_major")
2578 qualifier.matrixPacking = EmpRowMajor;
2580 else if(qualifierType == "column_major")
2582 qualifier.matrixPacking = EmpColumnMajor;
2584 else if(qualifierType == "location")
2586 error(qualifierTypeLine, "invalid layout qualifier", qualifierType.c_str(), "location requires an argument");
2591 error(qualifierTypeLine, "invalid layout qualifier", qualifierType.c_str());
2598 TLayoutQualifier TParseContext::parseLayoutQualifier(const TString &qualifierType, const TSourceLoc& qualifierTypeLine, const TString &intValueString, int intValue, const TSourceLoc& intValueLine)
2600 TLayoutQualifier qualifier;
2602 qualifier.location = -1;
2603 qualifier.matrixPacking = EmpUnspecified;
2604 qualifier.blockStorage = EbsUnspecified;
2606 if (qualifierType != "location")
2608 error(qualifierTypeLine, "invalid layout qualifier", qualifierType.c_str(), "only location may have arguments");
2613 // must check that location is non-negative
2616 error(intValueLine, "out of range:", intValueString.c_str(), "location must be non-negative");
2621 qualifier.location = intValue;
2628 TLayoutQualifier TParseContext::joinLayoutQualifiers(TLayoutQualifier leftQualifier, TLayoutQualifier rightQualifier)
2630 TLayoutQualifier joinedQualifier = leftQualifier;
2632 if (rightQualifier.location != -1)
2634 joinedQualifier.location = rightQualifier.location;
2636 if(rightQualifier.matrixPacking != EmpUnspecified)
2638 joinedQualifier.matrixPacking = rightQualifier.matrixPacking;
2640 if(rightQualifier.blockStorage != EbsUnspecified)
2642 joinedQualifier.blockStorage = rightQualifier.blockStorage;
2645 return joinedQualifier;
2649 TPublicType TParseContext::joinInterpolationQualifiers(const TSourceLoc &interpolationLoc, TQualifier interpolationQualifier,
2650 const TSourceLoc &storageLoc, TQualifier storageQualifier)
2652 TQualifier mergedQualifier = EvqSmoothIn;
2654 if(storageQualifier == EvqFragmentIn) {
2655 if(interpolationQualifier == EvqSmooth)
2656 mergedQualifier = EvqSmoothIn;
2657 else if(interpolationQualifier == EvqFlat)
2658 mergedQualifier = EvqFlatIn;
2659 else UNREACHABLE(interpolationQualifier);
2661 else if(storageQualifier == EvqCentroidIn) {
2662 if(interpolationQualifier == EvqSmooth)
2663 mergedQualifier = EvqCentroidIn;
2664 else if(interpolationQualifier == EvqFlat)
2665 mergedQualifier = EvqFlatIn;
2666 else UNREACHABLE(interpolationQualifier);
2668 else if(storageQualifier == EvqVertexOut) {
2669 if(interpolationQualifier == EvqSmooth)
2670 mergedQualifier = EvqSmoothOut;
2671 else if(interpolationQualifier == EvqFlat)
2672 mergedQualifier = EvqFlatOut;
2673 else UNREACHABLE(interpolationQualifier);
2675 else if(storageQualifier == EvqCentroidOut) {
2676 if(interpolationQualifier == EvqSmooth)
2677 mergedQualifier = EvqCentroidOut;
2678 else if(interpolationQualifier == EvqFlat)
2679 mergedQualifier = EvqFlatOut;
2680 else UNREACHABLE(interpolationQualifier);
2683 error(interpolationLoc, "interpolation qualifier requires a fragment 'in' or vertex 'out' storage qualifier", getQualifierString(interpolationQualifier));
2686 mergedQualifier = storageQualifier;
2690 type.setBasic(EbtVoid, mergedQualifier, storageLoc);
2694 TFieldList *TParseContext::addStructDeclaratorList(const TPublicType &typeSpecifier, TFieldList *fieldList)
2696 if(voidErrorCheck(typeSpecifier.line, (*fieldList)[0]->name(), typeSpecifier.type))
2701 for(unsigned int i = 0; i < fieldList->size(); ++i)
2704 // Careful not to replace already known aspects of type, like array-ness
2706 TType *type = (*fieldList)[i]->type();
2707 type->setBasicType(typeSpecifier.type);
2708 type->setNominalSize(typeSpecifier.primarySize);
2709 type->setSecondarySize(typeSpecifier.secondarySize);
2710 type->setPrecision(typeSpecifier.precision);
2711 type->setQualifier(typeSpecifier.qualifier);
2712 type->setLayoutQualifier(typeSpecifier.layoutQualifier);
2714 // don't allow arrays of arrays
2717 if(arrayTypeErrorCheck(typeSpecifier.line, typeSpecifier))
2720 if(typeSpecifier.array)
2721 type->setArraySize(typeSpecifier.arraySize);
2722 if(typeSpecifier.userDef)
2724 type->setStruct(typeSpecifier.userDef->getStruct());
2727 if(structNestingErrorCheck(typeSpecifier.line, *(*fieldList)[i]))
2736 TPublicType TParseContext::addStructure(const TSourceLoc &structLine, const TSourceLoc &nameLine,
2737 const TString *structName, TFieldList *fieldList)
2739 TStructure *structure = new TStructure(structName, fieldList);
2740 TType *structureType = new TType(structure);
2742 // Store a bool in the struct if we're at global scope, to allow us to
2743 // skip the local struct scoping workaround in HLSL.
2744 structure->setUniqueId(TSymbolTableLevel::nextUniqueId());
2745 structure->setAtGlobalScope(symbolTable.atGlobalLevel());
2747 if(!structName->empty())
2749 if(reservedErrorCheck(nameLine, *structName))
2753 TVariable *userTypeDef = new TVariable(structName, *structureType, true);
2754 if(!symbolTable.declare(*userTypeDef))
2756 error(nameLine, "redefinition", structName->c_str(), "struct");
2761 // ensure we do not specify any storage qualifiers on the struct members
2762 for(unsigned int typeListIndex = 0; typeListIndex < fieldList->size(); typeListIndex++)
2764 const TField &field = *(*fieldList)[typeListIndex];
2765 const TQualifier qualifier = field.type()->getQualifier();
2772 error(field.line(), "invalid qualifier on struct member", getQualifierString(qualifier));
2778 TPublicType publicType;
2779 publicType.setBasic(EbtStruct, EvqTemporary, structLine);
2780 publicType.userDef = structureType;
2781 exitStructDeclaration();
2786 bool TParseContext::enterStructDeclaration(const TSourceLoc &line, const TString& identifier)
2788 ++mStructNestingLevel;
2790 // Embedded structure definitions are not supported per GLSL ES spec.
2791 // They aren't allowed in GLSL either, but we need to detect this here
2792 // so we don't rely on the GLSL compiler to catch it.
2793 if (mStructNestingLevel > 1) {
2794 error(line, "", "Embedded struct definitions are not allowed");
2801 void TParseContext::exitStructDeclaration()
2803 --mStructNestingLevel;
2806 bool TParseContext::structNestingErrorCheck(const TSourceLoc &line, const TField &field)
2808 static const int kWebGLMaxStructNesting = 4;
2810 if(field.type()->getBasicType() != EbtStruct)
2815 // We're already inside a structure definition at this point, so add
2816 // one to the field's struct nesting.
2817 if(1 + field.type()->getDeepestStructNesting() > kWebGLMaxStructNesting)
2819 std::stringstream reasonStream;
2820 reasonStream << "Reference of struct type "
2821 << field.type()->getStruct()->name().c_str()
2822 << " exceeds maximum allowed nesting level of "
2823 << kWebGLMaxStructNesting;
2824 std::string reason = reasonStream.str();
2825 error(line, reason.c_str(), field.name().c_str(), "");
2832 TIntermTyped *TParseContext::createUnaryMath(TOperator op, TIntermTyped *child, const TSourceLoc &loc, const TType *funcReturnType)
2834 if(child == nullptr)
2842 if(child->getBasicType() != EbtBool ||
2843 child->isMatrix() ||
2851 if((child->getBasicType() != EbtInt && child->getBasicType() != EbtUInt) ||
2852 child->isMatrix() ||
2858 case EOpPostIncrement:
2859 case EOpPreIncrement:
2860 case EOpPostDecrement:
2861 case EOpPreDecrement:
2863 if(child->getBasicType() == EbtStruct ||
2864 child->getBasicType() == EbtBool ||
2869 // Operators for built-ins are already type checked against their prototype.
2874 return intermediate.addUnaryMath(op, child, loc); // FIXME , funcReturnType);
2877 TIntermTyped *TParseContext::addUnaryMath(TOperator op, TIntermTyped *child, const TSourceLoc &loc)
2879 TIntermTyped *node = createUnaryMath(op, child, loc, nullptr);
2882 unaryOpError(loc, getOperatorString(op), child->getCompleteString());
2889 TIntermTyped *TParseContext::addUnaryMathLValue(TOperator op, TIntermTyped *child, const TSourceLoc &loc)
2891 if(lValueErrorCheck(loc, getOperatorString(op), child))
2893 return addUnaryMath(op, child, loc);
2896 bool TParseContext::binaryOpCommonCheck(TOperator op, TIntermTyped *left, TIntermTyped *right, const TSourceLoc &loc)
2898 if(left->isArray() || right->isArray())
2900 if(mShaderVersion < 300)
2902 error(loc, "Invalid operation for arrays", getOperatorString(op));
2906 if(left->isArray() != right->isArray())
2908 error(loc, "array / non-array mismatch", getOperatorString(op));
2920 error(loc, "Invalid operation for arrays", getOperatorString(op));
2923 // At this point, size of implicitly sized arrays should be resolved.
2924 if(left->getArraySize() != right->getArraySize())
2926 error(loc, "array size mismatch", getOperatorString(op));
2931 // Check ops which require integer / ivec parameters
2932 bool isBitShift = false;
2935 case EOpBitShiftLeft:
2936 case EOpBitShiftRight:
2937 case EOpBitShiftLeftAssign:
2938 case EOpBitShiftRightAssign:
2939 // Unsigned can be bit-shifted by signed and vice versa, but we need to
2940 // check that the basic type is an integer type.
2942 if(!IsInteger(left->getBasicType()) || !IsInteger(right->getBasicType()))
2950 case EOpBitwiseAndAssign:
2951 case EOpBitwiseXorAssign:
2952 case EOpBitwiseOrAssign:
2953 // It is enough to check the type of only one operand, since later it
2954 // is checked that the operand types match.
2955 if(!IsInteger(left->getBasicType()))
2964 // GLSL ES 1.00 and 3.00 do not support implicit type casting.
2965 // So the basic type should usually match.
2966 if(!isBitShift && left->getBasicType() != right->getBasicType())
2971 // Check that type sizes match exactly on ops that require that.
2972 // Also check restrictions for structs that contain arrays or samplers.
2979 // ESSL 1.00 sections 5.7, 5.8, 5.9
2980 if(mShaderVersion < 300 && left->getType().isStructureContainingArrays())
2982 error(loc, "undefined operation for structs containing arrays", getOperatorString(op));
2985 // Samplers as l-values are disallowed also in ESSL 3.00, see section 4.1.7,
2986 // we interpret the spec so that this extends to structs containing samplers,
2987 // similarly to ESSL 1.00 spec.
2988 if((mShaderVersion < 300 || op == EOpAssign || op == EOpInitialize) &&
2989 left->getType().isStructureContainingSamplers())
2991 error(loc, "undefined operation for structs containing samplers", getOperatorString(op));
2995 case EOpGreaterThan:
2996 case EOpLessThanEqual:
2997 case EOpGreaterThanEqual:
2998 if((left->getNominalSize() != right->getNominalSize()) ||
2999 (left->getSecondarySize() != right->getSecondarySize()))
3010 TIntermSwitch *TParseContext::addSwitch(TIntermTyped *init, TIntermAggregate *statementList, const TSourceLoc &loc)
3012 TBasicType switchType = init->getBasicType();
3013 if((switchType != EbtInt && switchType != EbtUInt) ||
3018 error(init->getLine(), "init-expression in a switch statement must be a scalar integer", "switch");
3025 if(!ValidateSwitch::validate(switchType, this, statementList, loc))
3032 TIntermSwitch *node = intermediate.addSwitch(init, statementList, loc);
3035 error(loc, "erroneous switch statement", "switch");
3042 TIntermCase *TParseContext::addCase(TIntermTyped *condition, const TSourceLoc &loc)
3044 if(mSwitchNestingLevel == 0)
3046 error(loc, "case labels need to be inside switch statements", "case");
3050 if(condition == nullptr)
3052 error(loc, "case label must have a condition", "case");
3056 if((condition->getBasicType() != EbtInt && condition->getBasicType() != EbtUInt) ||
3057 condition->isMatrix() ||
3058 condition->isArray() ||
3059 condition->isVector())
3061 error(condition->getLine(), "case label must be a scalar integer", "case");
3064 TIntermConstantUnion *conditionConst = condition->getAsConstantUnion();
3065 if(conditionConst == nullptr)
3067 error(condition->getLine(), "case label must be constant", "case");
3070 TIntermCase *node = intermediate.addCase(condition, loc);
3073 error(loc, "erroneous case statement", "case");
3080 TIntermCase *TParseContext::addDefault(const TSourceLoc &loc)
3082 if(mSwitchNestingLevel == 0)
3084 error(loc, "default labels need to be inside switch statements", "default");
3088 TIntermCase *node = intermediate.addCase(nullptr, loc);
3091 error(loc, "erroneous default statement", "default");
3097 TIntermTyped *TParseContext::createAssign(TOperator op, TIntermTyped *left, TIntermTyped *right, const TSourceLoc &loc)
3099 if(binaryOpCommonCheck(op, left, right, loc))
3101 return intermediate.addAssign(op, left, right, loc);
3106 TIntermTyped *TParseContext::addAssign(TOperator op, TIntermTyped *left, TIntermTyped *right, const TSourceLoc &loc)
3108 TIntermTyped *node = createAssign(op, left, right, loc);
3111 assignError(loc, "assign", left->getCompleteString(), right->getCompleteString());
3118 TIntermTyped *TParseContext::addBinaryMathInternal(TOperator op, TIntermTyped *left, TIntermTyped *right,
3119 const TSourceLoc &loc)
3121 if(!binaryOpCommonCheck(op, left, right, loc))
3130 case EOpGreaterThan:
3131 case EOpLessThanEqual:
3132 case EOpGreaterThanEqual:
3133 ASSERT(!left->isArray() && !right->isArray());
3134 if(left->isMatrix() || left->isVector() ||
3135 left->getBasicType() == EbtStruct)
3143 ASSERT(!left->isArray() && !right->isArray());
3144 if(left->getBasicType() != EbtBool ||
3145 left->isMatrix() || left->isVector())
3154 ASSERT(!left->isArray() && !right->isArray());
3155 if(left->getBasicType() == EbtStruct || left->getBasicType() == EbtBool)
3161 ASSERT(!left->isArray() && !right->isArray());
3162 // Note that this is only for the % operator, not for mod()
3163 if(left->getBasicType() == EbtStruct || left->getBasicType() == EbtBool || left->getBasicType() == EbtFloat)
3168 // Note that for bitwise ops, type checking is done in promote() to
3169 // share code between ops and compound assignment
3174 return intermediate.addBinaryMath(op, left, right, loc);
3177 TIntermTyped *TParseContext::addBinaryMath(TOperator op, TIntermTyped *left, TIntermTyped *right, const TSourceLoc &loc)
3179 TIntermTyped *node = addBinaryMathInternal(op, left, right, loc);
3182 binaryOpError(loc, getOperatorString(op), left->getCompleteString(), right->getCompleteString());
3189 TIntermTyped *TParseContext::addBinaryMathBooleanResult(TOperator op, TIntermTyped *left, TIntermTyped *right, const TSourceLoc &loc)
3191 TIntermTyped *node = addBinaryMathInternal(op, left, right, loc);
3194 binaryOpError(loc, getOperatorString(op), left->getCompleteString(), right->getCompleteString());
3196 ConstantUnion *unionArray = new ConstantUnion[1];
3197 unionArray->setBConst(false);
3198 return intermediate.addConstantUnion(unionArray, TType(EbtBool, EbpUndefined, EvqConstExpr), loc);
3203 TIntermBranch *TParseContext::addBranch(TOperator op, const TSourceLoc &loc)
3208 if(mLoopNestingLevel <= 0)
3210 error(loc, "continue statement only allowed in loops", "");
3215 if(mLoopNestingLevel <= 0 && mSwitchNestingLevel <= 0)
3217 error(loc, "break statement only allowed in loops and switch statements", "");
3222 if(mCurrentFunctionType->getBasicType() != EbtVoid)
3224 error(loc, "non-void function must return a value", "return");
3229 // No checks for discard
3232 return intermediate.addBranch(op, loc);
3235 TIntermBranch *TParseContext::addBranch(TOperator op, TIntermTyped *returnValue, const TSourceLoc &loc)
3237 ASSERT(op == EOpReturn);
3238 mFunctionReturnsValue = true;
3239 if(mCurrentFunctionType->getBasicType() == EbtVoid)
3241 error(loc, "void function cannot return a value", "return");
3244 else if(*mCurrentFunctionType != returnValue->getType())
3246 error(loc, "function return is not matching type:", "return");
3249 return intermediate.addBranch(op, returnValue, loc);
3252 TIntermTyped *TParseContext::addFunctionCallOrMethod(TFunction *fnCall, TIntermNode *paramNode, TIntermNode *thisNode, const TSourceLoc &loc, bool *fatalError)
3254 *fatalError = false;
3255 TOperator op = fnCall->getBuiltInOp();
3256 TIntermTyped *callNode = nullptr;
3258 if(thisNode != nullptr)
3260 ConstantUnion *unionArray = new ConstantUnion[1];
3262 TIntermTyped *typedThis = thisNode->getAsTyped();
3263 if(fnCall->getName() != "length")
3265 error(loc, "invalid method", fnCall->getName().c_str());
3268 else if(paramNode != nullptr)
3270 error(loc, "method takes no parameters", "length");
3273 else if(typedThis == nullptr || !typedThis->isArray())
3275 error(loc, "length can only be called on arrays", "length");
3280 arraySize = typedThis->getArraySize();
3281 if(typedThis->getAsSymbolNode() == nullptr)
3283 // This code path can be hit with expressions like these:
3285 // (func()).length()
3286 // (int[3](0, 1, 2)).length()
3287 // ESSL 3.00 section 5.9 defines expressions so that this is not actually a valid expression.
3288 // It allows "An array name with the length method applied" in contrast to GLSL 4.4 spec section 5.9
3289 // which allows "An array, vector or matrix expression with the length method applied".
3290 error(loc, "length can only be called on array names, not on array expressions", "length");
3294 unionArray->setIConst(arraySize);
3295 callNode = intermediate.addConstantUnion(unionArray, TType(EbtInt, EbpUndefined, EvqConstExpr), loc);
3297 else if(op != EOpNull)
3300 // Then this should be a constructor.
3301 // Don't go through the symbol table for constructors.
3302 // Their parameters will be verified algorithmically.
3304 TType type(EbtVoid, EbpUndefined); // use this to get the type back
3305 if(!constructorErrorCheck(loc, paramNode, *fnCall, op, &type))
3308 // It's a constructor, of type 'type'.
3310 callNode = addConstructor(paramNode, &type, op, fnCall, loc);
3313 if(callNode == nullptr)
3316 callNode = intermediate.setAggregateOperator(nullptr, op, loc);
3318 callNode->setType(type);
3323 // Not a constructor. Find it in the symbol table.
3325 const TFunction *fnCandidate;
3327 fnCandidate = findFunction(loc, fnCall, &builtIn);
3331 // A declared function.
3333 if(builtIn && !fnCandidate->getExtension().empty() &&
3334 extensionErrorCheck(loc, fnCandidate->getExtension()))
3338 op = fnCandidate->getBuiltInOp();
3339 if(builtIn && op != EOpNull)
3342 // A function call mapped to a built-in operation.
3344 if(fnCandidate->getParamCount() == 1)
3347 // Treat it like a built-in unary operator.
3349 callNode = createUnaryMath(op, paramNode->getAsTyped(), loc, &fnCandidate->getReturnType());
3350 if(callNode == nullptr)
3352 std::stringstream extraInfoStream;
3353 extraInfoStream << "built in unary operator function. Type: "
3354 << static_cast<TIntermTyped*>(paramNode)->getCompleteString();
3355 std::string extraInfo = extraInfoStream.str();
3356 error(paramNode->getLine(), " wrong operand type", "Internal Error", extraInfo.c_str());
3363 TIntermAggregate *aggregate = intermediate.setAggregateOperator(paramNode, op, loc);
3364 aggregate->setType(fnCandidate->getReturnType());
3366 // Some built-in functions have out parameters too.
3367 functionCallLValueErrorCheck(fnCandidate, aggregate);
3369 callNode = aggregate;
3374 // This is a real function call
3376 TIntermAggregate *aggregate = intermediate.setAggregateOperator(paramNode, EOpFunctionCall, loc);
3377 aggregate->setType(fnCandidate->getReturnType());
3379 // this is how we know whether the given function is a builtIn function or a user defined function
3380 // if builtIn == false, it's a userDefined -> could be an overloaded builtIn function also
3381 // if builtIn == true, it's definitely a builtIn function with EOpNull
3383 aggregate->setUserDefined();
3384 aggregate->setName(fnCandidate->getMangledName());
3386 callNode = aggregate;
3388 functionCallLValueErrorCheck(fnCandidate, aggregate);
3390 callNode->setType(fnCandidate->getReturnType());
3394 // error message was put out by findFunction()
3395 // Put on a dummy node for error recovery
3396 ConstantUnion *unionArray = new ConstantUnion[1];
3397 unionArray->setFConst(0.0f);
3398 callNode = intermediate.addConstantUnion(unionArray, TType(EbtFloat, EbpUndefined, EvqConstExpr), loc);
3407 // Parse an array of strings using yyparse.
3409 // Returns 0 for success.
3411 int PaParseStrings(int count, const char* const string[], const int length[],
3412 TParseContext* context) {
3413 if ((count == 0) || (string == NULL))
3416 if (glslang_initialize(context))
3419 int error = glslang_scan(count, string, length, context);
3421 error = glslang_parse(context);
3423 glslang_finalize(context);
3425 return (error == 0) && (context->numErrors() == 0) ? 0 : 1;