-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patherrors.js
83 lines (71 loc) · 2.13 KB
/
errors.js
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
const nullable = str => (str ? str : '')
class LoxError {
constructor(msg, startCoordinates, endCoordinates) {
this.msg = msg
this.startCoordinates = startCoordinates
this.endCoordinates = endCoordinates
}
toString() {
return this.msg
}
}
class RuntimeError extends LoxError {
constructor(msg, token) {
super(
`${nullable(token.lexeme && `at "${token.lexeme}": `)}${msg}`,
token.startCoordinates,
token.endCoordinates
)
}
}
class ReturnError {
constructor(val) {
this.value = val
}
}
const error = (msg, startCoordinates, endCoordinates) =>
new LoxError(msg, startCoordinates, endCoordinates)
const parseError = (msg, token) => {
if (token.type === token.EOF) {
return new LoxError(msg, token.startCoordinates, token.endCoordinates)
} else {
return new LoxError(
`${nullable(token.lexeme && `at "${token.lexeme}": `)}${msg}`,
token.startCoordinates,
token.endCoordinates
)
}
}
const runtimeError = (msg, token) => new RuntimeError(msg, token)
const formatLoxError = (e, code) => {
if (e instanceof LoxError) {
const frontIndex = code.lastIndexOf('\n', e.startCoordinates.index)
const preErrorStart = frontIndex < 0 ? 0 : frontIndex
const preErrorSection = code.substring(preErrorStart, e.startCoordinates.index)
// Error String
const errorSection = code.substring(e.startCoordinates.index, e.endCoordinates.index)
// Post Error String
const backIndex = code.indexOf('\n', e.endCoordinates.index)
const postErrorStart = backIndex < 0 ? code.length : backIndex
const postErrorSection = code.substring(e.endCoordinates.index, postErrorStart)
// Print Critical Code
const errorType = e instanceof RuntimeError ? 'Runtime Error' : 'Parse Error'
return {
oneLiner: `${errorType}: ${e.toString()} at ${e.endCoordinates.line}:${e.endCoordinates.col +
1}`,
preErrorSection,
errorSection,
postErrorSection
}
} else {
return { oneLiner: `Unexpected javascript Error: ${e}` }
}
}
module.exports = {
error,
LoxError,
ReturnError,
runtimeError,
parseError,
formatLoxError
}