all repos — min @ d0d644faeeecdd1812927dbd61b3061ab3e81187

A small but practical concatenative programming language.

minpkg/core/parser.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
 1094
 1095
 1096
 1097
 1098
 1099
 1100
 1101
 1102
 1103
 1104
 1105
 1106
 1107
 1108
 1109
 1110
 1111
 1112
 1113
 1114
 1115
 1116
 1117
 1118
 1119
 1120
 1121
 1122
 1123
 1124
 1125
 1126
 1127
 1128
 1129
 1130
 1131
 1132
 1133
 1134
 1135
 1136
 1137
 1138
 1139
 1140
 1141
 1142
 1143
 1144
 1145
 1146
 1147
 1148
 1149
 1150
 1151
 1152
 1153
 1154
 1155
 1156
 1157
 1158
 1159
 1160
 1161
 1162
 1163
 1164
 1165
 1166
 1167
 1168
 1169
 1170
 1171
 1172
 1173
 1174
 1175
# Adapted from: https://github.com/Araq/Nimrod/blob/v0.9.6/lib/pure/json.nim
import
  std/[lexbase,
  strutils,
  sequtils,
  streams,
  critbits,
  logging,
  json]

import
  baseutils

import std/unicode except strip

type
  MinTokenKind* = enum
    tkError,
    tkEof,
    tkString,
    tkCommand,
    tkInt,
    tkFloat,
    tkBracketLe,
    tkBracketRi,
    tkSqBracketLe,
    tkSqBracketRi,
    tkBraceLe,
    tkBraceRi,
    tkSymbol,
    tkNull,
    tkTrue,
    tkFalse,
    tkLineComment,
    tkBlockComment,
    tkLineDocComment,
    tkBlockDocComment,
    tkSpace
  MinKind* = enum
    minInt,
    minFloat,
    minQuotation,
    minCommand,
    minDictionary,
    minString,
    minSymbol,
    minNull,
    minBool
  MinEventKind* = enum   ## enumeration of all events that may occur when parsing
    eMinError,           ## an error ocurred during parsing
    eMinEof,             ## end of file reached
    eMinString,          ## a string literal
    eMinInt,             ## an integer literal
    eMinFloat,           ## a float literal
    eMinQuotationStart,  ## start of an array: the ``(`` token
    eMinQuotationEnd,    ## start of an array: the ``)`` token
    eMinDictionaryStart, ## start of a dictionary: the ``{`` token
    eMinDictionaryEnd    ## start of a dictionary: the ``}`` token
  MinParserError* = enum    ## enumeration that lists all errors that can occur
    errNone,                ## no error
    errInvalidToken,        ## invalid token
    errStringExpected,      ## string expected
    errBracketRiExpected,   ## ``)`` expected
    errBraceRiExpected,     ## ``}`` expected
    errQuoteExpected,       ## ``"`` or ``'`` expected
    errSqBracketRiExpected, ## ``]`` expected
    errEOC_Expected,        ## ``*/`` expected
    errEofExpected,         ## EOF expected
    errExprExpected
  MinParser* = object of BaseLexer
    a*: string
    doc*: bool
    currSym*: MinValue
    token*: MinTokenKind
    kind*: MinEventKind
    err*: MinParserError
    filename*: string
  MinValue* = ref MinValueObject
  MinValueObject* {.acyclic, final.} = object
    line*: int
    column*: int
    filename*: string
    outerSym*: string
    docComment*: string
    case kind*: MinKind
      of minNull: discard
      of minInt: intVal*: BiggestInt
      of minFloat: floatVal*: BiggestFloat
      of minCommand: cmdVal*: string
      of minDictionary:
        scope*: ref MinScope
        obj*: pointer
        objType*: string
      of minQuotation:
        qVal*: seq[MinValue]
      of minString: strVal*: string
      of minSymbol: symVal*: string
      of minBool: boolVal*: bool
  MinScopeKind* = enum
    minNativeScope,
    minLangScope
  MinScope* {.acyclic, shallow, final.} = object
    parent*: ref MinScope
    symbols*: CritBitTree[MinOperator]
    sigils*: CritBitTree[MinOperator]
    kind*: MinScopeKind
  MinOperatorProc* = proc (i: In) {.closure.}
  MinOperatorKind* = enum
    minProcOp
    minValOp
  MinOperator* = object
    sealed*: bool
    doc*: JsonNode
    mdl*: MinValue # Only set in case of modules
    case kind*: MinOperatorKind
    of minProcOp:
      prc*: MinOperatorProc
    of minValOp:
      quotation*: bool
      val*: MinValue
  MinStack* = seq[MinValue]
  In* = var MinInterpreter
  MinInterpreter* = object
    stack*: MinStack
    trace*: MinStack
    stackcopy*: MinStack
    pwd*: string
    scope*: ref MinScope
    parser*: MinParser
    currSym*: MinValue
    filename*: string
    evaluating*: bool
  MinParsingError* = ref object of ValueError
  MinUndefinedError* = ref object of ValueError
  MinEmptyStackError* = ref object of ValueError
  MinInvalidError* = ref object of ValueError
  MinOutOfBoundsError* = ref object of ValueError
  MinNumBase* = enum
    baseDec = "dec"
    baseOct = "oct"
    baseBin = "bin"
    baseHex = "hex"

var CVARCOUNT = 0
var NUMBASE*: MinNumBase = baseDec

# Helpers

proc raiseInvalid*(msg: string) =
  raise MinInvalidError(msg: msg)

proc raiseUndefined*(msg: string) =
  raise MinUndefinedError(msg: msg)

proc raiseOutOfBounds*(msg: string) =
  raise MinOutOfBoundsError(msg: msg)

proc raiseEmptyStack*() =
  raise MinEmptyStackError(msg: "Insufficient items on the stack")

proc dVal*(v: MinValue): CritBitTree[MinOperator] {.inline.} =
  if v.kind != minDictionary:
    raiseInvalid("dVal - Dictionary expected, got " & $v.kind)
  if v.scope.isNil:
    return CritBitTree[MinOperator]()
  return v.scope.symbols

const
  errorMessages: array[MinParserError, string] = [
    "no error",
    "invalid token",
    "string expected",
    "')' expected",
    "'}' expected",
    "'\"' expected",
    "']' expected",
    "'*/' expected",
    "EOF expected",
    "expression expected"
  ]
  tokToStr: array[MinTokenKind, string] = [
    "invalid token",
    "EOF",
    "string literal",
    "command literal",
    "int literal",
    "float literal",
    "(",
    ")",
    "[",
    "]",
    "{",
    "}",
    "symbol",
    "null",
    "true",
    "false",
    "line comment",
    "block comment",
    "line documentation comment",
    "block documentation comment",
    "space"
  ]

proc newScope*(parent: ref MinScope, kind = minLangScope): MinScope =
  result = MinScope(parent: parent, kind: kind)

proc newScopeRef*(parent: ref MinScope, kind = minLangScope): ref MinScope =
  new(result)
  result[] = newScope(parent, kind)

proc open*(my: var MinParser, input: Stream, filename: string) =
  lexbase.open(my, input)
  my.filename = filename
  my.kind = eMinError
  my.a = ""

proc close*(my: var MinParser) {.inline.} =
  lexbase.close(my)

proc getInt*(my: MinParser): int {.inline.} =
  assert(my.kind == eMinInt)
  return parseint(my.a)

proc getFloat*(my: MinParser): float {.inline.} =
  assert(my.kind == eMinFloat)
  return parseFloat(my.a)

proc kind*(my: MinParser): MinEventKind {.inline.} =
  return my.kind

proc getColumn*(my: MinParser): int {.inline.} =
  result = getColNumber(my, my.bufpos)

proc getLine*(my: MinParser): int {.inline.} =
  result = my.lineNumber

proc getFilename*(my: MinParser): string {.inline.} =
  result = my.filename

proc errorMsg*(my: MinParser, msg: string): string =
  assert(my.kind == eMinError)
  result = "$1 [l:$2, c:$3] ERROR - $4" % [
    my.filename, $getLine(my), $getColumn(my), msg]

proc errorMsg*(my: MinParser): string =
  assert(my.kind == eMinError)
  result = errorMsg(my, errorMessages[my.err])

proc errorMsgExpected*(my: MinParser, e: string): string =
  result = errorMsg(my, e & " expected")

proc raiseParsing*(p: MinParser, msg: string) {.noinline, noreturn.} =
  raise MinParsingError(msg: errorMsgExpected(p, msg))

proc raiseUndefined*(p: MinParser, msg: string) {.noinline, noreturn,
    extern: "min_exported_symbol_$1_2".} =
  raise MinUndefinedError(msg: errorMsg(p, msg))

proc parseNumber(my: var MinParser) =
  var pos = my.bufpos
  var buf = my.buf
  var base = 'd'
  if buf[pos] == '-':
    add(my.a, '-')
    inc(pos)
  if buf[pos] == '0':
    add(my.a, buf[pos])
    inc(pos)
    if buf[pos] in {'o', 'b', 'x'}:
      base = buf[pos]
      add(my.a, buf[pos])
      inc(pos)
      if base == 'b':
        while buf[pos] in {'0', '1'}:
          add(my.a, buf[pos])
          inc(pos)
      elif base == 'o':
        while buf[pos] in {'0', '1', '2', '3', '4', '5', '6', '7'}:
          add(my.a, buf[pos])
          inc(pos)
      elif base == 'x':
        while buf[pos] in HexDigits:
          add(my.a, buf[pos])
          inc(pos)
  if buf[pos] == '.':
    add(my.a, ".")
    inc(pos)
  else:
    while buf[pos] in Digits:
      add(my.a, buf[pos])
      inc(pos)
    if buf[pos] == '.':
      add(my.a, '.')
      inc(pos)
  # digits after the dot:
  while buf[pos] in Digits:
    add(my.a, buf[pos])
    inc(pos)
  if buf[pos] in {'E', 'e'}:
    add(my.a, buf[pos])
    inc(pos)
    if buf[pos] in {'+', '-'}:
      add(my.a, buf[pos])
      inc(pos)
    while buf[pos] in Digits:
      add(my.a, buf[pos])
      inc(pos)
  my.bufpos = pos

proc handleHexChar(c: char, x: var int): bool =
  result = true # Success
  case c
  of '0'..'9': x = (x shl 4) or (ord(c) - ord('0'))
  of 'a'..'f': x = (x shl 4) or (ord(c) - ord('a') + 10)
  of 'A'..'F': x = (x shl 4) or (ord(c) - ord('A') + 10)
  else: result = false # error

proc parseString(my: var MinParser): MinTokenKind =
  result = tkString
  var pos = my.bufpos + 1
  var buf = my.buf
  while true:
    case buf[pos]
    of '\0':
      my.err = errQuoteExpected
      result = tkError
      break
    of '"':
      inc(pos)
      break
    of '\\':
      case buf[pos+1]
      of '\\', '"', '\'', '/':
        add(my.a, buf[pos+1])
        inc(pos, 2)
      of 'b':
        add(my.a, '\b')
        inc(pos, 2)
      of 'f':
        add(my.a, '\f')
        inc(pos, 2)
      of 'n':
        add(my.a, '\L')
        inc(pos, 2)
      of 'r':
        add(my.a, '\C')
        inc(pos, 2)
      of 't':
        add(my.a, '\t')
        inc(pos, 2)
      of 'u':
        inc(pos, 2)
        var r: int
        if handleHexChar(buf[pos], r): inc(pos)
        if handleHexChar(buf[pos], r): inc(pos)
        if handleHexChar(buf[pos], r): inc(pos)
        if handleHexChar(buf[pos], r): inc(pos)
        add(my.a, toUTF8(Rune(r)))
      else:
        # don't bother with the error
        add(my.a, buf[pos])
        inc(pos)
    of '\c':
      pos = lexbase.handleCR(my, pos)
      buf = my.buf
      add(my.a, '\c')
    of '\L':
      pos = lexbase.handleLF(my, pos)
      buf = my.buf
      add(my.a, '\L')
    else:
      add(my.a, buf[pos])
      inc(pos)
  my.bufpos = pos # store back

proc parseCommand(my: var MinParser): MinTokenKind =
  result = tkCommand
  var pos = my.bufpos + 1
  var buf = my.buf
  while true:
    case buf[pos]
    of '\0':
      my.err = errSqBracketRiExpected
      result = tkError
      break
    of ']':
      inc(pos)
      break
    of '\\':
      case buf[pos+1]
      of '\\', '"', '\'', '/':
        add(my.a, buf[pos+1])
        inc(pos, 2)
      of 'b':
        add(my.a, '\b')
        inc(pos, 2)
      of 'f':
        add(my.a, '\f')
        inc(pos, 2)
      of 'n':
        add(my.a, '\L')
        inc(pos, 2)
      of 'r':
        add(my.a, '\C')
        inc(pos, 2)
      of 't':
        add(my.a, '\t')
        inc(pos, 2)
      of 'u':
        inc(pos, 2)
        var r: int
        if handleHexChar(buf[pos], r): inc(pos)
        if handleHexChar(buf[pos], r): inc(pos)
        if handleHexChar(buf[pos], r): inc(pos)
        if handleHexChar(buf[pos], r): inc(pos)
        add(my.a, toUTF8(Rune(r)))
      else:
        # don't bother with the error
        add(my.a, buf[pos])
        inc(pos)
    of '\c':
      pos = lexbase.handleCR(my, pos)
      buf = my.buf
      add(my.a, '\c')
    of '\L':
      pos = lexbase.handleLF(my, pos)
      buf = my.buf
      add(my.a, '\L')
    else:
      add(my.a, buf[pos])
      inc(pos)
  my.bufpos = pos # store back

proc parseSymbol(my: var MinParser): MinTokenKind =
  result = tkSymbol
  var pos = my.bufpos
  var buf = my.buf
  if not(buf[pos] in Whitespace):
    while not(buf[pos] in WhiteSpace) and not(buf[pos] in ['\0', ')', '(', '}',
        '{', '[', ']']):
      if buf[pos] == '"':
        add(my.a, buf[pos])
        my.bufpos = pos
        let r = parseString(my)
        if r == tkError:
          result = tkError
          return
        add(my.a, buf[pos])
        return
      else:
        add(my.a, buf[pos])
        inc(pos)
  my.bufpos = pos

proc addDoc(my: var MinParser, docComment: string, reset = true) =
  if my.doc and not my.currSym.isNil and my.currSym.kind == minSymbol:
    if reset:
      my.doc = false
    if my.currSym.docComment.len == 0 or my.currSym.docComment.len > 0 and
        my.currSym.docComment[my.currSym.docComment.len-1] == '\n':
      my.currSym.docComment &= docComment.strip(true, false)
    else:
      my.currSym.docComment &= docComment

proc getToken*(my: var MinParser): MinTokenKind =
  setLen(my.a, 0)
  case my.buf[my.bufpos]
  of ';':
    # skip line comment:
    if my.buf[my.bufpos+1] == ';':
      my.doc = true
      inc(my.bufpos, 1)
    inc(my.bufpos, 1)
    while true:
      case my.buf[my.bufpos]
      of '\0':
        break
      of '\c':
        add(my.a, my.buf[my.bufpos])
        my.bufpos = lexbase.handleCR(my, my.bufpos)
        if my.doc:
          result = tkLineDocComment
        else:
          result = tkLineComment
        my.addDoc "\n"
        break
      of '\L':
        add(my.a, my.buf[my.bufpos])
        my.bufpos = lexbase.handleLF(my, my.bufpos)
        if my.doc:
          result = tkLineDocComment
        else:
          result = tkLineComment
        my.addDoc "\n"
        break
      else:
        add(my.a, my.buf[my.bufpos])
        my.addDoc $my.buf[my.bufpos], false
        inc(my.bufpos)
  of '#':
    if my.buf[my.bufpos+1] == '|':
      inc(my.bufpos, 1)
      if my.buf[my.bufpos+1] == '|':
        inc(my.bufpos, 1)
        my.doc = true
      inc(my.bufpos, 1)
      while true:
        case my.buf[my.bufpos]
        of '\0':
          my.err = errEOC_Expected
          break
        of '\c':
          add(my.a, my.buf[my.bufpos])
          my.bufpos = lexbase.handleCR(my, my.bufpos)
          my.addDoc "\n", false
        of '\L':
          add(my.a, my.buf[my.bufpos])
          my.bufpos = lexbase.handleLF(my, my.bufpos)
          my.addDoc "\n", false
        of '|':
          inc(my.bufpos)
          if my.buf[my.bufpos] == '|':
            inc(my.bufpos)
          if my.buf[my.bufpos] == '#':
            inc(my.bufpos)
            break
          my.addDoc $my.buf[my.bufpos], false
        else:
          add(my.a, my.buf[my.bufpos])
          my.addDoc $my.buf[my.bufpos], false
          inc(my.bufpos)
      if my.doc:
        result = tkBlockDocComment
      else:
        result = tkBlockComment
    else:
      result = parseSymbol(my)
  of ' ', '\t', '\c', '\L':
    while true:
      case my.buf[my.bufpos]:
      of ' ', '\t':
        add(my.a, my.buf[my.bufpos])
        result = tkSpace
        inc(my.bufpos)
      of '\c':
        add(my.a, my.buf[my.bufpos])
        result = tkSpace
        my.bufpos = lexbase.handleCR(my, my.bufpos)
      of '\L':
        add(my.a, my.buf[my.bufpos])
        result = tkSpace
        my.bufpos = lexbase.handleLF(my, my.bufpos)
      else:
        break
  of '-', '.':
    if my.bufpos+1 <= my.buf.len and my.buf[my.bufpos+1] in '0'..'9':
      parseNumber(my)
      if {'.', 'e', 'E'} in my.a:
        result = tkFloat
      else:
        result = tkInt
    else:
      result = parseSymbol(my)
  of '0'..'9':
    parseNumber(my)
    if {'.', 'e', 'E'} in my.a:
      result = tkFloat
    else:
      result = tkInt
  of '"':
    result = parseString(my)
  of '(':
    add(my.a, my.buf[my.bufpos])
    inc(my.bufpos)
    result = tkBracketLe
  of ')':
    add(my.a, my.buf[my.bufpos])
    inc(my.bufpos)
    result = tkBracketRi
  of '[':
    result = parseCommand(my)
  of '{':
    add(my.a, my.buf[my.bufpos])
    inc(my.bufpos)
    result = tkBraceLe
  of '}':
    add(my.a, my.buf[my.bufpos])
    inc(my.bufpos)
    result = tkBraceRi
  of '\0':
    result = tkEof
  else:
    result = parseSymbol(my)
    case my.a
    of "null": result = tkNull
    of "true": result = tkTrue
    of "false": result = tkFalse
    else:
      discard
  my.token = result

proc eat(p: var MinParser, token: MinTokenKind) =
  if p.token == token: discard getToken(p)
  else: raiseParsing(p, tokToStr[token])

proc `$`*(a: MinValue): string {.inline.} =
  case a.kind:
    of minNull:
      return "null"
    of minBool:
      return $a.boolVal
    of minSymbol:
      return a.symVal
    of minString:
      return "\""&a.strVal.escapeJsonUnquoted&"\""
    of minInt:
      case NUMBASE
      of baseDec:
        return $a.intVal
      of baseOct:
        return "0o" & a.intVal.toOct(sizeof(a))
      of baseBin:
        return "0b" & a.intVal.toBin(sizeof(a))
      of baseHex:
        return "0x" & a.intVal.toHex(sizeof(a))
    of minFloat:
      return $a.floatVal
    of minQuotation:
      var q = "("
      for i in a.qVal:
        q = q & $i & " "
      q = q.strip & ")"
      return q
    of minDictionary:
      var d = "{"
      for i in a.dVal.pairs:
        var v = ""
        if i.val.kind == minProcOp:
          v = "<native>"
        else:
          v = $i.val.val
        var k = $i.key
        if k.contains(" "):
          k = "\"$1\"" % k
        d = d & v & " :" & k & " "
      if a.objType != "":
        d = d & ";" & a.objType
      d = d.strip & "}"
      return d
    of minCommand:
      return "[" & a.cmdVal & "]"

proc `$$`*(a: MinValue): string {.inline.} =
  case a.kind:
    of minNull:
      return "null"
    of minBool:
      return $a.boolVal
    of minSymbol:
      return a.symVal
    of minString:
      return a.strVal
    of minInt:
      case NUMBASE
      of baseDec:
        return $a.intVal
      of baseOct:
        return "0o" & a.intVal.toOct(sizeof(a))
      of baseBin:
        return "0b" & a.intVal.toBin(sizeof(a))
      of baseHex:
        return "0x" & a.intVal.toHex(sizeof(a))
    of minFloat:
      return $a.floatVal
    of minQuotation:
      var q = "("
      for i in a.qVal:
        q = q & $i & " "
      q = q.strip & ")"
      return q
    of minCommand:
      return "[" & a.cmdVal & "]"
    of minDictionary:
      var d = "{"
      for i in a.dVal.pairs:
        var v = ""
        if i.val.kind == minProcOp:
          v = "<native>"
        else:
          v = $i.val.val
        var k = $i.key
        if k.contains(" "):
          k = "\"$1\"" % k
        d = d & v & " :" & k & " "
      if a.objType != "":
        d = d & ";" & a.objType
      d = d.strip & "}"
      return d

proc setSymbol*(scope: ref MinScope, key: string, value: MinOperator,
    override = false, define = false): bool {.discardable.}

proc parseMinValue*(p: var MinParser, i: In): MinValue =
  case p.token
  of tkNull:
    result = MinValue(kind: minNull)
    discard getToken(p)
  of tkTrue:
    result = MinValue(kind: minBool, boolVal: true)
    discard getToken(p)
  of tkFalse:
    result = MinValue(kind: minBool, boolVal: false)
    discard getToken(p)
  of tkString:
    result = MinValue(kind: minString, strVal: p.a)
    p.a = ""
    discard getToken(p)
  of tkCommand:
    result = MinValue(kind: minCommand, cmdVal: p.a)
    p.a = ""
    discard getToken(p)
  of tkInt:
    var baseIndex = 1
    var minLen = 2
    if p.a[0] == '-':
      baseIndex = 2
      minLen = 3
    if p.a.len > minLen and p.a[baseIndex] in {'b', 'o', 'x'}:
      case p.a[baseIndex]
      of 'o':
        result = MinValue(kind: minInt, intVal: parseOctInt(p.a))
      of 'b':
        result = MinValue(kind: minInt, intVal: parseBinInt(p.a))
      of 'x':
        result = MinValue(kind: minInt, intVal: parseHexInt(p.a))
      else:
        result = MinValue(kind: minInt, intVal: parseInt(p.a))
    else:
      result = MinValue(kind: minInt, intVal: parseInt(p.a))
    discard getToken(p)
  of tkFloat:
    result = MinValue(kind: minFloat, floatVal: parseFloat(p.a))
    discard getToken(p)
  of tkBracketLe:
    var q = newSeq[MinValue](0)
    discard getToken(p)
    while p.token != tkBracketRi:
      let v = p.parseMinValue(i)
      if not v.isNil:
        q.add v
    eat(p, tkBracketRi)
    result = MinValue(kind: minQuotation, qVal: q)
  of tkBraceLe:
    var scope = newScopeRef(nil)
    var val: MinValue
    discard getToken(p)
    var c = 0
    while p.token != tkBraceRi:
      let v = p.parseMinValue(i)
      if v.isNil:
        continue
      c = c+1
      if val.isNil:
        val = v
      elif v.kind == minSymbol:
        let key = v.symVal
        if key[0] == ':':
          var offset = 0
          if key[1] == '"':
            offset = 1
          scope.symbols[key[1+offset .. key.len-1-offset]] = MinOperator(
              kind: minValOp, val: val, sealed: false)
          val = nil
        else:
          raiseInvalid("Invalid dictionary key: " & key)
      else:
        raiseInvalid("Invalid dictionary key: " & $v)
    eat(p, tkBraceRi)
    if c mod 2 != 0:
      raiseInvalid("Invalid dictionary")
    result = MinValue(kind: minDictionary, scope: scope)
  of tkSymbol:
    result = MinValue(kind: minSymbol, symVal: p.a, column: p.getColumn,
        line: p.lineNumber, filename: p.filename)
    p.a = ""
    p.currSym = result
    discard getToken(p)
  of tkLineComment, tkBlockComment, tkLineDocComment, tkBlockDocComment, tkSpace:
    eat(p, p.token)
    result = nil #p.parseMinValue(i)
    #discard getToken(p)
  else:
    let err = "Undefined or invalid value (" & $p.token & "): " & p.a
    raiseUndefined(p, err)
  if not result.isNil:
    result.filename = p.filename

proc compileMinValue*(p: var MinParser, i: In, push = true, indent = ""): seq[string] =
  var op = indent
  if push:
    op = indent&"i.push "
  result = newSeq[string](0)
  case p.token
  of tkNull:
    result = @[op&"MinValue(kind: minNull)"]
    discard getToken(p)
  of tkTrue:
    result = @[op&"MinValue(kind: minBool, boolVal: true)"]
    discard getToken(p)
  of tkFalse:
    result = @[op&"MinValue(kind: minBool, boolVal: false)"]
    discard getToken(p)
  of tkString:
    result = @[op&"MinValue(kind: minString, strVal: "&p.a.escapeEx&")"]
    p.a = ""
    discard getToken(p)
  of tkInt:
    result = @[op&"MinValue(kind: minInt, intVal: "&p.a&")"]
    discard getToken(p)
  of tkFloat:
    result = @[op&"MinValue(kind: minFloat, floatVal: "&p.a&")"]
    discard getToken(p)
  of tkBracketLe:
    CVARCOUNT.inc
    var qvar = "q" & $CVARCOUNT
    result.add indent&"var "&qvar&" = newSeq[MinValue](0)"
    discard getToken(p)
    while p.token != tkBracketRi:
      var instructions = p.compileMinValue(i, false, indent)
      let v = instructions.pop
      result = result.concat(instructions)
      if v.len > 0:
        result.add indent&qvar&".add "&v
    eat(p, tkBracketRi)
    result.add op&"MinValue(kind: minQuotation, qVal: "&qvar&")"
  of tkSqBracketLe, tkSqBracketRi:
    discard getToken(p)
  of tkCommand:
    result = @[op&"MinValue(kind: minCommand, cmdVal: "&p.a.escapeEx&")"]
    discard getToken(p)
  of tkBraceLe:
    result = newSeq[string](0)
    var val: MinValue
    discard getToken(p)
    var c = 0
    var valInitialized = false
    CVARCOUNT.inc
    var scopevar = "scope" & $CVARCOUNT
    CVARCOUNT.inc
    var valvar = "val" & $CVARCOUNT
    while p.token != tkBraceRi:
      c = c+1
      var instructions = p.compileMinValue(i, false, indent)
      let v = p.parseMinValue(i)
      if v.isNil:
        continue
      let vs = instructions.pop
      result = result.concat(instructions)
      if val.isNil:
        if not valInitialized:
          result.add indent&"var "&valvar&": MinValue"
          valInitialized = true
        result.add indent&valvar&" = "&vs
      elif v.kind == minSymbol:
        let key = v.symVal
        if key[0] == ':':
          result.add indent&scopevar&".setSymbol("&key[1 ..
              key.len-1]&"), MinOperator(kind: minValOp, val: "&valvar&", sealed: false))"
          val = nil
        else:
          raiseInvalid("Invalid dictionary key: " & key)
      else:
        raiseInvalid("Invalid dictionary key: " & $v)
    eat(p, tkBraceRi)
    if c mod 2 != 0:
      raiseInvalid("Invalid dictionary")
    result.add indent&"var "&scopevar&" = newScopeRef(nil)"
    result.add op&"MinValue(kind: minDictionary, scope: "&scopevar&")"
  of tkSymbol:
    result = @[op&"MinValue(kind: minSymbol, symVal: "&p.a.escapeEx&")"]
    p.a = ""
    discard getToken(p)
  of tkLineComment, tkBlockComment, tkLineDocComment, tkBlockDocComment, tkSpace:
    eat(p, p.token)
    result = @[""]
    #discard getToken(p)
    #result = p.compileMinValue(i, push, indent)
  else:
    raiseUndefined(p, "Undefined value: '"&p.a&"'")

proc print*(a: MinValue) =
  stdout.write($$a)
  stdout.flushFile()

# Predicates

proc isNull*(s: MinValue): bool =
  return s.kind == minNull

proc isSymbol*(s: MinValue): bool =
  return s.kind == minSymbol

proc isQuotation*(s: MinValue): bool =
  return s.kind == minQuotation

proc isCommand*(s: MinValue): bool =
  return s.kind == minCommand

proc isString*(s: MinValue): bool =
  return s.kind == minString

proc isFloat*(s: MinValue): bool =
  return s.kind == minFloat

proc isInt*(s: MinValue): bool =
  return s.kind == minInt

proc isNumber*(s: MinValue): bool =
  return s.kind == minInt or s.kind == minFloat

proc isBool*(s: MinValue): bool =
  return s.kind == minBool

proc isStringLike*(s: MinValue): bool =
  return s.isSymbol or s.isString or (s.isQuotation and s.qVal.len == 1 and
      s.qVal[0].isSymbol)

proc isDictionary*(q: MinValue): bool =
  return q.kind == minDictionary

proc isTypedDictionary*(q: MinValue): bool =
  if q.isDictionary:
    return q.objType != ""
  return false

proc isTypedDictionary*(q: MinValue, t: string): bool =
  if q.isTypedDictionary:
    return q.objType == t
  return false

proc `==`*(a: MinValue, b: MinValue): bool {.inline,
    extern: "min_exported_symbol_eqeq".} =
  if not (a.kind == b.kind or (a.isNumber and b.isNumber)):
    return false
  if a.kind == minSymbol and b.kind == minSymbol:
    return a.symVal == b.symVal
  elif a.kind == minInt and b.kind == minInt:
    return a.intVal == b.intVal
  elif a.kind == minInt and b.kind == minFloat:
    return a.intVal.float == b.floatVal.float
  elif a.kind == minFloat and b.kind == minFloat:
    return a.floatVal == b.floatVal
  elif a.kind == minFloat and b.kind == minInt:
    return a.floatVal == b.intVal.float
  elif a.kind == b.kind:
    if a.kind == minString:
      return a.strVal == b.strVal
    elif a.kind == minBool:
      return a.boolVal == b.boolVal
    elif a.kind == minNull:
      return true
    elif a.kind == minQuotation:
      if a.qVal.len == b.qVal.len:
        var c = 0
        for item in a.qVal:
          if item == b.qVal[c]:
            c.inc
          else:
            return false
        return true
      else:
        return false
    elif a.kind == minDictionary:
      let aVal = a.dVal
      let bVal = b.dVal
      if aVal.len != bVal.len:
        return false
      else:
        for t in aVal.pairs:
          if not bVal.hasKey(t.key):
            return false
          let v1 = t.val
          let v2 = bVal[t.key]
          if v1.kind != v2.kind:
            return false
          if v1.kind == minValOp:
            return v1.val == v2.val
        if a.objType == "" and b.objType == "":
          return true
        elif a.objType != "" and b.objType != "":
          return a.objType == b.objType
        else:
          return false
  else:
    return false

## Scope-related methods

proc copy*(s: ref MinScope): ref MinScope =
  var scope = newScope(s.parent)
  scope.symbols = s.symbols
  scope.sigils = s.sigils
  new(result)
  result[] = scope

proc getDictionary(d: MinOperator): MinValue =
  if d.kind == minProcOp:
    return d.mdl
  elif d.kind == minValOp and d.val.kind == minQuotation and d.val.qVal.len ==
  1 and d.val.qVal[0].kind == minDictionary:
    return d.val.qVal[0]
  elif d.kind == minValOp and d.val.kind == minDictionary:
    return d.val

proc getSymbolFromPath(scope: ref MinScope, keys: var seq[
    string]): MinOperator

proc isNull*(op: MinOperator): bool =
  return op.kind == minValOp and op.val.kind == minNull

proc getSymbol*(scope: ref MinScope, key: string): MinOperator =
  debug "getSymbol: $#" % [key]
  if scope.symbols.hasKey(key):
    return scope.symbols[key]
  elif key.contains ".":
    var keys = key.split(".")
    return getSymbolFromPath(scope, keys)
  else:
    if scope.parent.isNil:
      debug("Unable to retrieve symbol '$1' (not found)." % key)
      return MinOperator(kind: minValOp, val: MinValue(kind: minNull))
    return scope.parent.getSymbol(key)

proc getSymbolFromPath(scope: ref MinScope, keys: var seq[
    string]): MinOperator =
  let sym = keys[0]
  keys.delete(0)
  let d = scope.getSymbol(sym)
  let dict = d.getDictionary
  if not dict.isNil:
    if keys.len > 1:
      return dict.scope.getSymbolFromPath(keys)
    else:
      return dict.scope.getSymbol(keys[0])
  else:
    debug("Symbol '$1' is not a dictionary." % sym)
    return MinOperator(kind: minValOp, val: MinValue(kind: minNull))

proc delSymbolFromPath(scope: ref MinScope, keys: var seq[
    string]): bool

proc delSymbol*(scope: ref MinScope, key: string): bool {.discardable.} =
  if scope.symbols.hasKey(key):
    if scope.symbols[key].sealed:
      raiseInvalid("Symbol '$1' is sealed." % key)
    scope.symbols.excl(key)
    return true
  elif key.contains ".":
    var keys = key.split(".")
    return delSymbolFromPath(scope, keys)
  return false

proc delSymbolFromPath(scope: ref MinScope, keys: var seq[
    string]): bool =
  let sym = keys[0]
  keys.delete(0)
  let d = scope.getSymbol(sym)
  let dict = d.getDictionary
  if not dict.isNil:
    if keys.len > 1:
      return dict.scope.delSymbolFromPath(keys)
    else:
      return dict.scope.delSymbol(keys[0])
  else:
    raiseInvalid("Symbol '$1' is not a dictionary." % sym)

proc setSymbolFromPath(scope: ref MinScope, keys: var seq[
    string], value: MinOperator, override = false,
        define = false): bool {.discardable.}

proc setSymbol*(scope: ref MinScope, key: string, value: MinOperator,
    override = false, define = false): bool {.discardable.} =
  result = false
  # check if a symbol already exists in current scope
  debug "setSymbol: $#" % [key]
  if not scope.isNil and scope.symbols.hasKey(key):
    if not override and scope.symbols[key].sealed:
      raiseInvalid("Symbol '$1' is sealed ." % key)
    scope.symbols[key] = value
    debug "setSymbol (existing): $# = $#" % [key, $value]
    result = true
  elif key.contains ".":
    var keys = key.split(".")
    return setSymbolFromPath(scope, keys, value, override, define)
  # define new symbol
  elif not scope.isNil and define:
    debug "setSymbol (new): $# = $#" % [key, $value]
    scope.symbols[key] = value
    result = true
  else:
    # Go up the scope chain and attempt to find the symbol
    if not scope.parent.isNil:
      result = scope.parent.setSymbol(key, value, override, define)
    else:
      debug "setSymbol: failure to set: $# = $#" % [key, $value]

proc setSymbolFromPath(scope: ref MinScope, keys: var seq[
    string], value: MinOperator, override = false,
        define = false): bool {.discardable.} =
  let sym = keys[0]
  keys.delete(0)
  let d = scope.getSymbol(sym)
  let dict = d.getDictionary
  debug "setSymbolFromPath: Found dictionary $# - keys: $#" % [sym, keys.join(".")]
  if not dict.isNil:
    if keys.len > 1:
      return dict.scope.setSymbolFromPath(keys, value, override, define)
    else:
      return dict.scope.setSymbol(keys[0], value, override, define)
  else:
    raiseInvalid("Symbol '$1' is not a dictionary." % sym)

proc getSigil*(scope: ref MinScope, key: string): MinOperator =
  if scope.sigils.hasKey(key):
    return scope.sigils[key]
  elif not scope.parent.isNil:
    return scope.parent.getSigil(key)
  else:
    raiseUndefined("Sigil '$1' not found." % key)

proc hasSigil*(scope: ref MinScope, key: string): bool =
  if scope.isNil:
    return false
  elif scope.sigils.hasKey(key):
    return true
  elif not scope.parent.isNil:
    return scope.parent.hasSigil(key)
  else:
    return false

proc delSigil*(scope: ref MinScope, key: string): bool {.discardable.} =
  if scope.sigils.hasKey(key):
    if scope.sigils[key].sealed:
      raiseInvalid("Sigil '$1' is sealed." % key)
    scope.sigils.excl(key)
    return true
  return false

proc setSigil*(scope: ref MinScope, key: string, value: MinOperator,
    override = false): bool {.discardable.} =
  result = false
  # check if a sigil already exists in current scope
  if not scope.isNil and scope.sigils.hasKey(key):
    if not override and scope.sigils[key].sealed:
      raiseInvalid("Sigil '$1' is sealed." % key)
    scope.sigils[key] = value
    result = true
  else:
    # Go up the scope chain and attempt to find the sigil
    if not scope.parent.isNil:
      result = scope.parent.setSymbol(key, value)

proc previous*(scope: ref MinScope): ref MinScope =
  if scope.parent.isNil:
    return scope
  else:
    return scope.parent

proc hasParent*(scope: ref MinScope, parent: ref MinScope): bool =
  if scope.parent.isNil:
    return false
  if scope.parent == parent:
    return true
  return scope.parent.hasParent parent