|
@@ -0,0 +1,55 @@
|
|
1
|
+const Node = require('./node')
|
|
2
|
+const tokenTypes = require('./tokenTypes')
|
|
3
|
+
|
|
4
|
+module.exports = class Parser {
|
|
5
|
+ constructor(tokens) {
|
|
6
|
+ this.tokens = tokens
|
|
7
|
+ }
|
|
8
|
+
|
|
9
|
+ parse() {
|
|
10
|
+ let tree = []
|
|
11
|
+ while (this.tokens.peek().type !== tokenTypes.EOF) {
|
|
12
|
+ tree.push(this.expr())
|
|
13
|
+ }
|
|
14
|
+ return tree
|
|
15
|
+ }
|
|
16
|
+
|
|
17
|
+ expr() {
|
|
18
|
+ this.tokens.eat(tokenTypes.OPAREN)
|
|
19
|
+
|
|
20
|
+ let tokenTypesToEndTheLoop = [
|
|
21
|
+ tokenTypes.OPAREN,
|
|
22
|
+ tokenTypes.CPAREN,
|
|
23
|
+ tokenTypes.EOF,
|
|
24
|
+ ]
|
|
25
|
+
|
|
26
|
+ let functionCallNode = new Node()
|
|
27
|
+ functionCallNode.functionName = this.tokens.eat(tokenTypes.LITERAL).value
|
|
28
|
+ functionCallNode.args = []
|
|
29
|
+ functionCallNode.subtree = []
|
|
30
|
+
|
|
31
|
+ while (!tokenTypesToEndTheLoop.includes(this.tokens.peek().type)) {
|
|
32
|
+ if (this.tokens.peek().type === tokenTypes.ATTRIBUTE) {
|
|
33
|
+ functionCallNode.args.push(this.attribute())
|
|
34
|
+ }
|
|
35
|
+ }
|
|
36
|
+
|
|
37
|
+ this.tokens.eat(tokenTypes.CPAREN)
|
|
38
|
+
|
|
39
|
+ return functionCallNode
|
|
40
|
+ }
|
|
41
|
+
|
|
42
|
+ attribute() {
|
|
43
|
+ let attributeNode = new Node()
|
|
44
|
+ attributeNode.attributeName = this.tokens.eat(tokenTypes.ATTRIBUTE).value
|
|
45
|
+ attributeNode.attributeValue = this.string()
|
|
46
|
+ return attributeNode
|
|
47
|
+ }
|
|
48
|
+
|
|
49
|
+ string() {
|
|
50
|
+ this.tokens.eat(tokenTypes.QUOTE)
|
|
51
|
+ let stringValue = this.tokens.eat(tokenTypes.LITERAL).value
|
|
52
|
+ this.tokens.eat(tokenTypes.QUOTE)
|
|
53
|
+ return stringValue
|
|
54
|
+ }
|
|
55
|
+}
|