summary refs log tree commit diff stats
path: root/lib/nimhcr.nim
Commit message (Collapse)AuthorAgeFilesLines
* fix nimrtl and nimhcr on arc/orc (#21814)metagn2023-05-091-6/+10
| | | | | | | | | | | * fix/workaround for nimrtl and nimhcr on arc/orc fixes #21803 * try fix clang, debug linux failure * just make duplicated procs not rtl * actual fix for duplicated procs
* fixes #20526; use `nimPreviewSlimSystem` for documentation build (#20714)ringabout2022-11-011-0/+3
| | | | | | | * fixes #20526; use `nimPreviewSlimSystem` for `koch docs` * fixes documentation errors * fixes remaning issues
* make implicit cstring conversions explicit (#19488)ee72022-08-191-7/+7
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | The Nim manual says that an implicit conversion to cstring will eventually not be allowed [1]: A Nim `string` is implicitly convertible to `cstring` for convenience. [...] Even though the conversion is implicit, it is not *safe*: The garbage collector does not consider a `cstring` to be a root and may collect the underlying memory. For this reason, the implicit conversion will be removed in future releases of the Nim compiler. Certain idioms like conversion of a `const` string to `cstring` are safe and will remain to be allowed. And from Nim 1.6.0, such a conversion triggers a warning [2]: A dangerous implicit conversion to `cstring` now triggers a `[CStringConv]` warning. This warning will become an error in future versions! Use an explicit conversion like `cstring(x)` in order to silence the warning. However, some files in this repo produced such a warning. For example, before this commit, compiling `parsejson.nim` would produce: /foo/Nim/lib/pure/parsejson.nim(221, 37) Warning: implicit conversion to 'cstring' from a non-const location: my.buf; this will become a compile time error in the future [CStringConv] /foo/Nim/lib/pure/parsejson.nim(231, 39) Warning: implicit conversion to 'cstring' from a non-const location: my.buf; this will become a compile time error in the future [CStringConv] This commit resolves the most visible `CStringConv` warnings, making the cstring conversions explicit. [1] https://github.com/nim-lang/Nim/blob/d2318d9ccfe6/doc/manual.md#cstring-type [2] https://github.com/nim-lang/Nim/blob/d2318d9ccfe6/changelogs/changelog_1_6_0.md#type-system
* fixes #17647 (#17667)Andreas Rumpf2021-04-071-4/+4
|
* use single backtick (#17100)flywind2021-02-181-1/+1
|
* fix some warnings (#16952)flywind2021-02-081-2/+2
|
* styleCheck: Fix some inconsistent identifiers (#16177)ee72020-12-211-2/+2
|
* testament: generic N-fold batching: windows CI 37mn=>16m (#14823)Timothee Cour2020-06-271-0/+4
| | | | | | | | | * testament: run CI faster thanks to batching * move ta_in, tstdin into existing tosproc * move ta_out,tafalse,texitcode,tstderr into existing tosproc * joinable osproc * move tstdout into existing tosproc * spec: batchable; fix tests * fixup
* hotfix: make 'nim doc nimhcr' work on all platformsAraq2020-03-231-33/+33
|
* style fix: change 'JS' to 'js' to make it consistent (#13168)Miran2020-01-161-2/+2
|
* fix several typos in documentation and comments (#12553)Nindaleth2019-10-301-2/+2
|
* [ci skip] Add note to nimhcr.nim (#12050)nc-x2019-08-261-0/+1
|
* - adding _actual as a suffix only for calls to an actual proc and not ↵Viktor Kirilov2019-08-231-1/+1
| | | | | | through a global function pointer - fixes https://github.com/nim-lang/Nim/issues/11996 (#12007) - adding forward declarations for reloadable functions within a module - fix compilation errors when 2 such functions reference each other - fixes https://github.com/nim-lang/Nim/issues/11608 - preserve permissions of copied executable binaries
* Fix HCR crash because certain procs were hcrGetProc'ed before being ↵nc-x2019-08-181-1/+1
| | | | hcrRegisterProc'ed (#11971)
* style improvements; fixes #11774Araq2019-07-191-3/+3
|
* improvements on the hot code reloading support (#10892)Viktor Kirilov2019-03-231-7/+14
| | | | | | | | * calling the "_actual" versions of functions when defined within the same module - slowdown for the snappy compression is now down from x6 to x4-x5 when HCR is ON * dynamically linking to the runtime for VS when HCR is on - binaries are smaller * compilerProcs are also called using the _actual direct version within the module they are defined (system)! * updated comments & goals * handling VS-compatible compilers on Windows in a cleaner way * now the .dll/.so files end up in the nimcache even when --nimcache isn't explicitly stated
* Don't include the nimhcr dev docs in the system module documentation (#10759)zah2019-03-081-180/+180
|
* Initial version of the hot-code reloading support for native targets (#10729)zah2019-02-261-0/+652
* squashed work by Zahary * squashing a ton of useful history... otherwise rebasing on top of upstream Nim after commit 82c009a2cbc5d07ab9a847f1c58228a20efaf219 would be impossible. * Code review changes; Working test suite (without code reloading enabled) * - documentation - implemented the HCR test - almost works... - fix the issue on Unix where for executable targets the source file for the main module of a project in nimcache was being overwritten with the binary itself (and thus the actual source code was lost) - fixing embedded paths to shared objects on unix (the "lib" prefix was being prepended to the entire path instead of just the filename) - other fixes - removing unnecessary includes since that file is already included in chcks.nim which is in turn included in system.nim (and previously was getting imported in chcks.nim but then system.nim improts something... and that breaks HCR (perhaps it could be fixed but it would be nice not to import anything in system)) * fix for clang & C++ - explicitly casting a function pointer to void* more stable mangling of parameter names when HCR is on the length of the static arrays in the DatInit functions is now part of the name of the variables, so when they get resized they get also recreated more stable mangling for inline functions - no longer depends on the module which first used them work on the new complicated HCR test - turned surprisingly complex - WIP test now successfully passes even when re-running `koch test` (previously when the nimcache wasn't cold that lead to errors) better documentation calling setStackBottomWith for PreMain passes over the HcrInit/DatInit/Init calls of all modules are now in the proper order (first all of one type, then all of the next). Also typeinfo globals are registered (created) in a single pass before the DatInit pass (because of the way generic instantiations are handled) Fix the test suite execution on macOs fix for being able to query the program arguments when using HCR on posix! other fixes * Bugfix: Fix a compilation error in C++ mode when a function pointer is converted to a raw pointer * basic documentation for the new hot code reloading semantics * Add change log entry * Don't re-execute the top-level statements while reloading JS code * fix a number of tests broken in a recent bugfix * Review changes * Added {.executeOnReload.} pragma that indicates top-level statements that should be executed on each reload. To make this work, I've modified the way the `if (hcr_init_) {...}` guards are produced in the init code. This still needs more work as the new guards seem to be inserted within the previously generated guards. This change also removes the need for `lastRegistedGlobal` in nimhcr. * Implemented the `signatureHash` magic and the `hasModuleChanged` API depending on it (the actual logic is not imlemented yet). * Add the "hcr" prefix to all HCR-related symbols in the system module. Added a new `hotcodereloading` module exporting the high-level API to the user. Besides being more hygienic, this was also required in order to make it possible to use macros in the high-level API. Without the split, `system` would have to import `macros`, which was going to produce the well-known init problems. * Attempted to solve the "GC markers problem". Crashes were expected with the previous code, because the GC markers were compiled as normal procs are registered in the GC. When their module is unloaded, dangling pointers will remain in the GC tables. To solve this issue, I don't register any GC markers when HCR is on, but I add them to the HCR globals metadata and I use a single marker registed in nimhcr during the initialization of the system module that will be responsible for marking all globals. * fix a compilation error * - implemented the hasModuleChanged functionality - tuples can be returned and broken into different vars in global scope - added comments for the closnig scopes of the if statements in the init proc - the new executeOnReload pragma works now! - other fixes * finally! fixing this hack in a proper way - declaring the destructor out of line (out of the class body) - we no longer need to forward-declare popCurrentExceptionEx * Force full module parsing This is a temporary hack that breaks some tests. I'll investigate later how these can be fixed. * tuples are now properly handled when global! * these comments mess up the codegen in debug mode when $n is not actually a new line (or something like that) - these labels are intended only for GOTO labels anyway... * "solved" the issue with the .pdb locks on windows when a binary is being debugged and hot code reloading is used at the same time * fixes after rebasing... * small fixes for the test * better handling of globals! no more compiler crashes for locals with the global pragma, also simplified code around loops in global scope which have local vars (actually globals) * we can now use the global pragma even for ... globals! * the right output * lets try those boehm GC tests * after the test is ran it will be at its starting state - no git modifications * clarification in the docs * removed unnecessary line directives for forward declarations of functions - they were causing trouble with hot code reloading when no semantic change propagates to the main module but a line directive got changed and thus the main module had to be recompiled since the .c code had changed * fixed bug! was inserting duplicate keys into the table and later was removing only 1 copy of all the duplicates (after a few reloads) * no longer breaking into DatInit code when not supposed to * fixes after rebasing * yet more fixes after rebasing * Update jssys.nim * Rework the HCR path-handling logic After reviewing the code more carefully, I've noticed that the old logic will be broken when the user overrides the '--out:f' compiler option. Besides fixing this issues, I took the opportunity to implement the missing '--outdir:d' option. Other changes: * ./koch test won't overwrite any HCR and RTL builds located in nim/lib * HCR and RTL are compiled with --threads:on by default * Clean up the globals registration logic * Handle non-flattened top-level stmtlists in JS as well * The HCR is not supported with the Boehm GC yet Also fixes some typos and the expected output of the HCR integration test * The GC marker procs are now properly used as trampolines * Fix the HCR integration test in release builds * Fix ./koch tools * this forward declaration doesn't seem to be necessary, and in fact breaks HCR because a 2nd function pointer is emitted for this externed/rtl func * the forward declaration I removed in the last commit was actually necessary * Attempt to make all tests green * Fix tgenscript * BAT file for running the HCR integration test on Windows [skip ci] * Fix the docgen tests * A final fix for Travis (hopefully)
7'>e25474154 ^
ade67f1ab ^
e25474154 ^














dab64b5c0 ^
e25474154 ^




bab74b6dc ^





e25474154 ^






e25474154 ^





































dab64b5c0 ^
e25474154 ^

















d10973adb ^
e25474154 ^























































































e25474154 ^
ade67f1ab ^
e25474154 ^



ade67f1ab ^

e25474154 ^











































e25474154 ^










ade67f1ab ^

e25474154 ^





e25474154 ^

dab64b5c0 ^

e25474154 ^
































e25474154 ^



dab64b5c0 ^

e25474154 ^





































f46870fe1 ^
e25474154 ^









e25474154 ^
ade67f1ab ^

e25474154 ^
ade67f1ab ^


e25474154 ^

ade67f1ab ^
e25474154 ^













































ade67f1ab ^
e25474154 ^


























































































































































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963


                               
                                         







                                                                      
                                                        




































                                                                                                        
                                  






                                                                             

                                                  


































                                                                                
                             
           




                            
           

















                                                     
                                              










                                                                      
                           
                   
                                       
                     

























































                                                                                
                                    
           
                                        
                                                         





















                                                                     
                                       









                                                                       
                           

                                                    




                                                           























                                                                                        
                                          















                                                                        
                           







































                                                                                      
                           








































                                                                                
                                         









                                                                     
                           





















                                                                      
                                       







                                                                           
                           














                                                                                 
             




                                                





                                                                           






                                                          





































                                                                            
                    

















                                                                   
                                                        























































































                                                                     
                      
                         



                                     

                           











































                                                                              










                                                                          

                               





                                       

               

                                       
































                                                                                



                               

                                       





































                                                                                
                                









                                                                             
                                           

                                                                         
               


                                            

             
                                               













































                                                                                
                           


























































































































































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

# this module contains routines for accessing and iterating over types

import 
  intsets, ast, astalgo, trees, msgs, strutils, platform

proc firstOrd*(t: PType): biggestInt
proc lastOrd*(t: PType): biggestInt
proc lengthOrd*(t: PType): biggestInt
type 
  TPreferedDesc* = enum 
    preferName, preferDesc

proc TypeToString*(typ: PType, prefer: TPreferedDesc = preferName): string
proc getProcHeader*(sym: PSym): string
proc base*(t: PType): PType
  # ------------------- type iterator: ----------------------------------------
type 
  TTypeIter* = proc (t: PType, closure: PObject): bool # should return true if the iteration should stop
  TTypeMutator* = proc (t: PType, closure: PObject): PType # copy t and mutate it
  TTypePredicate* = proc (t: PType): bool

proc IterOverType*(t: PType, iter: TTypeIter, closure: PObject): bool
  # Returns result of `iter`.
proc mutateType*(t: PType, iter: TTypeMutator, closure: PObject): PType
  # Returns result of `iter`.
proc SameType*(x, y: PType): bool
proc SameTypeOrNil*(a, b: PType): bool
proc equalOrDistinctOf*(x, y: PType): bool
type 
  TParamsEquality* = enum     # they are equal, but their
                              # identifiers or their return
                              # type differ (i.e. they cannot be
                              # overloaded)
                              # this used to provide better error messages
    paramsNotEqual,           # parameters are not equal
    paramsEqual,              # parameters are equal
    paramsIncompatible

proc equalParams*(a, b: PNode): TParamsEquality
  # returns whether the parameter lists of the procs a, b are exactly the same
proc isOrdinalType*(t: PType): bool
proc enumHasHoles*(t: PType): bool
const 
  abstractPtrs* = {tyVar, tyPtr, tyRef, tyGenericInst, tyDistinct, tyOrdinal}
  abstractVar* = {tyVar, tyGenericInst, tyDistinct, tyOrdinal}
  abstractRange* = {tyGenericInst, tyRange, tyDistinct, tyOrdinal}
  abstractVarRange* = {tyGenericInst, tyRange, tyVar, tyDistinct, tyOrdinal}
  abstractInst* = {tyGenericInst, tyDistinct, tyOrdinal}

  skipPtrs* = {tyVar, tyPtr, tyRef, tyGenericInst}

proc skipTypes*(t: PType, kinds: TTypeKinds): PType
proc elemType*(t: PType): PType
proc containsObject*(t: PType): bool
proc containsGarbageCollectedRef*(typ: PType): bool
proc containsHiddenPointer*(typ: PType): bool
proc canFormAcycle*(typ: PType): bool
proc isCompatibleToCString*(a: PType): bool
proc getOrdValue*(n: PNode): biggestInt
proc computeSize*(typ: PType): biggestInt
proc getSize*(typ: PType): biggestInt
proc isPureObject*(typ: PType): bool
proc inheritanceDiff*(a, b: PType): int
  # | returns: 0 iff `a` == `b`
  # | returns: -x iff `a` is the x'th direct superclass of `b`
  # | returns: +x iff `a` is the x'th direct subclass of `b`
  # | returns: `maxint` iff `a` and `b` are not compatible at all
proc InvalidGenericInst*(f: PType): bool
  # for debugging
type 
  TTypeFieldResult* = enum 
    frNone,                   # type has no object type field 
    frHeader,                 # type has an object type field only in the header
    frEmbedded                # type has an object type field somewhere embedded

proc analyseObjectWithTypeField*(t: PType): TTypeFieldResult
  # this does a complex analysis whether a call to ``objectInit`` needs to be
  # made or intializing of the type field suffices or if there is no type field
  # at all in this type.
proc typeAllowed*(t: PType, kind: TSymKind): bool
# implementation

proc InvalidGenericInst(f: PType): bool = 
  result = (f.kind == tyGenericInst) and (lastSon(f) == nil)

proc inheritanceDiff(a, b: PType): int = 
  # conversion to superclass?
  var x = a
  result = 0
  while (x != nil): 
    if x.id == b.id: return 
    x = x.sons[0]
    dec(result)
  var y = b
  result = 0
  while (y != nil): 
    if y.id == a.id: return 
    y = y.sons[0]
    inc(result)
  result = high(int)

proc isPureObject(typ: PType): bool = 
  var t: PType
  t = typ
  while t.sons[0] != nil: t = t.sons[0]
  result = (t.sym != nil) and (sfPure in t.sym.flags)

proc getOrdValue(n: PNode): biggestInt = 
  case n.kind
  of nkCharLit..nkInt64Lit: result = n.intVal
  of nkNilLit: result = 0
  else: 
    LocalError(n.info, errOrdinalTypeExpected)
    result = 0

proc isCompatibleToCString(a: PType): bool = 
  result = false
  if a.kind == tyArray: 
    if (firstOrd(a.sons[0]) == 0) and
        (skipTypes(a.sons[0], {tyRange}).kind in {tyInt..tyInt64}) and
        (a.sons[1].kind == tyChar): 
      result = true
  
proc getProcHeader(sym: PSym): string = 
  result = sym.name.s & '('
  var n = sym.typ.n
  for i in countup(1, sonsLen(n) - 1): 
    var p = n.sons[i]
    if (p.kind != nkSym): InternalError("getProcHeader")
    add(result, p.sym.name.s)
    add(result, ": ")
    add(result, typeToString(p.sym.typ))
    if i != sonsLen(n) - 1: add(result, ", ")
  add(result, ')')
  if n.sons[0].typ != nil: result = result & ": " & typeToString(n.sons[0].typ)
  
proc elemType(t: PType): PType = 
  assert(t != nil)
  case t.kind
  of tyGenericInst, tyDistinct: result = elemType(lastSon(t))
  of tyArray, tyArrayConstr: result = t.sons[1]
  else: result = t.sons[0]
  assert(result != nil)

proc skipGeneric(t: PType): PType = 
  result = t
  while result.kind == tyGenericInst: result = lastSon(result)
  
proc skipRange(t: PType): PType = 
  result = t
  while result.kind == tyRange: result = base(result)
  
proc skipAbstract(t: PType): PType = 
  result = t
  while result.kind in {tyRange, tyGenericInst}: result = lastSon(result)
  
proc skipVar(t: PType): PType = 
  result = t
  while result.kind == tyVar: result = result.sons[0]
  
proc skipVarGeneric(t: PType): PType = 
  result = t
  while result.kind in {tyGenericInst, tyVar}: result = lastSon(result)
  
proc skipPtrsGeneric(t: PType): PType = 
  result = t
  while result.kind in {tyGenericInst, tyVar, tyPtr, tyRef}: 
    result = lastSon(result)
  
proc skipVarGenericRange(t: PType): PType = 
  result = t
  while result.kind in {tyGenericInst, tyVar, tyRange}: result = lastSon(result)
  
proc skipGenericRange(t: PType): PType = 
  result = t
  while result.kind in {tyGenericInst, tyVar, tyRange}: result = lastSon(result)
  
proc skipTypes(t: PType, kinds: TTypeKinds): PType = 
  result = t
  while result.kind in kinds: result = lastSon(result)
  
proc isOrdinalType(t: PType): bool = 
  assert(t != nil)
  result = (t.Kind in {tyChar, tyInt..tyInt64, tyBool, tyEnum}) or
      (t.Kind in {tyRange, tyOrdinal}) and isOrdinalType(t.sons[0])

proc enumHasHoles(t: PType): bool = 
  var b = t
  while b.kind == tyRange: b = b.sons[0]
  result = b.Kind == tyEnum and tfEnumHasHoles in b.flags

proc iterOverTypeAux(marker: var TIntSet, t: PType, iter: TTypeIter, 
                     closure: PObject): bool
proc iterOverNode(marker: var TIntSet, n: PNode, iter: TTypeIter, 
                  closure: PObject): bool = 
  result = false
  if n != nil: 
    case n.kind
    of nkNone..nkNilLit: 
      # a leaf
      result = iterOverTypeAux(marker, n.typ, iter, closure)
    else: 
      for i in countup(0, sonsLen(n) - 1): 
        result = iterOverNode(marker, n.sons[i], iter, closure)
        if result: return 
  
proc iterOverTypeAux(marker: var TIntSet, t: PType, iter: TTypeIter, 
                     closure: PObject): bool = 
  result = false
  if t == nil: return 
  result = iter(t, closure)
  if result: return 
  if not ContainsOrIncl(marker, t.id): 
    case t.kind
    of tyGenericInst, tyGenericBody: 
      result = iterOverTypeAux(marker, lastSon(t), iter, closure)
    else: 
      for i in countup(0, sonsLen(t) - 1): 
        result = iterOverTypeAux(marker, t.sons[i], iter, closure)
        if result: return 
      if t.n != nil: result = iterOverNode(marker, t.n, iter, closure)
  
proc IterOverType(t: PType, iter: TTypeIter, closure: PObject): bool = 
  var marker = InitIntSet()
  result = iterOverTypeAux(marker, t, iter, closure)

proc searchTypeForAux(t: PType, predicate: TTypePredicate, 
                      marker: var TIntSet): bool

proc searchTypeNodeForAux(n: PNode, p: TTypePredicate, 
                          marker: var TIntSet): bool = 
  result = false
  case n.kind
  of nkRecList: 
    for i in countup(0, sonsLen(n) - 1): 
      result = searchTypeNodeForAux(n.sons[i], p, marker)
      if result: return 
  of nkRecCase: 
    assert(n.sons[0].kind == nkSym)
    result = searchTypeNodeForAux(n.sons[0], p, marker)
    if result: return 
    for i in countup(1, sonsLen(n) - 1): 
      case n.sons[i].kind
      of nkOfBranch, nkElse: 
        result = searchTypeNodeForAux(lastSon(n.sons[i]), p, marker)
        if result: return 
      else: internalError("searchTypeNodeForAux(record case branch)")
  of nkSym: 
    result = searchTypeForAux(n.sym.typ, p, marker)
  else: internalError(n.info, "searchTypeNodeForAux()")
  
proc searchTypeForAux(t: PType, predicate: TTypePredicate, marker: var TIntSet): bool = 
  # iterates over VALUE types!
  result = false
  if t == nil: return 
  if ContainsOrIncl(marker, t.id): return 
  result = Predicate(t)
  if result: return 
  case t.kind
  of tyObject: 
    result = searchTypeForAux(t.sons[0], predicate, marker)
    if not result: result = searchTypeNodeForAux(t.n, predicate, marker)
  of tyGenericInst, tyDistinct: 
    result = searchTypeForAux(lastSon(t), predicate, marker)
  of tyArray, tyArrayConstr, tySet, tyTuple: 
    for i in countup(0, sonsLen(t) - 1): 
      result = searchTypeForAux(t.sons[i], predicate, marker)
      if result: return 
  else: 
    nil

proc searchTypeFor(t: PType, predicate: TTypePredicate): bool = 
  var marker = InitIntSet()
  result = searchTypeForAux(t, predicate, marker)

proc isObjectPredicate(t: PType): bool = 
  result = t.kind == tyObject

proc containsObject(t: PType): bool = 
  result = searchTypeFor(t, isObjectPredicate)

proc isObjectWithTypeFieldPredicate(t: PType): bool = 
  result = (t.kind == tyObject) and (t.sons[0] == nil) and
      not ((t.sym != nil) and (sfPure in t.sym.flags)) and
      not (tfFinal in t.flags)

proc analyseObjectWithTypeFieldAux(t: PType, marker: var TIntSet): TTypeFieldResult = 
  var res: TTypeFieldResult
  result = frNone
  if t == nil: return 
  case t.kind
  of tyObject: 
    if (t.n != nil): 
      if searchTypeNodeForAux(t.n, isObjectWithTypeFieldPredicate, marker): 
        return frEmbedded
    for i in countup(0, sonsLen(t) - 1): 
      res = analyseObjectWithTypeFieldAux(t.sons[i], marker)
      if res == frEmbedded: 
        return frEmbedded
      if res == frHeader: result = frHeader
    if result == frNone: 
      if isObjectWithTypeFieldPredicate(t): result = frHeader
  of tyGenericInst, tyDistinct: 
    result = analyseObjectWithTypeFieldAux(lastSon(t), marker)
  of tyArray, tyArrayConstr, tyTuple: 
    for i in countup(0, sonsLen(t) - 1): 
      res = analyseObjectWithTypeFieldAux(t.sons[i], marker)
      if res != frNone: 
        return frEmbedded
  else: 
    nil

proc analyseObjectWithTypeField(t: PType): TTypeFieldResult = 
  var marker = InitIntSet()
  result = analyseObjectWithTypeFieldAux(t, marker)

proc isGBCRef(t: PType): bool = 
  result = t.kind in {tyRef, tySequence, tyString}

proc containsGarbageCollectedRef(typ: PType): bool = 
  # returns true if typ contains a reference, sequence or string (all the things
  # that are garbage-collected)
  result = searchTypeFor(typ, isGBCRef)

proc isHiddenPointer(t: PType): bool = 
  result = t.kind in {tyString, tySequence}

proc containsHiddenPointer(typ: PType): bool = 
  # returns true if typ contains a string, table or sequence (all the things
  # that need to be copied deeply)
  result = searchTypeFor(typ, isHiddenPointer)

proc canFormAcycleAux(marker: var TIntSet, typ: PType, startId: int): bool
proc canFormAcycleNode(marker: var TIntSet, n: PNode, startId: int): bool = 
  result = false
  if n != nil: 
    result = canFormAcycleAux(marker, n.typ, startId)
    if not result: 
      case n.kind
      of nkNone..nkNilLit: 
        nil
      else: 
        for i in countup(0, sonsLen(n) - 1): 
          result = canFormAcycleNode(marker, n.sons[i], startId)
          if result: return 
  
proc canFormAcycleAux(marker: var TIntSet, typ: PType, startId: int): bool = 
  var t: PType
  result = false
  if typ == nil: return 
  if tfAcyclic in typ.flags: return 
  t = skipTypes(typ, abstractInst)
  if tfAcyclic in t.flags: return 
  case t.kind
  of tyTuple, tyObject, tyRef, tySequence, tyArray, tyArrayConstr, tyOpenArray: 
    if not ContainsOrIncl(marker, t.id): 
      for i in countup(0, sonsLen(t) - 1): 
        result = canFormAcycleAux(marker, t.sons[i], startId)
        if result: return 
      if t.n != nil: result = canFormAcycleNode(marker, t.n, startId)
    else: 
      result = t.id == startId
  else: 
    nil

proc canFormAcycle(typ: PType): bool = 
  var marker = InitIntSet()
  result = canFormAcycleAux(marker, typ, typ.id)

proc mutateTypeAux(marker: var TIntSet, t: PType, iter: TTypeMutator, 
                   closure: PObject): PType
proc mutateNode(marker: var TIntSet, n: PNode, iter: TTypeMutator, 
                closure: PObject): PNode = 
  result = nil
  if n != nil: 
    result = copyNode(n)
    result.typ = mutateTypeAux(marker, n.typ, iter, closure)
    case n.kind
    of nkNone..nkNilLit: 
      # a leaf
    else: 
      for i in countup(0, sonsLen(n) - 1): 
        addSon(result, mutateNode(marker, n.sons[i], iter, closure))
  
proc mutateTypeAux(marker: var TIntSet, t: PType, iter: TTypeMutator, 
                   closure: PObject): PType = 
  result = nil
  if t == nil: return 
  result = iter(t, closure)
  if not ContainsOrIncl(marker, t.id): 
    for i in countup(0, sonsLen(t) - 1): 
      result.sons[i] = mutateTypeAux(marker, result.sons[i], iter, closure)
      if (result.sons[i] == nil) and (result.kind == tyGenericInst): 
        assert(false)
    if t.n != nil: result.n = mutateNode(marker, t.n, iter, closure)
  assert(result != nil)

proc mutateType(t: PType, iter: TTypeMutator, closure: PObject): PType = 
  var marker = InitIntSet()
  result = mutateTypeAux(marker, t, iter, closure)

proc rangeToStr(n: PNode): string = 
  assert(n.kind == nkRange)
  result = ValueToString(n.sons[0]) & ".." & ValueToString(n.sons[1])

proc TypeToString(typ: PType, prefer: TPreferedDesc = preferName): string = 
  const 
    typeToStr: array[TTypeKind, string] = ["None", "bool", "Char", "empty", 
      "Array Constructor [$1]", "nil", "expr", "stmt", "typeDesc", 
      "GenericInvokation", "GenericBody", "GenericInst", "GenericParam", 
      "distinct $1", "enum", "ordinal[$1]", "array[$1, $2]", "object", "tuple", 
      "set[$1]", "range[$1]", "ptr ", "ref ", "var ", "seq[$1]", "proc", 
      "pointer", "OpenArray[$1]", "string", "CString", "Forward", "int", "int8", 
      "int16", "int32", "int64", "float", "float32", "float64", "float128"]
  var t = typ
  result = ""
  if t == nil: return 
  if (prefer == preferName) and (t.sym != nil): 
    return t.sym.Name.s
  case t.Kind
  of tyGenericBody, tyGenericInst, tyGenericInvokation:
    result = typeToString(t.sons[0]) & '['
    for i in countup(1, sonsLen(t) -1 -ord(t.kind != tyGenericInvokation)):
      if i > 1: add(result, ", ")
      add(result, typeToString(t.sons[i]))
    add(result, ']')
  of tyArray: 
    if t.sons[0].kind == tyRange: 
      result = "array[" & rangeToStr(t.sons[0].n) & ", " &
          typeToString(t.sons[1]) & ']'
    else: 
      result = "array[" & typeToString(t.sons[0]) & ", " &
          typeToString(t.sons[1]) & ']'
  of tyArrayConstr: 
    result = "Array constructor[" & rangeToStr(t.sons[0].n) & ", " &
        typeToString(t.sons[1]) & ']'
  of tySequence: 
    result = "seq[" & typeToString(t.sons[0]) & ']'
  of tyOrdinal: 
    result = "ordinal[" & typeToString(t.sons[0]) & ']'
  of tySet: 
    result = "set[" & typeToString(t.sons[0]) & ']'
  of tyOpenArray: 
    result = "openarray[" & typeToString(t.sons[0]) & ']'
  of tyDistinct: 
    result = "distinct " & typeToString(t.sons[0], preferName)
  of tyTuple: 
    # we iterate over t.sons here, because t.n may be nil
    result = "tuple["
    if t.n != nil: 
      assert(sonsLen(t.n) == sonsLen(t))
      for i in countup(0, sonsLen(t.n) - 1): 
        assert(t.n.sons[i].kind == nkSym)
        add(result, t.n.sons[i].sym.name.s & ": " & typeToString(t.sons[i]))
        if i < sonsLen(t.n) - 1: add(result, ", ")
    else: 
      for i in countup(0, sonsLen(t) - 1): 
        add(result, typeToString(t.sons[i]))
        if i < sonsLen(t) - 1: add(result, ", ")
    add(result, ']')
  of tyPtr, tyRef, tyVar: 
    result = typeToStr[t.kind] & typeToString(t.sons[0])
  of tyRange: 
    result = "range " & rangeToStr(t.n)
  of tyProc: 
    result = "proc ("
    for i in countup(1, sonsLen(t) - 1): 
      add(result, typeToString(t.sons[i]))
      if i < sonsLen(t) - 1: add(result, ", ")
    add(result, ')')
    if t.sons[0] != nil: add(result, ": " & TypeToString(t.sons[0]))
    var prag: string
    if t.callConv != ccDefault: prag = CallingConvToStr[t.callConv]
    else: prag = ""
    if tfNoSideEffect in t.flags: 
      addSep(prag)
      add(prag, "noSideEffect")
    if len(prag) != 0: add(result, "{." & prag & ".}")
  else: 
    result = typeToStr[t.kind]

proc resultType(t: PType): PType = 
  assert(t.kind == tyProc)
  result = t.sons[0]          # nil is allowed
  
proc base(t: PType): PType = 
  result = t.sons[0]

proc firstOrd(t: PType): biggestInt = 
  case t.kind
  of tyBool, tyChar, tySequence, tyOpenArray, tyString: 
    result = 0
  of tySet, tyVar: 
    result = firstOrd(t.sons[0])
  of tyArray, tyArrayConstr: 
    result = firstOrd(t.sons[0])
  of tyRange: 
    assert(t.n != nil)        # range directly given:
    assert(t.n.kind == nkRange)
    result = getOrdValue(t.n.sons[0])
  of tyInt: 
    if platform.intSize == 4: result = - (2147483646) - 2
    else: result = 0x8000000000000000'i64
  of tyInt8: 
    result = - 128
  of tyInt16: 
    result = - 32768
  of tyInt32: 
    result = - 2147483646 - 2
  of tyInt64: 
    result = 0x8000000000000000'i64
  of tyEnum: 
    # if basetype <> nil then return firstOrd of basetype
    if (sonsLen(t) > 0) and (t.sons[0] != nil): 
      result = firstOrd(t.sons[0])
    else: 
      assert(t.n.sons[0].kind == nkSym)
      result = t.n.sons[0].sym.position
  of tyGenericInst, tyDistinct: 
    result = firstOrd(lastSon(t))
  else: 
    InternalError("invalid kind for first(" & $t.kind & ')')
    result = 0

proc lastOrd(t: PType): biggestInt = 
  case t.kind
  of tyBool: 
    result = 1
  of tyChar: 
    result = 255
  of tySet, tyVar: 
    result = lastOrd(t.sons[0])
  of tyArray, tyArrayConstr: 
    result = lastOrd(t.sons[0])
  of tyRange: 
    assert(t.n != nil)        # range directly given:
    assert(t.n.kind == nkRange)
    result = getOrdValue(t.n.sons[1])
  of tyInt: 
    if platform.intSize == 4: result = 0x7FFFFFFF
    else: result = 0x7FFFFFFFFFFFFFFF'i64
  of tyInt8: 
    result = 0x0000007F
  of tyInt16: 
    result = 0x00007FFF
  of tyInt32: 
    result = 0x7FFFFFFF
  of tyInt64: 
    result = 0x7FFFFFFFFFFFFFFF'i64
  of tyEnum: 
    assert(t.n.sons[sonsLen(t.n) - 1].kind == nkSym)
    result = t.n.sons[sonsLen(t.n) - 1].sym.position
  of tyGenericInst, tyDistinct: 
    result = firstOrd(lastSon(t))
  else: 
    InternalError("invalid kind for last(" & $t.kind & ')')
    result = 0

proc lengthOrd(t: PType): biggestInt = 
  case t.kind
  of tyInt64, tyInt32, tyInt: result = lastOrd(t)
  of tyDistinct: result = lengthOrd(t.sons[0])
  else: result = lastOrd(t) - firstOrd(t) + 1
  
proc equalParam(a, b: PSym): TParamsEquality = 
  if SameTypeOrNil(a.typ, b.typ): 
    if (a.ast == b.ast): 
      result = paramsEqual
    elif (a.ast != nil) and (b.ast != nil): 
      if ExprStructuralEquivalent(a.ast, b.ast): result = paramsEqual
      else: result = paramsIncompatible
    elif (a.ast != nil): 
      result = paramsEqual
    elif (b.ast != nil): 
      result = paramsIncompatible
  else: 
    result = paramsNotEqual
  
proc equalParams(a, b: PNode): TParamsEquality = 
  result = paramsEqual
  var length = sonsLen(a)
  if length != sonsLen(b): 
    result = paramsNotEqual
  else: 
    for i in countup(1, length - 1): 
      var m = a.sons[i].sym
      var n = b.sons[i].sym
      assert((m.kind == skParam) and (n.kind == skParam))
      case equalParam(m, n)
      of paramsNotEqual: 
        return paramsNotEqual
      of paramsEqual: 
        nil
      of paramsIncompatible: 
        result = paramsIncompatible
      if (m.name.id != n.name.id): 
        # BUGFIX
        return paramsNotEqual # paramsIncompatible;
      # continue traversal! If not equal, we can return immediately; else
      # it stays incompatible
    if not SameTypeOrNil(a.sons[0].typ, b.sons[0].typ): 
      if (a.sons[0].typ == nil) or (b.sons[0].typ == nil): 
        result = paramsNotEqual # one proc has a result, the other not is OK
      else: 
        result = paramsIncompatible # overloading by different
                                    # result types does not work
  
proc SameTypeOrNil(a, b: PType): bool = 
  if a == b: 
    result = true
  else: 
    if (a == nil) or (b == nil): result = false
    else: result = SameType(a, b)
  
proc SameLiteral(x, y: PNode): bool = 
  result = false
  if x.kind == y.kind: 
    case x.kind
    of nkCharLit..nkInt64Lit: result = x.intVal == y.intVal
    of nkFloatLit..nkFloat64Lit: result = x.floatVal == y.floatVal
    of nkNilLit: result = true
    else: assert(false)
  
proc SameRanges(a, b: PNode): bool = 
  result = SameLiteral(a.sons[0], b.sons[0]) and
      SameLiteral(a.sons[1], b.sons[1])

proc sameTuple(a, b: PType, DistinctOf: bool): bool = 
  # two tuples are equivalent iff the names, types and positions are the same;
  # however, both types may not have any field names (t.n may be nil) which
  # complicates the matter a bit.
  if sonsLen(a) == sonsLen(b): 
    result = true
    for i in countup(0, sonsLen(a) - 1): 
      if DistinctOf: result = equalOrDistinctOf(a.sons[i], b.sons[i])
      else: result = SameType(a.sons[i], b.sons[i])
      if not result: return 
    if (a.n != nil) and (b.n != nil): 
      for i in countup(0, sonsLen(a.n) - 1): 
        # check field names: 
        if a.n.sons[i].kind != nkSym: InternalError(a.n.info, "sameTuple")
        if b.n.sons[i].kind != nkSym: InternalError(b.n.info, "sameTuple")
        var x = a.n.sons[i].sym
        var y = b.n.sons[i].sym
        result = x.name.id == y.name.id
        if not result: break 
  else: 
    result = false
  
proc SameType(x, y: PType): bool = 
  if x == y: 
    return true
  var a = skipTypes(x, {tyGenericInst})
  var b = skipTypes(y, {tyGenericInst})
  assert(a != nil)
  assert(b != nil)
  if a.kind != b.kind: 
    return false
  case a.Kind
  of tyEmpty, tyChar, tyBool, tyNil, tyPointer, tyString, tyCString, 
     tyInt..tyFloat128, tyExpr, tyStmt, tyTypeDesc: 
    result = true
  of tyEnum, tyForward, tyObject, tyDistinct: 
    result = (a.id == b.id)
  of tyTuple: 
    result = sameTuple(a, b, false)
  of tyGenericInst: 
    result = sameType(lastSon(a), lastSon(b))
  of tyGenericParam, tyGenericInvokation, tyGenericBody, tySequence, tyOrdinal, 
     tyOpenArray, tySet, tyRef, tyPtr, tyVar, tyArrayConstr, tyArray, tyProc: 
    if sonsLen(a) == sonsLen(b): 
      result = true
      for i in countup(0, sonsLen(a) - 1): 
        result = SameTypeOrNil(a.sons[i], b.sons[i]) # BUGFIX
        if not result: return 
      if result and (a.kind == tyProc): 
        result = a.callConv == b.callConv # BUGFIX
    else: 
      result = false
  of tyRange: 
    result = SameTypeOrNil(a.sons[0], b.sons[0]) and
        SameValue(a.n.sons[0], b.n.sons[0]) and
        SameValue(a.n.sons[1], b.n.sons[1])
  of tyNone: 
    result = false
  
proc equalOrDistinctOf(x, y: PType): bool = 
  if x == y: 
    return true
  if (x == nil) or (y == nil): 
    return false
  var a = skipTypes(x, {tyGenericInst})
  var b = skipTypes(y, {tyGenericInst})
  assert(a != nil)
  assert(b != nil)
  if a.kind != b.kind: 
    if a.kind == tyDistinct: a = a.sons[0]
    if a.kind != b.kind: 
      return false
  case a.Kind
  of tyEmpty, tyChar, tyBool, tyNil, tyPointer, tyString, tyCString, 
     tyInt..tyFloat128, tyExpr, tyStmt, tyTypeDesc: 
    result = true
  of tyEnum, tyForward, tyObject, tyDistinct: 
    result = (a.id == b.id)
  of tyTuple: 
    result = sameTuple(a, b, true)
  of tyGenericInst: 
    result = equalOrDistinctOf(lastSon(a), lastSon(b))
  of tyGenericParam, tyGenericInvokation, tyGenericBody, tySequence, tyOrdinal, 
     tyOpenArray, tySet, tyRef, tyPtr, tyVar, tyArrayConstr, tyArray, tyProc: 
    if sonsLen(a) == sonsLen(b): 
      result = true
      for i in countup(0, sonsLen(a) - 1): 
        result = equalOrDistinctOf(a.sons[i], b.sons[i])
        if not result: return 
      if result and (a.kind == tyProc): result = a.callConv == b.callConv
    else: 
      result = false
  of tyRange: 
    result = equalOrDistinctOf(a.sons[0], b.sons[0]) and
        SameValue(a.n.sons[0], b.n.sons[0]) and
        SameValue(a.n.sons[1], b.n.sons[1])
  of tyNone: 
    result = false
  
proc typeAllowedAux(marker: var TIntSet, typ: PType, kind: TSymKind): bool
proc typeAllowedNode(marker: var TIntSet, n: PNode, kind: TSymKind): bool = 
  result = true
  if n != nil: 
    result = typeAllowedAux(marker, n.typ, kind)
    #if not result: debug(n.typ)
    if result: 
      case n.kind
      of nkNone..nkNilLit: 
        nil
      else: 
        for i in countup(0, sonsLen(n) - 1): 
          result = typeAllowedNode(marker, n.sons[i], kind)
          if not result: return 
  
proc typeAllowedAux(marker: var TIntSet, typ: PType, kind: TSymKind): bool = 
  assert(kind in {skVar, skConst, skParam})
  # if we have already checked the type, return true, because we stop the
  # evaluation if something is wrong:
  result = true
  if typ == nil: return
  if ContainsOrIncl(marker, typ.id): return 
  var t = skipTypes(typ, abstractInst)
  case t.kind
  of tyVar: 
    var t2 = skipTypes(t.sons[0], abstractInst)
    case t2.kind
    of tyVar: 
      result = false          # ``var var`` is always an invalid type:
    of tyOpenArray: 
      result = (kind == skParam) and typeAllowedAux(marker, t2, kind)
    else: result = (kind != skConst) and typeAllowedAux(marker, t2, kind)
  of tyProc: 
    for i in countup(1, sonsLen(t) - 1): 
      result = typeAllowedAux(marker, t.sons[i], skParam)
      if not result: return 
    if t.sons[0] != nil: result = typeAllowedAux(marker, t.sons[0], skVar)
  of tyExpr, tyStmt, tyTypeDesc: 
    result = true
  of tyGenericBody, tyGenericParam, tyForward, tyNone, tyGenericInvokation: 
    result = false            #InternalError('shit found');
  of tyEmpty, tyNil: 
    result = kind == skConst
  of tyString, tyBool, tyChar, tyEnum, tyInt..tyFloat128, tyCString, tyPointer: 
    result = true
  of tyOrdinal: 
    result = kind == skParam
  of tyGenericInst, tyDistinct: 
    result = typeAllowedAux(marker, lastSon(t), kind)
  of tyRange: 
    result = skipTypes(t.sons[0], abstractInst).kind in
        {tyChar, tyEnum, tyInt..tyFloat128}
  of tyOpenArray: 
    result = (kind == skParam) and typeAllowedAux(marker, t.sons[0], skVar)
  of tySequence: 
    result = (kind != skConst) and typeAllowedAux(marker, t.sons[0], skVar) or
        (t.sons[0].kind == tyEmpty)
  of tyArray: 
    result = typeAllowedAux(marker, t.sons[1], skVar)
  of tyPtr, tyRef: 
    result = typeAllowedAux(marker, t.sons[0], skVar)
  of tyArrayConstr, tyTuple, tySet: 
    for i in countup(0, sonsLen(t) - 1): 
      result = typeAllowedAux(marker, t.sons[i], kind)
      if not result: return 
  of tyObject: 
    for i in countup(0, sonsLen(t) - 1): 
      result = typeAllowedAux(marker, t.sons[i], skVar)
      if not result: return 
    if t.n != nil: result = typeAllowedNode(marker, t.n, skVar)
  
proc typeAllowed(t: PType, kind: TSymKind): bool = 
  var marker = InitIntSet()
  result = typeAllowedAux(marker, t, kind)

proc align(address, alignment: biggestInt): biggestInt = 
  result = (address + (alignment - 1)) and not (alignment - 1)

proc computeSizeAux(typ: PType, a: var biggestInt): biggestInt
proc computeRecSizeAux(n: PNode, a, currOffset: var biggestInt): biggestInt = 
  var maxAlign, maxSize, b, res: biggestInt
  case n.kind
  of nkRecCase: 
    assert(n.sons[0].kind == nkSym)
    result = computeRecSizeAux(n.sons[0], a, currOffset)
    maxSize = 0
    maxAlign = 1
    for i in countup(1, sonsLen(n) - 1): 
      case n.sons[i].kind
      of nkOfBranch, nkElse: 
        res = computeRecSizeAux(lastSon(n.sons[i]), b, currOffset)
        if res < 0: 
          return res
        maxSize = max(maxSize, res)
        maxAlign = max(maxAlign, b)
      else: internalError("computeRecSizeAux(record case branch)")
    currOffset = align(currOffset, maxAlign) + maxSize
    result = align(result, maxAlign) + maxSize
    a = maxAlign
  of nkRecList: 
    result = 0
    maxAlign = 1
    for i in countup(0, sonsLen(n) - 1): 
      res = computeRecSizeAux(n.sons[i], b, currOffset)
      if res < 0: 
        return res
      currOffset = align(currOffset, b) + res
      result = align(result, b) + res
      if b > maxAlign: maxAlign = b
    a = maxAlign
  of nkSym: 
    result = computeSizeAux(n.sym.typ, a)
    n.sym.offset = int(currOffset)
  else: 
    InternalError("computeRecSizeAux()")
    a = 1
    result = - 1

proc computeSizeAux(typ: PType, a: var biggestInt): biggestInt = 
  var res, maxAlign, length, currOffset: biggestInt
  if typ.size == - 2: 
    # we are already computing the size of the type
    # --> illegal recursion in type
    return - 2
  if typ.size >= 0: 
    # size already computed
    result = typ.size
    a = typ.align
    return 
  typ.size = - 2              # mark as being computed
  case typ.kind
  of tyInt: 
    result = IntSize
    a = result
  of tyInt8, tyBool, tyChar: 
    result = 1
    a = result
  of tyInt16: 
    result = 2
    a = result
  of tyInt32, tyFloat32: 
    result = 4
    a = result
  of tyInt64, tyFloat64: 
    result = 8
    a = result
  of tyFloat: 
    result = floatSize
    a = result
  of tyProc: 
    if typ.callConv == ccClosure: result = 2 * ptrSize
    else: result = ptrSize
    a = ptrSize
  of tyNil, tyCString, tyString, tySequence, tyPtr, tyRef, tyOpenArray: 
    result = ptrSize
    a = result
  of tyArray, tyArrayConstr: 
    result = lengthOrd(typ.sons[0]) * computeSizeAux(typ.sons[1], a)
  of tyEnum: 
    if firstOrd(typ) < 0: 
      result = 4              # use signed int32
    else: 
      length = lastOrd(typ)   # BUGFIX: use lastOrd!
      if length + 1 < `shl`(1, 8): result = 1
      elif length + 1 < `shl`(1, 16): result = 2
      elif length + 1 < `shl`(biggestInt(1), 32): result = 4
      else: result = 8
    a = result
  of tySet: 
    length = lengthOrd(typ.sons[0])
    if length <= 8: 
      result = 1
    elif length <= 16: 
      result = 2
    elif length <= 32: 
      result = 4
    elif length <= 64: 
      result = 8
    elif align(length, 8) mod 8 == 0: 
      result = align(length, 8) div 8
    else: 
      result = align(length, 8) div 8 + 1 # BUGFIX!
    a = result
  of tyRange: 
    result = computeSizeAux(typ.sons[0], a)
  of tyTuple: 
    result = 0
    maxAlign = 1
    for i in countup(0, sonsLen(typ) - 1): 
      res = computeSizeAux(typ.sons[i], a)
      if res < 0: 
        return res
      maxAlign = max(maxAlign, a)
      result = align(result, a) + res
    result = align(result, maxAlign)
    a = maxAlign
  of tyObject: 
    if typ.sons[0] != nil: 
      result = computeSizeAux(typ.sons[0], a)
      if result < 0: return 
      maxAlign = a
    elif isObjectWithTypeFieldPredicate(typ): 
      result = intSize
      maxAlign = result
    else: 
      result = 0
      maxAlign = 1
    currOffset = result
    result = computeRecSizeAux(typ.n, a, currOffset)
    if result < 0: return 
    if a < maxAlign: a = maxAlign
    result = align(result, a)
  of tyGenericInst, tyDistinct, tyGenericBody: 
    result = computeSizeAux(lastSon(typ), a)
  else: 
    #internalError('computeSizeAux()');
    result = - 1
  typ.size = result
  typ.align = int(a)

proc computeSize(typ: PType): biggestInt = 
  var a: biggestInt = 1
  result = computeSizeAux(typ, a)

proc getSize(typ: PType): biggestInt = 
  result = computeSize(typ)
  if result < 0: InternalError("getSize(" & $typ.kind & ')')