frawor / plugin / frawor / fwc / parser.vim

   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
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
"▶1 Header
scriptencoding utf-8
if exists('s:_pluginloaded') || exists('g:fraworOptions._donotload') ||
            \exists('g:frawor__donotload')
    finish
endif
execute frawor#Setup('0.0', {'@/resources': '0.0'}, 1)
let s:parser={}
"▶1 Define messages
let s:_messages={
            \     'int': 'internal error: %s',
            \     'eos': 'unexpected end of string',
            \  'ukfunc': 'unknown function: %s',
            \  'ukfarg': 'unknown function argument: %s',
            \'unmatchp': 'unmatched `%s''',
            \ 'uenvvar': 'unknown enviroment variable: %s',
            \  'invvar': 'invalid variable description: %s',
            \  'invact': 'invalid action description: %s',
            \'invssubs': 'invalid subscript in slice expression: %s',
            \ 'uoption': 'unknown option: %s',
            \  'argmis': 'missing arguments to %s',
            \  'actmis': 'missing arguments description',
            \ 'typemis': 'missing type description',
            \ 'invtype': 'invalid type description: %s',
            \  'invreg': 'invalid regular expression: %s',
            \ 'wordend': 'regular expression cannot end with %s',
            \  'noexpr': 'expected expression, but got nothing',
        \}
"▶1 s:args
let s:args={}
"▶2 pipe
let s:args.pipe={}
"▶3 pipe.func
" Replaces {argument} with the result of running {func}({argument})
let s:args.pipe.func=['func']
"▶3 pipe.eval
" Replaces {argument} with the result of evaluating {expr}
let s:args.pipe.eval=['expr']
"▶3 pipe.run
" Replaces {argument} with the result of calling itself with {var} as argument 
" list
let s:args.pipe.run=['var']
"▶3 pipe.earg
" Replaces {argument} with the result of evaluating itself
let s:args.pipe.earg=[]
"▶3 pipe.tuple
" Checks whether {argument} is a list with a fixed length and then process given 
" pipes for each of the arguments
let s:args.pipe.tuple=['*arg']
"▶3 pipe.list
" Checks whether {argument} is a list and then filter each item using given 
" specification
let s:args.pipe.list=['arg']
"▶3 pipe.dict
" Checks whether {argument} is a dictionary and transform it using given 
" {ddescr}
let s:args.pipe.dict=['ddescr']
"▶3 pipe.in
" Picks up first element from {var}::List that matches {argument}. If {matcher} 
" is absent then {argument} may be of any type. In other case it should be 
" string.
let s:args.pipe.in=['var', '?omtchr']
"▶3 pipe.key
" Picks up first key from {var}::Dictionary that matches {argument}
let s:args.pipe.key=['var', '?omtchr']
"▶3 pipe.take
" Replaces {argument} with value of the first key from {var}::Dictionary that 
" matches {argument}
let s:args.pipe.take=['var', 'matcher']
"▶3 pipe.substitute
" Runs substitute on {argument}
let s:args.pipe.substitute=['reg', 'string', 'string']
"▶3 pipe.bool
" Transforms {argument} to 0 if it is empty and to 1 otherwise
let s:args.pipe.bool=[]
"▶2 check
let s:args.check={}
"▶3 check.func
" Checks whether result of running {func}({argument}) isnot 0
let s:args.check.func=['func']
"▶3 check.eval
" Checks whether result of running eval({expr}) isnot 0
let s:args.check.eval=['expr']
"▶3 check.not
let s:args.check.not=['arg']
"▶3 check.either
" Checks whether {argument} matches one of given specifications
let s:args.check.either=['*arg']
"▶3 check.tuple
" Checks whether {argument} is a list with a fixed length and each element 
" matching given specification
let s:args.check.tuple=['*arg']
"▶3 check.list
" Checks whether {argument} is a list where each item matches given 
" specification
let s:args.check.list=['arg']
"▶3 check.dict
" Checks whether {argument} is a dictionary matching given {ddescr}
let s:args.check.dict=['ddescr']
"▶3 check.in
" Checks whether {argument} is inside list {var}. Matcher is ignored
let s:args.check.in=['var', '?omtchr']
"▶3 check.key
" Checks whether {argument} is a key of {var}. Matcher is ignored
let s:args.check.key=['var', '?omtchr']
"▶3 check.haskey
" Checks whether {argument} is a dictionary with given keys
let s:args.check.haskey=['*string']
"▶3 check.range
" Checks whether {argument} is in given range
let s:args.check.range=['number', 'number']
"▶3 check.match
" Checks whether {argument} is a string that matches {reg}
let s:args.check.match=['reg']
"▶3 check.path
" Checks whether {argument} is a path matching given specification
let s:args.check.path=['path']
"▶3 check.type
" Checks whether {argument} has one of given types
let s:args.check.type=['*type']
"▶3 check.isfunc
" Checks whether {argument} is a callable function reference. Additional 
" argument determines whether strings should not be accepted
let s:args.check.isfunc=['?one']
"▶3 check.isreg
" Checks whether {argument} is a valid regular expression
let s:args.check.isreg=[]
"▶3 check.bool
" Checks whether {argument} is either 0 or 1
let s:args.check.bool=[]
"▶3 check._, check.any
" Unconditionally accepts {argument}
let s:args.check._=[]
let s:args.check.any=s:args.check._
"▶2 arg
let s:args.argcheck=copy(s:args.check)
let s:args.argfilter=extend(copy(s:args.check), s:args.pipe)
"▶2 matcher
let s:args.matcher={}
"▶3 matcher.func
" Uses some other function as matcher. Function must accept list or dictionary 
" and return a list of strings. Additional argument determines what should be 
" done if function returns list with more then one item
let s:args.matcher.func=['func', '?one']
"▶3 matcher.exact
" Requires exact match. First additional argument determines whether match 
" should be done case-insensitively, second determines whether ambigious matches 
" should be accepted (only used if first argument is true)
let s:args.matcher.exact=['?one', '?one']
"▶3 matcher.start
" Requires match at the start of string. First optional arguments determines 
" case sensitivity, second determines whether ambigious matches should be 
" accepted (in this case first match in sorted list will be taken)
let s:args.matcher.start=['?one', '?one']
"▶3 matcher.smart
" `smart' matcher tries to gues what element is really ment. Additional argument 
" determines whether ambigious match should be accepted (in this case first 
" match in sorted list will be taken)
let s:args.matcher.smart=['?one']
"▶1 getmatch   :: Dict, String → String
function s:F.getmatch(dict, str)
    if has_key(a:dict, a:str)
        return a:str
    endif
    let lstr=len(a:str)-1
    return get(filter(sort(keys(a:dict)), 'v:val[:'.lstr.'] is a:str'), 0, 0)
endfunction
"▶1 add        :: &self
" Adds an element to current context
function s:parser.add(item)
    call add(self.l, a:item)
    return self
endfunction
"▶1 conclose   :: &self
" Closes current context
function s:parser.conclose()
    call remove(self.stack, -1)
    let self.l=self.stack[-1]
    return self
endfunction
"▶1 addcon     :: ()[, conelement1[, ...]] + self → self + self
" Adds new context with given elements
function s:parser.addcon(...)
    let con=copy(a:000)
    call self.add(con)
    call add(self.stack, con)
    let self.l=con
    return self
endfunction
"▶1 removestr  :: (UInt) + self → self + self(s)
function s:parser.removestr(len)
    if a:len>0
        let self.s=self.s[(a:len):]
        let self.len-=a:len
    endif
    return self
endfunction
"▶1 delblanks  :: &self(s)
function s:parser.delblanks()
    return self.removestr(match(self.s, '\S'))
endfunction
"▶1 ungetc     :: (Char) + self → self + self(s)
function s:parser.ungetc(c)
    call add(self.ungot, a:c)
    let self.len+=len(a:c)
    return self
endfunction
"▶1 ungotjoin  :: &self(s)
function s:parser.ungotjoin()
    let joined=substitute(join(reverse(remove(self.ungot, 0, -1))),
                \         '\w\@<! \w\@!', '', 'g')
    if joined[-1:]=~#'^\w' && self.s=~#'^\w'
        let joined.=' '
    endif
    let self.len+=len(joined)
    let self.s=joined.self.s
    return self
endfunction
"▶1 readc      :: () + self → String + self(s)
" Gets next character or word
function s:parser.readc()
    if !empty(self.ungot)
        let c=remove(self.ungot, -1)
        let self.len-=len(c)
        return c
    endif
    call self.delblanks()
    if !self.len
        call self.throw('eos')
    endif
    let c=self.s[0]
    if c!~#'\w'
        call self.removestr(1)
    else
        let c=matchstr(self.s, '^\w\+')
        call self.removestr(len(c))
    endif
    return c
endfunction
"▶1 readstr    :: () + self → String + self(s)
" Gets next double-quoted string. Backslash just escapes next character, no 
" other translations are done
" {dstr} :: '"' ( ( ! '\' | '"' ) | ( '\\' | '\"' ) )* '"'
"  {str} :: {dstr} | {sstr}
function s:parser.readstr()
    if !empty(self.ungot)
        call self.throw('int', 'strungetc')
    endif
    let c=matchstr(self.s, '\v(\\.|[^\\"])*"')
    if empty(c)
        call self.throw('unmatchp', '"')
    endif
    call self.removestr(len(c))
    return substitute(c[:-2], '\\\(.\)', '\1', 'g')
endfunction
"▶1 readsstr   :: () + self → String + self(s)
" Gets next single-quoted string.
" {sstr} :: "'" ( "''" | ( ! "'" ) )* "'"
"  {str} :: {dstr} | {sstr}
function s:parser.readsstr()
    if !empty(self.ungot)
        call self.throw('int', 'strungetc')
    endif
    let c=matchstr(self.s, "\\v(''|[^'])*'")
    if empty(c)
        call self.throw('unmatchp', "'")
    endif
    call self.removestr(len(c))
    return substitute(c[:-2], "''", "'", 'g')
endfunction
"▶1 readreg    :: endstr + self → String + self(s)
" Gets the next regular expression. {endstr} determines border character
" {reg} :: ( "\" . | ! "\" {endstr} ) {endstr}
" {endstr} :: {char} \ {wordchar}
function s:parser.readreg(endstr)
    if !empty(self.ungot)
        call self.throw('int', 'regungetc')
    endif
    if a:endstr=~#'^\w'
        call self.throw('wordend', a:endstr)
    endif
    let c=matchstr(self.s, '\v(\\.|[^\\'.escape(a:endstr, '\]^-').'])+'.
                \          '\V'.escape(a:endstr, '\'))
    if empty(c)
        call self.throw('unmatchp', a:endstr)
    endif
    call self.removestr(len(c))
    try
        call matchstr('', c)
    catch
        call self.throw('invreg', c)
    endtry
    return c[:-2]
endfunction
"▶1 readflt    :: () + self → String|0 + self(s)
"  {flt} :: ( "+" | "-" ) ( "nan" | "inf" | {unum} )
" {unum} :: {d}* "."? {d}* ( "e" ( "+" | "-" )? [0-9]+ )?
"    {d} :: [0-9] | "_"
function s:parser.readflt()
    if !empty(self.ungot)
        call self.ungotjoin()
    endif
    call self.delblanks()
    let c=matchstr(self.s,
                \'\v\c^[+-]? *%(nan|inf|[0-9_]*\.?[0-9_]*%(e[+-]?\d+)?)')
    call self.removestr(len(c))
    if empty(c)
        return 0
    endif
    return substitute(substitute(substitute(substitute(tolower(c),
                \'[_ ]',           '',     'g'),
                \'^[+-]\=\d\@!',   '&0',   '' ),
                \'\.\d\@!',        '.0',   '' ),
                \'\v^[+-]?\d+e@=', '&.0',  '' )
endfunction
"▶1 readexpr   :: () + self → String + self(s)
let s:parens={'(': ')', '[': ']', '{': '}'}
let s:revparens={}
call map(copy(s:parens), 'extend(s:revparens, {v:val : v:key})')
function s:parser.readexpr()
    if !empty(self.ungot)
        call self.throw('int', 'fltungetc')
    endif
    call self.delblanks()
    let c=''
    let parens=[]
    while !empty(self.s)
        let chunk=matchstr(self.s, '\v^.{-}[''[\](){}"]')
        let stopsym=''
        if empty(chunk)
            let chunk=self.s
        else
            let stopsym=chunk[-1:]
        endif
        if has_key(s:parens, stopsym)
            call add(parens, s:parens[stopsym])
        elseif has_key(s:revparens, stopsym)
            let close=''
            while !empty(parens) && parens[-1] isnot stopsym
                let close.=remove(parens, -1)
            endwhile
            let c.=close
            if !empty(parens)
                call remove(parens, -1)
            endif
        elseif stopsym is '"'
            let string=matchstr(self.s, '\v(\\.|[^\\"])*"', len(chunk))
            if empty(string)
                call self.throw('unmatchp', '"')
            else
                let chunk.=string
            endif
        elseif stopsym is "'"
            let string=matchstr(self.s, '\v(''''|[^''])*''', len(chunk))
            if empty(string)
                call self.throw('unmatchp', "'")
            else
                let chunk.=string
            endif
        endif
        call self.removestr(len(chunk))
        let c.=chunk
        if empty(parens)
            break
        endif
    endwhile
    let c.=join(parens, '')
    if empty(c)
        call self.throw('noexpr')
    endif
    return c
endfunction
"▶1 scanlist   :: farg + self → self
" Scans a list of elements that looks either like "{e1}, {e2}", "({e1} {e2})" or 
" "({e1}, {e2})" (last two can be combined).
" Input: {<farg>} ( "," {<farg>} )*
"      | "(" ( {<farg>} ","? )* ")"?
" Output: context({<farg>}*)
function s:parser.scanlist(farg)
    call self.addcon()
    if self.len
        let c=self.readc()
        if c is '('
            while self.len
                let c=self.readc()
                if c is ')'
                    break
                elseif c isnot ','
                    call self.ungetc(c)
                    call call(self['get'.a:farg], [], self)
                endif
            endwhile
        else
            call self.ungetc(c)
            while self.len
                call call(self['get'.a:farg], [], self)
                if self.len
                    let c=self.readc()
                    if c isnot ','
                        call self.ungetc(c)
                        break
                    endif
                endif
            endwhile
        endif
    endif
    return self.conclose()
endfunction
"▶1 intfunc    :: &self
" Gets pipe, func, argument or matcher that may accept one or more arguments. 
" Arguments are described in s:args and have a form [?][*]{aname}, where {aname} 
" is a part of get* function name, ? determines whether argument can be omitted 
" (it really makes a difference only at the end of the string), * says that 
" string should be scanned for a list of arguments with arbitrary length, not 
" just for a single one
" Input: {funcname} [arguments]?
"        {funcname} :: {wordchar}+
" Output: context(intfunc, {funcname}[, contexts])
function s:parser.intfunc()
    let type=self.l[0]
    if type is 'arg'
        let type.=self.type
    endif
    let c=self.readc()
    let func=s:F.getmatch(s:args[type], c)
    if func is 0 "▶2
        call self.throw('ukfunc', c)
    endif        "▲2
    call self.addcon('intfunc', func)
    let fargs=get(s:args[type], func, [])
    for farg in fargs
        if farg[0] is '?'
            let farg=farg[1:]
        elseif !self.len "▶2
            call self.throw('argmis', type.'.'.func)
        endif            "▲2
        if farg[0] is '*'
            call self.scanlist(farg[1:])
        else
            call call(self['get'.farg], [], self)
        endif
    endfor
    return self.conclose()
endfunction
"▶1 getarg     :: &self!
" Simple wrapper to scan()
function s:parser.getarg()
    return self.scan()
endfunction
"▶1 getone     :: &self!
" Consumes a word and adds 1 to context if next word is "1", otherwise adds 0. 
" If next word is "0", it is consumed.
" Input: ( "0" | "1" )?
" Output: add(0|1)
function s:parser.getone()
    if !self.len
        call self.add(0)
    else
        let c=self.readc()
        if c is '1'
            call self.add(1)
        else
            call self.add(0)
            if c isnot '0'
                call self.ungetc(c)
            endif
        endif
    endif
    return self
endfunction
"▶1 gettype    :: &self!
" Adds type number to the context.
" Valid arguments: s[tring], n[umber], f[loat], d[ictionary], l[ist], fu[nction]
"                   "", '',     -0,      .0,         {},        []
" Input: {typedescr}
" Output: add({typeNumber})
"         {typeNumber}: any number described in |type()|
let s:typechars={
            \'{': [type({}),  '}'],
            \'[': [type([]),  ']'],
            \'"': [type(""),  '"'],
            \"'": [type(''),  "'"],
            \'-': [type(0),   '0'],
        \}
let s:typewords={
            \    'string': type(''),
            \    'number': type(0),
            \'dictionary': type({}),
            \      'list': type([]),
            \  'function': 2,
        \}
if has('float')
    let s:typechars['.']=[type(0.0), '0']
    let s:typewords.float=type(0.0)
endif
function s:parser.gettype()
    if !self.len
        call self.throw('typemis')
    endif
    let c=self.readc()
    if has_key(s:typechars, c)
        call self.add(s:typechars[c][0])
        if self.len
            let readchar=s:typechars[c][1]
            let c=self.readc()
            if c isnot readchar
                call self.ungetc(c)
            endif
        endif
    else
        let type=s:F.getmatch(s:typewords, tolower(c))
        if type is 0
            call self.throw('invtype', c)
        endif
        call self.add(s:typewords[type])
    endif
    return self
endfunction
"▶1 getstring  :: &self!
" Gets either a string or variable name
" Input: ( "$" {var} | {str} | {wordchar}+ )?
" Output: add({string}) | *getvar
function s:parser.getstring()
    if self.len
        let c=self.readc()
        if c is '$'
            call self.getvar()
        elseif c is '"'
            call self.add(self.readstr())
        elseif c is "'"
            call self.add(self.readsstr())
        elseif c=~#'^\w'
            call self.add(c)
        else
            call self.add('').ungetc(c)
        endif
    else
        call self.add('')
    endif
    return self
endfunction
"▶1 getpath    :: &self!
" Gets path specification:
" Input: [( "d" | "f" )] [ "r" ] [( "w" | "W" | "p" )] [ "x" ]
"        & ! ( "d" | ^ ) "r"
"        & ! ( "d" ) ( "w" | "W" | "p" )? "x"
" 1. "d" for directory and "f" for regular file, otherwise both may be accepted
" 2. "r" for readable file (not directory)
" 3. "w" for writeable file or directory (unless "f" is specified),
"    "W" for writeable file or directory (unless "f" is specified) or
"        non-existant file in writeable directory (unless "d" is specified),
"    "p" like "W", but also accepts any path that can be created (for example,
"        if you have directory /a and you can write to it, then path /a/b/c/d 
"        will be accepted),
" 4. "x" for executable file (not directory)
" Output: add({pathspec})
function s:parser.getpath()
    let c=self.readc()
    if c=~#'\v^[df]?r?[wWp]?x?$' && c!~#'\v^%(d%(.{,2}x|r)|r)'
        call self.add(c)
    else
        call self.add('r').ungetc(c)
    endif
    return self
endfunction
"▶1 getsubscr  :: &self!
" Input: ( "."? ( ":" {n} {n} | {subscript} ) )*
"        {subscript} :: {str}
"                     | [0-9] {wordchar}*
"                     | {wordchar}+
"                     | "$" {var}
"                     | {var}
"                {n} :: "-"? {wordchar}+
"                     | "$" {var}
"                     | {var}
" Output: add((String|Number|context(Number, Number))*)
function s:parser.getsubscr()
    let requiresdot=0
    while self.len
        let c=self.readc()
        if requiresdot
            let requiresdot=0
            if c isnot '.'
                call self.ungetc(c)
                break
            endif
            continue
        elseif c=~#'^\d'
            call self.add(+c)
        elseif c=~#'^\w'
            call self.add(c)
        elseif c is '"'
            call self.add(self.readstr())
        elseif c is "'"
            call self.add(self.readsstr())
        elseif c is ':'
            call self.addcon()
            " Start and end subscripts
            for i in range(0, 1)
                let v=self.readc()
                if v is '-'
                    call self.add(+v.(self.readc()))
                elseif v=~#'^\d'
                    call self.add(+v)
                elseif v is '$'
                    call self.getvar()
                else
                    call self.ungetc(v).getvar()
                endif
            endfor
            call self.conclose()
        elseif c is '$'
            call self.addcon().getvar()
        else
            call self.addcon().ungetc(c).getvar()
        endif
        let requiresdot=1
    endwhile
    return self
endfunction
"▶1 getddescr  :: &self
" Gets dictionary description:
" Input: "{" ({keydescr} {arg})* "}"
"        {keydescr} :: {str}
"                    | "/" {reg}(endstr=/)
"                    | "?" {arg}
"                    | "*" {func}
"                    | "=" {expr}
"                    | "-"
"                    | {wordchar}+
" Output: context(ddescr, {keycon}*)
"         {keycon} :: context(eq,    String, {arg})
"                   | context(regex, String, {arg})
"                   | context(check, {arg},  {arg})
"                   | context(func,  {func}, {arg})
"                   | context(expr,  {expr}, {arg})
"                   | context(any,           {arg})
function s:parser.getddescr()
    call self.addcon('ddescr')
    if self.len
        let c=self.readc()
        if c isnot '{'
            call self.ungetc(c)
        endif
        let prevlen=-1
        while self.len && self.len!=prevlen
            let prevlen=self.len
            let c=self.readc()
            if c is '}'
                break
            elseif c is '/'
                call self.addcon('regex', self.readreg('/')).scan().conclose()
            elseif c is '*'
                call self.addcon('func').getfunc().scan().conclose()
            elseif c is '='
                call self.addcon('expr').getexpr().scan().conclose()
            elseif c is '?'
                call self.addcon('check').scan().scan().conclose()
            elseif c is '-'
                call self.addcon('any').scan().conclose()
            elseif c is '"'
                call self.addcon('eq', self.readstr()).scan().conclose()
            elseif c is "'"
                call self.addcon('eq', self.readsstr()).scan().conclose()
            elseif c=~#'^\w'
                call self.addcon('eq', c).scan().conclose()
            endif
        endwhile
    endif
    return self.conclose()
endfunction
"▶1 getreg     :: &self
" Gets regular expression
" Input: "$" {var}
"      | {startchar} {reg}(endchar={endchar})
"           {startchar} :: ! ( {wordchar} | "$" )
"             {endchar} :: pair({startchar}) | {startchar}
" Output: context(regex, {var}|String)
let s:pairs={
            \'(': ')',
            \'[': ']',
            \'{': '}',
            \'<': '>',
        \}
function s:parser.getreg()
    call self.addcon('regex')
    let c=self.readc()
    if c is '$'
        call self.getvar()
    else
        call self.add(self.readreg(get(s:pairs, c, c)))
    endif
    return self.conclose()
endfunction
"▶1 getnumber  :: &self
" Get integer or floating point number (including ±inf and nan)
" Input: {flt}
"      | "$" {var}
"      | ""
" Output: context(inf, "+" | "-")
"       | context(nan)
"       | context(number, Number)
"       | context(float, Float)
"       | *getvar
function s:parser.getnumber()
    let f=self.readflt()
    if f is 0
        let c=self.readc()
        if c is '$'
            return self.getvar()
        else
            call self.ungetc(c)
        endif
    elseif f[-3:] is 'inf'
        let sign=f[0]
        if f[0] is 'i'
            let sign='+'
        endif
        return self.addcon('inf', sign).conclose()
    elseif f is 'nan'
        return self.addcon('nan').conclose()
    endif
    let r=eval(f)
    if type(r) is type(0)
        return self.addcon('number', r).conclose()
    else
        return self.addcon('float', r).conclose()
    endif
endfunction
"▶1 getexpr    :: &self
" Input: {expr}
" Output: context(expr, String)
function s:parser.getexpr()
    return self.addcon('expr', self.readexpr()).conclose()
endfunction
"▶1 getchvar   :: &self
" Input: ( ( "^"* ) | ( ">" | "<" )* ) ( "." {subscr} )?
" Output: context(argument, Number, {subscr}?)
"       | context(cur, UInt, {subscr}?)
function s:parser.getchvar()
    if self.len
        let c=self.readc()
        if c is '<' || c is '>'
            call self.addcon('argument', 0)
            call self.ungetc(c)
            while self.len
                let c=self.readc()
                if c is '>'
                    let self.l[-1]+=1
                elseif c is '<'
                    let self.l[-1]-=1
                else
                    break
                endif
            endwhile
        else
            call self.ungetc(c).addcon('cur', 0)
            while self.len
                let c=self.readc()
                if c is '^'
                    let self.l[-1]+=1
                else
                    break
                endif
            endwhile
        endif
        if c is '.'
            call self.getsubscr()
        elseif self.len
            call self.ungetc(c)
        endif
    else
        call self.addcon('cur', 0)
    endif
    return self.conclose()
endfunction
"▶1 getlist    :: &self
" Input: ( "$" {var} | {str} | {wordchar}+ | {var} )* "]"?
" Output: context(list, ({var}|String)*)
function s:parser.getlist()
    call self.addcon('list')
    while self.len
        let c=self.readc()
        if c is ']'
            break
        elseif c is '$'
            call self.getvar()
        elseif c is '"'
            call self.add(self.readstr())
        elseif c is "'"
            call self.add(self.readsstr())
        elseif c=~#'^\w'
            call self.add(c)
        else
            call self.ungetc(c).getvar()
        endif
    endwhile
    return self.conclose()
endfunction
"▶1 getvar     :: &self
" Input: {wordchar}+ {subscr}*
"      | "@" {chvar}
"      | "=" {expr}
"      | "[" {list}
"      | "$" {var}
"      | {str}
" Output: context(plugvar, String, {subscr}*)
"       | {chvar}
"       | {expr}
"       | {list}
"       | context(evaluate, {var})
"       | context(string, String)
function s:parser.getvar()
    let c=self.readc()
    if c=~#'^\w'
        call self.addcon('plugvar').ungetc(c).getsubscr().conclose()
    elseif c is '@'
        return self.getchvar()
    elseif c is '='
        return self.getexpr()
    elseif c is '['
        call self.getlist()
    elseif c is '*'
        call self.getfunc()
    elseif c is '$'
        call self.addcon('evaluate').getvar().conclose()
    elseif c is '"'
        call self.addcon('string', self.readstr()).conclose()
    elseif c is "'"
        call self.addcon('string', self.readsstr()).conclose()
    else
        call self.throw('invvar', c)
    endif
    return self
endfunction
"▶1 getfunc    :: &self
" Input: {var} ( "(" ( "." | {var} | "," )* ")"? )?
" Output: context(func, {var}, ({var}|context(this))*)
function s:parser.getfunc()
    call self.addcon('func').getvar()
    if self.len
        let c=self.readc()
        if c is '('
            while self.len
                let c=self.readc()
                if c is ')'
                    break
                elseif c is '.'
                    call self.addcon('this').conclose()
                elseif c isnot ','
                    call self.ungetc(c).getvar()
                endif
            endwhile
        else
            call self.ungetc(c)
        endif
    endif
    return self.conclose()
endfunction
"▶1 getmatcher :: &self
" Input: {intfunc}
" Output: context(matcher, {intfunc})
function s:parser.getmatcher()
    return self.addcon('matcher').intfunc().conclose()
endfunction
"▶1 getomtchr  :: &self
" Input: ( "~" {intfunc} )?
" Output: context(matcher, {intfunc})?
function s:parser.getomtchr()
    if self.len
        let c=self.readc()
        if c is '~'
            return self.getmatcher()
        endif
        return self.ungetc(c)
    endif
    return self
endfunction
"▶1 scanfie    :: contextName + self → self + self
" Input: {intfunc}
"      | "*" {func}
"      | "=" {expr}
" Output: context(<contextName>, {intfunc}|{func}|{expr})
function s:parser.scanfie(cname)
    call self.addcon(a:cname)
    let c=self.readc()
    if c is '*'
        call self.getfunc()
    elseif c is '='
        call self.getexpr()
    else
        call self.ungetc(c).intfunc()
    endif
    return self.conclose()
endfunction
"▶1 scanmsg    :: &self
" Input: {wordchar}+ ( "(" ( "." | "%" | {var} | "," ) ")"? )?
" Output: context(msg, String, {msgarg}*)
"         {msgarg} :: context(curval)
"                   | context(curarg)
"                   | {var}
function s:parser.scanmsg()
    call self.addcon('msg', self.readc())
    if self.len
        let c=self.readc()
        if c is '('
            while self.len
                let c=self.readc()
                if c is ')'
                    break
                elseif c is '.'
                    call self.addcon('curval').conclose()
                elseif c is '%'
                    call self.addcon('curarg').conclose()
                elseif c isnot ','
                    call self.ungetc(c).getvar()
                endif
            endwhile
        else
            call self.ungetc(c)
        endif
    endif
    return self.conclose()
endfunction
"▶1 scanopt    :: &self
" Input: {arg}* "]"?
" Output: context(optional, {arg}*)
function s:parser.scanopt()
    call self.addcon('optional')
    let prevlen=-1
    while self.len && self.len!=prevlen
        let prevlen=self.len
        let c=self.readc()
        if c is ']'
            break
        else
            call self.ungetc(c).scan()
        endif
    endwhile
    return self.conclose()
endfunction
"▶1 scanpref   :: &self
" Input: ({prefdescr} ( "-" | {arg} ) )* "}"?
"        {prefdescr} :: {prefopts}? ( {str} | {wordchar}+ )
"         {prefopts} :: ( "?" | "!" | "*" | "+" {digit}+ )* ( ":" {var} )?
" Output: context(prefixes, context(String, {prefopts}[, {var}][, {arg}+]))
"         {prefopts} :: { "alt": Bool, "list": Bool, "opt": Bool,
"                         "argnum": UInt }
let s:defprefopts={'alt': 0, 'list': 0, 'opt': 0, 'argnum': 1}
function s:parser.scanpref()
    call self.addcon('prefixes')
    let c=self.readc()
    if c is '~'
        call self.getmatcher()
    else
        call self.ungetc(c)
    endif
    let prevlen=-1
    while self.len && prevlen!=self.len
        let prevlen=self.len
        let c=self.readc()
        if !exists('pref')
            if !exists('prefopts')
                let prefopts=copy(s:defprefopts)
            endif
            let prefopts.argnum=1
            if c=~#'^\w'
                let pref=c
            elseif c is '"'
                let c=self.readstr()
                let pref=c
            elseif c is "'"
                let c=self.readsstr()
                let pref=c
            elseif c is '+'
                let prefopts.argnum=+self.readc()
            elseif c is '?'
                let prefopts.opt=1
            elseif c is '!'
                let prefopts.alt=1
            elseif c is '*'
                let prefopts.list=1
            elseif c is '}'
                break
            else
                call self.ungetc(c)
                break
            endif
        else
            call self.addcon('prefix', pref, prefopts)
            if c is ':'
                call self.getvar()
                let c=self.readc()
            endif
            if c is '-'
                let prefopts.argnum=0
            else
                call self.ungetc(c)
            endif
            let argnum=prefopts.argnum
            while argnum
                call self.scan()
                let argnum-=1
            endwhile
            unlet pref prefopts
            call self.conclose()
        endif
    endwhile
    return self.conclose()
endfunction
"▶1 scanact    :: &self
" Input: "~" {matcher} ( {actdescr} ( "-" | "(" {arg}* ")"? | {arg} ) )* ">"?
"        {actdescr} :: {str}
"                    | {wordchar}+
" Output: context(actions[, {matcher}],
"                 (context(action, 0|String|{arg}, {arg}*))
function s:parser.scanact()
    call self.addcon('actions')
    let c=self.readc()
    if c is '~'
        call self.getmatcher()
    else
        call self.ungetc(c)
    endif
    let hasaction=0
    let prevlen=-1
    while self.len && prevlen!=self.len
        let prevlen=self.len
        let c=self.readc()
        if !hasaction
            let hasaction=1
            if c is '>'
                let hasaction=0
                break
            elseif c is '"'
                call self.addcon('action', self.readstr())
            elseif c is "'"
                call self.addcon('action', self.readsstr())
            elseif c is '-'
                call self.addcon('action', 0)
            elseif c=~#'^\w'
                call self.addcon('action', c)
            else
                call self.ungetc(c).addcon('action').scan()
            endif
        else
            let hasaction=0
            if c is '('
                while self.len
                    let c=self.readc()
                    if c is ')'
                        break
                    endif
                    call self.ungetc(c).scan()
                endwhile
            elseif c isnot '>' && c isnot '-'
                call self.ungetc(c).scan()
            endif
            call self.conclose()
        endif
    endwhile
    if hasaction
        call self.conclose()
    endif
    return self.conclose()
endfunction
"▶1 scan       :: &self
" Input: "[" {opt}  ⎫
"      | "{" {pref} ⎬ (only at toplevel or in context(action or optional))
"      | "<" {act}  ⎪
"      | "+" {arg}  ⎭
"      | ( ":" {var} )? ( | "(" ( "|" {pipe} | "#" {msg} | {intfunc} )* ")"?
"                         | ( "|" {pipe} | "#" {msg} )* {intfunc}? )
"        ⎺⎺⎺⎺⎺⎺\/⎺⎺⎺⎺⎺⎺
"           only in
"       context(optional)
" Output: {opt}                ⎫
"       | {pref}               ⎬ (only at toplevel or in context(action or
"       | {act}                ⎪                                 optional))
"       | context(next, {arg}) ⎭
"       | context(arg[, context(defval)], ({pipe}|{check}|{msg}|{intfunc})*)
"                    ⎺⎺⎺⎺⎺⎺⎺⎺⎺V⎺⎺⎺⎺⎺⎺⎺⎺⎺
"                          only in
"                     context(optional)
function s:parser.scan()
    "▶2 optional, prefixes, actions, next
    let c=self.readc()
    let type=get(self.l, 0, '')
    if type is 'top' || type is 'optional'
                \|| (type is 'action' && len(self.l)>1)
        if c is '['
            return self.scanopt()
        elseif c is '{'
            return self.scanpref()
        elseif c is '<'
            return self.scanact()
        elseif c is '+'
            return self.addcon('next').scan().conclose()
        endif
    endif
    "▲2
    call self.addcon('arg')
    "▶2 Default value
    if type is 'optional' && c is ':'
        call self.addcon('defval').getvar().conclose()
        let c=self.readc()
    endif
    "▶2 Define variables used to determine how to handle second word
    let accepttext=(type is 'next' || self.o.only)
    let hasparen=0
    let hastext=0
    if c is '('
        let hasparen=1
        let accepttext=1
    else
        call self.ungetc(c)
    endif
    "▲2
    while self.len
        let c=self.readc()
        if c is '|'
            call self.scanfie('pipe')
        elseif c is '?'
            call self.scanfie('check')
        elseif c is '#'
            call self.scanmsg()
        elseif (!hastext || accepttext) && c=~#'^\w'
            let hastext=1
            call self.ungetc(c).intfunc()
            if !accepttext
                break
            endif
        elseif hasparen && c is ')'
            break
        else
            call self.ungetc(c)
            break
        endif
    endwhile
    return self.conclose()
endfunction
"▶1 scanopts   :: &self
" Input: "-" "("? ( "no"? ( "only" | "recursive" | "onlystrings" ) )* ")"
" Output: add(<self.o>)
let s:options={'only': 0, 'recursive': 0, 'onlystrings': 0}
function s:parser.scanopts()
    let c=self.readc()
    let self.o=copy(s:options)
    call self.add(self.o)
    if c is '-'
        let c=self.readc()
        if c isnot '('
            call self.ungetc(c)
        endif
        while self.len
            let c=self.readc()
            if c is ')'
                break
            elseif has_key(self.o, c)     " -(option)
                let self.o[c]=1
            elseif has_key(self.o, c[2:]) " -(nooption)
                let self.o[c[2:]]=0
            else
                call self.throw('uoption', c)
            endif
        endwhile
    else
        call self.ungetc(c)
    endif
    return self
endfunction
"▶1 parsestr   :: String → SynTree
function s:F.parsestr(string, type)
    "▶2 Setup self
    let s   =   {    's': a:string,
                \ 'tree': ['top'],
                \ 'type': a:type,
                \'stack': [],
                \'ungot': [],
                \    'l': 0,
                \  'len': len(a:string),
                \}
    call extend(s, s:parser, 'error')
    " FIXME Redefine this function with more verbose one
    let s.throw=s:_f.throw
    call add(s.stack, s.tree)
    let s.l=s.stack[-1]
    "▲2
    call s.scanopts()
    if s.o.only
        call s.scan()
    else
        let prevlen=-1
        while s.len && s.len!=prevlen
            let prevlen=s.len
            call s.scan()
        endwhile
    endif
    return s.tree
endfunction
"▶1 Post resource
call s:_f.postresource('fwc_parser', s:F.parsestr)
"▶1
call frawor#Lockvar(s:, '')
" vim: fmr=▶,▲ sw=4 ts=4 sts=4 et tw=80
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.