blob: fcaca768242c728b9fb84bbfc1d4a04fd7862244 [file] [log] [blame]
//
// Copyright (c) 2002-2014 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "compiler/translator/ParseContext.h"
#include <stdarg.h>
#include <stdio.h>
#include "common/mathutil.h"
#include "compiler/preprocessor/SourceLocation.h"
#include "compiler/translator/Declarator.h"
#include "compiler/translator/ParseContext_autogen.h"
#include "compiler/translator/StaticType.h"
#include "compiler/translator/ValidateGlobalInitializer.h"
#include "compiler/translator/ValidateSwitch.h"
#include "compiler/translator/glslang.h"
#include "compiler/translator/tree_util/IntermNode_util.h"
#include "compiler/translator/util.h"
namespace sh
{
///////////////////////////////////////////////////////////////////////
//
// Sub- vector and matrix fields
//
////////////////////////////////////////////////////////////////////////
namespace
{
const int kWebGLMaxStructNesting = 4;
bool ContainsSampler(const TStructure *structType);
bool ContainsSampler(const TType &type)
{
if (IsSampler(type.getBasicType()))
{
return true;
}
if (type.getBasicType() == EbtStruct)
{
return ContainsSampler(type.getStruct());
}
return false;
}
bool ContainsSampler(const TStructure *structType)
{
for (const auto &field : structType->fields())
{
if (ContainsSampler(*field->type()))
return true;
}
return false;
}
// Get a token from an image argument to use as an error message token.
const char *GetImageArgumentToken(TIntermTyped *imageNode)
{
ASSERT(IsImage(imageNode->getBasicType()));
while (imageNode->getAsBinaryNode() &&
(imageNode->getAsBinaryNode()->getOp() == EOpIndexIndirect ||
imageNode->getAsBinaryNode()->getOp() == EOpIndexDirect))
{
imageNode = imageNode->getAsBinaryNode()->getLeft();
}
TIntermSymbol *imageSymbol = imageNode->getAsSymbolNode();
if (imageSymbol)
{
return imageSymbol->getName().data();
}
return "image";
}
bool CanSetDefaultPrecisionOnType(const TPublicType &type)
{
if (!SupportsPrecision(type.getBasicType()))
{
return false;
}
if (type.getBasicType() == EbtUInt)
{
// ESSL 3.00.4 section 4.5.4
return false;
}
if (type.isAggregate())
{
// Not allowed to set for aggregate types
return false;
}
return true;
}
// Map input primitive types to input array sizes in a geometry shader.
GLuint GetGeometryShaderInputArraySize(TLayoutPrimitiveType primitiveType)
{
switch (primitiveType)
{
case EptPoints:
return 1u;
case EptLines:
return 2u;
case EptTriangles:
return 3u;
case EptLinesAdjacency:
return 4u;
case EptTrianglesAdjacency:
return 6u;
default:
UNREACHABLE();
return 0u;
}
}
bool IsBufferOrSharedVariable(TIntermTyped *var)
{
if (var->isInterfaceBlock() || var->getQualifier() == EvqBuffer ||
var->getQualifier() == EvqShared)
{
return true;
}
return false;
}
} // namespace
// This tracks each binding point's current default offset for inheritance of subsequent
// variables using the same binding, and keeps offsets unique and non overlapping.
// See GLSL ES 3.1, section 4.4.6.
class TParseContext::AtomicCounterBindingState
{
public:
AtomicCounterBindingState() : mDefaultOffset(0) {}
// Inserts a new span and returns -1 if overlapping, else returns the starting offset of
// newly inserted span.
int insertSpan(int start, size_t length)
{
gl::RangeI newSpan(start, start + static_cast<int>(length));
for (const auto &span : mSpans)
{
if (newSpan.intersects(span))
{
return -1;
}
}
mSpans.push_back(newSpan);
mDefaultOffset = newSpan.high();
return start;
}
// Inserts a new span starting from the default offset.
int appendSpan(size_t length) { return insertSpan(mDefaultOffset, length); }
void setDefaultOffset(int offset) { mDefaultOffset = offset; }
private:
int mDefaultOffset;
std::vector<gl::RangeI> mSpans;
};
TParseContext::TParseContext(TSymbolTable &symt,
TExtensionBehavior &ext,
sh::GLenum type,
ShShaderSpec spec,
ShCompileOptions options,
bool checksPrecErrors,
TDiagnostics *diagnostics,
const ShBuiltInResources &resources)
: symbolTable(symt),
mDeferredNonEmptyDeclarationErrorCheck(false),
mShaderType(type),
mShaderSpec(spec),
mCompileOptions(options),
mShaderVersion(100),
mTreeRoot(nullptr),
mLoopNestingLevel(0),
mStructNestingLevel(0),
mSwitchNestingLevel(0),
mCurrentFunctionType(nullptr),
mFunctionReturnsValue(false),
mChecksPrecisionErrors(checksPrecErrors),
mFragmentPrecisionHighOnESSL1(false),
mDefaultUniformMatrixPacking(EmpColumnMajor),
mDefaultUniformBlockStorage(sh::IsWebGLBasedSpec(spec) ? EbsStd140 : EbsShared),
mDefaultBufferMatrixPacking(EmpColumnMajor),
mDefaultBufferBlockStorage(sh::IsWebGLBasedSpec(spec) ? EbsStd140 : EbsShared),
mDiagnostics(diagnostics),
mDirectiveHandler(ext,
*mDiagnostics,
mShaderVersion,
mShaderType,
resources.WEBGL_debug_shader_precision == 1),
mPreprocessor(mDiagnostics, &mDirectiveHandler, angle::pp::PreprocessorSettings(spec)),
mScanner(nullptr),
mMinProgramTexelOffset(resources.MinProgramTexelOffset),
mMaxProgramTexelOffset(resources.MaxProgramTexelOffset),
mMinProgramTextureGatherOffset(resources.MinProgramTextureGatherOffset),
mMaxProgramTextureGatherOffset(resources.MaxProgramTextureGatherOffset),
mComputeShaderLocalSizeDeclared(false),
mComputeShaderLocalSize(-1),
mNumViews(-1),
mMaxNumViews(resources.MaxViewsOVR),
mMaxImageUnits(resources.MaxImageUnits),
mMaxCombinedTextureImageUnits(resources.MaxCombinedTextureImageUnits),
mMaxUniformLocations(resources.MaxUniformLocations),
mMaxUniformBufferBindings(resources.MaxUniformBufferBindings),
mMaxAtomicCounterBindings(resources.MaxAtomicCounterBindings),
mMaxShaderStorageBufferBindings(resources.MaxShaderStorageBufferBindings),
mDeclaringFunction(false),
mGeometryShaderInputPrimitiveType(EptUndefined),
mGeometryShaderOutputPrimitiveType(EptUndefined),
mGeometryShaderInvocations(0),
mGeometryShaderMaxVertices(-1),
mMaxGeometryShaderInvocations(resources.MaxGeometryShaderInvocations),
mMaxGeometryShaderMaxVertices(resources.MaxGeometryOutputVertices)
{}
TParseContext::~TParseContext() {}
bool TParseContext::parseVectorFields(const TSourceLoc &line,
const ImmutableString &compString,
int vecSize,
TVector<int> *fieldOffsets)
{
ASSERT(fieldOffsets);
size_t fieldCount = compString.length();
if (fieldCount > 4u)
{
error(line, "illegal vector field selection", compString);
return false;
}
fieldOffsets->resize(fieldCount);
enum
{
exyzw,
ergba,
estpq
} fieldSet[4];
for (unsigned int i = 0u; i < fieldOffsets->size(); ++i)
{
switch (compString[i])
{
case 'x':
(*fieldOffsets)[i] = 0;
fieldSet[i] = exyzw;
break;
case 'r':
(*fieldOffsets)[i] = 0;
fieldSet[i] = ergba;
break;
case 's':
(*fieldOffsets)[i] = 0;
fieldSet[i] = estpq;
break;
case 'y':
(*fieldOffsets)[i] = 1;
fieldSet[i] = exyzw;
break;
case 'g':
(*fieldOffsets)[i] = 1;
fieldSet[i] = ergba;
break;
case 't':
(*fieldOffsets)[i] = 1;
fieldSet[i] = estpq;
break;
case 'z':
(*fieldOffsets)[i] = 2;
fieldSet[i] = exyzw;
break;
case 'b':
(*fieldOffsets)[i] = 2;
fieldSet[i] = ergba;
break;
case 'p':
(*fieldOffsets)[i] = 2;
fieldSet[i] = estpq;
break;
case 'w':
(*fieldOffsets)[i] = 3;
fieldSet[i] = exyzw;
break;
case 'a':
(*fieldOffsets)[i] = 3;
fieldSet[i] = ergba;
break;
case 'q':
(*fieldOffsets)[i] = 3;
fieldSet[i] = estpq;
break;
default:
error(line, "illegal vector field selection", compString);
return false;
}
}
for (unsigned int i = 0u; i < fieldOffsets->size(); ++i)
{
if ((*fieldOffsets)[i] >= vecSize)
{
error(line, "vector field selection out of range", compString);
return false;
}
if (i > 0)
{
if (fieldSet[i] != fieldSet[i - 1])
{
error(line, "illegal - vector component fields not from the same set", compString);
return false;
}
}
}
return true;
}
///////////////////////////////////////////////////////////////////////
//
// Errors
//
////////////////////////////////////////////////////////////////////////
//
// Used by flex/bison to output all syntax and parsing errors.
//
void TParseContext::error(const TSourceLoc &loc, const char *reason, const char *token)
{
mDiagnostics->error(loc, reason, token);
}
void TParseContext::error(const TSourceLoc &loc, const char *reason, const ImmutableString &token)
{
mDiagnostics->error(loc, reason, token.data());
}
void TParseContext::warning(const TSourceLoc &loc, const char *reason, const char *token)
{
mDiagnostics->warning(loc, reason, token);
}
void TParseContext::outOfRangeError(bool isError,
const TSourceLoc &loc,
const char *reason,
const char *token)
{
if (isError)
{
error(loc, reason, token);
}
else
{
warning(loc, reason, token);
}
}
//
// Same error message for all places assignments don't work.
//
void TParseContext::assignError(const TSourceLoc &line,
const char *op,
const TType &left,
const TType &right)
{
TInfoSinkBase reasonStream;
reasonStream << "cannot convert from '" << right << "' to '" << left << "'";
error(line, reasonStream.c_str(), op);
}
//
// Same error message for all places unary operations don't work.
//
void TParseContext::unaryOpError(const TSourceLoc &line, const char *op, const TType &operand)
{
TInfoSinkBase reasonStream;
reasonStream << "wrong operand type - no operation '" << op
<< "' exists that takes an operand of type " << operand
<< " (or there is no acceptable conversion)";
error(line, reasonStream.c_str(), op);
}
//
// Same error message for all binary operations don't work.
//
void TParseContext::binaryOpError(const TSourceLoc &line,
const char *op,
const TType &left,
const TType &right)
{
TInfoSinkBase reasonStream;
reasonStream << "wrong operand types - no operation '" << op
<< "' exists that takes a left-hand operand of type '" << left
<< "' and a right operand of type '" << right
<< "' (or there is no acceptable conversion)";
error(line, reasonStream.c_str(), op);
}
void TParseContext::checkPrecisionSpecified(const TSourceLoc &line,
TPrecision precision,
TBasicType type)
{
if (!mChecksPrecisionErrors)
return;
if (precision != EbpUndefined && !SupportsPrecision(type))
{
error(line, "illegal type for precision qualifier", getBasicString(type));
}
if (precision == EbpUndefined)
{
switch (type)
{
case EbtFloat:
error(line, "No precision specified for (float)", "");
return;
case EbtInt:
case EbtUInt:
UNREACHABLE(); // there's always a predeclared qualifier
error(line, "No precision specified (int)", "");
return;
default:
if (IsOpaqueType(type))
{
error(line, "No precision specified", getBasicString(type));
return;
}
}
}
}
void TParseContext::markStaticReadIfSymbol(TIntermNode *node)
{
TIntermSwizzle *swizzleNode = node->getAsSwizzleNode();
if (swizzleNode)
{
markStaticReadIfSymbol(swizzleNode->getOperand());
return;
}
TIntermBinary *binaryNode = node->getAsBinaryNode();
if (binaryNode)
{
switch (binaryNode->getOp())
{
case EOpIndexDirect:
case EOpIndexIndirect:
case EOpIndexDirectStruct:
case EOpIndexDirectInterfaceBlock:
markStaticReadIfSymbol(binaryNode->getLeft());
return;
default:
return;
}
}
TIntermSymbol *symbolNode = node->getAsSymbolNode();
if (symbolNode)
{
symbolTable.markStaticRead(symbolNode->variable());
}
}
// Both test and if necessary, spit out an error, to see if the node is really
// an l-value that can be operated on this way.
bool TParseContext::checkCanBeLValue(const TSourceLoc &line, const char *op, TIntermTyped *node)
{
TIntermSwizzle *swizzleNode = node->getAsSwizzleNode();
if (swizzleNode)
{
bool ok = checkCanBeLValue(line, op, swizzleNode->getOperand());
if (ok && swizzleNode->hasDuplicateOffsets())
{
error(line, " l-value of swizzle cannot have duplicate components", op);
return false;
}
return ok;
}
TIntermBinary *binaryNode = node->getAsBinaryNode();
if (binaryNode)
{
switch (binaryNode->getOp())
{
case EOpIndexDirect:
case EOpIndexIndirect:
case EOpIndexDirectStruct:
case EOpIndexDirectInterfaceBlock:
if (node->getMemoryQualifier().readonly)
{
error(line, "can't modify a readonly variable", op);
return false;
}
return checkCanBeLValue(line, op, binaryNode->getLeft());
default:
break;
}
error(line, " l-value required", op);
return false;
}
std::string message;
switch (node->getQualifier())
{
case EvqConst:
message = "can't modify a const";
break;
case EvqConstReadOnly:
message = "can't modify a const";
break;
case EvqAttribute:
message = "can't modify an attribute";
break;
case EvqFragmentIn:
case EvqVertexIn:
case EvqGeometryIn:
case EvqFlatIn:
case EvqSmoothIn:
case EvqCentroidIn:
message = "can't modify an input";
break;
case EvqUniform:
message = "can't modify a uniform";
break;
case EvqVaryingIn:
message = "can't modify a varying";
break;
case EvqFragCoord:
message = "can't modify gl_FragCoord";
break;
case EvqFrontFacing:
message = "can't modify gl_FrontFacing";
break;
case EvqPointCoord:
message = "can't modify gl_PointCoord";
break;
case EvqNumWorkGroups:
message = "can't modify gl_NumWorkGroups";
break;
case EvqWorkGroupSize:
message = "can't modify gl_WorkGroupSize";
break;
case EvqWorkGroupID:
message = "can't modify gl_WorkGroupID";
break;
case EvqLocalInvocationID:
message = "can't modify gl_LocalInvocationID";
break;
case EvqGlobalInvocationID:
message = "can't modify gl_GlobalInvocationID";
break;
case EvqLocalInvocationIndex:
message = "can't modify gl_LocalInvocationIndex";
break;
case EvqViewIDOVR:
message = "can't modify gl_ViewID_OVR";
break;
case EvqComputeIn:
message = "can't modify work group size variable";
break;
case EvqPerVertexIn:
message = "can't modify any member in gl_in";
break;
case EvqPrimitiveIDIn:
message = "can't modify gl_PrimitiveIDIn";
break;
case EvqInvocationID:
message = "can't modify gl_InvocationID";
break;
case EvqPrimitiveID:
if (mShaderType == GL_FRAGMENT_SHADER)
{
message = "can't modify gl_PrimitiveID in a fragment shader";
}
break;
case EvqLayer:
if (mShaderType == GL_FRAGMENT_SHADER)
{
message = "can't modify gl_Layer in a fragment shader";
}
break;
default:
//
// Type that can't be written to?
//
if (node->getBasicType() == EbtVoid)
{
message = "can't modify void";
}
if (IsOpaqueType(node->getBasicType()))
{
message = "can't modify a variable with type ";
message += getBasicString(node->getBasicType());
}
else if (node->getMemoryQualifier().readonly)
{
message = "can't modify a readonly variable";
}
}
ASSERT(binaryNode == nullptr && swizzleNode == nullptr);
TIntermSymbol *symNode = node->getAsSymbolNode();
if (message.empty() && symNode != nullptr)
{
symbolTable.markStaticWrite(symNode->variable());
return true;
}
std::stringstream reasonStream;
reasonStream << "l-value required";
if (!message.empty())
{
if (symNode)
{
// Symbol inside an expression can't be nameless.
ASSERT(symNode->variable().symbolType() != SymbolType::Empty);
const ImmutableString &symbol = symNode->getName();
reasonStream << " (" << message << " \"" << symbol << "\")";
}
else
{
reasonStream << " (" << message << ")";
}
}
std::string reason = reasonStream.str();
error(line, reason.c_str(), op);
return false;
}
// Both test, and if necessary spit out an error, to see if the node is really
// a constant.
void TParseContext::checkIsConst(TIntermTyped *node)
{
if (node->getQualifier() != EvqConst)
{
error(node->getLine(), "constant expression required", "");
}
}
// Both test, and if necessary spit out an error, to see if the node is really
// an integer.
void TParseContext::checkIsScalarInteger(TIntermTyped *node, const char *token)
{
if (!node->isScalarInt())
{
error(node->getLine(), "integer expression required", token);
}
}
// Both test, and if necessary spit out an error, to see if we are currently
// globally scoped.
bool TParseContext::checkIsAtGlobalLevel(const TSourceLoc &line, const char *token)
{
if (!symbolTable.atGlobalLevel())
{
error(line, "only allowed at global scope", token);
return false;
}
return true;
}
// ESSL 3.00.5 sections 3.8 and 3.9.
// If it starts "gl_" or contains two consecutive underscores, it's reserved.
// Also checks for "webgl_" and "_webgl_" reserved identifiers if parsing a webgl shader.
bool TParseContext::checkIsNotReserved(const TSourceLoc &line, const ImmutableString &identifier)
{
static const char *reservedErrMsg = "reserved built-in name";
if (identifier.beginsWith("gl_"))
{
error(line, reservedErrMsg, "gl_");
return false;
}
if (sh::IsWebGLBasedSpec(mShaderSpec))
{
if (identifier.beginsWith("webgl_"))
{
error(line, reservedErrMsg, "webgl_");
return false;
}
if (identifier.beginsWith("_webgl_"))
{
error(line, reservedErrMsg, "_webgl_");
return false;
}
}
if (identifier.contains("__"))
{
error(line,
"identifiers containing two consecutive underscores (__) are reserved as "
"possible future keywords",
identifier);
return false;
}
return true;
}
// Make sure the argument types are correct for constructing a specific type.
bool TParseContext::checkConstructorArguments(const TSourceLoc &line,
const TIntermSequence &arguments,
const TType &type)
{
if (arguments.empty())
{
error(line, "constructor does not have any arguments", "constructor");
return false;
}
for (TIntermNode *arg : arguments)
{
markStaticReadIfSymbol(arg);
const TIntermTyped *argTyped = arg->getAsTyped();
ASSERT(argTyped != nullptr);
if (type.getBasicType() != EbtStruct && IsOpaqueType(argTyped->getBasicType()))
{
std::string reason("cannot convert a variable with type ");
reason += getBasicString(argTyped->getBasicType());
error(line, reason.c_str(), "constructor");
return false;
}
else if (argTyped->getMemoryQualifier().writeonly)
{
error(line, "cannot convert a variable with writeonly", "constructor");
return false;
}
if (argTyped->getBasicType() == EbtVoid)
{
error(line, "cannot convert a void", "constructor");
return false;
}
}
if (type.isArray())
{
// The size of an unsized constructor should already have been determined.
ASSERT(!type.isUnsizedArray());
if (static_cast<size_t>(type.getOutermostArraySize()) != arguments.size())
{
error(line, "array constructor needs one argument per array element", "constructor");
return false;
}
// GLSL ES 3.00 section 5.4.4: Each argument must be the same type as the element type of
// the array.
for (TIntermNode *const &argNode : arguments)
{
const TType &argType = argNode->getAsTyped()->getType();
if (mShaderVersion < 310 && argType.isArray())
{
error(line, "constructing from a non-dereferenced array", "constructor");
return false;
}
if (!argType.isElementTypeOf(type))
{
error(line, "Array constructor argument has an incorrect type", "constructor");
return false;
}
}
}
else if (type.getBasicType() == EbtStruct)
{
const TFieldList &fields = type.getStruct()->fields();
if (fields.size() != arguments.size())
{
error(line,
"Number of constructor parameters does not match the number of structure fields",
"constructor");
return false;
}
for (size_t i = 0; i < fields.size(); i++)
{
if (i >= arguments.size() ||
arguments[i]->getAsTyped()->getType() != *fields[i]->type())
{
error(line, "Structure constructor arguments do not match structure fields",
"constructor");
return false;
}
}
}
else
{
// We're constructing a scalar, vector, or matrix.
// Note: It's okay to have too many components available, but not okay to have unused
// arguments. 'full' will go to true when enough args have been seen. If we loop again,
// there is an extra argument, so 'overFull' will become true.
size_t size = 0;
bool full = false;
bool overFull = false;
bool matrixArg = false;
for (TIntermNode *arg : arguments)
{
const TIntermTyped *argTyped = arg->getAsTyped();
ASSERT(argTyped != nullptr);
if (argTyped->getBasicType() == EbtStruct)
{
error(line, "a struct cannot be used as a constructor argument for this type",
"constructor");
return false;
}
if (argTyped->getType().isArray())
{
error(line, "constructing from a non-dereferenced array", "constructor");
return false;
}
if (argTyped->getType().isMatrix())
{
matrixArg = true;
}
size += argTyped->getType().getObjectSize();
if (full)
{
overFull = true;
}
if (size >= type.getObjectSize())
{
full = true;
}
}
if (type.isMatrix() && matrixArg)
{
if (arguments.size() != 1)
{
error(line, "constructing matrix from matrix can only take one argument",
"constructor");
return false;
}
}
else
{
if (size != 1 && size < type.getObjectSize())
{
error(line, "not enough data provided for construction", "constructor");
return false;
}
if (overFull)
{
error(line, "too many arguments", "constructor");
return false;
}
}
}
return true;
}
// This function checks to see if a void variable has been declared and raise an error message for
// such a case
//
// returns true in case of an error
//
bool TParseContext::checkIsNonVoid(const TSourceLoc &line,
const ImmutableString &identifier,
const TBasicType &type)
{
if (type == EbtVoid)
{
error(line, "illegal use of type 'void'", identifier);
return false;
}
return true;
}
// This function checks to see if the node (for the expression) contains a scalar boolean expression
// or not.
bool TParseContext::checkIsScalarBool(const TSourceLoc &line, const TIntermTyped *type)
{
if (type->getBasicType() != EbtBool || !type->isScalar())
{
error(line, "boolean expression expected", "");
return false;
}
return true;
}
// This function checks to see if the node (for the expression) contains a scalar boolean expression
// or not.
void TParseContext::checkIsScalarBool(const TSourceLoc &line, const TPublicType &pType)
{
if (pType.getBasicType() != EbtBool || pType.isAggregate())
{
error(line, "boolean expression expected", "");
}
}
bool TParseContext::checkIsNotOpaqueType(const TSourceLoc &line,
const TTypeSpecifierNonArray &pType,
const char *reason)
{
if (pType.type == EbtStruct)
{
if (ContainsSampler(pType.userDef))
{
std::stringstream reasonStream;
reasonStream << reason << " (structure contains a sampler)";
std::string reasonStr = reasonStream.str();
error(line, reasonStr.c_str(), getBasicString(pType.type));
return false;
}
// only samplers need to be checked from structs, since other opaque types can't be struct
// members.
return true;
}
else if (IsOpaqueType(pType.type))
{
error(line, reason, getBasicString(pType.type));
return false;
}
return true;
}
void TParseContext::checkDeclaratorLocationIsNotSpecified(const TSourceLoc &line,
const TPublicType &pType)
{
if (pType.layoutQualifier.location != -1)
{
error(line, "location must only be specified for a single input or output variable",
"location");
}
}
void TParseContext::checkLocationIsNotSpecified(const TSourceLoc &location,
const TLayoutQualifier &layoutQualifier)
{
if (layoutQualifier.location != -1)
{
const char *errorMsg = "invalid layout qualifier: only valid on program inputs and outputs";
if (mShaderVersion >= 310)
{
errorMsg =
"invalid layout qualifier: only valid on shader inputs, outputs, and uniforms";
}
error(location, errorMsg, "location");
}
}
void TParseContext::checkStd430IsForShaderStorageBlock(const TSourceLoc &location,
const TLayoutBlockStorage &blockStorage,
const TQualifier &qualifier)
{
if (blockStorage == EbsStd430 && qualifier != EvqBuffer)
{
error(location, "The std430 layout is supported only for shader storage blocks.", "std430");
}
}
void TParseContext::checkOutParameterIsNotOpaqueType(const TSourceLoc &line,
TQualifier qualifier,
const TType &type)
{
ASSERT(qualifier == EvqOut || qualifier == EvqInOut);
if (IsOpaqueType(type.getBasicType()))
{
error(line, "opaque types cannot be output parameters", type.getBasicString());
}
}
// Do size checking for an array type's size.
unsigned int TParseContext::checkIsValidArraySize(const TSourceLoc &line, TIntermTyped *expr)
{
TIntermConstantUnion *constant = expr->getAsConstantUnion();
// ANGLE should be able to fold any EvqConst expressions resulting in an integer - but to be
// safe against corner cases we still check for constant folding. Some interpretations of the
// spec have allowed constant expressions with side effects - like array length() method on a
// non-constant array.
if (expr->getQualifier() != EvqConst || constant == nullptr || !constant->isScalarInt())
{
error(line, "array size must be a constant integer expression", "");
return 1u;
}
unsigned int size = 0u;
if (constant->getBasicType() == EbtUInt)
{
size = constant->getUConst(0);
}
else
{
int signedSize = constant->getIConst(0);
if (signedSize < 0)
{
error(line, "array size must be non-negative", "");
return 1u;
}
size = static_cast<unsigned int>(signedSize);
}
if (size == 0u)
{
error(line, "array size must be greater than zero", "");
return 1u;
}
// The size of arrays is restricted here to prevent issues further down the
// compiler/translator/driver stack. Shader Model 5 generation hardware is limited to
// 4096 registers so this should be reasonable even for aggressively optimizable code.
const unsigned int sizeLimit = 65536;
if (size > sizeLimit)
{
error(line, "array size too large", "");
return 1u;
}
return size;
}
// See if this qualifier can be an array.
bool TParseContext::checkIsValidQualifierForArray(const TSourceLoc &line,
const TPublicType &elementQualifier)
{
if ((elementQualifier.qualifier == EvqAttribute) ||
(elementQualifier.qualifier == EvqVertexIn) ||
(elementQualifier.qualifier == EvqConst && mShaderVersion < 300))
{
error(line, "cannot declare arrays of this qualifier",
TType(elementQualifier).getQualifierString());
return false;
}
return true;
}
// See if this element type can be formed into an array.
bool TParseContext::checkArrayElementIsNotArray(const TSourceLoc &line,
const TPublicType &elementType)
{
if (mShaderVersion < 310 && elementType.isArray())
{
TInfoSinkBase typeString;
typeString << TType(elementType);
error(line, "cannot declare arrays of arrays", typeString.c_str());
return false;
}
return true;
}
// Check if this qualified element type can be formed into an array. This is only called when array
// brackets are associated with an identifier in a declaration, like this:
// float a[2];
// Similar checks are done in addFullySpecifiedType for array declarations where the array brackets
// are associated with the type, like this:
// float[2] a;
bool TParseContext::checkIsValidTypeAndQualifierForArray(const TSourceLoc &indexLocation,
const TPublicType &elementType)
{
if (!checkArrayElementIsNotArray(indexLocation, elementType))
{
return false;
}
// In ESSL1.00 shaders, structs cannot be varying (section 4.3.5). This is checked elsewhere.
// In ESSL3.00 shaders, struct inputs/outputs are allowed but not arrays of structs (section
// 4.3.4).
// Geometry shader requires each user-defined input be declared as arrays or inside input
// blocks declared as arrays (GL_EXT_geometry_shader section 11.1gs.4.3). For the purposes of
// interface matching, such variables and blocks are treated as though they were not declared
// as arrays (GL_EXT_geometry_shader section 7.4.1).
if (mShaderVersion >= 300 && elementType.getBasicType() == EbtStruct &&
sh::IsVarying(elementType.qualifier) &&
!IsGeometryShaderInput(mShaderType, elementType.qualifier))
{
TInfoSinkBase typeString;
typeString << TType(elementType);
error(indexLocation, "cannot declare arrays of structs of this qualifier",
typeString.c_str());
return false;
}
return checkIsValidQualifierForArray(indexLocation, elementType);
}
// Enforce non-initializer type/qualifier rules.
void TParseContext::checkCanBeDeclaredWithoutInitializer(const TSourceLoc &line,
const ImmutableString &identifier,
TType *type)
{
ASSERT(type != nullptr);
if (type->getQualifier() == EvqConst)
{
// Make the qualifier make sense.
type->setQualifier(EvqTemporary);
// Generate informative error messages for ESSL1.
// In ESSL3 arrays and structures containing arrays can be constant.
if (mShaderVersion < 300 && type->isStructureContainingArrays())
{
error(line,
"structures containing arrays may not be declared constant since they cannot be "
"initialized",
identifier);
}
else
{
error(line, "variables with qualifier 'const' must be initialized", identifier);
}
}
// This will make the type sized if it isn't sized yet.
checkIsNotUnsizedArray(line, "implicitly sized arrays need to be initialized", identifier,
type);
}
// Do some simple checks that are shared between all variable declarations,
// and update the symbol table.
//
// Returns true if declaring the variable succeeded.
//
bool TParseContext::declareVariable(const TSourceLoc &line,
const ImmutableString &identifier,
const TType *type,
TVariable **variable)
{
ASSERT((*variable) == nullptr);
(*variable) = new TVariable(&symbolTable, identifier, type, SymbolType::UserDefined);
ASSERT(type->getLayoutQualifier().index == -1 ||
(isExtensionEnabled(TExtension::EXT_blend_func_extended) &&
mShaderType == GL_FRAGMENT_SHADER && mShaderVersion >= 300));
if (type->getQualifier() == EvqFragmentOut)
{
if (type->getLayoutQualifier().index != -1 && type->getLayoutQualifier().location == -1)
{
error(line,
"If index layout qualifier is specified for a fragment output, location must "
"also be specified.",
"index");
return false;
}
}
else
{
checkIndexIsNotSpecified(line, type->getLayoutQualifier().index);
}
checkBindingIsValid(line, *type);
bool needsReservedCheck = true;
// gl_LastFragData may be redeclared with a new precision qualifier
if (type->isArray() && identifier.beginsWith("gl_LastFragData"))
{
const TVariable *maxDrawBuffers = static_cast<const TVariable *>(
symbolTable.findBuiltIn(ImmutableString("gl_MaxDrawBuffers"), mShaderVersion));
if (type->isArrayOfArrays())
{
error(line, "redeclaration of gl_LastFragData as an array of arrays", identifier);
return false;
}
else if (static_cast<int>(type->getOutermostArraySize()) ==
maxDrawBuffers->getConstPointer()->getIConst())
{
if (const TSymbol *builtInSymbol = symbolTable.findBuiltIn(identifier, mShaderVersion))
{
needsReservedCheck = !checkCanUseExtension(line, builtInSymbol->extension());
}
}
else
{
error(line, "redeclaration of gl_LastFragData with size != gl_MaxDrawBuffers",
identifier);
return false;
}
}
if (needsReservedCheck && !checkIsNotReserved(line, identifier))
return false;
if (!symbolTable.declare(*variable))
{
error(line, "redefinition", identifier);
return false;
}
if (!checkIsNonVoid(line, identifier, type->getBasicType()))
return false;
return true;
}
void TParseContext::checkIsParameterQualifierValid(
const TSourceLoc &line,
const TTypeQualifierBuilder &typeQualifierBuilder,
TType *type)
{
// The only parameter qualifiers a parameter can have are in, out, inout or const.
TTypeQualifier typeQualifier = typeQualifierBuilder.getParameterTypeQualifier(mDiagnostics);
if (typeQualifier.qualifier == EvqOut || typeQualifier.qualifier == EvqInOut)
{
checkOutParameterIsNotOpaqueType(line, typeQualifier.qualifier, *type);
}
if (!IsImage(type->getBasicType()))
{
checkMemoryQualifierIsNotSpecified(typeQualifier.memoryQualifier, line);
}
else
{
type->setMemoryQualifier(typeQualifier.memoryQualifier);
}
type->setQualifier(typeQualifier.qualifier);
if (typeQualifier.precision != EbpUndefined)
{
type->setPrecision(typeQualifier.precision);
}
}
template <size_t size>
bool TParseContext::checkCanUseOneOfExtensions(const TSourceLoc &line,
const std::array<TExtension, size> &extensions)
{
ASSERT(!extensions.empty());
const TExtensionBehavior &extBehavior = extensionBehavior();
bool canUseWithWarning = false;
bool canUseWithoutWarning = false;
const char *errorMsgString = "";
TExtension errorMsgExtension = TExtension::UNDEFINED;
for (TExtension extension : extensions)
{
auto extIter = extBehavior.find(extension);
if (canUseWithWarning)
{
// We already have an extension that we can use, but with a warning.
// See if we can use the alternative extension without a warning.
if (extIter == extBehavior.end())
{
continue;
}
if (extIter->second == EBhEnable || extIter->second == EBhRequire)
{
canUseWithoutWarning = true;
break;
}
continue;
}
if (extIter == extBehavior.end())
{
errorMsgString = "extension is not supported";
errorMsgExtension = extension;
}
else if (extIter->second == EBhUndefined || extIter->second == EBhDisable)
{
errorMsgString = "extension is disabled";
errorMsgExtension = extension;
}
else if (extIter->second == EBhWarn)
{
errorMsgExtension = extension;
canUseWithWarning = true;
}
else
{
ASSERT(extIter->second == EBhEnable || extIter->second == EBhRequire);
canUseWithoutWarning = true;
break;
}
}
if (canUseWithoutWarning)
{
return true;
}
if (canUseWithWarning)
{
warning(line, "extension is being used", GetExtensionNameString(errorMsgExtension));
return true;
}
error(line, errorMsgString, GetExtensionNameString(errorMsgExtension));
return false;
}
template bool TParseContext::checkCanUseOneOfExtensions(
const TSourceLoc &line,
const std::array<TExtension, 1> &extensions);
template bool TParseContext::checkCanUseOneOfExtensions(
const TSourceLoc &line,
const std::array<TExtension, 2> &extensions);
template bool TParseContext::checkCanUseOneOfExtensions(
const TSourceLoc &line,
const std::array<TExtension, 3> &extensions);
bool TParseContext::checkCanUseExtension(const TSourceLoc &line, TExtension extension)
{
ASSERT(extension != TExtension::UNDEFINED);
return checkCanUseOneOfExtensions(line, std::array<TExtension, 1u>{{extension}});
}
// ESSL 3.00.6 section 4.8 Empty Declarations: "The combinations of qualifiers that cause
// compile-time or link-time errors are the same whether or not the declaration is empty".
// This function implements all the checks that are done on qualifiers regardless of if the
// declaration is empty.
void TParseContext::declarationQualifierErrorCheck(const sh::TQualifier qualifier,
const sh::TLayoutQualifier &layoutQualifier,
const TSourceLoc &location)
{
if (qualifier == EvqShared && !layoutQualifier.isEmpty())
{
error(location, "Shared memory declarations cannot have layout specified", "layout");
}
if (layoutQualifier.matrixPacking != EmpUnspecified)
{
error(location, "layout qualifier only valid for interface blocks",
getMatrixPackingString(layoutQualifier.matrixPacking));
return;
}
if (layoutQualifier.blockStorage != EbsUnspecified)
{
error(location, "layout qualifier only valid for interface blocks",
getBlockStorageString(layoutQualifier.blockStorage));
return;
}
if (qualifier == EvqFragmentOut)
{
if (layoutQualifier.location != -1 && layoutQualifier.yuv == true)
{
error(location, "invalid layout qualifier combination", "yuv");
return;
}
}
else
{
checkYuvIsNotSpecified(location, layoutQualifier.yuv);
}
// If multiview extension is enabled, "in" qualifier is allowed in the vertex shader in previous
// parsing steps. So it needs to be checked here.
if (isExtensionEnabled(TExtension::OVR_multiview) && mShaderVersion < 300 &&
qualifier == EvqVertexIn)
{
error(location, "storage qualifier supported in GLSL ES 3.00 and above only", "in");
}
bool canHaveLocation = qualifier == EvqVertexIn || qualifier == EvqFragmentOut;
if (mShaderVersion >= 310)
{
canHaveLocation = canHaveLocation || qualifier == EvqUniform || IsVarying(qualifier);
// We're not checking whether the uniform location is in range here since that depends on
// the type of the variable.
// The type can only be fully determined for non-empty declarations.
}
if (!canHaveLocation)
{
checkLocationIsNotSpecified(location, layoutQualifier);
}
}
void TParseContext::atomicCounterQualifierErrorCheck(const TPublicType &publicType,
const TSourceLoc &location)
{
if (publicType.precision != EbpHigh)
{
error(location, "Can only be highp", "atomic counter");
}
// dEQP enforces compile error if location is specified. See uniform_location.test.
if (publicType.layoutQualifier.location != -1)
{
error(location, "location must not be set for atomic_uint", "layout");
}
if (publicType.layoutQualifier.binding == -1)
{
error(location, "no binding specified", "atomic counter");
}
}
void TParseContext::emptyDeclarationErrorCheck(const TType &type, const TSourceLoc &location)
{
if (type.isUnsizedArray())
{
// ESSL3 spec section 4.1.9: Array declaration which leaves the size unspecified is an
// error. It is assumed that this applies to empty declarations as well.
error(location, "empty array declaration needs to specify a size", "");
}
if (type.getQualifier() != EvqFragmentOut)
{
checkIndexIsNotSpecified(location, type.getLayoutQualifier().index);
}
}
// These checks are done for all declarations that are non-empty. They're done for non-empty
// declarations starting a declarator list, and declarators that follow an empty declaration.
void TParseContext::nonEmptyDeclarationErrorCheck(const TPublicType &publicType,
const TSourceLoc &identifierLocation)
{
switch (publicType.qualifier)
{
case EvqVaryingIn:
case EvqVaryingOut:
case EvqAttribute:
case EvqVertexIn:
case EvqFragmentOut:
case EvqComputeIn:
if (publicType.getBasicType() == EbtStruct)
{
error(identifierLocation, "cannot be used with a structure",
getQualifierString(publicType.qualifier));
return;
}
break;
case EvqBuffer:
if (publicType.getBasicType() != EbtInterfaceBlock)
{
error(identifierLocation,
"cannot declare buffer variables at global scope(outside a block)",
getQualifierString(publicType.qualifier));
return;
}
break;
default:
break;
}
std::string reason(getBasicString(publicType.getBasicType()));
reason += "s must be uniform";
if (publicType.qualifier != EvqUniform &&
!checkIsNotOpaqueType(identifierLocation, publicType.typeSpecifierNonArray, reason.c_str()))
{
return;
}
if ((publicType.qualifier != EvqTemporary && publicType.qualifier != EvqGlobal &&
publicType.qualifier != EvqConst) &&
publicType.getBasicType() == EbtYuvCscStandardEXT)
{
error(identifierLocation, "cannot be used with a yuvCscStandardEXT",
getQualifierString(publicType.qualifier));
return;
}
if (mShaderVersion >= 310 && publicType.qualifier == EvqUniform)
{
// Valid uniform declarations can't be unsized arrays since uniforms can't be initialized.
// But invalid shaders may still reach here with an unsized array declaration.
TType type(publicType);
if (!type.isUnsizedArray())
{
checkUniformLocationInRange(identifierLocation, type.getLocationCount(),
publicType.layoutQualifier);
}
}
// check for layout qualifier issues
const TLayoutQualifier layoutQualifier = publicType.layoutQualifier;
if (IsImage(publicType.getBasicType()))
{
switch (layoutQualifier.imageInternalFormat)
{
case EiifRGBA32F:
case EiifRGBA16F:
case EiifR32F:
case EiifRGBA8:
case EiifRGBA8_SNORM:
if (!IsFloatImage(publicType.getBasicType()))
{
error(identifierLocation,
"internal image format requires a floating image type",
getBasicString(publicType.getBasicType()));
return;
}
break;
case EiifRGBA32I:
case EiifRGBA16I:
case EiifRGBA8I:
case EiifR32I:
if (!IsIntegerImage(publicType.getBasicType()))
{
error(identifierLocation,
"internal image format requires an integer image type",
getBasicString(publicType.getBasicType()));
return;
}
break;
case EiifRGBA32UI:
case EiifRGBA16UI:
case EiifRGBA8UI:
case EiifR32UI:
if (!IsUnsignedImage(publicType.getBasicType()))
{
error(identifierLocation,
"internal image format requires an unsigned image type",
getBasicString(publicType.getBasicType()));
return;
}
break;
case EiifUnspecified:
error(identifierLocation, "layout qualifier", "No image internal format specified");
return;
default:
error(identifierLocation, "layout qualifier", "unrecognized token");
return;
}
// GLSL ES 3.10 Revision 4, 4.9 Memory Access Qualifiers
switch (layoutQualifier.imageInternalFormat)
{
case EiifR32F:
case EiifR32I:
case EiifR32UI:
break;
default:
if (!publicType.memoryQualifier.readonly && !publicType.memoryQualifier.writeonly)
{
error(identifierLocation, "layout qualifier",
"Except for images with the r32f, r32i and r32ui format qualifiers, "
"image variables must be qualified readonly and/or writeonly");
return;
}
break;
}
}
else
{
checkInternalFormatIsNotSpecified(identifierLocation, layoutQualifier.imageInternalFormat);
checkMemoryQualifierIsNotSpecified(publicType.memoryQualifier, identifierLocation);
}
if (IsAtomicCounter(publicType.getBasicType()))
{
atomicCounterQualifierErrorCheck(publicType, identifierLocation);
}
else
{
checkOffsetIsNotSpecified(identifierLocation, layoutQualifier.offset);
}
}
void TParseContext::checkBindingIsValid(const TSourceLoc &identifierLocation, const TType &type)
{
TLayoutQualifier layoutQualifier = type.getLayoutQualifier();
// Note that the ESSL 3.10 section 4.4.5 is not particularly clear on how the binding qualifier
// on arrays of arrays should be handled. We interpret the spec so that the binding value is
// incremented for each element of the innermost nested arrays. This is in line with how arrays
// of arrays of blocks are specified to behave in GLSL 4.50 and a conservative interpretation
// when it comes to which shaders are accepted by the compiler.
int arrayTotalElementCount = type.getArraySizeProduct();
if (IsImage(type.getBasicType()))
{
checkImageBindingIsValid(identifierLocation, layoutQualifier.binding,
arrayTotalElementCount);
}
else if (IsSampler(type.getBasicType()))
{
checkSamplerBindingIsValid(identifierLocation, layoutQualifier.binding,
arrayTotalElementCount);
}
else if (IsAtomicCounter(type.getBasicType()))
{
checkAtomicCounterBindingIsValid(identifierLocation, layoutQualifier.binding);
}
else
{
ASSERT(!IsOpaqueType(type.getBasicType()));
checkBindingIsNotSpecified(identifierLocation, layoutQualifier.binding);
}
}
void TParseContext::checkLayoutQualifierSupported(const TSourceLoc &location,
const ImmutableString &layoutQualifierName,
int versionRequired)
{
if (mShaderVersion < versionRequired)
{
error(location, "invalid layout qualifier: not supported", layoutQualifierName);
}
}
bool TParseContext::checkWorkGroupSizeIsNotSpecified(const TSourceLoc &location,
const TLayoutQualifier &layoutQualifier)
{
const sh::WorkGroupSize &localSize = layoutQualifier.localSize;
for (size_t i = 0u; i < localSize.size(); ++i)
{
if (localSize[i] != -1)
{
error(location,
"invalid layout qualifier: only valid when used with 'in' in a compute shader "
"global layout declaration",
getWorkGroupSizeString(i));
return false;
}
}
return true;
}
void TParseContext::checkInternalFormatIsNotSpecified(const TSourceLoc &location,
TLayoutImageInternalFormat internalFormat)
{
if (internalFormat != EiifUnspecified)
{
error(location, "invalid layout qualifier: only valid when used with images",
getImageInternalFormatString(internalFormat));
}
}
void TParseContext::checkIndexIsNotSpecified(const TSourceLoc &location, int index)
{
if (index != -1)
{
error(location,
"invalid layout qualifier: only valid when used with a fragment shader output in "
"ESSL version >= 3.00 and EXT_blend_func_extended is enabled",
"index");
}
}
void TParseContext::checkBindingIsNotSpecified(const TSourceLoc &location, int binding)
{
if (binding != -1)
{
error(location,
"invalid layout qualifier: only valid when used with opaque types or blocks",
"binding");
}
}
void TParseContext::checkOffsetIsNotSpecified(const TSourceLoc &location, int offset)
{
if (offset != -1)
{
error(location, "invalid layout qualifier: only valid when used with atomic counters",
"offset");
}
}
void TParseContext::checkImageBindingIsValid(const TSourceLoc &location,
int binding,
int arrayTotalElementCount)
{
// Expects arraySize to be 1 when setting binding for only a single variable.
if (binding >= 0 && binding + arrayTotalElementCount > mMaxImageUnits)
{
error(location, "image binding greater than gl_MaxImageUnits", "binding");
}
}
void TParseContext::checkSamplerBindingIsValid(const TSourceLoc &location,
int binding,
int arrayTotalElementCount)
{
// Expects arraySize to be 1 when setting binding for only a single variable.
if (binding >= 0 && binding + arrayTotalElementCount > mMaxCombinedTextureImageUnits)
{
error(location, "sampler binding greater than maximum texture units", "binding");
}
}
void TParseContext::checkBlockBindingIsValid(const TSourceLoc &location,
const TQualifier &qualifier,
int binding,
int arraySize)
{
int size = (arraySize == 0 ? 1 : arraySize);
if (qualifier == EvqUniform)
{
if (binding + size > mMaxUniformBufferBindings)
{
error(location, "uniform block binding greater than MAX_UNIFORM_BUFFER_BINDINGS",
"binding");
}
}
else if (qualifier == EvqBuffer)
{
if (binding + size > mMaxShaderStorageBufferBindings)
{
error(location,
"shader storage block binding greater than MAX_SHADER_STORAGE_BUFFER_BINDINGS",
"binding");
}
}
}
void TParseContext::checkAtomicCounterBindingIsValid(const TSourceLoc &location, int binding)
{
if (binding >= mMaxAtomicCounterBindings)
{
error(location, "atomic counter binding greater than gl_MaxAtomicCounterBindings",
"binding");
}
}
void TParseContext::checkUniformLocationInRange(const TSourceLoc &location,
int objectLocationCount,
const TLayoutQualifier &layoutQualifier)
{
int loc = layoutQualifier.location;
if (loc >= 0 && loc + objectLocationCount > mMaxUniformLocations)
{
error(location, "Uniform location out of range", "location");
}
}
void TParseContext::checkYuvIsNotSpecified(const TSourceLoc &location, bool yuv)
{
if (yuv != false)
{
error(location, "invalid layout qualifier: only valid on program outputs", "yuv");
}
}
void TParseContext::functionCallRValueLValueErrorCheck(const TFunction *fnCandidate,
TIntermAggregate *fnCall)
{
for (size_t i = 0; i < fnCandidate->getParamCount(); ++i)
{
TQualifier qual = fnCandidate->getParam(i)->getType().getQualifier();
TIntermTyped *argument = (*(fnCall->getSequence()))[i]->getAsTyped();
bool argumentIsRead = (IsQualifierUnspecified(qual) || qual == EvqIn || qual == EvqInOut ||
qual == EvqConstReadOnly);
if (argumentIsRead)
{
markStaticReadIfSymbol(argument);
if (!IsImage(argument->getBasicType()))
{
if (argument->getMemoryQualifier().writeonly)
{
error(argument->getLine(),
"Writeonly value cannot be passed for 'in' or 'inout' parameters.",
fnCall->functionName());
return;
}
}
}
if (qual == EvqOut || qual == EvqInOut)
{
if (!checkCanBeLValue(argument->getLine(), "assign", argument))
{
error(argument->getLine(),
"Constant value cannot be passed for 'out' or 'inout' parameters.",
fnCall->functionName());
return;
}
}
}
}
void TParseContext::checkInvariantVariableQualifier(bool invariant,
const TQualifier qualifier,
const TSourceLoc &invariantLocation)
{
if (!invariant)
return;
if (mShaderVersion < 300)
{
// input variables in the fragment shader can be also qualified as invariant
if (!sh::CanBeInvariantESSL1(qualifier))
{
error(invariantLocation, "Cannot be qualified as invariant.", "invariant");
}
}
else
{
if (!sh::CanBeInvariantESSL3OrGreater(qualifier))
{
error(invariantLocation, "Cannot be qualified as invariant.", "invariant");
}
}
}
bool TParseContext::isExtensionEnabled(TExtension extension) const
{
return IsExtensionEnabled(extensionBehavior(), extension);
}
void TParseContext::handleExtensionDirective(const TSourceLoc &loc,
const char *extName,
const char *behavior)
{
angle::pp::SourceLocation srcLoc;
srcLoc.file = loc.first_file;
srcLoc.line = loc.first_line;
mDirectiveHandler.handleExtension(srcLoc, extName, behavior);
}
void TParseContext::handlePragmaDirective(const TSourceLoc &loc,
const char *name,
const char *value,
bool stdgl)
{
angle::pp::SourceLocation srcLoc;
srcLoc.file = loc.first_file;
srcLoc.line = loc.first_line;
mDirectiveHandler.handlePragma(srcLoc, name, value, stdgl);
}
sh::WorkGroupSize TParseContext::getComputeShaderLocalSize() const
{
sh::WorkGroupSize result(-1);
for (size_t i = 0u; i < result.size(); ++i)
{
if (mComputeShaderLocalSizeDeclared && mComputeShaderLocalSize[i] == -1)
{
result[i] = 1;
}
else
{
result[i] = mComputeShaderLocalSize[i];
}
}
return result;
}
TIntermConstantUnion *TParseContext::addScalarLiteral(const TConstantUnion *constantUnion,
const TSourceLoc &line)
{
TIntermConstantUnion *node = new TIntermConstantUnion(
constantUnion, TType(constantUnion->getType(), EbpUndefined, EvqConst));
node->setLine(line);
return node;
}
/////////////////////////////////////////////////////////////////////////////////
//
// Non-Errors.
//
/////////////////////////////////////////////////////////////////////////////////
const TVariable *TParseContext::getNamedVariable(const TSourceLoc &location,
const ImmutableString &name,
const TSymbol *symbol)
{
if (!symbol)
{
error(location, "undeclared identifier", name);
return nullptr;
}
if (!symbol->isVariable())
{
error(location, "variable expected", name);
return nullptr;
}
const TVariable *variable = static_cast<const TVariable *>(symbol);
if (variable->extension() != TExtension::UNDEFINED)
{
checkCanUseExtension(location, variable->extension());
}
// GLSL ES 3.1 Revision 4, 7.1.3 Compute Shader Special Variables
if (getShaderType() == GL_COMPUTE_SHADER && !mComputeShaderLocalSizeDeclared &&
variable->getType().getQualifier() == EvqWorkGroupSize)
{
error(location,
"It is an error to use gl_WorkGroupSize before declaring the local group size",
"gl_WorkGroupSize");
}
return variable;
}
TIntermTyped *TParseContext::parseVariableIdentifier(const TSourceLoc &location,
const ImmutableString &name,
const TSymbol *symbol)
{
const TVariable *variable = getNamedVariable(location, name, symbol);
if (!variable)
{
TIntermTyped *node = CreateZeroNode(TType(EbtFloat, EbpHigh, EvqConst));
node->setLine(location);
return node;
}
const TType &variableType = variable->getType();
TIntermTyped *node = nullptr;
if (variable->getConstPointer() && variableType.canReplaceWithConstantUnion())
{
const TConstantUnion *constArray = variable->getConstPointer();
node = new TIntermConstantUnion(constArray, variableType);
}
else if (variableType.getQualifier() == EvqWorkGroupSize && mComputeShaderLocalSizeDeclared)
{
// gl_WorkGroupSize can be used to size arrays according to the ESSL 3.10.4 spec, so it
// needs to be added to the AST as a constant and not as a symbol.
sh::WorkGroupSize workGroupSize = getComputeShaderLocalSize();
TConstantUnion *constArray = new TConstantUnion[3];
for (size_t i = 0; i < 3; ++i)
{
constArray[i].setUConst(static_cast<unsigned int>(workGroupSize[i]));
}
ASSERT(variableType.getBasicType() == EbtUInt);
ASSERT(variableType.getObjectSize() == 3);
TType type(variableType);
type.setQualifier(EvqConst);
node = new TIntermConstantUnion(constArray, type);
}
else if ((mGeometryShaderInputPrimitiveType != EptUndefined) &&
(variableType.getQualifier() == EvqPerVertexIn))
{
ASSERT(symbolTable.getGlInVariableWithArraySize() != nullptr);
node = new TIntermSymbol(symbolTable.getGlInVariableWithArraySize());
}
else
{
node = new TIntermSymbol(variable);
}
ASSERT(node != nullptr);
node->setLine(location);
return node;
}
// Initializers show up in several places in the grammar. Have one set of
// code to handle them here.
//
// Returns true on success.
bool TParseContext::executeInitializer(const TSourceLoc &line,
const ImmutableString &identifier,
TType *type,
TIntermTyped *initializer,
TIntermBinary **initNode)
{
ASSERT(initNode != nullptr);
ASSERT(*initNode == nullptr);
if (type->isUnsizedArray())
{
// In case initializer is not an array or type has more dimensions than initializer, this
// will default to setting array sizes to 1. We have not checked yet whether the initializer
// actually is an array or not. Having a non-array initializer for an unsized array will
// result in an error later, so we don't generate an error message here.
auto *arraySizes = initializer->getType().getArraySizes();
type->sizeUnsizedArrays(arraySizes);
}
const TQualifier qualifier = type->getQualifier();
bool constError = false;
if (qualifier == EvqConst)
{
if (EvqConst != initializer->getType().getQualifier())
{
TInfoSinkBase reasonStream;
reasonStream << "assigning non-constant to '" << *type << "'";
error(line, reasonStream.c_str(), "=");
// We're still going to declare the variable to avoid extra error messages.
type->setQualifier(EvqTemporary);
constError = true;
}
}
TVariable *variable = nullptr;
if (!declareVariable(line, identifier, type, &variable))
{
return false;
}
if (constError)
{
return false;
}
bool globalInitWarning = false;
if (symbolTable.atGlobalLevel() &&
!ValidateGlobalInitializer(initializer, mShaderVersion, &globalInitWarning))
{
// Error message does not completely match behavior with ESSL 1.00, but
// we want to steer developers towards only using constant expressions.
error(line, "global variable initializers must be constant expressions", "=");
return false;
}
if (globalInitWarning)
{
warning(
line,
"global variable initializers should be constant expressions "
"(uniforms and globals are allowed in global initializers for legacy compatibility)",
"=");
}
// identifier must be of type constant, a global, or a temporary
if ((qualifier != EvqTemporary) && (qualifier != EvqGlobal) && (qualifier != EvqConst))
{
error(line, " cannot initialize this type of qualifier ",
variable->getType().getQualifierString());
return false;
}
TIntermSymbol *intermSymbol = new TIntermSymbol(variable);
intermSymbol->setLine(line);
if (!binaryOpCommonCheck(EOpInitialize, intermSymbol, initializer, line))
{
assignError(line, "=", variable->getType(), initializer->getType());
return false;
}
if (qualifier == EvqConst)
{
// Save the constant folded value to the variable if possible.
const TConstantUnion *constArray = initializer->getConstantValue();
if (constArray)
{
variable->shareConstPointer(constArray);
if (initializer->getType().canReplaceWithConstantUnion())
{
ASSERT(*initNode == nullptr);
return true;
}
}
}
*initNode = new TIntermBinary(EOpInitialize, intermSymbol, initializer);
markStaticReadIfSymbol(initializer);
(*initNode)->setLine(line);
return true;
}
TIntermNode *TParseContext::addConditionInitializer(const TPublicType &pType,
const ImmutableString &identifier,
TIntermTyped *initializer,
const TSourceLoc &loc)
{
checkIsScalarBool(loc, pType);
TIntermBinary *initNode = nullptr;
TType *type = new TType(pType);
if (executeInitializer(loc, identifier, type, initializer, &initNode))
{
// The initializer is valid. The init condition needs to have a node - either the
// initializer node, or a constant node in case the initialized variable is const and won't
// be recorded in the AST.
if (initNode == nullptr)
{
return initializer;
}
else
{
TIntermDeclaration *declaration = new TIntermDeclaration();
declaration->appendDeclarator(initNode);
return declaration;
}
}
return nullptr;
}
TIntermNode *TParseContext::addLoop(TLoopType type,
TIntermNode *init,
TIntermNode *cond,
TIntermTyped *expr,
TIntermNode *body,
const TSourceLoc &line)
{
TIntermNode *node = nullptr;
TIntermTyped *typedCond = nullptr;
if (cond)
{
markStaticReadIfSymbol(cond);
typedCond = cond->getAsTyped();
}
if (expr)
{
markStaticReadIfSymbol(expr);
}
// In case the loop body was not parsed as a block and contains a statement that simply refers
// to a variable, we need to mark it as statically used.
if (body)
{
markStaticReadIfSymbol(body);
}
if (cond == nullptr || typedCond)
{
if (type == ELoopDoWhile)
{
checkIsScalarBool(line, typedCond);
}
// In the case of other loops, it was checked before that the condition is a scalar boolean.
ASSERT(mDiagnostics->numErrors() > 0 || typedCond == nullptr ||
(typedCond->getBasicType() == EbtBool && !typedCond->isArray() &&
!typedCond->isVector()));
node = new TIntermLoop(type, init, typedCond, expr, EnsureBlock(body));
node->setLine(line);
return node;
}
ASSERT(type != ELoopDoWhile);
TIntermDeclaration *declaration = cond->getAsDeclarationNode();
ASSERT(declaration);
TIntermBinary *declarator = declaration->getSequence()->front()->getAsBinaryNode();
ASSERT(declarator->getLeft()->getAsSymbolNode());
// The condition is a declaration. In the AST representation we don't support declarations as
// loop conditions. Wrap the loop to a block that declares the condition variable and contains
// the loop.
TIntermBlock *block = new TIntermBlock();
TIntermDeclaration *declareCondition = new TIntermDeclaration();
declareCondition->appendDeclarator(declarator->getLeft()->deepCopy());
block->appendStatement(declareCondition);
TIntermBinary *conditionInit = new TIntermBinary(EOpAssign, declarator->getLeft()->deepCopy(),
declarator->getRight()->deepCopy());
TIntermLoop *loop = new TIntermLoop(type, init, conditionInit, expr, EnsureBlock(body));
block->appendStatement(loop);
loop->setLine(line);
block->setLine(line);
return block;
}
TIntermNode *TParseContext::addIfElse(TIntermTyped *cond,
TIntermNodePair code,
const TSourceLoc &loc)
{
bool isScalarBool = checkIsScalarBool(loc, cond);
// In case the conditional statements were not parsed as blocks and contain a statement that
// simply refers to a variable, we need to mark them as statically used.
if (code.node1)
{
markStaticReadIfSymbol(code.node1);
}
if (code.node2)
{
markStaticReadIfSymbol(code.node2);
}
// For compile time constant conditions, prune the code now.
if (isScalarBool && cond->getAsConstantUnion())
{
if (cond->getAsConstantUnion()->getBConst(0) == true)
{
return EnsureBlock(code.node1);
}
else
{
return EnsureBlock(code.node2);
}
}
TIntermIfElse *node = new TIntermIfElse(cond, EnsureBlock(code.node1), EnsureBlock(code.node2));
markStaticReadIfSymbol(cond);
node->setLine(loc);
return node;
}
void TParseContext::addFullySpecifiedType(TPublicType *typeSpecifier)
{
checkPrecisionSpecified(typeSpecifier->getLine(), typeSpecifier->precision,
typeSpecifier->getBasicType());
if (mShaderVersion < 300 && typeSpecifier->isArray())
{
error(typeSpecifier->getLine(), "not supported", "first-class array");
typeSpecifier->clearArrayness();
}
}
TPublicType TParseContext::addFullySpecifiedType(const TTypeQualifierBuilder &typeQualifierBuilder,
const TPublicType &typeSpecifier)
{
TTypeQualifier typeQualifier = typeQualifierBuilder.getVariableTypeQualifier(mDiagnostics);
TPublicType returnType = typeSpecifier;
returnType.qualifier = typeQualifier.qualifier;
returnType.invariant = typeQualifier.invariant;
returnType.layoutQualifier = typeQualifier.layoutQualifier;
returnType.memoryQualifier = typeQualifier.memoryQualifier;
returnType.precision = typeSpecifier.precision;
if (typeQualifier.precision != EbpUndefined)
{
returnType.precision = typeQualifier.precision;
}
checkPrecisionSpecified(typeSpecifier.getLine(), returnType.precision,
typeSpecifier.getBasicType());
checkInvariantVariableQualifier(returnType.invariant, returnType.qualifier,
typeSpecifier.getLine());
checkWorkGroupSizeIsNotSpecified(typeSpecifier.getLine(), returnType.layoutQualifier);
if (mShaderVersion < 300)
{
if (typeSpecifier.isArray())
{
error(typeSpecifier.getLine(), "not supported", "first-class array");
returnType.clearArrayness();
}
if (returnType.qualifier == EvqAttribute &&
(typeSpecifier.getBasicType() == EbtBool || typeSpecifier.getBasicType() == EbtInt))
{
error(typeSpecifier.getLine(), "cannot be bool or int",
getQualifierString(returnType.qualifier));
}
if ((returnType.qualifier == EvqVaryingIn || returnType.qualifier == EvqVaryingOut) &&
(typeSpecifier.getBasicType() == EbtBool || typeSpecifier.getBasicType() == EbtInt))
{
error(typeSpecifier.getLine(), "cannot be bool or int",
getQualifierString(returnType.qualifier));
}
}
else
{
if (!returnType.layoutQualifier.isEmpty())
{
checkIsAtGlobalLevel(typeSpecifier.getLine(), "layout");
}
if (sh::IsVarying(returnType.qualifier) || returnType.qualifier == EvqVertexIn ||
returnType.qualifier == EvqFragmentOut)
{
checkInputOutputTypeIsValidES3(returnType.qualifier, typeSpecifier,
typeSpecifier.getLine());
}
if (returnType.qualifier == EvqComputeIn)
{
error(typeSpecifier.getLine(), "'in' can be only used to specify the local group size",
"in");
}
}
return returnType;
}
void TParseContext::checkInputOutputTypeIsValidES3(const TQualifier qualifier,
const TPublicType &type,
const TSourceLoc &qualifierLocation)
{
// An input/output variable can never be bool or a sampler. Samplers are checked elsewhere.
if (type.getBasicType() == EbtBool)
{
error(qualifierLocation, "cannot be bool", getQualifierString(qualifier));
}
// Specific restrictions apply for vertex shader inputs and fragment shader outputs.
switch (qualifier)
{
case EvqVertexIn:
// ESSL 3.00 section 4.3.4
if (type.isArray())
{
error(qualifierLocation, "cannot be array", getQualifierString(qualifier));
}
// Vertex inputs with a struct type are disallowed in nonEmptyDeclarationErrorCheck
return;
case EvqFragmentOut:
// ESSL 3.00 section 4.3.6
if (type.typeSpecifierNonArray.isMatrix())
{
error(qualifierLocation, "cannot be matrix", getQualifierString(qualifier));
}
// Fragment outputs with a struct type are disallowed in nonEmptyDeclarationErrorCheck
return;
default:
break;
}
// Vertex shader outputs / fragment shader inputs have a different, slightly more lenient set of
// restrictions.
bool typeContainsIntegers =
(type.getBasicType() == EbtInt || type.getBasicType() == EbtUInt ||
type.isStructureContainingType(EbtInt) || type.isStructureContainingType(EbtUInt));
if (typeContainsIntegers && qualifier != EvqFlatIn && qualifier != EvqFlatOut)
{
error(qualifierLocation, "must use 'flat' interpolation here",
getQualifierString(qualifier));
}
if (type.getBasicType() == EbtStruct)
{
// ESSL 3.00 sections 4.3.4 and 4.3.6.
// These restrictions are only implied by the ESSL 3.00 spec, but
// the ESSL 3.10 spec lists these restrictions explicitly.
if (type.isArray())
{
error(qualifierLocation, "cannot be an array of structures",
getQualifierString(qualifier));
}
if (type.isStructureContainingArrays())
{
error(qualifierLocation, "cannot be a structure containing an array",
getQualifierString(qualifier));
}
if (type.isStructureContainingType(EbtStruct))
{
error(qualifierLocation, "cannot be a structure containing a structure",
getQualifierString(qualifier));
}
if (type.isStructureContainingType(EbtBool))
{
error(qualifierLocation, "cannot be a structure containing a bool",
getQualifierString(qualifier));
}
}
}
void TParseContext::checkLocalVariableConstStorageQualifier(const TQualifierWrapperBase &qualifier)
{
if (qualifier.getType() == QtStorage)
{
const TStorageQualifierWrapper &storageQualifier =
static_cast<const TStorageQualifierWrapper &>(qualifier);
if (!declaringFunction() && storageQualifier.getQualifier() != EvqConst &&
!symbolTable.atGlobalLevel())
{
error(storageQualifier.getLine(),
"Local variables can only use the const storage qualifier.",
storageQualifier.getQualifierString());
}
}
}
void TParseContext::checkMemoryQualifierIsNotSpecified(const TMemoryQualifier &memoryQualifier,
const TSourceLoc &location)
{
const std::string reason(
"Only allowed with shader storage blocks, variables declared within shader storage blocks "
"and variables declared as image types.");
if (memoryQualifier.readonly)
{
error(location, reason.c_str(), "readonly");
}
if (memoryQualifier.writeonly)
{
error(location, reason.c_str(), "writeonly");
}
if (memoryQualifier.coherent)
{
error(location, reason.c_str(), "coherent");
}
if (memoryQualifier.restrictQualifier)
{
error(location, reason.c_str(), "restrict");
}
if (memoryQualifier.volatileQualifier)
{
error(location, reason.c_str(), "volatile");
}
}
// Make sure there is no offset overlapping, and store the newly assigned offset to "type" in
// intermediate tree.
void TParseContext::checkAtomicCounterOffsetDoesNotOverlap(bool forceAppend,
const TSourceLoc &loc,
TType *type)
{
if (!IsAtomicCounter(type->getBasicType()))
{
return;
}
const size_t size = type->isArray() ? kAtomicCounterArrayStride * type->getArraySizeProduct()
: kAtomicCounterSize;
TLayoutQualifier layoutQualifier = type->getLayoutQualifier();
auto &bindingState = mAtomicCounterBindingStates[layoutQualifier.binding];
int offset;
if (layoutQualifier.offset == -1 || forceAppend)
{
offset = bindingState.appendSpan(size);
}
else
{
offset = bindingState.insertSpan(layoutQualifier.offset, size);
}
if (offset == -1)
{
error(loc, "Offset overlapping", "atomic counter");
return;
}
layoutQualifier.offset = offset;
type->setLayoutQualifier(layoutQualifier);
}
void TParseContext::checkGeometryShaderInputAndSetArraySize(const TSourceLoc &location,
const ImmutableString &token,
TType *type)
{
if (IsGeometryShaderInput(mShaderType, type->getQualifier()))
{
if (type->isArray() && type->getOutermostArraySize() == 0u)
{
// Set size for the unsized geometry shader inputs if they are declared after a valid
// input primitive declaration.
if (mGeometryShaderInputPrimitiveType != EptUndefined)
{
ASSERT(symbolTable.getGlInVariableWithArraySize() != nullptr);
type->sizeOutermostUnsizedArray(
symbolTable.getGlInVariableWithArraySize()->getType().getOutermostArraySize());
}
else
{
// [GLSL ES 3.2 SPEC Chapter 4.4.1.2]
// An input can be declared without an array size if there is a previous layout
// which specifies the size.
error(location,
"Missing a valid input primitive declaration before declaring an unsized "
"array input",
token);
}
}
else if (type->isArray())
{
setGeometryShaderInputArraySize(type->getOutermostArraySize(), location);
}
else
{
error(location, "Geometry shader input variable must be declared as an array", token);
}
}
}
TIntermDeclaration *TParseContext::parseSingleDeclaration(
TPublicType &publicType,
const TSourceLoc &identifierOrTypeLocation,
const ImmutableString &identifier)
{
TType *type = new TType(publicType);
if ((mCompileOptions & SH_FLATTEN_PRAGMA_STDGL_INVARIANT_ALL) &&
mDirectiveHandler.pragma().stdgl.invariantAll)
{
TQualifier qualifier = type->getQualifier();
// The directive handler has already taken care of rejecting invalid uses of this pragma
// (for example, in ESSL 3.00 fragment shaders), so at this point, flatten it into all
// affected variable declarations:
//
// 1. Built-in special variables which are inputs to the fragment shader. (These are handled
// elsewhere, in TranslatorGLSL.)
//
// 2. Outputs from vertex shaders in ESSL 1.00 and 3.00 (EvqVaryingOut and EvqVertexOut). It
// is actually less likely that there will be bugs in the handling of ESSL 3.00 shaders, but
// the way this is currently implemented we have to enable this compiler option before
// parsing the shader and determining the shading language version it uses. If this were
// implemented as a post-pass, the workaround could be more targeted.
//
// 3. Inputs in ESSL 1.00 fragment shaders (EvqVaryingIn). This is somewhat in violation of
// the specification, but there are desktop OpenGL drivers that expect that this is the
// behavior of the #pragma when specified in ESSL 1.00 fragment shaders.
if (qualifier == EvqVaryingOut || qualifier == EvqVertexOut || qualifier == EvqVaryingIn)
{
type->setInvariant(true);
}
}
checkGeometryShaderInputAndSetArraySize(identifierOrTypeLocation, identifier, type);
declarationQualifierErrorCheck(publicType.qualifier, publicType.layoutQualifier,
identifierOrTypeLocation);
bool emptyDeclaration = (identifier == "");
mDeferredNonEmptyDeclarationErrorCheck = emptyDeclaration;
TIntermSymbol *symbol = nullptr;
if (emptyDeclaration)
{
emptyDeclarationErrorCheck(*type, identifierOrTypeLocation);
// In most cases we don't need to create a symbol node for an empty declaration.
// But if the empty declaration is declaring a struct type, the symbol node will store that.
if (type->getBasicType() == EbtStruct)
{
TVariable *emptyVariable =
new TVariable(&symbolTable, kEmptyImmutableString, type, SymbolType::Empty);
symbol = new TIntermSymbol(emptyVariable);
}
else if (IsAtomicCounter(publicType.getBasicType()))
{
setAtomicCounterBindingDefaultOffset(publicType, identifierOrTypeLocation);
}
}
else
{
nonEmptyDeclarationErrorCheck(publicType, identifierOrTypeLocation);
checkCanBeDeclaredWithoutInitializer(identifierOrTypeLocation, identifier, type);
checkAtomicCounterOffsetDoesNotOverlap(false, identifierOrTypeLocation, type);
TVariable *variable = nullptr;
if (declareVariable(identifierOrTypeLocation, identifier, type, &variable))
{
symbol = new TIntermSymbol(variable);
}
}
TIntermDeclaration *declaration = new TIntermDeclaration();
declaration->setLine(identifierOrTypeLocation);
if (symbol)
{
symbol->setLine(identifierOrTypeLocation);
declaration->appendDeclarator(symbol);
}
return declaration;
}
TIntermDeclaration *TParseContext::parseSingleArrayDeclaration(
TPublicType &elementType,
const TSourceLoc &identifierLocation,
const ImmutableString &identifier,
const TSourceLoc &indexLocation,
const TVector<unsigned int> &arraySizes)
{
mDeferredNonEmptyDeclarationErrorCheck = false;
declarationQualifierErrorCheck(elementType.qualifier, elementType.layoutQualifier,
identifierLocation);
nonEmptyDeclarationErrorCheck(elementType, identifierLocation);
checkIsValidTypeAndQualifierForArray(indexLocation, elementType);
TType *arrayType = new TType(elementType);
arrayType->makeArrays(arraySizes);
checkGeometryShaderInputAndSetArraySize(indexLocation, identifier, arrayType);
checkCanBeDeclaredWithoutInitializer(identifierLocation, identifier, arrayType);
checkAtomicCounterOffsetDoesNotOverlap(false, identifierLocation, arrayType);
TIntermDeclaration *declaration = new TIntermDeclaration();
declaration->setLine(identifierLocation);
TVariable *variable = nullptr;
if (declareVariable(identifierLocation, identifier, arrayType, &variable))
{
TIntermSymbol *symbol = new TIntermSymbol(variable);
symbol->setLine(identifierLocation);
declaration->appendDeclarator(symbol);
}
return declaration;
}
TIntermDeclaration *TParseContext::parseSingleInitDeclaration(const TPublicType &publicType,
const TSourceLoc &identifierLocation,
const ImmutableString &identifier,
const TSourceLoc &initLocation,
TIntermTyped *initializer)
{
mDeferredNonEmptyDeclarationErrorCheck = false;
declarationQualifierErrorCheck(publicType.qualifier, publicType.layoutQualifier,
identifierLocation);
nonEmptyDeclarationErrorCheck(publicType, identifierLocation);
TIntermDeclaration *declaration = new TIntermDeclaration();
declaration->setLine(identifierLocation);
TIntermBinary *initNode = nullptr;
TType *type = new TType(publicType);
if (executeInitializer(identifierLocation, identifier, type, initializer, &initNode))
{
if (initNode)
{
declaration->appendDeclarator(initNode);
}
}
return declaration;
}
TIntermDeclaration *TParseContext::parseSingleArrayInitDeclaration(
TPublicType &elementType,
const TSourceLoc &identifierLocation,
const ImmutableString &identifier,
const TSourceLoc &indexLocation,
const TVector<unsigned int> &arraySizes,
const TSourceLoc &initLocation,
TIntermTyped *initializer)
{
mDeferredNonEmptyDeclarationErrorCheck = false;
declarationQualifierErrorCheck(elementType.qualifier, elementType.layoutQualifier,
identifierLocation);
nonEmptyDeclarationErrorCheck(elementType, identifierLocation);
checkIsValidTypeAndQualifierForArray(indexLocation, elementType);
TType *arrayType = new TType(elementType);
arrayType->makeArrays(arraySizes);
TIntermDeclaration *declaration = new TIntermDeclaration();
declaration->setLine(identifierLocation);
// initNode will correspond to the whole of "type b[n] = initializer".
TIntermBinary *initNode = nullptr;
if (executeInitializer(identifierLocation, identifier, arrayType, initializer, &initNode))
{
if (initNode)
{
declaration->appendDeclarator(initNode);
}
}
return declaration;
}
TIntermInvariantDeclaration *TParseContext::parseInvariantDeclaration(
const TTypeQualifierBuilder &typeQualifierBuilder,
const TSourceLoc &identifierLoc,
const ImmutableString &identifier,
const TSymbol *symbol)
{
TTypeQualifier typeQualifier = typeQualifierBuilder.getVariableTypeQualifier(mDiagnostics);
if (!typeQualifier.invariant)
{
error(identifierLoc, "Expected invariant", identifier);
return nullptr;
}
if (!checkIsAtGlobalLevel(identifierLoc, "invariant varying"))
{
return nullptr;
}
if (!symbol)
{
error(identifierLoc, "undeclared identifier declared as invariant", identifier);
return nullptr;
}
if (!IsQualifierUnspecified(typeQualifier.qualifier))
{
error(identifierLoc, "invariant declaration specifies qualifier",
getQualifierString(typeQualifier.qualifier));
}
if (typeQualifier.precision != EbpUndefined)
{
error(identifierLoc, "invariant declaration specifies precision",
getPrecisionString(typeQualifier.precision));
}
if (!typeQualifier.layoutQualifier.isEmpty())
{
error(identifierLoc, "invariant declaration specifies layout", "'layout'");
}
const TVariable *variable = getNamedVariable(identifierLoc, identifier, symbol);
if (!variable)
{
return nullptr;
}
const TType &type = variable->getType();
checkInvariantVariableQualifier(typeQualifier.invariant, type.getQualifier(),
typeQualifier.line);
checkMemoryQualifierIsNotSpecified(typeQualifier.memoryQualifier, typeQualifier.line);
symbolTable.addInvariantVarying(*variable);
TIntermSymbol *intermSymbol = new TIntermSymbol(variable);
intermSymbol->setLine(identifierLoc);
return new TIntermInvariantDeclaration(intermSymbol, identifierLoc);
}
void TParseContext::parseDeclarator(TPublicType &publicType,
const TSourceLoc &identifierLocation,
const ImmutableString &identifier,
TIntermDeclaration *declarationOut)
{
// If the declaration starting this declarator list was empty (example: int,), some checks were
// not performed.
if (mDeferredNonEmptyDeclarationErrorCheck)
{
nonEmptyDeclarationErrorCheck(publicType, identifierLocation);
mDeferredNonEmptyDeclarationErrorCheck = false;
}