summary refs log blame commit diff stats
path: root/doc/regexprs.txt
blob: b7370d858ce8cebbe83f650d21cfd20cf2eb97af (plain) (tree)













































                                                                           
                                                               
                                                               
                                                           
































                                                                               
                                           





                                                                























































































                                                                               
                                                                         




                                                                             
                                                                          
                                 
                                                                           
                                     
                                                                           





































                                                                               
                                                                           














                                                                            
                                                                       






























                                                                               
Licence of the PCRE library
===========================

PCRE is a library of functions to support regular expressions whose
syntax and semantics are as close as possible to those of the Perl 5
language.

| Written by Philip Hazel
| Copyright (c) 1997-2005 University of Cambridge

----------------------------------------------------------------------

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice,
  this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.

* Neither the name of the University of Cambridge nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.


Regular expression syntax and semantics
=======================================

As the regular expressions supported by this module are enormous,
the reader is referred to http://perldoc.perl.org/perlre.html for the
full documentation of Perl's regular expressions.

Because the backslash ``\`` is a meta character both in the Nim
programming language and in regular expressions, it is strongly
recommended that one uses the *raw* strings of Nim, so that
backslashes are interpreted by the regular expression engine::

  r"\S"  # matches any character that is not whitespace

A regular expression is a pattern that is matched against a subject string
from left to right. Most characters stand for themselves in a pattern, and
match the corresponding characters in the subject. As a trivial example,
the pattern::

  The quick brown fox

matches a portion of a subject string that is identical to itself.
The power of regular expressions comes from the ability to include
alternatives and repetitions in the pattern. These are encoded in
the pattern by the use of metacharacters, which do not stand for
themselves but instead are interpreted in some special way.

There are two different sets of metacharacters: those that are recognized
anywhere in the pattern except within square brackets, and those that are
recognized in square brackets. Outside square brackets, the metacharacters
are as follows:

==============     ============================================================
meta character     meaning
==============     ============================================================
``\``              general escape character with several uses
``^``              assert start of string (or line, in multiline mode)
``$``              assert end of string (or line, in multiline mode)
``.``              match any character except newline (by default)
``[``              start character class definition
``|``              start of alternative branch
``(``              start subpattern
``)``              end subpattern
``{``              start min/max quantifier
``?``              extends the meaning of ``(``
                   | also 0 or 1 quantifier (equal to ``{0,1}``)
                   | also quantifier minimizer
``*``              0 or more quantifier (equal to ``{0,}``)
``+``              1 or more quantifier (equal to ``{1,}``)
                   | also "possessive quantifier"
==============     ============================================================


Part of a pattern that is in square brackets is called a "character class".
In a character class the only metacharacters are:

==============     ============================================================
meta character     meaning
==============     ============================================================
``\``              general escape character
``^``              negate the class, but only if the first character
``-``              indicates character range
``[``              POSIX character class (only if followed by POSIX syntax)
``]``              terminates the character class
==============     ============================================================


The following sections describe the use of each of the metacharacters.


Backslash
---------
The `backslash`:idx: character has several uses. Firstly, if it is followed
by a non-alphanumeric character, it takes away any special meaning that
character may have. This use of backslash as an escape character applies
both inside and outside character classes.

For example, if you want to match a ``*`` character, you write ``\*`` in
the pattern. This escaping action applies whether or not the following
character would otherwise be interpreted as a metacharacter, so it is always
safe to precede a non-alphanumeric with backslash to specify that it stands
for itself. In particular, if you want to match a backslash, you write ``\\``.


Non-printing characters
-----------------------
A second use of backslash provides a way of encoding non-printing characters
in patterns in a visible manner. There is no restriction on the appearance of
non-printing characters, apart from the binary zero that terminates a pattern,
but when a pattern is being prepared by text editing, it is usually easier to
use one of the following escape sequences than the binary character it
represents::

==============     ============================================================
character          meaning
==============     ============================================================
``\a``             alarm, that is, the BEL character (hex 07)
``\e``             escape (hex 1B)
``\f``             formfeed (hex 0C)
``\n``             newline (hex 0A)
``\r``             carriage return (hex 0D)
``\t``             tab (hex 09)
``\ddd``           character with octal code ddd, or backreference
``\xhh``           character with hex code hh
==============     ============================================================

After ``\x``, from zero to two hexadecimal digits are read (letters can be in
upper or lower case). In UTF-8 mode, any number of hexadecimal digits may
appear between ``\x{`` and ``}``, but the value of the character code must be
less than 2**31 (that is, the maximum hexadecimal value is 7FFFFFFF). If
characters other than hexadecimal digits appear between ``\x{`` and ``}``, or
if there is no terminating ``}``, this form of escape is not recognized.
Instead, the initial ``\x`` will be interpreted as a basic hexadecimal escape,
with no following digits, giving a character whose value is zero.

After ``\0`` up to two further octal digits are read. In both cases, if there
are fewer than two digits, just those that are present are used. Thus the
sequence ``\0\x\07`` specifies two binary zeros followed by a BEL character
(code value 7). Make sure you supply two digits after the initial zero if
the pattern character that follows is itself an octal digit.

The handling of a backslash followed by a digit other than 0 is complicated.
Outside a character class, PCRE reads it and any following digits as a
decimal number. If the number is less than 10, or if there have been at least
that many previous capturing left parentheses in the expression, the entire
sequence is taken as a back reference. A description of how this works is
given later, following the discussion of parenthesized subpatterns.

Inside a character class, or if the decimal number is greater than 9 and
there have not been that many capturing subpatterns, PCRE re-reads up to
three octal digits following the backslash, and generates a single byte
from the least significant 8 bits of the value. Any subsequent digits stand
for themselves. For example:

==============     ============================================================
example            meaning
==============     ============================================================
``\040``           is another way of writing a space
``\40``            is the same, provided there are fewer than 40 previous
                   capturing subpatterns
``\7``             is always a back reference
``\11``            might be a back reference, or another way of writing a tab
``\011``           is always a tab
``\0113``          is a tab followed by the character "3"
``\113``           might be a back reference, otherwise the character with
                   octal code 113
``\377``           might be a back reference, otherwise the byte consisting
                   entirely of 1 bits
``\81``            is either a back reference, or a binary zero followed by
                   the two characters "8" and "1"
==============     ============================================================

Note that octal values of 100 or greater must not be introduced by a leading
zero, because no more than three octal digits are ever read.

All the sequences that define a single byte value or a single UTF-8 character
(in UTF-8 mode) can be used both inside and outside character classes. In
addition, inside a character class, the sequence ``\b`` is interpreted as the
backspace character (hex 08), and the sequence ``\X`` is interpreted as the
character "X". Outside a character class, these sequences have different
meanings (see below).

Generic character types
-----------------------
The third use of backslash is for specifying `generic character types`:idx:.
The following are always recognized:

==============     ============================================================
character type     meaning
==============     ============================================================
``\d``             any decimal digit
``\D``             any character that is not a decimal digit
``\s``             any whitespace character
``\S``             any character that is not a whitespace character
``\w``             any "word" character
``\W``             any "non-word" character
==============     ============================================================

Each pair of escape sequences partitions the complete set of characters into
two disjoint sets. Any given character matches one, and only one, of each pair.

These character type sequences can appear both inside and outside character
classes. They each match one character of the appropriate type. If the
current matching point is at the end of the subject string, all of them fail,
since there is no character to match.

For compatibility with Perl, ``\s`` does not match the VT character (code 11).
This makes it different from the POSIX "space" class. The ``\s`` characters
are HT (9), LF (10), FF (12), CR (13), and space (32).

A "word" character is an underscore or any character less than 256 that is
a letter or digit. The definition of letters and digits is controlled by
PCRE's low-valued character tables, and may vary if locale-specific matching
is taking place (see "Locale support" in the pcreapi page). For example,
in the "fr_FR" (French) locale, some character codes greater than 128 are
used for accented letters, and these are matched by ``\w``.

In UTF-8 mode, characters with values greater than 128 never match ``\d``,
``\s``, or ``\w``, and always match ``\D``, ``\S``, and ``\W``. This is true
even when Unicode character property support is available.

Simple assertions
-----------------
The fourth use of backslash is for certain `simple assertions`:idx:. An
assertion specifies a condition that has to be met at a particular point in
a match, without consuming any characters from the subject string. The use of
subpatterns for more complicated assertions is described below. The
backslashed assertions are::

==============     ============================================================
assertion          meaning
==============     ============================================================
``\b``             matches at a word boundary
``\B``             matches when not at a word boundary
``\A``             matches at start of subject
``\Z``             matches at end of subject or before newline at end
``\z``             matches at end of subject
``\G``             matches at first matching position in subject
==============     ============================================================

These assertions may not appear in character classes (but note that ``\b``
has a different meaning, namely the backspace character, inside a character
class).

A word boundary is a position in the subject string where the current
character and the previous character do not both match ``\w`` or ``\W`` (i.e.
one matches ``\w`` and the other matches ``\W``), or the start or end of the
string if the first or last character matches ``\w``, respectively.

The ``\A``, ``\Z``, and ``\z`` assertions differ from the traditional
circumflex and dollar in that they only ever match at the very start and
end of the subject string, whatever options are set.
The difference between ``\Z`` and ``\z`` is that ``\Z`` matches before
a newline that is the last character of the string as well as at the end
of the string, whereas ``\z`` matches only at the end.
g.nim?h=devel&id=5e570bae479209b60f5cb7c92d60f2e1b1083320'>5e570bae4 ^
244c14db0 ^

d5b01dfb7 ^
15dad22a0 ^
f191059e5 ^

92b8fac94 ^
f191059e5 ^
244c14db0 ^
5e570bae4 ^

244c14db0 ^
92b8fac94 ^
244c14db0 ^
9257c29ff ^

244c14db0 ^
f191059e5 ^
d5b01dfb7 ^

92b8fac94 ^

15dad22a0 ^
d5b01dfb7 ^
92b8fac94 ^
f191059e5 ^
d5b01dfb7 ^

15dad22a0 ^
d5b01dfb7 ^


73c6efdf6 ^
d5b01dfb7 ^


15dad22a0 ^
15dad22a0 ^
92b8fac94 ^
15dad22a0 ^




991b3096e ^
9257c29ff ^
5e570bae4 ^
fc858927f ^


991b3096e ^
9257c29ff ^
991b3096e ^


15dad22a0 ^

244c14db0 ^
2633e3fb2 ^

15dad22a0 ^


3f8732624 ^


d5b01dfb7 ^

92b8fac94 ^

d5b01dfb7 ^

92b8fac94 ^
3f8732624 ^
2633e3fb2 ^
15dad22a0 ^


244c14db0 ^





1785c6877 ^
244c14db0 ^














15dad22a0 ^
632aece19 ^
2633e3fb2 ^
2c4a1dbc0 ^



15dad22a0 ^

2633e3fb2 ^
73c6efdf6 ^
2633e3fb2 ^
d5b01dfb7 ^

15dad22a0 ^
2294c02cc ^
d5b01dfb7 ^





15dad22a0 ^

92b8fac94 ^
37229df7f ^


3f8732624 ^

15dad22a0 ^
73c6efdf6 ^
15dad22a0 ^



2c4a1dbc0 ^
7b539c9e5 ^




15dad22a0 ^
991b3096e ^
15dad22a0 ^

73c6efdf6 ^
15dad22a0 ^
d5b01dfb7 ^

15dad22a0 ^

f191059e5 ^

7d05356df ^
f191059e5 ^
2294c02cc ^



37229df7f ^


15dad22a0 ^


d5b01dfb7 ^
15dad22a0 ^




d5b01dfb7 ^
7b539c9e5 ^
d5b01dfb7 ^
15dad22a0 ^

d5b01dfb7 ^
15dad22a0 ^




73c6efdf6 ^
15dad22a0 ^
7b4560337 ^
92b8fac94 ^
7b539c9e5 ^
92b8fac94 ^
7b4560337 ^
15dad22a0 ^


7b539c9e5 ^
92b8fac94 ^
7b4560337 ^
15dad22a0 ^
92b8fac94 ^
3f8732624 ^

15dad22a0 ^

73c6efdf6 ^
2633e3fb2 ^
15dad22a0 ^

2633e3fb2 ^
d57fe6c90 ^








15dad22a0 ^






2633e3fb2 ^
d01ff8994 ^




d5b01dfb7 ^
d01ff8994 ^





15dad22a0 ^
d01ff8994 ^
15dad22a0 ^
2633e3fb2 ^

15dad22a0 ^
2633e3fb2 ^
15dad22a0 ^
2633e3fb2 ^

98458a307 ^

5e15dec17 ^

98458a307 ^
d57fe6c90 ^
92b8fac94 ^
d5b01dfb7 ^



d57fe6c90 ^
d01ff8994 ^














632aece19 ^
3f8732624 ^











































15dad22a0 ^
20b6dc382 ^
15dad22a0 ^
73c6efdf6 ^
15dad22a0 ^

3f8732624 ^




92b8fac94 ^
d5b01dfb7 ^
d01ff8994 ^









f191059e5 ^








d01ff8994 ^
f191059e5 ^


d5b01dfb7 ^
92b8fac94 ^
d5b01dfb7 ^

15dad22a0 ^

d5b01dfb7 ^

15dad22a0 ^

5e15dec17 ^
92b8fac94 ^
5e15dec17 ^
15dad22a0 ^

37229df7f ^


3f8732624 ^

15dad22a0 ^
73c6efdf6 ^
244c14db0 ^



3f8732624 ^





15dad22a0 ^
3f8732624 ^






















2633e3fb2 ^
20b6dc382 ^
27ec76dd3 ^

1785c6877 ^
15dad22a0 ^

15dad22a0 ^
d5b01dfb7 ^
7b539c9e5 ^
d5b01dfb7 ^
a6e0679ae ^



92b8fac94 ^
a6e0679ae ^
92b8fac94 ^
603dc3600 ^


92b8fac94 ^
15dad22a0 ^
3f8732624 ^




7d6500f1d ^
244c14db0 ^
1785c6877 ^
7d6500f1d ^
244c14db0 ^









7a2c11d3c ^

7a2c11d3c ^

1465a7b08 ^
37229df7f ^

7a2c11d3c ^

7a2c11d3c ^






814fcb263 ^
1fada12a5 ^
814fcb263 ^














244c14db0 ^
814fcb263 ^
244c14db0 ^
814fcb263 ^







ed28f3c8d ^
438703f59 ^
814fcb263 ^






37229df7f ^
814fcb263 ^








244c14db0 ^
814fcb263 ^









1fada12a5 ^



814fcb263 ^

92b8fac94 ^
814fcb263 ^





7a2c11d3c ^




814fcb263 ^

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


                               
                                         






                                                                    






































                                                                              
                     

                  
                                                    


















































                                                                              
     
                                                     
                     
                   
 
    

                                   




                                    
                                                                 
                                                                    
                                          

              




                                  

                                  
                                    
                    
                                          

                                              
                                
                                               
                     
 





















































































                                                                             
                                                                        

                
                                    
                                 
                                        

                                  

                                                                        
  
                                               
             

                                        
 








                                                        


                                       


                                                                         






                                            
                                                                      


                                    
                              


                         
                                                                 
                           
                                           
                           
                                  
                                                 

                               
                                    
                       


                                   

                                                         
 



                                   
 
                                                       

                                                                     
                                          
                              
 
                                                 









                                                              
                     



                                                             

                                             

                                                 
                                               

                                                     

                        
                                                                 
                                  

                                                                              
                                                 
                      
  

                                                           
                                                                     
                                                      
                               

                                                                        
                                     
 

                                                                        

                                             
 
                              
                                                           
                                                 

                                               
                                         


                                                         
           


                                                              
                                              
                                
                                                 




                                                                            
                                     
                                                                         
                                                        


                                                         
                                    
                                                                       


                                                                              

                                                                
                     

             


                                                   


                                                       

                                                                            

                                                                     

                                               
                                                                          
                                                                    
       


                                         





                                                                              
                                       














                                                                   
                                                          
                                              
                             



                                                            

                                                                              
             
                                                         
           

                  
                                                         
                                               





                                                                            

                        
                                                      


                                                        

                                                                       
                         
           



                                                 
 




                                            
                                                      
                     

                                                  
           
           

                                                                              

                                

                                                                       
                                                   
                                   



                                                    


                                             


                                                                           
                                                                            




                                                                    
                             
                                               
                                           

                                        
                         




                                                                           
                                          
                                  
                           
                                                                             
                                                                        
                                                               
                                            


                                 
                                                                          
                                                                 
                                            
           
                                                

                                                                        

                                              
           
       

                                        
 








                                                                              






                                           
 




                                                                      
 





                                                     
 
                                                                          
                                         

                                          
               
                        
                                                  

                              

                                                          

                                              
                                 
                                                                       
                                                        



                                                                
                                                          














                                                                    
 











































                                                                                
                                                            
                         
             
                                                         

                     




                                                                             
                                                         
                      









                                                                          








                                                                      
                                  


                                            
                                                     
                                                    

                                

                                     

                                                                  

                                                                         
                                    
                                                    
                                                        

                                                                             


                                                     

                                                                       
                         
           



                                              





                                               
       






















                                                                        
 
                                                 

                                                                            
                                                    

                                 
       
                               
                                       
                                      



                                                                  
                                                                 
                                    
                                                    


                                                                      
                                                                      
                                




                                         
 
                                                                
                                                    
                 









                                                                              

                                                                        

                                
 

                                                   

                                         






                                                  
                                       
                                                                     














                                                                  
             
                         
 







                              
                  
                                                                         






                                                              
                     








                                                    
  









                                                                          



                                

                                                 
                   





                                                                




                                                                    

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

# This include file implements lambda lifting for the transformator.

import 
  intsets, strutils, lists, options, ast, astalgo, trees, treetab, msgs, os, 
  idents, renderer, types, magicsys, rodread

discard """
  The basic approach is that captured vars need to be put on the heap and
  that the calling chain needs to be explicitely modelled. Things to consider:
  
  proc a =
    var v = 0
    proc b =
      var w = 2
      
      for x in 0..3:
        proc c = capture v, w, x
        c()
    b()
    
    for x in 0..4:
      proc d = capture x
      d()
  
  Needs to be translated into:
    
  proc a =
    var cl: *
    new cl
    cl.v = 0
    
    proc b(cl) =
      var bcl: *
      new bcl
      bcl.w = 2
      bcl.up = cl
      
      for x in 0..3:
        var bcl2: *
        new bcl2
        bcl2.up = bcl
        bcl2.up2 = cl
        bcl2.x = x
      
        proc c(cl) = capture cl.up2.v, cl.up.w, cl.x
        c(bcl2)
      
      c(bcl)
    
    b(cl)
    
    for x in 0..4:
      var acl2: *
      new acl2
      acl2.x = x
      proc d(cl) = capture cl.x
      d(acl2)
    
  Closures as interfaces:
  
  proc outer: T =
    var captureMe: TObject # value type required for efficiency
    proc getter(): int = result = captureMe.x
    proc setter(x: int) = captureMe.x = x
    
    result = (getter, setter)
    
  Is translated to:
  
  proc outer: T =
    var cl: *
    new cl
    
    proc getter(cl): int = result = cl.captureMe.x
    proc setter(cl: *, x: int) = cl.captureMe.x = x
    
    result = ((cl, getter), (cl, setter))
    
    
  For 'byref' capture, the outer proc needs to access the captured var through
  the indirection too. For 'bycopy' capture, the outer proc accesses the var
  not through the indirection.
    
  Possible optimizations: 
  
  1) If the closure contains a single 'ref' and this
  reference is not re-assigned (check ``sfAddrTaken`` flag) make this the
  closure. This is an important optimization if closures are used as 
  interfaces.
  2) If the closure does not escape, put it onto the stack, not on the heap.
  3) Dataflow analysis would help to eliminate the 'up' indirections.
  4) If the captured var is not actually used in the outer proc (common?),
  put it into an inner proc.

"""

const
  upName* = ":up" # field name for the 'up' reference
  paramName* = ":env"
  envName* = ":env"

type
  PInnerContext = ref TInnerContext
  POuterContext = ref TOuterContext

  PEnv = ref TEnv
  TDep = tuple[e: PEnv, field: PSym]
  TEnv {.final.} = object of TObject
    attachedNode: PNode
    createdVar: PSym         # if != nil it is a used environment
    capturedVars: seq[PSym] # captured variables in this environment
    deps: seq[TDep]         # dependencies
    up: PEnv
    tup: PType
  
  TInnerContext {.final.} = object
    fn: PSym
    closureParam: PSym
    localsToAccess: TIdNodeTable
    
  TOuterContext {.final.} = object
    fn: PSym # may also be a module!
    currentEnv: PEnv
    isIter: bool   # first class iterator?
    capturedVars, processed: TIntSet
    localsToEnv: TIdTable # PSym->PEnv mapping
    localsToAccess: TIdNodeTable
    lambdasToEnv: TIdTable # PSym->PEnv mapping
    up: POuterContext

    closureParam, state, resultSym: PSym # only if isIter
    tup: PType # only if isIter


proc getStateType(iter: PSym): PType =
  var n = newNodeI(nkRange, iter.info)
  addSon(n, newIntNode(nkIntLit, -1))
  addSon(n, newIntNode(nkIntLit, 0))
  result = newType(tyRange, iter)
  result.n = n
  rawAddSon(result, getSysType(tyInt))

proc createStateField(iter: PSym): PSym =
  result = newSym(skField, getIdent(":state"), iter, iter.info)
  result.typ = getStateType(iter)

proc newIterResult(iter: PSym): PSym =
  if resultPos < iter.ast.len:
    result = iter.ast.sons[resultPos].sym
  else:
    # XXX a bit hacky:
    result = newSym(skResult, getIdent":result", iter, iter.info)
    result.typ = iter.typ.sons[0]
    incl(result.flags, sfUsed)
    iter.ast.add newSymNode(result)

proc addHiddenParam(routine: PSym, param: PSym) =
  var params = routine.ast.sons[paramsPos]
  # -1 is correct here as param.position is 0 based but we have at position 0
  # some nkEffect node:
  param.position = params.len-1
  addSon(params, newSymNode(param))
  incl(routine.typ.flags, tfCapturesEnv)
  #echo "produced environment: ", param.id, " for ", routine.name.s

proc getHiddenParam(routine: PSym): PSym =
  let params = routine.ast.sons[paramsPos]
  let hidden = lastSon(params)
  assert hidden.kind == nkSym
  result = hidden.sym

proc getEnvParam(routine: PSym): PSym =
  let params = routine.ast.sons[paramsPos]
  let hidden = lastSon(params)
  if hidden.kind == nkSym and hidden.sym.name.s == paramName:
    result = hidden.sym
    
proc addField(tup: PType, s: PSym) =
  var field = newSym(skField, s.name, s.owner, s.info)
  let t = skipIntLit(s.typ)
  field.typ = t
  field.position = sonsLen(tup)
  addSon(tup.n, newSymNode(field))
  rawAddSon(tup, t)

proc initIterContext(c: POuterContext, iter: PSym) =
  c.fn = iter
  c.capturedVars = initIntSet()

  var cp = getEnvParam(iter)
  if cp == nil:
    c.tup = newType(tyTuple, iter)
    c.tup.n = newNodeI(nkRecList, iter.info)

    cp = newSym(skParam, getIdent(paramName), iter, iter.info)
    incl(cp.flags, sfFromGeneric)
    cp.typ = newType(tyRef, iter)
    rawAddSon(cp.typ, c.tup)
    addHiddenParam(iter, cp)

    c.state = createStateField(iter)
    addField(c.tup, c.state)
  else:
    c.tup = cp.typ.sons[0]
    assert c.tup.kind == tyTuple
    if c.tup.len > 0:
      c.state = c.tup.n[0].sym
    else:
      c.state = createStateField(iter)
      addField(c.tup, c.state)

  c.closureParam = cp
  if iter.typ.sons[0] != nil:
    c.resultSym = newIterResult(iter)
    #iter.ast.add(newSymNode(c.resultSym))

proc newOuterContext(fn: PSym, up: POuterContext = nil): POuterContext =
  new(result)
  result.fn = fn
  result.capturedVars = initIntSet()
  result.processed = initIntSet()
  initIdNodeTable(result.localsToAccess)
  initIdTable(result.localsToEnv)
  initIdTable(result.lambdasToEnv)
  result.isIter = fn.kind == skIterator and fn.typ.callConv == ccClosure
  if result.isIter: initIterContext(result, fn)
  
proc newInnerContext(fn: PSym): PInnerContext =
  new(result)
  result.fn = fn
  initIdNodeTable(result.localsToAccess)

proc newEnv(outerProc: PSym, up: PEnv, n: PNode): PEnv =
  new(result)
  result.deps = @[]
  result.capturedVars = @[]
  result.tup = newType(tyTuple, outerProc)
  result.tup.n = newNodeI(nkRecList, outerProc.info)
  result.up = up
  result.attachedNode = n

proc addCapturedVar(e: PEnv, v: PSym) =
  for x in e.capturedVars:
    if x == v: return
  # XXX meh, just add the state field for every closure for now, it's too
  # hard to figure out if it comes from a closure iterator:
  if e.tup.len == 0: addField(e.tup, createStateField(v.owner))
  e.capturedVars.add(v)
  addField(e.tup, v)
  
proc addDep(e, d: PEnv, owner: PSym): PSym =
  for x, field in items(e.deps):
    if x == d: return field
  var pos = sonsLen(e.tup)
  result = newSym(skField, getIdent(upName & $pos), owner, owner.info)
  result.typ = newType(tyRef, owner)
  result.position = pos
  assert d.tup != nil
  rawAddSon(result.typ, d.tup)
  addField(e.tup, result)
  e.deps.add((d, result))
  
proc indirectAccess(a: PNode, b: PSym, info: TLineInfo): PNode = 
  # returns a[].b as a node
  var deref = newNodeI(nkHiddenDeref, info)
  deref.typ = a.typ.sons[0]
  assert deref.typ.kind == tyTuple
  let field = getSymFromList(deref.typ.n, b.name)
  assert field != nil, b.name.s
  addSon(deref, a)
  result = newNodeI(nkDotExpr, info)
  addSon(result, deref)
  addSon(result, newSymNode(field))
  result.typ = field.typ

proc indirectAccess(a, b: PSym, info: TLineInfo): PNode =
  result = indirectAccess(newSymNode(a), b, info)

proc newCall(a, b: PSym): PNode =
  result = newNodeI(nkCall, a.info)
  result.add newSymNode(a)
  result.add newSymNode(b)

proc isInnerProc(s, outerProc: PSym): bool {.inline.} =
  result = (s.kind in {skProc, skMethod, skConverter} or
            s.kind == skIterator and s.typ.callConv == ccClosure) and
           s.skipGenericOwner == outerProc
  #s.typ.callConv == ccClosure

proc addClosureParam(i: PInnerContext, e: PEnv) =
  var cp = getEnvParam(i.fn)
  if cp == nil:
    cp = newSym(skParam, getIdent(paramName), i.fn, i.fn.info)
    incl(cp.flags, sfFromGeneric)
    cp.typ = newType(tyRef, i.fn)
    rawAddSon(cp.typ, e.tup)
    addHiddenParam(i.fn, cp)
  else:
    e.tup = cp.typ.sons[0]
    assert e.tup.kind == tyTuple
  i.closureParam = cp
  #echo "closure param added for ", i.fn.name.s, " ", i.fn.id

proc dummyClosureParam(o: POuterContext, i: PInnerContext) =
  var e = o.currentEnv
  if idTableGet(o.lambdasToEnv, i.fn) == nil:
    idTablePut(o.lambdasToEnv, i.fn, e)
  if i.closureParam == nil: addClosureParam(i, e)

proc illegalCapture(s: PSym): bool {.inline.} =
  result = skipTypes(s.typ, abstractInst).kind in 
                   {tyVar, tyOpenArray, tyVarargs} or
      s.kind == skResult

proc captureVar(o: POuterContext, i: PInnerContext, local: PSym, 
                info: TLineInfo) =
  # for inlined variables the owner is still wrong, so it can happen that it's
  # not a captured variable at all ... *sigh* 
  var it = PEnv(idTableGet(o.localsToEnv, local))
  if it == nil: return
  
  if illegalCapture(local) or o.fn.id != local.owner.id or 
      i.fn.typ.callConv notin {ccClosure, ccDefault}:
    # Currently captures are restricted to a single level of nesting:
    localError(info, errIllegalCaptureX, local.name.s)
  i.fn.typ.callConv = ccClosure
  #echo "captureVar ", i.fn.name.s, i.fn.id, " ", local.name.s, local.id

  incl(i.fn.typ.flags, tfCapturesEnv)

  # we need to remember which inner most closure belongs to this lambda:
  var e = o.currentEnv
  if idTableGet(o.lambdasToEnv, i.fn) == nil:
    idTablePut(o.lambdasToEnv, i.fn, e)

  # variable already captured:
  if idNodeTableGet(i.localsToAccess, local) != nil: return
  if i.closureParam == nil: addClosureParam(i, e)
  
  # check which environment `local` belongs to:
  var access = newSymNode(i.closureParam)
  addCapturedVar(it, local)
  if it == e:
    # common case: local directly in current environment:
    discard
  else:
    # it's in some upper environment:
    access = indirectAccess(access, addDep(e, it, i.fn), info)
  access = indirectAccess(access, local, info)
  incl(o.capturedVars, local.id)
  idNodeTablePut(i.localsToAccess, local, access)

proc interestingVar(s: PSym): bool {.inline.} =
  result = s.kind in {skVar, skLet, skTemp, skForVar, skParam, skResult} and
    sfGlobal notin s.flags

proc semCaptureSym*(s, owner: PSym) =
  if interestingVar(s) and owner.id != s.owner.id and s.kind != skResult:
    if owner.typ != nil and not isGenericRoutine(owner):
      # XXX: is this really safe?
      # if we capture a var from another generic routine,
      # it won't be consider captured.
      owner.typ.callConv = ccClosure
    #echo "semCaptureSym ", owner.name.s, owner.id, " ", s.name.s, s.id
    # since the analysis is not entirely correct, we don't set 'tfCapturesEnv'
    # here

proc gatherVars(o: POuterContext, i: PInnerContext, n: PNode) = 
  # gather used vars for closure generation
  if n == nil: return
  case n.kind
  of nkSym:
    var s = n.sym
    if interestingVar(s) and i.fn.id != s.owner.id:
      captureVar(o, i, s, n.info)
    elif s.kind in {skProc, skMethod, skConverter} and
            s.skipGenericOwner == o.fn and 
            tfCapturesEnv in s.typ.flags and s != i.fn:
      # call to some other inner proc; we need to track the dependencies for
      # this:
      let env = PEnv(idTableGet(o.lambdasToEnv, i.fn))
      if env == nil: internalError(n.info, "no environment computed")
      if o.currentEnv != env:
        discard addDep(o.currentEnv, env, i.fn)
        internalError(n.info, "too complex environment handling required")
  of nkEmpty..pred(nkSym), succ(nkSym)..nkNilLit, nkClosure: discard
  else:
    for k in countup(0, sonsLen(n) - 1): 
      gatherVars(o, i, n.sons[k])

proc generateThunk(prc: PNode, dest: PType): PNode =
  ## Converts 'prc' into '(thunk, nil)' so that it's compatible with
  ## a closure.
  
  # we cannot generate a proper thunk here for GC-safety reasons (see internal
  # documentation):
  if gCmd == cmdCompileToJS: return prc
  result = newNodeIT(nkClosure, prc.info, dest)
  var conv = newNodeIT(nkHiddenStdConv, prc.info, dest)
  conv.add(emptyNode)
  conv.add(prc)
  result.add(conv)
  result.add(newNodeIT(nkNilLit, prc.info, getSysType(tyNil)))

proc transformOuterConv(n: PNode): PNode =
  # numeric types need range checks:
  var dest = skipTypes(n.typ, abstractVarRange)
  var source = skipTypes(n.sons[1].typ, abstractVarRange)
  if dest.kind == tyProc:
    if dest.callConv == ccClosure and source.callConv == ccDefault:
      result = generateThunk(n.sons[1], dest)

proc makeClosure(prc, env: PSym, info: TLineInfo): PNode =
  result = newNodeIT(nkClosure, info, prc.typ)
  result.add(newSymNode(prc))
  if env == nil:
    result.add(newNodeIT(nkNilLit, info, getSysType(tyNil)))
  else:
    result.add(newSymNode(env))

proc transformInnerProc(o: POuterContext, i: PInnerContext, n: PNode): PNode =
  case n.kind
  of nkEmpty..pred(nkSym), succ(nkSym)..nkNilLit: discard
  of nkSym:
    let s = n.sym
    if s == i.fn: 
      # recursive calls go through (lambda, hiddenParam):
      assert i.closureParam != nil, i.fn.name.s
      result = makeClosure(s, i.closureParam, n.info)
    elif isInnerProc(s, o.fn) and s.typ.callConv == ccClosure:
      # ugh: call to some other inner proc; 
      assert i.closureParam != nil
      # XXX this is not correct in general! may also be some 'closure.upval'
      result = makeClosure(s, i.closureParam, n.info)
    else:
      # captured symbol?
      result = idNodeTableGet(i.localsToAccess, n.sym)
  of nkLambdaKinds, nkIteratorDef:
    if n.typ != nil:
      result = transformInnerProc(o, i, n.sons[namePos])
  of nkProcDef, nkMethodDef, nkConverterDef, nkMacroDef, nkTemplateDef,
      nkClosure:
    # don't recurse here:
    discard
  else:
    for j in countup(0, sonsLen(n) - 1):
      let x = transformInnerProc(o, i, n.sons[j])
      if x != nil: n.sons[j] = x

proc closureCreationPoint(n: PNode): PNode =
  result = newNodeI(nkStmtList, n.info)
  result.add(emptyNode)
  result.add(n)

proc searchForInnerProcs(o: POuterContext, n: PNode) =
  if n == nil: return
  case n.kind
  of nkEmpty..pred(nkSym), succ(nkSym)..nkNilLit: 
    discard
  of nkSym:
    if isInnerProc(n.sym, o.fn) and not containsOrIncl(o.processed, n.sym.id):
      var inner = newInnerContext(n.sym)
      let body = n.sym.getBody
      gatherVars(o, inner, body)
      # dummy closure param needed?
      if inner.closureParam == nil and n.sym.typ.callConv == ccClosure:
        #assert tfCapturesEnv notin n.sym.typ.flags
        dummyClosureParam(o, inner)
      # only transform if it really needs a closure:
      if inner.closureParam != nil:
        let ti = transformInnerProc(o, inner, body)
        if ti != nil: n.sym.ast.sons[bodyPos] = ti
  of nkLambdaKinds, nkIteratorDef:
    if n.typ != nil:
      searchForInnerProcs(o, n.sons[namePos])
  of nkWhileStmt, nkForStmt, nkParForStmt, nkBlockStmt:
    # some nodes open a new scope, so they are candidates for the insertion
    # of closure creation; however for simplicity we merge closures between
    # branches, in fact, only loop bodies are of interest here as only they 
    # yield observable changes in semantics. For Zahary we also
    # include ``nkBlock``.
    var body = n.len-1
    for i in countup(0, body - 1): searchForInnerProcs(o, n.sons[i])
    # special handling for the loop body:
    let oldEnv = o.currentEnv
    let ex = closureCreationPoint(n.sons[body])
    o.currentEnv = newEnv(o.fn, oldEnv, ex)
    searchForInnerProcs(o, n.sons[body])
    n.sons[body] = ex
    o.currentEnv = oldEnv
  of nkVarSection, nkLetSection:
    # we need to compute a mapping var->declaredBlock. Note: The definition
    # counts, not the block where it is captured!
    for i in countup(0, sonsLen(n) - 1):
      var it = n.sons[i]
      if it.kind == nkCommentStmt: discard
      elif it.kind == nkIdentDefs:
        var L = sonsLen(it)
        if it.sons[0].kind != nkSym: internalError(it.info, "transformOuter")
        #echo "set: ", it.sons[0].sym.name.s, " ", o.currentBlock == nil
        idTablePut(o.localsToEnv, it.sons[0].sym, o.currentEnv)
        searchForInnerProcs(o, it.sons[L-1])
      elif it.kind == nkVarTuple:
        var L = sonsLen(it)
        for j in countup(0, L-3):
          #echo "set: ", it.sons[j].sym.name.s, " ", o.currentBlock == nil
          idTablePut(o.localsToEnv, it.sons[j].sym, o.currentEnv)
        searchForInnerProcs(o, it.sons[L-1])
      else:
        internalError(it.info, "transformOuter")
  of nkProcDef, nkMethodDef, nkConverterDef, nkMacroDef, nkTemplateDef, 
     nkClosure:
    # don't recurse here:
    # XXX recurse here and setup 'up' pointers
    discard
  else:
    for i in countup(0, sonsLen(n) - 1):
      searchForInnerProcs(o, n.sons[i])

proc newAsgnStmt(le, ri: PNode, info: TLineInfo): PNode = 
  # Bugfix: unfortunately we cannot use 'nkFastAsgn' here as that would
  # mean to be able to capture string literals which have no GC header.
  # However this can only happen if the capture happens through a parameter,
  # which is however the only case when we generate an assignment in the first
  # place.
  result = newNodeI(nkAsgn, info, 2)
  result.sons[0] = le
  result.sons[1] = ri

proc addVar*(father, v: PNode) = 
  var vpart = newNodeI(nkIdentDefs, v.info)
  addSon(vpart, v)
  addSon(vpart, ast.emptyNode)
  addSon(vpart, ast.emptyNode)
  addSon(father, vpart)

proc newClosureCreationVar(o: POuterContext; e: PEnv): PSym =
  result = newSym(skVar, getIdent(envName), o.fn, e.attachedNode.info)
  incl(result.flags, sfShadowed)
  result.typ = newType(tyRef, o.fn)
  result.typ.rawAddSon(e.tup)

proc getClosureVar(o: POuterContext; e: PEnv): PSym =
  if e.createdVar == nil:
    result = newClosureCreationVar(o, e)
    e.createdVar = result
  else:
    result = e.createdVar

proc rawClosureCreation(o: POuterContext, scope: PEnv; env: PSym): PNode =
  result = newNodeI(nkStmtList, env.info)
  var v = newNodeI(nkVarSection, env.info)
  addVar(v, newSymNode(env))
  result.add(v)
  # add 'new' statement:
  result.add(newCall(getSysSym"internalNew", env))
  
  # add assignment statements:
  for local in scope.capturedVars:
    let fieldAccess = indirectAccess(env, local, env.info)
    if local.kind == skParam:
      # maybe later: (sfByCopy in local.flags)
      # add ``env.param = param``
      result.add(newAsgnStmt(fieldAccess, newSymNode(local), env.info))
    idNodeTablePut(o.localsToAccess, local, fieldAccess)
  # add support for 'up' references:
  for e, field in items(scope.deps):
    # add ``env.up = env2``
    result.add(newAsgnStmt(indirectAccess(env, field, env.info),
               newSymNode(getClosureVar(o, e)), env.info))
  
proc generateClosureCreation(o: POuterContext, scope: PEnv): PNode =
  var env = getClosureVar(o, scope)
  result = rawClosureCreation(o, scope, env)

proc generateIterClosureCreation(o: POuterContext; env: PEnv;
                                 scope: PNode): PSym =
  result = newClosureCreationVar(o, env)
  let cc = rawClosureCreation(o, env, result)
  var insertPoint = scope.sons[0]
  if insertPoint.kind == nkEmpty: scope.sons[0] = cc
  else:
    assert cc.kind == nkStmtList and insertPoint.kind == nkStmtList
    for x in cc: insertPoint.add(x)
  if env.createdVar == nil: env.createdVar = result

proc interestingIterVar(s: PSym): bool {.inline.} =
  result = s.kind in {skVar, skLet, skTemp, skForVar} and sfGlobal notin s.flags

proc transformOuterProc(o: POuterContext, n: PNode): PNode

proc transformYield(c: POuterContext, n: PNode): PNode =
  inc c.state.typ.n.sons[1].intVal
  let stateNo = c.state.typ.n.sons[1].intVal

  var stateAsgnStmt = newNodeI(nkAsgn, n.info)
  stateAsgnStmt.add(indirectAccess(newSymNode(c.closureParam),c.state,n.info))
  stateAsgnStmt.add(newIntTypeNode(nkIntLit, stateNo, getSysType(tyInt)))

  var retStmt = newNodeI(nkReturnStmt, n.info)
  if n.sons[0].kind != nkEmpty:
    var a = newNodeI(nkAsgn, n.sons[0].info)
    var retVal = transformOuterProc(c, n.sons[0])
    addSon(a, newSymNode(c.resultSym))
    addSon(a, if retVal.isNil: n.sons[0] else: retVal)
    retStmt.add(a)
  else:
    retStmt.add(emptyNode)
  
  var stateLabelStmt = newNodeI(nkState, n.info)
  stateLabelStmt.add(newIntTypeNode(nkIntLit, stateNo, getSysType(tyInt)))
  
  result = newNodeI(nkStmtList, n.info)
  result.add(stateAsgnStmt)
  result.add(retStmt)
  result.add(stateLabelStmt)

proc transformReturn(c: POuterContext, n: PNode): PNode =
  result = newNodeI(nkStmtList, n.info)
  var stateAsgnStmt = newNodeI(nkAsgn, n.info)
  stateAsgnStmt.add(indirectAccess(newSymNode(c.closureParam),c.state,n.info))
  stateAsgnStmt.add(newIntTypeNode(nkIntLit, -1, getSysType(tyInt)))
  result.add(stateAsgnStmt)
  result.add(n)

proc outerProcSons(o: POuterContext, n: PNode) =
  for i in countup(0, sonsLen(n) - 1):
    let x = transformOuterProc(o, n.sons[i])
    if x != nil: n.sons[i] = x

proc transformOuterProc(o: POuterContext, n: PNode): PNode =
  if n == nil: return nil
  case n.kind
  of nkEmpty..pred(nkSym), succ(nkSym)..nkNilLit: discard
  of nkSym:
    var local = n.sym

    if o.isIter and interestingIterVar(local) and o.fn.id == local.owner.id:
      if not containsOrIncl(o.capturedVars, local.id): addField(o.tup, local)
      return indirectAccess(newSymNode(o.closureParam), local, n.info)

    var closure = PEnv(idTableGet(o.lambdasToEnv, local))
    if closure != nil:
      # we need to replace the lambda with '(lambda, env)':
      if local.kind == skIterator and local.typ.callConv == ccClosure:
        # consider: [i1, i2, i1]  Since we merged the iterator's closure
        # with the captured owning variables, we need to generate the
        # closure generation code again:
        let createdVar = generateIterClosureCreation(o, closure,
                                                     closure.attachedNode)
        return makeClosure(local, createdVar, n.info)
      
      let a = closure.createdVar
      if a != nil:
        return makeClosure(local, a, n.info)
      else:
        # can happen for dummy closures:
        var scope = closure.attachedNode
        assert scope.kind == nkStmtList
        if scope.sons[0].kind == nkEmpty:
          # change the empty node to contain the closure construction:
          scope.sons[0] = generateClosureCreation(o, closure)
        let x = closure.createdVar
        assert x != nil
        return makeClosure(local, x, n.info)
    
    if not contains(o.capturedVars, local.id): return
    var env = PEnv(idTableGet(o.localsToEnv, local))
    if env == nil: return
    var scope = env.attachedNode
    assert scope.kind == nkStmtList
    if scope.sons[0].kind == nkEmpty:
      # change the empty node to contain the closure construction:
      scope.sons[0] = generateClosureCreation(o, env)
    
    # change 'local' to 'closure.local', unless it's a 'byCopy' variable:
    # if sfByCopy notin local.flags:
    result = idNodeTableGet(o.localsToAccess, local)
    assert result != nil, "cannot find: " & local.name.s
    # else it is captured by copy and this means that 'outer' should continue
    # to access the local as a local.
  of nkLambdaKinds, nkIteratorDef:
    if n.typ != nil:
      result = transformOuterProc(o, n.sons[namePos])
  of nkProcDef, nkMethodDef, nkConverterDef, nkMacroDef, nkTemplateDef,
      nkClosure:
    # don't recurse here:
    discard
  of nkHiddenStdConv, nkHiddenSubConv, nkConv:
    let x = transformOuterProc(o, n.sons[1])
    if x != nil: n.sons[1] = x
    result = transformOuterConv(n)
  of nkYieldStmt:
    if o.isIter: result = transformYield(o, n)
    else: outerProcSons(o, n)
  of nkReturnStmt:
    if o.isIter: result = transformReturn(o, n)
    else: outerProcSons(o, n)
  else:
    outerProcSons(o, n)

proc liftIterator(c: POuterContext, body: PNode): PNode =
  let iter = c.fn
  result = newNodeI(nkStmtList, iter.info)
  var gs = newNodeI(nkGotoState, iter.info)
  gs.add(indirectAccess(newSymNode(c.closureParam), c.state, iter.info))
  result.add(gs)
  var state0 = newNodeI(nkState, iter.info)
  state0.add(newIntNode(nkIntLit, 0))
  result.add(state0)
  
  let newBody = transformOuterProc(c, body)
  if newBody != nil:
    result.add(newBody)
  else:
    result.add(body)

  var stateAsgnStmt = newNodeI(nkAsgn, iter.info)
  stateAsgnStmt.add(indirectAccess(newSymNode(c.closureParam),
                    c.state,iter.info))
  stateAsgnStmt.add(newIntTypeNode(nkIntLit, -1, getSysType(tyInt)))
  result.add(stateAsgnStmt)

proc liftLambdas*(fn: PSym, body: PNode): PNode =
  # XXX gCmd == cmdCompileToJS does not suffice! The compiletime stuff needs
  # the transformation even when compiling to JS ...
  if body.kind == nkEmpty or gCmd == cmdCompileToJS:
    # ignore forward declaration:
    result = body
  else:
    var o = newOuterContext(fn)
    let ex = closureCreationPoint(body)
    o.currentEnv = newEnv(fn, nil, ex)
    # put all params into the environment so they can be captured:
    let params = fn.typ.n
    for i in 1.. <params.len: 
      if params.sons[i].kind != nkSym:
        internalError(params.info, "liftLambdas: strange params")
      let param = params.sons[i].sym
      idTablePut(o.localsToEnv, param, o.currentEnv)
    # put the 'result' into the environment so it can be captured:
    let ast = fn.ast
    if resultPos < sonsLen(ast) and ast.sons[resultPos].kind == nkSym:
      idTablePut(o.localsToEnv, ast.sons[resultPos].sym, o.currentEnv)
    searchForInnerProcs(o, body)
    if o.isIter:
      result = liftIterator(o, ex)
    else:
      discard transformOuterProc(o, body)
      result = ex

proc liftLambdasForTopLevel*(module: PSym, body: PNode): PNode =
  if body.kind == nkEmpty or gCmd == cmdCompileToJS:
    result = body
  else:
    var o = newOuterContext(module)
    let ex = closureCreationPoint(body)
    o.currentEnv = newEnv(module, nil, ex)
    searchForInnerProcs(o, body)
    discard transformOuterProc(o, body)
    result = ex

# ------------------- iterator transformation --------------------------------

proc liftIterSym*(n: PNode): PNode =
  # transforms  (iter)  to  (let env = newClosure[iter](); (iter, env)) 
  let iter = n.sym
  assert iter.kind == skIterator

  result = newNodeIT(nkStmtListExpr, n.info, n.typ)
  
  var env = copySym(getHiddenParam(iter))
  env.kind = skLet
  var v = newNodeI(nkVarSection, n.info)
  addVar(v, newSymNode(env))
  result.add(v)
  # add 'new' statement:
  result.add(newCall(getSysSym"internalNew", env))
  result.add makeClosure(iter, env, n.info)

proc liftForLoop*(body: PNode): PNode =
  # problem ahead: the iterator could be invoked indirectly, but then
  # we don't know what environment to create here: 
  # 
  # iterator count(): int =
  #   yield 0
  # 
  # iterator count2(): int =
  #   var x = 3
  #   yield x
  #   inc x
  #   yield x
  # 
  # proc invoke(iter: iterator(): int) =
  #   for x in iter(): echo x
  #
  # --> When to create the closure? --> for the (count) occurence!
  discard """
      for i in foo(): ...

    Is transformed to:
      
      cl = createClosure()
      while true:
        let i = foo(cl)
        nkBreakState(cl.state)
        ...
    """
  var L = body.len
  internalAssert body.kind == nkForStmt and body[L-2].kind in nkCallKinds
  var call = body[L-2]

  result = newNodeI(nkStmtList, body.info)
  
  # static binding?
  var env: PSym
  if call[0].kind == nkSym and call[0].sym.kind == skIterator:
    # createClosure()
    let iter = call[0].sym
    assert iter.kind == skIterator
    env = copySym(getHiddenParam(iter))

    var v = newNodeI(nkVarSection, body.info)
    addVar(v, newSymNode(env))
    result.add(v)
    # add 'new' statement:
    result.add(newCall(getSysSym"internalNew", env))
  
  var loopBody = newNodeI(nkStmtList, body.info, 3)
  var whileLoop = newNodeI(nkWhileStmt, body.info, 2)
  whileLoop.sons[0] = newIntTypeNode(nkIntLit, 1, getSysType(tyBool))
  whileLoop.sons[1] = loopBody
  result.add whileLoop
  
  # setup loopBody:
  # gather vars in a tuple:
  var v2 = newNodeI(nkLetSection, body.info)
  var vpart = newNodeI(if L == 3: nkIdentDefs else: nkVarTuple, body.info)
  for i in 0 .. L-3: 
    assert body[i].kind == nkSym
    body[i].sym.kind = skLet
    addSon(vpart, body[i])

  addSon(vpart, ast.emptyNode) # no explicit type
  if not env.isNil:
    call.sons[0] = makeClosure(call.sons[0].sym, env, body.info)
  addSon(vpart, call)
  addSon(v2, vpart)

  loopBody.sons[0] = v2
  var bs = newNodeI(nkBreakState, body.info)
  #if not env.isNil:
  #  bs.addSon(indirectAccess(env, 
  #    newSym(skField, getIdent":state", env, env.info), body.info))
  #else:
  bs.addSon(call.sons[0])
  loopBody.sons[1] = bs
  loopBody.sons[2] = body[L-1]