Skip to content

String interpolation #1115

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion src/ast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,16 @@ export abstract class Node {
return expr;
}

static createTemplateLiteralExpression(
value: string,
range: Range
): StringLiteralExpression {
var expr = new StringLiteralExpression();
expr.range = range;
expr.value = value;
return expr;
}

static createSuperExpression(
range: Range
): SuperExpression {
Expand Down Expand Up @@ -1300,7 +1310,8 @@ export enum LiteralKind {
STRING,
REGEXP,
ARRAY,
OBJECT
OBJECT,
TEMPLATE,
}

/** Checks if the given node represents a numeric (float or integer) literal. */
Expand Down Expand Up @@ -1555,6 +1566,14 @@ export class StringLiteralExpression extends LiteralExpression {
value: string;
}

/** Represents a string template literal expression. */
export class TemplateLiteralExpression extends LiteralExpression {
literalKind = LiteralKind.TEMPLATE;

/** String value without quotes. */
value: string;
}

/** Represents a `super` expression. */
export class SuperExpression extends IdentifierExpression {
kind = NodeKind.SUPER;
Expand Down
15 changes: 13 additions & 2 deletions src/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,8 @@ import {

nodeIsConstantValue,
findDecorator,
isTypeOmitted
isTypeOmitted,
TemplateLiteralExpression
} from "./ast";

import {
Expand Down Expand Up @@ -7707,6 +7708,10 @@ export class Compiler extends DiagnosticEmitter {
assert(!implicitlyNegate);
return this.compileStringLiteral(<StringLiteralExpression>expression, constraints);
}
case LiteralKind.TEMPLATE: {
assert(!implicitlyNegate);
return this.compileTemplateLiteral(<TemplateLiteralExpression>expression, constraints);
}
case LiteralKind.OBJECT: {
assert(!implicitlyNegate);
return this.compileObjectLiteral(<ObjectLiteralExpression>expression, contextualType);
Expand All @@ -7721,7 +7726,13 @@ export class Compiler extends DiagnosticEmitter {
return module.unreachable();
}

private compileStringLiteral(
compileTemplateLiteral(arg0: TemplateLiteralExpression, constraints: Constraints): ExpressionRef {
const innerExpressions: ExpressionRef[] = [];

return 0;
}

compileStringLiteral(
expression: StringLiteralExpression,
constraints: Constraints
): ExpressionRef {
Expand Down
92 changes: 69 additions & 23 deletions src/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import {
} from "./diagnostics";

import {
normalizePath
normalizePath, CharCode
} from "./util";

import {
Expand Down Expand Up @@ -322,7 +322,7 @@ export class Parser extends DiagnosticEmitter {
statement = this.parseExport(tn, startPos, (flags & CommonFlags.DECLARE) != 0);
}

// handle non-declaration statements
// handle non-declaration statements
} else {
if (exportEnd) {
this.error(
Expand Down Expand Up @@ -503,32 +503,32 @@ export class Parser extends DiagnosticEmitter {
return null;
}

// 'void'
// 'void'
} else if (token == Token.VOID) {
type = Node.createNamedType(
Node.createSimpleTypeName("void", tn.range()), [], false, tn.range(startPos, tn.pos)
);

// 'this'
// 'this'
} else if (token == Token.THIS) {
type = Node.createNamedType(
Node.createSimpleTypeName("this", tn.range()), [], false, tn.range(startPos, tn.pos)
);

// 'true'
// 'true'
} else if (token == Token.TRUE || token == Token.FALSE) {
type = Node.createNamedType(
Node.createSimpleTypeName("bool", tn.range()), [], false, tn.range(startPos, tn.pos)
);

// StringLiteral
// StringLiteral
} else if (token == Token.STRINGLITERAL) {
tn.readString();
type = Node.createNamedType(
Node.createSimpleTypeName("string", tn.range()), [], false, tn.range(startPos, tn.pos)
);

// Identifier
// Identifier
} else if (token == Token.IDENTIFIER) {
let name = this.parseTypeName(tn);
if (!name) return null;
Expand Down Expand Up @@ -608,7 +608,7 @@ export class Parser extends DiagnosticEmitter {
}
type = Node.createNamedType(
Node.createSimpleTypeName("Array", bracketRange),
[ type ],
[type],
nullable,
tn.range(startPos, tn.pos)
);
Expand Down Expand Up @@ -696,7 +696,7 @@ export class Parser extends DiagnosticEmitter {
param.parameterKind = kind;
param.name = name;
param.type = type;
if (!parameters) parameters = [ param ];
if (!parameters) parameters = [param];
else parameters.push(param);
} else {
if (!isSignature) {
Expand All @@ -710,7 +710,7 @@ export class Parser extends DiagnosticEmitter {
param.parameterKind = kind;
param.name = name;
param.type = Node.createOmittedType(tn.range().atEnd);
if (!parameters) parameters = [ param ];
if (!parameters) parameters = [param];
else parameters.push(param);
this.error(
DiagnosticCode.Type_expected,
Expand Down Expand Up @@ -761,7 +761,7 @@ export class Parser extends DiagnosticEmitter {
param.parameterKind = firstParamKind;
param.name = firstParamNameNoType;
param.type = Node.createOmittedType(firstParamNameNoType.range.atEnd);
if (!parameters) parameters = [ param ];
if (!parameters) parameters = [param];
else parameters.push(param);
this.error(
DiagnosticCode.Type_expected,
Expand Down Expand Up @@ -1057,7 +1057,7 @@ export class Parser extends DiagnosticEmitter {
);
typeParameter.defaultType = null;
}
if (!typeParameters) typeParameters = [ typeParameter ];
if (!typeParameters) typeParameters = [typeParameter];
else typeParameters.push(typeParameter);
if (!tn.skip(Token.COMMA)) {
if (tn.skip(Token.GREATERTHAN)) {
Expand Down Expand Up @@ -1486,9 +1486,9 @@ export class Parser extends DiagnosticEmitter {
return null;
}

// or at '(' of arrow function:
// Parameters (':' Type)?
// Statement
// or at '(' of arrow function:
// Parameters (':' Type)?
// Statement

} else {
arrowKind = ArrowKind.ARROW_PARENTHESIZED;
Expand Down Expand Up @@ -2131,7 +2131,7 @@ export class Parser extends DiagnosticEmitter {
name.range
);

// field: (':' Type)? ('=' Expression)? ';'?
// field: (':' Type)? ('=' Expression)? ';'?
} else {
if (flags & CommonFlags.ABSTRACT) {
this.error(
Expand Down Expand Up @@ -2369,7 +2369,7 @@ export class Parser extends DiagnosticEmitter {
let internalPath = assert(ret.internalPath);
let source = tn.source;
let exportPaths = source.exportPaths;
if (!exportPaths) source.exportPaths = [ internalPath ];
if (!exportPaths) source.exportPaths = [internalPath];
else if (!exportPaths.includes(internalPath)) exportPaths.push(internalPath);
if (!this.seenlog.has(internalPath)) {
this.dependees.set(internalPath, this.currentSource);
Expand Down Expand Up @@ -3011,7 +3011,7 @@ export class Parser extends DiagnosticEmitter {

var startPos = tn.tokenPos;
var statements: Statement[],
statement: Statement | null;
statement: Statement | null;

// 'case' Expression ':' Statement*

Expand All @@ -3033,7 +3033,7 @@ export class Parser extends DiagnosticEmitter {
);
}

// 'default' ':' Statement*
// 'default' ':' Statement*

} else if (tn.skip(Token.DEFAULT)) {
if (tn.skip(Token.COLON)) {
Expand Down Expand Up @@ -3397,7 +3397,7 @@ export class Parser extends DiagnosticEmitter {
}
again = false; // parenthesized
break;
}
}
case Token.COMMA: {
break; // continue
}
Expand Down Expand Up @@ -3560,7 +3560,11 @@ export class Parser extends DiagnosticEmitter {
return this.maybeParseCallExpression(tn, expr);
}
case Token.STRINGLITERAL: {
return Node.createStringLiteralExpression(tn.readString(), tn.range(startPos, tn.pos));
return this.parseStringLiteral(tn, startPos);
}
case Token.TEMPLATELITERAL: {
return this.parseTemplateLiteralExpression(tn);
// return Node.createTemplateLiteralExpression(tn.readString(), tn.range(startPos, tn.pos));
}
case Token.INTEGERLITERAL: {
return Node.createIntegerLiteralExpression(tn.readInteger(), tn.range(startPos, tn.pos));
Expand Down Expand Up @@ -3609,6 +3613,48 @@ export class Parser extends DiagnosticEmitter {
}
}
}
parseStringLiteral(tn: Tokenizer, startPos: i32, quote: i32 = -1): Expression {
return Node.createStringLiteralExpression(tn.readString(quote), tn.range(startPos, tn.pos));
}

parseTemplateLiteralExpression(tn: Tokenizer): Expression | null {
var startPos = tn.pos;
tn.inStringTemplate = true;

// at `(String*${ Expression }*String*)*`
const parts: Expression[] = [this.parseStringLiteral(tn, startPos)];

var token = tn.peek();
while (token == Token.DOLLAR) {
tn.skip(token);
tn.skip(Token.OPENBRACE);
let expr = this.parseExpressionStart(tn);
if (expr == null) return null;
parts.push(expr);
tn.skip(Token.CLOSEBRACE);
token = tn.next();
if (token == Token.TEMPLATELITERAL) {
break;
}
if (token == Token.DOLLAR) {
continue;
}
startPos = tn.pos;
parts.push(this.parseStringLiteral(tn, startPos, CharCode.BACKTICK));
token = tn.next();
}
if (token == Token.TEMPLATELITERAL) {
tn.advance();
tn.inStringTemplate = false;
}
if (parts.length == 1) {
return parts[0];
}
return parts.reduce((acc: Expression | null, expr: Expression) => {
if (acc == null) return expr;
return Node.createBinaryExpression(Token.PLUS, acc, expr, tn.range(startPos, tn.pos));
}, null);
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ideally this would generate a TemplateLiteral node holding the nodes of the template literal plus having a step to compile such a node in the compiler, instead of transpiling. Otherwise the AST cannot be reused for syntax highlighting in a future IDE extension. On such a node, I could imagine properties like stringParts[N], expressionParts[N-1].

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ahh good point. Should we also add a default toString to all reference types?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My vote is that the expressions must have a type String in the expressionParts field. Although, it would be nice to check for an empty toString() method. I realize this might not be possible.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The basic types already have #toString implementations, like I32#toString for i32s, String#toString (returning itself) for strings etc. Typically one would resolve the expression parts, obtaining their type, and error if there is no toString or call it otherwise before concatenating with string parts.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I vote for a default toString() method, that uses something like nameof<T>().

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's entirely possible to do something like this:

if (!isDefined(obj.toString())) ERROR("Must implement toString()");

As-pect uses this technique now.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the compiler context, perhaps this might not be so useful, actually.


tryParseTypeArgumentsBeforeArguments(
tn: Tokenizer
Expand All @@ -3628,7 +3674,7 @@ export class Parser extends DiagnosticEmitter {
tn.reset(state);
return null;
}
if (!typeArguments) typeArguments = [ type ];
if (!typeArguments) typeArguments = [type];
else typeArguments.push(type);
} while (tn.skip(Token.COMMA));
if (tn.skip(Token.GREATERTHAN) && tn.skip(Token.OPENPAREN)) {
Expand Down Expand Up @@ -3780,7 +3826,7 @@ export class Parser extends DiagnosticEmitter {
}
// CommaExpression
case Token.COMMA: {
let commaExprs: Expression[] = [ expr ];
let commaExprs: Expression[] = [expr];
do {
expr = this.parseExpression(tn, Precedence.COMMA + 1);
if (!expr) return null;
Expand Down
Loading