summary refs log tree commit diff stats
path: root/tests
ModeNameSize
d---------actiontable44log stats plain
d---------alias76log stats plain
d---------align128log stats plain
d---------ambsym361log stats plain
d---------arc3676log stats plain
d---------arithm146log stats plain
d---------array473log stats plain
d---------assert327log stats plain
d---------assign223log stats plain
-rw-r--r--ast_pattern_matching.nim18828log stats plain blame
d---------astoverload45log stats plain
d---------astspec40log stats plain
d---------async2807log stats plain
d---------avr118log stats plain
d---------benchmarks73log stats plain
d---------bind267log stats plain
d---------borrow132log stats plain
d---------casestmt495log stats plain
d---------ccgbugs4037log stats plain
d---------ccgbugs296log stats plain
d---------clearmsg199log stats plain
d---------closure924log stats plain
d---------cnstseq40log stats plain
d---------collections260log stats plain
d---------compilepragma70log stats plain
d---------compiler869log stats plain
d---------compilerapi162log stats plain
d---------compilerfeatures44log stats plain
d---------compiles269log stats plain
d---------concat39log stats plain
d---------concepts1652log stats plain
-rw-r--r--config.nims1813log stats plain blame
d---------constr409log stats plain
d---------constraints44log stats plain
d---------constructors131log stats plain
d---------controlflow211log stats plain
d---------converter806log stats plain
d---------coroutines330log stats plain
d---------cpp1593log stats plain
d---------defaultprocparam98log stats plain
d---------deprecated282log stats plain
d---------destructor3352log stats plain
d---------dir with space76log stats plain
d---------discard284log stats plain
d---------distinct162log stats plain
d---------distros47log stats plain
d---------dll1075log stats plain
-rw-r--r--dummy.txt27log stats plain blame
d---------effects2046log stats plain
d---------enum706log stats plain
d---------errmsgs3725log stats plain
d---------exception1302log stats plain
d---------exprs266log stats plain
d---------fields85log stats plain
d---------float483log stats plain
d---------fragmentation127log stats plain
d---------friends80log stats plain
d---------gc995log stats plain
d---------generics3235log stats plain
d---------gensym85log stats plain
d---------global241log stats plain
d---------ic564log stats plain
d---------import_in_config109log stats plain
d---------importalls560log stats plain
d---------init422log stats plain
d---------isolate81log stats plain
d---------iter1754log stats plain
-rw-r--r--js.html765log stats plain blame
-rw-r--r--js.nim572log stats plain blame
d---------js3532log stats plain
d---------lent270log stats plain
d---------let191log stats plain
d---------lexer771log stats plain
d---------lookups169log stats plain
-rw-r--r--m14634.nim1579log stats plain blame
d---------macros3557log stats plain
d---------magics115log stats plain
d---------manyloc268log stats plain
d---------metatype1301log stats plain
d---------method550log stats plain
d---------misc5937log stats plain
-rw-r--r--mmaptest.nim1204log stats plain blame
d---------modules2442log stats plain
d---------namedparams134log stats plain
d---------navigator121log stats plain
d---------newconfig217log stats plain
d---------nimble373log stats plain
d---------nimdoc315log stats plain
d---------niminaction245log stats plain
d---------notnil386log stats plain
d---------objects1078log stats plain
d---------objvariant680log stats plain
d---------openarray287log stats plain
d---------osproc244log stats plain
d---------overflw167log stats plain
d---------overload764log stats plain
d---------package89log stats plain
d---------package_level_objects164log stats plain
d---------parallel1381log stats plain
d---------parser1784log stats plain
d---------pragmas1623log stats plain
d---------proc416log stats plain
d---------procvar88log stats plain
d---------range342log stats plain
d---------rational83log stats plain
-rw-r--r--readme.md1353log stats plain blame
d---------realtimeGC75log stats plain
-rw-r--r--rectest.nim57log stats plain blame
d---------sandwich189log stats plain
d---------sets308log stats plain
d---------showoff286log stats plain
d---------slice41log stats plain
d---------specialops205log stats plain
d---------statictypes429log stats plain
-rw-r--r--stckovfl.nim141log stats plain blame
d---------stdlib8350log stats plain
d---------stmt174log stats plain
d---------strictnotnil94log stats plain
d---------stylecheck275log stats plain
d---------system1134log stats plain
d---------template2324log stats plain
-rw-r--r--test_nimscript.nims3628log stats plain blame
d---------testament253log stats plain
d---------testdata401log stats plain
d---------threads553log stats plain
d---------tools334log stats plain
d---------trmacros258log stats plain
d---------tuples560log stats plain
d---------typerel1981log stats plain
d---------types2058log stats plain
d---------untestable356log stats plain
d---------usingstmt42log stats plain
d---------valgrind88log stats plain
d---------varres456log stats plain
d---------varstmt76log stats plain
d---------views473log stats plain
d---------vm3634log stats plain
d---------whenstmt156log stats plain
d---------xml352log stats plain
65c0c336c993607020bc422fa804ea8b87fd5f2'>^
886a1ab15 ^
f18b3af9d ^
886a1ab15 ^

5e15dec17 ^

ce859d8c1 ^
5e15dec17 ^


da190876d ^
a85b57971 ^

5e15dec17 ^
5348fef00 ^
6e8ed8c6f ^
5e15dec17 ^



886a1ab15 ^
a296f091e ^
5e15dec17 ^
a296f091e ^
1786e3099 ^
a296f091e ^
4a77b66b1 ^
a296f091e ^



4a77b66b1 ^
a296f091e ^
5e15dec17 ^

b9079b871 ^
f18b3af9d ^
9b9a18094 ^

ce859d8c1 ^

9b9a18094 ^
3e7b04683 ^

9b9a18094 ^
3e7b04683 ^

9b9a18094 ^
cc28eef38 ^
9b9a18094 ^

1d14cb1ad ^
bf057f0d2 ^


70ea45cdb ^
bf057f0d2 ^

fe30ec83e ^
5e15dec17 ^
669a56449 ^
5e15dec17 ^

6df259f15 ^
92b8fac94 ^
5e15dec17 ^

da190876d ^
5e15dec17 ^
6e8ed8c6f ^
92b8fac94 ^
b5b5e6e76 ^
92b8fac94 ^
886a1ab15 ^
6bcdb9c8f ^


5e15dec17 ^

6e8ed8c6f ^
886a1ab15 ^

e68830a95 ^
5e15dec17 ^
51e01879b ^
5e15dec17 ^
258aabba6 ^
4a77b66b1 ^

ee67a67ac ^
6df259f15 ^
9b9a18094 ^
f18b3af9d ^
9b9a18094 ^

db35ac435 ^
9b9a18094 ^
9b9a18094 ^




5e15dec17 ^
f18b3af9d ^
5e15dec17 ^




f18b3af9d ^
5e15dec17 ^
ce859d8c1 ^
5e15dec17 ^
cc28eef38 ^
5e15dec17 ^


bba551fd1 ^
5e15dec17 ^


cc28eef38 ^
e42c304e4 ^




4e4d466d0 ^
5e15dec17 ^

4e4d466d0 ^
5e15dec17 ^
ce859d8c1 ^
5e15dec17 ^

2d546ca0a ^




5348fef00 ^
6e8ed8c6f ^
2d546ca0a ^
5e15dec17 ^

bf592c4e9 ^
ce859d8c1 ^
5e15dec17 ^
f18b3af9d ^
5e15dec17 ^
ce859d8c1 ^
5e15dec17 ^
3c8c5d081 ^
cc28eef38 ^
3c8c5d081 ^




5e15dec17 ^
3c8c5d081 ^
9b9a18094 ^

b9079b871 ^
ce859d8c1 ^
b9079b871 ^

5e15dec17 ^
f18b3af9d ^
5e15dec17 ^
bba551fd1 ^
ce859d8c1 ^

5e15dec17 ^


bba551fd1 ^
f18b3af9d ^
5e15dec17 ^
bba551fd1 ^
ce859d8c1 ^

5e15dec17 ^
f18b3af9d ^
5e15dec17 ^
bba551fd1 ^
ce859d8c1 ^

bba551fd1 ^
5e15dec17 ^



bba551fd1 ^
5e15dec17 ^


1a61c4d46 ^

5e15dec17 ^


c1627354d ^
5e15dec17 ^





886a1ab15 ^

3e056afb1 ^

dc956c485 ^
d65101268 ^


ba4dd92f4 ^
8ef66b973 ^
40ec7be45 ^
ba4dd92f4 ^





40ec7be45 ^
8ef66b973 ^


ce859d8c1 ^
8ef66b973 ^




ba4dd92f4 ^
8ef66b973 ^
40ec7be45 ^
8ef66b973 ^

ba4dd92f4 ^




40ec7be45 ^
ba4dd92f4 ^


8ef66b973 ^
ba4dd92f4 ^

173e8c491 ^


ba4dd92f4 ^
6a94ca318 ^
e68830a95 ^
ba4dd92f4 ^





6e8ed8c6f ^
ba4dd92f4 ^








bf057f0d2 ^
da190876d ^
fe30ec83e ^
da190876d ^
669a56449 ^
da190876d ^

92b8fac94 ^
da190876d ^


92b8fac94 ^
b5b5e6e76 ^
da190876d ^



ee67a67ac ^
2df9b442c ^
da190876d ^
c95f6f117 ^
da190876d ^

92b8fac94 ^

b5b5e6e76 ^
da190876d ^
f18b3af9d ^
da190876d ^
bba551fd1 ^
bba551fd1 ^
5131b3cea ^
e6e0527fd ^
5131b3cea ^
e25474154 ^
5131b3cea ^
e25474154 ^
28394153a ^
ed6160ad6 ^




28394153a ^
5348fef00 ^
6e8ed8c6f ^
5131b3cea ^
f767e1749 ^
46efaf294 ^
9a6f47ae6 ^
5e15dec17 ^
e5bd3b5b9 ^

6bcdb9c8f ^

bba551fd1 ^
6bcdb9c8f ^

bba551fd1 ^
6bcdb9c8f ^

60b187513 ^
6bcdb9c8f ^
438703f59 ^
b9079b871 ^

f2cdbc92e ^
b9079b871 ^
60b187513 ^


6bcdb9c8f ^





e25474154 ^


6bcdb9c8f ^





60b187513 ^
1d14cb1ad ^

5e15dec17 ^

258aabba6 ^
6df259f15 ^
5e15dec17 ^

da190876d ^



34ab1d3e3 ^
fe30ec83e ^
9a6f47ae6 ^
46efaf294 ^
e25474154 ^

2c9e56a78 ^

ce859d8c1 ^
2c9e56a78 ^
ce859d8c1 ^
92b8fac94 ^
c45b714df ^
3d1c6de63 ^
c45b714df ^
92b8fac94 ^
b64eeeb43 ^

6975ba401 ^
af7c92c00 ^
39ebe2175 ^
60b187513 ^
bba551fd1 ^
46e9ff613 ^





6e8ed8c6f ^
46e9ff613 ^


bba551fd1 ^
af7c92c00 ^
355ae07b8 ^
af7c92c00 ^

46e9ff613 ^
92b8fac94 ^
af7c92c00 ^

f6f5c9e9e ^
af7c92c00 ^
2df9b442c ^
355ae07b8 ^

bba551fd1 ^
af7c92c00 ^
92b8fac94 ^
af7c92c00 ^
46e9ff613 ^
af7c92c00 ^
ce859d8c1 ^
af7c92c00 ^
bba551fd1 ^
bf698fbc2 ^




af7c92c00 ^


92b8fac94 ^
af7c92c00 ^


4d01408a4 ^
af7c92c00 ^
bba551fd1 ^
b64eeeb43 ^

ce859d8c1 ^
b64eeeb43 ^
af7c92c00 ^

b64eeeb43 ^





ce859d8c1 ^
b64eeeb43 ^
ce859d8c1 ^
bf698fbc2 ^



f18b3af9d ^
bf698fbc2 ^
af7c92c00 ^
92b8fac94 ^
af7c92c00 ^
4d01408a4 ^
92b8fac94 ^
af7c92c00 ^
f6f5c9e9e ^
bba551fd1 ^
331d1a6ca ^
af7c92c00 ^

331d1a6ca ^
af7c92c00 ^
331d1a6ca ^
af7c92c00 ^


331d1a6ca ^
af7c92c00 ^
331d1a6ca ^
af7c92c00 ^


bba551fd1 ^
331d1a6ca ^

af7c92c00 ^
331d1a6ca ^
af7c92c00 ^

bba551fd1 ^
f18b3af9d ^
af7c92c00 ^

c95f6f117 ^
af7c92c00 ^
bba551fd1 ^
af7c92c00 ^
92b8fac94 ^
af7c92c00 ^
92b8fac94 ^
af7c92c00 ^
355ae07b8 ^

af7c92c00 ^

4d01408a4 ^
f18b3af9d ^
af7c92c00 ^

1d14cb1ad ^
9a6f47ae6 ^
1786e3099 ^

258aabba6 ^
6df259f15 ^
1786e3099 ^
46efaf294 ^
af7c92c00 ^




ce859d8c1 ^
9a6f47ae6 ^
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

 
                            
                                         




                                                   

                       
           

                     
                                            
                
                       
 

             
 
                    
 




                                                                            


                                                                




                                        
                            



                                                                
                                 
                                 
                   
 





                                                                          

                    
           
                               
                 


                          
                                 
                               
                                 
                                                                 
                                                      
                                                                      


                                                 
       

                                                                  

                                                                         
                                                       
                                 
                   

                             

                                           

                                   
                                                                    
                       
                     




                                                                         
                                                    
                
                                    
                                           



                                                 
         
                               

                                    
                                                                      
                       
                                                      
                                    
 
                                                             
             

                                                     
                                       
                                 
 
    
                   
               
                                     
               
                                            
               

                                                 
      

                                                     
             

                                                      
             
              
                                       
                



                                                  
                               
              
 
                                                           
                                                        
                                                                


                                                   

                                 

                                  
                 
 
                                                          



                             







                                                          
                        
       
                             

                                                      
                                                                 
                                                                     




                                                               








                                                                  





                                                          
                                   



                                  
                                      
       

                                  









                                                                          
                                                                      
                                                                 
                        
                                                        
                                                             

                                          
                                                
                            
                                                            
         
                                      
 
                                                            
                       
                                                              
                                                            
             
               

                                                         
                      
                                       
                    
                                          
             
              
            
                                          

                                  



                                                              
                                       



                                                                           
                        
       
                              

                                                          

                                                                           
                                          


                                                                               
                                  

                                    
                           
                                          
                      



                                                           
                                                               
                             
              
                               
                                          
                         
              



                                                    
              
                              

               
                                                                              
                                

                                        

                                                                                      
                      

                             
                                              

                             
                                              
                      

                                         
                                             


                                                         
                       

                                               
                                                     
            
                                                                

             
                                         
                                       

                                                  
                             
                                      
                        
                                    
                                               
                                          
                                                  


                                                      

                                      
                        

                                          
            
                                       
                
                                          
                 

                                                    
                                           
           
              
                              

                        
                    
                                                




                                                
                
                              




                                            
                              
                       
                                       
                        
                        


                                                     
                             


                                              
                        




                                            
                

                                              
                 
                                           
                                  

                                 




                                                
                                    
                           
                                                 

                                          
                                
                                     
                                               
                              
                       
                                       
                        
                  
                        




                                                           
                                                     
                   

                                                
                    
                                     

                                          
                    
                              
                       
                                          

                                                            


                                            
                   
                              
                       
                                          

                                                           
                                        
                              
                       
                                          

                                                           
                                   



                                              
           


                                                

                                                


                                                  
                                                    





                                                     

                                               

                                               
              


                                              
                   
                                     
                                                              





                                          
                                                              


                                          
                                  




                     
                     
                                       
                                                                 

                                            




                                            
                                                                 


                                            
         

                                     


                                                   
                            
                                                                            
                                                  





                                                                 
                        








                                                
                                   
 
                                                          
            
                                                                

             
                                       


                                                  
                                    
                                               



                                            
                                           
           
       
                                                                            

                                                    

                                               
                                             
              
                              
                                                      
 
                                                   
             
                   
                                                           
                           
       
                                                 
 




                                                                           
 
                            
                     
                         
                           
                 
              
                                                       

                                                     

               
                                              

                                                                               
       

                                          
                       
                                       
                                             

                                                                               
                                               
                                


                                                     





                                                     


                                                                





                                                             
                                            

                                                          

                           
                            
                             

               



                                                             
                                                               
                                                                  
               
             

            

                                       
                                                                                 
                                       
                                                                              
                                                 
                  
                                                       
       
                                                   

                                        
 
                                                       
                                               
                                                                        
 





                                                                       
                    


                                                
 
                                                             
              

                                                  
                                  
                                    

                                               
                                                                              
           
               

                                                                         
 
                                                      
                                       
                                                             
                                
         
                                                          
                
 




                                                               


             
                                       


                                          
                                      
                 
                                                                        

                                                                           
                                                          
                                   

                                              





                                                                          
                                                            
         
                                                          



                                           
                                
                                                     
                 
                                               
                
                                                          
                                            
                            
                                                                            
 
                                                                                  

                                                                              
                                     
                                                   
                                                 


                                                     
                       
                                                   
                                                 


                                                     
 

                                                                                   
                                                   
                                                 

                                                     
 
                              

                                                   
                                                                            
                                                  
               
                              
                                         
                  
                                    
                                               

                                             

                                                        
                 
                              

                                                   
                                               
              

                           
                            
                             
           
                             




                                                 
                                                               
               
#
#
#           The Nim Compiler
#        (c) Copyright 2015 Andreas Rumpf
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

# included from sem.nim

discard """
  hygienic templates:

    template `||` (a, b: untyped): untyped =
      let aa = a
      if aa: aa else: b

    var
      a, b: T

    echo a || b || a

  Each evaluation context has to be different and we need to perform
  some form of preliminary symbol lookup in template definitions. Hygiene is
  a way to achieve lexical scoping at compile time.
"""

const
  errImplOfXNotAllowed = "implementation of '$1' is not allowed"

type
  TSymBinding = enum
    spNone, spGenSym, spInject

proc symBinding(n: PNode): TSymBinding =
  for i in 0 ..< sonsLen(n):
    var it = n.sons[i]
    var key = if it.kind == nkExprColonExpr: it.sons[0] else: it
    if key.kind == nkIdent:
      case whichKeyword(key.ident)
      of wGensym: return spGenSym
      of wInject: return spInject
      else: discard

type
  TSymChoiceRule = enum
    scClosed, scOpen, scForceOpen

proc symChoice(c: PContext, n: PNode, s: PSym, r: TSymChoiceRule): PNode =
  var
    a: PSym
    o: TOverloadIter
  var i = 0
  a = initOverloadIter(o, c, n)
  while a != nil:
    if a.kind != skModule:
      inc(i)
      if i > 1: break
    a = nextOverloadIter(o, c, n)
  let info = getCallLineInfo(n)
  if i <= 1 and r != scForceOpen:
    # XXX this makes more sense but breaks bootstrapping for now:
    # (s.kind notin routineKinds or s.magic != mNone):
    # for instance 'nextTry' is both in tables.nim and astalgo.nim ...
    result = newSymNode(s, info)
    markUsed(c.config, info, s, c.graph.usageSym)
    onUse(info, s)
  else:
    # semantic checking requires a type; ``fitNode`` deals with it
    # appropriately
    let kind = if r == scClosed or n.kind == nkDotExpr: nkClosedSymChoice
               else: nkOpenSymChoice
    result = newNodeIT(kind, info, newTypeS(tyNone, c))
    a = initOverloadIter(o, c, n)
    while a != nil:
      if a.kind != skModule:
        incl(a.flags, sfUsed)
        addSon(result, newSymNode(a, info))
        onUse(info, a)
      a = nextOverloadIter(o, c, n)

proc semBindStmt(c: PContext, n: PNode, toBind: var IntSet): PNode =
  for i in 0 ..< n.len:
    var a = n.sons[i]
    # If 'a' is an overloaded symbol, we used to use the first symbol
    # as a 'witness' and use the fact that subsequent lookups will yield
    # the same symbol!
    # This is however not true anymore for hygienic templates as semantic
    # processing for them changes the symbol table...
    let s = qualifiedLookUp(c, a, {checkUndeclared})
    if s != nil:
      # we need to mark all symbols:
      let sc = symChoice(c, n, s, scClosed)
      if sc.kind == nkSym:
        toBind.incl(sc.sym.id)
      else:
        for x in items(sc): toBind.incl(x.sym.id)
    else:
      illFormedAst(a, c.config)
  result = newNodeI(nkEmpty, n.info)

proc semMixinStmt(c: PContext, n: PNode, toMixin: var IntSet): PNode =
  for i in 0 ..< n.len:
    toMixin.incl(considerQuotedIdent(c, n.sons[i]).id)
  result = newNodeI(nkEmpty, n.info)

proc replaceIdentBySym(c: PContext; n: var PNode, s: PNode) =
  case n.kind
  of nkPostfix: replaceIdentBySym(c, n.sons[1], s)
  of nkPragmaExpr: replaceIdentBySym(c, n.sons[0], s)
  of nkIdent, nkAccQuoted, nkSym: n = s
  else: illFormedAst(n, c.config)

type
  TemplCtx = object
    c: PContext
    toBind, toMixin, toInject: IntSet
    owner: PSym
    cursorInBody: bool # only for nimsuggest
    scopeN: int

template withBracketExpr(ctx, x, body: untyped) =
  body

proc getIdentNode(c: var TemplCtx, n: PNode): PNode =
  case n.kind
  of nkPostfix: result = getIdentNode(c, n.sons[1])
  of nkPragmaExpr: result = getIdentNode(c, n.sons[0])
  of nkIdent:
    result = n
    let s = qualifiedLookUp(c.c, n, {})
    if s != nil:
      if s.owner == c.owner and s.kind == skParam:
        result = newSymNode(s, n.info)
  of nkAccQuoted, nkSym: result = n
  else:
    illFormedAst(n, c.c.config)
    result = n

proc isTemplParam(c: TemplCtx, n: PNode): bool {.inline.} =
  result = n.kind == nkSym and n.sym.kind == skParam and
           n.sym.owner == c.owner and sfGenSym notin n.sym.flags

proc semTemplBody(c: var TemplCtx, n: PNode): PNode

proc openScope(c: var TemplCtx) =
  openScope(c.c)

proc closeScope(c: var TemplCtx) =
  closeScope(c.c)

proc semTemplBodyScope(c: var TemplCtx, n: PNode): PNode =
  openScope(c)
  result = semTemplBody(c, n)
  closeScope(c)

proc onlyReplaceParams(c: var TemplCtx, n: PNode): PNode =
  result = n
  if n.kind == nkIdent:
    let s = qualifiedLookUp(c.c, n, {})
    if s != nil:
      if s.owner == c.owner and s.kind == skParam:
        incl(s.flags, sfUsed)
        result = newSymNode(s, n.info)
        onUse(n.info, s)
  else:
    for i in 0 ..< n.safeLen:
      result.sons[i] = onlyReplaceParams(c, n.sons[i])

proc newGenSym(kind: TSymKind, n: PNode, c: var TemplCtx): PSym =
  result = newSym(kind, considerQuotedIdent(c.c, n), c.owner, n.info)
  incl(result.flags, sfGenSym)
  incl(result.flags, sfShadowed)

proc addLocalDecl(c: var TemplCtx, n: var PNode, k: TSymKind) =
  # locals default to 'gensym':
  if n.kind == nkPragmaExpr and symBinding(n.sons[1]) == spInject:
    # even if injected, don't produce a sym choice here:
    #n = semTemplBody(c, n)
    var x = n[0]
    while true:
      case x.kind
      of nkPostfix: x = x[1]
      of nkPragmaExpr: x = x[0]
      of nkIdent: break
      of nkAccQuoted:
        # consider:  type `T TemplParam` {.inject.}
        # it suffices to return to treat it like 'inject':
        n = onlyReplaceParams(c, n)
        return
      else:
        illFormedAst(x, c.c.config)
    let ident = getIdentNode(c, x)
    if not isTemplParam(c, ident):
      c.toInject.incl(x.ident.id)
    else:
      replaceIdentBySym(c.c, n, ident)
  else:
    let ident = getIdentNode(c, n)
    if not isTemplParam(c, ident):
      # fix #2670, consider:
      #
      # when b:
      #    var a = "hi"
      # else:
      #    var a = 5
      # echo a
      #
      # We need to ensure that both 'a' produce the same gensym'ed symbol.
      # So we need only check the *current* scope.
      let s = localSearchInScope(c.c, considerQuotedIdent(c.c, ident))
      if s != nil and s.owner == c.owner and sfGenSym in s.flags:
        onUse(n.info, s)
        replaceIdentBySym(c.c, n, newSymNode(s, n.info))
      elif not (n.kind == nkSym and sfGenSym in n.sym.flags):
        let local = newGenSym(k, ident, c)
        addPrelimDecl(c.c, local)
        styleCheckDef(c.c.config, n.info, local)
        onDef(n.info, local)
        replaceIdentBySym(c.c, n, newSymNode(local, n.info))
    else:
      replaceIdentBySym(c.c, n, ident)

proc semTemplSymbol(c: PContext, n: PNode, s: PSym): PNode =
  incl(s.flags, sfUsed)
  # we do not call onUse here, as the identifier is not really
  # resolved here. We will fixup the used identifiers later.
  case s.kind
  of skUnknown:
    # Introduced in this pass! Leave it as an identifier.
    result = n
  of OverloadableSyms:
    result = symChoice(c, n, s, scOpen)
  of skGenericParam:
    result = newSymNodeTypeDesc(s, n.info)
  of skParam:
    result = n
  of skType:
    result = newSymNodeTypeDesc(s, n.info)
  else:
    result = newSymNode(s, n.info)

proc semRoutineInTemplName(c: var TemplCtx, n: PNode): PNode =
  result = n
  if n.kind == nkIdent:
    let s = qualifiedLookUp(c.c, n, {})
    if s != nil:
      if s.owner == c.owner and (s.kind == skParam or sfGenSym in s.flags):
        incl(s.flags, sfUsed)
        result = newSymNode(s, n.info)
        onUse(n.info, s)
  else:
    for i in 0 ..< safeLen(n):
      result.sons[i] = semRoutineInTemplName(c, n.sons[i])

proc semRoutineInTemplBody(c: var TemplCtx, n: PNode, k: TSymKind): PNode =
  result = n
  checkSonsLen(n, bodyPos + 1, c.c.config)
  # routines default to 'inject':
  if n.kind notin nkLambdaKinds and symBinding(n.sons[pragmasPos]) == spGenSym:
    let ident = getIdentNode(c, n.sons[namePos])
    if not isTemplParam(c, ident):
      var s = newGenSym(k, ident, c)
      s.ast = n
      addPrelimDecl(c.c, s)
      styleCheckDef(c.c.config, n.info, s)
      onDef(n.info, s)
      n.sons[namePos] = newSymNode(s, n.sons[namePos].info)
    else:
      n.sons[namePos] = ident
  else:
    n.sons[namePos] = semRoutineInTemplName(c, n.sons[namePos])
  # open scope for parameters
  openScope(c)
  for i in patternPos..miscPos:
    n.sons[i] = semTemplBody(c, n.sons[i])
  # open scope for locals
  inc c.scopeN
  openScope(c)
  n.sons[bodyPos] = semTemplBody(c, n.sons[bodyPos])
  # close scope for locals
  closeScope(c)
  dec c.scopeN
  # close scope for parameters
  closeScope(c)

proc semTemplSomeDecl(c: var TemplCtx, n: PNode, symKind: TSymKind; start=0) =
  for i in start ..< sonsLen(n):
    var a = n.sons[i]
    if a.kind == nkCommentStmt: continue
    if (a.kind != nkIdentDefs) and (a.kind != nkVarTuple): illFormedAst(a, c.c.config)
    checkMinSonsLen(a, 3, c.c.config)
    var L = sonsLen(a)
    when defined(nimsuggest):
      inc c.c.inTypeContext
    a.sons[L-2] = semTemplBody(c, a.sons[L-2])
    when defined(nimsuggest):
      dec c.c.inTypeContext
    a.sons[L-1] = semTemplBody(c, a.sons[L-1])
    for j in 0 .. L-3:
      addLocalDecl(c, a.sons[j], symKind)

proc semPattern(c: PContext, n: PNode): PNode

proc semTemplBodySons(c: var TemplCtx, n: PNode): PNode =
  result = n
  for i in 0 ..< n.len:
    result.sons[i] = semTemplBody(c, n.sons[i])

proc semTemplBody(c: var TemplCtx, n: PNode): PNode =
  result = n
  semIdeForTemplateOrGenericCheck(c.c.config, n, c.cursorInBody)
  case n.kind
  of nkIdent:
    if n.ident.id in c.toInject: return n
    let s = qualifiedLookUp(c.c, n, {})
    if s != nil:
      if s.owner == c.owner and s.kind == skParam:
        incl(s.flags, sfUsed)
        result = newSymNode(s, n.info)
        onUse(n.info, s)
      elif contains(c.toBind, s.id):
        result = symChoice(c.c, n, s, scClosed)
      elif contains(c.toMixin, s.name.id):
        result = symChoice(c.c, n, s, scForceOpen)
      elif s.owner == c.owner and sfGenSym in s.flags:
        # template tmp[T](x: var seq[T]) =
        # var yz: T
        incl(s.flags, sfUsed)
        result = newSymNode(s, n.info)
        onUse(n.info, s)
      else:
        result = semTemplSymbol(c.c, n, s)
  of nkBind:
    result = semTemplBody(c, n.sons[0])
  of nkBindStmt:
    result = semBindStmt(c.c, n, c.toBind)
  of nkMixinStmt:
    if c.scopeN > 0: result = semTemplBodySons(c, n)
    else: result = semMixinStmt(c.c, n, c.toMixin)
  of nkEmpty, nkSym..nkNilLit, nkComesFrom:
    discard
  of nkIfStmt:
    for i in 0 ..< sonsLen(n):
      var it = n.sons[i]
      if it.len == 2:
        openScope(c)
        it.sons[0] = semTemplBody(c, it.sons[0])
        it.sons[1] = semTemplBody(c, it.sons[1])
        closeScope(c)
      else:
        n.sons[i] = semTemplBodyScope(c, it)
  of nkWhileStmt:
    openScope(c)
    for i in 0 ..< sonsLen(n):
      n.sons[i] = semTemplBody(c, n.sons[i])
    closeScope(c)
  of nkCaseStmt:
    openScope(c)
    n.sons[0] = semTemplBody(c, n.sons[0])
    for i in 1 ..< sonsLen(n):
      var a = n.sons[i]
      checkMinSonsLen(a, 1, c.c.config)
      var L = sonsLen(a)
      for j in 0 .. L-2:
        a.sons[j] = semTemplBody(c, a.sons[j])
      a.sons[L-1] = semTemplBodyScope(c, a.sons[L-1])
    closeScope(c)
  of nkForStmt, nkParForStmt:
    var L = sonsLen(n)
    openScope(c)
    n.sons[L-2] = semTemplBody(c, n.sons[L-2])
    for i in 0 .. L - 3:
      if n[i].kind == nkVarTuple:
        for j in 0 ..< sonsLen(n[i])-1:
          addLocalDecl(c, n[i][j], skForVar)
      else:
        addLocalDecl(c, n.sons[i], skForVar)
    openScope(c)
    n.sons[L-1] = semTemplBody(c, n.sons[L-1])
    closeScope(c)
    closeScope(c)
  of nkBlockStmt, nkBlockExpr, nkBlockType:
    checkSonsLen(n, 2, c.c.config)
    openScope(c)
    if n.sons[0].kind != nkEmpty:
      addLocalDecl(c, n.sons[0], skLabel)
      when false:
        # labels are always 'gensym'ed:
        let s = newGenSym(skLabel, n.sons[0], c)
        addPrelimDecl(c.c, s)
        styleCheckDef(c.c.config, s)
        onDef(n[0].info, s)
        n.sons[0] = newSymNode(s, n.sons[0].info)
    n.sons[1] = semTemplBody(c, n.sons[1])
    closeScope(c)
  of nkTryStmt, nkHiddenTryStmt:
    checkMinSonsLen(n, 2, c.c.config)
    n.sons[0] = semTemplBodyScope(c, n.sons[0])
    for i in 1 ..< sonsLen(n):
      var a = n.sons[i]
      checkMinSonsLen(a, 1, c.c.config)
      var L = sonsLen(a)
      openScope(c)
      for j in 0 .. L-2:
        if a.sons[j].isInfixAs():
          addLocalDecl(c, a.sons[j].sons[2], skLet)
          a.sons[j].sons[1] = semTemplBody(c, a.sons[j][1])
        else:
          a.sons[j] = semTemplBody(c, a.sons[j])
      a.sons[L-1] = semTemplBodyScope(c, a.sons[L-1])
      closeScope(c)
  of nkVarSection: semTemplSomeDecl(c, n, skVar)
  of nkLetSection: semTemplSomeDecl(c, n, skLet)
  of nkFormalParams:
    checkMinSonsLen(n, 1, c.c.config)
    n.sons[0] = semTemplBody(c, n.sons[0])
    semTemplSomeDecl(c, n, skParam, 1)
  of nkConstSection:
    for i in 0 ..< sonsLen(n):
      var a = n.sons[i]
      if a.kind == nkCommentStmt: continue
      if (a.kind != nkConstDef): illFormedAst(a, c.c.config)
      checkSonsLen(a, 3, c.c.config)
      addLocalDecl(c, a.sons[0], skConst)
      a.sons[1] = semTemplBody(c, a.sons[1])
      a.sons[2] = semTemplBody(c, a.sons[2])
  of nkTypeSection:
    for i in 0 ..< sonsLen(n):
      var a = n.sons[i]
      if a.kind == nkCommentStmt: continue
      if (a.kind != nkTypeDef): illFormedAst(a, c.c.config)
      checkSonsLen(a, 3, c.c.config)
      addLocalDecl(c, a.sons[0], skType)
    for i in 0 ..< sonsLen(n):
      var a = n.sons[i]
      if a.kind == nkCommentStmt: continue
      if (a.kind != nkTypeDef): illFormedAst(a, c.c.config)
      checkSonsLen(a, 3, c.c.config)
      if a.sons[1].kind != nkEmpty:
        openScope(c)
        a.sons[1] = semTemplBody(c, a.sons[1])
        a.sons[2] = semTemplBody(c, a.sons[2])
        closeScope(c)
      else:
        a.sons[2] = semTemplBody(c, a.sons[2])
  of nkProcDef, nkLambdaKinds:
    result = semRoutineInTemplBody(c, n, skProc)
  of nkFuncDef:
    result = semRoutineInTemplBody(c, n, skFunc)
  of nkMethodDef:
    result = semRoutineInTemplBody(c, n, skMethod)
  of nkIteratorDef:
    result = semRoutineInTemplBody(c, n, skIterator)
  of nkTemplateDef:
    result = semRoutineInTemplBody(c, n, skTemplate)
  of nkMacroDef:
    result = semRoutineInTemplBody(c, n, skMacro)
  of nkConverterDef:
    result = semRoutineInTemplBody(c, n, skConverter)
  of nkPragmaExpr:
    result.sons[0] = semTemplBody(c, n.sons[0])
  of nkPostfix:
    result.sons[1] = semTemplBody(c, n.sons[1])
  of nkPragma:
    for x in n:
      if x.kind == nkExprColonExpr:
        x.sons[1] = semTemplBody(c, x.sons[1])
  of nkBracketExpr:
    result = newNodeI(nkCall, n.info)
    result.add newIdentNode(getIdent(c.c.cache, "[]"), n.info)
    for i in 0 ..< n.len: result.add(n[i])
    let n0 = semTemplBody(c, n.sons[0])
    withBracketExpr c, n0:
      result = semTemplBodySons(c, result)
  of nkCurlyExpr:
    result = newNodeI(nkCall, n.info)
    result.add newIdentNode(getIdent(c.c.cache, "{}"), n.info)
    for i in 0 ..< n.len: result.add(n[i])
    result = semTemplBodySons(c, result)
  of nkAsgn, nkFastAsgn:
    checkSonsLen(n, 2, c.c.config)
    let a = n.sons[0]
    let b = n.sons[1]

    let k = a.kind
    case k
    of nkBracketExpr:
      result = newNodeI(nkCall, n.info)
      result.add newIdentNode(getIdent(c.c.cache, "[]="), n.info)
      for i in 0 ..< a.len: result.add(a[i])
      result.add(b)
      let a0 = semTemplBody(c, a.sons[0])
      withBracketExpr c, a0:
        result = semTemplBodySons(c, result)
    of nkCurlyExpr:
      result = newNodeI(nkCall, n.info)
      result.add newIdentNode(getIdent(c.c.cache, "{}="), n.info)
      for i in 0 ..< a.len: result.add(a[i])
      result.add(b)
      result = semTemplBodySons(c, result)
    else:
      result = semTemplBodySons(c, n)
  of nkCallKinds-{nkPostfix}:
    # do not transform runnableExamples (bug #9143)
    if not isRunnableExamples(n[0]):
      result = semTemplBodySons(c, n)
  of nkDotExpr, nkAccQuoted:
    # dotExpr is ambiguous: note that we explicitly allow 'x.TemplateParam',
    # so we use the generic code for nkDotExpr too
    let s = qualifiedLookUp(c.c, n, {})
    if s != nil:
      # do not symchoice a quoted template parameter (bug #2390):
      if s.owner == c.owner and s.kind == skParam and
          n.kind == nkAccQuoted and n.len == 1:
        incl(s.flags, sfUsed)
        onUse(n.info, s)
        return newSymNode(s, n.info)
      elif contains(c.toBind, s.id):
        return symChoice(c.c, n, s, scClosed)
      elif contains(c.toMixin, s.name.id):
        return symChoice(c.c, n, s, scForceOpen)
      else:
        return symChoice(c.c, n, s, scOpen)
    result = semTemplBodySons(c, n)
  else:
    result = semTemplBodySons(c, n)

proc semTemplBodyDirty(c: var TemplCtx, n: PNode): PNode =
  result = n
  semIdeForTemplateOrGenericCheck(c.c.config, n, c.cursorInBody)
  case n.kind
  of nkIdent:
    let s = qualifiedLookUp(c.c, n, {})
    if s != nil:
      if s.owner == c.owner and s.kind == skParam:
        result = newSymNode(s, n.info)
      elif contains(c.toBind, s.id):
        result = symChoice(c.c, n, s, scClosed)
  of nkBind:
    result = semTemplBodyDirty(c, n.sons[0])
  of nkBindStmt:
    result = semBindStmt(c.c, n, c.toBind)
  of nkEmpty, nkSym..nkNilLit, nkComesFrom:
    discard
  else:
    # dotExpr is ambiguous: note that we explicitly allow 'x.TemplateParam',
    # so we use the generic code for nkDotExpr too
    if n.kind == nkDotExpr or n.kind == nkAccQuoted:
      let s = qualifiedLookUp(c.c, n, {})
      if s != nil and contains(c.toBind, s.id):
        return symChoice(c.c, n, s, scClosed)
    result = n
    for i in 0 ..< sonsLen(n):
      result.sons[i] = semTemplBodyDirty(c, n.sons[i])

proc semTemplateDef(c: PContext, n: PNode): PNode =
  var s: PSym
  if isTopLevel(c):
    s = semIdentVis(c, skTemplate, n.sons[0], {sfExported})
    incl(s.flags, sfGlobal)
  else:
    s = semIdentVis(c, skTemplate, n.sons[0], {})

  if s.owner != nil:
    const names = ["!=", ">=", ">", "incl", "excl", "in", "notin", "isnot"]
    if sfSystemModule in s.owner.flags and s.name.s in names or
       s.owner.name.s == "vm" and s.name.s == "stackTrace":
      incl(s.flags, sfCallsite)

  styleCheckDef(c.config, s)
  onDef(n[0].info, s)
  # check parameter list:
  #s.scope = c.currentScope
  pushOwner(c, s)
  openScope(c)
  n.sons[namePos] = newSymNode(s, n.sons[namePos].info)
  if n.sons[pragmasPos].kind != nkEmpty:
    pragma(c, s, n.sons[pragmasPos], templatePragmas)

  var gp: PNode
  if n.sons[genericParamsPos].kind != nkEmpty:
    n.sons[genericParamsPos] = semGenericParamList(c, n.sons[genericParamsPos])
    gp = n.sons[genericParamsPos]
  else:
    gp = newNodeI(nkGenericParams, n.info)
  # process parameters:
  var allUntyped = true
  if n.sons[paramsPos].kind != nkEmpty:
    semParamList(c, n.sons[paramsPos], gp, s)
    # a template's parameters are not gensym'ed even if that was originally the
    # case as we determine whether it's a template parameter in the template
    # body by the absence of the sfGenSym flag:
    for i in 1 .. s.typ.n.len-1:
      let param = s.typ.n.sons[i].sym
      param.flags.excl sfGenSym
      if param.typ.kind != tyExpr: allUntyped = false
    if sonsLen(gp) > 0:
      if n.sons[genericParamsPos].kind == nkEmpty:
        # we have a list of implicit type parameters:
        n.sons[genericParamsPos] = gp
    # no explicit return type? -> use tyStmt
    if n.sons[paramsPos].sons[0].kind == nkEmpty:
      # use ``stmt`` as implicit result type
      s.typ.sons[0] = newTypeS(tyStmt, c)
      s.typ.n.sons[0] = newNodeIT(nkType, n.info, s.typ.sons[0])
  else:
    s.typ = newTypeS(tyProc, c)
    # XXX why do we need tyStmt as a return type again?
    s.typ.n = newNodeI(nkFormalParams, n.info)
    rawAddSon(s.typ, newTypeS(tyStmt, c))
    addSon(s.typ.n, newNodeIT(nkType, n.info, s.typ.sons[0]))
  if allUntyped: incl(s.flags, sfAllUntyped)
  if n.sons[patternPos].kind != nkEmpty:
    n.sons[patternPos] = semPattern(c, n.sons[patternPos])
  var ctx: TemplCtx
  ctx.toBind = initIntSet()
  ctx.toMixin = initIntSet()
  ctx.toInject = initIntSet()
  ctx.c = c
  ctx.owner = s
  if sfDirty in s.flags:
    n.sons[bodyPos] = semTemplBodyDirty(ctx, n.sons[bodyPos])
  else:
    n.sons[bodyPos] = semTemplBody(ctx, n.sons[bodyPos])
  # only parameters are resolved, no type checking is performed
  semIdeForTemplateOrGeneric(c, n.sons[bodyPos], ctx.cursorInBody)
  closeScope(c)
  popOwner(c)
  s.ast = n
  result = n
  if sfCustomPragma in s.flags:
    if n.sons[bodyPos].kind != nkEmpty:
      localError(c.config, n.sons[bodyPos].info, errImplOfXNotAllowed % s.name.s)
  elif n.sons[bodyPos].kind == nkEmpty:
    localError(c.config, n.info, "implementation of '$1' expected" % s.name.s)
  var proto = searchForProc(c, c.currentScope, s)
  if proto == nil:
    addInterfaceOverloadableSymAt(c, c.currentScope, s)
  else:
    symTabReplace(c.currentScope.symbols, proto, s)
  if n.sons[patternPos].kind != nkEmpty:
    c.patterns.add(s)

proc semPatternBody(c: var TemplCtx, n: PNode): PNode =
  template templToExpand(s: untyped): untyped =
    s.kind == skTemplate and (s.typ.len == 1 or sfAllUntyped in s.flags)

  proc newParam(c: var TemplCtx, n: PNode, s: PSym): PNode =
    # the param added in the current scope is actually wrong here for
    # macros because they have a shadowed param of type 'PNimNode' (see
    # semtypes.addParamOrResult). Within the pattern we have to ensure
    # to use the param with the proper type though:
    incl(s.flags, sfUsed)
    onUse(n.info, s)
    let x = c.owner.typ.n.sons[s.position+1].sym
    assert x.name == s.name
    result = newSymNode(x, n.info)

  proc handleSym(c: var TemplCtx, n: PNode, s: PSym): PNode =
    result = n
    if s != nil:
      if s.owner == c.owner and s.kind == skParam:
        result = newParam(c, n, s)
      elif contains(c.toBind, s.id):
        result = symChoice(c.c, n, s, scClosed)
      elif templToExpand(s):
        result = semPatternBody(c, semTemplateExpr(c.c, n, s, {efNoSemCheck}))
      else:
        discard
        # we keep the ident unbound for matching instantiated symbols and
        # more flexibility

  proc expectParam(c: var TemplCtx, n: PNode): PNode =
    let s = qualifiedLookUp(c.c, n, {})
    if s != nil and s.owner == c.owner and s.kind == skParam:
      result = newParam(c, n, s)
    else:
      localError(c.c.config, n.info, "invalid expression")
      result = n

  proc stupidStmtListExpr(n: PNode): bool =
    for i in 0 .. n.len-2:
      if n[i].kind notin {nkEmpty, nkCommentStmt}: return false
    result = true

  result = n
  case n.kind
  of nkIdent:
    let s = qualifiedLookUp(c.c, n, {})
    result = handleSym(c, n, s)
  of nkBindStmt:
    result = semBindStmt(c.c, n, c.toBind)
  of nkEmpty, nkSym..nkNilLit: discard
  of nkCurlyExpr:
    # we support '(pattern){x}' to bind a subpattern to a parameter 'x';
    # '(pattern){|x}' does the same but the matches will be gathered in 'x'
    if n.len != 2:
      localError(c.c.config, n.info, "invalid expression")
    elif n.sons[1].kind == nkIdent:
      n.sons[0] = semPatternBody(c, n.sons[0])
      n.sons[1] = expectParam(c, n.sons[1])
    elif n.sons[1].kind == nkPrefix and n.sons[1].sons[0].kind == nkIdent:
      let opr = n.sons[1].sons[0]
      if opr.ident.s == "|":
        n.sons[0] = semPatternBody(c, n.sons[0])
        n.sons[1].sons[1] = expectParam(c, n.sons[1].sons[1])
      else:
        localError(c.c.config, n.info, "invalid expression")
    else:
      localError(c.c.config, n.info, "invalid expression")
  of nkStmtList, nkStmtListExpr:
    if stupidStmtListExpr(n):
      result = semPatternBody(c, n.lastSon)
    else:
      for i in 0 ..< sonsLen(n):
        result.sons[i] = semPatternBody(c, n.sons[i])
  of nkCallKinds:
    let s = qualifiedLookUp(c.c, n.sons[0], {})
    if s != nil:
      if s.owner == c.owner and s.kind == skParam: discard
      elif contains(c.toBind, s.id): discard
      elif templToExpand(s):
        return semPatternBody(c, semTemplateExpr(c.c, n, s, {efNoSemCheck}))

    if n.kind == nkInfix and (let id = considerQuotedIdent(c.c, n[0]); id != nil):
      # we interpret `*` and `|` only as pattern operators if they occur in
      # infix notation, so that '`*`(a, b)' can be used for verbatim matching:
      if id.s == "*" or id.s == "**":
        result = newNodeI(nkPattern, n.info, n.len)
        result.sons[0] = newIdentNode(id, n.info)
        result.sons[1] = semPatternBody(c, n.sons[1])
        result.sons[2] = expectParam(c, n.sons[2])
        return
      elif id.s == "|":
        result = newNodeI(nkPattern, n.info, n.len)
        result.sons[0] = newIdentNode(id, n.info)
        result.sons[1] = semPatternBody(c, n.sons[1])
        result.sons[2] = semPatternBody(c, n.sons[2])
        return

    if n.kind == nkPrefix and (let id = considerQuotedIdent(c.c, n[0]); id != nil):
      if id.s == "~":
        result = newNodeI(nkPattern, n.info, n.len)
        result.sons[0] = newIdentNode(id, n.info)
        result.sons[1] = semPatternBody(c, n.sons[1])
        return

    for i in 0 ..< sonsLen(n):
      result.sons[i] = semPatternBody(c, n.sons[i])
  else:
    # dotExpr is ambiguous: note that we explicitly allow 'x.TemplateParam',
    # so we use the generic code for nkDotExpr too
    case n.kind
    of nkDotExpr, nkAccQuoted:
      let s = qualifiedLookUp(c.c, n, {})
      if s != nil:
        if contains(c.toBind, s.id):
          return symChoice(c.c, n, s, scClosed)
        else:
          return newIdentNode(s.name, n.info)
    of nkPar:
      if n.len == 1: return semPatternBody(c, n.sons[0])
    else: discard
    for i in 0 ..< sonsLen(n):
      result.sons[i] = semPatternBody(c, n.sons[i])

proc semPattern(c: PContext, n: PNode): PNode =
  openScope(c)
  var ctx: TemplCtx
  ctx.toBind = initIntSet()
  ctx.toMixin = initIntSet()
  ctx.toInject = initIntSet()
  ctx.c = c
  ctx.owner = getCurrOwner(c)
  result = flattenStmts(semPatternBody(ctx, n))
  if result.kind in {nkStmtList, nkStmtListExpr}:
    if result.len == 1:
      result = result.sons[0]
    elif result.len == 0:
      localError(c.config, n.info, "a pattern cannot be empty")
  closeScope(c)