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 "ValidateSwitch.h"
16 ///////////////////////////////////////////////////////////////////////
18 // Sub- vector and matrix fields
20 ////////////////////////////////////////////////////////////////////////
23 // Look at a '.' field selector string and change it into offsets
26 bool TParseContext::parseVectorFields(const TString& compString, int vecSize, TVectorFields& fields, const TSourceLoc &line)
28 fields.num = (int) compString.size();
30 error(line, "illegal vector field selection", compString.c_str());
40 for (int i = 0; i < fields.num; ++i) {
41 switch (compString[i]) {
43 fields.offsets[i] = 0;
47 fields.offsets[i] = 0;
51 fields.offsets[i] = 0;
55 fields.offsets[i] = 1;
59 fields.offsets[i] = 1;
63 fields.offsets[i] = 1;
67 fields.offsets[i] = 2;
71 fields.offsets[i] = 2;
75 fields.offsets[i] = 2;
79 fields.offsets[i] = 3;
83 fields.offsets[i] = 3;
87 fields.offsets[i] = 3;
91 error(line, "illegal vector field selection", compString.c_str());
96 for (int i = 0; i < fields.num; ++i) {
97 if (fields.offsets[i] >= vecSize) {
98 error(line, "vector field selection out of range", compString.c_str());
103 if (fieldSet[i] != fieldSet[i-1]) {
104 error(line, "illegal - vector component fields not from the same set", compString.c_str());
115 // Look at a '.' field selector string and change it into offsets
118 bool TParseContext::parseMatrixFields(const TString& compString, int matCols, int matRows, TMatrixFields& fields, const TSourceLoc &line)
120 fields.wholeRow = false;
121 fields.wholeCol = false;
125 if (compString.size() != 2) {
126 error(line, "illegal length of matrix field selection", compString.c_str());
130 if (compString[0] == '_') {
131 if (compString[1] < '0' || compString[1] > '3') {
132 error(line, "illegal matrix field selection", compString.c_str());
135 fields.wholeCol = true;
136 fields.col = compString[1] - '0';
137 } else if (compString[1] == '_') {
138 if (compString[0] < '0' || compString[0] > '3') {
139 error(line, "illegal matrix field selection", compString.c_str());
142 fields.wholeRow = true;
143 fields.row = compString[0] - '0';
145 if (compString[0] < '0' || compString[0] > '3' ||
146 compString[1] < '0' || compString[1] > '3') {
147 error(line, "illegal matrix field selection", compString.c_str());
150 fields.row = compString[0] - '0';
151 fields.col = compString[1] - '0';
154 if (fields.row >= matRows || fields.col >= matCols) {
155 error(line, "matrix field selection out of range", compString.c_str());
162 ///////////////////////////////////////////////////////////////////////
166 ////////////////////////////////////////////////////////////////////////
169 // Track whether errors have occurred.
171 void TParseContext::recover()
176 // Used by flex/bison to output all syntax and parsing errors.
178 void TParseContext::error(const TSourceLoc& loc,
179 const char* reason, const char* token,
180 const char* extraInfo)
182 pp::SourceLocation srcLoc;
183 DecodeSourceLoc(loc, &srcLoc.file, &srcLoc.line);
184 diagnostics.writeInfo(pp::Diagnostics::PP_ERROR,
185 srcLoc, reason, token, extraInfo);
189 void TParseContext::warning(const TSourceLoc& loc,
190 const char* reason, const char* token,
191 const char* extraInfo) {
192 pp::SourceLocation srcLoc;
193 DecodeSourceLoc(loc, &srcLoc.file, &srcLoc.line);
194 diagnostics.writeInfo(pp::Diagnostics::PP_WARNING,
195 srcLoc, reason, token, extraInfo);
198 void TParseContext::trace(const char* str)
200 diagnostics.writeDebug(str);
204 // Same error message for all places assignments don't work.
206 void TParseContext::assignError(const TSourceLoc &line, const char* op, TString left, TString right)
208 std::stringstream extraInfoStream;
209 extraInfoStream << "cannot convert from '" << right << "' to '" << left << "'";
210 std::string extraInfo = extraInfoStream.str();
211 error(line, "", op, extraInfo.c_str());
215 // Same error message for all places unary operations don't work.
217 void TParseContext::unaryOpError(const TSourceLoc &line, const char* op, TString operand)
219 std::stringstream extraInfoStream;
220 extraInfoStream << "no operation '" << op << "' exists that takes an operand of type " << operand
221 << " (or there is no acceptable conversion)";
222 std::string extraInfo = extraInfoStream.str();
223 error(line, " wrong operand type", op, extraInfo.c_str());
227 // Same error message for all binary operations don't work.
229 void TParseContext::binaryOpError(const TSourceLoc &line, const char* op, TString left, TString right)
231 std::stringstream extraInfoStream;
232 extraInfoStream << "no operation '" << op << "' exists that takes a left-hand operand of type '" << left
233 << "' and a right operand of type '" << right << "' (or there is no acceptable conversion)";
234 std::string extraInfo = extraInfoStream.str();
235 error(line, " wrong operand types ", op, extraInfo.c_str());
238 bool TParseContext::precisionErrorCheck(const TSourceLoc &line, TPrecision precision, TBasicType type){
239 if (!checksPrecisionErrors)
243 if( precision == EbpUndefined ){
244 error( line, "No precision specified for (float)", "" );
249 if( precision == EbpUndefined ){
250 error( line, "No precision specified (int)", "" );
261 // Both test and if necessary, spit out an error, to see if the node is really
262 // an l-value that can be operated on this way.
264 // Returns true if the was an error.
266 bool TParseContext::lValueErrorCheck(const TSourceLoc &line, const char* op, TIntermTyped* node)
268 TIntermSymbol* symNode = node->getAsSymbolNode();
269 TIntermBinary* binaryNode = node->getAsBinaryNode();
274 switch(binaryNode->getOp()) {
276 case EOpIndexIndirect:
277 case EOpIndexDirectStruct:
278 return lValueErrorCheck(line, op, binaryNode->getLeft());
279 case EOpVectorSwizzle:
280 errorReturn = lValueErrorCheck(line, op, binaryNode->getLeft());
282 int offset[4] = {0,0,0,0};
284 TIntermTyped* rightNode = binaryNode->getRight();
285 TIntermAggregate *aggrNode = rightNode->getAsAggregate();
287 for (TIntermSequence::iterator p = aggrNode->getSequence().begin();
288 p != aggrNode->getSequence().end(); p++) {
289 int value = (*p)->getAsTyped()->getAsConstantUnion()->getIConst(0);
291 if (offset[value] > 1) {
292 error(line, " l-value of swizzle cannot have duplicate components", op);
303 error(line, " l-value required", op);
309 const char* symbol = 0;
311 symbol = symNode->getSymbol().c_str();
313 const char* message = 0;
314 switch (node->getQualifier()) {
315 case EvqConstExpr: message = "can't modify a const"; break;
316 case EvqConstReadOnly: message = "can't modify a const"; break;
317 case EvqAttribute: message = "can't modify an attribute"; break;
318 case EvqFragmentIn: message = "can't modify an input"; break;
319 case EvqVertexIn: message = "can't modify an input"; break;
320 case EvqUniform: message = "can't modify a uniform"; break;
324 case EvqVaryingIn: message = "can't modify a varying"; break;
325 case EvqInput: message = "can't modify an input"; break;
326 case EvqFragCoord: message = "can't modify gl_FragCoord"; break;
327 case EvqFrontFacing: message = "can't modify gl_FrontFacing"; break;
328 case EvqPointCoord: message = "can't modify gl_PointCoord"; break;
329 case EvqInstanceID: message = "can't modify gl_InstanceID"; break;
333 // Type that can't be written to?
335 if(IsSampler(node->getBasicType()))
337 message = "can't modify a sampler";
339 else if(node->getBasicType() == EbtVoid)
341 message = "can't modify void";
345 if (message == 0 && binaryNode == 0 && symNode == 0) {
346 error(line, " l-value required", op);
353 // Everything else is okay, no error.
359 // If we get here, we have an error and a message.
362 std::stringstream extraInfoStream;
363 extraInfoStream << "\"" << symbol << "\" (" << message << ")";
364 std::string extraInfo = extraInfoStream.str();
365 error(line, " l-value required", op, extraInfo.c_str());
368 std::stringstream extraInfoStream;
369 extraInfoStream << "(" << message << ")";
370 std::string extraInfo = extraInfoStream.str();
371 error(line, " l-value required", op, extraInfo.c_str());
378 // Both test, and if necessary spit out an error, to see if the node is really
381 // Returns true if the was an error.
383 bool TParseContext::constErrorCheck(TIntermTyped* node)
385 if (node->getQualifier() == EvqConstExpr)
388 error(node->getLine(), "constant expression required", "");
394 // Both test, and if necessary spit out an error, to see if the node is really
397 // Returns true if the was an error.
399 bool TParseContext::integerErrorCheck(TIntermTyped* node, const char* token)
401 if (node->isScalarInt())
404 error(node->getLine(), "integer expression required", token);
410 // Both test, and if necessary spit out an error, to see if we are currently
413 // Returns true if the was an error.
415 bool TParseContext::globalErrorCheck(const TSourceLoc &line, bool global, const char* token)
420 error(line, "only allowed at global scope", token);
426 // For now, keep it simple: if it starts "gl_", it's reserved, independent
427 // of scope. Except, if the symbol table is at the built-in push-level,
428 // which is when we are parsing built-ins.
429 // Also checks for "webgl_" and "_webgl_" reserved identifiers if parsing a
432 // Returns true if there was an error.
434 bool TParseContext::reservedErrorCheck(const TSourceLoc &line, const TString& identifier)
436 static const char* reservedErrMsg = "reserved built-in name";
437 if (!symbolTable.atBuiltInLevel()) {
438 if (identifier.compare(0, 3, "gl_") == 0) {
439 error(line, reservedErrMsg, "gl_");
442 if (identifier.find("__") != TString::npos) {
443 error(line, "identifiers containing two consecutive underscores (__) are reserved as possible future keywords", identifier.c_str());
452 // Make sure there is enough data provided to the constructor to build
453 // something of the type of the constructor. Also returns the type of
456 // Returns true if there was an error in construction.
458 bool TParseContext::constructorErrorCheck(const TSourceLoc &line, TIntermNode* node, TFunction& function, TOperator op, TType* type)
460 *type = function.getReturnType();
462 bool constructingMatrix = false;
464 case EOpConstructMat2:
465 case EOpConstructMat3:
466 case EOpConstructMat4:
467 constructingMatrix = true;
474 // Note: It's okay to have too many components available, but not okay to have unused
475 // arguments. 'full' will go to true when enough args have been seen. If we loop
476 // again, there is an extra argument, so 'overfull' will become true.
480 bool constType = true;
482 bool overFull = false;
483 bool matrixInMatrix = false;
484 bool arrayArg = false;
485 for (size_t i = 0; i < function.getParamCount(); ++i) {
486 const TParameter& param = function.getParam(i);
487 size += param.type->getObjectSize();
489 if (constructingMatrix && param.type->isMatrix())
490 matrixInMatrix = true;
493 if (op != EOpConstructStruct && !type->isArray() && size >= type->getObjectSize())
495 if (param.type->getQualifier() != EvqConstExpr)
497 if (param.type->isArray())
502 type->setQualifier(EvqConstExpr);
504 if (type->isArray() && type->getArraySize() != function.getParamCount()) {
505 error(line, "array constructor needs one argument per array element", "constructor");
509 if (arrayArg && op != EOpConstructStruct) {
510 error(line, "constructing from a non-dereferenced array", "constructor");
514 if (matrixInMatrix && !type->isArray()) {
515 if (function.getParamCount() != 1) {
516 error(line, "constructing matrix from matrix can only take one argument", "constructor");
522 error(line, "too many arguments", "constructor");
526 if (op == EOpConstructStruct && !type->isArray() && int(type->getStruct()->fields().size()) != function.getParamCount()) {
527 error(line, "Number of constructor parameters does not match the number of structure fields", "constructor");
531 if (!type->isMatrix() || !matrixInMatrix) {
532 if ((op != EOpConstructStruct && size != 1 && size < type->getObjectSize()) ||
533 (op == EOpConstructStruct && size < type->getObjectSize())) {
534 error(line, "not enough data provided for construction", "constructor");
539 TIntermTyped *typed = node ? node->getAsTyped() : 0;
541 error(line, "constructor argument does not have a type", "constructor");
544 if (op != EOpConstructStruct && IsSampler(typed->getBasicType())) {
545 error(line, "cannot convert a sampler", "constructor");
548 if (typed->getBasicType() == EbtVoid) {
549 error(line, "cannot convert a void", "constructor");
556 // This function checks to see if a void variable has been declared and raise an error message for such a case
558 // returns true in case of an error
560 bool TParseContext::voidErrorCheck(const TSourceLoc &line, const TString& identifier, const TBasicType& type)
562 if(type == EbtVoid) {
563 error(line, "illegal use of type 'void'", identifier.c_str());
570 // This function checks to see if the node (for the expression) contains a scalar boolean expression or not
572 // returns true in case of an error
574 bool TParseContext::boolErrorCheck(const TSourceLoc &line, const TIntermTyped* type)
576 if (type->getBasicType() != EbtBool || type->isArray() || type->isMatrix() || type->isVector()) {
577 error(line, "boolean expression expected", "");
584 // This function checks to see if the node (for the expression) contains a scalar boolean expression or not
586 // returns true in case of an error
588 bool TParseContext::boolErrorCheck(const TSourceLoc &line, const TPublicType& pType)
590 if (pType.type != EbtBool || pType.array || (pType.primarySize > 1) || (pType.secondarySize > 1)) {
591 error(line, "boolean expression expected", "");
598 bool TParseContext::samplerErrorCheck(const TSourceLoc &line, const TPublicType& pType, const char* reason)
600 if (pType.type == EbtStruct) {
601 if (containsSampler(*pType.userDef)) {
602 error(line, reason, getBasicString(pType.type), "(structure contains a sampler)");
608 } else if (IsSampler(pType.type)) {
609 error(line, reason, getBasicString(pType.type));
617 bool TParseContext::structQualifierErrorCheck(const TSourceLoc &line, const TPublicType& pType)
619 switch(pType.qualifier)
632 if(pType.type == EbtStruct)
634 error(line, "cannot be used with a structure", getQualifierString(pType.qualifier));
643 if (pType.qualifier != EvqUniform && samplerErrorCheck(line, pType, "samplers must be uniform"))
646 // check for layout qualifier issues
647 const TLayoutQualifier layoutQualifier = pType.layoutQualifier;
649 if (pType.qualifier != EvqVertexIn && pType.qualifier != EvqFragmentOut &&
650 layoutLocationErrorCheck(line, pType.layoutQualifier))
658 // These checks are common for all declarations starting a declarator list, and declarators that follow an empty
661 bool TParseContext::singleDeclarationErrorCheck(const TPublicType &publicType, const TSourceLoc &identifierLocation)
663 switch(publicType.qualifier)
670 if(publicType.type == EbtStruct)
672 error(identifierLocation, "cannot be used with a structure",
673 getQualifierString(publicType.qualifier));
680 if(publicType.qualifier != EvqUniform && samplerErrorCheck(identifierLocation, publicType,
681 "samplers must be uniform"))
686 // check for layout qualifier issues
687 const TLayoutQualifier layoutQualifier = publicType.layoutQualifier;
689 if(layoutQualifier.matrixPacking != EmpUnspecified)
691 error(identifierLocation, "layout qualifier", getMatrixPackingString(layoutQualifier.matrixPacking),
692 "only valid for interface blocks");
696 if(layoutQualifier.blockStorage != EbsUnspecified)
698 error(identifierLocation, "layout qualifier", getBlockStorageString(layoutQualifier.blockStorage),
699 "only valid for interface blocks");
703 if(publicType.qualifier != EvqVertexIn && publicType.qualifier != EvqFragmentOut &&
704 layoutLocationErrorCheck(identifierLocation, publicType.layoutQualifier))
712 bool TParseContext::layoutLocationErrorCheck(const TSourceLoc &location, const TLayoutQualifier &layoutQualifier)
\r
714 if(layoutQualifier.location != -1)
\r
716 error(location, "invalid layout qualifier:", "location", "only valid on program inputs and outputs");
\r
723 bool TParseContext::locationDeclaratorListCheck(const TSourceLoc& line, const TPublicType &pType)
725 if(pType.layoutQualifier.location != -1)
727 error(line, "location must only be specified for a single input or output variable", "location");
734 bool TParseContext::parameterSamplerErrorCheck(const TSourceLoc &line, TQualifier qualifier, const TType& type)
736 if ((qualifier == EvqOut || qualifier == EvqInOut) &&
737 type.getBasicType() != EbtStruct && IsSampler(type.getBasicType())) {
738 error(line, "samplers cannot be output parameters", type.getBasicString());
745 bool TParseContext::containsSampler(TType& type)
747 if (IsSampler(type.getBasicType()))
750 if (type.getBasicType() == EbtStruct) {
751 const TFieldList& fields = type.getStruct()->fields();
752 for(unsigned int i = 0; i < fields.size(); ++i) {
753 if (containsSampler(*fields[i]->type()))
762 // Do size checking for an array type's size.
764 // Returns true if there was an error.
766 bool TParseContext::arraySizeErrorCheck(const TSourceLoc &line, TIntermTyped* expr, int& size)
768 TIntermConstantUnion* constant = expr->getAsConstantUnion();
770 if (constant == 0 || !constant->isScalarInt())
772 error(line, "array size must be a constant integer expression", "");
776 if (constant->getBasicType() == EbtUInt)
778 unsigned int uintSize = constant->getUConst(0);
779 if (uintSize > static_cast<unsigned int>(std::numeric_limits<int>::max()))
781 error(line, "array size too large", "");
786 size = static_cast<int>(uintSize);
790 size = constant->getIConst(0);
794 error(line, "array size must be a positive integer", "");
804 // See if this qualifier can be an array.
806 // Returns true if there is an error.
808 bool TParseContext::arrayQualifierErrorCheck(const TSourceLoc &line, TPublicType type)
810 if ((type.qualifier == EvqAttribute) || (type.qualifier == EvqVertexIn) || (type.qualifier == EvqConstExpr)) {
811 error(line, "cannot declare arrays of this qualifier", TType(type).getCompleteString().c_str());
819 // See if this type can be an array.
821 // Returns true if there is an error.
823 bool TParseContext::arrayTypeErrorCheck(const TSourceLoc &line, TPublicType type)
826 // Can the type be an array?
829 error(line, "cannot declare arrays of arrays", TType(type).getCompleteString().c_str());
837 // Do all the semantic checking for declaring an array, with and
838 // without a size, and make the right changes to the symbol table.
840 // size == 0 means no specified size.
842 // Returns true if there was an error.
844 bool TParseContext::arrayErrorCheck(const TSourceLoc &line, TString& identifier, TPublicType type, TVariable*& variable)
847 // Don't check for reserved word use until after we know it's not in the symbol table,
848 // because reserved arrays can be redeclared.
851 bool builtIn = false;
852 bool sameScope = false;
853 TSymbol* symbol = symbolTable.find(identifier, shaderVersion, &builtIn, &sameScope);
854 if (symbol == 0 || !sameScope) {
855 if (reservedErrorCheck(line, identifier))
858 variable = new TVariable(&identifier, TType(type));
861 variable->getType().setArraySize(type.arraySize);
863 if (! symbolTable.declare(*variable)) {
865 error(line, "INTERNAL ERROR inserting new symbol", identifier.c_str());
869 if (! symbol->isVariable()) {
870 error(line, "variable expected", identifier.c_str());
874 variable = static_cast<TVariable*>(symbol);
875 if (! variable->getType().isArray()) {
876 error(line, "redeclaring non-array as array", identifier.c_str());
879 if (variable->getType().getArraySize() > 0) {
880 error(line, "redeclaration of array with size", identifier.c_str());
884 if (! variable->getType().sameElementType(TType(type))) {
885 error(line, "redeclaration of array with a different type", identifier.c_str());
889 TType* t = variable->getArrayInformationType();
891 if (t->getMaxArraySize() > type.arraySize) {
892 error(line, "higher index value already used for the array", identifier.c_str());
895 t->setArraySize(type.arraySize);
896 t = t->getArrayInformationType();
900 variable->getType().setArraySize(type.arraySize);
903 if (voidErrorCheck(line, identifier, type.type))
909 bool TParseContext::arraySetMaxSize(TIntermSymbol *node, TType* type, int size, bool updateFlag, const TSourceLoc &line)
911 bool builtIn = false;
912 TSymbol* symbol = symbolTable.find(node->getSymbol(), shaderVersion, &builtIn);
914 error(line, " undeclared identifier", node->getSymbol().c_str());
917 TVariable* variable = static_cast<TVariable*>(symbol);
919 type->setArrayInformationType(variable->getArrayInformationType());
920 variable->updateArrayInformationType(type);
922 // special casing to test index value of gl_FragData. If the accessed index is >= gl_MaxDrawBuffers
924 if (node->getSymbol() == "gl_FragData") {
925 TSymbol* fragData = symbolTable.find("gl_MaxDrawBuffers", shaderVersion, &builtIn);
928 int fragDataValue = static_cast<TVariable*>(fragData)->getConstPointer()[0].getIConst();
929 if (fragDataValue <= size) {
930 error(line, "", "[", "gl_FragData can only have a max array size of up to gl_MaxDrawBuffers");
935 // we dont want to update the maxArraySize when this flag is not set, we just want to include this
936 // node type in the chain of node types so that its updated when a higher maxArraySize comes in.
941 variable->getType().setMaxArraySize(size);
942 type->setMaxArraySize(size);
945 while(tt->getArrayInformationType() != 0) {
946 tt = tt->getArrayInformationType();
947 tt->setMaxArraySize(size);
954 // Enforce non-initializer type/qualifier rules.
956 // Returns true if there was an error.
958 bool TParseContext::nonInitConstErrorCheck(const TSourceLoc &line, TString& identifier, TPublicType& type, bool array)
960 if (type.qualifier == EvqConstExpr)
962 // Make the qualifier make sense.
963 type.qualifier = EvqTemporary;
967 error(line, "arrays may not be declared constant since they cannot be initialized", identifier.c_str());
969 else if (type.isStructureContainingArrays())
971 error(line, "structures containing arrays may not be declared constant since they cannot be initialized", identifier.c_str());
975 error(line, "variables with qualifier 'const' must be initialized", identifier.c_str());
985 // Do semantic checking for a variable declaration that has no initializer,
986 // and update the symbol table.
988 // Returns true if there was an error.
990 bool TParseContext::nonInitErrorCheck(const TSourceLoc &line, const TString& identifier, TPublicType& type)
992 if(type.qualifier == EvqConstExpr)
994 // Make the qualifier make sense.
995 type.qualifier = EvqTemporary;
997 // Generate informative error messages for ESSL1.
998 // In ESSL3 arrays and structures containing arrays can be constant.
999 if(shaderVersion < 300 && type.isStructureContainingArrays())
1002 "structures containing arrays may not be declared constant since they cannot be initialized",
1003 identifier.c_str());
1007 error(line, "variables with qualifier 'const' must be initialized", identifier.c_str());
1012 if(type.isUnsizedArray())
1014 error(line, "implicitly sized arrays need to be initialized", identifier.c_str());
1020 // Do some simple checks that are shared between all variable declarations,
1021 // and update the symbol table.
1023 // Returns true if declaring the variable succeeded.
1025 bool TParseContext::declareVariable(const TSourceLoc &line, const TString &identifier, const TType &type,
1026 TVariable **variable)
1028 ASSERT((*variable) == nullptr);
1030 // gl_LastFragData may be redeclared with a new precision qualifier
1031 if(type.isArray() && identifier.compare(0, 15, "gl_LastFragData") == 0)
1033 const TVariable *maxDrawBuffers =
1034 static_cast<const TVariable *>(symbolTable.findBuiltIn("gl_MaxDrawBuffers", shaderVersion));
1035 if(type.getArraySize() != maxDrawBuffers->getConstPointer()->getIConst())
1037 error(line, "redeclaration of gl_LastFragData with size != gl_MaxDrawBuffers", identifier.c_str());
1042 if(reservedErrorCheck(line, identifier))
1045 (*variable) = new TVariable(&identifier, type);
1046 if(!symbolTable.declare(**variable))
1048 error(line, "redefinition", identifier.c_str());
1050 (*variable) = nullptr;
1054 if(voidErrorCheck(line, identifier, type.getBasicType()))
1060 bool TParseContext::paramErrorCheck(const TSourceLoc &line, TQualifier qualifier, TQualifier paramQualifier, TType* type)
1062 if (qualifier != EvqConstReadOnly && qualifier != EvqTemporary) {
1063 error(line, "qualifier not allowed on function parameter", getQualifierString(qualifier));
1066 if (qualifier == EvqConstReadOnly && paramQualifier != EvqIn) {
1067 error(line, "qualifier not allowed with ", getQualifierString(qualifier), getQualifierString(paramQualifier));
1071 if (qualifier == EvqConstReadOnly)
1072 type->setQualifier(EvqConstReadOnly);
1074 type->setQualifier(paramQualifier);
1079 bool TParseContext::extensionErrorCheck(const TSourceLoc &line, const TString& extension)
1081 const TExtensionBehavior& extBehavior = extensionBehavior();
1082 TExtensionBehavior::const_iterator iter = extBehavior.find(extension.c_str());
1083 if (iter == extBehavior.end()) {
1084 error(line, "extension", extension.c_str(), "is not supported");
1087 // In GLSL ES, an extension's default behavior is "disable".
1088 if (iter->second == EBhDisable || iter->second == EBhUndefined) {
1089 error(line, "extension", extension.c_str(), "is disabled");
1092 if (iter->second == EBhWarn) {
1093 warning(line, "extension", extension.c_str(), "is being used");
1100 bool TParseContext::functionCallLValueErrorCheck(const TFunction *fnCandidate, TIntermAggregate *aggregate)
1102 for(size_t i = 0; i < fnCandidate->getParamCount(); ++i)
1104 TQualifier qual = fnCandidate->getParam(i).type->getQualifier();
1105 if(qual == EvqOut || qual == EvqInOut)
1107 TIntermTyped *node = (aggregate->getSequence())[i]->getAsTyped();
1108 if(lValueErrorCheck(node->getLine(), "assign", node))
1110 error(node->getLine(),
1111 "Constant value cannot be passed for 'out' or 'inout' parameters.", "Error");
1120 bool TParseContext::supportsExtension(const char* extension)
1122 const TExtensionBehavior& extbehavior = extensionBehavior();
1123 TExtensionBehavior::const_iterator iter = extbehavior.find(extension);
1124 return (iter != extbehavior.end());
1127 void TParseContext::handleExtensionDirective(const TSourceLoc &line, const char* extName, const char* behavior)
1129 pp::SourceLocation loc;
1130 DecodeSourceLoc(line, &loc.file, &loc.line);
1131 directiveHandler.handleExtension(loc, extName, behavior);
1134 void TParseContext::handlePragmaDirective(const TSourceLoc &line, const char* name, const char* value)
1136 pp::SourceLocation loc;
1137 DecodeSourceLoc(line, &loc.file, &loc.line);
1138 directiveHandler.handlePragma(loc, name, value);
1141 /////////////////////////////////////////////////////////////////////////////////
1145 /////////////////////////////////////////////////////////////////////////////////
1147 const TVariable *TParseContext::getNamedVariable(const TSourceLoc &location,
1148 const TString *name,
1149 const TSymbol *symbol)
1151 const TVariable *variable = NULL;
1155 error(location, "undeclared identifier", name->c_str());
1158 else if(!symbol->isVariable())
1160 error(location, "variable expected", name->c_str());
1165 variable = static_cast<const TVariable*>(symbol);
1167 if(symbolTable.findBuiltIn(variable->getName(), shaderVersion))
1172 // Reject shaders using both gl_FragData and gl_FragColor
1173 TQualifier qualifier = variable->getType().getQualifier();
1174 if(qualifier == EvqFragData)
1176 mUsesFragData = true;
1178 else if(qualifier == EvqFragColor)
1180 mUsesFragColor = true;
1183 // This validation is not quite correct - it's only an error to write to
1184 // both FragData and FragColor. For simplicity, and because users shouldn't
1185 // be rewarded for reading from undefined varaibles, return an error
1186 // if they are both referenced, rather than assigned.
1187 if(mUsesFragData && mUsesFragColor)
1189 error(location, "cannot use both gl_FragData and gl_FragColor", name->c_str());
1196 TType type(EbtFloat, EbpUndefined);
1197 TVariable *fakeVariable = new TVariable(name, type);
1198 symbolTable.declare(*fakeVariable);
1199 variable = fakeVariable;
1206 // Look up a function name in the symbol table, and make sure it is a function.
1208 // Return the function symbol if found, otherwise 0.
1210 const TFunction* TParseContext::findFunction(const TSourceLoc &line, TFunction* call, bool *builtIn)
1212 // First find by unmangled name to check whether the function name has been
1213 // hidden by a variable name or struct typename.
1214 const TSymbol* symbol = symbolTable.find(call->getName(), shaderVersion, builtIn);
1216 symbol = symbolTable.find(call->getMangledName(), shaderVersion, builtIn);
1220 error(line, "no matching overloaded function found", call->getName().c_str());
1224 if (!symbol->isFunction()) {
1225 error(line, "function name expected", call->getName().c_str());
1229 return static_cast<const TFunction*>(symbol);
1233 // Initializers show up in several places in the grammar. Have one set of
1234 // code to handle them here.
1236 bool TParseContext::executeInitializer(const TSourceLoc& line, const TString& identifier, const TPublicType& pType,
1237 TIntermTyped* initializer, TIntermNode*& intermNode, TVariable* variable)
1239 TType type = TType(pType);
1241 if (variable == 0) {
1242 if (reservedErrorCheck(line, identifier))
1245 if (voidErrorCheck(line, identifier, pType.type))
1249 // add variable to symbol table
1251 variable = new TVariable(&identifier, type);
1252 if (! symbolTable.declare(*variable)) {
1253 error(line, "redefinition", variable->getName().c_str());
1255 // don't delete variable, it's used by error recovery, and the pool
1256 // pop will take care of the memory
1261 // identifier must be of type constant, a global, or a temporary
1263 TQualifier qualifier = variable->getType().getQualifier();
1264 if ((qualifier != EvqTemporary) && (qualifier != EvqGlobal) && (qualifier != EvqConstExpr)) {
1265 error(line, " cannot initialize this type of qualifier ", variable->getType().getQualifierString());
1269 // test for and propagate constant
1272 if (qualifier == EvqConstExpr) {
1273 if (qualifier != initializer->getType().getQualifier()) {
1274 std::stringstream extraInfoStream;
1275 extraInfoStream << "'" << variable->getType().getCompleteString() << "'";
1276 std::string extraInfo = extraInfoStream.str();
1277 error(line, " assigning non-constant to", "=", extraInfo.c_str());
1278 variable->getType().setQualifier(EvqTemporary);
1281 if (type != initializer->getType()) {
1282 error(line, " non-matching types for const initializer ",
1283 variable->getType().getQualifierString());
1284 variable->getType().setQualifier(EvqTemporary);
1287 if (initializer->getAsConstantUnion()) {
1288 ConstantUnion* unionArray = variable->getConstPointer();
1290 if (type.getObjectSize() == 1 && type.getBasicType() != EbtStruct) {
1291 *unionArray = (initializer->getAsConstantUnion()->getUnionArrayPointer())[0];
1293 variable->shareConstPointer(initializer->getAsConstantUnion()->getUnionArrayPointer());
1295 } else if (initializer->getAsSymbolNode()) {
1296 const TSymbol* symbol = symbolTable.find(initializer->getAsSymbolNode()->getSymbol(), shaderVersion);
1297 const TVariable* tVar = static_cast<const TVariable*>(symbol);
1299 ConstantUnion* constArray = tVar->getConstPointer();
1300 variable->shareConstPointer(constArray);
1302 std::stringstream extraInfoStream;
1303 extraInfoStream << "'" << variable->getType().getCompleteString() << "'";
1304 std::string extraInfo = extraInfoStream.str();
1305 error(line, " cannot assign to", "=", extraInfo.c_str());
1306 variable->getType().setQualifier(EvqTemporary);
1311 if (qualifier != EvqConstExpr) {
1312 TIntermSymbol* intermSymbol = intermediate.addSymbol(variable->getUniqueId(), variable->getName(), variable->getType(), line);
1313 intermNode = intermediate.addAssign(EOpInitialize, intermSymbol, initializer, line);
1314 if (intermNode == 0) {
1315 assignError(line, "=", intermSymbol->getCompleteString(), initializer->getCompleteString());
1324 bool TParseContext::areAllChildConst(TIntermAggregate* aggrNode)
1326 ASSERT(aggrNode != NULL);
1327 if (!aggrNode->isConstructor())
1330 bool allConstant = true;
1332 // check if all the child nodes are constants so that they can be inserted into
1334 TIntermSequence &sequence = aggrNode->getSequence() ;
1335 for (TIntermSequence::iterator p = sequence.begin(); p != sequence.end(); ++p) {
1336 if (!(*p)->getAsTyped()->getAsConstantUnion())
1343 TPublicType TParseContext::addFullySpecifiedType(TQualifier qualifier, bool invariant, TLayoutQualifier layoutQualifier, const TPublicType &typeSpecifier)
1345 TPublicType returnType = typeSpecifier;
1346 returnType.qualifier = qualifier;
1347 returnType.invariant = invariant;
1348 returnType.layoutQualifier = layoutQualifier;
1350 if(typeSpecifier.array)
1352 error(typeSpecifier.line, "not supported", "first-class array");
1354 returnType.clearArrayness();
1357 if(shaderVersion < 300)
1359 if(qualifier == EvqAttribute && (typeSpecifier.type == EbtBool || typeSpecifier.type == EbtInt))
1361 error(typeSpecifier.line, "cannot be bool or int", getQualifierString(qualifier));
1365 if((qualifier == EvqVaryingIn || qualifier == EvqVaryingOut) &&
1366 (typeSpecifier.type == EbtBool || typeSpecifier.type == EbtInt))
1368 error(typeSpecifier.line, "cannot be bool or int", getQualifierString(qualifier));
1380 case EvqCentroidOut:
1382 if(typeSpecifier.type == EbtBool)
1384 error(typeSpecifier.line, "cannot be bool", getQualifierString(qualifier));
1387 if(typeSpecifier.type == EbtInt || typeSpecifier.type == EbtUInt)
1389 error(typeSpecifier.line, "must use 'flat' interpolation here", getQualifierString(qualifier));
1395 case EvqFragmentOut:
1398 if(typeSpecifier.type == EbtBool)
1400 error(typeSpecifier.line, "cannot be bool", getQualifierString(qualifier));
1412 TIntermAggregate *TParseContext::parseSingleDeclaration(TPublicType &publicType,
1413 const TSourceLoc &identifierOrTypeLocation,
1414 const TString &identifier)
1416 TIntermSymbol *symbol = intermediate.addSymbol(0, identifier, TType(publicType), identifierOrTypeLocation);
1418 bool emptyDeclaration = (identifier == "");
1420 mDeferredSingleDeclarationErrorCheck = emptyDeclaration;
1422 if(emptyDeclaration)
1424 if(publicType.isUnsizedArray())
1426 // ESSL3 spec section 4.1.9: Array declaration which leaves the size unspecified is an error.
1427 // It is assumed that this applies to empty declarations as well.
1428 error(identifierOrTypeLocation, "empty array declaration needs to specify a size", identifier.c_str());
1433 if(singleDeclarationErrorCheck(publicType, identifierOrTypeLocation))
1436 if(nonInitErrorCheck(identifierOrTypeLocation, identifier, publicType))
1439 TVariable *variable = nullptr;
1440 if(!declareVariable(identifierOrTypeLocation, identifier, TType(publicType), &variable))
1443 if(variable && symbol)
1444 symbol->setId(variable->getUniqueId());
1447 return intermediate.makeAggregate(symbol, identifierOrTypeLocation);
1450 TIntermAggregate *TParseContext::parseSingleArrayDeclaration(TPublicType &publicType,
1451 const TSourceLoc &identifierLocation,
1452 const TString &identifier,
1453 const TSourceLoc &indexLocation,
1454 TIntermTyped *indexExpression)
1456 mDeferredSingleDeclarationErrorCheck = false;
1458 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1461 if(nonInitErrorCheck(identifierLocation, identifier, publicType))
1464 if(arrayTypeErrorCheck(indexLocation, publicType) || arrayQualifierErrorCheck(indexLocation, publicType))
1469 TType arrayType(publicType);
1472 if(arraySizeErrorCheck(identifierLocation, indexExpression, size))
1476 // Make the type an array even if size check failed.
1477 // This ensures useless error messages regarding the variable's non-arrayness won't follow.
1478 arrayType.setArraySize(size);
1480 TVariable *variable = nullptr;
1481 if(!declareVariable(identifierLocation, identifier, arrayType, &variable))
1484 TIntermSymbol *symbol = intermediate.addSymbol(0, identifier, arrayType, identifierLocation);
1485 if(variable && symbol)
1486 symbol->setId(variable->getUniqueId());
1488 return intermediate.makeAggregate(symbol, identifierLocation);
1491 TIntermAggregate *TParseContext::parseSingleInitDeclaration(const TPublicType &publicType,
1492 const TSourceLoc &identifierLocation,
1493 const TString &identifier,
1494 const TSourceLoc &initLocation,
1495 TIntermTyped *initializer)
1497 mDeferredSingleDeclarationErrorCheck = false;
1499 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1502 TIntermNode *intermNode = nullptr;
1503 if(!executeInitializer(identifierLocation, identifier, publicType, initializer, intermNode))
1506 // Build intermediate representation
1508 return intermNode ? intermediate.makeAggregate(intermNode, initLocation) : nullptr;
1517 TIntermAggregate *TParseContext::parseSingleArrayInitDeclaration(TPublicType &publicType,
1518 const TSourceLoc &identifierLocation,
1519 const TString &identifier,
1520 const TSourceLoc &indexLocation,
1521 TIntermTyped *indexExpression,
1522 const TSourceLoc &initLocation,
1523 TIntermTyped *initializer)
1525 mDeferredSingleDeclarationErrorCheck = false;
1527 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1530 if(arrayTypeErrorCheck(indexLocation, publicType) || arrayQualifierErrorCheck(indexLocation, publicType))
1535 TPublicType arrayType(publicType);
1538 // If indexExpression is nullptr, then the array will eventually get its size implicitly from the initializer.
1539 if(indexExpression != nullptr && arraySizeErrorCheck(identifierLocation, indexExpression, size))
1543 // Make the type an array even if size check failed.
1544 // This ensures useless error messages regarding the variable's non-arrayness won't follow.
1545 arrayType.setArray(true, size);
1547 // initNode will correspond to the whole of "type b[n] = initializer".
1548 TIntermNode *initNode = nullptr;
1549 if(!executeInitializer(identifierLocation, identifier, arrayType, initializer, initNode))
1551 return initNode ? intermediate.makeAggregate(initNode, initLocation) : nullptr;
1560 TIntermAggregate *TParseContext::parseInvariantDeclaration(const TSourceLoc &invariantLoc,
1561 const TSourceLoc &identifierLoc,
1562 const TString *identifier,
1563 const TSymbol *symbol)
1565 // invariant declaration
1566 if(globalErrorCheck(invariantLoc, symbolTable.atGlobalLevel(), "invariant varying"))
1573 error(identifierLoc, "undeclared identifier declared as invariant", identifier->c_str());
1579 const TString kGlFrontFacing("gl_FrontFacing");
1580 if(*identifier == kGlFrontFacing)
1582 error(identifierLoc, "identifier should not be declared as invariant", identifier->c_str());
1586 symbolTable.addInvariantVarying(std::string(identifier->c_str()));
1587 const TVariable *variable = getNamedVariable(identifierLoc, identifier, symbol);
1589 const TType &type = variable->getType();
1590 TIntermSymbol *intermSymbol = intermediate.addSymbol(variable->getUniqueId(),
1591 *identifier, type, identifierLoc);
1593 TIntermAggregate *aggregate = intermediate.makeAggregate(intermSymbol, identifierLoc);
1594 aggregate->setOp(EOpInvariantDeclaration);
1599 TIntermAggregate *TParseContext::parseDeclarator(TPublicType &publicType, TIntermAggregate *aggregateDeclaration,
1600 const TSourceLoc &identifierLocation, const TString &identifier)
1602 // If the declaration starting this declarator list was empty (example: int,), some checks were not performed.
1603 if(mDeferredSingleDeclarationErrorCheck)
1605 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1607 mDeferredSingleDeclarationErrorCheck = false;
1610 if(locationDeclaratorListCheck(identifierLocation, publicType))
1613 if(nonInitErrorCheck(identifierLocation, identifier, publicType))
1616 TVariable *variable = nullptr;
1617 if(!declareVariable(identifierLocation, identifier, TType(publicType), &variable))
1620 TIntermSymbol *symbol = intermediate.addSymbol(0, identifier, TType(publicType), identifierLocation);
1621 if(variable && symbol)
1622 symbol->setId(variable->getUniqueId());
1624 return intermediate.growAggregate(aggregateDeclaration, symbol, identifierLocation);
1627 TIntermAggregate *TParseContext::parseArrayDeclarator(TPublicType &publicType, TIntermAggregate *aggregateDeclaration,
1628 const TSourceLoc &identifierLocation, const TString &identifier,
1629 const TSourceLoc &arrayLocation, TIntermTyped *indexExpression)
1631 // If the declaration starting this declarator list was empty (example: int,), some checks were not performed.
1632 if(mDeferredSingleDeclarationErrorCheck)
1634 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1636 mDeferredSingleDeclarationErrorCheck = false;
1639 if(locationDeclaratorListCheck(identifierLocation, publicType))
1642 if(nonInitErrorCheck(identifierLocation, identifier, publicType))
1645 if(arrayTypeErrorCheck(arrayLocation, publicType) || arrayQualifierErrorCheck(arrayLocation, publicType))
1651 TType arrayType = TType(publicType);
1653 if(arraySizeErrorCheck(arrayLocation, indexExpression, size))
1657 arrayType.setArraySize(size);
1659 TVariable *variable = nullptr;
1660 if(!declareVariable(identifierLocation, identifier, arrayType, &variable))
1663 TIntermSymbol *symbol = intermediate.addSymbol(0, identifier, arrayType, identifierLocation);
1664 if(variable && symbol)
1665 symbol->setId(variable->getUniqueId());
1667 return intermediate.growAggregate(aggregateDeclaration, symbol, identifierLocation);
1673 TIntermAggregate *TParseContext::parseInitDeclarator(const TPublicType &publicType, TIntermAggregate *aggregateDeclaration,
1674 const TSourceLoc &identifierLocation, const TString &identifier,
1675 const TSourceLoc &initLocation, TIntermTyped *initializer)
1677 // If the declaration starting this declarator list was empty (example: int,), some checks were not performed.
1678 if(mDeferredSingleDeclarationErrorCheck)
1680 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1682 mDeferredSingleDeclarationErrorCheck = false;
1685 if(locationDeclaratorListCheck(identifierLocation, publicType))
1688 TIntermNode *intermNode = nullptr;
1689 if(!executeInitializer(identifierLocation, identifier, publicType, initializer, intermNode))
1692 // build the intermediate representation
1696 return intermediate.growAggregate(aggregateDeclaration, intermNode, initLocation);
1700 return aggregateDeclaration;
1710 TIntermAggregate *TParseContext::parseArrayInitDeclarator(const TPublicType &publicType,
1711 TIntermAggregate *aggregateDeclaration,
1712 const TSourceLoc &identifierLocation,
1713 const TString &identifier,
1714 const TSourceLoc &indexLocation,
1715 TIntermTyped *indexExpression,
1716 const TSourceLoc &initLocation, TIntermTyped *initializer)
1718 // If the declaration starting this declarator list was empty (example: int,), some checks were not performed.
1719 if(mDeferredSingleDeclarationErrorCheck)
1721 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1723 mDeferredSingleDeclarationErrorCheck = false;
1726 if(locationDeclaratorListCheck(identifierLocation, publicType))
1729 if(arrayTypeErrorCheck(indexLocation, publicType) || arrayQualifierErrorCheck(indexLocation, publicType))
1734 TPublicType arrayType(publicType);
1737 // If indexExpression is nullptr, then the array will eventually get its size implicitly from the initializer.
1738 if(indexExpression != nullptr && arraySizeErrorCheck(identifierLocation, indexExpression, size))
1742 // Make the type an array even if size check failed.
1743 // This ensures useless error messages regarding the variable's non-arrayness won't follow.
1744 arrayType.setArray(true, size);
1746 // initNode will correspond to the whole of "b[n] = initializer".
1747 TIntermNode *initNode = nullptr;
1748 if(!executeInitializer(identifierLocation, identifier, arrayType, initializer, initNode))
1752 return intermediate.growAggregate(aggregateDeclaration, initNode, initLocation);
1756 return aggregateDeclaration;
1766 void TParseContext::parseGlobalLayoutQualifier(const TPublicType &typeQualifier)
1768 if(shaderVersion < 300)
1770 error(typeQualifier.line, "layout qualifiers supported in GLSL ES 3.00 only", "layout");
1775 if(typeQualifier.qualifier != EvqUniform)
1777 error(typeQualifier.line, "invalid qualifier:", getQualifierString(typeQualifier.qualifier), "global layout must be uniform");
1782 const TLayoutQualifier layoutQualifier = typeQualifier.layoutQualifier;
1783 ASSERT(!layoutQualifier.isEmpty());
1785 if(layoutLocationErrorCheck(typeQualifier.line, typeQualifier.layoutQualifier))
1791 if(layoutQualifier.matrixPacking != EmpUnspecified)
1793 defaultMatrixPacking = layoutQualifier.matrixPacking;
1796 if(layoutQualifier.blockStorage != EbsUnspecified)
1798 defaultBlockStorage = layoutQualifier.blockStorage;
1802 // This function is used to test for the correctness of the parameters passed to various constructor functions
1803 // and also convert them to the right datatype if it is allowed and required.
1805 // Returns 0 for an error or the constructed node (aggregate or typed) for no error.
1807 TIntermTyped* TParseContext::addConstructor(TIntermNode* arguments, const TType* type, TOperator op, TFunction* fnCall, const TSourceLoc &line)
1809 TIntermAggregate *aggregateArguments = arguments->getAsAggregate();
1811 if(!aggregateArguments)
1813 aggregateArguments = new TIntermAggregate;
1814 aggregateArguments->getSequence().push_back(arguments);
1817 if(op == EOpConstructStruct)
1819 const TFieldList &fields = type->getStruct()->fields();
1820 TIntermSequence &args = aggregateArguments->getSequence();
1822 for(size_t i = 0; i < fields.size(); i++)
1824 if(args[i]->getAsTyped()->getType() != *fields[i]->type())
1826 error(line, "Structure constructor arguments do not match structure fields", "Error");
1834 // Turn the argument list itself into a constructor
1835 TIntermTyped *constructor = intermediate.setAggregateOperator(aggregateArguments, op, line);
1836 TIntermTyped *constConstructor = foldConstConstructor(constructor->getAsAggregate(), *type);
1837 if(constConstructor)
1839 return constConstructor;
1845 TIntermTyped* TParseContext::foldConstConstructor(TIntermAggregate* aggrNode, const TType& type)
1847 bool canBeFolded = areAllChildConst(aggrNode);
1848 aggrNode->setType(type);
1850 bool returnVal = false;
1851 ConstantUnion* unionArray = new ConstantUnion[type.getObjectSize()];
1852 if (aggrNode->getSequence().size() == 1) {
1853 returnVal = intermediate.parseConstTree(aggrNode->getLine(), aggrNode, unionArray, aggrNode->getOp(), type, true);
1856 returnVal = intermediate.parseConstTree(aggrNode->getLine(), aggrNode, unionArray, aggrNode->getOp(), type);
1861 return intermediate.addConstantUnion(unionArray, type, aggrNode->getLine());
1868 // This function returns the tree representation for the vector field(s) being accessed from contant vector.
1869 // If only one component of vector is accessed (v.x or v[0] where v is a contant vector), then a contant node is
1870 // returned, else an aggregate node is returned (for v.xy). The input to this function could either be the symbol
1871 // node or it could be the intermediate tree representation of accessing fields in a constant structure or column of
1872 // a constant matrix.
1874 TIntermTyped* TParseContext::addConstVectorNode(TVectorFields& fields, TIntermTyped* node, const TSourceLoc &line)
1876 TIntermTyped* typedNode;
1877 TIntermConstantUnion* tempConstantNode = node->getAsConstantUnion();
1879 ConstantUnion *unionArray;
1880 if (tempConstantNode) {
1881 unionArray = tempConstantNode->getUnionArrayPointer();
1886 } else { // The node has to be either a symbol node or an aggregate node or a tempConstant node, else, its an error
1887 error(line, "Cannot offset into the vector", "Error");
1893 ConstantUnion* constArray = new ConstantUnion[fields.num];
1895 for (int i = 0; i < fields.num; i++) {
1896 if (fields.offsets[i] >= node->getType().getObjectSize()) {
1897 std::stringstream extraInfoStream;
1898 extraInfoStream << "vector field selection out of range '" << fields.offsets[i] << "'";
1899 std::string extraInfo = extraInfoStream.str();
1900 error(line, "", "[", extraInfo.c_str());
1902 fields.offsets[i] = 0;
1905 constArray[i] = unionArray[fields.offsets[i]];
1908 typedNode = intermediate.addConstantUnion(constArray, node->getType(), line);
1913 // This function returns the column being accessed from a constant matrix. The values are retrieved from
1914 // the symbol table and parse-tree is built for a vector (each column of a matrix is a vector). The input
1915 // to the function could either be a symbol node (m[0] where m is a constant matrix)that represents a
1916 // constant matrix or it could be the tree representation of the constant matrix (s.m1[0] where s is a constant structure)
1918 TIntermTyped* TParseContext::addConstMatrixNode(int index, TIntermTyped* node, const TSourceLoc &line)
1920 TIntermTyped* typedNode;
1921 TIntermConstantUnion* tempConstantNode = node->getAsConstantUnion();
1923 if (index >= node->getType().getNominalSize()) {
1924 std::stringstream extraInfoStream;
1925 extraInfoStream << "matrix field selection out of range '" << index << "'";
1926 std::string extraInfo = extraInfoStream.str();
1927 error(line, "", "[", extraInfo.c_str());
1932 if (tempConstantNode) {
1933 ConstantUnion* unionArray = tempConstantNode->getUnionArrayPointer();
1934 int size = tempConstantNode->getType().getNominalSize();
1935 typedNode = intermediate.addConstantUnion(&unionArray[size*index], tempConstantNode->getType(), line);
1937 error(line, "Cannot offset into the matrix", "Error");
1948 // This function returns an element of an array accessed from a constant array. The values are retrieved from
1949 // the symbol table and parse-tree is built for the type of the element. The input
1950 // to the function could either be a symbol node (a[0] where a is a constant array)that represents a
1951 // constant array or it could be the tree representation of the constant array (s.a1[0] where s is a constant structure)
1953 TIntermTyped* TParseContext::addConstArrayNode(int index, TIntermTyped* node, const TSourceLoc &line)
1955 TIntermTyped* typedNode;
1956 TIntermConstantUnion* tempConstantNode = node->getAsConstantUnion();
1957 TType arrayElementType = node->getType();
1958 arrayElementType.clearArrayness();
1960 if (index >= node->getType().getArraySize()) {
1961 std::stringstream extraInfoStream;
1962 extraInfoStream << "array field selection out of range '" << index << "'";
1963 std::string extraInfo = extraInfoStream.str();
1964 error(line, "", "[", extraInfo.c_str());
1969 int arrayElementSize = arrayElementType.getObjectSize();
1971 if (tempConstantNode) {
1972 ConstantUnion* unionArray = tempConstantNode->getUnionArrayPointer();
1973 typedNode = intermediate.addConstantUnion(&unionArray[arrayElementSize * index], tempConstantNode->getType(), line);
1975 error(line, "Cannot offset into the array", "Error");
1986 // This function returns the value of a particular field inside a constant structure from the symbol table.
1987 // If there is an embedded/nested struct, it appropriately calls addConstStructNested or addConstStructFromAggr
1988 // function and returns the parse-tree with the values of the embedded/nested struct.
1990 TIntermTyped* TParseContext::addConstStruct(const TString& identifier, TIntermTyped* node, const TSourceLoc &line)
1992 const TFieldList &fields = node->getType().getStruct()->fields();
1993 TIntermTyped *typedNode;
1994 int instanceSize = 0;
1995 unsigned int index = 0;
1996 TIntermConstantUnion *tempConstantNode = node->getAsConstantUnion();
1998 for ( index = 0; index < fields.size(); ++index) {
1999 if (fields[index]->name() == identifier) {
2002 instanceSize += fields[index]->type()->getObjectSize();
2006 if (tempConstantNode) {
2007 ConstantUnion* constArray = tempConstantNode->getUnionArrayPointer();
2009 typedNode = intermediate.addConstantUnion(constArray+instanceSize, tempConstantNode->getType(), line); // type will be changed in the calling function
2011 error(line, "Cannot offset into the structure", "Error");
2021 // Interface/uniform blocks
2023 TIntermAggregate* TParseContext::addInterfaceBlock(const TPublicType& typeQualifier, const TSourceLoc& nameLine, const TString& blockName, TFieldList* fieldList,
2024 const TString* instanceName, const TSourceLoc& instanceLine, TIntermTyped* arrayIndex, const TSourceLoc& arrayIndexLine)
2026 if(reservedErrorCheck(nameLine, blockName))
2029 if(typeQualifier.qualifier != EvqUniform)
2031 error(typeQualifier.line, "invalid qualifier:", getQualifierString(typeQualifier.qualifier), "interface blocks must be uniform");
2035 TLayoutQualifier blockLayoutQualifier = typeQualifier.layoutQualifier;
2036 if(layoutLocationErrorCheck(typeQualifier.line, blockLayoutQualifier))
2041 if(blockLayoutQualifier.matrixPacking == EmpUnspecified)
2043 blockLayoutQualifier.matrixPacking = defaultMatrixPacking;
2046 if(blockLayoutQualifier.blockStorage == EbsUnspecified)
2048 blockLayoutQualifier.blockStorage = defaultBlockStorage;
2051 TSymbol* blockNameSymbol = new TSymbol(&blockName);
2052 if(!symbolTable.declare(*blockNameSymbol)) {
2053 error(nameLine, "redefinition", blockName.c_str(), "interface block name");
2057 // check for sampler types and apply layout qualifiers
2058 for(size_t memberIndex = 0; memberIndex < fieldList->size(); ++memberIndex) {
2059 TField* field = (*fieldList)[memberIndex];
2060 TType* fieldType = field->type();
2061 if(IsSampler(fieldType->getBasicType())) {
2062 error(field->line(), "unsupported type", fieldType->getBasicString(), "sampler types are not allowed in interface blocks");
2066 const TQualifier qualifier = fieldType->getQualifier();
2073 error(field->line(), "invalid qualifier on interface block member", getQualifierString(qualifier));
2078 // check layout qualifiers
2079 TLayoutQualifier fieldLayoutQualifier = fieldType->getLayoutQualifier();
2080 if(layoutLocationErrorCheck(field->line(), fieldLayoutQualifier))
2085 if(fieldLayoutQualifier.blockStorage != EbsUnspecified)
2087 error(field->line(), "invalid layout qualifier:", getBlockStorageString(fieldLayoutQualifier.blockStorage), "cannot be used here");
2091 if(fieldLayoutQualifier.matrixPacking == EmpUnspecified)
2093 fieldLayoutQualifier.matrixPacking = blockLayoutQualifier.matrixPacking;
2095 else if(!fieldType->isMatrix())
2097 error(field->line(), "invalid layout qualifier:", getMatrixPackingString(fieldLayoutQualifier.matrixPacking), "can only be used on matrix types");
2101 fieldType->setLayoutQualifier(fieldLayoutQualifier);
2106 if(arrayIndex != NULL)
2108 if(arraySizeErrorCheck(arrayIndexLine, arrayIndex, arraySize))
2112 TInterfaceBlock* interfaceBlock = new TInterfaceBlock(&blockName, fieldList, instanceName, arraySize, blockLayoutQualifier);
2113 TType interfaceBlockType(interfaceBlock, typeQualifier.qualifier, blockLayoutQualifier, arraySize);
2115 TString symbolName = "";
2120 // define symbols for the members of the interface block
2121 for(size_t memberIndex = 0; memberIndex < fieldList->size(); ++memberIndex)
2123 TField* field = (*fieldList)[memberIndex];
2124 TType* fieldType = field->type();
2126 // set parent pointer of the field variable
2127 fieldType->setInterfaceBlock(interfaceBlock);
2129 TVariable* fieldVariable = new TVariable(&field->name(), *fieldType);
2130 fieldVariable->setQualifier(typeQualifier.qualifier);
2132 if(!symbolTable.declare(*fieldVariable)) {
2133 error(field->line(), "redefinition", field->name().c_str(), "interface block member name");
2140 // add a symbol for this interface block
2141 TVariable* instanceTypeDef = new TVariable(instanceName, interfaceBlockType, false);
2142 instanceTypeDef->setQualifier(typeQualifier.qualifier);
2144 if(!symbolTable.declare(*instanceTypeDef)) {
2145 error(instanceLine, "redefinition", instanceName->c_str(), "interface block instance name");
2149 symbolId = instanceTypeDef->getUniqueId();
2150 symbolName = instanceTypeDef->getName();
2153 TIntermAggregate *aggregate = intermediate.makeAggregate(intermediate.addSymbol(symbolId, symbolName, interfaceBlockType, typeQualifier.line), nameLine);
2154 aggregate->setOp(EOpDeclaration);
2156 exitStructDeclaration();
2161 // Parse an array index expression
2163 TIntermTyped *TParseContext::addIndexExpression(TIntermTyped *baseExpression, const TSourceLoc &location, TIntermTyped *indexExpression)
2165 TIntermTyped *indexedExpression = NULL;
2167 if(!baseExpression->isArray() && !baseExpression->isMatrix() && !baseExpression->isVector())
2169 if(baseExpression->getAsSymbolNode())
2171 error(location, " left of '[' is not of type array, matrix, or vector ",
2172 baseExpression->getAsSymbolNode()->getSymbol().c_str());
2176 error(location, " left of '[' is not of type array, matrix, or vector ", "expression");
2181 TIntermConstantUnion *indexConstantUnion = indexExpression->getAsConstantUnion();
2183 if(indexExpression->getQualifier() == EvqConstExpr && indexConstantUnion)
2185 int index = indexConstantUnion->getIConst(0);
2188 std::stringstream infoStream;
2189 infoStream << index;
2190 std::string info = infoStream.str();
2191 error(location, "negative index", info.c_str());
2195 if(baseExpression->getType().getQualifier() == EvqConstExpr)
2197 if(baseExpression->isArray())
2199 // constant folding for arrays
2200 indexedExpression = addConstArrayNode(index, baseExpression, location);
2202 else if(baseExpression->isVector())
2204 // constant folding for vectors
2205 TVectorFields fields;
2207 fields.offsets[0] = index; // need to do it this way because v.xy sends fields integer array
2208 indexedExpression = addConstVectorNode(fields, baseExpression, location);
2210 else if(baseExpression->isMatrix())
2212 // constant folding for matrices
2213 indexedExpression = addConstMatrixNode(index, baseExpression, location);
2220 if(baseExpression->isArray())
2222 if(index >= baseExpression->getType().getArraySize())
2224 std::stringstream extraInfoStream;
2225 extraInfoStream << "array index out of range '" << index << "'";
2226 std::string extraInfo = extraInfoStream.str();
2227 error(location, "", "[", extraInfo.c_str());
2229 safeIndex = baseExpression->getType().getArraySize() - 1;
2232 else if((baseExpression->isVector() || baseExpression->isMatrix()) &&
2233 baseExpression->getType().getNominalSize() <= index)
2235 std::stringstream extraInfoStream;
2236 extraInfoStream << "field selection out of range '" << index << "'";
2237 std::string extraInfo = extraInfoStream.str();
2238 error(location, "", "[", extraInfo.c_str());
2240 safeIndex = baseExpression->getType().getNominalSize() - 1;
2243 // Don't modify the data of the previous constant union, because it can point
2244 // to builtins, like gl_MaxDrawBuffers. Instead use a new sanitized object.
2247 ConstantUnion *safeConstantUnion = new ConstantUnion();
2248 safeConstantUnion->setIConst(safeIndex);
2249 indexConstantUnion->replaceConstantUnion(safeConstantUnion);
2252 indexedExpression = intermediate.addIndex(EOpIndexDirect, baseExpression, indexExpression, location);
2257 if(baseExpression->isInterfaceBlock())
2260 "[", "array indexes for interface blocks arrays must be constant integral expressions");
2263 else if(baseExpression->getQualifier() == EvqFragmentOut)
2265 error(location, "", "[", "array indexes for fragment outputs must be constant integral expressions");
2269 indexedExpression = intermediate.addIndex(EOpIndexIndirect, baseExpression, indexExpression, location);
2272 if(indexedExpression == 0)
2274 ConstantUnion *unionArray = new ConstantUnion[1];
2275 unionArray->setFConst(0.0f);
2276 indexedExpression = intermediate.addConstantUnion(unionArray, TType(EbtFloat, EbpHigh, EvqConstExpr), location);
2278 else if(baseExpression->isArray())
2280 const TType &baseType = baseExpression->getType();
2281 if(baseType.getStruct())
2283 TType copyOfType(baseType.getStruct());
2284 indexedExpression->setType(copyOfType);
2286 else if(baseType.isInterfaceBlock())
2288 TType copyOfType(baseType.getInterfaceBlock(), baseType.getQualifier(), baseType.getLayoutQualifier(), 0);
2289 indexedExpression->setType(copyOfType);
2293 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(),
2294 EvqTemporary, static_cast<unsigned char>(baseExpression->getNominalSize()),
2295 static_cast<unsigned char>(baseExpression->getSecondarySize())));
2298 if(baseExpression->getType().getQualifier() == EvqConstExpr)
2300 indexedExpression->getTypePointer()->setQualifier(EvqConstExpr);
2303 else if(baseExpression->isMatrix())
2305 TQualifier qualifier = baseExpression->getType().getQualifier() == EvqConstExpr ? EvqConstExpr : EvqTemporary;
2306 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(),
2307 qualifier, static_cast<unsigned char>(baseExpression->getSecondarySize())));
2309 else if(baseExpression->isVector())
2311 TQualifier qualifier = baseExpression->getType().getQualifier() == EvqConstExpr ? EvqConstExpr : EvqTemporary;
2312 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(), qualifier));
2316 indexedExpression->setType(baseExpression->getType());
2319 return indexedExpression;
2322 TIntermTyped *TParseContext::addFieldSelectionExpression(TIntermTyped *baseExpression, const TSourceLoc &dotLocation,
2323 const TString &fieldString, const TSourceLoc &fieldLocation)
2325 TIntermTyped *indexedExpression = NULL;
2327 if(baseExpression->isArray())
2329 error(fieldLocation, "cannot apply dot operator to an array", ".");
2333 if(baseExpression->isVector())
2335 TVectorFields fields;
2336 if(!parseVectorFields(fieldString, baseExpression->getNominalSize(), fields, fieldLocation))
2339 fields.offsets[0] = 0;
2343 if(baseExpression->getType().getQualifier() == EvqConstExpr)
2345 // constant folding for vector fields
2346 indexedExpression = addConstVectorNode(fields, baseExpression, fieldLocation);
2347 if(indexedExpression == 0)
2350 indexedExpression = baseExpression;
2354 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(),
2355 EvqConstExpr, (unsigned char)(fieldString).size()));
2360 TString vectorString = fieldString;
2361 TIntermTyped *index = intermediate.addSwizzle(fields, fieldLocation);
2362 indexedExpression = intermediate.addIndex(EOpVectorSwizzle, baseExpression, index, dotLocation);
2363 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(),
2364 EvqTemporary, (unsigned char)vectorString.size()));
2367 else if(baseExpression->isMatrix())
2369 TMatrixFields fields;
2370 if(!parseMatrixFields(fieldString, baseExpression->getNominalSize(), baseExpression->getSecondarySize(), fields, fieldLocation))
2372 fields.wholeRow = false;
2373 fields.wholeCol = false;
2379 if(fields.wholeRow || fields.wholeCol)
2381 error(dotLocation, " non-scalar fields not implemented yet", ".");
2383 ConstantUnion *unionArray = new ConstantUnion[1];
2384 unionArray->setIConst(0);
2385 TIntermTyped *index = intermediate.addConstantUnion(unionArray, TType(EbtInt, EbpUndefined, EvqConstExpr),
2387 indexedExpression = intermediate.addIndex(EOpIndexDirect, baseExpression, index, dotLocation);
2388 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(),
2389 EvqTemporary, static_cast<unsigned char>(baseExpression->getNominalSize()),
2390 static_cast<unsigned char>(baseExpression->getSecondarySize())));
2394 ConstantUnion *unionArray = new ConstantUnion[1];
2395 unionArray->setIConst(fields.col * baseExpression->getSecondarySize() + fields.row);
2396 TIntermTyped *index = intermediate.addConstantUnion(unionArray, TType(EbtInt, EbpUndefined, EvqConstExpr),
2398 indexedExpression = intermediate.addIndex(EOpIndexDirect, baseExpression, index, dotLocation);
2399 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision()));
2402 else if(baseExpression->getBasicType() == EbtStruct)
2404 bool fieldFound = false;
2405 const TFieldList &fields = baseExpression->getType().getStruct()->fields();
2408 error(dotLocation, "structure has no fields", "Internal Error");
2410 indexedExpression = baseExpression;
2415 for(i = 0; i < fields.size(); ++i)
2417 if(fields[i]->name() == fieldString)
2425 if(baseExpression->getType().getQualifier() == EvqConstExpr)
2427 indexedExpression = addConstStruct(fieldString, baseExpression, dotLocation);
2428 if(indexedExpression == 0)
2431 indexedExpression = baseExpression;
2435 indexedExpression->setType(*fields[i]->type());
2436 // change the qualifier of the return type, not of the structure field
2437 // as the structure definition is shared between various structures.
2438 indexedExpression->getTypePointer()->setQualifier(EvqConstExpr);
2443 ConstantUnion *unionArray = new ConstantUnion[1];
2444 unionArray->setIConst(i);
2445 TIntermTyped *index = intermediate.addConstantUnion(unionArray, *fields[i]->type(), fieldLocation);
2446 indexedExpression = intermediate.addIndex(EOpIndexDirectStruct, baseExpression, index, dotLocation);
2447 indexedExpression->setType(*fields[i]->type());
2452 error(dotLocation, " no such field in structure", fieldString.c_str());
2454 indexedExpression = baseExpression;
2458 else if(baseExpression->isInterfaceBlock())
2460 bool fieldFound = false;
2461 const TFieldList &fields = baseExpression->getType().getInterfaceBlock()->fields();
2464 error(dotLocation, "interface block has no fields", "Internal Error");
2466 indexedExpression = baseExpression;
2471 for(i = 0; i < fields.size(); ++i)
2473 if(fields[i]->name() == fieldString)
2481 ConstantUnion *unionArray = new ConstantUnion[1];
2482 unionArray->setIConst(i);
2483 TIntermTyped *index = intermediate.addConstantUnion(unionArray, *fields[i]->type(), fieldLocation);
2484 indexedExpression = intermediate.addIndex(EOpIndexDirectInterfaceBlock, baseExpression, index,
2486 indexedExpression->setType(*fields[i]->type());
2490 error(dotLocation, " no such field in interface block", fieldString.c_str());
2492 indexedExpression = baseExpression;
2498 if(shaderVersion < 300)
2500 error(dotLocation, " field selection requires structure, vector, or matrix on left hand side",
2501 fieldString.c_str());
2506 " field selection requires structure, vector, matrix, or interface block on left hand side",
2507 fieldString.c_str());
2510 indexedExpression = baseExpression;
2513 return indexedExpression;
2516 TLayoutQualifier TParseContext::parseLayoutQualifier(const TString &qualifierType, const TSourceLoc& qualifierTypeLine)
2518 TLayoutQualifier qualifier;
2520 qualifier.location = -1;
2521 qualifier.matrixPacking = EmpUnspecified;
2522 qualifier.blockStorage = EbsUnspecified;
2524 if(qualifierType == "shared")
2526 qualifier.blockStorage = EbsShared;
2528 else if(qualifierType == "packed")
2530 qualifier.blockStorage = EbsPacked;
2532 else if(qualifierType == "std140")
2534 qualifier.blockStorage = EbsStd140;
2536 else if(qualifierType == "row_major")
2538 qualifier.matrixPacking = EmpRowMajor;
2540 else if(qualifierType == "column_major")
2542 qualifier.matrixPacking = EmpColumnMajor;
2544 else if(qualifierType == "location")
2546 error(qualifierTypeLine, "invalid layout qualifier", qualifierType.c_str(), "location requires an argument");
2551 error(qualifierTypeLine, "invalid layout qualifier", qualifierType.c_str());
2558 TLayoutQualifier TParseContext::parseLayoutQualifier(const TString &qualifierType, const TSourceLoc& qualifierTypeLine, const TString &intValueString, int intValue, const TSourceLoc& intValueLine)
2560 TLayoutQualifier qualifier;
2562 qualifier.location = -1;
2563 qualifier.matrixPacking = EmpUnspecified;
2564 qualifier.blockStorage = EbsUnspecified;
2566 if (qualifierType != "location")
2568 error(qualifierTypeLine, "invalid layout qualifier", qualifierType.c_str(), "only location may have arguments");
2573 // must check that location is non-negative
2576 error(intValueLine, "out of range:", intValueString.c_str(), "location must be non-negative");
2581 qualifier.location = intValue;
2588 TLayoutQualifier TParseContext::joinLayoutQualifiers(TLayoutQualifier leftQualifier, TLayoutQualifier rightQualifier)
2590 TLayoutQualifier joinedQualifier = leftQualifier;
2592 if (rightQualifier.location != -1)
2594 joinedQualifier.location = rightQualifier.location;
2596 if(rightQualifier.matrixPacking != EmpUnspecified)
2598 joinedQualifier.matrixPacking = rightQualifier.matrixPacking;
2600 if(rightQualifier.blockStorage != EbsUnspecified)
2602 joinedQualifier.blockStorage = rightQualifier.blockStorage;
2605 return joinedQualifier;
2609 TPublicType TParseContext::joinInterpolationQualifiers(const TSourceLoc &interpolationLoc, TQualifier interpolationQualifier,
2610 const TSourceLoc &storageLoc, TQualifier storageQualifier)
2612 TQualifier mergedQualifier = EvqSmoothIn;
2614 if(storageQualifier == EvqFragmentIn) {
2615 if(interpolationQualifier == EvqSmooth)
2616 mergedQualifier = EvqSmoothIn;
2617 else if(interpolationQualifier == EvqFlat)
2618 mergedQualifier = EvqFlatIn;
2621 else if(storageQualifier == EvqCentroidIn) {
2622 if(interpolationQualifier == EvqSmooth)
2623 mergedQualifier = EvqCentroidIn;
2624 else if(interpolationQualifier == EvqFlat)
2625 mergedQualifier = EvqFlatIn;
2628 else if(storageQualifier == EvqVertexOut) {
2629 if(interpolationQualifier == EvqSmooth)
2630 mergedQualifier = EvqSmoothOut;
2631 else if(interpolationQualifier == EvqFlat)
2632 mergedQualifier = EvqFlatOut;
2635 else if(storageQualifier == EvqCentroidOut) {
2636 if(interpolationQualifier == EvqSmooth)
2637 mergedQualifier = EvqCentroidOut;
2638 else if(interpolationQualifier == EvqFlat)
2639 mergedQualifier = EvqFlatOut;
2643 error(interpolationLoc, "interpolation qualifier requires a fragment 'in' or vertex 'out' storage qualifier", getQualifierString(interpolationQualifier));
2646 mergedQualifier = storageQualifier;
2650 type.setBasic(EbtVoid, mergedQualifier, storageLoc);
2654 TFieldList *TParseContext::addStructDeclaratorList(const TPublicType &typeSpecifier, TFieldList *fieldList)
2656 if(voidErrorCheck(typeSpecifier.line, (*fieldList)[0]->name(), typeSpecifier.type))
2661 for(unsigned int i = 0; i < fieldList->size(); ++i)
2664 // Careful not to replace already known aspects of type, like array-ness
2666 TType *type = (*fieldList)[i]->type();
2667 type->setBasicType(typeSpecifier.type);
2668 type->setNominalSize(typeSpecifier.primarySize);
2669 type->setSecondarySize(typeSpecifier.secondarySize);
2670 type->setPrecision(typeSpecifier.precision);
2671 type->setQualifier(typeSpecifier.qualifier);
2672 type->setLayoutQualifier(typeSpecifier.layoutQualifier);
2674 // don't allow arrays of arrays
2677 if(arrayTypeErrorCheck(typeSpecifier.line, typeSpecifier))
2680 if(typeSpecifier.array)
2681 type->setArraySize(typeSpecifier.arraySize);
2682 if(typeSpecifier.userDef)
2684 type->setStruct(typeSpecifier.userDef->getStruct());
2687 if(structNestingErrorCheck(typeSpecifier.line, *(*fieldList)[i]))
2696 TPublicType TParseContext::addStructure(const TSourceLoc &structLine, const TSourceLoc &nameLine,
2697 const TString *structName, TFieldList *fieldList)
2699 TStructure *structure = new TStructure(structName, fieldList);
2700 TType *structureType = new TType(structure);
2702 // Store a bool in the struct if we're at global scope, to allow us to
2703 // skip the local struct scoping workaround in HLSL.
2704 structure->setUniqueId(TSymbolTableLevel::nextUniqueId());
2705 structure->setAtGlobalScope(symbolTable.atGlobalLevel());
2707 if(!structName->empty())
2709 if(reservedErrorCheck(nameLine, *structName))
2713 TVariable *userTypeDef = new TVariable(structName, *structureType, true);
2714 if(!symbolTable.declare(*userTypeDef))
2716 error(nameLine, "redefinition", structName->c_str(), "struct");
2721 // ensure we do not specify any storage qualifiers on the struct members
2722 for(unsigned int typeListIndex = 0; typeListIndex < fieldList->size(); typeListIndex++)
2724 const TField &field = *(*fieldList)[typeListIndex];
2725 const TQualifier qualifier = field.type()->getQualifier();
2732 error(field.line(), "invalid qualifier on struct member", getQualifierString(qualifier));
2738 TPublicType publicType;
2739 publicType.setBasic(EbtStruct, EvqTemporary, structLine);
2740 publicType.userDef = structureType;
2741 exitStructDeclaration();
2746 bool TParseContext::enterStructDeclaration(const TSourceLoc &line, const TString& identifier)
2748 ++structNestingLevel;
2750 // Embedded structure definitions are not supported per GLSL ES spec.
2751 // They aren't allowed in GLSL either, but we need to detect this here
2752 // so we don't rely on the GLSL compiler to catch it.
2753 if (structNestingLevel > 1) {
2754 error(line, "", "Embedded struct definitions are not allowed");
2761 void TParseContext::exitStructDeclaration()
2763 --structNestingLevel;
2766 bool TParseContext::structNestingErrorCheck(const TSourceLoc &line, const TField &field)
2768 static const int kWebGLMaxStructNesting = 4;
2770 if(field.type()->getBasicType() != EbtStruct)
2775 // We're already inside a structure definition at this point, so add
2776 // one to the field's struct nesting.
2777 if(1 + field.type()->getDeepestStructNesting() > kWebGLMaxStructNesting)
2779 std::stringstream reasonStream;
2780 reasonStream << "Reference of struct type "
2781 << field.type()->getStruct()->name().c_str()
2782 << " exceeds maximum allowed nesting level of "
2783 << kWebGLMaxStructNesting;
2784 std::string reason = reasonStream.str();
2785 error(line, reason.c_str(), field.name().c_str(), "");
2792 TIntermTyped *TParseContext::createUnaryMath(TOperator op, TIntermTyped *child, const TSourceLoc &loc, const TType *funcReturnType)
2794 if(child == nullptr)
2802 if(child->getBasicType() != EbtBool ||
2803 child->isMatrix() ||
2811 if((child->getBasicType() != EbtInt && child->getBasicType() != EbtUInt) ||
2812 child->isMatrix() ||
2818 case EOpPostIncrement:
2819 case EOpPreIncrement:
2820 case EOpPostDecrement:
2821 case EOpPreDecrement:
2823 if(child->getBasicType() == EbtStruct ||
2824 child->getBasicType() == EbtBool ||
2829 // Operators for built-ins are already type checked against their prototype.
2834 return intermediate.addUnaryMath(op, child, loc); // FIXME , funcReturnType);
2837 TIntermTyped *TParseContext::addUnaryMath(TOperator op, TIntermTyped *child, const TSourceLoc &loc)
2839 TIntermTyped *node = createUnaryMath(op, child, loc, nullptr);
2842 unaryOpError(loc, getOperatorString(op), child->getCompleteString());
2849 TIntermTyped *TParseContext::addUnaryMathLValue(TOperator op, TIntermTyped *child, const TSourceLoc &loc)
2851 if(lValueErrorCheck(loc, getOperatorString(op), child))
2853 return addUnaryMath(op, child, loc);
2856 bool TParseContext::binaryOpCommonCheck(TOperator op, TIntermTyped *left, TIntermTyped *right, const TSourceLoc &loc)
2858 if(left->isArray() || right->isArray())
2860 if(shaderVersion < 300)
2862 error(loc, "Invalid operation for arrays", getOperatorString(op));
2866 if(left->isArray() != right->isArray())
2868 error(loc, "array / non-array mismatch", getOperatorString(op));
2880 error(loc, "Invalid operation for arrays", getOperatorString(op));
2883 // At this point, size of implicitly sized arrays should be resolved.
2884 if(left->getArraySize() != right->getArraySize())
2886 error(loc, "array size mismatch", getOperatorString(op));
2891 // Check ops which require integer / ivec parameters
2892 bool isBitShift = false;
2895 case EOpBitShiftLeft:
2896 case EOpBitShiftRight:
2897 case EOpBitShiftLeftAssign:
2898 case EOpBitShiftRightAssign:
2899 // Unsigned can be bit-shifted by signed and vice versa, but we need to
2900 // check that the basic type is an integer type.
2902 if(!IsInteger(left->getBasicType()) || !IsInteger(right->getBasicType()))
2910 case EOpBitwiseAndAssign:
2911 case EOpBitwiseXorAssign:
2912 case EOpBitwiseOrAssign:
2913 // It is enough to check the type of only one operand, since later it
2914 // is checked that the operand types match.
2915 if(!IsInteger(left->getBasicType()))
2924 // GLSL ES 1.00 and 3.00 do not support implicit type casting.
2925 // So the basic type should usually match.
2926 if(!isBitShift && left->getBasicType() != right->getBasicType())
2931 // Check that type sizes match exactly on ops that require that.
2932 // Also check restrictions for structs that contain arrays or samplers.
2939 // ESSL 1.00 sections 5.7, 5.8, 5.9
2940 if(shaderVersion < 300 && left->getType().isStructureContainingArrays())
2942 error(loc, "undefined operation for structs containing arrays", getOperatorString(op));
2945 // Samplers as l-values are disallowed also in ESSL 3.00, see section 4.1.7,
2946 // we interpret the spec so that this extends to structs containing samplers,
2947 // similarly to ESSL 1.00 spec.
2948 if((shaderVersion < 300 || op == EOpAssign || op == EOpInitialize) &&
2949 left->getType().isStructureContainingSamplers())
2951 error(loc, "undefined operation for structs containing samplers", getOperatorString(op));
2955 case EOpGreaterThan:
2956 case EOpLessThanEqual:
2957 case EOpGreaterThanEqual:
2958 if((left->getNominalSize() != right->getNominalSize()) ||
2959 (left->getSecondarySize() != right->getSecondarySize()))
2970 TIntermSwitch *TParseContext::addSwitch(TIntermTyped *init, TIntermAggregate *statementList, const TSourceLoc &loc)
2972 TBasicType switchType = init->getBasicType();
2973 if((switchType != EbtInt && switchType != EbtUInt) ||
2978 error(init->getLine(), "init-expression in a switch statement must be a scalar integer", "switch");
2985 if(!ValidateSwitch::validate(switchType, this, statementList, loc))
2992 TIntermSwitch *node = intermediate.addSwitch(init, statementList, loc);
2995 error(loc, "erroneous switch statement", "switch");
3002 TIntermCase *TParseContext::addCase(TIntermTyped *condition, const TSourceLoc &loc)
3004 if(switchNestingLevel == 0)
3006 error(loc, "case labels need to be inside switch statements", "case");
3010 if(condition == nullptr)
3012 error(loc, "case label must have a condition", "case");
3016 if((condition->getBasicType() != EbtInt && condition->getBasicType() != EbtUInt) ||
3017 condition->isMatrix() ||
3018 condition->isArray() ||
3019 condition->isVector())
3021 error(condition->getLine(), "case label must be a scalar integer", "case");
3024 TIntermConstantUnion *conditionConst = condition->getAsConstantUnion();
3025 if(conditionConst == nullptr)
3027 error(condition->getLine(), "case label must be constant", "case");
3030 TIntermCase *node = intermediate.addCase(condition, loc);
3033 error(loc, "erroneous case statement", "case");
3040 TIntermCase *TParseContext::addDefault(const TSourceLoc &loc)
3042 if(switchNestingLevel == 0)
3044 error(loc, "default labels need to be inside switch statements", "default");
3048 TIntermCase *node = intermediate.addCase(nullptr, loc);
3051 error(loc, "erroneous default statement", "default");
3058 TIntermBranch *TParseContext::addBranch(TOperator op, const TSourceLoc &loc)
3063 if(loopNestingLevel <= 0)
3065 error(loc, "continue statement only allowed in loops", "");
3070 if(loopNestingLevel <= 0 && switchNestingLevel <= 0)
3072 error(loc, "break statement only allowed in loops and switch statements", "");
3077 if(currentFunctionType->getBasicType() != EbtVoid)
3079 error(loc, "non-void function must return a value", "return");
3084 // No checks for discard
3087 return intermediate.addBranch(op, loc);
3090 TIntermBranch *TParseContext::addBranch(TOperator op, TIntermTyped *returnValue, const TSourceLoc &loc)
3092 ASSERT(op == EOpReturn);
3093 functionReturnsValue = true;
3094 if(currentFunctionType->getBasicType() == EbtVoid)
3096 error(loc, "void function cannot return a value", "return");
3099 else if(*currentFunctionType != returnValue->getType())
3101 error(loc, "function return is not matching type:", "return");
3104 return intermediate.addBranch(op, returnValue, loc);
3108 // Parse an array of strings using yyparse.
3110 // Returns 0 for success.
3112 int PaParseStrings(int count, const char* const string[], const int length[],
3113 TParseContext* context) {
3114 if ((count == 0) || (string == NULL))
3117 if (glslang_initialize(context))
3120 int error = glslang_scan(count, string, length, context);
3122 error = glslang_parse(context);
3124 glslang_finalize(context);
3126 return (error == 0) && (context->numErrors() == 0) ? 0 : 1;