From 844d4bf1fe57a2192ba7d89184aab779eeea4c3d Mon Sep 17 00:00:00 2001 From: Dilip Kola Date: Tue, 19 Sep 2023 17:27:47 +0530 Subject: [PATCH] feat: add support for short key value in object expr --- src/parser.ts | 38 +++++++++++++++++++++++++----- test/scenarios/objects/template.jt | 10 ++++---- 2 files changed, 37 insertions(+), 11 deletions(-) diff --git a/src/parser.ts b/src/parser.ts index e5833f6..5990615 100644 --- a/src/parser.ts +++ b/src/parser.ts @@ -828,13 +828,31 @@ export class JsonTemplateParser { return key; } - private parseObjectPropExpr(): ObjectPropExpression { - let key: Expression | string | undefined; - if (!this.lexer.matchSpread()) { - key = this.parseObjectKeyExpr(); - this.lexer.expect(':'); + private parseShortKeyValueObjectPropExpr(): ObjectPropExpression | undefined { + if (this.lexer.matchID() && (this.lexer.match(',', 1) || this.lexer.match('}', 1))) { + const key = this.lexer.lookahead().value; + const value = this.parseBaseExpr(); + return { + type: SyntaxType.OBJECT_PROP_EXPR, + key, + value, + }; } - const value = this.parseSpreadExpr(); + } + + private parseSpreadObjectPropExpr(): ObjectPropExpression | undefined { + if (this.lexer.matchSpread()) { + return { + type: SyntaxType.OBJECT_PROP_EXPR, + value: this.parseSpreadExpr(), + }; + } + } + + private parseNormalObjectPropExpr(): ObjectPropExpression { + const key = this.parseObjectKeyExpr(); + this.lexer.expect(':'); + const value = this.parseBaseExpr(); return { type: SyntaxType.OBJECT_PROP_EXPR, key, @@ -842,6 +860,14 @@ export class JsonTemplateParser { }; } + private parseObjectPropExpr(): ObjectPropExpression { + return ( + this.parseSpreadObjectPropExpr() ?? + this.parseShortKeyValueObjectPropExpr() ?? + this.parseNormalObjectPropExpr() + ); + } + private parseObjectExpr(): ObjectExpression { this.lexer.expect('{'); const props = this.parseCommaSeparatedElements('}', () => this.parseObjectPropExpr()); diff --git a/test/scenarios/objects/template.jt b/test/scenarios/objects/template.jt index bbc3db1..35df1f3 100644 --- a/test/scenarios/objects/template.jt +++ b/test/scenarios/objects/template.jt @@ -1,14 +1,14 @@ let c = "c key"; let d = 3; +let b = 2; let a = { - // short form for "a" - a: 1, - "b": 2, + "a": 1, + b, // [c] coverts to "c key" [c]: { // this coverts to d: 3 - d: d - } + d + }, }; a.({ a: .a,