Skip to content

Commit

Permalink
Support ["prop"] syntax on class definitions (#704)
Browse files Browse the repository at this point in the history
Some classes have properties which are not valid identifiers (such as
https://create.roblox.com/docs/reference/engine/classes/Studio)

This adds support for the following syntax in definition files:
```lua
declare class Foo
    ["a property"]: string
end
```

Closes #702
  • Loading branch information
JohnnyMorganz authored Oct 18, 2022
1 parent 49d6bc3 commit edb4453
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
19 changes: 19 additions & 0 deletions Ast/src/Parser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -905,6 +905,25 @@ AstStat* Parser::parseDeclaration(const Location& start)
{
props.push_back(parseDeclaredClassMethod());
}
else if (lexer.current().type == '[')
{
const Lexeme begin = lexer.current();
nextLexeme(); // [

std::optional<AstArray<char>> chars = parseCharArray();

expectMatchAndConsume(']', begin);
expectAndConsume(':', "property type annotation");
AstType* type = parseTypeAnnotation();

// TODO: since AstName conains a char*, it can't contain null
bool containsNull = chars && (strnlen(chars->data, chars->size) < chars->size);

if (chars && !containsNull)
props.push_back(AstDeclaredClassProp{AstName(chars->data), type, false});
else
report(begin.location, "String literal contains malformed escape sequence");
}
else
{
Name propName = parseName("property name");
Expand Down
17 changes: 17 additions & 0 deletions tests/TypeInfer.definitions.test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -362,4 +362,21 @@ TEST_CASE_FIXTURE(Fixture, "class_definition_overload_metamethods")
CHECK_EQ(toString(requireType("shouldBeVector")), "Vector3");
}

TEST_CASE_FIXTURE(Fixture, "class_definition_string_props")
{
loadDefinition(R"(
declare class Foo
["a property"]: string
end
)");

CheckResult result = check(R"(
local x: Foo
local y = x["a property"]
)");

LUAU_REQUIRE_NO_ERRORS(result);
CHECK_EQ(toString(requireType("y")), "string");
}

TEST_SUITE_END();

0 comments on commit edb4453

Please sign in to comment.