Source

frawor / plugin / frawor / fwc / compiler.vim

Full commit
  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
"▶1 Header
scriptencoding utf-8
if exists('s:_pluginloaded') || exists('g:fraworOptions._donotload') ||
            \exists('g:frawor__donotload')
    finish
endif
execute frawor#Setup('0.0', {'@/fwc/parser': '0.0'}, 1)
let s:constructor={}
"▶1 Messages
let s:_messages={
            \'notypes' : 'Expected at least one type specification',
            \'tooshort': 'Argument list is too short: '.
            \            'expected at least %u, but got %u',
            \'toolong' : 'Argument list is too long: '.
            \            'expected at most %u, but got %u',
            \'invlen'  : 'Invalid arguments length: expected %u, but got %u',
        \}
call extend(s:_messages, map({
            \ 'funcfail': 'custom function returned 0',
            \ 'exprfail': 'custom expression returned 0',
            \'typesfail': 'invalid type: expected one of %s, but got %s',
            \ 'typefail': 'invalid type: expected %s, but got %s',
            \    'nbool': 'invalid value: expected either 0 or 1, but got %s',
            \    'nfunc': 'function %s is not callable',
            \   'nsfunc': 'expected function name or '.
            \             'callable function reference, but got %s',
            \     'nreg': 'string `%s'' is not a valid regular expression (%s)',
            \   'nmatch': "string `%s' does not match regular expression `%s'",
            \  'keysmis': 'the following required keys are missing: %s',
            \   'keymis': 'key `%s'' is missing',
            \  'runfail': 'running argument failed with exception %s',
            \ 'evalfail': 'evaluating argument failed with exception %s',
            \   'nrange': '%s is not in range [%s, %s]',
            \  'nindict': '%s is not in dictionary',
            \  'ninlist': 'argument is not in list',
            \'invlstlen': 'invalid list length: expected %u, but got %u',
        \}, '"Error while processing check %s for %s: ".v:val'))
let s:_messages._types=['number', 'string', 'function reference', 'list',
            \           'dictionary']
if has('float')
    call add(s:_messages._types, 'float')
endif
"▶1 Matchers
"▶1 string         :: String → String
function s:F.string(str)
    return substitute(substitute(substitute(string(a:str),
                \"\n",     '''."\\n".''', 'g'),
                \"^''\\.", '',            ''),
                \"\\.''$", '',            '')
endfunction
"▶1 cleanup        :: list::[_, {arg}*] → + list
function s:F.cleanup(list)
    if len(a:list)>1
        let args=remove(a:list, 1, -1)
        let sq={}
        call add(a:list, sq)
        for arg in args
            if !has_key(sq, arg[0])
                let sq[arg[0]]=[]
            endif
            if arg[0] is 'actions' || arg[0] is 'prefixes'
                if get(get(arg, 1, []), 0, '') is 'matcher'
                    let sq[arg[0].'matcher']=remove(arg, 1)[1:]
                endif
                call extend(sq[arg[0]], filter(map(arg[1:], 'v:val[1:]'),
                            \                  '!empty(v:val)'))
            elseif arg[0] is 'next'
                if len(arg[1:][0])>1
                    call add(sq[arg[0]], arg[1:][0][1:])
                endif
            elseif arg[0] is 'optional'
                if len(arg)>1
                    call add(sq[arg[0]], arg)
                endif
            else
                if len(arg)>1
                    call add(sq[arg[0]], arg[1:])
                endif
            endif
        endfor
        call filter(sq, '!empty(v:val)')
        for key in filter(['actions', 'optional'], 'has_key(sq, v:val)')
            call map(copy(sq[key]), 's:F.cleanup(v:val)')
            call filter(sq[key], '!empty(v:val)')
            if empty(sq[key])
                call remove(sq, key)
            endif
        endfor
        if has_key(sq, 'optional')
            call map(sq.optional, 'v:val[1]')
        endif
    endif
endfunction
"▶1 add            :: item, ... + self → self + self
function s:constructor.add(...)
    let self.l+=a:000
    return self
endfunction
"▶1 up             :: &self
function s:constructor.up()
    call remove(self.stack, -1)
    let self.l=self.stack[-1]
    return self
endfunction
"▶1 deeper         :: ()[, conelement1[, ...]] + self → self + self
function s:constructor.deeper(...)
    if type(get(self.l, -1))==type([])
        let self.l[-1]+=a:000
        call add(self.stack, self.l[-1])
    else
        let con=copy(a:000)
        call self.add(con)
        call add(self.stack, con)
    endif
    let self.l=self.stack[-1]
    return self
endfunction
"▶1 close          :: &self
let s:cmdends={
            \    'if': 'endif',
            \'elseif': 'endif',
            \'else'  : 'endif',
            \'try'    : 'endtry',
            \'catch'  : 'endtry',
            \'finally': 'endtry',
            \'function': 'endfunction',
            \     'for': 'endfor',
            \   'while': 'endwhile',
            \'augroup': 'augroup END',
            \  'redir': 'redir END',
        \}
function s:constructor.close()
    let command=self.l[-2][:(stridx(self.l[-2], ' ')-1)]
    if has_key(s:cmdends, command)
        return self.add(s:cmdends[command])
    else
        return self
    endif
endfunction
"▶1 nextcond       :: [condition] + self → self + self
function s:constructor.nextcond(...)
    if !empty(self.l)
        if type(self.l[-1])==type([])
            let prevline=self.l[-2]
        else
            let prevline=self.l[-1]
        endif
        let command=prevline[:(stridx(prevline, ' ')-1)]
    endif
    if exists('command') && (command is 'if' || command is 'elseif')
        if a:0
            return self.add('elseif '.a:1).deeper()
        else
            return self.add('else').deeper()
        endif
    else
        if a:0
            return self.add('if '.a:1).deeper()
        else
            return self
        endif
    endif
endfunction
"▶1 addthrow       :: msg::String, msgarg, ... + self → self + self
function s:constructor.addthrow(msg, ...)
    let args=copy(a:000)
    let curidx=index(args, '@#@')
    if curidx!=-1
        let args=map(args[:(curidx-1)], 'string(v:val)')+[self.argstr(1)]+
                    \args[(curidx+1):]
    endif
    return self.add('call add(@$@messages, ['.string(a:msg).', '.
                \                             join(args, ', ').'])',
                \   'throw "CHECKFAILED"')
endfunction
"▶1 nextthrow      :: condition::expr, throwargs + self → self + self
function s:constructor.nextthrow(cond, ...)
    return call(self.nextcond(a:cond).addthrow, a:000, self).up()
endfunction
"▶1 getlenrange    :: adescr → (minlen, maxlen) + adescr
function s:F.getlenrange(adescr)
    let minimum=0
    let maximum=0
    "▶2 “arg” key
    if has_key(a:adescr, 'arg')
        let minimum=len(a:adescr.arg)
        let maximum=minimum
    endif
    "▶2 “optional” key
    if has_key(a:adescr, 'optional')
        let lenlist=map(copy(a:adescr.optional), 's:F.getlenrange(v:val)[1]')
        if index(lenlist, -1)!=-1
            let maximum=-1
        else
            let maximum+=max(lenlist)
        endif
    endif
    "▶2 “actions” key
    if has_key(a:adescr, 'actions')
        let minset=0
        let amin=0
        let amax=0
        let has0=0
        let hasa=0
        for action in a:adescr.actions
            if action[0] is 0
                let has0=1
            else
                let hasa=1
            endif
            if len(action)>1
                let [namin, namax]=s:F.getlenrange(action[1])
                if namin<amin || !minset
                    let minset=1
                    let amin=namin
                endif
                if namax==-1
                    let maximum=-1
                elseif namax>amax
                    let amax=namax
                endif
            endif
        endfor
        let minimum+=((has0)?(0):(hasa))+amin
        if maximum!=-1
            let maximum+=hasa+amax
        endif
    endif
    "▶2 “prefixes” key
    if has_key(a:adescr, 'prefixes')
        let maximum=-1
        for prefopts in map(copy(a:adescr.prefixes), 'v:val[1]')
            let minimum+=((prefopts.opt)?
                        \   (0):
                        \   ((prefopts.list)?
                        \       (2):
                        \       (1+prefopts.argnum)))
        endfor
    endif
    "▶2 “next” key
    if has_key(a:adescr, 'next')
        let maximum=-1
    endif
    "▲2
    let a:adescr.minimum=minimum
    let a:adescr.maximum=maximum
    return [minimum, maximum]
endfunction
"▶1 lencheck       :: minlen, maxlen + self → self + self
function s:constructor.lencheck(minimum, maximum)
    if a:maximum==a:minimum
        call self.nextthrow('@$@largs isnot '.a:maximum,
                    \       'invlen', a:minimum, '@$@largs')
    else
        if a:minimum>0
            call self.nextthrow('@$@largs<'.a:minimum,
                        \       'tooshort', a:minimum, '@$@largs')
        endif
        if a:maximum!=-1
            call self.nextthrow('@$@largs>'.a:maximum,
                        \       'toolong',  a:maximum, '@$@largs')
        endif
    endif
    return self.close()
endfunction
"▶1 substostr      :: [subscript] → String
function s:F.substostr(subscripts)
    let r=''
    for sub in a:subscripts
        let tsub=type(sub)
        if tsub==type('')
            if sub=~#'^\w\+$'
                let r.='.'.sub
            else
                let r.='['.s:F.string(sub).']'
            endif
        elseif tsub==type(0)
            let r.='['.sub.']'
        elseif tsub==type([])
            let r.='['.join(sub, ':').']'
        endif
        unlet sub
    endfor
    return r
endfunction
"▶1 getfunc        :: funccontext[, addarg, ...] + self → String + self
function s:constructor.getfunc(func, ...)
    let r=self.getvar(a:func[1]).'('
    let args=[]
    let added000=0
    for arg in a:func[2:]
        if a:0 && arg[0] is 'this'
            let args+=a:000
            let added000=1
        else
            call add(args, self.getvar(arg))
        endif
    endfor
    if a:0 && !added000
        let args+=a:000
    endif
    let r.=join(args, ', ').')'
    return r
endfunction
"▶1 getvar         :: varcontext + self → String + self
function s:constructor.getvar(var)
    if a:var[0] is 'plugvar'
        return '@%@.p.'.a:var[1].s:F.substostr(a:var[2:])
    elseif a:var[0] is 'expr'
        return substitute(a:var[1], '\V@.@', self.argstr(), 'g')
    elseif a:var[0] is 'string'
        return s:F.string(a:var[1])
    elseif a:var[0] is 'argument'
        return self.argstr(0, [self.subs[0]+a:var[1]]+a:var[2:])
    elseif a:var[0] is 'cur'
        return self.argstr(0, self.subs[:-1-a:var[1]]+a:var[2:])
    elseif a:var[0] is 'list'
        return '['.join(map(a:var[1:], 'type(v:val)=='.type('').'?'.
                    \                       's:F.string(v:val):'.
                    \                       'self.getvar(v:val)'), ', ').']'
    elseif a:var[0] is 'evaluate'
        return eval(substitute(self.getvar(a:var[1]), '@%@', 'self.vars', 'g'))
    elseif a:var[0] is 'func'
        return self.getfunc(a:var)
    elseif a:var[0] is 'this'
        return self.argstr()
    endif
endfunction
"▶1 argstr         :: [genString::Bool, [subscript]] + self → String
"▶2 addargchunk    :: [chunk], chunk::String, literal::Bool → _ + chunks
function s:F.addargchunk(chunks, chunk, literal)
    if a:literal==(len(a:chunks)%2)
        call add(a:chunks, a:chunk)
    else
        let a:chunks[-1].=a:chunk
    endif
endfunction
"▲2
function s:constructor.argstr(...)
    if get(a:000, 0, 0)
        let chunks=['@@@']
        for sub in get(a:000, 1, self.subs)
            let tsub=type(sub)
            if tsub==type('')
                if sub=~#'^\w\+$'
                    call s:F.addargchunk(chunks, '.'.sub, 0)
                else
                    call s:F.addargchunk(chunks, '['.s:F.string(sub).']', 0)
                endif
            elseif tsub==type(0)
                call s:F.addargchunk(chunks, '['.sub.']', 0)
            else
                if type(sub[0])==type('')
                    call s:F.addargchunk(chunks, '[', 0)
                    call s:F.addargchunk(chunks, sub[0], 1)
                    if len(sub)>1
                        call s:F.addargchunk(chunks, ':', 0)
                        call s:F.addargchunk(chunks, sub[1], 1)
                    endif
                    call s:F.addargchunk(chunks, ']', 0)
                else
                    call s:F.addargchunk(chunks, '['.join(sub, ':').']', 0)
                endif
            endif
            unlet sub
        endfor
        return join(map(chunks, 'v:key%2 ? v:val : string(v:val)'), '.')
    else
        return '@@@'.s:F.substostr(get(a:000, 1, self.subs))
    endif
endfunction
"▶1 addtuple       :: tupledesc, idx, defaultArgType + self → self + self
function s:constructor.addtuple(tuple, idx, default)
    let i=0
    for arg in a:tuple[1]
        call add(self.subs, i)
        call self.compilearg(arg, a:idx.'.'.i, a:default)
        call remove(self.subs, -1)
        let i+=1
    endfor
    return self
endfunction
"▶1 addlist        :: listdesc, idx, defaultArgType + self → self + self
function s:constructor.addlist(list, idx, default)
    let conid=printf('%X', len(self.stack))
    let largstr='@$@larg'.conid
    let istr='@$@i'.conid
    call self.add('let '.largstr.'=len('.self.argstr().')',
                \ 'let '.istr.'=0',
                \ 'while '.istr.'<'.largstr)
                \.deeper()
    call add(self.subs, [istr])
    call self.compilearg(a:list[1], a:idx.'.list', a:default)
    call self.add('let '.istr.'+=1')
    call remove(self.subs, -1)
    call self.up().close()
endfunction
"▶1 compilemsg     :: msgcontext, _ + self → self + self
function s:constructor.compilemsg(msg, idx)
    let msg=[a:msg[1]]
    for msgarg in a:msg[2:]
        if msgarg[0] is 'curval'
            call add(msg, self.argstr())
        elseif msgarg[0] is 'curarg'
            call add(msg, self.subs[0])
        else
            call add(msg, substitute(s:constructor.getvar(msgarg), '@#@',
                        \            escape(self.argstr(), '\&~'), 'g'))
        endif
    endfor
    return self
endfunction
"▶1 compilestring  :: {string} + self → self + self
function s:constructor.compilestring(str)
    if type(a:str)==type('')
        return s:F.string(a:str)
    endif
    return self.getvar(a:str)
endfunction
"▶1 compilepipe    :: pipecontext, idx + self → self + self
function s:constructor.compilepipe(pipe, idx)
    let curargstr=self.argstr()
    "▶2 `func' pipe
    if a:pipe[1][0] is 'func'
        call self.add('let '.curargstr.'='.self.getfunc(a:pipe[1], curargstr))
    "▶2 `expr' pipe
    elseif a:pipe[1][0] is 'expr'
        call self.add('let '.curargstr.'='.substitute(a:pipe[1][1],
                    \                                 '\V@.@', curargstr, 'g'))
    "▶2 Built-in pipes
    elseif a:pipe[1][0] is 'intfunc'
        let desc=a:pipe[1][1:]
        if a:0 && has_key(s:pipechecks, desc[0])
            call self.compilecheck(['check', s:pipechecks[desc[0]]], a:idx)
        endif
        "▶3 `func', `eval'
        if desc[0] is 'func' || desc[0] is 'eval'
            call self.compilepipe(desc, a:idx)
        "▶3 `run'
        elseif desc[0] is 'run'
            call self.add('try')
                        \.deeper('let '.curargstr.'=call('.curargstr.', '.
                        \                          self.getvar(desc[1]).', {})')
                        \.up().add('catch /.*/').deeper()
                        \.addthrow('runfail', a:idx, '@#@', 'v:exception')
                        \.up().close()
        "▶3 `earg'
        elseif desc[0] is 'earg'
            call self.add('try')
                        \.deeper('let '.curargstr.'=eval('.curargstr.')')
                        \.up().add('catch /.*/').deeper()
                        \.addthrow('evalfail', a:idx, '@#@', 'v:exception')
                        \.up().close()
        "▶3 `tuple'
        elseif desc[0] is 'tuple'
            call self.nextthrow('len('.curargstr.')!='.len(desc[1]),
                        \       'invlstlen', a:idx, '@#@', len(desc[1]),
                        \                    'len('.curargstr.')').close()
                        \.addtuple(desc, a:idx, 'pipe')
        "▶3 `list'
        elseif desc[0] is 'list'
            call self.addlist(desc, a:idx, 'pipe')
        "▶3 `dict'
        elseif desc[0] is 'dict'
            " TODO
        "▶3 `in'
        elseif desc[0] is 'in'
            if len(desc)==2 || (desc[2][1][0] is 'intfunc' &&
                        \       desc[2][1][1] is 'exact' &&
                        \       desc[2][1][2] is 0)
                call self.compilecheck(['check', a:pipe[1]], a:idx)
            else
                call self.addtypecond([type('')], idx)
                " TODO
            endif
        "▶3 `key'
        elseif desc[0] is 'key'
            if len(desc)==2 || (desc[2][1][0] is 'intfunc' &&
                        \       desc[2][1][1] is 'exact' &&
                        \       desc[2][1][2] is 0)
                call self.compilecheck(['check', a:pipe[1]], a:idx)
            else
                call self.addtypecond([type('')], idx)
                " TODO
            endif
        "▶3 `take'
        elseif desc[0] is 'take'
            " TODO
        "▶3 `substitute'
        elseif desc[0] is 'substitute'
            call self.add('let '.curargstr.'=substitute('.curargstr.', '.
                        \((type(desc[1][1])==type(''))?
                        \       (s:F.string(desc[1][1])):
                        \       (self.getvar(desc[1][1]))).', '.
                        \join(map(desc[2:], 'self.compilestring(v:val)'), ', ').
                        \')')
        "▶3 `bool'
        elseif desc[0] is 'bool'
            call self.add('let '.curargstr.'=!empty('.curargstr.')')
        "▲3
        else
            call self.compilecheck(['check', a:pipe[1]], a:idx)
        endif
    endif
    return self
endfunction
let s:constructor.compilefilter=s:constructor.compilepipe
"▶1 addtypecond    :: types, idx + self → self + self
function s:constructor.addtypecond(types, idx)
    let curargstr=self.argstr()
    let typenames=map(copy(a:types), 's:_messages._types[v:val]')
    if len(a:types)>=2
        call self.nextthrow('index('.string(a:types).', '.
                    \            'type('.curargstr.'))==-1',
                    \       'typesfail', a:idx, '@#@',
                    \                    string(join(typenames, '/')),
                    \                    '@%@.m.types[type('.curargstr.')]')
    elseif len(a:types)==1
        call self.nextthrow('type('.curargstr.')!='.a:types[0],
                    \       'typefail', a:idx, '@#@', string(typenames[0]),
                    \                   '@%@.m.types[type('.curargstr.')]')
    else
        call self.throw('notypes')
    endif
    return self
endfunction
"▶1 incidx         :: idx → idx
function s:F.incidx(idx)
    let subidxs=split(a:idx, '\V.')
    let subidxs[-1]+=1
    return join(subidxs, '.')
endfunction
"▶1 compilecheck   :: checkcontext, idx + self → self + self
function s:constructor.compilecheck(check, idx)
    let curargstr=self.argstr()
    let addedcond=0
    let idx=a:idx
    for check in a:check[1:]
        "▶2 `func' check
        if check[0] is 'func'
            let addedcond=1
            call self.nextthrow(self.getfunc(check, curargstr).' is 0',
                        \       'funcfail', idx, '@#@')
        "▶2 `expr' check
        elseif check[0] is 'expr'
            let addedcond=1
            call self.nextthrow(substitute(check[1], '\V@.@', curargstr, 'g').
                        \                                           ' is 0',
                        \       'exprfail', idx, '@#@')
        "▶2 `intfunc' check
        else
            let desc=check[1:]
            "▶3 `func'
            if desc[0] is 'func'
                let addedcond=1
                call self.nextthrow(self.getfunc(desc[1], curargstr).' is 0',
                            \       'funcfail', idx, '@#@')
            "▶3 `eval'
            elseif desc[0] is 'eval'
                let addedcond=1
                call self.nextthrow(substitute(desc[1][1],
                            \                  '\V@.@', curargstr, 'g').' is 0',
                            \       'exprfail', idx, '@#@')
            "▶3 `either'
            elseif desc[0] is 'either'
                " TODO
            "▶3 `tuple'
            elseif desc[0] is 'tuple'
                call self.addtypecond([type([])], idx)
                            \.nextthrow('len('.curargstr.')!='.len(desc[1]),
                            \           'invlstlen', idx, '@#@', len(desc[1]),
                            \                        'len('.curargstr.')')
                            \.addtuple(desc, idx, 'check')
            "▶3 `list'
            elseif desc[0] is 'list'
                call self.addtypecond([type([])], idx).close()
                let addedcond=0
                call self.addlist(desc, idx, 'check')
            "▶3 `dict'
            elseif desc[0] is 'dict'
                " TODO
            "▶3 `in'
            elseif desc[0] is 'in'
                let addedcond=1
                call self.nextthrow('index('.self.getvar(desc[1]).', '.
                            \                curargstr.')==-1',
                            \       'ninlist', idx, '@#@')
            "▶3 `key'
            elseif desc[0] is 'key'
                let addedcond=1
                call self.addtypecond([type('')], idx)
                call self.nextthrow('!has_key('.self.getvar(desc[1]).', '.
                            \                   curargstr.')',
                            \       'nindict', idx, '@#@', curargstr)
            "▶3 `haskey'
            elseif desc[0] is 'haskey'
                let addedcond=1
                call self.addtypecond([type({})], idx)
                if len(desc[1])>1
                    let keys='['.join(map(copy(desc[1]),
                                \         'type(v:val)==type("")?'.
                                \               's:F.string(v:val):'.
                                \               'self.getvar(v:val)'),
                                \', ').']'
                    let absentkeys='filter('.keys.', '.
                                \          string('!has_key('.curargstr.', '.
                                \                           'v:val)').')'
                    call self.nextthrow('!empty('.absentkeys.')',
                                \       'keysmis', idx, '@#@',
                                \                  'join('.absentkeys.', ", ")')
                elseif !empty(desc[1])
                    let keystr=((type(desc[1][0])==type(''))?
                                \       (s:F.string(desc[1][0])):
                                \       (self.getvar(desc[1][0])))
                    call self.nextthrow('!has_key('.curargstr.', '.keystr.')',
                                \       'keymis', idx, '@#@', keystr)
                endif
            "▶3 `range'
            elseif desc[0] is 'range'
                let addedcond=1
                "▶4 Determine whether we accept floating-point values
                let acceptfloat=has('float') &&
                            \(desc[1][0] is 'float' || desc[1][1] is 'float')
                if acceptfloat
                    call self.addtypecond([type(0), type(0.0)], idx)
                else
                    call self.addtypecond([type(0)], idx)
                endif
                "▶4 Obtain range borders
                let range=map(desc[1:],
                            \'((v:val[0] is "inf" || v:val[0] is "nan")?'.
                            \   '(""):'.
                            \   '((v:val[0] is "number"||v:val[0] is "float")?'.
                            \       '(v:val[1]):'.
                            \       '(self.getvar(v:val))))')
                if type(range[0])!=type('') && type(range[1])!=type('')
                            \&& range[0]>range[1]
                    call reverse(range)
                endif
                "▶4 Construct condition
                let cond=''
                call map(range, '((type(v:val)=='.type('').')?'.
                            \               '(v:val):'.
                            \               '(string(v:val)))')
                if range[0] isnot ''
                    let cond.=range[0].'>'.curargstr
                endif
                if range[1] isnot ''
                    if !empty(cond)
                        let cond.=' || '
                    endif
                    let cond.=curargstr.'>'.range[1]
                endif
                "▶4 Add condition to result
                if !empty(cond)
                    call self.nextthrow(cond, 'nrange', idx, '@#@',
                                \                       'string('.curargstr.')',
                                \                       'string('.range[0].')',
                                \                       'string('.range[1].')')
                endif
            "▶3 `match'
            elseif desc[0] is 'match'
                let addedcond=1
                call self.addtypecond([type('')], idx)
                let regex=((type(desc[1][1])==type(''))?
                            \(s:F.string(desc[1][1])):
                            \(self.getvar(desc[1][1])))
                call self.nextthrow(curargstr.'!~#'.regex,
                            \       'nmatch', idx, '@#@', curargstr, regex)
            "▶3 `path'
            elseif desc[0] is 'path'
                call self.addtypecond([type('')], idx)
                " TODO
            "▶3 `type'
            elseif desc[0] is 'type'
                let addedcond=1
                call self.addtypecond(desc[1], idx)
            "▶3 `isfunc'
            elseif desc[0] is 'isfunc'
                let addedcond=1
                let frefpref='string('.curargstr.')[10:11]'
                if desc[1]
                    call self.addtypecond([2], idx)
                    call self.nextthrow('!exists('.string('*'.curargstr).') ||'.
                                \                       frefpref.' is "s:"',
                                \       'nfunc', idx, '@#@',
                                \                'string('.curargstr.')[10:-3]')
                else
                    call self.nextthrow('!((type('.curargstr.')==2 && '.
                                \         'exists('.string('*'.curargstr).')&&'.
                                \          frefpref.' isnot "s:") '.
                                \        '|| (type('.curargstr.')=='.type('').
                                \            '&& '.curargstr.'=~#'.
                                \             '''\v^%(%([sla]@!\w:)?%(\w|\.)+|'.
                                \                    '%(s@!\w:)?\w+)$'''.
                                \            '&& exists("*".'.curargstr.')))',
                                \       'nsfunc', idx, '@#@',
                                \                 'string('.curargstr.')')
                endif
            "▶3 `isreg'
            elseif desc[0] is 'isreg'
                call self.addtypecond([type('')], idx)
                call self.close()
                let addedcond=0
                call self.add('try')
                          \.deeper('call matchstr("", '.curargstr.')').up()
                        \.add('catch /.*/').deeper()
                          \.addthrow('nreg', idx, '@#@', curargstr,
                          \                  'v:exception')
                        \.up().close()
            "▶3 `bool'
            elseif desc[0] is 'bool'
                let addedcond=1
                call self.nextthrow('index([0, 1], '.curargstr.')==-1',
                            \       'nbool', idx,'@#@', 'string('.curargstr.')')
            "▶3 `_', `any'
            elseif desc[0] is '_' || desc[0] is 'any'
                " Just do nothing here
            endif
            "▲3
        endif
        "▲2
        let idx=s:F.incidx(idx)
    endfor
    if addedcond
        call self.close()
    endif
    return self
endfunction
"▶1 compilearg     :: argcontext, idx[, defcomptype] + self → self + self
let s:pipechecks={
            \'substitute': ['intfunc', 'type',   [type('')]],
            \      'take': ['intfunc', 'type',   [type('')]],
            \       'run': ['intfunc', 'isfunc', 0         ],
            \      'earg': ['intfunc', 'type',   [type('')]],
            \     'tuple': ['intfunc', 'type',   [type([])]],
            \      'list': ['intfunc', 'type',   [type([])]],
            \      'dict': ['intfunc', 'type',   [type({})]],
        \}
function s:constructor.compilearg(argcon, idx, ...)
    let type=get(a:000, 0, self.type)
    if a:argcon[0] is 'arg'
        let arg=a:argcon[1:]
    else
        let arg=a:argcon
    endif
    let check=['check']
    let msg=[]
    let i=0
    let squashedlen=0
    for proc in arg
        if proc[0] is 'check'
            let squashedlen+=1
            call add(check, proc[1])
            let i+=1
            continue
        elseif proc[0] is 'pipe' && proc[1][0] is 'intfunc'
                    \&& has_key(s:pipechecks, proc[1][1])
            call add(check, s:pipechecks[proc[1][1]])
        elseif self.type is 'filter' && proc[0] is 'intfunc'
                    \&& has_key(s:pipechecks, proc[1])
            call add(check, s:pipechecks[proc[1]])
        endif
        if len(check)>1
            call self.compilecheck(check, a:idx.'.'.(i+((squashedlen)?
                        \                                   (1-squashedlen):
                        \                                   (0))))
            let squashedlen=0
            call remove(check, 1, -1)
        endif
        let compargs=[proc, a:idx.'.'.i]
        let comptype=proc[0]
        if comptype is 'intfunc'
            let comptype=type
            let compargs[0]=[comptype, compargs[0]]
        endif
        call call(self['compile'.comptype], compargs, self)
        let i+=1
    endfor
    if len(check)>1
        call self.compilecheck(check, a:idx.'.'.(i+1-len(check)))
        call remove(check, 1, -1)
    endif
    if type(self.subs[-1])==type(0)
        let self.subs[-1]+=1
    endif
    return self
endfunction
"▶1 compileadesc   :: adescr + self → self + self
function s:constructor.compileadesc(adescr)
    if !has_key(a:adescr, 'minimum')
        call s:F.getlenrange(a:adescr)
    endif
    if !has_key(a:adescr, 'checkedfor')
        call self.lencheck(self.subs[0]+a:adescr.minimum,
                    \      self.subs[0]+a:adescr.maximum)
        let a:adescr.checkedfor=1
    endif
    if has_key(a:adescr, 'arg')
        call map(a:adescr.arg, 'self.compilearg(v:val, v:key)')
    endif
    " TODO
    return self
endfunction
"▶1 tolstofstr     :: CTree::[String|CTree] → [String]
function s:F.tolstofstr(ctree)
    let r=[]
    let items=map(a:ctree, '[0, v:val]')
    while !empty(items)
        let [indent, item]=remove(items, 0)
        if type(item)==type([])
            call extend(items, map(item, '['.(indent+1).', v:val]'), 0)
        else
            call add(r, repeat('    ', indent).item)
        endif
        unlet item
    endwhile
    return r
endfunction
"▶1 compilestr     :: String, type → [String]
function s:F.compilestr(vars, string, type)
    "▶2 Setup self
    let t   =   { 'tree': s:_r.fwc_parser(a:string, a:type)[1:],
                \ 'type': a:type,
                \'ctree': [],
                \'stack': [],
                \ 'subs': [0],
                \    'l': 0,
                \ 'vars': a:vars,
                \ 'vids': {},
                \}
    call extend(t, s:constructor, 'error')
    let t.throw=s:_f.throw
    call add(t.stack, t.ctree)
    let t.l=t.stack[-1]
    "▲2
    call s:F.cleanup(t.tree)
    let t.o=remove(t.tree, 0)
    let t.tree=t.tree[0]
    if t.type is 'check' || t.type is 'filter'
        call   t.add('let @$@messages=[]',
                    \'let @$@pmessages=[]',
                    \'try').deeper()
        if !t.o.only
            call t.add('let @$@largs=len(@@@)')
            if t.type is 'check' || t.type is 'filter'
                call t.compileadesc(t.tree)
            else
            endif
        endif
        call t.up()
        call t.add('catch /^CHECKFAILED$/')
                \.deeper('for @$@targs in @$@messages')
                  \.deeper('call call(@%@.F.warn, @$@targs, {})')
                \.up().close()
                \.add('for @$@targs in @$@pmessages')
                  \.deeper('call call(@%@.p._f.warn, @$@targs, {})')
                \.up().close()
                \.add('return 0')
              \.up().close()
    else
        call t.add('let @@@=[]')
    endif
    if t.type is 'check'
        call t.add('return 1')
    elseif t.type is 'filter'
        call t.add('return @@@')
    else
        call t.add('return @@@')
    endif
    return s:F.tolstofstr(t.ctree)
endfunction
"▶1 makefunc       :: {f}, String, type → Fref + s:lastid, s:vars
let s:lastid=0
let s:vars={}
function s:F.makefunc(plugdict, fdict, string, type)
    let d={}
    let id=printf('%s%X', a:type, s:lastid)
    let s:lastid+=1
    let s:vars[id]={
                \'F': {'warn': s:_f.warn},
                \'p': a:plugdict.g,
                \'m': {'types': s:_messages._types},
            \}
    call add(a:fdict.ids, id)
    execute "function d.f(args)\n    ".
                \substitute(substitute(substitute(
                \join(s:F.compilestr(s:vars[id], a:string, a:type), "\n    "),
                \'@@@', ((a:type is 'completer')?
                \           ('variants'):
                \           ('a:args')), 'g'),
                \'@%@', 's:vars.'.id,    'g'),
                \'@$@', '',              'g')."\n".
            \"endfunction"
    return d.f
endfunction
"▶1 delids         :: {f}
function s:F.delids(plugdict, fdict)
    call map(a:fdict.ids, 'remove(s:vars, v:val)')
endfunction
"▶1 Register feature
call s:_f.newfeature('fwc_compile', {'cons': s:F.makefunc,
            \                      'unload': s:F.delids,
            \                        'init': {'ids': []}})
"▶1
" TODO implement recursion protection
" TODO implement onlystrings option (disables type checks)
call frawor#Lockvar(s:, 'lastid,vars')
" vim: fmr=▶,▲ sw=4 ts=4 sts=4 et tw=80