-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
180 lines (149 loc) · 4.51 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
import { RegExpMatchArrayLike, RegExpToken, Token } from 'match-to-token'
export { Token }
export type { TokenJson } from 'match-to-token'
import * as LexerErrorCauses from './causes'
export { LexerErrorCauses }
export { RegExpToken }
export type { RegExpMatchArrayLike }
export interface LexerError extends Error {
cause: LexerErrorCauses.UnexpectedToken
}
export class LexerError extends Error {
name = 'LexerError'
constructor(cause: Error) {
super(cause.message, { cause })
}
}
/**
* Error handler.
*
* @param error The error object
*/
export type ErrorHandler = (error: LexerError) => void
/**
* Filter function.
*
* @param token The token to match.
* @returns `true` if it passes or `false` if it's rejected
*/
export type FilterFunction = (token: Token) => boolean
export type Tokenizer = (input: string) => IterableIterator<RegExpMatchArray>
/**
* Lexer interface.
*/
export interface Lexer {
/**
* Returns token under current position and advances.
*/
advance(): Token
/**
* Returns token under current position.
* When passed a `group` and maybe a `value` it will only return
* the token if they match, otherwise will return `null`.
*
* @param group The group name to examine
* @param value The value to match
*/
peek(): Token
peek(group?: string, value?: string): Token | false
/**
* Advances position only when current `token.group` matches `group`,
* and optionally when `token.value` matches `value`,
* otherwise does nothing.
*
* @param group The group name to examine
* @param value The value to match
*/
accept(group: string, value?: string): Token | null
/**
* Same as accept() except it throws when `token.group` does not match `group`,
* or (optionally) when `token.value` does not match `value`,
*
* @param group The group name to examine
* @param value The value to match
*/
expect(group: string, value?: string): Token
/**
* Sets a function to handle errors. The error handler accepts an {@link Error} object.
*/
onerror(fn: ErrorHandler): void
/**
* Sets a filter function. The filter function receives a {@link Token} as first parameter.
*/
filter(fn: FilterFunction): void
unknown: Token
}
/**
* Generate a {@link Lexer} for given input string.
*/
export type LexerFactory = (input: string) => Lexer
/**
* Create a {@link LexerFactory} with the given {@link Tokenizer}.
*
* It can be anything that, when called with an `input` string, returns an interface that conforms to
* the `IterableIterator<RegExpMatchArray>` type as is returned, for example,
* by [`String.prototype.matchAll(regexp)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll)
*
* @param tokenize A tokenizer Iterable factory.
*/
export const createLexer = (tokenize: Tokenizer) =>
(input: string): Lexer => {
const eof = Token.create('', 'eof', { index: input.length, input })
const unknown = Token.create('', 'unknown', { index: 0, input })
const it = tokenize(input)
let last: Token
let curr: Token
//
// error handling
//
let errorFn: ErrorHandler = (error: Error) => {
throw error
}
const onerror = (fn: ErrorHandler) => {
errorFn = fn
}
//
// filter
//
let filterFn: FilterFunction = () => true
const filter = (fn: FilterFunction) => {
filterFn = fn
// when we receive filter, try to see if the current token passes,
// otherwise try to advance with our new filter using next()
if (!filterFn(curr)) curr = next()
}
//
// iterators
//
const next = () => {
let token
while ((token = it.next().value as Token)) {
if (token && !filterFn(token)) continue
break
}
if (!token) token = eof
return token as Token
}
const advance = () => (([last, curr] = [curr, next()]), last)
const peek = (group?: string, value?: string) => group != null ? curr.is(group, value) && curr : curr
const accept = (group: string, value?: string) => (curr.is(group, value) ? advance() : null)
const expect = (group: string, value?: string) => {
const token = accept(group, value)
if (!token) errorFn(new LexerError(new LexerErrorCauses.UnexpectedToken(curr, group, value)))
return token
}
//
// exports
//
advance() // initial advance is implicit
return {
onerror,
filter,
advance,
peek,
expect,
accept,
unknown,
} as Lexer
}
export default createLexer