summaryrefslogtreecommitdiffstats
path: root/source/slang/slang-parser.cpp
diff options
context:
space:
mode:
authorTheresa Foley <tfoleyNV@users.noreply.github.com>2022-01-25 12:59:52 -0800
committerGitHub <noreply@github.com>2022-01-25 12:59:52 -0800
commit618acb24fdd8e3c447e4ab8826ea9a4eb117885b (patch)
tree6762af64b3a81cd66c066efbee003ba54799035a /source/slang/slang-parser.cpp
parent6528b1c7f32d8e2c8de8f4e1dd386533cd14b8f1 (diff)
Add support for HLSL unorm/snorm (#2095)
Read/write resource types (what D3D/HLSL often refer to as UAVs) can be broadly categorized based on whether they require an underlying format (e.g., a `DXGI_FORMAT`) for reads, or not. D3D refers to the ones that require a format as "typed" UAVs (even though a `RWStructuredBuffer<MyData>` is clearly "typed" at the HLSL level). Vulkan refers to these cases as "storage images" and "storage texel buffers." Under the D3D model, an application does not have to specify the exact format for a formatted/"typed" UAV in order for loads to work, but it *does* need to specify if an HLSL resource with a declared `float` or vector-of-`float` element type will be backed by data with a `*_UNORM` or `*_SNORM` format. This is where the `unorm` and `snorm` type modifiers come in. Superficially, it might seem that adding this feature to the Slang compiler is "just" a matter of adding the two modifiers, which is easily done with a pair of one-line `syntax` declarations in `core.meta.slang` plus the corresponding AST node types. Unfortunately the superficial view misses the detail that, to date, Slang has not had any support for *type modifiers* at all, and has only supported *declaration modifiers*. The distinction has so far not mattered, even with modifiers like `const` because, e.g., the difference between a "`const` array of `float`" and an "array of `const float`" doesn't really matter. So, adding these two modifiers required introducing a lot of infrastructure along the way. Let's walk through what needed to happen: * As described above, the actual `syntax` was added easily in the Slang stdlib * I added a new subclass of `Modifier` for `TypeModifier`s in the AST, and added the AST nodes for `unorm` and `snorm` as subclasses of that. * In order to syntactically support modifiers applied to types (e.g., `unorm float`), I needed to add a `ModifiedTypeExpr` subclass of `Expr` that represents a base type expression with one or more modifiers applied * The parser needed some subtle new logic. There are two main cases where type modifiers will come up: 1. In contexts where we might be parsing a declaration (e.g., `const unorm float a`), we need to support a list of modifiers that might freely mix type modifiers and "declaration modifiers" which are not intended to apply to types. In this case we need to split the lis tof modifiers into the type-related ones and the declaration-related ones, and attach each subset to the appropriate place. This is very important for features like C-style pointers, where in `static const float* a;`, the `static` modifier applies to the entire declaration of `a`, but the `const` modifier *only* applies to the `float` type specifier, and *not* to the outer pointer type (the actual type of `a`). 2. In contexts where we are not parsing a declaration (e.g., a generic type argument), we need to support a list of modifiers and appy them *all* to the type specifier being parsed, even if some of them might not be appropriate. * While working in the parser I implemented a certain amount of unrelated cleanup for code that was using raw `Modifier*`s to represent lists of modifiers, instead of the purpose-built `Modifiers` type. * The `_parseGenericArg` case needed specific work, because it is an important case in the grammar where we need to parse *either* a type expression or a value exprssion, but cannot easily predict which we will see. The fix implemented for now is to always try to parse modifiers and, if we see any, to assume we are in the type case. Because of the rules for how modifiers in a C-like language inhere to the type specifier (and not necessarily the entire type), we need to refactor some of the type expression parsing routines to support parsing a "suffix" of a type expression. * Note: I decided to be conservative and only make these changes in `_parseGenericArg` because that is place that is *needed* in order for user code with `unorm`/`snorm` to work, but in practice a user could still confuse our parser by using type modifiers as part of a cast (e.g., `x = (unorm float)y;`). While there is currently no reason why a user should want to do this, it *does* suggest that we need to be prepared to see type modifiers in other ambiguous "expression or type?" contexts. We have so far preferred to avoid looking up built-in syntax declarations like modifiers in expression contexts, because we want to allow users to create variable names that might conflict with some of the more surprising modifier keywords in HLSL (e.g., both `triangle` and `sample` are modifier keyword). A nuanced strategy may be required when we get around to closing this gap (which will be needed around when we want full pointer support, since a cast like `(const SomeType*)somePtr` is pretty common). * In semantic checking, we now need a `visitModifiedTypeExpr`, which visits the base expression to produce a `Type` and then checks each of the `Modifier`s attached to it. During this process we need to translate the AST-level `Modifier`s into something that can exist properly in the universe of `Type`s. We introduce a `ModifiedType` subclass of `Type`, distinct from the `ModifiedTypeExpr` subclass of `Expr`. Furthermore, we introduce a `ModifierVal` subclass of `Val`, distinct from `Modifier`/`TypeModifier`. * One unfortunate thing here is that it means we have both, e.g., `UNormModifier` to represent the parsed syntax, and `UNormModifierVal` to represent the `Type`/`Val`-level representation of the same concept. It is quite likely that we are near the point where we can/should consider having two distinct AST representations: one for freshly-parsed ASTs and one for semantically-checked ASTs. The `Type`/`Val` hierarchy clearly belongs to the latter. * No actual semantic checking is currently being applied to the `unorm` and `snorm` modifiers, although we should in principle check that they are only being applied to `float` and vector-of-`float` types. * In an attempt to simplify some of the creation logic and build a tiny bit of reusable infrastructure, I went ahead and added the skeleton of a dedupe-caching system in `ASTBuilder` so that we can easily ensure only a single `UNormModifierVal` and a single `SNormModifierVal` ever get created inside the scope of a single builder. * TODO: Thinking about this, I'm now worried the deduplication does not mean I can make the simplifications I currently do in semantic checking by assuming that any two `UNormModifierVal`s will be pointer-identical. This is because we do not currently (IIRC) have the required "bottleneck" in the compiler where all ASTs get serialized after initial checking, and then deserialized when `import`ed into a downstream module, so that every AST node during a checking step comes from a single `ASTBuilder`. Hmm... * If we can rely on deduplication to do its thing, then the `Val` and `Type` implementations of modifiers can be relatively simple. * TODO: One issue here is that the equality comparison for `ModifiedType` currently checks for the same base type and the same modifiers in the same order. This works for now when we only have a small number of type modifiers and any given type will hae at most one, but in the longer run it relies on us to implement some kind of canonicalization scheme, which would both ensure that between `Modified(T, {A, B})` and `Modified(T, {B, A})` only one is allowed (that is, a canonical ordering on modifiers), and that we do not allow `Modified(Modified(T, {A}), {B})`. * TODO: One other issues is that the `ModifiedType` case does not currently interact correctly with the `as()`-based casting for types (whereas that operation *does* interact in a semantically-correct fashion with `typedef`s). Fixing this issue in a robust way really depends on us re-architecting the `Type` system so that *any* `Type` can have modifiers attached, with modifiers affecting type identity/deduplication. * The key place where `ModifiedType` creates a complication in semantic checking is type conversion/coercion. A user is likely to declare a `RWTexture2D<unorm float>`, fetch from it (producing a value of type `unorm float`) and then assign the result to a `float` variable, prompting for a conversion from `unorm float` to `float` (because they are distinct `Type`s). * We handle this case in the core `_coerce()` operation by checking if either `toType` or `fromType` is a `ModifiedType`. If *either* one is a modified type, we apply logic to check for modifiers that are present on one and not the other. Basically we check which modifiers need to be "dropped" and which need to be "added" during conversion, and validate that these modifiers *can* be dropped/added without creating a semantic error. The only type modifiers we support right now *can* be dropped/added like this, so we are fine. * TODO: When we add more complete pointer support, we could need logic here to validate when casts between, e.g., `const int*` and `int*` should/shouldn't be allowed. * Note: Even opening the door to type modifiers at all creates the same kind of challenges for user-defined generic types (and functions!) since `MyType<int>` and `MyType<const int>` are distinct instantiations in a future where we support `const` as a type modifier. We *may* need to plan to restrict where modified types can be used, so that certain built-in generic types support modified types as arguments, but user-defined types don't (or at least might need to opt-in to get support). * The result of a `_coerce()` that drops/adds modifiers is a `ModifierCastExpr`, which is a kind of no-op AST node that merely expresses that the conversion is allowed and valid. * In IR lowering we currently do the simple thing and translate a `ModifiedType` to a distinct IR node called `AttributedType`. * The change in terminology from "modifier" to "attribute" is to follow the way that these kinds of modifiers best map to the `IRAttr` case in the IR (rather than the `IRDecoration` case). We probably ought to do a careful terminology scrub here, because having this terminology mismatch between IR and AST could be a source of confusion. * TODO: In principle, using `IRAttributedType` creates the same basic problems as using `ModifiedType`: code that is usin `as()` or similar operations to check for a specific subclass of `IRType` may not see the case they were looking for due to use of `IRAttributedType`. * Initially I had hoped to avoid the problem by having the `IRAttr`s be attached directly as operands to an otherwise-ordinary `IRType`. E.g., a lowered `unorm float4` would be an `IRVectorType` with an "extra" operand that is an `IRUNormAttr`, something like: `Vector<Float, 4, UNorm>`. This sounds great (and looks great!), but runs into the problem that it is incompatible with the way we currently represent things like generic type parameters. A generic type parameter `T` is represented as an `IRParam`, and it does *not* make sense to have an additional `IRParam` to represent `const T` or `unorm T`, etc. * The Right Way to solve this stuff at both the AST and IR levels is to avoid passing around bare `Type*` or `IRType*` in general, and instead use a value type that implements the needed policy more directly: something like a `TypeHolder` or `IRTypeHolder` (placeholder name). The `*Holder` type would abstract over the various "wrapper" nodes required to store all the additional data like attributes but, importantly, would *not* allow that extra information to be dropped or lost during operations like casting (e.g., note how the current `Type` implementation of `as()` loses information on `typedef` names, making our error messages slightly worse). This is actually quite similar to how we currently use the `DeclRef<T>` system to allow working with what is *usually* a `T*` under the hood, but in a way that ensures we don't lose track of any generic substitution information. * During C-like code emit we have a process that turns an `IRType` into a chain of declarators as needed to emit a C-like declaration with pointers, arrays, etc. The `IRAttributedType` case needs to get folded into this logic. Basically, when we see an `IRAttributedType` we immediately emit any modifiers that are required to be in a prefix position, then recursively emit the underlying type with an extra layer of declarator that tracks the modifiers, so that we can emit any modifiers that should be placed in a postfix position *after* the type. As a specific example, our C/C++ back-end would want to use the postifx option to handle `const`, because then it can properly emit stuff like `int const * const *` and not the incorrect `const const int**`. * The HLSL emit logic overrides the prefix case for handling type attributes, and uses it to emit `unorm` and `snorm` where they occur. * One unfortunate detail is that (apparently) some downstream HLSL compilers do not allow the `unorm`/`snorm` modifiers to apply to `vector<float, *>` types, even though that should be semantically valid. Instead, they only support `float`, `float2`, `float3`, and `float4` explicitly. To work around this issue, we go ahead and change our HLSL emit logic so that when we encountered 1-to-4 component vectors of `float`, `int`, or `uint` we emit the type name using the typical HLSL shorthand. This is actually a signficicant change in our HLSL output, but it both seemed like a good fix to have anyway, and was also the only obvious way to address the downstream parser shortcomings without a massive kludge. * As a result of this change the `half-texture.slang` test broke, since it was using raw HLSL as the expected output. I changed the test to do a DXIL comparison instead, which is our preferred way of testing cross-compilation behavior (since it is more robust in the face of small changes to our source output).
Diffstat (limited to 'source/slang/slang-parser.cpp')
-rw-r--r--source/slang/slang-parser.cpp310
1 files changed, 265 insertions, 45 deletions
diff --git a/source/slang/slang-parser.cpp b/source/slang/slang-parser.cpp
index d9bbaaace..961691c9a 100644
--- a/source/slang/slang-parser.cpp
+++ b/source/slang/slang-parser.cpp
@@ -213,10 +213,10 @@ namespace Slang
static Decl* parseEnumDecl(Parser* parser);
- static Modifier* ParseOptSemantics(
+ static Modifiers _parseOptSemantics(
Parser* parser);
- static void ParseOptSemantics(
+ static void _parseOptSemantics(
Parser* parser,
Decl* decl);
@@ -234,6 +234,8 @@ namespace Slang
static TokenType peekTokenType(Parser* parser);
+ static Expr* _parseGenericArg(Parser* parser);
+
//
static void Unexpected(
@@ -1228,7 +1230,7 @@ namespace Slang
{
Expr* typeSpec = nullptr;
NameLoc nameAndLoc;
- Modifier* semantics = nullptr;
+ Modifiers semantics;
Expr* initializer = nullptr;
};
@@ -1483,7 +1485,7 @@ namespace Slang
parser->PushScope(decl);
parseParameterList(parser, decl);
- ParseOptSemantics(parser, decl);
+ _parseOptSemantics(parser, decl);
decl->body = parseOptBody(parser);
parser->PopScope();
@@ -1511,9 +1513,9 @@ namespace Slang
}
// Add modifiers to the end of the modifier list for a declaration
- void AddModifiers(Decl* decl, Modifier* modifiers)
+ static void _addModifiers(Decl* decl, Modifiers const& modifiers)
{
- if (!modifiers)
+ if (!modifiers.first)
return;
Modifier** link = &decl->modifiers.first;
@@ -1521,7 +1523,7 @@ namespace Slang
{
link = &(*link)->next;
}
- *link = modifiers;
+ *link = modifiers.first;
}
static Name* generateName(Parser* parser, String const& base)
@@ -1556,7 +1558,7 @@ namespace Slang
}
decl->type = TypeExp(declaratorInfo.typeSpec);
- AddModifiers(decl, declaratorInfo.semantics);
+ _addModifiers(decl, declaratorInfo.semantics);
decl->initExpr = declaratorInfo.initializer;
}
@@ -1695,7 +1697,7 @@ namespace Slang
struct InitDeclarator
{
RefPtr<Declarator> declarator;
- Modifier* semantics = nullptr;
+ Modifiers semantics;
Expr* initializer = nullptr;
};
@@ -1706,7 +1708,7 @@ namespace Slang
{
InitDeclarator result;
result.declarator = parseDeclarator(parser, options);
- result.semantics = ParseOptSemantics(parser);
+ result.semantics = _parseOptSemantics(parser);
return result;
}
@@ -1822,12 +1824,6 @@ namespace Slang
}
};
- // Pares an argument to an application of a generic
- Expr* ParseGenericArg(Parser* parser)
- {
- return parser->ParseArgExpr();
- }
-
// Create a type expression that will refer to the given declaration
static Expr*
createDeclRefType(Parser* parser, Decl* decl)
@@ -1866,10 +1862,10 @@ namespace Slang
parser->ReadToken(TokenType::OpLess);
parser->genericDepth++;
// For now assume all generics have at least one argument
- genericApp->arguments.add(ParseGenericArg(parser));
+ genericApp->arguments.add(_parseGenericArg(parser));
while (AdvanceIf(parser, TokenType::Comma))
{
- genericApp->arguments.add(ParseGenericArg(parser));
+ genericApp->arguments.add(_parseGenericArg(parser));
}
parser->genericDepth--;
@@ -2016,7 +2012,143 @@ namespace Slang
return parseThisTypeExpr(parser);
}
- static TypeSpec parseTypeSpec(Parser* parser)
+ /// Apply the given `modifiers` (if any) to the given `typeExpr`
+ static Expr* _applyModifiersToTypeExpr(Parser* parser, Expr* typeExpr, Modifiers const& modifiers)
+ {
+ if(modifiers.first)
+ {
+ // Currently, we represent a type with modifiers applied to it as
+ // an AST node of the `ModifiedTypeExpr` class. We will create
+ // one here and make it be the home for our `typeModifiers`.
+ //
+ ModifiedTypeExpr* modifiedTypeExpr = parser->astBuilder->create<ModifiedTypeExpr>();
+ modifiedTypeExpr->base.exp = typeExpr;
+ modifiedTypeExpr->modifiers = modifiers;
+ return modifiedTypeExpr;
+ }
+ else
+ {
+ // If none of the modifiers were type modifiers, we can leave
+ // the existing type expression alone.
+ return typeExpr;
+ }
+ }
+
+ /// Apply any type modifier in `ioBaseModifiers` to the given `typeExpr`.
+ ///
+ /// If any type modifiers were present, `ioBaseModifiers` will be updated
+ /// to only include those modifiers that were not type modifiers (if any).
+ ///
+ /// If no type modifiers were present, `ioBaseModifiers` will remain unchanged.
+ ///
+ static Expr* _applyTypeModifiersToTypeExpr(Parser* parser, Expr* typeExpr, Modifiers& ioBaseModifiers)
+ {
+ // The `Modifiers` that were passed in as `ioBaseModifiers` comprise
+ // a singly-linked list of `Modifier` nodes.
+ //
+ // It is possible that some of these modifiers represent type modifiers and,
+ // if so, we want to transfer those modifiers to apply to the type given
+ // by `typeExpr`. Any remaining modifiers that are not type modifiers will
+ // be left in the `ioBaseModifiers` list.
+ //
+ // The type modifiers will be collected into their own `Modifiers` list,
+ // and we will retain a poiner to the final pointer in the linked list
+ // (the one that is null), so that we can append to the end.
+ //
+ Modifiers typeModifiers;
+ Modifier** typeModifierLink = &typeModifiers.first;
+
+ // While iterating over the base modifiers, we need to be able to remove
+ // a linked-list node while inspecting it, so we will similarly keep a "link"
+ // variable that points at whatever location points to the current node
+ // (either the head of the list, or the `next` pointer in the previous modifier)
+ //
+ Modifier** baseModifierLink = &ioBaseModifiers.first;
+ while(auto baseModifier = *baseModifierLink)
+ {
+ // We want to detect whether we have a type modifier or not.
+ //
+ auto typeModifier = as<TypeModifier>(baseModifier);
+
+ // The easy case is when we *don't* have a type modifier.
+ //
+ if(!typeModifier)
+ {
+ // We want to leave the modifier where it is (in the list
+ // of "base" modifiers), and advance to the next one in order.
+ //
+ baseModifierLink = &baseModifier->next;
+ }
+ else
+ {
+ // If we have a type modifier, we need to graft it onto
+ // the list of type modifiers. This is done by writing
+ // a pointer to the type modifier into the "link" for
+ // the type modifier list, and updating the link to point
+ // to the `next` field of the current modifier (since that
+ // fill be the location any further type modifiers need
+ // to be linked).
+ //
+ *typeModifierLink = typeModifier;
+ typeModifierLink = &typeModifier->next;
+
+ // The above logic puts `typeModifier` into the type modifer
+ // list, but it doesn't remove it from the base modifier list.
+ // In order to do that we must replace the pointer to `typeModifer`
+ // with a pointer to whatever is next in the base list, and also
+ // null out the `next` field of `typeModifier` so that it no
+ // longer points to the base modifiers that come after it.
+ //
+ *baseModifierLink = typeModifier->next;
+ typeModifier->next = nullptr;
+
+ // Note: We do *not* need to update `baseModifierLink` before
+ // the next loop iteration, because `*baseModifierLink` has
+ // already been updated so that it points to the next node
+ // we want to visit.
+ }
+ }
+
+ // If we ended up finding any type modifiers, we want to apply them
+ // to the type expression.
+ //
+ return _applyModifiersToTypeExpr(parser, typeExpr, typeModifiers);
+ }
+
+ static TypeSpec _applyModifiersToTypeSpec(Parser* parser, TypeSpec typeSpec, Modifiers const& inModifiers)
+ {
+ // It is possible that the form of the type specifier will have
+ // included a declaration directly (e.g., using `struct { ... }`
+ // as a type specifier to declare both a type and value(s) of that
+ // type in one go).
+ //
+ if(auto decl = typeSpec.decl)
+ {
+ // In the case where there *is* a declaration, we want to apply
+ // any modifiers that logically belong to the type to the type,
+ // and any modifiers that logically belong to the declaration to
+ // the declaration.
+ //
+ Modifiers modifiers = inModifiers;
+ typeSpec.expr = _applyTypeModifiersToTypeExpr(parser, typeSpec.expr, modifiers);
+
+ // Any remaining modifiers should instead be applied to the declaration.
+ _addModifiers(decl, modifiers);
+ }
+ else
+ {
+ // If there are modifiers, then we apply *all* of them to the type expression.
+ // This may result in modifiers being applied that do not belong on a type;
+ // in that case we rely on downstream semantic checking to diagnose any error.
+ //
+ typeSpec.expr = _applyModifiersToTypeExpr(parser, typeSpec.expr, inModifiers);
+ }
+
+ return typeSpec;
+ }
+
+ /// Parse a type specifier, without dealing with modifiers.
+ static TypeSpec _parseSimpleTypeSpec(Parser* parser)
{
TypeSpec typeSpec;
@@ -2110,13 +2242,56 @@ namespace Slang
return typeSpec;
}
+ /// Parse a type specifier, following the given list of modifiers.
+ ///
+ /// If there are any modifiers in `ioModifiers`, this function may modify it
+ /// by stripping out any type modifiers and attaching them to the `TypeSpec`.
+ /// Any modifiers that are not type modifiers will be left where they were.
+ ///
+ static TypeSpec _parseTypeSpec(Parser* parser, Modifiers& ioModifiers)
+ {
+ TypeSpec typeSpec = _parseSimpleTypeSpec(parser);
+
+ // We don't know whether `ioModifiers` has any modifiers in it,
+ // or which of them might be type modifiers, so we will delegate
+ // figuring that out to a subroutine.
+ //
+ typeSpec.expr = _applyTypeModifiersToTypeExpr(parser, typeSpec.expr, ioModifiers);
+
+ return typeSpec;
+ }
+
+ /// Parse a type specifier, including any leading modifiers.
+ ///
+ /// Note that all the modifiers that precede the type specifier
+ /// will end up as modifiers for the type specifier even if they
+ /// should *not* be allowed as modifiers on a type.
+ ///
+ /// This function should not be used in contexts where a type specifier
+ /// is being parsed as part of a declaration, such that a subset of
+ /// the modifiers might inhere to the declaration rather than the
+ /// type specifier.
+ ///
+ static TypeSpec _parseTypeSpec(Parser* parser)
+ {
+ Modifiers modifiers = ParseModifiers(parser);
+ TypeSpec typeSpec = _parseSimpleTypeSpec(parser);
+
+ typeSpec = _applyModifiersToTypeSpec(parser, typeSpec, modifiers);
+
+ return typeSpec;
+ }
+
+
static DeclBase* ParseDeclaratorDecl(
- Parser* parser,
- ContainerDecl* containerDecl)
+ Parser* parser,
+ ContainerDecl* containerDecl,
+ Modifiers const& inModifiers)
{
SourceLoc startPosition = parser->tokenReader.peekLoc();
- auto typeSpec = parseTypeSpec(parser);
+ Modifiers modifiers = inModifiers;
+ auto typeSpec = _parseTypeSpec(parser, modifiers);
// We may need to build up multiple declarations in a group,
// but the common case will be when we have just a single
@@ -2206,7 +2381,7 @@ namespace Slang
// Only parse as a function if we didn't already see mutually-exclusive
// constructs when parsing the declarator.
&& !initDeclarator.initializer
- && !initDeclarator.semantics)
+ && !initDeclarator.semantics.first)
{
// Looks like a function, so parse it like one.
UnwrapDeclarator(parser->astBuilder, initDeclarator, &declaratorInfo);
@@ -2433,14 +2608,15 @@ namespace Slang
//
// opt-semantics ::= (':' semantic)*
//
- static Modifier* ParseOptSemantics(
+ static Modifiers _parseOptSemantics(
Parser* parser)
{
+ Modifiers modifiers;
+
if (!AdvanceIf(parser, TokenType::Colon))
- return nullptr;
+ return modifiers;
- Modifier* result = nullptr;
- Modifier** link = &result;
+ Modifier** link = &modifiers.first;
SLANG_ASSERT(!*link);
for (;;)
@@ -2470,18 +2646,18 @@ namespace Slang
// avoiding an infinite loop here.
if (!AdvanceIf(parser, TokenType::Colon))
{
- return result;
+ return modifiers;
}
}
}
- static void ParseOptSemantics(
+ static void _parseOptSemantics(
Parser* parser,
Decl* decl)
{
- AddModifiers(decl, ParseOptSemantics(parser));
+ _addModifiers(decl, _parseOptSemantics(parser));
}
static Decl* ParseHLSLBufferDecl(
@@ -2559,7 +2735,7 @@ namespace Slang
// Any semantics applied to the buffer declaration are taken as applying
// to the variable instead.
- ParseOptSemantics(parser, bufferVarDecl);
+ _parseOptSemantics(parser, bufferVarDecl);
// The declarations in the body belong to the data type.
parseDeclBody(parser, bufferDataTypeDecl);
@@ -2917,7 +3093,7 @@ namespace Slang
}
decl->loc = loc;
- AddModifiers(decl, modifiers.first);
+ _addModifiers(decl, modifiers);
parser->PushScope(decl);
@@ -3423,7 +3599,7 @@ namespace Slang
Decl* declToModify = decl;
if(auto genericDecl = as<GenericDecl>(decl))
declToModify = genericDecl->inner;
- AddModifiers(declToModify, modifiers.first);
+ _addModifiers(declToModify, modifiers);
// Make sure the decl is properly nested inside its lexical parent
if (containerDecl)
@@ -3435,7 +3611,7 @@ namespace Slang
static DeclBase* ParseDeclWithModifiers(
Parser* parser,
ContainerDecl* containerDecl,
- Modifiers modifiers )
+ Modifiers modifiers )
{
DeclBase* decl = nullptr;
@@ -3462,7 +3638,7 @@ namespace Slang
// Our final fallback case is to assume that the user is
// probably writing a C-style declarator-based declaration.
- decl = ParseDeclaratorDecl(parser, containerDecl);
+ decl = ParseDeclaratorDecl(parser, containerDecl, modifiers);
break;
}
break;
@@ -3483,7 +3659,7 @@ namespace Slang
// If nothing else matched, we try to parse an "ordinary" declarator-based declaration
default:
- decl = ParseDeclaratorDecl(parser, containerDecl);
+ decl = ParseDeclaratorDecl(parser, containerDecl, modifiers);
break;
}
@@ -4299,7 +4475,7 @@ namespace Slang
///
static Expr* _parseAtomicTypeExpr(Parser* parser)
{
- auto typeSpec = parseTypeSpec(parser);
+ auto typeSpec = _parseTypeSpec(parser);
if( typeSpec.decl )
{
AddMember(parser->currentScope, typeSpec.decl);
@@ -4318,15 +4494,8 @@ namespace Slang
return parsePostfixTypeSuffix(parser, typeExpr);
}
- /// Parse an infix type expression.
- ///
- /// Currently, the only infix type expression we support is the `&`
- /// operator for forming interface conjunctions.
- ///
- static Expr* _parseInfixTypeExpr(Parser* parser)
+ static Expr* _parseInfixTypeExprSuffix(Parser* parser, Expr* leftExpr)
{
- auto leftExpr = _parsePostfixTypeExpr(parser);
-
for(;;)
{
// As long as the next token is an `&`, we will try
@@ -4349,6 +4518,17 @@ namespace Slang
return leftExpr;
}
+ /// Parse an infix type expression.
+ ///
+ /// Currently, the only infix type expression we support is the `&`
+ /// operator for forming interface conjunctions.
+ ///
+ static Expr* _parseInfixTypeExpr(Parser* parser)
+ {
+ auto leftExpr = _parsePostfixTypeExpr(parser);
+ return _parseInfixTypeExprSuffix(parser, leftExpr);
+ }
+
Expr* Parser::ParseType()
{
return _parseInfixTypeExpr(this);
@@ -5508,6 +5688,46 @@ namespace Slang
return parsePrefixExpr(this);
}
+ /// Parse an argument to an application of a generic
+ static Expr* _parseGenericArg(Parser* parser)
+ {
+ // The grammar for generic arguments needs to be a super-set of the
+ // grammar for types and for expressions, because we do not know
+ // which to expect at each argument position during parsing.
+ //
+ // For the most part the expression grammar is more permissive than
+ // the type grammar, but types support modifiers that are not
+ // (currently) allowed in pure expression contexts.
+ //
+ // We could in theory allow modifiers to appear in expression contexts
+ // and deal with the cases where this should not be allowed downstream,
+ // but doing so runs a high risk of changing the meaning of existing code
+ // (notably in cases where a user might have used a variable name that
+ // overlaps with a language modifier keyword).
+ //
+ // Instead, we will simply detect the case where modifiers appear on
+ // a generic argument here, as a special case.
+ //
+ Modifiers modifiers = ParseModifiers(parser);
+ if(modifiers.first)
+ {
+ // If there are any modifiers, then we know that we are actually
+ // in the type case.
+ //
+ auto typeSpec = _parseSimpleTypeSpec(parser);
+ typeSpec = _applyModifiersToTypeSpec(parser, typeSpec, modifiers);
+
+ auto typeExpr = typeSpec.expr;
+
+ typeExpr = parsePostfixTypeSuffix(parser, typeExpr);
+ typeExpr = _parseInfixTypeExprSuffix(parser, typeExpr);
+
+ return typeExpr;
+ }
+
+ return parser->ParseArgExpr();
+ }
+
Expr* parseTermFromSourceFile(
ASTBuilder* astBuilder,
TokenSpan const& tokens,