TemplateParser.ts
74 lines
| 1.7 KiB
| video/mp2t
|
TypeScriptLexer
|
|
r59 | import { argumentNotEmptyString } from "../safe"; | ||
| import { MapOf } from "../interfaces"; | ||||
|
|
r65 | import { TraceSource, DebugLevel } from "../log/TraceSource"; | ||
| import m = require("module"); | ||||
| const trace = TraceSource.get(m.id); | ||||
|
|
r59 | |||
|
|
r82 | const splitRx = /(<%=|<%~|\[%~|\[%=|<%|\[%|%\]|%>)/; | ||
|
|
r59 | |||
| export enum TokenType { | ||||
| None, | ||||
| Text, | ||||
| OpenInlineBlock, | ||||
|
|
r82 | OpenFilterBlock, | ||
|
|
r59 | OpenBlock, | ||
| CloseBlock | ||||
| } | ||||
| const tokenMap: MapOf<TokenType> = { | ||||
| "<%": TokenType.OpenBlock, | ||||
| "[%": TokenType.OpenBlock, | ||||
| "<%=": TokenType.OpenInlineBlock, | ||||
| "[%=": TokenType.OpenInlineBlock, | ||||
|
|
r82 | "<%~": TokenType.OpenFilterBlock, | ||
| "[%~": TokenType.OpenFilterBlock, | ||||
|
|
r59 | "%>": TokenType.CloseBlock, | ||
| "%]": TokenType.CloseBlock | ||||
| }; | ||||
| export interface ITemplateParser { | ||||
| next(): boolean; | ||||
| token(): TokenType; | ||||
| value(): string; | ||||
| } | ||||
| export class TemplateParser implements ITemplateParser { | ||||
| _tokens: string[]; | ||||
| _pos = -1; | ||||
| _type: TokenType; | ||||
|
|
r115 | _value: string | undefined; | ||
|
|
r59 | |||
| constructor(text: string) { | ||||
| argumentNotEmptyString(text, "text"); | ||||
| this._tokens = text.split(splitRx); | ||||
| this._type = TokenType.None; | ||||
| } | ||||
| next() { | ||||
| this._pos++; | ||||
| if (this._pos < this._tokens.length) { | ||||
| this._value = this._tokens[this._pos]; | ||||
| this._type = tokenMap[this._value] || TokenType.Text; | ||||
|
|
r65 | |||
|
|
r59 | return true; | ||
| } else { | ||||
| this._type = TokenType.None; | ||||
| this._value = undefined; | ||||
| return false; | ||||
| } | ||||
| } | ||||
| token() { | ||||
| return this._type; | ||||
| } | ||||
| value() { | ||||
|
|
r115 | if (!this._value) | ||
| throw new Error("The current token doesn't have a value"); | ||||
|
|
r59 | return this._value; | ||
| } | ||||
| } | ||||
