diff options
| author | Tim Foley <tfoley@nvidia.com> | 2017-10-30 08:54:09 -0700 |
|---|---|---|
| committer | Tim Foley <tfoley@nvidia.com> | 2017-10-30 09:40:04 -0700 |
| commit | 42f1cff5c1471e6bc3988a9810c20b8bcc1c84dd (patch) | |
| tree | 95ce50d87fb26c7cc2f41e6afd518cfab6a91ef9 | |
| parent | 4ab545bcd0716cc3f2da432a921c1f53fdce7925 (diff) | |
Support explicit `this` expressions
This is the first step towards supporting traditional object-oriented method definitions; the second step will be to allow `this` expressions to be implicit.
- Add a test case using explicit `this`, and expected output
- Update parsing logic for expressions so that it handled identifiers similarly to the declaration and statement logic: first try to parse using a syntax declaration looked up in the curent scope, and otherwise fall back to the ordinary `VarExpr` case.
* As long as I'm making that change: switch `true` and `false` to be parsed via the callback mechanism rather than be special-cased.
* This change will also help out if we ever wanted to add `super`/`base` expressions, `new`, `sizeof`/`alignof` or any other expression keywords.
- Add a `ThisExpr` node and register a parser callback for it.
- Add semantic checks for `ThisExpr`: basically just look upwards through scopes until we find either an aggregate type declaration or an `extension` declaration, and then use that as the type of the expression.
- TODO: eventually we need to guard against a `this` expression inside of a `static` member.
- The IR generation logic already handled creation of `this` parameters in function signatures; the missing piece was to register the appropriate parameter in the context, so that we can use it as the lowering of a `this` expression.
| -rw-r--r-- | source/slang/check.cpp | 57 | ||||
| -rw-r--r-- | source/slang/diagnostic-defs.h | 13 | ||||
| -rw-r--r-- | source/slang/emit.cpp | 11 | ||||
| -rw-r--r-- | source/slang/expr-defs.h | 7 | ||||
| -rw-r--r-- | source/slang/lower-to-ir.cpp | 30 | ||||
| -rw-r--r-- | source/slang/parser.cpp | 57 | ||||
| -rw-r--r-- | tests/compute/explicit-this-expr.slang | 34 | ||||
| -rw-r--r-- | tests/compute/explicit-this-expr.slang.expected.txt | 4 |
8 files changed, 196 insertions, 17 deletions
diff --git a/source/slang/check.cpp b/source/slang/check.cpp index a42edc331..9b707d218 100644 --- a/source/slang/check.cpp +++ b/source/slang/check.cpp @@ -5970,6 +5970,11 @@ namespace Slang // We need to fix that. auto type = typeType->type; + if (type->As<ErrorType>()) + { + return CreateErrorExpr(expr); + } + LookupResult lookupResult = lookUpMember( getSession(), this, @@ -5988,6 +5993,10 @@ namespace Slang expr->BaseExpression, expr->loc); } + else if (baseType->As<ErrorType>()) + { + return CreateErrorExpr(expr); + } else { LookupResult lookupResult = lookUpMember( @@ -6093,6 +6102,54 @@ namespace Slang decl->SetCheckState(DeclCheckState::Checked); } + + // Perform semantic checking of an object-oriented `this` + // expression. + RefPtr<Expr> visitThisExpr(ThisExpr* expr) + { + // We will do an upwards search starting in the current + // scope, looking for a surrounding type (or `extension`) + // declaration that could be the referrant of the expression. + auto scope = expr->scope; + while (scope) + { + auto containerDecl = scope->containerDecl; + if (auto aggTypeDecl = containerDecl->As<AggTypeDecl>()) + { + EnsureDecl(aggTypeDecl); + + // Okay, we are using `this` in the context of an + // aggregate type, so the expression should be + // of the corresponding type. + expr->type = DeclRefType::Create( + getSession(), + makeDeclRef(aggTypeDecl)); + return expr; + } + else if (auto extensionDecl = containerDecl->As<ExtensionDecl>()) + { + EnsureDecl(extensionDecl); + + // When `this` is used in the context of an `extension` + // declaration, then it should refer to an instance of + // the type being extended. + // + // TODO: There is potentially a small gotcha here that + // lookup through such a `this` expression should probably + // prioritize members declared in the current extension + // if there are multiple extensions in scope that add + // members with the same name... + // + expr->type = QualType(extensionDecl->targetType.type); + return expr; + } + + scope = scope->parent; + } + + getSink()->diagnose(expr, Diagnostics::thisExpressionOutsideOfTypeDecl); + return CreateErrorExpr(expr); + } }; bool isPrimaryDecl( diff --git a/source/slang/diagnostic-defs.h b/source/slang/diagnostic-defs.h index 36e68c853..cca1c4869 100644 --- a/source/slang/diagnostic-defs.h +++ b/source/slang/diagnostic-defs.h @@ -308,15 +308,16 @@ DIAGNOSTIC(39999, Error, tooManyArguments, "too many arguments to call (got $0, DIAGNOSTIC(39999, Error, invalidIntegerLiteralSuffix, "invalid suffix '$0' on integer literal") DIAGNOSTIC(39999, Error, invalidFloatingPOintLiteralSuffix, "invalid suffix '$0' on floating-point literal") -DIAGNOSTIC(39999, Error, conflictingExplicitBindingsForParameter, "conflicting explicit bindings for parameter '$0'") -DIAGNOSTIC(39999, Warning, parameterBindingsOverlap, "explicit binding for parameter '$0' overlaps with parameter '$1'") +DIAGNOSTIC(39999, Error, conflictingExplicitBindingsForParameter, "conflicting explicit bindings for parameter '$0'") +DIAGNOSTIC(39999, Warning, parameterBindingsOverlap, "explicit binding for parameter '$0' overlaps with parameter '$1'") -DIAGNOSTIC(38000, Error, entryPointFunctionNotFound, "no function found matching entry point name '$0'") -DIAGNOSTIC(38001, Error, ambiguousEntryPoint, "more than one function matches entry point name '$0'") -DIAGNOSTIC(38002, Note, entryPointCandidate, "see candidate declaration for entry point '$0'") -DIAGNOSTIC(38003, Error, entryPointSymbolNotAFunction, "entry point '$0' must be declared as a function") +DIAGNOSTIC(38000, Error, entryPointFunctionNotFound, "no function found matching entry point name '$0'") +DIAGNOSTIC(38001, Error, ambiguousEntryPoint, "more than one function matches entry point name '$0'") +DIAGNOSTIC(38002, Note, entryPointCandidate, "see candidate declaration for entry point '$0'") +DIAGNOSTIC(38003, Error, entryPointSymbolNotAFunction, "entry point '$0' must be declared as a function") DIAGNOSTIC(38100, Error, typeDoesntImplementInterfaceRequirement, "type '$0' does not provide required interface member '$1'") +DIAGNOSTIC(38101, Error, thisExpressionOutsideOfTypeDecl, "'this' expression can only be used in members of an aggregate type") // // 4xxxx - IL code generation. diff --git a/source/slang/emit.cpp b/source/slang/emit.cpp index 6b411a25d..38e7376df 100644 --- a/source/slang/emit.cpp +++ b/source/slang/emit.cpp @@ -2381,6 +2381,17 @@ struct EmitVisitor if(needClose) Emit(")"); } + void visitThisExpr(ThisExpr* expr, ExprEmitArg const& arg) + { + auto prec = kEOp_Atomic; + auto outerPrec = arg.outerPrec; + bool needClose = MaybeEmitParens(outerPrec, prec); + + Emit("this"); + + if(needClose) Emit(")"); + } + void visitSwizzleExpr(SwizzleExpr* swizExpr, ExprEmitArg const& arg) { auto prec = kEOp_Postfix; diff --git a/source/slang/expr-defs.h b/source/slang/expr-defs.h index 81e8d9275..e3c16a674 100644 --- a/source/slang/expr-defs.h +++ b/source/slang/expr-defs.h @@ -148,3 +148,10 @@ END_SYNTAX_CLASS() SYNTAX_CLASS(ParenExpr, Expr) SYNTAX_FIELD(RefPtr<Expr>, base); END_SYNTAX_CLASS() + +// An object-oriented `this` expression, used to +// refer to the current instance of an enclosing type. +SYNTAX_CLASS(ThisExpr, Expr) + FIELD(RefPtr<Scope>, scope); +END_SYNTAX_CLASS() + diff --git a/source/slang/lower-to-ir.cpp b/source/slang/lower-to-ir.cpp index 2f0ea810e..93b84ad31 100644 --- a/source/slang/lower-to-ir.cpp +++ b/source/slang/lower-to-ir.cpp @@ -288,6 +288,15 @@ struct IRGenContext IRBuilder* irBuilder; + // The value to use for any `this` expressions + // that appear in the current context. + // + // TODO: If we ever allow nesting of (non-static) + // types, then we may need to support references + // to an "outer `this`", and this representation + // might be insufficient. + LoweredValInfo thisVal; + Session* getSession() { return shared->compileRequest->mSession; @@ -1008,6 +1017,11 @@ struct ExprLoweringVisitorBase : ExprVisitor<Derived, LoweredValInfo> return subscriptValue(type, baseVal, indexVal); } + LoweredValInfo visitThisExpr(ThisExpr* expr) + { + return context->thisVal; + } + LoweredValInfo visitMemberExpr(MemberExpr* expr) { auto loweredType = lowerType(context, expr->type); @@ -2360,9 +2374,18 @@ struct DeclLoweringVisitor : DeclVisitor<DeclLoweringVisitor, LoweredValInfo> }; struct ParameterInfo { + // This AST-level type of the parameter Type* type; + + // The direction (`in` vs `out` vs `in out`) ParameterDirection direction; + + // The variable/parameter declaration for + // this parameter (if any) VarDeclBase* decl; + + // Is this the representation of a `this` parameter? + bool isThisParam = false; }; // // We need a way to compute the appropriate `ParameterDirection` for a @@ -2399,6 +2422,7 @@ struct DeclLoweringVisitor : DeclVisitor<DeclLoweringVisitor, LoweredValInfo> info.type = paramDecl->getType(); info.decl = paramDecl; info.direction = getParameterDirection(paramDecl); + info.isThisParam = false; return info; } // @@ -2492,6 +2516,7 @@ struct DeclLoweringVisitor : DeclVisitor<DeclLoweringVisitor, LoweredValInfo> info.type = type; info.decl = nullptr; info.direction = direction; + info.isThisParam = true; ioParameterLists->params.Add(info); } @@ -2808,6 +2833,11 @@ struct DeclLoweringVisitor : DeclVisitor<DeclLoweringVisitor, LoweredValInfo> DeclRef<VarDeclBase> paramDeclRef = makeDeclRef(paramDecl); subContext->shared->declValues.Add(paramDeclRef, paramVal); } + + if (paramInfo.isThisParam) + { + subContext->thisVal = paramVal; + } } lowerStmt(subContext, decl->Body); diff --git a/source/slang/parser.cpp b/source/slang/parser.cpp index 3a8c5b362..322f403e6 100644 --- a/source/slang/parser.cpp +++ b/source/slang/parser.cpp @@ -3334,6 +3334,32 @@ namespace Slang static RefPtr<Expr> parsePrefixExpr(Parser* parser); + // Parse OOP `this` expression syntax + static RefPtr<RefObject> parseThisExpr(Parser* parser, void* /*userData*/) + { + RefPtr<ThisExpr> expr = new ThisExpr(); + expr->scope = parser->currentScope; + return expr; + } + + static RefPtr<Expr> parseBoolLitExpr(Parser* parser, bool value) + { + RefPtr<ConstantExpr> constExpr = new ConstantExpr(); + constExpr->ConstType = ConstantExpr::ConstantType::Bool; + constExpr->integerValue = value ? 1 : 0; + return constExpr; + } + + static RefPtr<RefObject> parseTrueExpr(Parser* parser, void* /*userData*/) + { + return parseBoolLitExpr(parser, true); + } + + static RefPtr<RefObject> parseFalseExpr(Parser* parser, void* /*userData*/) + { + return parseBoolLitExpr(parser, false); + } + static RefPtr<Expr> parseAtomicExpr(Parser* parser) { switch( peekTokenType(parser) ) @@ -3577,19 +3603,18 @@ namespace Slang case TokenType::Identifier: { - // TODO(tfoley): Need a name-lookup step here to resolve - // syntactic keywords in expression context. + // We will perform name lookup here so that we can find syntax + // keywords registered for use as expressions. + Token nameToken = peekToken(parser); - if (parser->LookAheadToken("true") || parser->LookAheadToken("false")) + RefPtr<Expr> parsedExpr; + if (tryParseUsingSyntaxDecl<Expr>(parser, &parsedExpr)) { - RefPtr<ConstantExpr> constExpr = new ConstantExpr(); - auto token = parser->tokenReader.AdvanceToken(); - constExpr->token = token; - parser->FillPosition(constExpr.Ptr()); - constExpr->ConstType = ConstantExpr::ConstantType::Bool; - constExpr->integerValue = token.Content == "true" ? 1 : 0; - - return constExpr; + if (!parsedExpr->loc.isValid()) + { + parsedExpr->loc = nameToken.loc; + } + return parsedExpr; } // Default behavior is just to create a name expression @@ -4090,6 +4115,16 @@ namespace Slang #undef MODIFIER + // Add syntax for expression keywords + #define EXPR(KEYWORD, CALLBACK) \ + addBuiltinSyntax<Expr>(session, scope, #KEYWORD, &CALLBACK) + + EXPR(this, parseThisExpr); + EXPR(true, parseTrueExpr); + EXPR(false, parseFalseExpr); + + #undef EXPR + return moduleDecl; } diff --git a/tests/compute/explicit-this-expr.slang b/tests/compute/explicit-this-expr.slang new file mode 100644 index 000000000..7bd8dff99 --- /dev/null +++ b/tests/compute/explicit-this-expr.slang @@ -0,0 +1,34 @@ +//TEST(smoke,compute):COMPARE_COMPUTE:-xslang -use-ir +//TEST_INPUT:ubuffer(data=[0 0 0 0], stride=4):dxbinding(0),glbinding(0),out + +// Access fields of a `struct` type from within a "method" by +// using an explicit `this` expression. + +struct A +{ + float x; + + float addWith(float y) + { + return this.x + y; + } +}; + +RWStructuredBuffer<float> outputBuffer : register(u0); + + +float test(float inVal) +{ + A a; + a.x = inVal; + return a.addWith(inVal*inVal); +} + +[numthreads(4, 1, 1)] +void computeMain(uint3 dispatchThreadID : SV_DispatchThreadID) +{ + uint tid = dispatchThreadID.x; + float inVal = float(tid); + float outVal = test(inVal); + outputBuffer[tid] = outVal; +}
\ No newline at end of file diff --git a/tests/compute/explicit-this-expr.slang.expected.txt b/tests/compute/explicit-this-expr.slang.expected.txt new file mode 100644 index 000000000..f73cfe6c3 --- /dev/null +++ b/tests/compute/explicit-this-expr.slang.expected.txt @@ -0,0 +1,4 @@ +0 +40000000 +40C00000 +41400000 |
