Support ["prop"] syntax on class definitions (#704)

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
This commit is contained in:
JohnnyMorganz 2022-10-18 18:15:26 +01:00 committed by GitHub
parent 49d6bc30ad
commit edb4453924
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 36 additions and 0 deletions

View file

@ -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");

View file

@ -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();