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(loc.first_file, loc.first_line);
184 mDiagnostics.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(loc.first_file, loc.first_line);
193 mDiagnostics.writeInfo(pp::Diagnostics::PP_WARNING,
194 srcLoc, reason, token, extraInfo);
197 void TParseContext::trace(const char* str)
199 mDiagnostics.writeDebug(str);
203 // Same error message for all places assignments don't work.
205 void TParseContext::assignError(const TSourceLoc &line, const char* op, TString left, TString right)
207 std::stringstream extraInfoStream;
208 extraInfoStream << "cannot convert from '" << right << "' to '" << left << "'";
209 std::string extraInfo = extraInfoStream.str();
210 error(line, "", op, extraInfo.c_str());
214 // Same error message for all places unary operations don't work.
216 void TParseContext::unaryOpError(const TSourceLoc &line, const char* op, TString operand)
218 std::stringstream extraInfoStream;
219 extraInfoStream << "no operation '" << op << "' exists that takes an operand of type " << operand
220 << " (or there is no acceptable conversion)";
221 std::string extraInfo = extraInfoStream.str();
222 error(line, " wrong operand type", op, extraInfo.c_str());
226 // Same error message for all binary operations don't work.
228 void TParseContext::binaryOpError(const TSourceLoc &line, const char* op, TString left, TString right)
230 std::stringstream extraInfoStream;
231 extraInfoStream << "no operation '" << op << "' exists that takes a left-hand operand of type '" << left
232 << "' and a right operand of type '" << right << "' (or there is no acceptable conversion)";
233 std::string extraInfo = extraInfoStream.str();
234 error(line, " wrong operand types ", op, extraInfo.c_str());
237 bool TParseContext::precisionErrorCheck(const TSourceLoc &line, TPrecision precision, TBasicType type){
238 if (!mChecksPrecisionErrors)
242 if( precision == EbpUndefined ){
243 error( line, "No precision specified for (float)", "" );
248 if( precision == EbpUndefined ){
249 error( line, "No precision specified (int)", "" );
260 // Both test and if necessary, spit out an error, to see if the node is really
261 // an l-value that can be operated on this way.
263 // Returns true if the was an error.
265 bool TParseContext::lValueErrorCheck(const TSourceLoc &line, const char* op, TIntermTyped* node)
267 TIntermSymbol* symNode = node->getAsSymbolNode();
268 TIntermBinary* binaryNode = node->getAsBinaryNode();
273 switch(binaryNode->getOp()) {
275 case EOpIndexIndirect:
276 case EOpIndexDirectStruct:
277 return lValueErrorCheck(line, op, binaryNode->getLeft());
278 case EOpVectorSwizzle:
279 errorReturn = lValueErrorCheck(line, op, binaryNode->getLeft());
281 int offset[4] = {0,0,0,0};
283 TIntermTyped* rightNode = binaryNode->getRight();
284 TIntermAggregate *aggrNode = rightNode->getAsAggregate();
286 for (TIntermSequence::iterator p = aggrNode->getSequence().begin();
287 p != aggrNode->getSequence().end(); p++) {
288 int value = (*p)->getAsTyped()->getAsConstantUnion()->getIConst(0);
290 if (offset[value] > 1) {
291 error(line, " l-value of swizzle cannot have duplicate components", op);
302 error(line, " l-value required", op);
308 const char* symbol = 0;
310 symbol = symNode->getSymbol().c_str();
312 const char* message = 0;
313 switch (node->getQualifier()) {
314 case EvqConstExpr: message = "can't modify a const"; break;
315 case EvqConstReadOnly: message = "can't modify a const"; break;
316 case EvqAttribute: message = "can't modify an attribute"; break;
317 case EvqFragmentIn: message = "can't modify an input"; break;
318 case EvqVertexIn: message = "can't modify an input"; break;
319 case EvqUniform: message = "can't modify a uniform"; break;
323 case EvqVaryingIn: message = "can't modify a varying"; break;
324 case EvqInput: message = "can't modify an input"; break;
325 case EvqFragCoord: message = "can't modify gl_FragCoord"; break;
326 case EvqFrontFacing: message = "can't modify gl_FrontFacing"; break;
327 case EvqPointCoord: message = "can't modify gl_PointCoord"; break;
328 case EvqInstanceID: message = "can't modify gl_InstanceID"; break;
332 // Type that can't be written to?
334 if(IsSampler(node->getBasicType()))
336 message = "can't modify a sampler";
338 else if(node->getBasicType() == EbtVoid)
340 message = "can't modify void";
344 if (message == 0 && binaryNode == 0 && symNode == 0) {
345 error(line, " l-value required", op);
352 // Everything else is okay, no error.
358 // If we get here, we have an error and a message.
361 std::stringstream extraInfoStream;
362 extraInfoStream << "\"" << symbol << "\" (" << message << ")";
363 std::string extraInfo = extraInfoStream.str();
364 error(line, " l-value required", op, extraInfo.c_str());
367 std::stringstream extraInfoStream;
368 extraInfoStream << "(" << message << ")";
369 std::string extraInfo = extraInfoStream.str();
370 error(line, " l-value required", op, extraInfo.c_str());
377 // Both test, and if necessary spit out an error, to see if the node is really
380 // Returns true if the was an error.
382 bool TParseContext::constErrorCheck(TIntermTyped* node)
384 if (node->getQualifier() == EvqConstExpr)
387 error(node->getLine(), "constant expression required", "");
393 // Both test, and if necessary spit out an error, to see if the node is really
396 // Returns true if the was an error.
398 bool TParseContext::integerErrorCheck(TIntermTyped* node, const char* token)
400 if (node->isScalarInt())
403 error(node->getLine(), "integer expression required", token);
409 // Both test, and if necessary spit out an error, to see if we are currently
412 // Returns true if the was an error.
414 bool TParseContext::globalErrorCheck(const TSourceLoc &line, bool global, const char* token)
419 error(line, "only allowed at global scope", token);
425 // For now, keep it simple: if it starts "gl_", it's reserved, independent
426 // of scope. Except, if the symbol table is at the built-in push-level,
427 // which is when we are parsing built-ins.
428 // Also checks for "webgl_" and "_webgl_" reserved identifiers if parsing a
431 // Returns true if there was an error.
433 bool TParseContext::reservedErrorCheck(const TSourceLoc &line, const TString& identifier)
435 static const char* reservedErrMsg = "reserved built-in name";
436 if (!symbolTable.atBuiltInLevel()) {
437 if (identifier.compare(0, 3, "gl_") == 0) {
438 error(line, reservedErrMsg, "gl_");
441 if (identifier.find("__") != TString::npos) {
442 error(line, "identifiers containing two consecutive underscores (__) are reserved as possible future keywords", identifier.c_str());
451 // Make sure there is enough data provided to the constructor to build
452 // something of the type of the constructor. Also returns the type of
455 // Returns true if there was an error in construction.
457 bool TParseContext::constructorErrorCheck(const TSourceLoc &line, TIntermNode* node, TFunction& function, TOperator op, TType* type)
459 *type = function.getReturnType();
461 bool constructingMatrix = false;
463 case EOpConstructMat2:
464 case EOpConstructMat2x3:
465 case EOpConstructMat2x4:
466 case EOpConstructMat3x2:
467 case EOpConstructMat3:
468 case EOpConstructMat3x4:
469 case EOpConstructMat4x2:
470 case EOpConstructMat4x3:
471 case EOpConstructMat4:
472 constructingMatrix = true;
479 // Note: It's okay to have too many components available, but not okay to have unused
480 // arguments. 'full' will go to true when enough args have been seen. If we loop
481 // again, there is an extra argument, so 'overfull' will become true.
486 bool overFull = false;
487 bool matrixInMatrix = false;
488 bool arrayArg = false;
489 for (size_t i = 0; i < function.getParamCount(); ++i) {
490 const TParameter& param = function.getParam(i);
491 size += param.type->getObjectSize();
493 if (constructingMatrix && param.type->isMatrix())
494 matrixInMatrix = true;
497 if (op != EOpConstructStruct && !type->isArray() && size >= type->getObjectSize())
499 if (param.type->isArray())
503 if(type->isArray()) {
504 if(type->getArraySize() == 0) {
505 type->setArraySize(function.getParamCount());
506 } else if(type->getArraySize() != (int)function.getParamCount()) {
507 error(line, "array constructor needs one argument per array element", "constructor");
512 if (arrayArg && op != EOpConstructStruct) {
513 error(line, "constructing from a non-dereferenced array", "constructor");
517 if (matrixInMatrix && !type->isArray()) {
518 if (function.getParamCount() != 1) {
519 error(line, "constructing matrix from matrix can only take one argument", "constructor");
525 error(line, "too many arguments", "constructor");
529 if (op == EOpConstructStruct && !type->isArray() && type->getStruct()->fields().size() != function.getParamCount()) {
530 error(line, "Number of constructor parameters does not match the number of structure fields", "constructor");
534 if (!type->isMatrix() || !matrixInMatrix) {
535 if ((op != EOpConstructStruct && size != 1 && size < type->getObjectSize()) ||
536 (op == EOpConstructStruct && size < type->getObjectSize())) {
537 error(line, "not enough data provided for construction", "constructor");
542 TIntermTyped *typed = node ? node->getAsTyped() : 0;
544 error(line, "constructor argument does not have a type", "constructor");
547 if (op != EOpConstructStruct && IsSampler(typed->getBasicType())) {
548 error(line, "cannot convert a sampler", "constructor");
551 if (typed->getBasicType() == EbtVoid) {
552 error(line, "cannot convert a void", "constructor");
559 // This function checks to see if a void variable has been declared and raise an error message for such a case
561 // returns true in case of an error
563 bool TParseContext::voidErrorCheck(const TSourceLoc &line, const TString& identifier, const TBasicType& type)
565 if(type == EbtVoid) {
566 error(line, "illegal use of type 'void'", identifier.c_str());
573 // This function checks to see if the node (for the expression) contains a scalar boolean expression or not
575 // returns true in case of an error
577 bool TParseContext::boolErrorCheck(const TSourceLoc &line, const TIntermTyped* type)
579 if (type->getBasicType() != EbtBool || type->isArray() || type->isMatrix() || type->isVector()) {
580 error(line, "boolean expression expected", "");
587 // This function checks to see if the node (for the expression) contains a scalar boolean expression or not
589 // returns true in case of an error
591 bool TParseContext::boolErrorCheck(const TSourceLoc &line, const TPublicType& pType)
593 if (pType.type != EbtBool || pType.array || (pType.primarySize > 1) || (pType.secondarySize > 1)) {
594 error(line, "boolean expression expected", "");
601 bool TParseContext::samplerErrorCheck(const TSourceLoc &line, const TPublicType& pType, const char* reason)
603 if (pType.type == EbtStruct) {
604 if (containsSampler(*pType.userDef)) {
605 error(line, reason, getBasicString(pType.type), "(structure contains a sampler)");
611 } else if (IsSampler(pType.type)) {
612 error(line, reason, getBasicString(pType.type));
620 bool TParseContext::structQualifierErrorCheck(const TSourceLoc &line, const TPublicType& pType)
622 switch(pType.qualifier)
635 if(pType.type == EbtStruct)
637 error(line, "cannot be used with a structure", getQualifierString(pType.qualifier));
646 if (pType.qualifier != EvqUniform && samplerErrorCheck(line, pType, "samplers must be uniform"))
649 // check for layout qualifier issues
650 const TLayoutQualifier layoutQualifier = pType.layoutQualifier;
652 if (pType.qualifier != EvqVertexIn && pType.qualifier != EvqFragmentOut &&
653 layoutLocationErrorCheck(line, pType.layoutQualifier))
661 // These checks are common for all declarations starting a declarator list, and declarators that follow an empty
664 bool TParseContext::singleDeclarationErrorCheck(const TPublicType &publicType, const TSourceLoc &identifierLocation)
666 switch(publicType.qualifier)
673 if(publicType.type == EbtStruct)
675 error(identifierLocation, "cannot be used with a structure",
676 getQualifierString(publicType.qualifier));
683 if(publicType.qualifier != EvqUniform && samplerErrorCheck(identifierLocation, publicType,
684 "samplers must be uniform"))
689 // check for layout qualifier issues
690 const TLayoutQualifier layoutQualifier = publicType.layoutQualifier;
692 if(layoutQualifier.matrixPacking != EmpUnspecified)
694 error(identifierLocation, "layout qualifier", getMatrixPackingString(layoutQualifier.matrixPacking),
695 "only valid for interface blocks");
699 if(layoutQualifier.blockStorage != EbsUnspecified)
701 error(identifierLocation, "layout qualifier", getBlockStorageString(layoutQualifier.blockStorage),
702 "only valid for interface blocks");
706 if(publicType.qualifier != EvqVertexIn && publicType.qualifier != EvqFragmentOut &&
707 layoutLocationErrorCheck(identifierLocation, publicType.layoutQualifier))
715 bool TParseContext::layoutLocationErrorCheck(const TSourceLoc &location, const TLayoutQualifier &layoutQualifier)
717 if(layoutQualifier.location != -1)
719 error(location, "invalid layout qualifier:", "location", "only valid on program inputs and outputs");
726 bool TParseContext::locationDeclaratorListCheck(const TSourceLoc& line, const TPublicType &pType)
728 if(pType.layoutQualifier.location != -1)
730 error(line, "location must only be specified for a single input or output variable", "location");
737 bool TParseContext::parameterSamplerErrorCheck(const TSourceLoc &line, TQualifier qualifier, const TType& type)
739 if ((qualifier == EvqOut || qualifier == EvqInOut) &&
740 type.getBasicType() != EbtStruct && IsSampler(type.getBasicType())) {
741 error(line, "samplers cannot be output parameters", type.getBasicString());
748 bool TParseContext::containsSampler(TType& type)
750 if (IsSampler(type.getBasicType()))
753 if (type.getBasicType() == EbtStruct) {
754 const TFieldList& fields = type.getStruct()->fields();
755 for(unsigned int i = 0; i < fields.size(); ++i) {
756 if (containsSampler(*fields[i]->type()))
765 // Do size checking for an array type's size.
767 // Returns true if there was an error.
769 bool TParseContext::arraySizeErrorCheck(const TSourceLoc &line, TIntermTyped* expr, int& size)
771 TIntermConstantUnion* constant = expr->getAsConstantUnion();
773 if (constant == 0 || !constant->isScalarInt())
775 error(line, "array size must be a constant integer expression", "");
779 if (constant->getBasicType() == EbtUInt)
781 unsigned int uintSize = constant->getUConst(0);
782 if (uintSize > static_cast<unsigned int>(std::numeric_limits<int>::max()))
784 error(line, "array size too large", "");
789 size = static_cast<int>(uintSize);
793 size = constant->getIConst(0);
797 error(line, "array size must be a positive integer", "");
807 // See if this qualifier can be an array.
809 // Returns true if there is an error.
811 bool TParseContext::arrayQualifierErrorCheck(const TSourceLoc &line, TPublicType type)
813 if ((type.qualifier == EvqAttribute) || (type.qualifier == EvqVertexIn) || (type.qualifier == EvqConstExpr)) {
814 error(line, "cannot declare arrays of this qualifier", TType(type).getCompleteString().c_str());
822 // See if this type can be an array.
824 // Returns true if there is an error.
826 bool TParseContext::arrayTypeErrorCheck(const TSourceLoc &line, TPublicType type)
829 // Can the type be an array?
832 error(line, "cannot declare arrays of arrays", TType(type).getCompleteString().c_str());
839 bool TParseContext::arraySetMaxSize(TIntermSymbol *node, TType* type, int size, bool updateFlag, const TSourceLoc &line)
841 bool builtIn = false;
842 TSymbol* symbol = symbolTable.find(node->getSymbol(), mShaderVersion, &builtIn);
844 error(line, " undeclared identifier", node->getSymbol().c_str());
847 TVariable* variable = static_cast<TVariable*>(symbol);
849 type->setArrayInformationType(variable->getArrayInformationType());
850 variable->updateArrayInformationType(type);
852 // special casing to test index value of gl_FragData. If the accessed index is >= gl_MaxDrawBuffers
854 if (node->getSymbol() == "gl_FragData") {
855 TSymbol* fragData = symbolTable.find("gl_MaxDrawBuffers", mShaderVersion, &builtIn);
858 int fragDataValue = static_cast<TVariable*>(fragData)->getConstPointer()[0].getIConst();
859 if (fragDataValue <= size) {
860 error(line, "", "[", "gl_FragData can only have a max array size of up to gl_MaxDrawBuffers");
865 // we dont want to update the maxArraySize when this flag is not set, we just want to include this
866 // node type in the chain of node types so that its updated when a higher maxArraySize comes in.
871 variable->getType().setMaxArraySize(size);
872 type->setMaxArraySize(size);
875 while(tt->getArrayInformationType() != 0) {
876 tt = tt->getArrayInformationType();
877 tt->setMaxArraySize(size);
884 // Enforce non-initializer type/qualifier rules.
886 // Returns true if there was an error.
888 bool TParseContext::nonInitConstErrorCheck(const TSourceLoc &line, TString& identifier, TPublicType& type, bool array)
890 if (type.qualifier == EvqConstExpr)
892 // Make the qualifier make sense.
893 type.qualifier = EvqTemporary;
897 error(line, "arrays may not be declared constant since they cannot be initialized", identifier.c_str());
899 else if (type.isStructureContainingArrays())
901 error(line, "structures containing arrays may not be declared constant since they cannot be initialized", identifier.c_str());
905 error(line, "variables with qualifier 'const' must be initialized", identifier.c_str());
915 // Do semantic checking for a variable declaration that has no initializer,
916 // and update the symbol table.
918 // Returns true if there was an error.
920 bool TParseContext::nonInitErrorCheck(const TSourceLoc &line, const TString& identifier, TPublicType& type)
922 if(type.qualifier == EvqConstExpr)
924 // Make the qualifier make sense.
925 type.qualifier = EvqTemporary;
927 // Generate informative error messages for ESSL1.
928 // In ESSL3 arrays and structures containing arrays can be constant.
929 if(mShaderVersion < 300 && type.isStructureContainingArrays())
932 "structures containing arrays may not be declared constant since they cannot be initialized",
937 error(line, "variables with qualifier 'const' must be initialized", identifier.c_str());
942 if(type.isUnsizedArray())
944 error(line, "implicitly sized arrays need to be initialized", identifier.c_str());
950 // Do some simple checks that are shared between all variable declarations,
951 // and update the symbol table.
953 // Returns true if declaring the variable succeeded.
955 bool TParseContext::declareVariable(const TSourceLoc &line, const TString &identifier, const TType &type,
956 TVariable **variable)
958 ASSERT((*variable) == nullptr);
960 // gl_LastFragData may be redeclared with a new precision qualifier
961 if(type.isArray() && identifier.compare(0, 15, "gl_LastFragData") == 0)
963 const TVariable *maxDrawBuffers =
964 static_cast<const TVariable *>(symbolTable.findBuiltIn("gl_MaxDrawBuffers", mShaderVersion));
965 if(type.getArraySize() != maxDrawBuffers->getConstPointer()->getIConst())
967 error(line, "redeclaration of gl_LastFragData with size != gl_MaxDrawBuffers", identifier.c_str());
972 if(reservedErrorCheck(line, identifier))
975 (*variable) = new TVariable(&identifier, type);
976 if(!symbolTable.declare(**variable))
978 error(line, "redefinition", identifier.c_str());
980 (*variable) = nullptr;
984 if(voidErrorCheck(line, identifier, type.getBasicType()))
990 bool TParseContext::paramErrorCheck(const TSourceLoc &line, TQualifier qualifier, TQualifier paramQualifier, TType* type)
992 if (qualifier != EvqConstReadOnly && qualifier != EvqTemporary) {
993 error(line, "qualifier not allowed on function parameter", getQualifierString(qualifier));
996 if (qualifier == EvqConstReadOnly && paramQualifier != EvqIn) {
997 error(line, "qualifier not allowed with ", getQualifierString(qualifier), getQualifierString(paramQualifier));
1001 if (qualifier == EvqConstReadOnly)
1002 type->setQualifier(EvqConstReadOnly);
1004 type->setQualifier(paramQualifier);
1009 bool TParseContext::extensionErrorCheck(const TSourceLoc &line, const TString& extension)
1011 const TExtensionBehavior& extBehavior = extensionBehavior();
1012 TExtensionBehavior::const_iterator iter = extBehavior.find(extension.c_str());
1013 if (iter == extBehavior.end()) {
1014 error(line, "extension", extension.c_str(), "is not supported");
1017 // In GLSL ES, an extension's default behavior is "disable".
1018 if (iter->second == EBhDisable || iter->second == EBhUndefined) {
1019 error(line, "extension", extension.c_str(), "is disabled");
1022 if (iter->second == EBhWarn) {
1023 warning(line, "extension", extension.c_str(), "is being used");
1030 bool TParseContext::functionCallLValueErrorCheck(const TFunction *fnCandidate, TIntermAggregate *aggregate)
1032 for(size_t i = 0; i < fnCandidate->getParamCount(); ++i)
1034 TQualifier qual = fnCandidate->getParam(i).type->getQualifier();
1035 if(qual == EvqOut || qual == EvqInOut)
1037 TIntermTyped *node = (aggregate->getSequence())[i]->getAsTyped();
1038 if(lValueErrorCheck(node->getLine(), "assign", node))
1040 error(node->getLine(),
1041 "Constant value cannot be passed for 'out' or 'inout' parameters.", "Error");
1050 void TParseContext::es3InvariantErrorCheck(const TQualifier qualifier, const TSourceLoc &invariantLocation)
1057 case EvqCentroidOut:
1059 case EvqFragmentOut:
1062 error(invariantLocation, "Only out variables can be invariant.", "invariant");
1068 bool TParseContext::supportsExtension(const char* extension)
1070 const TExtensionBehavior& extbehavior = extensionBehavior();
1071 TExtensionBehavior::const_iterator iter = extbehavior.find(extension);
1072 return (iter != extbehavior.end());
1075 void TParseContext::handleExtensionDirective(const TSourceLoc &line, const char* extName, const char* behavior)
1077 pp::SourceLocation loc(line.first_file, line.first_line);
1078 mDirectiveHandler.handleExtension(loc, extName, behavior);
1081 void TParseContext::handlePragmaDirective(const TSourceLoc &line, const char* name, const char* value)
1083 pp::SourceLocation loc(line.first_file, line.first_line);
1084 mDirectiveHandler.handlePragma(loc, name, value);
1087 /////////////////////////////////////////////////////////////////////////////////
1091 /////////////////////////////////////////////////////////////////////////////////
1093 const TVariable *TParseContext::getNamedVariable(const TSourceLoc &location,
1094 const TString *name,
1095 const TSymbol *symbol)
1097 const TVariable *variable = NULL;
1101 error(location, "undeclared identifier", name->c_str());
1104 else if(!symbol->isVariable())
1106 error(location, "variable expected", name->c_str());
1111 variable = static_cast<const TVariable*>(symbol);
1113 if(symbolTable.findBuiltIn(variable->getName(), mShaderVersion))
1118 // Reject shaders using both gl_FragData and gl_FragColor
1119 TQualifier qualifier = variable->getType().getQualifier();
1120 if(qualifier == EvqFragData)
1122 mUsesFragData = true;
1124 else if(qualifier == EvqFragColor)
1126 mUsesFragColor = true;
1129 // This validation is not quite correct - it's only an error to write to
1130 // both FragData and FragColor. For simplicity, and because users shouldn't
1131 // be rewarded for reading from undefined variables, return an error
1132 // if they are both referenced, rather than assigned.
1133 if(mUsesFragData && mUsesFragColor)
1135 error(location, "cannot use both gl_FragData and gl_FragColor", name->c_str());
1142 TType type(EbtFloat, EbpUndefined);
1143 TVariable *fakeVariable = new TVariable(name, type);
1144 symbolTable.declare(*fakeVariable);
1145 variable = fakeVariable;
1152 // Look up a function name in the symbol table, and make sure it is a function.
1154 // Return the function symbol if found, otherwise 0.
1156 const TFunction* TParseContext::findFunction(const TSourceLoc &line, TFunction* call, bool *builtIn)
1158 // First find by unmangled name to check whether the function name has been
1159 // hidden by a variable name or struct typename.
1160 const TSymbol* symbol = symbolTable.find(call->getName(), mShaderVersion, builtIn);
1162 symbol = symbolTable.find(call->getMangledName(), mShaderVersion, builtIn);
1166 error(line, "no matching overloaded function found", call->getName().c_str());
1170 if (!symbol->isFunction()) {
1171 error(line, "function name expected", call->getName().c_str());
1175 return static_cast<const TFunction*>(symbol);
1179 // Initializers show up in several places in the grammar. Have one set of
1180 // code to handle them here.
1182 bool TParseContext::executeInitializer(const TSourceLoc& line, const TString& identifier, const TPublicType& pType,
1183 TIntermTyped *initializer, TIntermNode **intermNode)
1185 ASSERT(intermNode != nullptr);
1186 TType type = TType(pType);
1188 if(type.isArray() && (type.getArraySize() == 0))
1190 type.setArraySize(initializer->getArraySize());
1193 TVariable *variable = nullptr;
1194 if(!declareVariable(line, identifier, type, &variable))
1199 bool globalInitWarning = false;
1200 if(symbolTable.atGlobalLevel() && !ValidateGlobalInitializer(initializer, this, &globalInitWarning))
1202 // Error message does not completely match behavior with ESSL 1.00, but
1203 // we want to steer developers towards only using constant expressions.
1204 error(line, "global variable initializers must be constant expressions", "=");
1207 if(globalInitWarning)
1209 warning(line, "global variable initializers should be constant expressions "
1210 "(uniforms and globals are allowed in global initializers for legacy compatibility)", "=");
1214 // identifier must be of type constant, a global, or a temporary
1216 TQualifier qualifier = type.getQualifier();
1217 if ((qualifier != EvqTemporary) && (qualifier != EvqGlobal) && (qualifier != EvqConstExpr)) {
1218 error(line, " cannot initialize this type of qualifier ", variable->getType().getQualifierString());
1222 // test for and propagate constant
1225 if (qualifier == EvqConstExpr) {
1226 if (qualifier != initializer->getQualifier()) {
1227 std::stringstream extraInfoStream;
1228 extraInfoStream << "'" << variable->getType().getCompleteString() << "'";
1229 std::string extraInfo = extraInfoStream.str();
1230 error(line, " assigning non-constant to", "=", extraInfo.c_str());
1231 variable->getType().setQualifier(EvqTemporary);
1235 if (type != initializer->getType()) {
1236 error(line, " non-matching types for const initializer ",
1237 variable->getType().getQualifierString());
1238 variable->getType().setQualifier(EvqTemporary);
1242 if (initializer->getAsConstantUnion()) {
1243 variable->shareConstPointer(initializer->getAsConstantUnion()->getUnionArrayPointer());
1244 } else if (initializer->getAsSymbolNode()) {
1245 const TSymbol* symbol = symbolTable.find(initializer->getAsSymbolNode()->getSymbol(), 0);
1246 const TVariable* tVar = static_cast<const TVariable*>(symbol);
1248 ConstantUnion* constArray = tVar->getConstPointer();
1249 variable->shareConstPointer(constArray);
1253 if (!variable->isConstant()) {
1254 TIntermSymbol* intermSymbol = intermediate.addSymbol(variable->getUniqueId(), variable->getName(), variable->getType(), line);
1255 *intermNode = createAssign(EOpInitialize, intermSymbol, initializer, line);
1256 if(*intermNode == nullptr) {
1257 assignError(line, "=", intermSymbol->getCompleteString(), initializer->getCompleteString());
1261 *intermNode = nullptr;
1266 TPublicType TParseContext::addFullySpecifiedType(TQualifier qualifier, bool invariant, TLayoutQualifier layoutQualifier, const TPublicType &typeSpecifier)
1268 TPublicType returnType = typeSpecifier;
1269 returnType.qualifier = qualifier;
1270 returnType.invariant = invariant;
1271 returnType.layoutQualifier = layoutQualifier;
1273 if(typeSpecifier.array)
1275 error(typeSpecifier.line, "not supported", "first-class array");
1277 returnType.clearArrayness();
1280 if(mShaderVersion < 300)
1282 if(qualifier == EvqAttribute && (typeSpecifier.type == EbtBool || typeSpecifier.type == EbtInt))
1284 error(typeSpecifier.line, "cannot be bool or int", getQualifierString(qualifier));
1288 if((qualifier == EvqVaryingIn || qualifier == EvqVaryingOut) &&
1289 (typeSpecifier.type == EbtBool || typeSpecifier.type == EbtInt))
1291 error(typeSpecifier.line, "cannot be bool or int", getQualifierString(qualifier));
1303 case EvqCentroidOut:
1305 if(typeSpecifier.type == EbtBool)
1307 error(typeSpecifier.line, "cannot be bool", getQualifierString(qualifier));
1310 if(typeSpecifier.type == EbtInt || typeSpecifier.type == EbtUInt)
1312 error(typeSpecifier.line, "must use 'flat' interpolation here", getQualifierString(qualifier));
1318 case EvqFragmentOut:
1321 if(typeSpecifier.type == EbtBool)
1323 error(typeSpecifier.line, "cannot be bool", getQualifierString(qualifier));
1335 TIntermAggregate *TParseContext::parseSingleDeclaration(TPublicType &publicType,
1336 const TSourceLoc &identifierOrTypeLocation,
1337 const TString &identifier)
1339 TIntermSymbol *symbol = intermediate.addSymbol(0, identifier, TType(publicType), identifierOrTypeLocation);
1341 bool emptyDeclaration = (identifier == "");
1343 mDeferredSingleDeclarationErrorCheck = emptyDeclaration;
1345 if(emptyDeclaration)
1347 if(publicType.isUnsizedArray())
1349 // ESSL3 spec section 4.1.9: Array declaration which leaves the size unspecified is an error.
1350 // It is assumed that this applies to empty declarations as well.
1351 error(identifierOrTypeLocation, "empty array declaration needs to specify a size", identifier.c_str());
1356 if(singleDeclarationErrorCheck(publicType, identifierOrTypeLocation))
1359 if(nonInitErrorCheck(identifierOrTypeLocation, identifier, publicType))
1362 TVariable *variable = nullptr;
1363 if(!declareVariable(identifierOrTypeLocation, identifier, TType(publicType), &variable))
1366 if(variable && symbol)
1367 symbol->setId(variable->getUniqueId());
1370 return intermediate.makeAggregate(symbol, identifierOrTypeLocation);
1373 TIntermAggregate *TParseContext::parseSingleArrayDeclaration(TPublicType &publicType,
1374 const TSourceLoc &identifierLocation,
1375 const TString &identifier,
1376 const TSourceLoc &indexLocation,
1377 TIntermTyped *indexExpression)
1379 mDeferredSingleDeclarationErrorCheck = false;
1381 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1384 if(nonInitErrorCheck(identifierLocation, identifier, publicType))
1387 if(arrayTypeErrorCheck(indexLocation, publicType) || arrayQualifierErrorCheck(indexLocation, publicType))
1392 TType arrayType(publicType);
1395 if(arraySizeErrorCheck(identifierLocation, indexExpression, size))
1399 // Make the type an array even if size check failed.
1400 // This ensures useless error messages regarding the variable's non-arrayness won't follow.
1401 arrayType.setArraySize(size);
1403 TVariable *variable = nullptr;
1404 if(!declareVariable(identifierLocation, identifier, arrayType, &variable))
1407 TIntermSymbol *symbol = intermediate.addSymbol(0, identifier, arrayType, identifierLocation);
1408 if(variable && symbol)
1409 symbol->setId(variable->getUniqueId());
1411 return intermediate.makeAggregate(symbol, identifierLocation);
1414 TIntermAggregate *TParseContext::parseSingleInitDeclaration(const TPublicType &publicType,
1415 const TSourceLoc &identifierLocation,
1416 const TString &identifier,
1417 const TSourceLoc &initLocation,
1418 TIntermTyped *initializer)
1420 mDeferredSingleDeclarationErrorCheck = false;
1422 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1425 TIntermNode *intermNode = nullptr;
1426 if(!executeInitializer(identifierLocation, identifier, publicType, initializer, &intermNode))
1429 // Build intermediate representation
1431 return intermNode ? intermediate.makeAggregate(intermNode, initLocation) : nullptr;
1440 TIntermAggregate *TParseContext::parseSingleArrayInitDeclaration(TPublicType &publicType,
1441 const TSourceLoc &identifierLocation,
1442 const TString &identifier,
1443 const TSourceLoc &indexLocation,
1444 TIntermTyped *indexExpression,
1445 const TSourceLoc &initLocation,
1446 TIntermTyped *initializer)
1448 mDeferredSingleDeclarationErrorCheck = false;
1450 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1453 if(arrayTypeErrorCheck(indexLocation, publicType) || arrayQualifierErrorCheck(indexLocation, publicType))
1458 TPublicType arrayType(publicType);
1461 // If indexExpression is nullptr, then the array will eventually get its size implicitly from the initializer.
1462 if(indexExpression != nullptr && arraySizeErrorCheck(identifierLocation, indexExpression, size))
1466 // Make the type an array even if size check failed.
1467 // This ensures useless error messages regarding the variable's non-arrayness won't follow.
1468 arrayType.setArray(true, size);
1470 // initNode will correspond to the whole of "type b[n] = initializer".
1471 TIntermNode *initNode = nullptr;
1472 if(!executeInitializer(identifierLocation, identifier, arrayType, initializer, &initNode))
1474 return initNode ? intermediate.makeAggregate(initNode, initLocation) : nullptr;
1483 TIntermAggregate *TParseContext::parseInvariantDeclaration(const TSourceLoc &invariantLoc,
1484 const TSourceLoc &identifierLoc,
1485 const TString *identifier,
1486 const TSymbol *symbol)
1488 // invariant declaration
1489 if(globalErrorCheck(invariantLoc, symbolTable.atGlobalLevel(), "invariant varying"))
1496 error(identifierLoc, "undeclared identifier declared as invariant", identifier->c_str());
1502 const TString kGlFrontFacing("gl_FrontFacing");
1503 if(*identifier == kGlFrontFacing)
1505 error(identifierLoc, "identifier should not be declared as invariant", identifier->c_str());
1509 symbolTable.addInvariantVarying(std::string(identifier->c_str()));
1510 const TVariable *variable = getNamedVariable(identifierLoc, identifier, symbol);
1512 const TType &type = variable->getType();
1513 TIntermSymbol *intermSymbol = intermediate.addSymbol(variable->getUniqueId(),
1514 *identifier, type, identifierLoc);
1516 TIntermAggregate *aggregate = intermediate.makeAggregate(intermSymbol, identifierLoc);
1517 aggregate->setOp(EOpInvariantDeclaration);
1522 TIntermAggregate *TParseContext::parseDeclarator(TPublicType &publicType, TIntermAggregate *aggregateDeclaration,
1523 const TSourceLoc &identifierLocation, const TString &identifier)
1525 // If the declaration starting this declarator list was empty (example: int,), some checks were not performed.
1526 if(mDeferredSingleDeclarationErrorCheck)
1528 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1530 mDeferredSingleDeclarationErrorCheck = false;
1533 if(locationDeclaratorListCheck(identifierLocation, publicType))
1536 if(nonInitErrorCheck(identifierLocation, identifier, publicType))
1539 TVariable *variable = nullptr;
1540 if(!declareVariable(identifierLocation, identifier, TType(publicType), &variable))
1543 TIntermSymbol *symbol = intermediate.addSymbol(0, identifier, TType(publicType), identifierLocation);
1544 if(variable && symbol)
1545 symbol->setId(variable->getUniqueId());
1547 return intermediate.growAggregate(aggregateDeclaration, symbol, identifierLocation);
1550 TIntermAggregate *TParseContext::parseArrayDeclarator(TPublicType &publicType, TIntermAggregate *aggregateDeclaration,
1551 const TSourceLoc &identifierLocation, const TString &identifier,
1552 const TSourceLoc &arrayLocation, TIntermTyped *indexExpression)
1554 // If the declaration starting this declarator list was empty (example: int,), some checks were not performed.
1555 if(mDeferredSingleDeclarationErrorCheck)
1557 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1559 mDeferredSingleDeclarationErrorCheck = false;
1562 if(locationDeclaratorListCheck(identifierLocation, publicType))
1565 if(nonInitErrorCheck(identifierLocation, identifier, publicType))
1568 if(arrayTypeErrorCheck(arrayLocation, publicType) || arrayQualifierErrorCheck(arrayLocation, publicType))
1574 TType arrayType = TType(publicType);
1576 if(arraySizeErrorCheck(arrayLocation, indexExpression, size))
1580 arrayType.setArraySize(size);
1582 TVariable *variable = nullptr;
1583 if(!declareVariable(identifierLocation, identifier, arrayType, &variable))
1586 TIntermSymbol *symbol = intermediate.addSymbol(0, identifier, arrayType, identifierLocation);
1587 if(variable && symbol)
1588 symbol->setId(variable->getUniqueId());
1590 return intermediate.growAggregate(aggregateDeclaration, symbol, identifierLocation);
1596 TIntermAggregate *TParseContext::parseInitDeclarator(const TPublicType &publicType, TIntermAggregate *aggregateDeclaration,
1597 const TSourceLoc &identifierLocation, const TString &identifier,
1598 const TSourceLoc &initLocation, TIntermTyped *initializer)
1600 // If the declaration starting this declarator list was empty (example: int,), some checks were not performed.
1601 if(mDeferredSingleDeclarationErrorCheck)
1603 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1605 mDeferredSingleDeclarationErrorCheck = false;
1608 if(locationDeclaratorListCheck(identifierLocation, publicType))
1611 TIntermNode *intermNode = nullptr;
1612 if(!executeInitializer(identifierLocation, identifier, publicType, initializer, &intermNode))
1615 // build the intermediate representation
1619 return intermediate.growAggregate(aggregateDeclaration, intermNode, initLocation);
1623 return aggregateDeclaration;
1633 TIntermAggregate *TParseContext::parseArrayInitDeclarator(const TPublicType &publicType,
1634 TIntermAggregate *aggregateDeclaration,
1635 const TSourceLoc &identifierLocation,
1636 const TString &identifier,
1637 const TSourceLoc &indexLocation,
1638 TIntermTyped *indexExpression,
1639 const TSourceLoc &initLocation, TIntermTyped *initializer)
1641 // If the declaration starting this declarator list was empty (example: int,), some checks were not performed.
1642 if(mDeferredSingleDeclarationErrorCheck)
1644 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1646 mDeferredSingleDeclarationErrorCheck = false;
1649 if(locationDeclaratorListCheck(identifierLocation, publicType))
1652 if(arrayTypeErrorCheck(indexLocation, publicType) || arrayQualifierErrorCheck(indexLocation, publicType))
1657 TPublicType arrayType(publicType);
1660 // If indexExpression is nullptr, then the array will eventually get its size implicitly from the initializer.
1661 if(indexExpression != nullptr && arraySizeErrorCheck(identifierLocation, indexExpression, size))
1665 // Make the type an array even if size check failed.
1666 // This ensures useless error messages regarding the variable's non-arrayness won't follow.
1667 arrayType.setArray(true, size);
1669 // initNode will correspond to the whole of "b[n] = initializer".
1670 TIntermNode *initNode = nullptr;
1671 if(!executeInitializer(identifierLocation, identifier, arrayType, initializer, &initNode))
1675 return intermediate.growAggregate(aggregateDeclaration, initNode, initLocation);
1679 return aggregateDeclaration;
1689 void TParseContext::parseGlobalLayoutQualifier(const TPublicType &typeQualifier)
1691 if(mShaderVersion < 300)
1693 error(typeQualifier.line, "layout qualifiers supported in GLSL ES 3.00 only", "layout");
1698 if(typeQualifier.qualifier != EvqUniform)
1700 error(typeQualifier.line, "invalid qualifier:", getQualifierString(typeQualifier.qualifier), "global layout must be uniform");
1705 const TLayoutQualifier layoutQualifier = typeQualifier.layoutQualifier;
1706 ASSERT(!layoutQualifier.isEmpty());
1708 if(layoutLocationErrorCheck(typeQualifier.line, typeQualifier.layoutQualifier))
1714 if(layoutQualifier.matrixPacking != EmpUnspecified)
1716 mDefaultMatrixPacking = layoutQualifier.matrixPacking;
1719 if(layoutQualifier.blockStorage != EbsUnspecified)
1721 mDefaultBlockStorage = layoutQualifier.blockStorage;
1725 TIntermAggregate *TParseContext::addFunctionPrototypeDeclaration(const TFunction &function, const TSourceLoc &location)
1727 // Note: symbolTableFunction could be the same as function if this is the first declaration.
1728 // Either way the instance in the symbol table is used to track whether the function is declared
1730 TFunction *symbolTableFunction =
1731 static_cast<TFunction *>(symbolTable.find(function.getMangledName(), getShaderVersion()));
1732 if(symbolTableFunction->hasPrototypeDeclaration() && mShaderVersion == 100)
1734 // ESSL 1.00.17 section 4.2.7.
1735 // Doesn't apply to ESSL 3.00.4: see section 4.2.3.
1736 error(location, "duplicate function prototype declarations are not allowed", "function");
1739 symbolTableFunction->setHasPrototypeDeclaration();
1741 TIntermAggregate *prototype = new TIntermAggregate;
1742 prototype->setType(function.getReturnType());
1743 prototype->setName(function.getMangledName());
1745 for(size_t i = 0; i < function.getParamCount(); i++)
1747 const TParameter ¶m = function.getParam(i);
1750 TVariable variable(param.name, *param.type);
1752 TIntermSymbol *paramSymbol = intermediate.addSymbol(
1753 variable.getUniqueId(), variable.getName(), variable.getType(), location);
1754 prototype = intermediate.growAggregate(prototype, paramSymbol, location);
1758 TIntermSymbol *paramSymbol = intermediate.addSymbol(0, "", *param.type, location);
1759 prototype = intermediate.growAggregate(prototype, paramSymbol, location);
1763 prototype->setOp(EOpPrototype);
1767 if(!symbolTable.atGlobalLevel())
1769 // ESSL 3.00.4 section 4.2.4.
1770 error(location, "local function prototype declarations are not allowed", "function");
1777 TIntermAggregate *TParseContext::addFunctionDefinition(const TFunction &function, TIntermAggregate *functionPrototype, TIntermAggregate *functionBody, const TSourceLoc &location)
1779 //?? Check that all paths return a value if return type != void ?
1780 // May be best done as post process phase on intermediate code
1781 if(mCurrentFunctionType->getBasicType() != EbtVoid && !mFunctionReturnsValue)
1783 error(location, "function does not return a value:", "", function.getName().c_str());
1787 TIntermAggregate *aggregate = intermediate.growAggregate(functionPrototype, functionBody, location);
1788 intermediate.setAggregateOperator(aggregate, EOpFunction, location);
1789 aggregate->setName(function.getMangledName().c_str());
1790 aggregate->setType(function.getReturnType());
1792 // store the pragma information for debug and optimize and other vendor specific
1793 // information. This information can be queried from the parse tree
1794 aggregate->setOptimize(pragma().optimize);
1795 aggregate->setDebug(pragma().debug);
1797 if(functionBody && functionBody->getAsAggregate())
1798 aggregate->setEndLine(functionBody->getAsAggregate()->getEndLine());
1804 void TParseContext::parseFunctionPrototype(const TSourceLoc &location, TFunction *function, TIntermAggregate **aggregateOut)
1806 const TSymbol *builtIn = symbolTable.findBuiltIn(function->getMangledName(), getShaderVersion());
1810 error(location, "built-in functions cannot be redefined", function->getName().c_str());
1814 TFunction *prevDec = static_cast<TFunction *>(symbolTable.find(function->getMangledName(), getShaderVersion()));
1816 // Note: 'prevDec' could be 'function' if this is the first time we've seen function
1817 // as it would have just been put in the symbol table. Otherwise, we're looking up
1818 // an earlier occurance.
1820 if(prevDec->isDefined())
1822 // Then this function already has a body.
1823 error(location, "function already has a body", function->getName().c_str());
1826 prevDec->setDefined();
1828 // Overload the unique ID of the definition to be the same unique ID as the declaration.
1829 // Eventually we will probably want to have only a single definition and just swap the
1830 // arguments to be the definition's arguments.
1832 function->setUniqueId(prevDec->getUniqueId());
1834 // Raise error message if main function takes any parameters or return anything other than void
1835 if(function->getName() == "main")
1837 if(function->getParamCount() > 0)
1839 error(location, "function cannot take any parameter(s)", function->getName().c_str());
1842 if(function->getReturnType().getBasicType() != EbtVoid)
1844 error(location, "", function->getReturnType().getBasicString(), "main function cannot return a value");
1850 // Remember the return type for later checking for RETURN statements.
1852 mCurrentFunctionType = &(prevDec->getReturnType());
1853 mFunctionReturnsValue = false;
1856 // Insert parameters into the symbol table.
1857 // If the parameter has no name, it's not an error, just don't insert it
1858 // (could be used for unused args).
1860 // Also, accumulate the list of parameters into the HIL, so lower level code
1861 // knows where to find parameters.
1863 TIntermAggregate *paramNodes = new TIntermAggregate;
1864 for(size_t i = 0; i < function->getParamCount(); i++)
1866 const TParameter ¶m = function->getParam(i);
1869 TVariable *variable = new TVariable(param.name, *param.type);
1871 // Insert the parameters with name in the symbol table.
1873 if(!symbolTable.declare(*variable))
1875 error(location, "redefinition", variable->getName().c_str());
1877 paramNodes = intermediate.growAggregate(
1878 paramNodes, intermediate.addSymbol(0, "", *param.type, location), location);
1883 // Add the parameter to the HIL
1885 TIntermSymbol *symbol = intermediate.addSymbol(
1886 variable->getUniqueId(), variable->getName(), variable->getType(), location);
1888 paramNodes = intermediate.growAggregate(paramNodes, symbol, location);
1892 paramNodes = intermediate.growAggregate(
1893 paramNodes, intermediate.addSymbol(0, "", *param.type, location), location);
1896 intermediate.setAggregateOperator(paramNodes, EOpParameters, location);
1897 *aggregateOut = paramNodes;
1898 setLoopNestingLevel(0);
1901 TFunction *TParseContext::parseFunctionDeclarator(const TSourceLoc &location, TFunction *function)
1904 // We don't know at this point whether this is a function definition or a prototype.
1905 // The definition production code will check for redefinitions.
1906 // In the case of ESSL 1.00 the prototype production code will also check for redeclarations.
1908 // Return types and parameter qualifiers must match in all redeclarations, so those are checked
1911 TFunction *prevDec = static_cast<TFunction *>(symbolTable.find(function->getMangledName(), getShaderVersion()));
1914 if(prevDec->getReturnType() != function->getReturnType())
1916 error(location, "overloaded functions must have the same return type",
1917 function->getReturnType().getBasicString());
1920 for(size_t i = 0; i < prevDec->getParamCount(); ++i)
1922 if(prevDec->getParam(i).type->getQualifier() != function->getParam(i).type->getQualifier())
1924 error(location, "overloaded functions must have the same parameter qualifiers",
1925 function->getParam(i).type->getQualifierString());
1932 // Check for previously declared variables using the same name.
1934 TSymbol *prevSym = symbolTable.find(function->getName(), getShaderVersion());
1937 if(!prevSym->isFunction())
1939 error(location, "redefinition", function->getName().c_str(), "function");
1944 // We're at the inner scope level of the function's arguments and body statement.
1945 // Add the function prototype to the surrounding scope instead.
1946 symbolTable.getOuterLevel()->insert(*function);
1949 // If this is a redeclaration, it could also be a definition, in which case, we want to use the
1950 // variable names from this one, and not the one that's
1951 // being redeclared. So, pass back up this declaration, not the one in the symbol table.
1956 TFunction *TParseContext::addConstructorFunc(const TPublicType &publicTypeIn)
1958 TPublicType publicType = publicTypeIn;
1959 TOperator op = EOpNull;
1960 if(publicType.userDef)
1962 op = EOpConstructStruct;
1966 switch(publicType.type)
1969 if(publicType.isMatrix())
1971 switch(publicType.getCols())
1974 switch(publicType.getRows())
1976 case 2: op = EOpConstructMat2; break;
1977 case 3: op = EOpConstructMat2x3; break;
1978 case 4: op = EOpConstructMat2x4; break;
1982 switch(publicType.getRows())
1984 case 2: op = EOpConstructMat3x2; break;
1985 case 3: op = EOpConstructMat3; break;
1986 case 4: op = EOpConstructMat3x4; break;
1990 switch(publicType.getRows())
1992 case 2: op = EOpConstructMat4x2; break;
1993 case 3: op = EOpConstructMat4x3; break;
1994 case 4: op = EOpConstructMat4; break;
2001 switch(publicType.getNominalSize())
2003 case 1: op = EOpConstructFloat; break;
2004 case 2: op = EOpConstructVec2; break;
2005 case 3: op = EOpConstructVec3; break;
2006 case 4: op = EOpConstructVec4; break;
2012 switch(publicType.getNominalSize())
2014 case 1: op = EOpConstructInt; break;
2015 case 2: op = EOpConstructIVec2; break;
2016 case 3: op = EOpConstructIVec3; break;
2017 case 4: op = EOpConstructIVec4; break;
2022 switch(publicType.getNominalSize())
2024 case 1: op = EOpConstructUInt; break;
2025 case 2: op = EOpConstructUVec2; break;
2026 case 3: op = EOpConstructUVec3; break;
2027 case 4: op = EOpConstructUVec4; break;
2032 switch(publicType.getNominalSize())
2034 case 1: op = EOpConstructBool; break;
2035 case 2: op = EOpConstructBVec2; break;
2036 case 3: op = EOpConstructBVec3; break;
2037 case 4: op = EOpConstructBVec4; break;
2046 error(publicType.line, "cannot construct this type", getBasicString(publicType.type));
2048 publicType.type = EbtFloat;
2049 op = EOpConstructFloat;
2054 TType type(publicType);
2055 return new TFunction(&tempString, type, op);
2058 // This function is used to test for the correctness of the parameters passed to various constructor functions
2059 // and also convert them to the right datatype if it is allowed and required.
2061 // Returns 0 for an error or the constructed node (aggregate or typed) for no error.
2063 TIntermTyped* TParseContext::addConstructor(TIntermNode* arguments, const TType* type, TOperator op, TFunction* fnCall, const TSourceLoc &line)
2065 TIntermAggregate *aggregateArguments = arguments->getAsAggregate();
2067 if(!aggregateArguments)
2069 aggregateArguments = new TIntermAggregate;
2070 aggregateArguments->getSequence().push_back(arguments);
2073 if(op == EOpConstructStruct)
2075 const TFieldList &fields = type->getStruct()->fields();
2076 TIntermSequence &args = aggregateArguments->getSequence();
2078 for(size_t i = 0; i < fields.size(); i++)
2080 if(args[i]->getAsTyped()->getType() != *fields[i]->type())
2082 error(line, "Structure constructor arguments do not match structure fields", "Error");
2090 // Turn the argument list itself into a constructor
2091 TIntermAggregate *constructor = intermediate.setAggregateOperator(aggregateArguments, op, line);
2092 TIntermTyped *constConstructor = foldConstConstructor(constructor, *type);
2093 if(constConstructor)
2095 return constConstructor;
2101 TIntermTyped* TParseContext::foldConstConstructor(TIntermAggregate* aggrNode, const TType& type)
2103 aggrNode->setType(type);
2104 if (aggrNode->isConstantFoldable()) {
2105 bool returnVal = false;
2106 ConstantUnion* unionArray = new ConstantUnion[type.getObjectSize()];
2107 if (aggrNode->getSequence().size() == 1) {
2108 returnVal = intermediate.parseConstTree(aggrNode->getLine(), aggrNode, unionArray, aggrNode->getOp(), type, true);
2111 returnVal = intermediate.parseConstTree(aggrNode->getLine(), aggrNode, unionArray, aggrNode->getOp(), type);
2116 return intermediate.addConstantUnion(unionArray, type, aggrNode->getLine());
2123 // This function returns the tree representation for the vector field(s) being accessed from contant vector.
2124 // If only one component of vector is accessed (v.x or v[0] where v is a contant vector), then a contant node is
2125 // returned, else an aggregate node is returned (for v.xy). The input to this function could either be the symbol
2126 // node or it could be the intermediate tree representation of accessing fields in a constant structure or column of
2127 // a constant matrix.
2129 TIntermTyped* TParseContext::addConstVectorNode(TVectorFields& fields, TIntermTyped* node, const TSourceLoc &line)
2131 TIntermTyped* typedNode;
2132 TIntermConstantUnion* tempConstantNode = node->getAsConstantUnion();
2134 ConstantUnion *unionArray;
2135 if (tempConstantNode) {
2136 unionArray = tempConstantNode->getUnionArrayPointer();
2141 } else { // The node has to be either a symbol node or an aggregate node or a tempConstant node, else, its an error
2142 error(line, "Cannot offset into the vector", "Error");
2148 ConstantUnion* constArray = new ConstantUnion[fields.num];
2150 for (int i = 0; i < fields.num; i++) {
2151 if (fields.offsets[i] >= node->getType().getObjectSize()) {
2152 std::stringstream extraInfoStream;
2153 extraInfoStream << "vector field selection out of range '" << fields.offsets[i] << "'";
2154 std::string extraInfo = extraInfoStream.str();
2155 error(line, "", "[", extraInfo.c_str());
2157 fields.offsets[i] = 0;
2160 constArray[i] = unionArray[fields.offsets[i]];
2163 typedNode = intermediate.addConstantUnion(constArray, node->getType(), line);
2168 // This function returns the column being accessed from a constant matrix. The values are retrieved from
2169 // the symbol table and parse-tree is built for a vector (each column of a matrix is a vector). The input
2170 // to the function could either be a symbol node (m[0] where m is a constant matrix)that represents a
2171 // constant matrix or it could be the tree representation of the constant matrix (s.m1[0] where s is a constant structure)
2173 TIntermTyped* TParseContext::addConstMatrixNode(int index, TIntermTyped* node, const TSourceLoc &line)
2175 TIntermTyped* typedNode;
2176 TIntermConstantUnion* tempConstantNode = node->getAsConstantUnion();
2178 if (index >= node->getType().getNominalSize()) {
2179 std::stringstream extraInfoStream;
2180 extraInfoStream << "matrix field selection out of range '" << index << "'";
2181 std::string extraInfo = extraInfoStream.str();
2182 error(line, "", "[", extraInfo.c_str());
2187 if (tempConstantNode) {
2188 ConstantUnion* unionArray = tempConstantNode->getUnionArrayPointer();
2189 int size = tempConstantNode->getType().getNominalSize();
2190 typedNode = intermediate.addConstantUnion(&unionArray[size*index], tempConstantNode->getType(), line);
2192 error(line, "Cannot offset into the matrix", "Error");
2203 // This function returns an element of an array accessed from a constant array. The values are retrieved from
2204 // the symbol table and parse-tree is built for the type of the element. The input
2205 // to the function could either be a symbol node (a[0] where a is a constant array)that represents a
2206 // constant array or it could be the tree representation of the constant array (s.a1[0] where s is a constant structure)
2208 TIntermTyped* TParseContext::addConstArrayNode(int index, TIntermTyped* node, const TSourceLoc &line)
2210 TIntermTyped* typedNode;
2211 TIntermConstantUnion* tempConstantNode = node->getAsConstantUnion();
2212 TType arrayElementType = node->getType();
2213 arrayElementType.clearArrayness();
2215 if (index >= node->getType().getArraySize()) {
2216 std::stringstream extraInfoStream;
2217 extraInfoStream << "array field selection out of range '" << index << "'";
2218 std::string extraInfo = extraInfoStream.str();
2219 error(line, "", "[", extraInfo.c_str());
2224 int arrayElementSize = arrayElementType.getObjectSize();
2226 if (tempConstantNode) {
2227 ConstantUnion* unionArray = tempConstantNode->getUnionArrayPointer();
2228 typedNode = intermediate.addConstantUnion(&unionArray[arrayElementSize * index], tempConstantNode->getType(), line);
2230 error(line, "Cannot offset into the array", "Error");
2241 // This function returns the value of a particular field inside a constant structure from the symbol table.
2242 // If there is an embedded/nested struct, it appropriately calls addConstStructNested or addConstStructFromAggr
2243 // function and returns the parse-tree with the values of the embedded/nested struct.
2245 TIntermTyped* TParseContext::addConstStruct(const TString& identifier, TIntermTyped* node, const TSourceLoc &line)
2247 const TFieldList &fields = node->getType().getStruct()->fields();
2248 TIntermTyped *typedNode;
2249 int instanceSize = 0;
2250 unsigned int index = 0;
2251 TIntermConstantUnion *tempConstantNode = node->getAsConstantUnion();
2253 for ( index = 0; index < fields.size(); ++index) {
2254 if (fields[index]->name() == identifier) {
2257 instanceSize += fields[index]->type()->getObjectSize();
2261 if (tempConstantNode) {
2262 ConstantUnion* constArray = tempConstantNode->getUnionArrayPointer();
2264 typedNode = intermediate.addConstantUnion(constArray+instanceSize, tempConstantNode->getType(), line); // type will be changed in the calling function
2266 error(line, "Cannot offset into the structure", "Error");
2276 // Interface/uniform blocks
2278 TIntermAggregate* TParseContext::addInterfaceBlock(const TPublicType& typeQualifier, const TSourceLoc& nameLine, const TString& blockName, TFieldList* fieldList,
2279 const TString* instanceName, const TSourceLoc& instanceLine, TIntermTyped* arrayIndex, const TSourceLoc& arrayIndexLine)
2281 if(reservedErrorCheck(nameLine, blockName))
2284 if(typeQualifier.qualifier != EvqUniform)
2286 error(typeQualifier.line, "invalid qualifier:", getQualifierString(typeQualifier.qualifier), "interface blocks must be uniform");
2290 TLayoutQualifier blockLayoutQualifier = typeQualifier.layoutQualifier;
2291 if(layoutLocationErrorCheck(typeQualifier.line, blockLayoutQualifier))
2296 if(blockLayoutQualifier.matrixPacking == EmpUnspecified)
2298 blockLayoutQualifier.matrixPacking = mDefaultMatrixPacking;
2301 if(blockLayoutQualifier.blockStorage == EbsUnspecified)
2303 blockLayoutQualifier.blockStorage = mDefaultBlockStorage;
2306 TSymbol* blockNameSymbol = new TSymbol(&blockName);
2307 if(!symbolTable.declare(*blockNameSymbol)) {
2308 error(nameLine, "redefinition", blockName.c_str(), "interface block name");
2312 // check for sampler types and apply layout qualifiers
2313 for(size_t memberIndex = 0; memberIndex < fieldList->size(); ++memberIndex) {
2314 TField* field = (*fieldList)[memberIndex];
2315 TType* fieldType = field->type();
2316 if(IsSampler(fieldType->getBasicType())) {
2317 error(field->line(), "unsupported type", fieldType->getBasicString(), "sampler types are not allowed in interface blocks");
2321 const TQualifier qualifier = fieldType->getQualifier();
2328 error(field->line(), "invalid qualifier on interface block member", getQualifierString(qualifier));
2333 // check layout qualifiers
2334 TLayoutQualifier fieldLayoutQualifier = fieldType->getLayoutQualifier();
2335 if(layoutLocationErrorCheck(field->line(), fieldLayoutQualifier))
2340 if(fieldLayoutQualifier.blockStorage != EbsUnspecified)
2342 error(field->line(), "invalid layout qualifier:", getBlockStorageString(fieldLayoutQualifier.blockStorage), "cannot be used here");
2346 if(fieldLayoutQualifier.matrixPacking == EmpUnspecified)
2348 fieldLayoutQualifier.matrixPacking = blockLayoutQualifier.matrixPacking;
2350 else if(!fieldType->isMatrix())
2352 error(field->line(), "invalid layout qualifier:", getMatrixPackingString(fieldLayoutQualifier.matrixPacking), "can only be used on matrix types");
2356 fieldType->setLayoutQualifier(fieldLayoutQualifier);
2361 if(arrayIndex != NULL)
2363 if(arraySizeErrorCheck(arrayIndexLine, arrayIndex, arraySize))
2367 TInterfaceBlock* interfaceBlock = new TInterfaceBlock(&blockName, fieldList, instanceName, arraySize, blockLayoutQualifier);
2368 TType interfaceBlockType(interfaceBlock, typeQualifier.qualifier, blockLayoutQualifier, arraySize);
2370 TString symbolName = "";
2375 // define symbols for the members of the interface block
2376 for(size_t memberIndex = 0; memberIndex < fieldList->size(); ++memberIndex)
2378 TField* field = (*fieldList)[memberIndex];
2379 TType* fieldType = field->type();
2381 // set parent pointer of the field variable
2382 fieldType->setInterfaceBlock(interfaceBlock);
2384 TVariable* fieldVariable = new TVariable(&field->name(), *fieldType);
2385 fieldVariable->setQualifier(typeQualifier.qualifier);
2387 if(!symbolTable.declare(*fieldVariable)) {
2388 error(field->line(), "redefinition", field->name().c_str(), "interface block member name");
2395 // add a symbol for this interface block
2396 TVariable* instanceTypeDef = new TVariable(instanceName, interfaceBlockType, false);
2397 instanceTypeDef->setQualifier(typeQualifier.qualifier);
2399 if(!symbolTable.declare(*instanceTypeDef)) {
2400 error(instanceLine, "redefinition", instanceName->c_str(), "interface block instance name");
2404 symbolId = instanceTypeDef->getUniqueId();
2405 symbolName = instanceTypeDef->getName();
2408 TIntermAggregate *aggregate = intermediate.makeAggregate(intermediate.addSymbol(symbolId, symbolName, interfaceBlockType, typeQualifier.line), nameLine);
2409 aggregate->setOp(EOpDeclaration);
2411 exitStructDeclaration();
2416 // Parse an array index expression
2418 TIntermTyped *TParseContext::addIndexExpression(TIntermTyped *baseExpression, const TSourceLoc &location, TIntermTyped *indexExpression)
2420 TIntermTyped *indexedExpression = NULL;
2422 if(!baseExpression->isArray() && !baseExpression->isMatrix() && !baseExpression->isVector())
2424 if(baseExpression->getAsSymbolNode())
2426 error(location, " left of '[' is not of type array, matrix, or vector ",
2427 baseExpression->getAsSymbolNode()->getSymbol().c_str());
2431 error(location, " left of '[' is not of type array, matrix, or vector ", "expression");
2436 TIntermConstantUnion *indexConstantUnion = indexExpression->getAsConstantUnion();
2438 if(indexExpression->getQualifier() == EvqConstExpr && indexConstantUnion)
2440 int index = indexConstantUnion->getIConst(0);
2443 std::stringstream infoStream;
2444 infoStream << index;
2445 std::string info = infoStream.str();
2446 error(location, "negative index", info.c_str());
2450 if(baseExpression->getType().getQualifier() == EvqConstExpr)
2452 if(baseExpression->isArray())
2454 // constant folding for arrays
2455 indexedExpression = addConstArrayNode(index, baseExpression, location);
2457 else if(baseExpression->isVector())
2459 // constant folding for vectors
2460 TVectorFields fields;
2462 fields.offsets[0] = index; // need to do it this way because v.xy sends fields integer array
2463 indexedExpression = addConstVectorNode(fields, baseExpression, location);
2465 else if(baseExpression->isMatrix())
2467 // constant folding for matrices
2468 indexedExpression = addConstMatrixNode(index, baseExpression, location);
2475 if(baseExpression->isArray())
2477 if(index >= baseExpression->getType().getArraySize())
2479 std::stringstream extraInfoStream;
2480 extraInfoStream << "array index out of range '" << index << "'";
2481 std::string extraInfo = extraInfoStream.str();
2482 error(location, "", "[", extraInfo.c_str());
2484 safeIndex = baseExpression->getType().getArraySize() - 1;
2487 else if((baseExpression->isVector() || baseExpression->isMatrix()) &&
2488 baseExpression->getType().getNominalSize() <= index)
2490 std::stringstream extraInfoStream;
2491 extraInfoStream << "field selection out of range '" << index << "'";
2492 std::string extraInfo = extraInfoStream.str();
2493 error(location, "", "[", extraInfo.c_str());
2495 safeIndex = baseExpression->getType().getNominalSize() - 1;
2498 // Don't modify the data of the previous constant union, because it can point
2499 // to builtins, like gl_MaxDrawBuffers. Instead use a new sanitized object.
2502 ConstantUnion *safeConstantUnion = new ConstantUnion();
2503 safeConstantUnion->setIConst(safeIndex);
2504 indexConstantUnion->replaceConstantUnion(safeConstantUnion);
2507 indexedExpression = intermediate.addIndex(EOpIndexDirect, baseExpression, indexExpression, location);
2512 if(baseExpression->isInterfaceBlock())
2515 "[", "array indexes for interface blocks arrays must be constant integral expressions");
2518 else if(baseExpression->getQualifier() == EvqFragmentOut)
2520 error(location, "", "[", "array indexes for fragment outputs must be constant integral expressions");
2524 indexedExpression = intermediate.addIndex(EOpIndexIndirect, baseExpression, indexExpression, location);
2527 if(indexedExpression == 0)
2529 ConstantUnion *unionArray = new ConstantUnion[1];
2530 unionArray->setFConst(0.0f);
2531 indexedExpression = intermediate.addConstantUnion(unionArray, TType(EbtFloat, EbpHigh, EvqConstExpr), location);
2533 else if(baseExpression->isArray())
2535 const TType &baseType = baseExpression->getType();
2536 if(baseType.getStruct())
2538 TType copyOfType(baseType.getStruct());
2539 indexedExpression->setType(copyOfType);
2541 else if(baseType.isInterfaceBlock())
2543 TType copyOfType(baseType.getInterfaceBlock(), EvqTemporary, baseType.getLayoutQualifier(), 0);
2544 indexedExpression->setType(copyOfType);
2548 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(),
2549 EvqTemporary, static_cast<unsigned char>(baseExpression->getNominalSize()),
2550 static_cast<unsigned char>(baseExpression->getSecondarySize())));
2553 if(baseExpression->getType().getQualifier() == EvqConstExpr)
2555 indexedExpression->getTypePointer()->setQualifier(EvqConstExpr);
2558 else if(baseExpression->isMatrix())
2560 TQualifier qualifier = baseExpression->getType().getQualifier() == EvqConstExpr ? EvqConstExpr : EvqTemporary;
2561 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(),
2562 qualifier, static_cast<unsigned char>(baseExpression->getSecondarySize())));
2564 else if(baseExpression->isVector())
2566 TQualifier qualifier = baseExpression->getType().getQualifier() == EvqConstExpr ? EvqConstExpr : EvqTemporary;
2567 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(), qualifier));
2571 indexedExpression->setType(baseExpression->getType());
2574 return indexedExpression;
2577 TIntermTyped *TParseContext::addFieldSelectionExpression(TIntermTyped *baseExpression, const TSourceLoc &dotLocation,
2578 const TString &fieldString, const TSourceLoc &fieldLocation)
2580 TIntermTyped *indexedExpression = NULL;
2582 if(baseExpression->isArray())
2584 error(fieldLocation, "cannot apply dot operator to an array", ".");
2588 if(baseExpression->isVector())
2590 TVectorFields fields;
2591 if(!parseVectorFields(fieldString, baseExpression->getNominalSize(), fields, fieldLocation))
2594 fields.offsets[0] = 0;
2598 if(baseExpression->getAsConstantUnion())
2600 // constant folding for vector fields
2601 indexedExpression = addConstVectorNode(fields, baseExpression, fieldLocation);
2602 if(indexedExpression == 0)
2605 indexedExpression = baseExpression;
2609 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(),
2610 EvqConstExpr, (unsigned char)(fieldString).size()));
2615 TString vectorString = fieldString;
2616 TIntermTyped *index = intermediate.addSwizzle(fields, fieldLocation);
2617 indexedExpression = intermediate.addIndex(EOpVectorSwizzle, baseExpression, index, dotLocation);
2618 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(),
2619 baseExpression->getQualifier() == EvqConstExpr ? EvqConstExpr : EvqTemporary, (unsigned char)vectorString.size()));
2622 else if(baseExpression->isMatrix())
2624 TMatrixFields fields;
2625 if(!parseMatrixFields(fieldString, baseExpression->getNominalSize(), baseExpression->getSecondarySize(), fields, fieldLocation))
2627 fields.wholeRow = false;
2628 fields.wholeCol = false;
2634 if(fields.wholeRow || fields.wholeCol)
2636 error(dotLocation, " non-scalar fields not implemented yet", ".");
2638 ConstantUnion *unionArray = new ConstantUnion[1];
2639 unionArray->setIConst(0);
2640 TIntermTyped *index = intermediate.addConstantUnion(unionArray, TType(EbtInt, EbpUndefined, EvqConstExpr),
2642 indexedExpression = intermediate.addIndex(EOpIndexDirect, baseExpression, index, dotLocation);
2643 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(),
2644 EvqTemporary, static_cast<unsigned char>(baseExpression->getNominalSize()),
2645 static_cast<unsigned char>(baseExpression->getSecondarySize())));
2649 ConstantUnion *unionArray = new ConstantUnion[1];
2650 unionArray->setIConst(fields.col * baseExpression->getSecondarySize() + fields.row);
2651 TIntermTyped *index = intermediate.addConstantUnion(unionArray, TType(EbtInt, EbpUndefined, EvqConstExpr),
2653 indexedExpression = intermediate.addIndex(EOpIndexDirect, baseExpression, index, dotLocation);
2654 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision()));
2657 else if(baseExpression->getBasicType() == EbtStruct)
2659 bool fieldFound = false;
2660 const TFieldList &fields = baseExpression->getType().getStruct()->fields();
2663 error(dotLocation, "structure has no fields", "Internal Error");
2665 indexedExpression = baseExpression;
2670 for(i = 0; i < fields.size(); ++i)
2672 if(fields[i]->name() == fieldString)
2680 if(baseExpression->getType().getQualifier() == EvqConstExpr)
2682 indexedExpression = addConstStruct(fieldString, baseExpression, dotLocation);
2683 if(indexedExpression == 0)
2686 indexedExpression = baseExpression;
2690 indexedExpression->setType(*fields[i]->type());
2691 // change the qualifier of the return type, not of the structure field
2692 // as the structure definition is shared between various structures.
2693 indexedExpression->getTypePointer()->setQualifier(EvqConstExpr);
2698 ConstantUnion *unionArray = new ConstantUnion[1];
2699 unionArray->setIConst(i);
2700 TIntermTyped *index = intermediate.addConstantUnion(unionArray, *fields[i]->type(), fieldLocation);
2701 indexedExpression = intermediate.addIndex(EOpIndexDirectStruct, baseExpression, index, dotLocation);
2702 indexedExpression->setType(*fields[i]->type());
2707 error(dotLocation, " no such field in structure", fieldString.c_str());
2709 indexedExpression = baseExpression;
2713 else if(baseExpression->isInterfaceBlock())
2715 bool fieldFound = false;
2716 const TFieldList &fields = baseExpression->getType().getInterfaceBlock()->fields();
2719 error(dotLocation, "interface block has no fields", "Internal Error");
2721 indexedExpression = baseExpression;
2726 for(i = 0; i < fields.size(); ++i)
2728 if(fields[i]->name() == fieldString)
2736 ConstantUnion *unionArray = new ConstantUnion[1];
2737 unionArray->setIConst(i);
2738 TIntermTyped *index = intermediate.addConstantUnion(unionArray, *fields[i]->type(), fieldLocation);
2739 indexedExpression = intermediate.addIndex(EOpIndexDirectInterfaceBlock, baseExpression, index,
2741 indexedExpression->setType(*fields[i]->type());
2745 error(dotLocation, " no such field in interface block", fieldString.c_str());
2747 indexedExpression = baseExpression;
2753 if(mShaderVersion < 300)
2755 error(dotLocation, " field selection requires structure, vector, or matrix on left hand side",
2756 fieldString.c_str());
2761 " field selection requires structure, vector, matrix, or interface block on left hand side",
2762 fieldString.c_str());
2765 indexedExpression = baseExpression;
2768 return indexedExpression;
2771 TLayoutQualifier TParseContext::parseLayoutQualifier(const TString &qualifierType, const TSourceLoc& qualifierTypeLine)
2773 TLayoutQualifier qualifier;
2775 qualifier.location = -1;
2776 qualifier.matrixPacking = EmpUnspecified;
2777 qualifier.blockStorage = EbsUnspecified;
2779 if(qualifierType == "shared")
2781 qualifier.blockStorage = EbsShared;
2783 else if(qualifierType == "packed")
2785 qualifier.blockStorage = EbsPacked;
2787 else if(qualifierType == "std140")
2789 qualifier.blockStorage = EbsStd140;
2791 else if(qualifierType == "row_major")
2793 qualifier.matrixPacking = EmpRowMajor;
2795 else if(qualifierType == "column_major")
2797 qualifier.matrixPacking = EmpColumnMajor;
2799 else if(qualifierType == "location")
2801 error(qualifierTypeLine, "invalid layout qualifier", qualifierType.c_str(), "location requires an argument");
2806 error(qualifierTypeLine, "invalid layout qualifier", qualifierType.c_str());
2813 TLayoutQualifier TParseContext::parseLayoutQualifier(const TString &qualifierType, const TSourceLoc& qualifierTypeLine, const TString &intValueString, int intValue, const TSourceLoc& intValueLine)
2815 TLayoutQualifier qualifier;
2817 qualifier.location = -1;
2818 qualifier.matrixPacking = EmpUnspecified;
2819 qualifier.blockStorage = EbsUnspecified;
2821 if (qualifierType != "location")
2823 error(qualifierTypeLine, "invalid layout qualifier", qualifierType.c_str(), "only location may have arguments");
2828 // must check that location is non-negative
2831 error(intValueLine, "out of range:", intValueString.c_str(), "location must be non-negative");
2836 qualifier.location = intValue;
2843 TLayoutQualifier TParseContext::joinLayoutQualifiers(TLayoutQualifier leftQualifier, TLayoutQualifier rightQualifier)
2845 TLayoutQualifier joinedQualifier = leftQualifier;
2847 if (rightQualifier.location != -1)
2849 joinedQualifier.location = rightQualifier.location;
2851 if(rightQualifier.matrixPacking != EmpUnspecified)
2853 joinedQualifier.matrixPacking = rightQualifier.matrixPacking;
2855 if(rightQualifier.blockStorage != EbsUnspecified)
2857 joinedQualifier.blockStorage = rightQualifier.blockStorage;
2860 return joinedQualifier;
2864 TPublicType TParseContext::joinInterpolationQualifiers(const TSourceLoc &interpolationLoc, TQualifier interpolationQualifier,
2865 const TSourceLoc &storageLoc, TQualifier storageQualifier)
2867 TQualifier mergedQualifier = EvqSmoothIn;
2869 if(storageQualifier == EvqFragmentIn) {
2870 if(interpolationQualifier == EvqSmooth)
2871 mergedQualifier = EvqSmoothIn;
2872 else if(interpolationQualifier == EvqFlat)
2873 mergedQualifier = EvqFlatIn;
2874 else UNREACHABLE(interpolationQualifier);
2876 else if(storageQualifier == EvqCentroidIn) {
2877 if(interpolationQualifier == EvqSmooth)
2878 mergedQualifier = EvqCentroidIn;
2879 else if(interpolationQualifier == EvqFlat)
2880 mergedQualifier = EvqFlatIn;
2881 else UNREACHABLE(interpolationQualifier);
2883 else if(storageQualifier == EvqVertexOut) {
2884 if(interpolationQualifier == EvqSmooth)
2885 mergedQualifier = EvqSmoothOut;
2886 else if(interpolationQualifier == EvqFlat)
2887 mergedQualifier = EvqFlatOut;
2888 else UNREACHABLE(interpolationQualifier);
2890 else if(storageQualifier == EvqCentroidOut) {
2891 if(interpolationQualifier == EvqSmooth)
2892 mergedQualifier = EvqCentroidOut;
2893 else if(interpolationQualifier == EvqFlat)
2894 mergedQualifier = EvqFlatOut;
2895 else UNREACHABLE(interpolationQualifier);
2898 error(interpolationLoc, "interpolation qualifier requires a fragment 'in' or vertex 'out' storage qualifier", getQualifierString(interpolationQualifier));
2901 mergedQualifier = storageQualifier;
2905 type.setBasic(EbtVoid, mergedQualifier, storageLoc);
2909 TFieldList *TParseContext::addStructDeclaratorList(const TPublicType &typeSpecifier, TFieldList *fieldList)
2911 if(voidErrorCheck(typeSpecifier.line, (*fieldList)[0]->name(), typeSpecifier.type))
2916 for(unsigned int i = 0; i < fieldList->size(); ++i)
2919 // Careful not to replace already known aspects of type, like array-ness
2921 TType *type = (*fieldList)[i]->type();
2922 type->setBasicType(typeSpecifier.type);
2923 type->setNominalSize(typeSpecifier.primarySize);
2924 type->setSecondarySize(typeSpecifier.secondarySize);
2925 type->setPrecision(typeSpecifier.precision);
2926 type->setQualifier(typeSpecifier.qualifier);
2927 type->setLayoutQualifier(typeSpecifier.layoutQualifier);
2929 // don't allow arrays of arrays
2932 if(arrayTypeErrorCheck(typeSpecifier.line, typeSpecifier))
2935 if(typeSpecifier.array)
2936 type->setArraySize(typeSpecifier.arraySize);
2937 if(typeSpecifier.userDef)
2939 type->setStruct(typeSpecifier.userDef->getStruct());
2942 if(structNestingErrorCheck(typeSpecifier.line, *(*fieldList)[i]))
2951 TPublicType TParseContext::addStructure(const TSourceLoc &structLine, const TSourceLoc &nameLine,
2952 const TString *structName, TFieldList *fieldList)
2954 TStructure *structure = new TStructure(structName, fieldList);
2955 TType *structureType = new TType(structure);
2957 // Store a bool in the struct if we're at global scope, to allow us to
2958 // skip the local struct scoping workaround in HLSL.
2959 structure->setUniqueId(TSymbolTableLevel::nextUniqueId());
2960 structure->setAtGlobalScope(symbolTable.atGlobalLevel());
2962 if(!structName->empty())
2964 if(reservedErrorCheck(nameLine, *structName))
2968 TVariable *userTypeDef = new TVariable(structName, *structureType, true);
2969 if(!symbolTable.declare(*userTypeDef))
2971 error(nameLine, "redefinition", structName->c_str(), "struct");
2976 // ensure we do not specify any storage qualifiers on the struct members
2977 for(unsigned int typeListIndex = 0; typeListIndex < fieldList->size(); typeListIndex++)
2979 const TField &field = *(*fieldList)[typeListIndex];
2980 const TQualifier qualifier = field.type()->getQualifier();
2987 error(field.line(), "invalid qualifier on struct member", getQualifierString(qualifier));
2993 TPublicType publicType;
2994 publicType.setBasic(EbtStruct, EvqTemporary, structLine);
2995 publicType.userDef = structureType;
2996 exitStructDeclaration();
3001 bool TParseContext::enterStructDeclaration(const TSourceLoc &line, const TString& identifier)
3003 ++mStructNestingLevel;
3005 // Embedded structure definitions are not supported per GLSL ES spec.
3006 // They aren't allowed in GLSL either, but we need to detect this here
3007 // so we don't rely on the GLSL compiler to catch it.
3008 if (mStructNestingLevel > 1) {
3009 error(line, "", "Embedded struct definitions are not allowed");
3016 void TParseContext::exitStructDeclaration()
3018 --mStructNestingLevel;
3021 bool TParseContext::structNestingErrorCheck(const TSourceLoc &line, const TField &field)
3023 static const int kWebGLMaxStructNesting = 4;
3025 if(field.type()->getBasicType() != EbtStruct)
3030 // We're already inside a structure definition at this point, so add
3031 // one to the field's struct nesting.
3032 if(1 + field.type()->getDeepestStructNesting() > kWebGLMaxStructNesting)
3034 std::stringstream reasonStream;
3035 reasonStream << "Reference of struct type "
3036 << field.type()->getStruct()->name().c_str()
3037 << " exceeds maximum allowed nesting level of "
3038 << kWebGLMaxStructNesting;
3039 std::string reason = reasonStream.str();
3040 error(line, reason.c_str(), field.name().c_str(), "");
3047 TIntermTyped *TParseContext::createUnaryMath(TOperator op, TIntermTyped *child, const TSourceLoc &loc, const TType *funcReturnType)
3049 if(child == nullptr)
3057 if(child->getBasicType() != EbtBool ||
3058 child->isMatrix() ||
3066 if((child->getBasicType() != EbtInt && child->getBasicType() != EbtUInt) ||
3067 child->isMatrix() ||
3073 case EOpPostIncrement:
3074 case EOpPreIncrement:
3075 case EOpPostDecrement:
3076 case EOpPreDecrement:
3078 if(child->getBasicType() == EbtStruct ||
3079 child->getBasicType() == EbtBool ||
3084 // Operators for built-ins are already type checked against their prototype.
3089 return intermediate.addUnaryMath(op, child, loc, funcReturnType);
3092 TIntermTyped *TParseContext::addUnaryMath(TOperator op, TIntermTyped *child, const TSourceLoc &loc)
3094 TIntermTyped *node = createUnaryMath(op, child, loc, nullptr);
3097 unaryOpError(loc, getOperatorString(op), child->getCompleteString());
3104 TIntermTyped *TParseContext::addUnaryMathLValue(TOperator op, TIntermTyped *child, const TSourceLoc &loc)
3106 if(lValueErrorCheck(loc, getOperatorString(op), child))
3108 return addUnaryMath(op, child, loc);
3111 bool TParseContext::binaryOpCommonCheck(TOperator op, TIntermTyped *left, TIntermTyped *right, const TSourceLoc &loc)
3113 if(left->isArray() || right->isArray())
3115 if(mShaderVersion < 300)
3117 error(loc, "Invalid operation for arrays", getOperatorString(op));
3121 if(left->isArray() != right->isArray())
3123 error(loc, "array / non-array mismatch", getOperatorString(op));
3135 error(loc, "Invalid operation for arrays", getOperatorString(op));
3138 // At this point, size of implicitly sized arrays should be resolved.
3139 if(left->getArraySize() != right->getArraySize())
3141 error(loc, "array size mismatch", getOperatorString(op));
3146 // Check ops which require integer / ivec parameters
3147 bool isBitShift = false;
3150 case EOpBitShiftLeft:
3151 case EOpBitShiftRight:
3152 case EOpBitShiftLeftAssign:
3153 case EOpBitShiftRightAssign:
3154 // Unsigned can be bit-shifted by signed and vice versa, but we need to
3155 // check that the basic type is an integer type.
3157 if(!IsInteger(left->getBasicType()) || !IsInteger(right->getBasicType()))
3165 case EOpBitwiseAndAssign:
3166 case EOpBitwiseXorAssign:
3167 case EOpBitwiseOrAssign:
3168 // It is enough to check the type of only one operand, since later it
3169 // is checked that the operand types match.
3170 if(!IsInteger(left->getBasicType()))
3179 // GLSL ES 1.00 and 3.00 do not support implicit type casting.
3180 // So the basic type should usually match.
3181 if(!isBitShift && left->getBasicType() != right->getBasicType())
3186 // Check that type sizes match exactly on ops that require that.
3187 // Also check restrictions for structs that contain arrays or samplers.
3194 // ESSL 1.00 sections 5.7, 5.8, 5.9
3195 if(mShaderVersion < 300 && left->getType().isStructureContainingArrays())
3197 error(loc, "undefined operation for structs containing arrays", getOperatorString(op));
3200 // Samplers as l-values are disallowed also in ESSL 3.00, see section 4.1.7,
3201 // we interpret the spec so that this extends to structs containing samplers,
3202 // similarly to ESSL 1.00 spec.
3203 if((mShaderVersion < 300 || op == EOpAssign || op == EOpInitialize) &&
3204 left->getType().isStructureContainingSamplers())
3206 error(loc, "undefined operation for structs containing samplers", getOperatorString(op));
3210 case EOpGreaterThan:
3211 case EOpLessThanEqual:
3212 case EOpGreaterThanEqual:
3213 if((left->getNominalSize() != right->getNominalSize()) ||
3214 (left->getSecondarySize() != right->getSecondarySize()))
3225 TIntermSwitch *TParseContext::addSwitch(TIntermTyped *init, TIntermAggregate *statementList, const TSourceLoc &loc)
3227 TBasicType switchType = init->getBasicType();
3228 if((switchType != EbtInt && switchType != EbtUInt) ||
3233 error(init->getLine(), "init-expression in a switch statement must be a scalar integer", "switch");
3240 if(!ValidateSwitch::validate(switchType, this, statementList, loc))
3247 TIntermSwitch *node = intermediate.addSwitch(init, statementList, loc);
3250 error(loc, "erroneous switch statement", "switch");
3257 TIntermCase *TParseContext::addCase(TIntermTyped *condition, const TSourceLoc &loc)
3259 if(mSwitchNestingLevel == 0)
3261 error(loc, "case labels need to be inside switch statements", "case");
3265 if(condition == nullptr)
3267 error(loc, "case label must have a condition", "case");
3271 if((condition->getBasicType() != EbtInt && condition->getBasicType() != EbtUInt) ||
3272 condition->isMatrix() ||
3273 condition->isArray() ||
3274 condition->isVector())
3276 error(condition->getLine(), "case label must be a scalar integer", "case");
3279 TIntermConstantUnion *conditionConst = condition->getAsConstantUnion();
3280 if(conditionConst == nullptr)
3282 error(condition->getLine(), "case label must be constant", "case");
3285 TIntermCase *node = intermediate.addCase(condition, loc);
3288 error(loc, "erroneous case statement", "case");
3295 TIntermCase *TParseContext::addDefault(const TSourceLoc &loc)
3297 if(mSwitchNestingLevel == 0)
3299 error(loc, "default labels need to be inside switch statements", "default");
3303 TIntermCase *node = intermediate.addCase(nullptr, loc);
3306 error(loc, "erroneous default statement", "default");
3312 TIntermTyped *TParseContext::createAssign(TOperator op, TIntermTyped *left, TIntermTyped *right, const TSourceLoc &loc)
3314 if(binaryOpCommonCheck(op, left, right, loc))
3316 return intermediate.addAssign(op, left, right, loc);
3321 TIntermTyped *TParseContext::addAssign(TOperator op, TIntermTyped *left, TIntermTyped *right, const TSourceLoc &loc)
3323 TIntermTyped *node = createAssign(op, left, right, loc);
3326 assignError(loc, "assign", left->getCompleteString(), right->getCompleteString());
3333 TIntermTyped *TParseContext::addBinaryMathInternal(TOperator op, TIntermTyped *left, TIntermTyped *right,
3334 const TSourceLoc &loc)
3336 if(!binaryOpCommonCheck(op, left, right, loc))
3345 case EOpGreaterThan:
3346 case EOpLessThanEqual:
3347 case EOpGreaterThanEqual:
3348 ASSERT(!left->isArray() && !right->isArray());
3349 if(left->isMatrix() || left->isVector() ||
3350 left->getBasicType() == EbtStruct)
3358 ASSERT(!left->isArray() && !right->isArray());
3359 if(left->getBasicType() != EbtBool ||
3360 left->isMatrix() || left->isVector())
3369 ASSERT(!left->isArray() && !right->isArray());
3370 if(left->getBasicType() == EbtStruct || left->getBasicType() == EbtBool)
3376 ASSERT(!left->isArray() && !right->isArray());
3377 // Note that this is only for the % operator, not for mod()
3378 if(left->getBasicType() == EbtStruct || left->getBasicType() == EbtBool || left->getBasicType() == EbtFloat)
3383 // Note that for bitwise ops, type checking is done in promote() to
3384 // share code between ops and compound assignment
3389 return intermediate.addBinaryMath(op, left, right, loc);
3392 TIntermTyped *TParseContext::addBinaryMath(TOperator op, TIntermTyped *left, TIntermTyped *right, const TSourceLoc &loc)
3394 TIntermTyped *node = addBinaryMathInternal(op, left, right, loc);
3397 binaryOpError(loc, getOperatorString(op), left->getCompleteString(), right->getCompleteString());
3404 TIntermTyped *TParseContext::addBinaryMathBooleanResult(TOperator op, TIntermTyped *left, TIntermTyped *right, const TSourceLoc &loc)
3406 TIntermTyped *node = addBinaryMathInternal(op, left, right, loc);
3409 binaryOpError(loc, getOperatorString(op), left->getCompleteString(), right->getCompleteString());
3411 ConstantUnion *unionArray = new ConstantUnion[1];
3412 unionArray->setBConst(false);
3413 return intermediate.addConstantUnion(unionArray, TType(EbtBool, EbpUndefined, EvqConstExpr), loc);
3418 TIntermBranch *TParseContext::addBranch(TOperator op, const TSourceLoc &loc)
3423 if(mLoopNestingLevel <= 0)
3425 error(loc, "continue statement only allowed in loops", "");
3430 if(mLoopNestingLevel <= 0 && mSwitchNestingLevel <= 0)
3432 error(loc, "break statement only allowed in loops and switch statements", "");
3437 if(mCurrentFunctionType->getBasicType() != EbtVoid)
3439 error(loc, "non-void function must return a value", "return");
3444 // No checks for discard
3447 return intermediate.addBranch(op, loc);
3450 TIntermBranch *TParseContext::addBranch(TOperator op, TIntermTyped *returnValue, const TSourceLoc &loc)
3452 ASSERT(op == EOpReturn);
3453 mFunctionReturnsValue = true;
3454 if(mCurrentFunctionType->getBasicType() == EbtVoid)
3456 error(loc, "void function cannot return a value", "return");
3459 else if(*mCurrentFunctionType != returnValue->getType())
3461 error(loc, "function return is not matching type:", "return");
3464 return intermediate.addBranch(op, returnValue, loc);
3467 TIntermTyped *TParseContext::addFunctionCallOrMethod(TFunction *fnCall, TIntermNode *paramNode, TIntermNode *thisNode, const TSourceLoc &loc, bool *fatalError)
3469 *fatalError = false;
3470 TOperator op = fnCall->getBuiltInOp();
3471 TIntermTyped *callNode = nullptr;
3473 if(thisNode != nullptr)
3475 ConstantUnion *unionArray = new ConstantUnion[1];
3477 TIntermTyped *typedThis = thisNode->getAsTyped();
3478 if(fnCall->getName() != "length")
3480 error(loc, "invalid method", fnCall->getName().c_str());
3483 else if(paramNode != nullptr)
3485 error(loc, "method takes no parameters", "length");
3488 else if(typedThis == nullptr || !typedThis->isArray())
3490 error(loc, "length can only be called on arrays", "length");
3495 arraySize = typedThis->getArraySize();
3496 if(typedThis->getAsSymbolNode() == nullptr)
3498 // This code path can be hit with expressions like these:
3500 // (func()).length()
3501 // (int[3](0, 1, 2)).length()
3502 // ESSL 3.00 section 5.9 defines expressions so that this is not actually a valid expression.
3503 // It allows "An array name with the length method applied" in contrast to GLSL 4.4 spec section 5.9
3504 // which allows "An array, vector or matrix expression with the length method applied".
3505 error(loc, "length can only be called on array names, not on array expressions", "length");
3509 unionArray->setIConst(arraySize);
3510 callNode = intermediate.addConstantUnion(unionArray, TType(EbtInt, EbpUndefined, EvqConstExpr), loc);
3512 else if(op != EOpNull)
3515 // Then this should be a constructor.
3516 // Don't go through the symbol table for constructors.
3517 // Their parameters will be verified algorithmically.
3519 TType type(EbtVoid, EbpUndefined); // use this to get the type back
3520 if(!constructorErrorCheck(loc, paramNode, *fnCall, op, &type))
3523 // It's a constructor, of type 'type'.
3525 callNode = addConstructor(paramNode, &type, op, fnCall, loc);
3528 if(callNode == nullptr)
3531 callNode = intermediate.setAggregateOperator(nullptr, op, loc);
3537 // Not a constructor. Find it in the symbol table.
3539 const TFunction *fnCandidate;
3541 fnCandidate = findFunction(loc, fnCall, &builtIn);
3545 // A declared function.
3547 if(builtIn && !fnCandidate->getExtension().empty() &&
3548 extensionErrorCheck(loc, fnCandidate->getExtension()))
3552 op = fnCandidate->getBuiltInOp();
3553 if(builtIn && op != EOpNull)
3556 // A function call mapped to a built-in operation.
3558 if(fnCandidate->getParamCount() == 1)
3561 // Treat it like a built-in unary operator.
3563 callNode = createUnaryMath(op, paramNode->getAsTyped(), loc, &fnCandidate->getReturnType());
3564 if(callNode == nullptr)
3566 std::stringstream extraInfoStream;
3567 extraInfoStream << "built in unary operator function. Type: "
3568 << static_cast<TIntermTyped*>(paramNode)->getCompleteString();
3569 std::string extraInfo = extraInfoStream.str();
3570 error(paramNode->getLine(), " wrong operand type", "Internal Error", extraInfo.c_str());
3577 TIntermAggregate *aggregate = intermediate.setAggregateOperator(paramNode, op, loc);
3578 aggregate->setType(fnCandidate->getReturnType());
3580 // Some built-in functions have out parameters too.
3581 functionCallLValueErrorCheck(fnCandidate, aggregate);
3583 callNode = aggregate;
3585 if(fnCandidate->getParamCount() == 2)
3587 TIntermSequence ¶meters = paramNode->getAsAggregate()->getSequence();
3588 TIntermTyped *left = parameters[0]->getAsTyped();
3589 TIntermTyped *right = parameters[1]->getAsTyped();
3591 TIntermConstantUnion *leftTempConstant = left->getAsConstantUnion();
3592 TIntermConstantUnion *rightTempConstant = right->getAsConstantUnion();
3593 if (leftTempConstant && rightTempConstant)
3595 TIntermTyped *typedReturnNode = leftTempConstant->fold(op, rightTempConstant, infoSink());
3599 callNode = typedReturnNode;
3607 // This is a real function call
3609 TIntermAggregate *aggregate = intermediate.setAggregateOperator(paramNode, EOpFunctionCall, loc);
3610 aggregate->setType(fnCandidate->getReturnType());
3612 // this is how we know whether the given function is a builtIn function or a user defined function
3613 // if builtIn == false, it's a userDefined -> could be an overloaded builtIn function also
3614 // if builtIn == true, it's definitely a builtIn function with EOpNull
3616 aggregate->setUserDefined();
3617 aggregate->setName(fnCandidate->getMangledName());
3619 callNode = aggregate;
3621 functionCallLValueErrorCheck(fnCandidate, aggregate);
3626 // error message was put out by findFunction()
3627 // Put on a dummy node for error recovery
3628 ConstantUnion *unionArray = new ConstantUnion[1];
3629 unionArray->setFConst(0.0f);
3630 callNode = intermediate.addConstantUnion(unionArray, TType(EbtFloat, EbpUndefined, EvqConstExpr), loc);
3638 TIntermTyped *TParseContext::addTernarySelection(TIntermTyped *cond, TIntermTyped *trueBlock, TIntermTyped *falseBlock, const TSourceLoc &loc)
3640 if(boolErrorCheck(loc, cond))
3643 if(trueBlock->getType() != falseBlock->getType())
3645 binaryOpError(loc, ":", trueBlock->getCompleteString(), falseBlock->getCompleteString());
3649 // ESSL1 sections 5.2 and 5.7:
3650 // ESSL3 section 5.7:
3651 // Ternary operator is not among the operators allowed for structures/arrays.
3652 if(trueBlock->isArray() || trueBlock->getBasicType() == EbtStruct)
3654 error(loc, "ternary operator is not allowed for structures or arrays", ":");
3658 return intermediate.addSelection(cond, trueBlock, falseBlock, loc);
3662 // Parse an array of strings using yyparse.
3664 // Returns 0 for success.
3666 int PaParseStrings(int count, const char* const string[], const int length[],
3667 TParseContext* context) {
3668 if ((count == 0) || (string == NULL))
3671 if (glslang_initialize(context))
3674 int error = glslang_scan(count, string, length, context);
3676 error = glslang_parse(context);
3678 glslang_finalize(context);
3680 return (error == 0) && (context->numErrors() == 0) ? 0 : 1;