Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80550 views
1
import {types as tt} from "./tokentype"
2
import {Parser} from "./state"
3
import {lineBreak} from "./whitespace"
4
5
const pp = Parser.prototype
6
7
// ## Parser utilities
8
9
// Test whether a statement node is the string literal `"use strict"`.
10
11
pp.isUseStrict = function(stmt) {
12
return this.options.ecmaVersion >= 5 && stmt.type === "ExpressionStatement" &&
13
stmt.expression.type === "Literal" && stmt.expression.value === "use strict"
14
}
15
16
// Predicate that tests whether the next token is of the given
17
// type, and if yes, consumes it as a side effect.
18
19
pp.eat = function(type) {
20
if (this.type === type) {
21
this.next()
22
return true
23
} else {
24
return false
25
}
26
}
27
28
// Tests whether parsed token is a contextual keyword.
29
30
pp.isContextual = function(name) {
31
return this.type === tt.name && this.value === name
32
}
33
34
// Consumes contextual keyword if possible.
35
36
pp.eatContextual = function(name) {
37
return this.value === name && this.eat(tt.name)
38
}
39
40
// Asserts that following token is given contextual keyword.
41
42
pp.expectContextual = function(name) {
43
if (!this.eatContextual(name)) this.unexpected()
44
}
45
46
// Test whether a semicolon can be inserted at the current position.
47
48
pp.canInsertSemicolon = function() {
49
return this.type === tt.eof ||
50
this.type === tt.braceR ||
51
lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
52
}
53
54
pp.insertSemicolon = function() {
55
if (this.canInsertSemicolon()) {
56
if (this.options.onInsertedSemicolon)
57
this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc)
58
return true
59
}
60
}
61
62
// Consume a semicolon, or, failing that, see if we are allowed to
63
// pretend that there is a semicolon at this position.
64
65
pp.semicolon = function() {
66
if (!this.eat(tt.semi) && !this.insertSemicolon()) this.unexpected()
67
}
68
69
pp.afterTrailingComma = function(tokType) {
70
if (this.type == tokType) {
71
if (this.options.onTrailingComma)
72
this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc)
73
this.next()
74
return true
75
}
76
}
77
78
// Expect a token of a given type. If found, consume it, otherwise,
79
// raise an unexpected token error.
80
81
pp.expect = function(type) {
82
this.eat(type) || this.unexpected()
83
}
84
85
// Raise an unexpected token error.
86
87
pp.unexpected = function(pos) {
88
this.raise(pos != null ? pos : this.start, "Unexpected token")
89
}
90
91