Skip to content

Commit

Permalink
テンプレートリテラルに波括弧を含む式を埋め込められるように (aiscript-dev#845)
Browse files Browse the repository at this point in the history
  • Loading branch information
takejohn authored Nov 8, 2024
1 parent 2971abd commit d2f4965
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 10 deletions.
27 changes: 17 additions & 10 deletions src/parser/scanner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -491,6 +491,7 @@ export class Scanner implements ITokenStream {
let buf = '';
let tokenBuf: Token[] = [];
let state: 'string' | 'escape' | 'expr' | 'finish' = 'string';
let exprBracketDepth = 0;

const pos = this.stream.getPos();
let elementPos = pos;
Expand Down Expand Up @@ -556,17 +557,23 @@ export class Scanner implements ITokenStream {
this.stream.next();
continue;
}
// 埋め込み式の終了
if (this.stream.char === '{') {
exprBracketDepth++;
}
if ((this.stream.char as string) === '}') {
elements.push(TOKEN(TokenKind.TemplateExprElement, elementPos, { hasLeftSpacing, children: tokenBuf }));
// ここから文字列エレメントになるので位置を更新
elementPos = this.stream.getPos();
// TemplateExprElementトークンの終了位置をTokenStreamが取得するためのEOFトークンを追加
tokenBuf.push(TOKEN(TokenKind.EOF, elementPos));
tokenBuf = [];
state = 'string';
this.stream.next();
break;
// 埋め込み式の終了
if (exprBracketDepth === 0) {
elements.push(TOKEN(TokenKind.TemplateExprElement, elementPos, { hasLeftSpacing, children: tokenBuf }));
// ここから文字列エレメントになるので位置を更新
elementPos = this.stream.getPos();
// TemplateExprElementトークンの終了位置をTokenStreamが取得するためのEOFトークンを追加
tokenBuf.push(TOKEN(TokenKind.EOF, elementPos));
tokenBuf = [];
state = 'string';
this.stream.next();
break;
}
exprBracketDepth--;
}
const token = this.readToken();
tokenBuf.push(token);
Expand Down
7 changes: 7 additions & 0 deletions test/literals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,5 +185,12 @@ describe('Template syntax', () => {
`);
eq(res, STR('`a{b}c`'));
});

test.concurrent('nested brackets', async () => {
const res = await exe(`
<: \`{if true {1} else {2}}\`
`);
eq(res, STR('1'));
});
});

1 change: 1 addition & 0 deletions unreleased/braces-in-template-expression.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- テンプレートリテラルに波括弧を含む式を埋め込むことができるようになりました。

0 comments on commit d2f4965

Please sign in to comment.