all repos — min @ f30ddf488d2127a0fc4007f4e69a0af4158962f1

A small but practical concatenative programming language.

lib/min_lang.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
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
 1000
 1001
 1002
 1003
 1004
 1005
 1006
 1007
 1008
 1009
 1010
 1011
 1012
 1013
 1014
 1015
 1016
 1017
 1018
 1019
 1020
 1021
 1022
 1023
 1024
 1025
 1026
 1027
 1028
 1029
 1030
 1031
 1032
 1033
 1034
 1035
 1036
 1037
 1038
 1039
 1040
 1041
 1042
 1043
 1044
 1045
 1046
 1047
 1048
 1049
 1050
 1051
 1052
 1053
 1054
 1055
 1056
 1057
 1058
 1059
 1060
 1061
 1062
 1063
 1064
 1065
 1066
 1067
 1068
 1069
 1070
 1071
 1072
 1073
 1074
 1075
 1076
 1077
 1078
 1079
 1080
 1081
 1082
 1083
 1084
 1085
 1086
 1087
 1088
 1089
 1090
 1091
 1092
 1093
import 
  critbits, 
  strutils, 
  sequtils,
  parseopt,
  algorithm
when defined(mini):
  import
    rdstdin,
    ../core/minilogger
else:
  import 
    os,
    json,
    logging,
    ../packages/niftylogger,
    ../packages/nimline/nimline,
    ../packages/nim-sgregex/sgregex
import 
  ../core/env,
  ../core/meta,
  ../core/parser, 
  ../core/value, 
  ../core/interpreter, 
  ../core/utils,
  ../core/scope

proc lang_module*(i: In) =
  let def = i.scope

  when not defined(mini):
  
    def.symbol("from-json") do (i: In):
      let vals = i.expect("string")
      let s = vals[0]
      i.push i.fromJson(s.getString.parseJson)
      
    def.symbol("to-json") do (i: In):
      let vals = i.expect "a"
      let q = vals[0]
      i.push(($((i%q).pretty)).newVal)
  
    # Save/load symbols
  
    def.symbol("save-symbol") do (i: In) {.gcsafe.}:
      let vals = i.expect("'sym")
      let s = vals[0]
      let sym = s.getString
      let op = i.scope.getSymbol(sym)
      if op.kind == minProcOp:
        raiseInvalid("Symbol '$1' cannot be serialized." % sym)
      let json = MINSYMBOLS.readFile.parseJson
      json[sym] = i%op.val
      MINSYMBOLS.writeFile(json.pretty)

    def.symbol("load-symbol") do (i: In):
      let vals = i.expect("'sym")
      let s = vals[0]
      let sym = s.getString
      let json = MINSYMBOLS.readFile.parseJson
      if not json.hasKey(sym):
        raiseUndefined("Symbol '$1' not found." % sym)
      let val = i.fromJson(json[sym])
      i.scope.symbols[sym] = MinOperator(kind: minValOp, val: val, quotation: true)

    def.symbol("saved-symbols") do (i: In):
      var q = newSeq[MinValue](0)
      let json = MINSYMBOLS.readFile.parseJson
      for k,v in json.pairs:
        q.add k.newVal
      i.push q.newVal

    def.symbol("remove-symbol") do (i: In):
      let vals = i.expect("'sym")
      let s = vals[0]
      let sym = s.getString
      var json = MINSYMBOLS.readFile.parseJson
      if not json.hasKey(sym):
        raiseUndefined("Symbol '$1' not found." % sym)
      json.delete(sym)
      MINSYMBOLS.writeFile(json.pretty)

    def.symbol("load") do (i: In):
      let vals = i.expect("'sym")
      let s = vals[0]
      var file = s.getString
      if not file.endsWith(".min"):
        file = file & ".min"
      info("[load] File: ", file)
      if MINCOMPILED:
        var normalizedFile = strutils.replace(strutils.replace(file, "\\", "/"), "./", "")
        var compiledFile = normalizedFile
        var normalizedCurrFile = strutils.replace(strutils.replace(i.filename, "\\", "/"), "./", "")
        var parts = normalizedCurrFile.split("/")
        if parts.len > 1:
          discard parts.pop
          compiledFile = parts.join("/") & "/" & normalizedFile
        if COMPILEDMINFILES.hasKey(compiledFile):
          COMPILEDMINFILES[compiledFile](i)
          return
      var f = i.pwd.joinPath(file)
      if not f.fileExists:
        raiseInvalid("File '$1' does not exist." % file)
      i.load f

    def.symbol("require") do (i: In):
      let vals = i.expect("'sym")
      let s = vals[0]
      var file = s.getString
      if not file.endsWith(".min"):
        file = file & ".min"
      info("[require] File: ", file)
      if MINCOMPILED:
        var normalizedFile = strutils.replace(strutils.replace(file, "\\", "/"), "./", "")
        var compiledFile = normalizedFile
        var normalizedCurrFile = strutils.replace(strutils.replace(i.filename, "\\", "/"), "./", "")
        var parts = normalizedCurrFile.split("/")
        if parts.len > 1:
          discard parts.pop
          compiledFile = parts.join("/") & "/" & normalizedFile
        echo compiledFile, " - ", normalizedFile, " - ", i.filename, " - ", normalizedCurrFile
        if COMPILEDMINFILES.hasKey(compiledFile):
          var i2 = i.copy(file)
          COMPILEDMINFILES[compiledFile](i2)
          var mdl = newDict(i2.scope)
          mdl.objType = "module"
          for key, value in i2.scope.symbols.pairs:
            mdl.scope.symbols[key] = value
          i.push(mdl)
          return
      let fn = strutils.replace(i.filename, "./", "")
      var dirs: seq[string] = fn.split("/")
      discard dirs.pop
      var pwd = dirs.join("/")
      var f: string
      if pwd == "":
        f = file
      else:
        f = pwd&"/"&file
      if not f.fileExists:
        raiseInvalid("File '$1' does not exist." % file)
      i.push i.require(f)

    def.symbol("read") do (i: In):
      let vals = i.expect("'sym")
      let s = vals[0]
      var file = s.getString
      if not file.endsWith(".min"):
        file = file & ".min"
      info("[read] File: ", file)
      if not file.fileExists:
        raiseInvalid("File '$1' does not exist." % file)
      i.push i.read file

    def.symbol("raw-args") do (i: In):
      var args = newSeq[MinValue](0)
      for par in commandLineParams():
          args.add par.newVal
      i.push args.newVal

  def.symbol("with") do (i: In):
    let vals = i.expect("dict", "quot")
    var qscope = vals[0]
    var qprog = vals[1]
    i.withDictScope(qscope.scope):
      for v in qprog.qVal:
        i.push v

  def.symbol("publish") do (i: In):
    let vals = i.expect("dict", "'sym")
    let qscope = vals[0]
    let str = vals[1]
    let sym = str.getString
    if qscope.scope.symbols.hasKey(sym) and qscope.scope.symbols[sym].sealed:
      raiseUndefined("Attempting to redefine sealed symbol '$1'" % [sym])
    let scope = i.scope
    info("[publish] Symbol: $2" % [sym])
    let op = proc(i: In) {.closure.} =
      let origscope = i.scope 
      i.scope = scope
      i.evaluating = true
      i.push sym.newSym
      i.evaluating = false
      i.scope = origscope
    qscope.scope.symbols[sym] = MinOperator(kind: minProcOp, prc: op)

  ### End of symbols not present in minimin
  
  def.symbol("operator") do (i: In):
    let vals = i.expect("quot");
    let q = vals[0]
    if q.qVal.len != 4:
      raiseInvalid("Invalid operator definition")
    let tv = q.qVal[0]
    if not tv.isSymbol or (tv.symVal != "symbol" and tv.symVal != "sigil"):
      raiseInvalid("Incorrect operator type specified (it must be 'symbol' or 'sigil', found '$#')" % tv.symVal)
    let t = tv.symVal
    let nv = q.qVal[1]
    if not nv.isSymbol:
      raiseInvalid("Operator name must be a symbol")
    let n = nv.symVal
    when not defined(mini):
      if not n.match(USER_SYMBOL_REGEX):
        raiseInvalid("Operator name must not contain ivalid characters")
    # Validate signature
    let sv = q.qVal[2]
    if not sv.isQuotation:
      raiseInvalid("Signature must be a quotation")
    elif sv.qVal.len == 0:
      raiseInvalid("No signature specified")
    elif sv.qVal.len == 1 and sv.qVal[0] != "==>".newVal:
      raiseInvalid("Invalid signature")
    elif sv.qVal.len mod 2 == 0:
      raiseInvalid("Invalid signature")
    var c = 0
    # Process signature
    var inExpects= newSeq[string](0)
    var inVars = newSeq[string](0)
    var outExpects= newSeq[string](0)
    var outVars = newSeq[string](0)
    var o= false
    for vv in sv.qVal:
      if not vv.isSymbol:
        raiseInvalid("Signature must be a quotation id symbols")
      let v = vv.symVal
      var check = c mod 2 == 0
      if o:
        check = c mod 2 != 0
      if check:
        if v == "==>":
          o = true
        elif not validType(v):
          raiseInvalid("Invalid type specified in signature at position $#" % $(c+1))
        else:
          if o:
            outExpects.add v
          else:
            inExpects.add v
      else:
        if v[0] != ':':
          raiseInvalid("No mapping symbol specified in signature at position $#" % $(c+1))
        else:
          if o:
            outVars.add v[1..v.len-1]
          else:
            inVars.add v[1..v.len-1]
      c.inc()
    if not o:
      raiseInvalid("No output specified in signature")
    # Process body
    var bv = q.qVal[3]
    if not bv.isQuotation:
      raiseInvalid("Body must be a quotation")
    inExpects.reverse
    inVars.reverse
    var p: MinOperatorProc = proc (i: In) =
      var inVals = i.expect(inExpects)
      i.withScope():
        # Inject variables for mapped inputs
        for k in 0..inVars.len-1:
          i.scope.symbols[inVars[k]] = MinOperator(kind: minValOp, sealed: false, val: inVals[k], quotation: inVals[k].isQuotation)
        # Inject variables for mapped outputs
        for k in 0..outVars.len-1:
          i.scope.symbols[outVars[k]] = MinOperator(kind: minValOp, sealed: false, val: newNull(), quotation: false)
        # Actually execute the body of the operator
        var endSnapshot: seq[MinValue]
        var snapShot: seq[MinValue]
        try:
          snapshot = deepCopy(i.stack)
          i.dequote bv
          endSnapshot = i.stack
          if endSnapshot != snapshot:
            raiseInvalid("Operator '$#' is polluting the stack" % n)
        except MinReturnException:
          discard
        # Validate output
        for k in 0..outVars.len-1:
          i.push outVars[k].newSym
          let x = i.peek
          let o = outExpects[k]
          var r = false;
          if o.contains("|"):
            let types = o.split("|")
            for ut in types:
              if validate(x, ut):
                r = true
                break
          else:
            r = validate(x, o)
          if not r:
            discard i.pop
            raiseInvalid("Invalid value for output symbol '$#'. Expected $#, found $#" % [outVars[k], o, $x])
    # Define symbol/sigil
    if t == "symbol":
      if i.scope.symbols.hasKey(n) and i.scope.symbols[n].sealed:
        raiseUndefined("Attempting to redefine sealed symbol '$1'" % [n])
      i.scope.symbols[n] = MinOperator(kind: minProcOp, prc: p, sealed: false)
    else:
      if i.scope.sigils.hasKey(n) and i.scope.sigils[n].sealed:
        raiseUndefined("Attempting to redefine sealed sigil '$1'" % [n])
      i.scope.sigils[n] = MinOperator(kind: minProcOp, prc: p, sealed: true)

  def.symbol("expect-empty-stack") do (i: In):
    let l = i.stack.len
    if l != 0:
      raiseInvalid("Expected empty stack, found $# elements instead" % $l)

  def.symbol("exit") do (i: In):
    let vals = i.expect("int")
    quit(vals[0].intVal.int)

  def.symbol("puts") do (i: In):
    let a = i.peek
    echo $$a
  
  def.symbol("puts!") do (i: In):
    echo $$i.pop

  def.symbol("gets") do (i: In) {.gcsafe.}:
    when defined(mini):
      i.push readLineFromStdin("").newVal 
    else:
      var ed = initEditor()
      i.push ed.readLine().newVal
    
  def.symbol("apply") do (i: In):
    let vals = i.expect("quot|dict")
    var prog = vals[0]
    if prog.kind == minQuotation:
      i.apply prog
    else:
      i.push i.applyDict(prog)

  def.symbol("symbols") do (i: In):
    var q = newSeq[MinValue](0)
    var scope = i.scope
    while not scope.isNil:
      for s in scope.symbols.keys:
        q.add s.newVal
      scope = scope.parent
    i.push q.newVal

  def.symbol("defined?") do (i: In):
    let vals = i.expect("'sym")
    i.push(i.scope.hasSymbol(vals[0].getString).newVal)

  def.symbol("defined-sigil?") do (i: In):
    let vals = i.expect("'sym")
    i.push(i.scope.hasSigil(vals[0].getString).newVal)
  
  def.symbol("sigils") do (i: In):
    var q = newSeq[MinValue](0)
    var scope = i.scope
    while not scope.isNil:
      for s in scope.sigils.keys:
        q.add s.newVal
      scope = scope.parent
    i.push q.newVal

  def.symbol("scope-symbols") do (i: In):
    let vals = i.expect("dict")
    let m = vals[0]
    var q = newSeq[MinValue](0)
    for s in m.scope.symbols.keys:
      q.add s.newVal
    i.push q.newVal

  def.symbol("scope-sigils") do (i: In):
    let vals = i.expect("dict")
    let m = vals[0]
    var q = newSeq[MinValue](0)
    for s in m.scope.sigils.keys:
      q.add s.newVal
    i.push q.newVal

  def.symbol("lite?") do (i: In):
    i.push defined(lite).newVal

  def.symbol("mini?") do (i: In):
    i.push defined(mini).newVal

  def.symbol("from-yaml") do (i: In):
    let vals = i.expect("string")
    let s = vals[0]
    try:
      var dict = newDict(i.scope)
      let lines = s.strVal.split("\n")
      for line in lines:
        let pair = line.split(":")
        if pair.len == 1 and pair[0].len == 0:
          continue
        i.dset(dict, pair[0].strip, pair[1].strip.newVal)
        i.push(dict)
    except:
      raiseInvalid("Invalid/unsupported YAML object (only dictionaries with string values are supported)")

  def.symbol("to-yaml") do (i: In):
    let vals = i.expect "a"
    let a = vals[0]
    let err = "YAML conversion is only supported from dictionaries with string values"
    if a.kind != minDictionary:
      raiseInvalid(err)
    var yaml = ""
    try:
      for key in i.keys(a).qVal:
        let value = i.dget(a, key)
        if value.kind != minString:
          raiseInvalid(err)
        yaml &= "$1: $2\n" % [key.strVal, value.strVal]
      i.push(yaml.strip.newVal)
    except:
      raiseInvalid(err)

  def.symbol("loglevel") do (i: In):
    let vals = i.expect("'sym")
    let s = vals[0]
    var str = s.getString
    when defined(mini):
      echo "Log level: ", minilogger.setLogLevel(str)
    else:
      echo "Log level: ", niftylogger.setLogLevel(str)

  def.symbol("loglevel?") do (i: In):
    when defined(mini):
      i.push minilogger.getLogLevel().newVal
    else:
      i.push niftylogger.getLogLevel().newVal

  # Language constructs

  def.symbol("define") do (i: In):
    let vals = i.expect("'sym", "a")
    let sym = vals[0]
    var q1 = vals[1] # existing (auto-quoted)
    var symbol: string
    var isQuot = true
    if not q1.isQuotation:
      q1 = @[q1].newVal
      isQuot = false
    symbol = sym.getString
    when not defined(mini):
      if not symbol.match USER_SYMBOL_REGEX:
        raiseInvalid("Symbol identifier '$1' contains invalid characters." % symbol)
    info "[define] $1 = $2" % [symbol, $q1]
    if i.scope.symbols.hasKey(symbol) and i.scope.symbols[symbol].sealed:
      raiseUndefined("Attempting to redefine sealed symbol '$1'" % [symbol])
    i.scope.symbols[symbol] = MinOperator(kind: minValOp, val: q1, sealed: false, quotation: isQuot)
    
  def.symbol("define-sigil") do (i: In):
    let vals = i.expect("'sym", "a")
    let sym = vals[0]
    var q1 = vals[1] # existing (auto-quoted)
    var sigil: string
    var isQuot = true
    if not q1.isQuotation:
      q1 = @[q1].newVal
      isQuot = false
    sigil = sym.getString
    when not defined(mini):
      if not sigil.match USER_SYMBOL_REGEX:
        raiseInvalid("Sigil identifier '$1' contains invalid characters." % sigil)
    info "[sigil] $1 = $2" % [sigil, $q1]
    if i.scope.sigils.hasKey(sigil) and i.scope.sigils[sigil].sealed:
      raiseUndefined("Attempting to redefine sealed sigil '$1'" % [sigil])
    i.scope.sigils[sigil] = MinOperator(kind: minValOp, val: q1, sealed: true, quotation: isQuot)

  def.symbol("bind") do (i: In):
    let vals = i.expect("'sym", "a")
    let sym = vals[0]
    var q1 = vals[1] # existing (auto-quoted)
    var symbol: string
    var isQuot = true
    if not q1.isQuotation:
      q1 = @[q1].newVal
      isQuot = false
    symbol = sym.getString
    info "[bind] $1 = $2" % [symbol, $q1]
    let res = i.scope.setSymbol(symbol, MinOperator(kind: minValOp, val: q1, quotation: isQuot))
    if not res:
      raiseUndefined("Attempting to bind undefined symbol: " & symbol)

  def.symbol("delete") do (i: In):
    let vals = i.expect("'sym")
    let sym = vals[0]
    let res = i.scope.delSymbol(sym.getString) 
    if not res:
      raiseUndefined("Attempting to delete undefined symbol: " & sym.getString)
      
  def.symbol("delete-sigil") do (i: In):
    let vals = i.expect("'sym")
    let sym = vals[0]
    let res = i.scope.delSigil(sym.getString) 
    if not res:
      raiseUndefined("Attempting to delete undefined sigil: " & sym.getString)

  def.symbol("module") do (i: In):
    let vals = i.expect("'sym", "dict")
    let name = vals[0]
    var code = vals[1]
    code.objType = "module"
    code.filename = i.filename
    info("[module] $1 ($2 symbols)" % [name.getString, $code.scope.symbols.len])
    i.scope.symbols[name.getString] = MinOperator(kind: minValOp, val: code)

  def.symbol("scope") do (i: In):
    var dict = newDict(i.scope.parent)
    dict.objType = "module"
    dict.filename = i.filename
    dict.scope = i.scope
    i.push dict

  def.symbol("type") do (i: In):
    let vals = i.expect("a")
    i.push vals[0].typeName.newVal

  def.symbol("import") do (i: In):
    var vals = i.expect("'sym")
    let rawName = vals[0]
    var name: string
    name = rawName.getString
    var op = i.scope.getSymbol(name)
    i.apply(op)
    vals = i.expect("dict:module")
    let mdl = vals[0]
    info("[import] Importing: $1 ($2 symbols, $3 sigils)" % [name, $mdl.scope.symbols.len, $mdl.scope.sigils.len])
    for sym, val in mdl.scope.symbols.pairs:
      if i.scope.symbols.hasKey(sym) and i.scope.symbols[sym].sealed:
        raiseUndefined("Attempting to redefine sealed symbol '$1'" % [sym])
      i.debug "[import] $1" % [sym]
      i.scope.symbols[sym] = val
    for sig, val in mdl.scope.sigils.pairs:
      if i.scope.sigils.hasKey(sig) and i.scope.sigils[sig].sealed:
        raiseUndefined("Attempting to redefine sealed sigil '$1'" % [sig])
      i.debug "[import] $1" % [sig]
      i.scope.sigils[sig] = val
  
  def.symbol("eval") do (i: In):
    let vals = i.expect("string")
    let s = vals[0]
    i.eval s.strVal
    
  def.symbol("quit") do (i: In):
    i.push 0.newVal
    i.push "exit".newSym

  def.symbol("parse") do (i: In):
    let vals = i.expect("string")
    let s = vals[0]
    i.push i.parse s.strVal

  def.symbol("source") do (i: In):
    let vals = i.expect("'sym")
    let s = vals[0]
    let str = s.getString
    let sym = i.scope.getSymbol(str)
    if sym.kind == minValOp:
      i.push sym.val
    else:
      raiseInvalid("No source available for native symbol '$1'." % str)

  def.symbol("call") do (i: In):
    let vals = i.expect("'sym", "dict")
    let symbol = vals[0]
    let q = vals[1]
    let s = symbol.getString
    let origScope = i.scope
    i.scope = q.scope
    i.scope.parent = origScope
    let sym = i.scope.getSymbol(s)
    i.apply(sym)
    i.scope = origScope

  def.symbol("invoke") do (i: In):
    let vals = i.expect("'sym")
    let s = vals[0].getString
    let parts = s.split("/")
    if parts.len < 2:
      raiseInvalid("Dictionary identifier not specified")
    i.push parts[0].newSym
    for p in 0..parts.len-2:
      let vals = i.expect("dict")
      let mdl = vals[0]
      let symId = parts[p+1] 
      var q = newSeq[MinValue](0)
      q.add symId.newSym
      i.push q.newVal
      i.push mdl
      i.push "with".newSym

  def.symbol("set-type") do (i: In):
    let vals = i.expect("'sym", "dict")
    let symbol = vals[0]
    var d = vals[1]
    d.objType = symbol.getString
    i.push d

  def.symbol("raise") do (i: In):
    let vals = i.expect("dict")
    let err = vals[0]
    if err.dhas("error".newVal) and err.dhas("message".newVal):
      raiseRuntime("($1) $2" % [i.dget(err, "error".newVal).getString, i.dget(err, "message").getString], err)
    else:
      raiseInvalid("Invalid error dictionary")

  def.symbol("format-error") do (i: In):
    let vals = i.expect("dict:error")
    let err = vals[0]
    if err.dhas("error".newVal) and err.dhas("message".newVal):
      var msg: string
      var list = newSeq[MinValue]()
      list.add i.dget(err, "message")
      if err.dhas("symbol"):
        list.add i.dget(err, "symbol")
      if err.dhas("filename"):
        list.add i.dget(err, "filename")
      if err.dhas("line"):
        list.add i.dget(err, "line")
      if err.dhas("column"):
        list.add i.dget(err, "column")
      if list.len <= 3:
        msg = "$1" % $$list[0]
      else:
        msg = "$3($4,$5) `$2`: $1" % [$$list[0], $$list[1], $$list[2], $$list[3], $$list[4]]
      i.push msg.newVal
    else:
      raiseInvalid("Invalid error dictionary")

  def.symbol("try") do (i: In):
    let vals = i.expect("quot")
    let prog = vals[0]
    if prog.qVal.len == 0:
      raiseInvalid("Quotation must contain at least one element")
    var code = prog.qVal[0]
    var final, catch: MinValue
    var hasFinally = false
    var hasCatch = false
    if prog.qVal.len > 1:
      catch = prog.qVal[1]
      hasCatch = true
    if prog.qVal.len > 2:
      final = prog.qVal[2]
      hasFinally = true
    if (not code.isQuotation) or (hasCatch and not catch.isQuotation) or (hasFinally and not final.isQuotation):
      raiseInvalid("Quotation must contain at least one quotation")
    try:
      i.dequote(code)
    except MinRuntimeError:
      if not hasCatch:
        return
      let e = (MinRuntimeError)getCurrentException()
      i.push e.data
      i.dequote(catch)
    except:
      if not hasCatch:
        return
      let e = getCurrentException()
      var res = newDict(i.scope)
      var err = $e.name
      let col = err.find(":")
      if col >= 0:
        err = err[0..col-1]
      res.objType = "error"
      i.dset(res, "error", err.newVal)
      i.dset(res, "message", e.msg.newVal)
      if i.currSym.getString != "": # TODO investigate when this happens
        i.dset(res, "symbol", i.currSym)
        i.dset(res, "filename", i.currSym.filename.newVal)
      i.dset(res, "line", i.currSym.line.newVal)
      i.dset(res, "column", i.currSym.column.newVal)
      i.push res
      i.dequote(catch)
    finally:
      if hasFinally:
        i.dequote(final)

  def.symbol("quote") do (i: In):
    let vals = i.expect("a")
    let a = vals[0]
    i.push @[a].newVal
  
  def.symbol("dequote") do (i: In):
    let vals = i.expect("quot")
    var q = vals[0]
    i.dequote(q)

  def.symbol("tap") do (i: In):
    let vals = i.expect("quot", "a")
    let programs = vals[0]
    var a = vals[1]
    for program in programs.qVal:
      var p = program
      i.push(a)
      i.dequote(p)
      a = i.pop
    i.push(a)

  def.symbol("tap!") do (i: In):
    let vals = i.expect("quot", "a")
    let programs = vals[0]
    var a = vals[1]
    for program in programs.qVal:
      var p = program
      i.push(a)
      i.dequote(p)
      a = i.pop
  
  # Conditionals

  def.symbol("if") do (i: In):
    let vals = i.expect("quot", "quot", "quot")
    var fpath = vals[0]
    var tpath = vals[1]
    var check = vals[2]
    var stack = i.stack
    i.dequote(check)
    let res = i.pop
    i.stack = stack
    if not res.isBool:
      raiseInvalid("Result of check is not a boolean value")
    if res.boolVal == true:
      i.dequote(tpath)
    else:
      i.dequote(fpath)

  def.symbol("when") do (i: In):
    let vals = i.expect("quot", "quot")
    var tpath = vals[0]
    var check = vals[1]
    var stack = i.stack
    i.dequote(check)
    let res = i.pop
    i.stack = stack
    if not res.isBool:
      raiseInvalid("Result of check is not a boolean value")
    if res.boolVal == true:
      i.dequote(tpath)

  def.symbol("unless") do (i: In):
    let vals = i.expect("quot", "quot")
    var tpath = vals[0]
    var check = vals[1]
    var stack = i.stack
    i.dequote(check)
    let res = i.pop
    i.stack = stack
    if not res.isBool:
      raiseInvalid("Result of check is not a boolean value")
    if res.boolVal == false:
      i.dequote(tpath)

  # 4 (
  #   ((> 3) ("Greater than 3" put!))
  #   ((< 3) ("Smaller than 3" put!))
  #   ((true) ("Exactly 3" put!))
  # ) case
  def.symbol("case") do (i: In):
    let vals = i.expect("quot")
    var cases = vals[0]
    if cases.qVal.len == 0:
      raiseInvalid("Empty case operator")
    var k = 0
    let stack = i.stack
    for c in cases.qVal:
      i.stack = stack
      if not c.isQuotation:
        raiseInvalid("A quotation of quotations is required")
      k.inc
      if c.qVal.len != 2 or not c.qVal[0].isQuotation or not c.qVal[1].isQuotation:
        raiseInvalid("Inner quotations in case operator must contain two quotations")
      var q = c.qVal[0]
      i.dequote(q)
      let res = i.pop
      if not res.isBool():
        raiseInvalid("Result of case #$1 is not a boolean value" % $k)
      if res.boolVal == true:
        var t = c.qVal[1]
        i.dequote(t)
        break

  # Loops

  def.symbol("foreach") do (i: In):
    let vals = i.expect("quot", "quot")
    var prog = vals[0]
    var list = vals[1]
    for litem in list.qVal:
      i.push litem
      i.dequote(prog)
  
  def.symbol("times") do (i: In):
    let vals = i.expect("int", "quot")
    var t = vals[0]
    var prog = vals[1]
    if t.intVal < 1:
      raiseInvalid("A non-zero natural number is required")
    for c in 1..t.intVal:
      i.dequote(prog)
  
  def.symbol("while") do (i: In):
    let vals = i.expect("quot", "quot")
    var d = vals[0]
    var b = vals[1]
    for e in b.qVal:
      i.push e
    i.dequote(b)
    var check = i.pop
    while check.isBool and check.boolVal == true:
      i.dequote(d)
      i.dequote(b)
      check = i.pop
    discard i.pop

  # Other
  
  def.symbol("linrec") do (i: In):
    let vals = i.expect("quot", "quot", "quot", "quot")
    var r2 = vals[0]
    var r1 = vals[1]
    var t = vals[2]
    var p = vals[3]
    proc linrec(i: In, p, t, r1, r2: var MinValue) =
      i.dequote(p)
      var check = i.pop
      if check.isBool and check.boolVal == true:
        i.dequote(t)
      else:
        i.dequote(r1)
        i.linrec(p, t, r1, r2)
        i.dequote(r2)
    i.linrec(p, t, r1, r2)

  def.symbol("version") do (i: In):
    i.push pkgVersion.newVal

  def.symbol("seal") do (i: In):
    let vals = i.expect("'sym")
    let sym = vals[0].getString
    var s = i.scope.getSymbol(sym) 
    s.sealed = true
    i.scope.setSymbol(sym, s)
    
  def.symbol("seal-sigil") do (i: In):
    let vals = i.expect("'sym")
    let sym = vals[0].getString
    var s = i.scope.getSigil(sym) 
    s.sealed = true
    i.scope.setSigil(sym, s)

  def.symbol("unseal") do (i: In):
    let vals = i.expect("'sym")
    let sym = vals[0].getString
    var s = i.scope.getSymbol(sym) 
    s.sealed = false
    i.scope.setSymbol(sym, s, true)
  
  def.symbol("unseal-sigil") do (i: In):
    let vals = i.expect("'sym")
    let sym = vals[0].getString
    var s = i.scope.getSigil(sym) 
    when not defined(mini):
      if not sym.match USER_SYMBOL_REGEX:
        # Prevent accidentally unsealing system sigils
        # Not that they can redefined, but still
        raiseInvalid("Attempting to unseal system sigil: " & sym)
    s.sealed = false
    i.scope.setSigil(sym, s, true)
  
  def.symbol("quote-bind") do (i: In):
    let vals = i.expect("string", "a")
    let s = vals[0]
    let m = vals[1]
    i.push @[m].newVal
    i.push s
    i.push "bind".newSym

  def.symbol("quote-define") do (i: In):
    let vals = i.expect("string", "a")
    let s = vals[0]
    let m = vals[1]
    i.push @[m].newVal
    i.push s
    i.push "define".newSym


  def.symbol("args") do (i: In):
    var args = newSeq[MinValue](0)
    for kind, key, val in getopt():
      case kind:
        of cmdArgument:
          args.add key.newVal
        else:
          discard
    i.push args.newVal

  def.symbol("opts") do (i: In):
    var opts = newDict(i.scope) 
    for kind, key, val in getopt():
      case kind:
        of cmdLongOption, cmdShortOption:
          if val == "":
            opts = i.dset(opts, key.newVal, true.newVal)
          else:
            opts = i.dset(opts, key.newVal, val.newVal)
        else:
          discard
    i.push opts

  def.symbol("expect") do (i: In):
    var q: MinValue
    i.reqQuotationOfSymbols q
    i.push(i.expect(q.qVal.mapIt(it.getString())).reversed.newVal)
    
  def.symbol("reverse-expect-dequote") do (i: In):
    var q: MinValue
    i.reqQuotationOfSymbols q
    var req = i.expect(q.qVal.reversed.mapIt(it.getString())).newVal
    i.dequote(req)
  
  def.symbol("infix-dequote") do (i: In):
    let vals = i.expect("quot")
    let q = vals[0]
    proc infix(i: In, q: MinValue): MinValue =
      var ops = newSeq[MinValue](0)
      var res = newSeq[MinValue](0).newVal
      for x in q.qVal:
        if x.isSymbol:
          ops.add x
        else:
          if x.isQuotation:
            res.qVal.add i.infix(x)
          else:
            res.qVal.add x
          if ops.len > 0:
            res.qVal.add ops.pop
            i.dequote(res)
            res = newSeq[MinValue](0).newVal
      return i.pop
    i.push i.infix(q)
    
  def.symbol("prefix-dequote") do (i: In):
    let vals = i.expect("quot")
    var q = vals[0]
    q.qVal.reverse
    i.dequote(q)

  def.symbol("compiled?") do (i: In):
    i.push MINCOMPILED.newVal

  # Converters

  def.symbol("string") do (i: In):
    let s = i.pop
    i.push(($$s).newVal)

  def.symbol("bool") do (i: In):
    let v = i.pop
    let strcheck = (v.isString and (v.getString == "false" or v.getString == ""))
    let intcheck = v.isInt and v.intVal == 0
    let floatcheck = v.isFloat and v.floatVal == 0
    let boolcheck = v.isBool and v.boolVal == false
    let quotcheck = v.isQuotation and v.qVal.len == 0
    if v.isNull or strcheck or intcheck or floatcheck or boolcheck or quotcheck:
      i.push false.newVal
    else:
      i.push true.newVal

  def.symbol("int") do (i: In):
    let s = i.pop
    if s.isString:
      i.push s.getString.parseInt.newVal
    elif s.isNull:
      i.push 0.int.newVal
    elif s.isFloat:
      i.push s.floatVal.int.newVal
    elif s.isInt:
      i.push s
    elif s.isBool:
      if s.boolVal == true:
        i.push 1.int.newVal
      else:
        i.push 0.int.newVal
    else:
      raiseInvalid("Cannot convert a quotation to an integer.")

  def.symbol("float") do (i: In):
    let s = i.pop
    if s.isString:
      i.push s.getString.parseFloat.newVal
    elif s.isNull:
      i.push 0.int.newVal
    elif s.isInt:
      i.push s.intVal.float.newVal
    elif s.isFloat:
      i.push s
    elif s.isBool:
      if s.boolVal == true:
        i.push 1.float.newVal
      else:
        i.push 0.float.newVal
    else:
      raiseInvalid("Cannot convert a quotation to float.")

  def.symbol("prompt") do (i: In):
    when defined(mini):
      i.push "$ ".newVal
    else:
      i.eval(""""[$1]\n$$ " (.) => %""")

  # Sigils

  def.sigil("'") do (i: In):
    let vals = i.expect("string")
    let s = vals[0]
    i.push(@[s.strVal.newSym].newVal)

  def.sigil(":") do (i: In):
    i.push("define".newSym)

  def.sigil("~") do (i: In):
    i.push("delete".newSym)

  def.sigil("@") do (i: In):
    i.push("bind".newSym)

  def.sigil("+") do (i: In):
    i.push("module".newSym)

  def.sigil("^") do (i: In):
    i.push("call".newSym)

  def.sigil("*") do (i: In):
    i.push("invoke".newSym)

  def.sigil(">") do (i: In):
    i.push("save-symbol".newSym)

  def.sigil("<") do (i: In):
    i.push("load-symbol".newSym)

  def.sigil("#") do (i: In):
    i.push("quote-bind".newSym)

  def.sigil("=") do (i: In):
    i.push("quote-define".newSym)

  # Shorthand symbol aliases

  def.symbol("#") do (i: In):
    i.push("quote-bind".newSym)

  def.symbol("=") do (i: In):
    i.push("quote-define".newSym)
    
  def.symbol("=-=") do (i: In):
    i.push("expect-empty-stack".newSym)

  def.symbol(":") do (i: In):
    i.push("define".newSym)

  def.symbol("@") do (i: In):
    i.push("bind".newSym)

  def.symbol("^") do (i: In):
    i.push("call".newSym)

  def.symbol("'") do (i: In):
    i.push("quote".newSym)

  def.symbol("->") do (i: In):
    i.push("dequote".newSym)
    
  def.symbol("--") do (i: In):
    i.push("reverse-expect-dequote".newSym)

  def.symbol("::") do (i: In):
    i.push("operator".newSym)
    
  def.symbol("=>") do (i: In):
    i.push("apply".newSym)
    
  def.symbol("==>") do (i: In):
    discard # used within operator defs
    
  def.symbol("return") do (i: In):
    discard # used within operator defs
    
  def.symbol(">>") do (i: In):
    i.push("prefix-dequote".newSym)
    
  def.symbol("><") do (i: In):
    i.push("infix-dequote".newSym)

  def.finalize("ROOT")