| 5 | |
| 6 | |
| 7 | export default class TokenizerImpl implements Tokenizer { |
| 8 | private _spec: Spec; |
| 9 | private _string: String | undefined = undefined; |
| 10 | private _cursor: number; |
| 11 | |
| 12 | constructor(spec: Spec) { |
| 13 | this._spec = spec; |
| 14 | this._cursor = 0; |
| 15 | } |
| 16 | |
| 17 | initTokenizer(stringToTokenize: String) { |
| 18 | this._string = stringToTokenize; |
| 19 | this._cursor = 0; |
| 20 | } |
| 21 | |
| 22 | isEOF() { |
| 23 | if (!this._string) return true; |
| 24 | |
| 25 | return this._cursor === this._string.length; |
| 26 | } |
| 27 | |
| 28 | hasMoreTokens() { |
| 29 | if (!this._string) return false; |
| 30 | |
| 31 | return this._cursor < this._string.length; |
| 32 | } |
| 33 | |
| 34 | getNextToken(): Token | null { |
| 35 | if (!this._string) |
| 36 | throw new InvalidStateException( |
| 37 | "Tokenizer is not initialized with string. " + |
| 38 | "Please call initTokenizer method first." |
| 39 | ); |
| 40 | |
| 41 | if (!this.hasMoreTokens()) { |
| 42 | return null; |
| 43 | } |
| 44 | |
| 45 | const string = this._string.slice(this._cursor); |
| 46 | |
| 47 | for (const { regex, tokenType } of this._spec) { |
| 48 | const tokenValue = this._matched(regex, string); |
| 49 | |
| 50 | if (tokenValue === null) { |
| 51 | continue; |
| 52 | } |
| 53 | |
| 54 | if (tokenType === null) { |
| 55 | return this.getNextToken(); |
| 56 | } |
| 57 | |
| 58 | return { |
| 59 | type: tokenType, |
| 60 | value: tokenValue, |
| 61 | }; |
| 62 | } |
| 63 | |
| 64 | throw new SyntaxError(`Kya kar rha hai tu??...Unexpected token: "${string[0]}"`); |
nothing calls this directly
no outgoing calls
no test coverage detected