-
Notifications
You must be signed in to change notification settings - Fork 0
/
nrpnc.nim
498 lines (441 loc) · 19.4 KB
/
nrpnc.nim
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
# RPN Calculator
# Written by Chris DeBoy
#[
This is free and unencumbered software released into the public domain.
Zero-Clause BSD
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED “AS IS” AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA
OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
]#
import os, math, sequtils, strutils, tables, terminal
###############
# T Y P E S #
###############
type
Environment = ref object
name : string
program_stack : seq[string]
program_counter : int
definitions : Table[string, Environment]
parent : Environment
###################
# G L O B A L S #
###################
var
repl_mode : bool = false
stack : seq[float]
operations : Table[string, proc(environment: Environment):bool{.nimcall.}]
const whitespace = ["", "\t", "\n"]
const constants = {
"tau": TAU,
"pi": PI,
"e": E
}.toTable
#---------------------------------------------------------------------------------------------------
proc print_error(token_index: int, funcname, message: string) =
echo "> Error in token ", token_index, " of function ", funcname, ": ", message, "\n"
proc check_stack(environment: Environment): bool =
if 0 < len(stack): return false
print_error(environment.program_counter, environment.name, "Error: No values have been entered.")
true
proc print_head(environment: Environment): bool =
if check_stack(environment): return true
echo "= ", stack[0], "\n"
false
proc print_stack(environment: Environment): bool =
if check_stack(environment): return true
for index, element in stack:
echo "= ", stack[index]
echo ""
false
proc print_title() =
echo "Nim Reverse Polish Notation Calculator\n"
proc is_char(s: string): bool = len(s) == 1
proc is_number(s: string): bool =
try:
discard parseFloat(s)
true
except ValueError:
false
#---------------------------------------------------------------------------------------------------
proc is_last(environment: Environment): bool = environment.program_counter == environment.program_stack.high and repl_mode and environment.parent == nil
proc is_reserved(s: string): bool = s in whitespace and s in operations and s in constants
#---------------------------------------------------------------------------------------------------
# Applies a function, taking the top of the stack out as an argument, to every
# Element in the stack.
proc apply_stack(environment: Environment, op: proc(a: float): float): bool =
if check_stack(environment): return true
for index, element in stack:
stack[index] = op(element)
discard print_stack(environment)
false
proc apply_stack(environment: Environment, op: proc(a, b: float): float): bool =
if check_stack(environment): return true
let x = stack[0]
stack.delete(0)
for index, element in stack:
stack[index] = op(element, x)
discard print_stack(environment)
false
#---------------------------------------------------------------------------------------------------
# Applies a function to the top of the stack.
# Removes the top two elements, and pushes their result in
proc compute_head(environment: Environment, op: proc(a, b: float): float): bool =
if stack.high < 1:
print_error(environment.program_counter, environment.name, "Need additional value for operation.")
return true
let y = stack[0]
let x = stack[1]
stack.delete(0)
stack[0] = op(x, y)
if is_last(environment): discard print_head(environment)
# Removes the top element and pushes its result in.
proc compute_head(environment: Environment, op: proc(a:float): float): bool =
if check_stack(environment): return true
stack[0] = op(stack[0])
if is_last(environment): discard print_head(environment)
# Computes all the elements of the stack together and replaces them with their
# Result
proc compute_stack(environment: Environment, op: proc(a, b: float): float): bool =
if check_stack(environment): return true
var x = stack[0]
stack.delete(0)
while 0 < len(stack):
x = op(x, stack[0])
stack.delete(0)
stack.insert(x, 0)
if is_last(environment): discard print_head(environment)
false
#---------------------------------------------------------------------------------------------------
proc compute_abs(a: float): float = abs[float](a)
proc compute_add(a, b: float): float = a + b
proc compute_sub(a, b: float): float = a - b
proc compute_mul(a, b: float): float = a * b
proc compute_div(a, b: float): float = a / b
proc compute_pow(a, b: float): float = pow(a, b)
proc compute_mod(a, b: float): float = a mod b
proc compute_fac(a: float): float = float( fac(int(a)))
proc compute_les(a, b: float): float = float(a < b)
proc compute_mor(a, b: float): float = float(a > b)
proc compute_leq(a, b: float): float = float(a <= b)
proc compute_meq(a, b: float): float = float(a >= b)
proc compute_eq( a, b: float): float = float(a == b)
proc compute_neq(a, b: float): float = float(a != b)
#---------------------------------------------------------------------------------------------------
#************
# Operations
#************
proc do_clear_screen(environment: Environment): bool =
eraseScreen()
setCursorPos(0,0)
print_title()
false
proc do_dump_stack(environment: Environment): bool =
stack.setLen(0)
if is_last(environment): echo "> Stack dumped.\n"
false
proc do_dup(environment: Environment): bool =
if check_stack(environment): return true
stack.insert(stack[0])
if is_last(environment): echo "> Value ", stack[0], " duplicated.\n"
proc do_pop(environment: Environment): bool =
if check_stack(environment): return true
if is_last(environment): echo "> ", stack[0], " popped from top of the stack.\n"
stack.delete(0)
false
proc do_pop_at(environment: Environment): bool =
if check_stack(environment): return true
let index = int(stack[0])
if index < 1:
print_error(environment.program_counter, environment.name, "Given index to pop must be 1 or greater.")
return true
if stack.high < index:
print_error(environment.program_counter, environment.name, "Given index is out of stack bounds.")
return true
if is_last(environment): echo "> Value ", stack[index], " removed from index ", index, " of the stack.\n"
stack.delete(index)
proc do_quit(environment: Environment): bool =
echo "\tGoodbye!"
quit(0)
proc do_store_var(environment: Environment): bool =
if check_stack(environment): return true
var definition: Environment = Environment()
let next_instruction = environment.program_counter + 1
if next_instruction > environment.program_stack.high:
print_error(environment.program_counter, environment.name, "Program ended abruptly; No variable to store to.\n")
return true
let name = environment.program_stack[next_instruction]
if is_reserved(name):
echo "Function name: ", name
print_error(environment.program_counter, environment.name, "Variable name " & name & " attempts to override a reserved token.")
return true
definition.name = name
definition.program_stack.add($stack[0])
stack.delete(0)
environment.definitions.add(name, definition)
environment.program_counter = environment.program_counter + 1
if is_last(environment): echo definition.program_stack[0], " stored to ", name
# `if` works by checking if the top element of the stack is zero. If so, it exits,
# allowing the program counter to continue down the program stack. If not, it
# iterates through the program until it encounters an `else`, then sets the
# program counter to that position.
proc do_if(environment: Environment): bool =
if check_stack(environment): return true
if is_last(environment): print_error(environment.program_counter, environment.name, "Program ends abruptly -- conditional code needed.")
if stack[0] != 0: return false
let tok_num: int = environment.program_counter
var
if_count: int = 0
counter: int = environment.program_counter
close_reached: bool = false
while counter <= environment.program_stack.high:
inc(counter)
let token = environment.program_stack[counter]
case token
of "if": inc(if_count)
of "fi":
if if_count == 0:
close_reached = true
break
dec(if_count)
of "else":
if if_count == 0:
close_reached = true
break
if close_reached == false:
print_error(counter, environment.name, "if statement at token " & intToStr(tok_num) & " left unclosed.")
environment.program_counter = counter
# `else` works by skipping the program counter forward to its corresponding `fi`
# statement.
proc do_else(environment: Environment): bool =
if check_stack(environment): return true
if is_last(environment): print_error( environment.program_counter, environment.name, "Program ends abruptly -- else block needed.")
let tok_num: int = environment.program_counter
var
if_count: int = 0
counter: int = environment.program_counter
close_reached: bool = false
while counter <= environment.program_stack.high:
inc(counter)
let token = environment.program_stack[counter]
if token == "if": inc(if_count)
elif token == "fi":
if if_count == 0:
close_reached = true
break
dec(if_count)
if close_reached == false: print_error(counter, environment.name, "else statement at token " & intToStr(tok_num) & " left unclosed.")
environment.program_counter = counter
# Defines a function and adds it to `environment`.
proc do_defun(environment: Environment): bool =
if is_last(environment): print_error( environment.program_counter, environment.name, "Program ends abruptly -- function started, but not defined.")
let tok_num: int = environment.program_counter
var
defun_count: int = 0
counter: int = environment.program_counter + 1
close_reached: bool = false
defintion: Environment = Environment()
name: string = environment.program_stack[counter]
if is_reserved(name):
echo "Function name: ", name
print_error(environment.program_counter, environment.name, "Function name " & name & " attempts to override a reserved token.")
return true
defintion.name = name
defintion.parent = environment
while counter <= environment.program_stack.high:
counter.inc()
let token = environment.program_stack[counter]
if token == "{": defun_count.inc()
elif token == "}":
if defun_count == 0:
close_reached = true
break
defun_count.dec()
if (token in whitespace) == false: defintion.program_stack.add(token)
if close_reached == false: print_error(environment.program_counter, environment.name, "Function declaration at token " & intToStr(tok_num) & " left unclosed.")
environment.definitions.add(name, defintion)
environment.program_counter = counter
# Does nothing.
# "He's doing his best!"
proc do_nop(environment: Environment): bool = false
###################
# Math Operations #
###################
proc d2r(num: float): float = degToRad[float](num)
proc sgn(num: float): float = float(sgn[float](num))
proc r2d(num: float): float = radToDeg[float](num)
proc do_add(environment: Environment) : bool = compute_head(environment, compute_add)
proc do_sub(environment: Environment) : bool = compute_head(environment, compute_sub)
proc do_mul(environment: Environment) : bool = compute_head(environment, compute_mul)
proc do_div(environment: Environment) : bool = compute_head(environment, compute_div)
proc do_mod(environment: Environment) : bool = compute_head(environment, compute_mod)
proc do_les(environment: Environment) : bool = compute_head(environment, compute_les)
proc do_mor(environment: Environment) : bool = compute_head(environment, compute_mor)
proc do_leq(environment: Environment) : bool = compute_head(environment, compute_leq)
proc do_meq(environment: Environment) : bool = compute_head(environment, compute_meq)
proc do_eq(environment: Environment) : bool = compute_head(environment, compute_eq)
proc do_neq(environment: Environment) : bool = compute_head(environment, compute_neq)
proc do_abs(environment: Environment) : bool = compute_head(environment, compute_abs)
proc do_atan(environment: Environment) : bool = compute_head(environment, arctan)
proc do_atan2(environment: Environment) : bool = compute_head(environment, arctan2)
proc do_atanh(environment: Environment) : bool = compute_head(environment, arctanh)
proc do_cbrt(environment: Environment) : bool = compute_head(environment, cbrt)
proc do_ceil(environment: Environment) : bool = compute_head(environment, ceil)
proc do_cos(environment: Environment) : bool = compute_head(environment, cos)
proc do_cot(environment: Environment) : bool = compute_head(environment, cot)
proc do_csc(environment: Environment) : bool = compute_head(environment, csc)
proc do_d2r(environment: Environment) : bool = compute_head(environment, d2r)
proc do_exp(environment: Environment) : bool = compute_head(environment, exp)
proc do_fac(environment: Environment) : bool = compute_head(environment, compute_fac)
proc do_flr(environment: Environment) : bool = compute_head(environment, floor)
proc do_gam(environment: Environment) : bool = compute_head(environment, gamma)
proc do_gcd(environment: Environment) : bool = compute_head(environment, gcd)
proc do_hyp(environment: Environment) : bool = compute_head(environment, hypot)
proc do_log(environment: Environment) : bool = compute_head(environment, log10)
proc do_pow(environment: Environment) : bool = compute_head(environment, compute_pow)
proc do_r2d(environment: Environment) : bool = compute_head(environment, r2d)
proc do_sec(environment: Environment) : bool = compute_head(environment, sec)
proc do_sgn(environment: Environment) : bool = compute_head(environment, sgn)
proc do_sin(environment: Environment) : bool = compute_head(environment, sin)
proc do_sqrt(environment: Environment) : bool = compute_head(environment, sqrt)
proc do_tan(environment: Environment) : bool = compute_head(environment, tan)
proc cumulative_add(environment: Environment) : bool = compute_stack(environment, compute_add)
proc cumulative_sub(environment: Environment) : bool = compute_stack(environment, compute_sub)
proc cumulative_mul(environment: Environment) : bool = compute_stack(environment, compute_mul)
proc cumulative_div(environment: Environment) : bool = compute_stack(environment, compute_div)
proc apply_mod(environment: Environment) : bool = apply_stack(environment, compute_mod)
proc apply_pow(environment: Environment) : bool = apply_stack(environment, compute_pow)
operations = {
# Standard Operations
"+" : do_add,
"-" : do_sub,
"*" : do_mul,
"/" : do_div,
"%" : do_mod,
"^" : do_pow,
"?" : print_head,
# Variadic Operations
"?..." : print_stack,
"++" : cumulative_add,
"--" : cumulative_sub,
"**" : cumulative_mul,
"//" : cumulative_div,
"%..." : apply_mod,
"^..." : apply_pow,
# Comparison Operations
"<" : do_les,
">" : do_mor,
"<=" : do_leq,
">=" : do_meq,
"==" : do_eq,
"!=" : do_neq,
# Math Functions
"abs" : do_abs,
"atan" : do_atan,
"atan2" : do_atan2,
"atanh" : do_atanh,
"cbrt" : do_cbrt,
"ceil" : do_ceil,
"cos" : do_cos,
"cot" : do_cot,
"csc" : do_csc,
"d2r" : do_d2r,
"exp" : do_exp,
"fac" : do_fac,
"flr" : do_flr,
"gam" : do_gam,
"gcd" : do_gcd,
"hyp" : do_hyp,
"r2d" : do_r2d,
"sec" : do_sec,
"sgn" : do_sgn,
"sin" : do_sin,
"sqrt" : do_sqrt,
"tan" : do_tan,
# Control Flow
"if" : do_if,
"else" : do_else,
"fi" : do_nop,
"{" : do_defun,
"}" : do_nop,
# Miscelaneous Functions
"clr" : do_clear_screen,
"ds" : do_dump_stack,
"dup" : do_dup,
"pop" : do_pop,
"pop@" : do_pop_at,
"quit" : do_quit,
"sto:" : do_store_var
}.toTable
#---------------------------------------------------------------------------------------------------
proc execute(environment: Environment, function: string): bool
proc evaluate(environment: Environment) =
#echo user_input, " | ", len(user_input)
#program_stack = user_input
if len(environment.program_stack) == 0: return
let backup_stack = stack
var err = false
while environment.program_counter <= environment.program_stack.high:
let
index: int = environment.program_counter
token: string = environment.program_stack[index]
#is_last: bool = index == program_stack.high
if token in whitespace:
environment.program_counter.inc()
continue
if token in operations:
err = operations[token](environment)
elif token in constants:
stack.insert(constants[token])
if is_last(environment): discard print_head(environment)
elif is_number(token):
stack.insert(parseFloat(token), 0)
else:
if not execute(environment, token):
echo "> Syntax error in token, ", index, ": ", token, "\n"
err = true
else:
if is_last(environment): discard print_head(environment)
if err:
stack = backup_stack
return
environment.program_counter.inc()
environment.program_counter = 0
proc execute(environment: Environment, function: string): bool =
if not (function in environment.definitions):
if environment.parent != nil: return execute(environment.parent, function)
else: return false
else:
evaluate(environment.definitions[function])
return true
#---------------------------------------------------------------------------------------------------
#############
# M A I N #
#############
proc repl() =
var environment: Environment = Environment()
#environment.repl_mode = true
while true:
environment.program_stack = readLine(stdin).split(' ')
evaluate(environment)
#environment.program_counter = 0
let args = commandLineParams()
if len(args) > 0:
var environment: Environment = Environment()
environment.program_stack = args
evaluate(environment)
if len(stack) == 0: quit(0)
let product = stack[0]
if product mod 1 > 0: echo product
else: echo int(product)
else:
repl_mode = true
print_title()
repl()