1 // Copyright 2016 The SwiftShader Authors. All Rights Reserved.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 #include "ParseHelper.h"
21 #include "preprocessor/SourceLocation.h"
22 #include "ValidateGlobalInitializer.h"
23 #include "ValidateSwitch.h"
25 ///////////////////////////////////////////////////////////////////////
27 // Sub- vector and matrix fields
29 ////////////////////////////////////////////////////////////////////////
33 bool IsVaryingOut(TQualifier qualifier)
50 bool IsVaryingIn(TQualifier qualifier)
67 bool IsVarying(TQualifier qualifier)
69 return IsVaryingIn(qualifier) || IsVaryingOut(qualifier);
72 bool IsAssignment(TOperator op)
76 case EOpPostIncrement:
77 case EOpPostDecrement:
84 case EOpVectorTimesMatrixAssign:
85 case EOpVectorTimesScalarAssign:
86 case EOpMatrixTimesScalarAssign:
87 case EOpMatrixTimesMatrixAssign:
90 case EOpBitShiftLeftAssign:
91 case EOpBitShiftRightAssign:
92 case EOpBitwiseAndAssign:
93 case EOpBitwiseXorAssign:
94 case EOpBitwiseOrAssign:
103 // Look at a '.' field selector string and change it into offsets
106 bool TParseContext::parseVectorFields(const TString& compString, int vecSize, TVectorFields& fields, const TSourceLoc &line)
108 fields.num = (int) compString.size();
109 if (fields.num > 4) {
110 error(line, "illegal vector field selection", compString.c_str());
120 for (int i = 0; i < fields.num; ++i) {
121 switch (compString[i]) {
123 fields.offsets[i] = 0;
127 fields.offsets[i] = 0;
131 fields.offsets[i] = 0;
135 fields.offsets[i] = 1;
139 fields.offsets[i] = 1;
143 fields.offsets[i] = 1;
147 fields.offsets[i] = 2;
151 fields.offsets[i] = 2;
155 fields.offsets[i] = 2;
159 fields.offsets[i] = 3;
163 fields.offsets[i] = 3;
167 fields.offsets[i] = 3;
171 error(line, "illegal vector field selection", compString.c_str());
176 for (int i = 0; i < fields.num; ++i) {
177 if (fields.offsets[i] >= vecSize) {
178 error(line, "vector field selection out of range", compString.c_str());
183 if (fieldSet[i] != fieldSet[i-1]) {
184 error(line, "illegal - vector component fields not from the same set", compString.c_str());
195 // Look at a '.' field selector string and change it into offsets
198 bool TParseContext::parseMatrixFields(const TString& compString, int matCols, int matRows, TMatrixFields& fields, const TSourceLoc &line)
200 fields.wholeRow = false;
201 fields.wholeCol = false;
205 if (compString.size() != 2) {
206 error(line, "illegal length of matrix field selection", compString.c_str());
210 if (compString[0] == '_') {
211 if (compString[1] < '0' || compString[1] > '3') {
212 error(line, "illegal matrix field selection", compString.c_str());
215 fields.wholeCol = true;
216 fields.col = compString[1] - '0';
217 } else if (compString[1] == '_') {
218 if (compString[0] < '0' || compString[0] > '3') {
219 error(line, "illegal matrix field selection", compString.c_str());
222 fields.wholeRow = true;
223 fields.row = compString[0] - '0';
225 if (compString[0] < '0' || compString[0] > '3' ||
226 compString[1] < '0' || compString[1] > '3') {
227 error(line, "illegal matrix field selection", compString.c_str());
230 fields.row = compString[0] - '0';
231 fields.col = compString[1] - '0';
234 if (fields.row >= matRows || fields.col >= matCols) {
235 error(line, "matrix field selection out of range", compString.c_str());
242 ///////////////////////////////////////////////////////////////////////
246 ////////////////////////////////////////////////////////////////////////
249 // Track whether errors have occurred.
251 void TParseContext::recover()
256 // Used by flex/bison to output all syntax and parsing errors.
258 void TParseContext::error(const TSourceLoc& loc,
259 const char* reason, const char* token,
260 const char* extraInfo)
262 pp::SourceLocation srcLoc(loc.first_file, loc.first_line);
263 mDiagnostics.writeInfo(pp::Diagnostics::PP_ERROR,
264 srcLoc, reason, token, extraInfo);
268 void TParseContext::warning(const TSourceLoc& loc,
269 const char* reason, const char* token,
270 const char* extraInfo) {
271 pp::SourceLocation srcLoc(loc.first_file, loc.first_line);
272 mDiagnostics.writeInfo(pp::Diagnostics::PP_WARNING,
273 srcLoc, reason, token, extraInfo);
276 void TParseContext::trace(const char* str)
278 mDiagnostics.writeDebug(str);
282 // Same error message for all places assignments don't work.
284 void TParseContext::assignError(const TSourceLoc &line, const char* op, TString left, TString right)
286 std::stringstream extraInfoStream;
287 extraInfoStream << "cannot convert from '" << right << "' to '" << left << "'";
288 std::string extraInfo = extraInfoStream.str();
289 error(line, "", op, extraInfo.c_str());
293 // Same error message for all places unary operations don't work.
295 void TParseContext::unaryOpError(const TSourceLoc &line, const char* op, TString operand)
297 std::stringstream extraInfoStream;
298 extraInfoStream << "no operation '" << op << "' exists that takes an operand of type " << operand
299 << " (or there is no acceptable conversion)";
300 std::string extraInfo = extraInfoStream.str();
301 error(line, " wrong operand type", op, extraInfo.c_str());
305 // Same error message for all binary operations don't work.
307 void TParseContext::binaryOpError(const TSourceLoc &line, const char* op, TString left, TString right)
309 std::stringstream extraInfoStream;
310 extraInfoStream << "no operation '" << op << "' exists that takes a left-hand operand of type '" << left
311 << "' and a right operand of type '" << right << "' (or there is no acceptable conversion)";
312 std::string extraInfo = extraInfoStream.str();
313 error(line, " wrong operand types ", op, extraInfo.c_str());
316 bool TParseContext::precisionErrorCheck(const TSourceLoc &line, TPrecision precision, TBasicType type){
317 if (!mChecksPrecisionErrors)
321 if( precision == EbpUndefined ){
322 error( line, "No precision specified for (float)", "" );
327 if( precision == EbpUndefined ){
328 error( line, "No precision specified (int)", "" );
339 // Both test and if necessary, spit out an error, to see if the node is really
340 // an l-value that can be operated on this way.
342 // Returns true if the was an error.
344 bool TParseContext::lValueErrorCheck(const TSourceLoc &line, const char* op, TIntermTyped* node)
346 TIntermSymbol* symNode = node->getAsSymbolNode();
347 TIntermBinary* binaryNode = node->getAsBinaryNode();
352 switch(binaryNode->getOp()) {
354 case EOpIndexIndirect:
355 case EOpIndexDirectStruct:
356 case EOpIndexDirectInterfaceBlock:
357 return lValueErrorCheck(line, op, binaryNode->getLeft());
358 case EOpVectorSwizzle:
359 errorReturn = lValueErrorCheck(line, op, binaryNode->getLeft());
361 int offset[4] = {0,0,0,0};
363 TIntermTyped* rightNode = binaryNode->getRight();
364 TIntermAggregate *aggrNode = rightNode->getAsAggregate();
366 for (TIntermSequence::iterator p = aggrNode->getSequence().begin();
367 p != aggrNode->getSequence().end(); p++) {
368 int value = (*p)->getAsTyped()->getAsConstantUnion()->getIConst(0);
370 if (offset[value] > 1) {
371 error(line, " l-value of swizzle cannot have duplicate components", op);
382 error(line, " l-value required", op);
388 const char* symbol = 0;
390 symbol = symNode->getSymbol().c_str();
392 const char* message = 0;
393 switch (node->getQualifier()) {
394 case EvqConstExpr: message = "can't modify a const"; break;
395 case EvqConstReadOnly: message = "can't modify a const"; break;
396 case EvqAttribute: message = "can't modify an attribute"; break;
397 case EvqFragmentIn: message = "can't modify an input"; break;
398 case EvqVertexIn: message = "can't modify an input"; break;
399 case EvqUniform: message = "can't modify a uniform"; break;
403 case EvqVaryingIn: message = "can't modify a varying"; break;
404 case EvqInput: message = "can't modify an input"; break;
405 case EvqFragCoord: message = "can't modify gl_FragCoord"; break;
406 case EvqFrontFacing: message = "can't modify gl_FrontFacing"; break;
407 case EvqPointCoord: message = "can't modify gl_PointCoord"; break;
408 case EvqInstanceID: message = "can't modify gl_InstanceID"; break;
412 // Type that can't be written to?
414 if(IsSampler(node->getBasicType()))
416 message = "can't modify a sampler";
418 else if(node->getBasicType() == EbtVoid)
420 message = "can't modify void";
424 if (message == 0 && binaryNode == 0 && symNode == 0) {
425 error(line, " l-value required", op);
432 // Everything else is okay, no error.
438 // If we get here, we have an error and a message.
441 std::stringstream extraInfoStream;
442 extraInfoStream << "\"" << symbol << "\" (" << message << ")";
443 std::string extraInfo = extraInfoStream.str();
444 error(line, " l-value required", op, extraInfo.c_str());
447 std::stringstream extraInfoStream;
448 extraInfoStream << "(" << message << ")";
449 std::string extraInfo = extraInfoStream.str();
450 error(line, " l-value required", op, extraInfo.c_str());
457 // Both test, and if necessary spit out an error, to see if the node is really
460 // Returns true if the was an error.
462 bool TParseContext::constErrorCheck(TIntermTyped* node)
464 if (node->getQualifier() == EvqConstExpr)
467 error(node->getLine(), "constant expression required", "");
473 // Both test, and if necessary spit out an error, to see if the node is really
476 // Returns true if the was an error.
478 bool TParseContext::integerErrorCheck(TIntermTyped* node, const char* token)
480 if (node->isScalarInt())
483 error(node->getLine(), "integer expression required", token);
489 // Both test, and if necessary spit out an error, to see if we are currently
492 // Returns true if the was an error.
494 bool TParseContext::globalErrorCheck(const TSourceLoc &line, bool global, const char* token)
499 error(line, "only allowed at global scope", token);
505 // For now, keep it simple: if it starts "gl_", it's reserved, independent
506 // of scope. Except, if the symbol table is at the built-in push-level,
507 // which is when we are parsing built-ins.
508 // Also checks for "webgl_" and "_webgl_" reserved identifiers if parsing a
511 // Returns true if there was an error.
513 bool TParseContext::reservedErrorCheck(const TSourceLoc &line, const TString& identifier)
515 static const char* reservedErrMsg = "reserved built-in name";
516 if (!symbolTable.atBuiltInLevel()) {
517 if (identifier.compare(0, 3, "gl_") == 0) {
518 error(line, reservedErrMsg, "gl_");
521 if (identifier.find("__") != TString::npos) {
522 error(line, "identifiers containing two consecutive underscores (__) are reserved as possible future keywords", identifier.c_str());
531 // Make sure there is enough data provided to the constructor to build
532 // something of the type of the constructor. Also returns the type of
535 // Returns true if there was an error in construction.
537 bool TParseContext::constructorErrorCheck(const TSourceLoc &line, TIntermNode* node, TFunction& function, TOperator op, TType* type)
539 *type = function.getReturnType();
541 bool constructingMatrix = false;
543 case EOpConstructMat2:
544 case EOpConstructMat2x3:
545 case EOpConstructMat2x4:
546 case EOpConstructMat3x2:
547 case EOpConstructMat3:
548 case EOpConstructMat3x4:
549 case EOpConstructMat4x2:
550 case EOpConstructMat4x3:
551 case EOpConstructMat4:
552 constructingMatrix = true;
559 // Note: It's okay to have too many components available, but not okay to have unused
560 // arguments. 'full' will go to true when enough args have been seen. If we loop
561 // again, there is an extra argument, so 'overfull' will become true.
566 bool overFull = false;
567 bool matrixInMatrix = false;
568 bool arrayArg = false;
569 for (size_t i = 0; i < function.getParamCount(); ++i) {
570 const TParameter& param = function.getParam(i);
571 size += param.type->getObjectSize();
573 if (constructingMatrix && param.type->isMatrix())
574 matrixInMatrix = true;
577 if (op != EOpConstructStruct && !type->isArray() && size >= type->getObjectSize())
579 if (param.type->isArray())
583 if(type->isArray()) {
584 if(type->getArraySize() == 0) {
585 type->setArraySize(function.getParamCount());
586 } else if(type->getArraySize() != (int)function.getParamCount()) {
587 error(line, "array constructor needs one argument per array element", "constructor");
592 if (arrayArg && op != EOpConstructStruct) {
593 error(line, "constructing from a non-dereferenced array", "constructor");
597 if (matrixInMatrix && !type->isArray()) {
598 if (function.getParamCount() != 1) {
599 error(line, "constructing matrix from matrix can only take one argument", "constructor");
605 error(line, "too many arguments", "constructor");
609 if (op == EOpConstructStruct && !type->isArray() && type->getStruct()->fields().size() != function.getParamCount()) {
610 error(line, "Number of constructor parameters does not match the number of structure fields", "constructor");
614 if (!type->isMatrix() || !matrixInMatrix) {
615 if ((op != EOpConstructStruct && size != 1 && size < type->getObjectSize()) ||
616 (op == EOpConstructStruct && size < type->getObjectSize())) {
617 error(line, "not enough data provided for construction", "constructor");
622 TIntermTyped *typed = node ? node->getAsTyped() : 0;
624 error(line, "constructor argument does not have a type", "constructor");
627 if (op != EOpConstructStruct && IsSampler(typed->getBasicType())) {
628 error(line, "cannot convert a sampler", "constructor");
631 if (typed->getBasicType() == EbtVoid) {
632 error(line, "cannot convert a void", "constructor");
639 // This function checks to see if a void variable has been declared and raise an error message for such a case
641 // returns true in case of an error
643 bool TParseContext::voidErrorCheck(const TSourceLoc &line, const TString& identifier, const TBasicType& type)
645 if(type == EbtVoid) {
646 error(line, "illegal use of type 'void'", identifier.c_str());
653 // This function checks to see if the node (for the expression) contains a scalar boolean expression or not
655 // returns true in case of an error
657 bool TParseContext::boolErrorCheck(const TSourceLoc &line, const TIntermTyped* type)
659 if (type->getBasicType() != EbtBool || type->isArray() || type->isMatrix() || type->isVector()) {
660 error(line, "boolean expression expected", "");
667 // This function checks to see if the node (for the expression) contains a scalar boolean expression or not
669 // returns true in case of an error
671 bool TParseContext::boolErrorCheck(const TSourceLoc &line, const TPublicType& pType)
673 if (pType.type != EbtBool || pType.array || (pType.primarySize > 1) || (pType.secondarySize > 1)) {
674 error(line, "boolean expression expected", "");
681 bool TParseContext::samplerErrorCheck(const TSourceLoc &line, const TPublicType& pType, const char* reason)
683 if (pType.type == EbtStruct) {
684 if (containsSampler(*pType.userDef)) {
685 error(line, reason, getBasicString(pType.type), "(structure contains a sampler)");
691 } else if (IsSampler(pType.type)) {
692 error(line, reason, getBasicString(pType.type));
700 bool TParseContext::structQualifierErrorCheck(const TSourceLoc &line, const TPublicType& pType)
702 switch(pType.qualifier)
715 if(pType.type == EbtStruct)
717 error(line, "cannot be used with a structure", getQualifierString(pType.qualifier));
726 if (pType.qualifier != EvqUniform && samplerErrorCheck(line, pType, "samplers must be uniform"))
729 // check for layout qualifier issues
730 if (pType.qualifier != EvqVertexIn && pType.qualifier != EvqFragmentOut &&
731 layoutLocationErrorCheck(line, pType.layoutQualifier))
739 // These checks are common for all declarations starting a declarator list, and declarators that follow an empty
742 bool TParseContext::singleDeclarationErrorCheck(const TPublicType &publicType, const TSourceLoc &identifierLocation)
744 switch(publicType.qualifier)
751 if(publicType.type == EbtStruct)
753 error(identifierLocation, "cannot be used with a structure",
754 getQualifierString(publicType.qualifier));
761 if(publicType.qualifier != EvqUniform && samplerErrorCheck(identifierLocation, publicType,
762 "samplers must be uniform"))
767 // check for layout qualifier issues
768 const TLayoutQualifier layoutQualifier = publicType.layoutQualifier;
770 if(layoutQualifier.matrixPacking != EmpUnspecified)
772 error(identifierLocation, "layout qualifier", getMatrixPackingString(layoutQualifier.matrixPacking),
773 "only valid for interface blocks");
777 if(layoutQualifier.blockStorage != EbsUnspecified)
779 error(identifierLocation, "layout qualifier", getBlockStorageString(layoutQualifier.blockStorage),
780 "only valid for interface blocks");
784 if(publicType.qualifier != EvqVertexIn && publicType.qualifier != EvqFragmentOut &&
785 layoutLocationErrorCheck(identifierLocation, publicType.layoutQualifier))
793 bool TParseContext::layoutLocationErrorCheck(const TSourceLoc &location, const TLayoutQualifier &layoutQualifier)
795 if(layoutQualifier.location != -1)
797 error(location, "invalid layout qualifier:", "location", "only valid on program inputs and outputs");
804 bool TParseContext::locationDeclaratorListCheck(const TSourceLoc& line, const TPublicType &pType)
806 if(pType.layoutQualifier.location != -1)
808 error(line, "location must only be specified for a single input or output variable", "location");
815 bool TParseContext::parameterSamplerErrorCheck(const TSourceLoc &line, TQualifier qualifier, const TType& type)
817 if ((qualifier == EvqOut || qualifier == EvqInOut) &&
818 type.getBasicType() != EbtStruct && IsSampler(type.getBasicType())) {
819 error(line, "samplers cannot be output parameters", type.getBasicString());
826 bool TParseContext::containsSampler(TType& type)
828 if (IsSampler(type.getBasicType()))
831 if (type.getBasicType() == EbtStruct || type.isInterfaceBlock()) {
832 const TFieldList& fields = type.getStruct()->fields();
833 for(unsigned int i = 0; i < fields.size(); ++i) {
834 if (containsSampler(*fields[i]->type()))
843 // Do size checking for an array type's size.
845 // Returns true if there was an error.
847 bool TParseContext::arraySizeErrorCheck(const TSourceLoc &line, TIntermTyped* expr, int& size)
849 TIntermConstantUnion* constant = expr->getAsConstantUnion();
851 if (expr->getQualifier() != EvqConstExpr || constant == 0 || !constant->isScalarInt())
853 error(line, "array size must be a constant integer expression", "");
857 if (constant->getBasicType() == EbtUInt)
859 unsigned int uintSize = constant->getUConst(0);
860 if (uintSize > static_cast<unsigned int>(std::numeric_limits<int>::max()))
862 error(line, "array size too large", "");
867 size = static_cast<int>(uintSize);
871 size = constant->getIConst(0);
875 error(line, "array size must be non-negative", "");
883 error(line, "array size must be greater than zero", "");
891 // See if this qualifier can be an array.
893 // Returns true if there is an error.
895 bool TParseContext::arrayQualifierErrorCheck(const TSourceLoc &line, TPublicType type)
897 if ((type.qualifier == EvqAttribute) || (type.qualifier == EvqVertexIn) || (type.qualifier == EvqConstExpr && mShaderVersion < 300)) {
898 error(line, "cannot declare arrays of this qualifier", TType(type).getCompleteString().c_str());
906 // See if this type can be an array.
908 // Returns true if there is an error.
910 bool TParseContext::arrayTypeErrorCheck(const TSourceLoc &line, TPublicType type)
913 // Can the type be an array?
916 error(line, "cannot declare arrays of arrays", TType(type).getCompleteString().c_str());
920 // In ESSL1.00 shaders, structs cannot be varying (section 4.3.5). This is checked elsewhere.
921 // In ESSL3.00 shaders, struct inputs/outputs are allowed but not arrays of structs (section 4.3.4).
922 if(mShaderVersion >= 300 && type.type == EbtStruct && IsVarying(type.qualifier))
924 error(line, "cannot declare arrays of structs of this qualifier",
925 TType(type).getCompleteString().c_str());
932 bool TParseContext::arraySetMaxSize(TIntermSymbol *node, TType* type, int size, bool updateFlag, const TSourceLoc &line)
934 bool builtIn = false;
935 TSymbol* symbol = symbolTable.find(node->getSymbol(), mShaderVersion, &builtIn);
937 error(line, " undeclared identifier", node->getSymbol().c_str());
940 TVariable* variable = static_cast<TVariable*>(symbol);
942 type->setArrayInformationType(variable->getArrayInformationType());
943 variable->updateArrayInformationType(type);
945 // special casing to test index value of gl_FragData. If the accessed index is >= gl_MaxDrawBuffers
947 if (node->getSymbol() == "gl_FragData") {
948 TSymbol* fragData = symbolTable.find("gl_MaxDrawBuffers", mShaderVersion, &builtIn);
951 int fragDataValue = static_cast<TVariable*>(fragData)->getConstPointer()[0].getIConst();
952 if (fragDataValue <= size) {
953 error(line, "", "[", "gl_FragData can only have a max array size of up to gl_MaxDrawBuffers");
958 // we dont want to update the maxArraySize when this flag is not set, we just want to include this
959 // node type in the chain of node types so that its updated when a higher maxArraySize comes in.
964 variable->getType().setMaxArraySize(size);
965 type->setMaxArraySize(size);
968 while(tt->getArrayInformationType() != 0) {
969 tt = tt->getArrayInformationType();
970 tt->setMaxArraySize(size);
977 // Enforce non-initializer type/qualifier rules.
979 // Returns true if there was an error.
981 bool TParseContext::nonInitConstErrorCheck(const TSourceLoc &line, TString& identifier, TPublicType& type, bool array)
983 if (type.qualifier == EvqConstExpr)
985 // Make the qualifier make sense.
986 type.qualifier = EvqTemporary;
990 error(line, "arrays may not be declared constant since they cannot be initialized", identifier.c_str());
992 else if (type.isStructureContainingArrays())
994 error(line, "structures containing arrays may not be declared constant since they cannot be initialized", identifier.c_str());
998 error(line, "variables with qualifier 'const' must be initialized", identifier.c_str());
1008 // Do semantic checking for a variable declaration that has no initializer,
1009 // and update the symbol table.
1011 // Returns true if there was an error.
1013 bool TParseContext::nonInitErrorCheck(const TSourceLoc &line, const TString& identifier, TPublicType& type)
1015 if(type.qualifier == EvqConstExpr)
1017 // Make the qualifier make sense.
1018 type.qualifier = EvqTemporary;
1020 // Generate informative error messages for ESSL1.
1021 // In ESSL3 arrays and structures containing arrays can be constant.
1022 if(mShaderVersion < 300 && type.isStructureContainingArrays())
1025 "structures containing arrays may not be declared constant since they cannot be initialized",
1026 identifier.c_str());
1030 error(line, "variables with qualifier 'const' must be initialized", identifier.c_str());
1035 if(type.isUnsizedArray())
1037 error(line, "implicitly sized arrays need to be initialized", identifier.c_str());
1043 // Do some simple checks that are shared between all variable declarations,
1044 // and update the symbol table.
1046 // Returns true if declaring the variable succeeded.
1048 bool TParseContext::declareVariable(const TSourceLoc &line, const TString &identifier, const TType &type,
1049 TVariable **variable)
1051 ASSERT((*variable) == nullptr);
1053 // gl_LastFragData may be redeclared with a new precision qualifier
1054 if(type.isArray() && identifier.compare(0, 15, "gl_LastFragData") == 0)
1056 const TVariable *maxDrawBuffers =
1057 static_cast<const TVariable *>(symbolTable.findBuiltIn("gl_MaxDrawBuffers", mShaderVersion));
1058 if(type.getArraySize() != maxDrawBuffers->getConstPointer()->getIConst())
1060 error(line, "redeclaration of gl_LastFragData with size != gl_MaxDrawBuffers", identifier.c_str());
1065 if(reservedErrorCheck(line, identifier))
1068 (*variable) = new TVariable(&identifier, type);
1069 if(!symbolTable.declare(**variable))
1071 error(line, "redefinition", identifier.c_str());
1073 (*variable) = nullptr;
1077 if(voidErrorCheck(line, identifier, type.getBasicType()))
1083 bool TParseContext::paramErrorCheck(const TSourceLoc &line, TQualifier qualifier, TQualifier paramQualifier, TType* type)
1085 if (qualifier != EvqConstReadOnly && qualifier != EvqTemporary) {
1086 error(line, "qualifier not allowed on function parameter", getQualifierString(qualifier));
1089 if (qualifier == EvqConstReadOnly && paramQualifier != EvqIn) {
1090 error(line, "qualifier not allowed with ", getQualifierString(qualifier), getQualifierString(paramQualifier));
1094 if (qualifier == EvqConstReadOnly)
1095 type->setQualifier(EvqConstReadOnly);
1097 type->setQualifier(paramQualifier);
1102 bool TParseContext::extensionErrorCheck(const TSourceLoc &line, const TString& extension)
1104 const TExtensionBehavior& extBehavior = extensionBehavior();
1105 TExtensionBehavior::const_iterator iter = extBehavior.find(extension.c_str());
1106 if (iter == extBehavior.end()) {
1107 error(line, "extension", extension.c_str(), "is not supported");
1110 // In GLSL ES, an extension's default behavior is "disable".
1111 if (iter->second == EBhDisable || iter->second == EBhUndefined) {
1112 error(line, "extension", extension.c_str(), "is disabled");
1115 if (iter->second == EBhWarn) {
1116 warning(line, "extension", extension.c_str(), "is being used");
1123 bool TParseContext::functionCallLValueErrorCheck(const TFunction *fnCandidate, TIntermAggregate *aggregate)
1125 for(size_t i = 0; i < fnCandidate->getParamCount(); ++i)
1127 TQualifier qual = fnCandidate->getParam(i).type->getQualifier();
1128 if(qual == EvqOut || qual == EvqInOut)
1130 TIntermTyped *node = (aggregate->getSequence())[i]->getAsTyped();
1131 if(lValueErrorCheck(node->getLine(), "assign", node))
1133 error(node->getLine(),
1134 "Constant value cannot be passed for 'out' or 'inout' parameters.", "Error");
1143 void TParseContext::es3InvariantErrorCheck(const TQualifier qualifier, const TSourceLoc &invariantLocation)
1150 case EvqCentroidOut:
1152 case EvqFragmentOut:
1155 error(invariantLocation, "Only out variables can be invariant.", "invariant");
1161 bool TParseContext::supportsExtension(const char* extension)
1163 const TExtensionBehavior& extbehavior = extensionBehavior();
1164 TExtensionBehavior::const_iterator iter = extbehavior.find(extension);
1165 return (iter != extbehavior.end());
1168 void TParseContext::handleExtensionDirective(const TSourceLoc &line, const char* extName, const char* behavior)
1170 pp::SourceLocation loc(line.first_file, line.first_line);
1171 mDirectiveHandler.handleExtension(loc, extName, behavior);
1174 void TParseContext::handlePragmaDirective(const TSourceLoc &line, const char* name, const char* value)
1176 pp::SourceLocation loc(line.first_file, line.first_line);
1177 mDirectiveHandler.handlePragma(loc, name, value);
1180 /////////////////////////////////////////////////////////////////////////////////
1184 /////////////////////////////////////////////////////////////////////////////////
1186 const TVariable *TParseContext::getNamedVariable(const TSourceLoc &location,
1187 const TString *name,
1188 const TSymbol *symbol)
1190 const TVariable *variable = nullptr;
1194 error(location, "undeclared identifier", name->c_str());
1197 else if(!symbol->isVariable())
1199 error(location, "variable expected", name->c_str());
1204 variable = static_cast<const TVariable*>(symbol);
1206 if(symbolTable.findBuiltIn(variable->getName(), mShaderVersion))
1211 // Reject shaders using both gl_FragData and gl_FragColor
1212 TQualifier qualifier = variable->getType().getQualifier();
1213 if(qualifier == EvqFragData)
1215 mUsesFragData = true;
1217 else if(qualifier == EvqFragColor)
1219 mUsesFragColor = true;
1222 // This validation is not quite correct - it's only an error to write to
1223 // both FragData and FragColor. For simplicity, and because users shouldn't
1224 // be rewarded for reading from undefined variables, return an error
1225 // if they are both referenced, rather than assigned.
1226 if(mUsesFragData && mUsesFragColor)
1228 error(location, "cannot use both gl_FragData and gl_FragColor", name->c_str());
1235 TType type(EbtFloat, EbpUndefined);
1236 TVariable *fakeVariable = new TVariable(name, type);
1237 symbolTable.declare(*fakeVariable);
1238 variable = fakeVariable;
1245 // Look up a function name in the symbol table, and make sure it is a function.
1247 // Return the function symbol if found, otherwise 0.
1249 const TFunction* TParseContext::findFunction(const TSourceLoc &line, TFunction* call, bool *builtIn)
1251 // First find by unmangled name to check whether the function name has been
1252 // hidden by a variable name or struct typename.
1253 const TSymbol* symbol = symbolTable.find(call->getName(), mShaderVersion, builtIn);
1255 symbol = symbolTable.find(call->getMangledName(), mShaderVersion, builtIn);
1259 error(line, "no matching overloaded function found", call->getName().c_str());
1263 if (!symbol->isFunction()) {
1264 error(line, "function name expected", call->getName().c_str());
1268 return static_cast<const TFunction*>(symbol);
1272 // Initializers show up in several places in the grammar. Have one set of
1273 // code to handle them here.
1275 bool TParseContext::executeInitializer(const TSourceLoc& line, const TString& identifier, const TPublicType& pType,
1276 TIntermTyped *initializer, TIntermNode **intermNode)
1278 ASSERT(intermNode != nullptr);
1279 TType type = TType(pType);
1281 if(type.isUnsizedArray())
1283 // We have not checked yet whether the initializer actually is an array or not.
1284 if(initializer->isArray())
1286 type.setArraySize(initializer->getArraySize());
1290 // Having a non-array initializer for an unsized array will result in an error later,
1291 // so we don't generate an error message here.
1292 type.setArraySize(1u);
1296 TVariable *variable = nullptr;
1297 if(!declareVariable(line, identifier, type, &variable))
1302 bool globalInitWarning = false;
1303 if(symbolTable.atGlobalLevel() && !ValidateGlobalInitializer(initializer, this, &globalInitWarning))
1305 // Error message does not completely match behavior with ESSL 1.00, but
1306 // we want to steer developers towards only using constant expressions.
1307 error(line, "global variable initializers must be constant expressions", "=");
1310 if(globalInitWarning)
1312 warning(line, "global variable initializers should be constant expressions "
1313 "(uniforms and globals are allowed in global initializers for legacy compatibility)", "=");
1317 // identifier must be of type constant, a global, or a temporary
1319 TQualifier qualifier = type.getQualifier();
1320 if ((qualifier != EvqTemporary) && (qualifier != EvqGlobal) && (qualifier != EvqConstExpr)) {
1321 error(line, " cannot initialize this type of qualifier ", variable->getType().getQualifierString());
1325 // test for and propagate constant
1328 if (qualifier == EvqConstExpr) {
1329 if (qualifier != initializer->getQualifier()) {
1330 std::stringstream extraInfoStream;
1331 extraInfoStream << "'" << variable->getType().getCompleteString() << "'";
1332 std::string extraInfo = extraInfoStream.str();
1333 error(line, " assigning non-constant to", "=", extraInfo.c_str());
1334 variable->getType().setQualifier(EvqTemporary);
1338 if (type != initializer->getType()) {
1339 error(line, " non-matching types for const initializer ",
1340 variable->getType().getQualifierString());
1341 variable->getType().setQualifier(EvqTemporary);
1345 if (initializer->getAsConstantUnion()) {
1346 variable->shareConstPointer(initializer->getAsConstantUnion()->getUnionArrayPointer());
1347 } else if (initializer->getAsSymbolNode()) {
1348 const TSymbol* symbol = symbolTable.find(initializer->getAsSymbolNode()->getSymbol(), 0);
1349 const TVariable* tVar = static_cast<const TVariable*>(symbol);
1351 ConstantUnion* constArray = tVar->getConstPointer();
1352 variable->shareConstPointer(constArray);
1356 if (!variable->isConstant()) {
1357 TIntermSymbol* intermSymbol = intermediate.addSymbol(variable->getUniqueId(), variable->getName(), variable->getType(), line);
1358 *intermNode = createAssign(EOpInitialize, intermSymbol, initializer, line);
1359 if(*intermNode == nullptr) {
1360 assignError(line, "=", intermSymbol->getCompleteString(), initializer->getCompleteString());
1364 *intermNode = nullptr;
1369 TPublicType TParseContext::addFullySpecifiedType(TQualifier qualifier, bool invariant, TLayoutQualifier layoutQualifier, const TPublicType &typeSpecifier)
1371 TPublicType returnType = typeSpecifier;
1372 returnType.qualifier = qualifier;
1373 returnType.invariant = invariant;
1374 returnType.layoutQualifier = layoutQualifier;
1376 if(typeSpecifier.array)
1378 error(typeSpecifier.line, "not supported", "first-class array");
1380 returnType.clearArrayness();
1383 if(mShaderVersion < 300)
1385 if(typeSpecifier.array)
1387 error(typeSpecifier.line, "not supported", "first-class array");
1388 returnType.clearArrayness();
1391 if(qualifier == EvqAttribute && (typeSpecifier.type == EbtBool || typeSpecifier.type == EbtInt))
1393 error(typeSpecifier.line, "cannot be bool or int", getQualifierString(qualifier));
1397 if((qualifier == EvqVaryingIn || qualifier == EvqVaryingOut) &&
1398 (typeSpecifier.type == EbtBool || typeSpecifier.type == EbtInt))
1400 error(typeSpecifier.line, "cannot be bool or int", getQualifierString(qualifier));
1406 if(!returnType.layoutQualifier.isEmpty())
1408 globalErrorCheck(typeSpecifier.line, symbolTable.atGlobalLevel(), "layout");
1411 if(IsVarying(returnType.qualifier) || returnType.qualifier == EvqVertexIn || returnType.qualifier == EvqFragmentOut)
1413 checkInputOutputTypeIsValidES3(returnType.qualifier, typeSpecifier, typeSpecifier.line);
1420 void TParseContext::checkInputOutputTypeIsValidES3(const TQualifier qualifier,
1421 const TPublicType &type,
1422 const TSourceLoc &qualifierLocation)
1424 // An input/output variable can never be bool or a sampler. Samplers are checked elsewhere.
1425 if(type.type == EbtBool)
1427 error(qualifierLocation, "cannot be bool", getQualifierString(qualifier));
1430 // Specific restrictions apply for vertex shader inputs and fragment shader outputs.
1434 // ESSL 3.00 section 4.3.4
1437 error(qualifierLocation, "cannot be array", getQualifierString(qualifier));
1439 // Vertex inputs with a struct type are disallowed in singleDeclarationErrorCheck
1441 case EvqFragmentOut:
1442 // ESSL 3.00 section 4.3.6
1445 error(qualifierLocation, "cannot be matrix", getQualifierString(qualifier));
1447 // Fragment outputs with a struct type are disallowed in singleDeclarationErrorCheck
1453 // Vertex shader outputs / fragment shader inputs have a different, slightly more lenient set of
1455 bool typeContainsIntegers = (type.type == EbtInt || type.type == EbtUInt ||
1456 type.isStructureContainingType(EbtInt) ||
1457 type.isStructureContainingType(EbtUInt));
1458 if(typeContainsIntegers && qualifier != EvqFlatIn && qualifier != EvqFlatOut)
1460 error(qualifierLocation, "must use 'flat' interpolation here", getQualifierString(qualifier));
1463 if(type.type == EbtStruct)
1465 // ESSL 3.00 sections 4.3.4 and 4.3.6.
1466 // These restrictions are only implied by the ESSL 3.00 spec, but
1467 // the ESSL 3.10 spec lists these restrictions explicitly.
1470 error(qualifierLocation, "cannot be an array of structures", getQualifierString(qualifier));
1472 if(type.isStructureContainingArrays())
1474 error(qualifierLocation, "cannot be a structure containing an array", getQualifierString(qualifier));
1476 if(type.isStructureContainingType(EbtStruct))
1478 error(qualifierLocation, "cannot be a structure containing a structure", getQualifierString(qualifier));
1480 if(type.isStructureContainingType(EbtBool))
1482 error(qualifierLocation, "cannot be a structure containing a bool", getQualifierString(qualifier));
1487 TIntermAggregate *TParseContext::parseSingleDeclaration(TPublicType &publicType,
1488 const TSourceLoc &identifierOrTypeLocation,
1489 const TString &identifier)
1491 TIntermSymbol *symbol = intermediate.addSymbol(0, identifier, TType(publicType), identifierOrTypeLocation);
1493 bool emptyDeclaration = (identifier == "");
1495 mDeferredSingleDeclarationErrorCheck = emptyDeclaration;
1497 if(emptyDeclaration)
1499 if(publicType.isUnsizedArray())
1501 // ESSL3 spec section 4.1.9: Array declaration which leaves the size unspecified is an error.
1502 // It is assumed that this applies to empty declarations as well.
1503 error(identifierOrTypeLocation, "empty array declaration needs to specify a size", identifier.c_str());
1508 if(singleDeclarationErrorCheck(publicType, identifierOrTypeLocation))
1511 if(nonInitErrorCheck(identifierOrTypeLocation, identifier, publicType))
1514 TVariable *variable = nullptr;
1515 if(!declareVariable(identifierOrTypeLocation, identifier, TType(publicType), &variable))
1518 if(variable && symbol)
1519 symbol->setId(variable->getUniqueId());
1522 return intermediate.makeAggregate(symbol, identifierOrTypeLocation);
1525 TIntermAggregate *TParseContext::parseSingleArrayDeclaration(TPublicType &publicType,
1526 const TSourceLoc &identifierLocation,
1527 const TString &identifier,
1528 const TSourceLoc &indexLocation,
1529 TIntermTyped *indexExpression)
1531 mDeferredSingleDeclarationErrorCheck = false;
1533 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1536 if(nonInitErrorCheck(identifierLocation, identifier, publicType))
1539 if(arrayTypeErrorCheck(indexLocation, publicType) || arrayQualifierErrorCheck(indexLocation, publicType))
1544 TType arrayType(publicType);
1547 if(arraySizeErrorCheck(identifierLocation, indexExpression, size))
1551 // Make the type an array even if size check failed.
1552 // This ensures useless error messages regarding the variable's non-arrayness won't follow.
1553 arrayType.setArraySize(size);
1555 TVariable *variable = nullptr;
1556 if(!declareVariable(identifierLocation, identifier, arrayType, &variable))
1559 TIntermSymbol *symbol = intermediate.addSymbol(0, identifier, arrayType, identifierLocation);
1560 if(variable && symbol)
1561 symbol->setId(variable->getUniqueId());
1563 return intermediate.makeAggregate(symbol, identifierLocation);
1566 TIntermAggregate *TParseContext::parseSingleInitDeclaration(const TPublicType &publicType,
1567 const TSourceLoc &identifierLocation,
1568 const TString &identifier,
1569 const TSourceLoc &initLocation,
1570 TIntermTyped *initializer)
1572 mDeferredSingleDeclarationErrorCheck = false;
1574 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1577 TIntermNode *intermNode = nullptr;
1578 if(!executeInitializer(identifierLocation, identifier, publicType, initializer, &intermNode))
1581 // Build intermediate representation
1583 return intermNode ? intermediate.makeAggregate(intermNode, initLocation) : nullptr;
1592 TIntermAggregate *TParseContext::parseSingleArrayInitDeclaration(TPublicType &publicType,
1593 const TSourceLoc &identifierLocation,
1594 const TString &identifier,
1595 const TSourceLoc &indexLocation,
1596 TIntermTyped *indexExpression,
1597 const TSourceLoc &initLocation,
1598 TIntermTyped *initializer)
1600 mDeferredSingleDeclarationErrorCheck = false;
1602 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1605 if(arrayTypeErrorCheck(indexLocation, publicType) || arrayQualifierErrorCheck(indexLocation, publicType))
1610 TPublicType arrayType(publicType);
1613 // If indexExpression is nullptr, then the array will eventually get its size implicitly from the initializer.
1614 if(indexExpression != nullptr && arraySizeErrorCheck(identifierLocation, indexExpression, size))
1618 // Make the type an array even if size check failed.
1619 // This ensures useless error messages regarding the variable's non-arrayness won't follow.
1620 arrayType.setArray(true, size);
1622 // initNode will correspond to the whole of "type b[n] = initializer".
1623 TIntermNode *initNode = nullptr;
1624 if(!executeInitializer(identifierLocation, identifier, arrayType, initializer, &initNode))
1626 return initNode ? intermediate.makeAggregate(initNode, initLocation) : nullptr;
1635 TIntermAggregate *TParseContext::parseInvariantDeclaration(const TSourceLoc &invariantLoc,
1636 const TSourceLoc &identifierLoc,
1637 const TString *identifier,
1638 const TSymbol *symbol)
1640 // invariant declaration
1641 if(globalErrorCheck(invariantLoc, symbolTable.atGlobalLevel(), "invariant varying"))
1648 error(identifierLoc, "undeclared identifier declared as invariant", identifier->c_str());
1654 const TString kGlFrontFacing("gl_FrontFacing");
1655 if(*identifier == kGlFrontFacing)
1657 error(identifierLoc, "identifier should not be declared as invariant", identifier->c_str());
1661 symbolTable.addInvariantVarying(std::string(identifier->c_str()));
1662 const TVariable *variable = getNamedVariable(identifierLoc, identifier, symbol);
1664 const TType &type = variable->getType();
1665 TIntermSymbol *intermSymbol = intermediate.addSymbol(variable->getUniqueId(),
1666 *identifier, type, identifierLoc);
1668 TIntermAggregate *aggregate = intermediate.makeAggregate(intermSymbol, identifierLoc);
1669 aggregate->setOp(EOpInvariantDeclaration);
1674 TIntermAggregate *TParseContext::parseDeclarator(TPublicType &publicType, TIntermAggregate *aggregateDeclaration,
1675 const TSourceLoc &identifierLocation, const TString &identifier)
1677 // If the declaration starting this declarator list was empty (example: int,), some checks were not performed.
1678 if(mDeferredSingleDeclarationErrorCheck)
1680 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1682 mDeferredSingleDeclarationErrorCheck = false;
1685 if(locationDeclaratorListCheck(identifierLocation, publicType))
1688 if(nonInitErrorCheck(identifierLocation, identifier, publicType))
1691 TVariable *variable = nullptr;
1692 if(!declareVariable(identifierLocation, identifier, TType(publicType), &variable))
1695 TIntermSymbol *symbol = intermediate.addSymbol(0, identifier, TType(publicType), identifierLocation);
1696 if(variable && symbol)
1697 symbol->setId(variable->getUniqueId());
1699 return intermediate.growAggregate(aggregateDeclaration, symbol, identifierLocation);
1702 TIntermAggregate *TParseContext::parseArrayDeclarator(TPublicType &publicType, TIntermAggregate *aggregateDeclaration,
1703 const TSourceLoc &identifierLocation, const TString &identifier,
1704 const TSourceLoc &arrayLocation, TIntermTyped *indexExpression)
1706 // If the declaration starting this declarator list was empty (example: int,), some checks were not performed.
1707 if(mDeferredSingleDeclarationErrorCheck)
1709 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1711 mDeferredSingleDeclarationErrorCheck = false;
1714 if(locationDeclaratorListCheck(identifierLocation, publicType))
1717 if(nonInitErrorCheck(identifierLocation, identifier, publicType))
1720 if(arrayTypeErrorCheck(arrayLocation, publicType) || arrayQualifierErrorCheck(arrayLocation, publicType))
1726 TType arrayType = TType(publicType);
1728 if(arraySizeErrorCheck(arrayLocation, indexExpression, size))
1732 arrayType.setArraySize(size);
1734 TVariable *variable = nullptr;
1735 if(!declareVariable(identifierLocation, identifier, arrayType, &variable))
1738 TIntermSymbol *symbol = intermediate.addSymbol(0, identifier, arrayType, identifierLocation);
1739 if(variable && symbol)
1740 symbol->setId(variable->getUniqueId());
1742 return intermediate.growAggregate(aggregateDeclaration, symbol, identifierLocation);
1748 TIntermAggregate *TParseContext::parseInitDeclarator(const TPublicType &publicType, TIntermAggregate *aggregateDeclaration,
1749 const TSourceLoc &identifierLocation, const TString &identifier,
1750 const TSourceLoc &initLocation, TIntermTyped *initializer)
1752 // If the declaration starting this declarator list was empty (example: int,), some checks were not performed.
1753 if(mDeferredSingleDeclarationErrorCheck)
1755 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1757 mDeferredSingleDeclarationErrorCheck = false;
1760 if(locationDeclaratorListCheck(identifierLocation, publicType))
1763 TIntermNode *intermNode = nullptr;
1764 if(!executeInitializer(identifierLocation, identifier, publicType, initializer, &intermNode))
1767 // build the intermediate representation
1771 return intermediate.growAggregate(aggregateDeclaration, intermNode, initLocation);
1775 return aggregateDeclaration;
1785 TIntermAggregate *TParseContext::parseArrayInitDeclarator(const TPublicType &publicType,
1786 TIntermAggregate *aggregateDeclaration,
1787 const TSourceLoc &identifierLocation,
1788 const TString &identifier,
1789 const TSourceLoc &indexLocation,
1790 TIntermTyped *indexExpression,
1791 const TSourceLoc &initLocation, TIntermTyped *initializer)
1793 // If the declaration starting this declarator list was empty (example: int,), some checks were not performed.
1794 if(mDeferredSingleDeclarationErrorCheck)
1796 if(singleDeclarationErrorCheck(publicType, identifierLocation))
1798 mDeferredSingleDeclarationErrorCheck = false;
1801 if(locationDeclaratorListCheck(identifierLocation, publicType))
1804 if(arrayTypeErrorCheck(indexLocation, publicType) || arrayQualifierErrorCheck(indexLocation, publicType))
1809 TPublicType arrayType(publicType);
1812 // If indexExpression is nullptr, then the array will eventually get its size implicitly from the initializer.
1813 if(indexExpression != nullptr && arraySizeErrorCheck(identifierLocation, indexExpression, size))
1817 // Make the type an array even if size check failed.
1818 // This ensures useless error messages regarding the variable's non-arrayness won't follow.
1819 arrayType.setArray(true, size);
1821 // initNode will correspond to the whole of "b[n] = initializer".
1822 TIntermNode *initNode = nullptr;
1823 if(!executeInitializer(identifierLocation, identifier, arrayType, initializer, &initNode))
1827 return intermediate.growAggregate(aggregateDeclaration, initNode, initLocation);
1831 return aggregateDeclaration;
1841 void TParseContext::parseGlobalLayoutQualifier(const TPublicType &typeQualifier)
1843 if(mShaderVersion < 300)
1845 error(typeQualifier.line, "layout qualifiers supported in GLSL ES 3.00 only", "layout");
1850 if(typeQualifier.qualifier != EvqUniform)
1852 error(typeQualifier.line, "invalid qualifier:", getQualifierString(typeQualifier.qualifier), "global layout must be uniform");
1857 const TLayoutQualifier layoutQualifier = typeQualifier.layoutQualifier;
1858 ASSERT(!layoutQualifier.isEmpty());
1860 if(layoutLocationErrorCheck(typeQualifier.line, typeQualifier.layoutQualifier))
1866 if(layoutQualifier.matrixPacking != EmpUnspecified)
1868 mDefaultMatrixPacking = layoutQualifier.matrixPacking;
1871 if(layoutQualifier.blockStorage != EbsUnspecified)
1873 mDefaultBlockStorage = layoutQualifier.blockStorage;
1877 TIntermAggregate *TParseContext::addFunctionPrototypeDeclaration(const TFunction &function, const TSourceLoc &location)
1879 // Note: symbolTableFunction could be the same as function if this is the first declaration.
1880 // Either way the instance in the symbol table is used to track whether the function is declared
1882 TFunction *symbolTableFunction =
1883 static_cast<TFunction *>(symbolTable.find(function.getMangledName(), getShaderVersion()));
1884 if(symbolTableFunction->hasPrototypeDeclaration() && mShaderVersion == 100)
1886 // ESSL 1.00.17 section 4.2.7.
1887 // Doesn't apply to ESSL 3.00.4: see section 4.2.3.
1888 error(location, "duplicate function prototype declarations are not allowed", "function");
1891 symbolTableFunction->setHasPrototypeDeclaration();
1893 TIntermAggregate *prototype = new TIntermAggregate;
1894 prototype->setType(function.getReturnType());
1895 prototype->setName(function.getMangledName());
1897 for(size_t i = 0; i < function.getParamCount(); i++)
1899 const TParameter ¶m = function.getParam(i);
1902 TVariable variable(param.name, *param.type);
1904 TIntermSymbol *paramSymbol = intermediate.addSymbol(
1905 variable.getUniqueId(), variable.getName(), variable.getType(), location);
1906 prototype = intermediate.growAggregate(prototype, paramSymbol, location);
1910 TIntermSymbol *paramSymbol = intermediate.addSymbol(0, "", *param.type, location);
1911 prototype = intermediate.growAggregate(prototype, paramSymbol, location);
1915 prototype->setOp(EOpPrototype);
1919 if(!symbolTable.atGlobalLevel())
1921 // ESSL 3.00.4 section 4.2.4.
1922 error(location, "local function prototype declarations are not allowed", "function");
1929 TIntermAggregate *TParseContext::addFunctionDefinition(const TFunction &function, TIntermAggregate *functionPrototype, TIntermAggregate *functionBody, const TSourceLoc &location)
1931 //?? Check that all paths return a value if return type != void ?
1932 // May be best done as post process phase on intermediate code
1933 if(mCurrentFunctionType->getBasicType() != EbtVoid && !mFunctionReturnsValue)
1935 error(location, "function does not return a value:", "", function.getName().c_str());
1939 TIntermAggregate *aggregate = intermediate.growAggregate(functionPrototype, functionBody, location);
1940 intermediate.setAggregateOperator(aggregate, EOpFunction, location);
1941 aggregate->setName(function.getMangledName().c_str());
1942 aggregate->setType(function.getReturnType());
1944 // store the pragma information for debug and optimize and other vendor specific
1945 // information. This information can be queried from the parse tree
1946 aggregate->setOptimize(pragma().optimize);
1947 aggregate->setDebug(pragma().debug);
1949 if(functionBody && functionBody->getAsAggregate())
1950 aggregate->setEndLine(functionBody->getAsAggregate()->getEndLine());
1956 void TParseContext::parseFunctionPrototype(const TSourceLoc &location, TFunction *function, TIntermAggregate **aggregateOut)
1958 const TSymbol *builtIn = symbolTable.findBuiltIn(function->getMangledName(), getShaderVersion());
1962 error(location, "built-in functions cannot be redefined", function->getName().c_str());
1966 TFunction *prevDec = static_cast<TFunction *>(symbolTable.find(function->getMangledName(), getShaderVersion()));
1968 // Note: 'prevDec' could be 'function' if this is the first time we've seen function
1969 // as it would have just been put in the symbol table. Otherwise, we're looking up
1970 // an earlier occurance.
1972 if(prevDec->isDefined())
1974 // Then this function already has a body.
1975 error(location, "function already has a body", function->getName().c_str());
1978 prevDec->setDefined();
1980 // Overload the unique ID of the definition to be the same unique ID as the declaration.
1981 // Eventually we will probably want to have only a single definition and just swap the
1982 // arguments to be the definition's arguments.
1984 function->setUniqueId(prevDec->getUniqueId());
1986 // Raise error message if main function takes any parameters or return anything other than void
1987 if(function->getName() == "main")
1989 if(function->getParamCount() > 0)
1991 error(location, "function cannot take any parameter(s)", function->getName().c_str());
1994 if(function->getReturnType().getBasicType() != EbtVoid)
1996 error(location, "", function->getReturnType().getBasicString(), "main function cannot return a value");
2002 // Remember the return type for later checking for RETURN statements.
2004 mCurrentFunctionType = &(prevDec->getReturnType());
2005 mFunctionReturnsValue = false;
2008 // Insert parameters into the symbol table.
2009 // If the parameter has no name, it's not an error, just don't insert it
2010 // (could be used for unused args).
2012 // Also, accumulate the list of parameters into the HIL, so lower level code
2013 // knows where to find parameters.
2015 TIntermAggregate *paramNodes = new TIntermAggregate;
2016 for(size_t i = 0; i < function->getParamCount(); i++)
2018 const TParameter ¶m = function->getParam(i);
2021 TVariable *variable = new TVariable(param.name, *param.type);
2023 // Insert the parameters with name in the symbol table.
2025 if(!symbolTable.declare(*variable))
2027 error(location, "redefinition", variable->getName().c_str());
2029 paramNodes = intermediate.growAggregate(
2030 paramNodes, intermediate.addSymbol(0, "", *param.type, location), location);
2035 // Add the parameter to the HIL
2037 TIntermSymbol *symbol = intermediate.addSymbol(
2038 variable->getUniqueId(), variable->getName(), variable->getType(), location);
2040 paramNodes = intermediate.growAggregate(paramNodes, symbol, location);
2044 paramNodes = intermediate.growAggregate(
2045 paramNodes, intermediate.addSymbol(0, "", *param.type, location), location);
2048 intermediate.setAggregateOperator(paramNodes, EOpParameters, location);
2049 *aggregateOut = paramNodes;
2050 setLoopNestingLevel(0);
2053 TFunction *TParseContext::parseFunctionDeclarator(const TSourceLoc &location, TFunction *function)
2056 // We don't know at this point whether this is a function definition or a prototype.
2057 // The definition production code will check for redefinitions.
2058 // In the case of ESSL 1.00 the prototype production code will also check for redeclarations.
2060 // Return types and parameter qualifiers must match in all redeclarations, so those are checked
2063 TFunction *prevDec = static_cast<TFunction *>(symbolTable.find(function->getMangledName(), getShaderVersion()));
2064 if(getShaderVersion() >= 300 && symbolTable.hasUnmangledBuiltIn(function->getName().c_str()))
2066 // With ESSL 3.00, names of built-in functions cannot be redeclared as functions.
2067 // Therefore overloading or redefining builtin functions is an error.
2068 error(location, "Name of a built-in function cannot be redeclared as function", function->getName().c_str());
2072 if(prevDec->getReturnType() != function->getReturnType())
2074 error(location, "overloaded functions must have the same return type",
2075 function->getReturnType().getBasicString());
2078 for(size_t i = 0; i < prevDec->getParamCount(); ++i)
2080 if(prevDec->getParam(i).type->getQualifier() != function->getParam(i).type->getQualifier())
2082 error(location, "overloaded functions must have the same parameter qualifiers",
2083 function->getParam(i).type->getQualifierString());
2090 // Check for previously declared variables using the same name.
2092 TSymbol *prevSym = symbolTable.find(function->getName(), getShaderVersion());
2095 if(!prevSym->isFunction())
2097 error(location, "redefinition", function->getName().c_str(), "function");
2102 // We're at the inner scope level of the function's arguments and body statement.
2103 // Add the function prototype to the surrounding scope instead.
2104 symbolTable.getOuterLevel()->insert(*function);
2107 // If this is a redeclaration, it could also be a definition, in which case, we want to use the
2108 // variable names from this one, and not the one that's
2109 // being redeclared. So, pass back up this declaration, not the one in the symbol table.
2114 TFunction *TParseContext::addConstructorFunc(const TPublicType &publicTypeIn)
2116 TPublicType publicType = publicTypeIn;
2117 TOperator op = EOpNull;
2118 if(publicType.userDef)
2120 op = EOpConstructStruct;
2124 op = TypeToConstructorOperator(TType(publicType));
2127 error(publicType.line, "cannot construct this type", getBasicString(publicType.type));
2129 publicType.type = EbtFloat;
2130 op = EOpConstructFloat;
2135 TType type(publicType);
2136 return new TFunction(&tempString, type, op);
2139 // This function is used to test for the correctness of the parameters passed to various constructor functions
2140 // and also convert them to the right datatype if it is allowed and required.
2142 // Returns 0 for an error or the constructed node (aggregate or typed) for no error.
2144 TIntermTyped* TParseContext::addConstructor(TIntermNode* arguments, const TType* type, TOperator op, TFunction* fnCall, const TSourceLoc &line)
2146 TIntermAggregate *aggregateArguments = arguments->getAsAggregate();
2148 if(!aggregateArguments)
2150 aggregateArguments = new TIntermAggregate;
2151 aggregateArguments->getSequence().push_back(arguments);
2156 // GLSL ES 3.00 section 5.4.4: Each argument must be the same type as the element type of
2158 for(TIntermNode *&argNode : aggregateArguments->getSequence())
2160 const TType &argType = argNode->getAsTyped()->getType();
2161 // It has already been checked that the argument is not an array.
2162 ASSERT(!argType.isArray());
2163 if(!argType.sameElementType(*type))
2165 error(line, "Array constructor argument has an incorrect type", "Error");
2170 else if(op == EOpConstructStruct)
2172 const TFieldList &fields = type->getStruct()->fields();
2173 TIntermSequence &args = aggregateArguments->getSequence();
2175 for(size_t i = 0; i < fields.size(); i++)
2177 if(args[i]->getAsTyped()->getType() != *fields[i]->type())
2179 error(line, "Structure constructor arguments do not match structure fields", "Error");
2187 // Turn the argument list itself into a constructor
2188 TIntermAggregate *constructor = intermediate.setAggregateOperator(aggregateArguments, op, line);
2189 TIntermTyped *constConstructor = foldConstConstructor(constructor, *type);
2190 if(constConstructor)
2192 return constConstructor;
2198 TIntermTyped* TParseContext::foldConstConstructor(TIntermAggregate* aggrNode, const TType& type)
2200 aggrNode->setType(type);
2201 if (aggrNode->isConstantFoldable()) {
2202 bool returnVal = false;
2203 ConstantUnion* unionArray = new ConstantUnion[type.getObjectSize()];
2204 if (aggrNode->getSequence().size() == 1) {
2205 returnVal = intermediate.parseConstTree(aggrNode->getLine(), aggrNode, unionArray, aggrNode->getOp(), type, true);
2208 returnVal = intermediate.parseConstTree(aggrNode->getLine(), aggrNode, unionArray, aggrNode->getOp(), type);
2213 return intermediate.addConstantUnion(unionArray, type, aggrNode->getLine());
2220 // This function returns the tree representation for the vector field(s) being accessed from contant vector.
2221 // If only one component of vector is accessed (v.x or v[0] where v is a contant vector), then a contant node is
2222 // returned, else an aggregate node is returned (for v.xy). The input to this function could either be the symbol
2223 // node or it could be the intermediate tree representation of accessing fields in a constant structure or column of
2224 // a constant matrix.
2226 TIntermTyped* TParseContext::addConstVectorNode(TVectorFields& fields, TIntermTyped* node, const TSourceLoc &line)
2228 TIntermTyped* typedNode;
2229 TIntermConstantUnion* tempConstantNode = node->getAsConstantUnion();
2231 ConstantUnion *unionArray;
2232 if (tempConstantNode) {
2233 unionArray = tempConstantNode->getUnionArrayPointer();
2238 } else { // The node has to be either a symbol node or an aggregate node or a tempConstant node, else, its an error
2239 error(line, "Cannot offset into the vector", "Error");
2245 ConstantUnion* constArray = new ConstantUnion[fields.num];
2247 int objSize = static_cast<int>(node->getType().getObjectSize());
2248 for (int i = 0; i < fields.num; i++) {
2249 if (fields.offsets[i] >= objSize) {
2250 std::stringstream extraInfoStream;
2251 extraInfoStream << "vector field selection out of range '" << fields.offsets[i] << "'";
2252 std::string extraInfo = extraInfoStream.str();
2253 error(line, "", "[", extraInfo.c_str());
2255 fields.offsets[i] = 0;
2258 constArray[i] = unionArray[fields.offsets[i]];
2261 typedNode = intermediate.addConstantUnion(constArray, node->getType(), line);
2266 // This function returns the column being accessed from a constant matrix. The values are retrieved from
2267 // the symbol table and parse-tree is built for a vector (each column of a matrix is a vector). The input
2268 // to the function could either be a symbol node (m[0] where m is a constant matrix)that represents a
2269 // constant matrix or it could be the tree representation of the constant matrix (s.m1[0] where s is a constant structure)
2271 TIntermTyped* TParseContext::addConstMatrixNode(int index, TIntermTyped* node, const TSourceLoc &line)
2273 TIntermTyped* typedNode;
2274 TIntermConstantUnion* tempConstantNode = node->getAsConstantUnion();
2276 if (index >= node->getType().getNominalSize()) {
2277 std::stringstream extraInfoStream;
2278 extraInfoStream << "matrix field selection out of range '" << index << "'";
2279 std::string extraInfo = extraInfoStream.str();
2280 error(line, "", "[", extraInfo.c_str());
2285 if (tempConstantNode) {
2286 ConstantUnion* unionArray = tempConstantNode->getUnionArrayPointer();
2287 int size = tempConstantNode->getType().getNominalSize();
2288 typedNode = intermediate.addConstantUnion(&unionArray[size*index], tempConstantNode->getType(), line);
2290 error(line, "Cannot offset into the matrix", "Error");
2301 // This function returns an element of an array accessed from a constant array. The values are retrieved from
2302 // the symbol table and parse-tree is built for the type of the element. The input
2303 // to the function could either be a symbol node (a[0] where a is a constant array)that represents a
2304 // constant array or it could be the tree representation of the constant array (s.a1[0] where s is a constant structure)
2306 TIntermTyped* TParseContext::addConstArrayNode(int index, TIntermTyped* node, const TSourceLoc &line)
2308 TIntermTyped* typedNode;
2309 TIntermConstantUnion* tempConstantNode = node->getAsConstantUnion();
2310 TType arrayElementType = node->getType();
2311 arrayElementType.clearArrayness();
2313 if (index >= node->getType().getArraySize()) {
2314 std::stringstream extraInfoStream;
2315 extraInfoStream << "array field selection out of range '" << index << "'";
2316 std::string extraInfo = extraInfoStream.str();
2317 error(line, "", "[", extraInfo.c_str());
2322 size_t arrayElementSize = arrayElementType.getObjectSize();
2324 if (tempConstantNode) {
2325 ConstantUnion* unionArray = tempConstantNode->getUnionArrayPointer();
2326 typedNode = intermediate.addConstantUnion(&unionArray[arrayElementSize * index], tempConstantNode->getType(), line);
2328 error(line, "Cannot offset into the array", "Error");
2339 // This function returns the value of a particular field inside a constant structure from the symbol table.
2340 // If there is an embedded/nested struct, it appropriately calls addConstStructNested or addConstStructFromAggr
2341 // function and returns the parse-tree with the values of the embedded/nested struct.
2343 TIntermTyped* TParseContext::addConstStruct(const TString& identifier, TIntermTyped* node, const TSourceLoc &line)
2345 const TFieldList &fields = node->getType().getStruct()->fields();
2346 TIntermTyped *typedNode;
2347 size_t instanceSize = 0;
2348 TIntermConstantUnion *tempConstantNode = node->getAsConstantUnion();
2350 for(size_t index = 0; index < fields.size(); ++index) {
2351 if (fields[index]->name() == identifier) {
2354 instanceSize += fields[index]->type()->getObjectSize();
2358 if (tempConstantNode) {
2359 ConstantUnion* constArray = tempConstantNode->getUnionArrayPointer();
2361 typedNode = intermediate.addConstantUnion(constArray+instanceSize, tempConstantNode->getType(), line); // type will be changed in the calling function
2363 error(line, "Cannot offset into the structure", "Error");
2373 // Interface/uniform blocks
2375 TIntermAggregate* TParseContext::addInterfaceBlock(const TPublicType& typeQualifier, const TSourceLoc& nameLine, const TString& blockName, TFieldList* fieldList,
2376 const TString* instanceName, const TSourceLoc& instanceLine, TIntermTyped* arrayIndex, const TSourceLoc& arrayIndexLine)
2378 if(reservedErrorCheck(nameLine, blockName))
2381 if(typeQualifier.qualifier != EvqUniform)
2383 error(typeQualifier.line, "invalid qualifier:", getQualifierString(typeQualifier.qualifier), "interface blocks must be uniform");
2387 TLayoutQualifier blockLayoutQualifier = typeQualifier.layoutQualifier;
2388 if(layoutLocationErrorCheck(typeQualifier.line, blockLayoutQualifier))
2393 if(blockLayoutQualifier.matrixPacking == EmpUnspecified)
2395 blockLayoutQualifier.matrixPacking = mDefaultMatrixPacking;
2398 if(blockLayoutQualifier.blockStorage == EbsUnspecified)
2400 blockLayoutQualifier.blockStorage = mDefaultBlockStorage;
2403 TSymbol* blockNameSymbol = new TSymbol(&blockName);
2404 if(!symbolTable.declare(*blockNameSymbol)) {
2405 error(nameLine, "redefinition", blockName.c_str(), "interface block name");
2409 // check for sampler types and apply layout qualifiers
2410 for(size_t memberIndex = 0; memberIndex < fieldList->size(); ++memberIndex) {
2411 TField* field = (*fieldList)[memberIndex];
2412 TType* fieldType = field->type();
2413 if(IsSampler(fieldType->getBasicType())) {
2414 error(field->line(), "unsupported type", fieldType->getBasicString(), "sampler types are not allowed in interface blocks");
2418 const TQualifier qualifier = fieldType->getQualifier();
2425 error(field->line(), "invalid qualifier on interface block member", getQualifierString(qualifier));
2430 // check layout qualifiers
2431 TLayoutQualifier fieldLayoutQualifier = fieldType->getLayoutQualifier();
2432 if(layoutLocationErrorCheck(field->line(), fieldLayoutQualifier))
2437 if(fieldLayoutQualifier.blockStorage != EbsUnspecified)
2439 error(field->line(), "invalid layout qualifier:", getBlockStorageString(fieldLayoutQualifier.blockStorage), "cannot be used here");
2443 if(fieldLayoutQualifier.matrixPacking == EmpUnspecified)
2445 fieldLayoutQualifier.matrixPacking = blockLayoutQualifier.matrixPacking;
2447 else if(!fieldType->isMatrix())
2449 error(field->line(), "invalid layout qualifier:", getMatrixPackingString(fieldLayoutQualifier.matrixPacking), "can only be used on matrix types");
2453 fieldType->setLayoutQualifier(fieldLayoutQualifier);
2460 if(arraySizeErrorCheck(arrayIndexLine, arrayIndex, arraySize))
2464 TInterfaceBlock* interfaceBlock = new TInterfaceBlock(&blockName, fieldList, instanceName, arraySize, blockLayoutQualifier);
2465 TType interfaceBlockType(interfaceBlock, typeQualifier.qualifier, blockLayoutQualifier, arraySize);
2467 TString symbolName = "";
2472 // define symbols for the members of the interface block
2473 for(size_t memberIndex = 0; memberIndex < fieldList->size(); ++memberIndex)
2475 TField* field = (*fieldList)[memberIndex];
2476 TType* fieldType = field->type();
2478 // set parent pointer of the field variable
2479 fieldType->setInterfaceBlock(interfaceBlock);
2481 TVariable* fieldVariable = new TVariable(&field->name(), *fieldType);
2482 fieldVariable->setQualifier(typeQualifier.qualifier);
2484 if(!symbolTable.declare(*fieldVariable)) {
2485 error(field->line(), "redefinition", field->name().c_str(), "interface block member name");
2492 // add a symbol for this interface block
2493 TVariable* instanceTypeDef = new TVariable(instanceName, interfaceBlockType, false);
2494 instanceTypeDef->setQualifier(typeQualifier.qualifier);
2496 if(!symbolTable.declare(*instanceTypeDef)) {
2497 error(instanceLine, "redefinition", instanceName->c_str(), "interface block instance name");
2501 symbolId = instanceTypeDef->getUniqueId();
2502 symbolName = instanceTypeDef->getName();
2505 TIntermAggregate *aggregate = intermediate.makeAggregate(intermediate.addSymbol(symbolId, symbolName, interfaceBlockType, typeQualifier.line), nameLine);
2506 aggregate->setOp(EOpDeclaration);
2508 exitStructDeclaration();
2513 // Parse an array index expression
2515 TIntermTyped *TParseContext::addIndexExpression(TIntermTyped *baseExpression, const TSourceLoc &location, TIntermTyped *indexExpression)
2517 TIntermTyped *indexedExpression = nullptr;
2519 if(!baseExpression->isArray() && !baseExpression->isMatrix() && !baseExpression->isVector())
2521 if(baseExpression->getAsSymbolNode())
2523 error(location, " left of '[' is not of type array, matrix, or vector ",
2524 baseExpression->getAsSymbolNode()->getSymbol().c_str());
2528 error(location, " left of '[' is not of type array, matrix, or vector ", "expression");
2533 TIntermConstantUnion *indexConstantUnion = indexExpression->getAsConstantUnion();
2535 if(indexExpression->getQualifier() == EvqConstExpr && indexConstantUnion)
2537 int index = indexConstantUnion->getIConst(0);
2540 std::stringstream infoStream;
2541 infoStream << index;
2542 std::string info = infoStream.str();
2543 error(location, "negative index", info.c_str());
2547 if(baseExpression->getType().getQualifier() == EvqConstExpr)
2549 if(baseExpression->isArray())
2551 // constant folding for arrays
2552 indexedExpression = addConstArrayNode(index, baseExpression, location);
2554 else if(baseExpression->isVector())
2556 // constant folding for vectors
2557 TVectorFields fields;
2559 fields.offsets[0] = index; // need to do it this way because v.xy sends fields integer array
2560 indexedExpression = addConstVectorNode(fields, baseExpression, location);
2562 else if(baseExpression->isMatrix())
2564 // constant folding for matrices
2565 indexedExpression = addConstMatrixNode(index, baseExpression, location);
2572 if(baseExpression->isArray())
2574 if(index >= baseExpression->getType().getArraySize())
2576 std::stringstream extraInfoStream;
2577 extraInfoStream << "array index out of range '" << index << "'";
2578 std::string extraInfo = extraInfoStream.str();
2579 error(location, "", "[", extraInfo.c_str());
2581 safeIndex = baseExpression->getType().getArraySize() - 1;
2584 else if((baseExpression->isVector() || baseExpression->isMatrix()) &&
2585 baseExpression->getType().getNominalSize() <= index)
2587 std::stringstream extraInfoStream;
2588 extraInfoStream << "field selection out of range '" << index << "'";
2589 std::string extraInfo = extraInfoStream.str();
2590 error(location, "", "[", extraInfo.c_str());
2592 safeIndex = baseExpression->getType().getNominalSize() - 1;
2595 // Don't modify the data of the previous constant union, because it can point
2596 // to builtins, like gl_MaxDrawBuffers. Instead use a new sanitized object.
2599 ConstantUnion *safeConstantUnion = new ConstantUnion();
2600 safeConstantUnion->setIConst(safeIndex);
2601 indexConstantUnion->replaceConstantUnion(safeConstantUnion);
2604 indexedExpression = intermediate.addIndex(EOpIndexDirect, baseExpression, indexExpression, location);
2609 if(baseExpression->isInterfaceBlock())
2612 "[", "array indexes for interface blocks arrays must be constant integral expressions");
2615 else if(baseExpression->getQualifier() == EvqFragmentOut)
2617 error(location, "", "[", "array indexes for fragment outputs must be constant integral expressions");
2621 indexedExpression = intermediate.addIndex(EOpIndexIndirect, baseExpression, indexExpression, location);
2624 if(indexedExpression == 0)
2626 ConstantUnion *unionArray = new ConstantUnion[1];
2627 unionArray->setFConst(0.0f);
2628 indexedExpression = intermediate.addConstantUnion(unionArray, TType(EbtFloat, EbpHigh, EvqConstExpr), location);
2630 else if(baseExpression->isArray())
2632 const TType &baseType = baseExpression->getType();
2633 if(baseType.getStruct())
2635 TType copyOfType(baseType.getStruct());
2636 indexedExpression->setType(copyOfType);
2638 else if(baseType.isInterfaceBlock())
2640 TType copyOfType(baseType.getInterfaceBlock(), EvqTemporary, baseType.getLayoutQualifier(), 0);
2641 indexedExpression->setType(copyOfType);
2645 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(),
2646 EvqTemporary, static_cast<unsigned char>(baseExpression->getNominalSize()),
2647 static_cast<unsigned char>(baseExpression->getSecondarySize())));
2650 if(baseExpression->getType().getQualifier() == EvqConstExpr)
2652 indexedExpression->getTypePointer()->setQualifier(EvqConstExpr);
2655 else if(baseExpression->isMatrix())
2657 TQualifier qualifier = baseExpression->getType().getQualifier() == EvqConstExpr ? EvqConstExpr : EvqTemporary;
2658 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(),
2659 qualifier, static_cast<unsigned char>(baseExpression->getSecondarySize())));
2661 else if(baseExpression->isVector())
2663 TQualifier qualifier = baseExpression->getType().getQualifier() == EvqConstExpr ? EvqConstExpr : EvqTemporary;
2664 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(), qualifier));
2668 indexedExpression->setType(baseExpression->getType());
2671 return indexedExpression;
2674 TIntermTyped *TParseContext::addFieldSelectionExpression(TIntermTyped *baseExpression, const TSourceLoc &dotLocation,
2675 const TString &fieldString, const TSourceLoc &fieldLocation)
2677 TIntermTyped *indexedExpression = nullptr;
2679 if(baseExpression->isArray())
2681 error(fieldLocation, "cannot apply dot operator to an array", ".");
2685 if(baseExpression->isVector())
2687 TVectorFields fields;
2688 if(!parseVectorFields(fieldString, baseExpression->getNominalSize(), fields, fieldLocation))
2691 fields.offsets[0] = 0;
2695 if(baseExpression->getAsConstantUnion())
2697 // constant folding for vector fields
2698 indexedExpression = addConstVectorNode(fields, baseExpression, fieldLocation);
2699 if(indexedExpression == 0)
2702 indexedExpression = baseExpression;
2706 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(),
2707 EvqConstExpr, (unsigned char)(fieldString).size()));
2712 TString vectorString = fieldString;
2713 TIntermTyped *index = intermediate.addSwizzle(fields, fieldLocation);
2714 indexedExpression = intermediate.addIndex(EOpVectorSwizzle, baseExpression, index, dotLocation);
2715 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(),
2716 baseExpression->getQualifier() == EvqConstExpr ? EvqConstExpr : EvqTemporary, (unsigned char)vectorString.size()));
2719 else if(baseExpression->isMatrix())
2721 TMatrixFields fields;
2722 if(!parseMatrixFields(fieldString, baseExpression->getNominalSize(), baseExpression->getSecondarySize(), fields, fieldLocation))
2724 fields.wholeRow = false;
2725 fields.wholeCol = false;
2731 if(fields.wholeRow || fields.wholeCol)
2733 error(dotLocation, " non-scalar fields not implemented yet", ".");
2735 ConstantUnion *unionArray = new ConstantUnion[1];
2736 unionArray->setIConst(0);
2737 TIntermTyped *index = intermediate.addConstantUnion(unionArray, TType(EbtInt, EbpUndefined, EvqConstExpr),
2739 indexedExpression = intermediate.addIndex(EOpIndexDirect, baseExpression, index, dotLocation);
2740 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision(),
2741 EvqTemporary, static_cast<unsigned char>(baseExpression->getNominalSize()),
2742 static_cast<unsigned char>(baseExpression->getSecondarySize())));
2746 ConstantUnion *unionArray = new ConstantUnion[1];
2747 unionArray->setIConst(fields.col * baseExpression->getSecondarySize() + fields.row);
2748 TIntermTyped *index = intermediate.addConstantUnion(unionArray, TType(EbtInt, EbpUndefined, EvqConstExpr),
2750 indexedExpression = intermediate.addIndex(EOpIndexDirect, baseExpression, index, dotLocation);
2751 indexedExpression->setType(TType(baseExpression->getBasicType(), baseExpression->getPrecision()));
2754 else if(baseExpression->getBasicType() == EbtStruct)
2756 bool fieldFound = false;
2757 const TFieldList &fields = baseExpression->getType().getStruct()->fields();
2760 error(dotLocation, "structure has no fields", "Internal Error");
2762 indexedExpression = baseExpression;
2767 for(i = 0; i < fields.size(); ++i)
2769 if(fields[i]->name() == fieldString)
2777 if(baseExpression->getType().getQualifier() == EvqConstExpr)
2779 indexedExpression = addConstStruct(fieldString, baseExpression, dotLocation);
2780 if(indexedExpression == 0)
2783 indexedExpression = baseExpression;
2787 indexedExpression->setType(*fields[i]->type());
2788 // change the qualifier of the return type, not of the structure field
2789 // as the structure definition is shared between various structures.
2790 indexedExpression->getTypePointer()->setQualifier(EvqConstExpr);
2795 TIntermTyped *index = TIntermTyped::CreateIndexNode(i);
2796 index->setLine(fieldLocation);
2797 indexedExpression = intermediate.addIndex(EOpIndexDirectStruct, baseExpression, index, dotLocation);
2798 indexedExpression->setType(*fields[i]->type());
2803 error(dotLocation, " no such field in structure", fieldString.c_str());
2805 indexedExpression = baseExpression;
2809 else if(baseExpression->isInterfaceBlock())
2811 bool fieldFound = false;
2812 const TFieldList &fields = baseExpression->getType().getInterfaceBlock()->fields();
2815 error(dotLocation, "interface block has no fields", "Internal Error");
2817 indexedExpression = baseExpression;
2822 for(i = 0; i < fields.size(); ++i)
2824 if(fields[i]->name() == fieldString)
2832 ConstantUnion *unionArray = new ConstantUnion[1];
2833 unionArray->setIConst(i);
2834 TIntermTyped *index = intermediate.addConstantUnion(unionArray, *fields[i]->type(), fieldLocation);
2835 indexedExpression = intermediate.addIndex(EOpIndexDirectInterfaceBlock, baseExpression, index,
2837 indexedExpression->setType(*fields[i]->type());
2841 error(dotLocation, " no such field in interface block", fieldString.c_str());
2843 indexedExpression = baseExpression;
2849 if(mShaderVersion < 300)
2851 error(dotLocation, " field selection requires structure, vector, or matrix on left hand side",
2852 fieldString.c_str());
2857 " field selection requires structure, vector, matrix, or interface block on left hand side",
2858 fieldString.c_str());
2861 indexedExpression = baseExpression;
2864 return indexedExpression;
2867 TLayoutQualifier TParseContext::parseLayoutQualifier(const TString &qualifierType, const TSourceLoc& qualifierTypeLine)
2869 TLayoutQualifier qualifier;
2871 qualifier.location = -1;
2872 qualifier.matrixPacking = EmpUnspecified;
2873 qualifier.blockStorage = EbsUnspecified;
2875 if(qualifierType == "shared")
2877 qualifier.blockStorage = EbsShared;
2879 else if(qualifierType == "packed")
2881 qualifier.blockStorage = EbsPacked;
2883 else if(qualifierType == "std140")
2885 qualifier.blockStorage = EbsStd140;
2887 else if(qualifierType == "row_major")
2889 qualifier.matrixPacking = EmpRowMajor;
2891 else if(qualifierType == "column_major")
2893 qualifier.matrixPacking = EmpColumnMajor;
2895 else if(qualifierType == "location")
2897 error(qualifierTypeLine, "invalid layout qualifier", qualifierType.c_str(), "location requires an argument");
2902 error(qualifierTypeLine, "invalid layout qualifier", qualifierType.c_str());
2909 TLayoutQualifier TParseContext::parseLayoutQualifier(const TString &qualifierType, const TSourceLoc& qualifierTypeLine, const TString &intValueString, int intValue, const TSourceLoc& intValueLine)
2911 TLayoutQualifier qualifier;
2913 qualifier.location = -1;
2914 qualifier.matrixPacking = EmpUnspecified;
2915 qualifier.blockStorage = EbsUnspecified;
2917 if (qualifierType != "location")
2919 error(qualifierTypeLine, "invalid layout qualifier", qualifierType.c_str(), "only location may have arguments");
2924 // must check that location is non-negative
2927 error(intValueLine, "out of range:", intValueString.c_str(), "location must be non-negative");
2932 qualifier.location = intValue;
2939 TLayoutQualifier TParseContext::joinLayoutQualifiers(TLayoutQualifier leftQualifier, TLayoutQualifier rightQualifier)
2941 TLayoutQualifier joinedQualifier = leftQualifier;
2943 if (rightQualifier.location != -1)
2945 joinedQualifier.location = rightQualifier.location;
2947 if(rightQualifier.matrixPacking != EmpUnspecified)
2949 joinedQualifier.matrixPacking = rightQualifier.matrixPacking;
2951 if(rightQualifier.blockStorage != EbsUnspecified)
2953 joinedQualifier.blockStorage = rightQualifier.blockStorage;
2956 return joinedQualifier;
2960 TPublicType TParseContext::joinInterpolationQualifiers(const TSourceLoc &interpolationLoc, TQualifier interpolationQualifier,
2961 const TSourceLoc &storageLoc, TQualifier storageQualifier)
2963 TQualifier mergedQualifier = EvqSmoothIn;
2965 if(storageQualifier == EvqFragmentIn) {
2966 if(interpolationQualifier == EvqSmooth)
2967 mergedQualifier = EvqSmoothIn;
2968 else if(interpolationQualifier == EvqFlat)
2969 mergedQualifier = EvqFlatIn;
2970 else UNREACHABLE(interpolationQualifier);
2972 else if(storageQualifier == EvqCentroidIn) {
2973 if(interpolationQualifier == EvqSmooth)
2974 mergedQualifier = EvqCentroidIn;
2975 else if(interpolationQualifier == EvqFlat)
2976 mergedQualifier = EvqFlatIn;
2977 else UNREACHABLE(interpolationQualifier);
2979 else if(storageQualifier == EvqVertexOut) {
2980 if(interpolationQualifier == EvqSmooth)
2981 mergedQualifier = EvqSmoothOut;
2982 else if(interpolationQualifier == EvqFlat)
2983 mergedQualifier = EvqFlatOut;
2984 else UNREACHABLE(interpolationQualifier);
2986 else if(storageQualifier == EvqCentroidOut) {
2987 if(interpolationQualifier == EvqSmooth)
2988 mergedQualifier = EvqCentroidOut;
2989 else if(interpolationQualifier == EvqFlat)
2990 mergedQualifier = EvqFlatOut;
2991 else UNREACHABLE(interpolationQualifier);
2994 error(interpolationLoc, "interpolation qualifier requires a fragment 'in' or vertex 'out' storage qualifier", getQualifierString(interpolationQualifier));
2997 mergedQualifier = storageQualifier;
3001 type.setBasic(EbtVoid, mergedQualifier, storageLoc);
3005 TFieldList *TParseContext::addStructDeclaratorList(const TPublicType &typeSpecifier, TFieldList *fieldList)
3007 if(voidErrorCheck(typeSpecifier.line, (*fieldList)[0]->name(), typeSpecifier.type))
3012 for(unsigned int i = 0; i < fieldList->size(); ++i)
3015 // Careful not to replace already known aspects of type, like array-ness
3017 TType *type = (*fieldList)[i]->type();
3018 type->setBasicType(typeSpecifier.type);
3019 type->setNominalSize(typeSpecifier.primarySize);
3020 type->setSecondarySize(typeSpecifier.secondarySize);
3021 type->setPrecision(typeSpecifier.precision);
3022 type->setQualifier(typeSpecifier.qualifier);
3023 type->setLayoutQualifier(typeSpecifier.layoutQualifier);
3025 // don't allow arrays of arrays
3028 if(arrayTypeErrorCheck(typeSpecifier.line, typeSpecifier))
3031 if(typeSpecifier.array)
3032 type->setArraySize(typeSpecifier.arraySize);
3033 if(typeSpecifier.userDef)
3035 type->setStruct(typeSpecifier.userDef->getStruct());
3038 if(structNestingErrorCheck(typeSpecifier.line, *(*fieldList)[i]))
3047 TPublicType TParseContext::addStructure(const TSourceLoc &structLine, const TSourceLoc &nameLine,
3048 const TString *structName, TFieldList *fieldList)
3050 TStructure *structure = new TStructure(structName, fieldList);
3051 TType *structureType = new TType(structure);
3053 // Store a bool in the struct if we're at global scope, to allow us to
3054 // skip the local struct scoping workaround in HLSL.
3055 structure->setUniqueId(TSymbolTableLevel::nextUniqueId());
3056 structure->setAtGlobalScope(symbolTable.atGlobalLevel());
3058 if(!structName->empty())
3060 if(reservedErrorCheck(nameLine, *structName))
3064 TVariable *userTypeDef = new TVariable(structName, *structureType, true);
3065 if(!symbolTable.declare(*userTypeDef))
3067 error(nameLine, "redefinition", structName->c_str(), "struct");
3072 // ensure we do not specify any storage qualifiers on the struct members
3073 for(unsigned int typeListIndex = 0; typeListIndex < fieldList->size(); typeListIndex++)
3075 const TField &field = *(*fieldList)[typeListIndex];
3076 const TQualifier qualifier = field.type()->getQualifier();
3083 error(field.line(), "invalid qualifier on struct member", getQualifierString(qualifier));
3089 TPublicType publicType;
3090 publicType.setBasic(EbtStruct, EvqTemporary, structLine);
3091 publicType.userDef = structureType;
3092 exitStructDeclaration();
3097 bool TParseContext::enterStructDeclaration(const TSourceLoc &line, const TString& identifier)
3099 ++mStructNestingLevel;
3101 // Embedded structure definitions are not supported per GLSL ES spec.
3102 // They aren't allowed in GLSL either, but we need to detect this here
3103 // so we don't rely on the GLSL compiler to catch it.
3104 if (mStructNestingLevel > 1) {
3105 error(line, "", "Embedded struct definitions are not allowed");
3112 void TParseContext::exitStructDeclaration()
3114 --mStructNestingLevel;
3117 bool TParseContext::structNestingErrorCheck(const TSourceLoc &line, const TField &field)
3119 static const int kWebGLMaxStructNesting = 4;
3121 if(field.type()->getBasicType() != EbtStruct)
3126 // We're already inside a structure definition at this point, so add
3127 // one to the field's struct nesting.
3128 if(1 + field.type()->getDeepestStructNesting() > kWebGLMaxStructNesting)
3130 std::stringstream reasonStream;
3131 reasonStream << "Reference of struct type "
3132 << field.type()->getStruct()->name().c_str()
3133 << " exceeds maximum allowed nesting level of "
3134 << kWebGLMaxStructNesting;
3135 std::string reason = reasonStream.str();
3136 error(line, reason.c_str(), field.name().c_str(), "");
3143 TIntermTyped *TParseContext::createUnaryMath(TOperator op, TIntermTyped *child, const TSourceLoc &loc, const TType *funcReturnType)
3145 if(child == nullptr)
3153 if(child->getBasicType() != EbtBool ||
3154 child->isMatrix() ||
3162 if((child->getBasicType() != EbtInt && child->getBasicType() != EbtUInt) ||
3163 child->isMatrix() ||
3169 case EOpPostIncrement:
3170 case EOpPreIncrement:
3171 case EOpPostDecrement:
3172 case EOpPreDecrement:
3174 if(child->getBasicType() == EbtStruct ||
3175 child->getBasicType() == EbtBool ||
3180 // Operators for built-ins are already type checked against their prototype.
3185 return intermediate.addUnaryMath(op, child, loc, funcReturnType);
3188 TIntermTyped *TParseContext::addUnaryMath(TOperator op, TIntermTyped *child, const TSourceLoc &loc)
3190 TIntermTyped *node = createUnaryMath(op, child, loc, nullptr);
3193 unaryOpError(loc, getOperatorString(op), child->getCompleteString());
3200 TIntermTyped *TParseContext::addUnaryMathLValue(TOperator op, TIntermTyped *child, const TSourceLoc &loc)
3202 if(lValueErrorCheck(loc, getOperatorString(op), child))
3204 return addUnaryMath(op, child, loc);
3207 bool TParseContext::binaryOpCommonCheck(TOperator op, TIntermTyped *left, TIntermTyped *right, const TSourceLoc &loc)
3209 if(left->isArray() || right->isArray())
3211 if(mShaderVersion < 300)
3213 error(loc, "Invalid operation for arrays", getOperatorString(op));
3217 if(left->isArray() != right->isArray())
3219 error(loc, "array / non-array mismatch", getOperatorString(op));
3231 error(loc, "Invalid operation for arrays", getOperatorString(op));
3234 // At this point, size of implicitly sized arrays should be resolved.
3235 if(left->getArraySize() != right->getArraySize())
3237 error(loc, "array size mismatch", getOperatorString(op));
3242 // Check ops which require integer / ivec parameters
3243 bool isBitShift = false;
3246 case EOpBitShiftLeft:
3247 case EOpBitShiftRight:
3248 case EOpBitShiftLeftAssign:
3249 case EOpBitShiftRightAssign:
3250 // Unsigned can be bit-shifted by signed and vice versa, but we need to
3251 // check that the basic type is an integer type.
3253 if(!IsInteger(left->getBasicType()) || !IsInteger(right->getBasicType()))
3261 case EOpBitwiseAndAssign:
3262 case EOpBitwiseXorAssign:
3263 case EOpBitwiseOrAssign:
3264 // It is enough to check the type of only one operand, since later it
3265 // is checked that the operand types match.
3266 if(!IsInteger(left->getBasicType()))
3275 // GLSL ES 1.00 and 3.00 do not support implicit type casting.
3276 // So the basic type should usually match.
3277 if(!isBitShift && left->getBasicType() != right->getBasicType())
3282 // Check that type sizes match exactly on ops that require that.
3283 // Also check restrictions for structs that contain arrays or samplers.
3290 // ESSL 1.00 sections 5.7, 5.8, 5.9
3291 if(mShaderVersion < 300 && left->getType().isStructureContainingArrays())
3293 error(loc, "undefined operation for structs containing arrays", getOperatorString(op));
3296 // Samplers as l-values are disallowed also in ESSL 3.00, see section 4.1.7,
3297 // we interpret the spec so that this extends to structs containing samplers,
3298 // similarly to ESSL 1.00 spec.
3299 if((mShaderVersion < 300 || op == EOpAssign || op == EOpInitialize) &&
3300 left->getType().isStructureContainingSamplers())
3302 error(loc, "undefined operation for structs containing samplers", getOperatorString(op));
3306 case EOpGreaterThan:
3307 case EOpLessThanEqual:
3308 case EOpGreaterThanEqual:
3309 if((left->getNominalSize() != right->getNominalSize()) ||
3310 (left->getSecondarySize() != right->getSecondarySize()))
3319 case EOpBitShiftLeft:
3320 case EOpBitShiftRight:
3328 case EOpBitShiftLeftAssign:
3329 case EOpBitShiftRightAssign:
3330 case EOpBitwiseAndAssign:
3331 case EOpBitwiseXorAssign:
3332 case EOpBitwiseOrAssign:
3333 if((left->isMatrix() && right->isVector()) || (left->isVector() && right->isMatrix()))
3338 // Are the sizes compatible?
3339 if(left->getNominalSize() != right->getNominalSize() || left->getSecondarySize() != right->getSecondarySize())
3341 // If the nominal sizes of operands do not match:
3342 // One of them must be a scalar.
3343 if(!left->isScalar() && !right->isScalar())
3346 // In the case of compound assignment other than multiply-assign,
3347 // the right side needs to be a scalar. Otherwise a vector/matrix
3348 // would be assigned to a scalar. A scalar can't be shifted by a
3350 if(!right->isScalar() && (IsAssignment(op) || op == EOpBitShiftLeft || op == EOpBitShiftRight))
3361 TIntermSwitch *TParseContext::addSwitch(TIntermTyped *init, TIntermAggregate *statementList, const TSourceLoc &loc)
3363 TBasicType switchType = init->getBasicType();
3364 if((switchType != EbtInt && switchType != EbtUInt) ||
3369 error(init->getLine(), "init-expression in a switch statement must be a scalar integer", "switch");
3376 if(!ValidateSwitch::validate(switchType, this, statementList, loc))
3383 TIntermSwitch *node = intermediate.addSwitch(init, statementList, loc);
3386 error(loc, "erroneous switch statement", "switch");
3393 TIntermCase *TParseContext::addCase(TIntermTyped *condition, const TSourceLoc &loc)
3395 if(mSwitchNestingLevel == 0)
3397 error(loc, "case labels need to be inside switch statements", "case");
3401 if(condition == nullptr)
3403 error(loc, "case label must have a condition", "case");
3407 if((condition->getBasicType() != EbtInt && condition->getBasicType() != EbtUInt) ||
3408 condition->isMatrix() ||
3409 condition->isArray() ||
3410 condition->isVector())
3412 error(condition->getLine(), "case label must be a scalar integer", "case");
3415 TIntermConstantUnion *conditionConst = condition->getAsConstantUnion();
3416 if(conditionConst == nullptr)
3418 error(condition->getLine(), "case label must be constant", "case");
3421 TIntermCase *node = intermediate.addCase(condition, loc);
3424 error(loc, "erroneous case statement", "case");
3431 TIntermCase *TParseContext::addDefault(const TSourceLoc &loc)
3433 if(mSwitchNestingLevel == 0)
3435 error(loc, "default labels need to be inside switch statements", "default");
3439 TIntermCase *node = intermediate.addCase(nullptr, loc);
3442 error(loc, "erroneous default statement", "default");
3448 TIntermTyped *TParseContext::createAssign(TOperator op, TIntermTyped *left, TIntermTyped *right, const TSourceLoc &loc)
3450 if(binaryOpCommonCheck(op, left, right, loc))
3452 return intermediate.addAssign(op, left, right, loc);
3457 TIntermTyped *TParseContext::addAssign(TOperator op, TIntermTyped *left, TIntermTyped *right, const TSourceLoc &loc)
3459 TIntermTyped *node = createAssign(op, left, right, loc);
3462 assignError(loc, "assign", left->getCompleteString(), right->getCompleteString());
3469 TIntermTyped *TParseContext::addBinaryMathInternal(TOperator op, TIntermTyped *left, TIntermTyped *right,
3470 const TSourceLoc &loc)
3472 if(!binaryOpCommonCheck(op, left, right, loc))
3481 case EOpGreaterThan:
3482 case EOpLessThanEqual:
3483 case EOpGreaterThanEqual:
3484 ASSERT(!left->isArray() && !right->isArray());
3485 if(left->isMatrix() || left->isVector() ||
3486 left->getBasicType() == EbtStruct)
3494 ASSERT(!left->isArray() && !right->isArray());
3495 if(left->getBasicType() != EbtBool ||
3496 left->isMatrix() || left->isVector())
3505 ASSERT(!left->isArray() && !right->isArray());
3506 if(left->getBasicType() == EbtStruct || left->getBasicType() == EbtBool)
3512 ASSERT(!left->isArray() && !right->isArray());
3513 // Note that this is only for the % operator, not for mod()
3514 if(left->getBasicType() == EbtStruct || left->getBasicType() == EbtBool || left->getBasicType() == EbtFloat)
3519 // Note that for bitwise ops, type checking is done in promote() to
3520 // share code between ops and compound assignment
3525 return intermediate.addBinaryMath(op, left, right, loc);
3528 TIntermTyped *TParseContext::addBinaryMath(TOperator op, TIntermTyped *left, TIntermTyped *right, const TSourceLoc &loc)
3530 TIntermTyped *node = addBinaryMathInternal(op, left, right, loc);
3533 binaryOpError(loc, getOperatorString(op), left->getCompleteString(), right->getCompleteString());
3540 TIntermTyped *TParseContext::addBinaryMathBooleanResult(TOperator op, TIntermTyped *left, TIntermTyped *right, const TSourceLoc &loc)
3542 TIntermTyped *node = addBinaryMathInternal(op, left, right, loc);
3545 binaryOpError(loc, getOperatorString(op), left->getCompleteString(), right->getCompleteString());
3547 ConstantUnion *unionArray = new ConstantUnion[1];
3548 unionArray->setBConst(false);
3549 return intermediate.addConstantUnion(unionArray, TType(EbtBool, EbpUndefined, EvqConstExpr), loc);
3554 TIntermBranch *TParseContext::addBranch(TOperator op, const TSourceLoc &loc)
3559 if(mLoopNestingLevel <= 0)
3561 error(loc, "continue statement only allowed in loops", "");
3566 if(mLoopNestingLevel <= 0 && mSwitchNestingLevel <= 0)
3568 error(loc, "break statement only allowed in loops and switch statements", "");
3573 if(mCurrentFunctionType->getBasicType() != EbtVoid)
3575 error(loc, "non-void function must return a value", "return");
3580 // No checks for discard
3583 return intermediate.addBranch(op, loc);
3586 TIntermBranch *TParseContext::addBranch(TOperator op, TIntermTyped *returnValue, const TSourceLoc &loc)
3588 ASSERT(op == EOpReturn);
3589 mFunctionReturnsValue = true;
3590 if(mCurrentFunctionType->getBasicType() == EbtVoid)
3592 error(loc, "void function cannot return a value", "return");
3595 else if(*mCurrentFunctionType != returnValue->getType())
3597 error(loc, "function return is not matching type:", "return");
3600 return intermediate.addBranch(op, returnValue, loc);
3603 TIntermTyped *TParseContext::addFunctionCallOrMethod(TFunction *fnCall, TIntermNode *paramNode, TIntermNode *thisNode, const TSourceLoc &loc, bool *fatalError)
3605 *fatalError = false;
3606 TOperator op = fnCall->getBuiltInOp();
3607 TIntermTyped *callNode = nullptr;
3609 if(thisNode != nullptr)
3611 ConstantUnion *unionArray = new ConstantUnion[1];
3613 TIntermTyped *typedThis = thisNode->getAsTyped();
3614 if(fnCall->getName() != "length")
3616 error(loc, "invalid method", fnCall->getName().c_str());
3619 else if(paramNode != nullptr)
3621 error(loc, "method takes no parameters", "length");
3624 else if(typedThis == nullptr || !typedThis->isArray())
3626 error(loc, "length can only be called on arrays", "length");
3631 arraySize = typedThis->getArraySize();
3632 if(typedThis->getAsSymbolNode() == nullptr)
3634 // This code path can be hit with expressions like these:
3636 // (func()).length()
3637 // (int[3](0, 1, 2)).length()
3638 // ESSL 3.00 section 5.9 defines expressions so that this is not actually a valid expression.
3639 // It allows "An array name with the length method applied" in contrast to GLSL 4.4 spec section 5.9
3640 // which allows "An array, vector or matrix expression with the length method applied".
3641 error(loc, "length can only be called on array names, not on array expressions", "length");
3645 unionArray->setIConst(arraySize);
3646 callNode = intermediate.addConstantUnion(unionArray, TType(EbtInt, EbpUndefined, EvqConstExpr), loc);
3648 else if(op != EOpNull)
3651 // Then this should be a constructor.
3652 // Don't go through the symbol table for constructors.
3653 // Their parameters will be verified algorithmically.
3655 TType type(EbtVoid, EbpUndefined); // use this to get the type back
3656 if(!constructorErrorCheck(loc, paramNode, *fnCall, op, &type))
3659 // It's a constructor, of type 'type'.
3661 callNode = addConstructor(paramNode, &type, op, fnCall, loc);
3664 if(callNode == nullptr)
3667 callNode = intermediate.setAggregateOperator(nullptr, op, loc);
3673 // Not a constructor. Find it in the symbol table.
3675 const TFunction *fnCandidate;
3677 fnCandidate = findFunction(loc, fnCall, &builtIn);
3681 // A declared function.
3683 if(builtIn && !fnCandidate->getExtension().empty() &&
3684 extensionErrorCheck(loc, fnCandidate->getExtension()))
3688 op = fnCandidate->getBuiltInOp();
3689 if(builtIn && op != EOpNull)
3692 // A function call mapped to a built-in operation.
3694 if(fnCandidate->getParamCount() == 1)
3697 // Treat it like a built-in unary operator.
3699 callNode = createUnaryMath(op, paramNode->getAsTyped(), loc, &fnCandidate->getReturnType());
3700 if(callNode == nullptr)
3702 std::stringstream extraInfoStream;
3703 extraInfoStream << "built in unary operator function. Type: "
3704 << static_cast<TIntermTyped*>(paramNode)->getCompleteString();
3705 std::string extraInfo = extraInfoStream.str();
3706 error(paramNode->getLine(), " wrong operand type", "Internal Error", extraInfo.c_str());
3713 TIntermAggregate *aggregate = intermediate.setAggregateOperator(paramNode, op, loc);
3714 aggregate->setType(fnCandidate->getReturnType());
3716 // Some built-in functions have out parameters too.
3717 functionCallLValueErrorCheck(fnCandidate, aggregate);
3719 callNode = aggregate;
3721 if(fnCandidate->getParamCount() == 2)
3723 TIntermSequence ¶meters = paramNode->getAsAggregate()->getSequence();
3724 TIntermTyped *left = parameters[0]->getAsTyped();
3725 TIntermTyped *right = parameters[1]->getAsTyped();
3727 TIntermConstantUnion *leftTempConstant = left->getAsConstantUnion();
3728 TIntermConstantUnion *rightTempConstant = right->getAsConstantUnion();
3729 if (leftTempConstant && rightTempConstant)
3731 TIntermTyped *typedReturnNode = leftTempConstant->fold(op, rightTempConstant, infoSink());
3735 callNode = typedReturnNode;
3743 // This is a real function call
3745 TIntermAggregate *aggregate = intermediate.setAggregateOperator(paramNode, EOpFunctionCall, loc);
3746 aggregate->setType(fnCandidate->getReturnType());
3748 // this is how we know whether the given function is a builtIn function or a user defined function
3749 // if builtIn == false, it's a userDefined -> could be an overloaded builtIn function also
3750 // if builtIn == true, it's definitely a builtIn function with EOpNull
3752 aggregate->setUserDefined();
3753 aggregate->setName(fnCandidate->getMangledName());
3755 callNode = aggregate;
3757 functionCallLValueErrorCheck(fnCandidate, aggregate);
3762 // error message was put out by findFunction()
3763 // Put on a dummy node for error recovery
3764 ConstantUnion *unionArray = new ConstantUnion[1];
3765 unionArray->setFConst(0.0f);
3766 callNode = intermediate.addConstantUnion(unionArray, TType(EbtFloat, EbpUndefined, EvqConstExpr), loc);
3774 TIntermTyped *TParseContext::addTernarySelection(TIntermTyped *cond, TIntermTyped *trueBlock, TIntermTyped *falseBlock, const TSourceLoc &loc)
3776 if(boolErrorCheck(loc, cond))
3779 if(trueBlock->getType() != falseBlock->getType())
3781 binaryOpError(loc, ":", trueBlock->getCompleteString(), falseBlock->getCompleteString());
3785 // ESSL1 sections 5.2 and 5.7:
3786 // ESSL3 section 5.7:
3787 // Ternary operator is not among the operators allowed for structures/arrays.
3788 if(trueBlock->isArray() || trueBlock->getBasicType() == EbtStruct)
3790 error(loc, "ternary operator is not allowed for structures or arrays", ":");
3794 return intermediate.addSelection(cond, trueBlock, falseBlock, loc);
3798 // Parse an array of strings using yyparse.
3800 // Returns 0 for success.
3802 int PaParseStrings(int count, const char* const string[], const int length[],
3803 TParseContext* context) {
3804 if ((count == 0) || !string)
3807 if (glslang_initialize(context))
3810 int error = glslang_scan(count, string, length, context);
3812 error = glslang_parse(context);
3814 glslang_finalize(context);
3816 return (error == 0) && (context->numErrors() == 0) ? 0 : 1;