-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParser.lua
More file actions
82 lines (70 loc) · 1.96 KB
/
Copy pathParser.lua
File metadata and controls
82 lines (70 loc) · 1.96 KB
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
--- @class Parser: class
--- @field tokens string[] the input tokens, parsed from source code
--- @field tokenTypes TokenType[] the types of each token, parralel with the `tokens` array
--- @field pos integer the current token's position
--- @field backtrackPoint integer? the point to backtrack to when needed
local Parser = require("class"):extend("Parser")
function Parser:init(tokens, tokenTypes)
self.tokens = tokens
self.tokenTypes = tokenTypes
self.pos = 1
end
function Parser:isEof()
return self.tokenTypes[self.pos] == "eof"
end
function Parser:peek()
local pos = self.pos
return self.tokens[pos], self.tokenTypes[pos]
end
function Parser:skip()
self.pos = self.pos + 1
end
function Parser:next()
local pos = self.pos
local token, tokenType = self.tokens[pos], self.tokenTypes[pos]
self.pos = pos + 1
return token, tokenType
end
function Parser:setBacktrackPoint()
self.backtrackPoint = self.pos
end
function Parser:backtrack()
self.pos = self.backtrackPoint
end
function Parser:consume(expected)
local token = self:peek()
if expected ~= token then
error("Expected '" .. expected .. "', got '" .. token .. "'.")
end
self:skip()
return token
end
function Parser:isNext(token)
local currentToken = self.tokens[self.pos]
if currentToken == token then
self:skip()
return true
end
return false
end
---Checks if the current token is as expected, without consuming it
---@param token string
---@return boolean
function Parser:check(token)
return self.tokens[self.pos] == token
end
--- Accepts a parsable object or function
--- @generic T
--- @param parsable Parsable<T>
--- @return T
function Parser:accept(parsable)
local t = type(parsable)
if t == "function" then
return parsable(self)
elseif t == "table" then
return parsable:parse(self)
else
error("Expected parsable (function or class), got " .. t .. ".")
end
end
return Parser