-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexpr_eval.nim
More file actions
240 lines (175 loc) · 4.92 KB
/
Copy pathexpr_eval.nim
File metadata and controls
240 lines (175 loc) · 4.92 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
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# expr_eval.nim
#
# Supported grammar:
# number e.g. 12, 3.5
# operators:
# + - * / // %
# parentheses:
# ( expr )
# unary:
# +x, -x
# variable:
# x (optional via evalExpr(expr, xValue))
#
# Notes:
# - Whitespace is ignored
# - / = float division
# - // = floor division
# - Output is string (int if exact, float if needed)
import std/strutils, std/math
# -----------------------------
# Tokens
# -----------------------------
type
TokenKind* = enum
tkNumber, tkPlus, tkMinus, tkMul, tkDiv, tkFloorDiv, tkMod,
tkLParen, tkRParen, tkEOF
Token* = object
kind*: TokenKind
value*: float
# -----------------------------
# Tokenizer
# -----------------------------
proc isDigit(c: char): bool =
c >= '0' and c <= '9'
proc tokenize*(expr: string): seq[Token] =
var i = 0
while i < expr.len:
let c = expr[i]
if c == ' ':
inc i
continue
if isDigit(c) or c == '.':
let start = i
while i < expr.len and (isDigit(expr[i]) or expr[i] == '.'):
inc i
let numStr = expr[start..<i]
result.add(Token(kind: tkNumber, value: parseFloat(numStr)))
continue
case c
of '%':
result.add(Token(kind: tkMod)); inc i
of '+':
result.add(Token(kind: tkPlus)); inc i
of '-':
result.add(Token(kind: tkMinus)); inc i
of '*':
result.add(Token(kind: tkMul)); inc i
of '/':
if i + 1 < expr.len and expr[i + 1] == '/':
result.add(Token(kind: tkFloorDiv))
i += 2
else:
result.add(Token(kind: tkDiv))
inc i
of '(':
result.add(Token(kind: tkLParen)); inc i
of ')':
result.add(Token(kind: tkRParen)); inc i
else:
raise newException(ValueError, "Invalid char: " & $c)
result.add(Token(kind: tkEOF))
# -----------------------------
# Parser
# -----------------------------
type Parser = object
tokens: seq[Token]
pos: int
proc current(p: Parser): Token =
p.tokens[p.pos]
proc advance(p: var Parser) =
inc p.pos
proc parseExpr(p: var Parser): float
proc parseFactor(p: var Parser): float =
case p.current.kind
of tkPlus:
p.advance()
return parseFactor(p)
of tkMinus:
p.advance()
return -parseFactor(p)
of tkNumber:
let t = p.current
p.advance()
return t.value
of tkLParen:
p.advance()
let v = parseExpr(p)
if p.current.kind != tkRParen:
raise newException(ValueError, "Missing closing parenthesis")
p.advance()
return v
else:
raise newException(ValueError, "Expected number or expression")
proc parseTerm(p: var Parser): float =
var left = parseFactor(p)
while true:
case p.current.kind
of tkMul:
p.advance()
left *= parseFactor(p)
of tkDiv:
p.advance()
left /= parseFactor(p)
of tkFloorDiv:
p.advance()
let rhs = parseFactor(p)
left = floor(left / rhs)
of tkMod:
p.advance()
let rhs = parseFactor(p)
left = left mod rhs # float mod via Nim's built-in overload
else:
break
left
proc parseExpr(p: var Parser): float =
var left = parseTerm(p)
while true:
case p.current.kind
of tkPlus:
p.advance()
left += parseTerm(p)
of tkMinus:
p.advance()
left -= parseTerm(p)
else:
break
left
# -----------------------------
# Formatting
# -----------------------------
proc formatResult*(x: float): string =
let rounded = round(x)
if abs(x - rounded) < 1e-9:
return $int(rounded)
var s = formatFloat(x, ffDecimal, 10)
while s.len > 0 and s[^1] == '0':
s.setLen(s.len - 1)
if s.len > 0 and s[^1] == '.':
s.setLen(s.len - 1)
s
# -----------------------------
# Public API (no variable)
# -----------------------------
proc evalExpr*(expr: string): string =
let tokens = tokenize(expr)
var p = Parser(tokens: tokens, pos: 0)
let value = parseExpr(p)
formatResult(value)
# -----------------------------
# Public API (with x substitution)
# -----------------------------
proc evalExpr*(expr: string; xValue: string): string =
var resultExpr = ""
var i = 0
while i < expr.len:
if expr[i] == 'x':
let prevOk = i == 0 or not expr[i - 1].isAlphaNumeric
let nextOk = i + 1 >= expr.len or not expr[i + 1].isAlphaNumeric
if prevOk and nextOk:
resultExpr.add("(" & xValue & ")")
inc i
continue
resultExpr.add(expr[i])
inc i
evalExpr(resultExpr)