summary refs log tree commit diff stats
path: root/compiler/semfold.nim
blob: 4740ddcb3d995f28e3647a2e60954c375c2b94d4 (plain) (blame)
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
#
#
#           The Nimrod Compiler
#        (c) Copyright 2012 Andreas Rumpf
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

# this module folds constants; used by semantic checking phase
# and evaluation phase

import 
  strutils, lists, options, ast, astalgo, trees, treetab, nimsets, times, 
  nversion, platform, math, msgs, os, condsyms, idents, renderer, types,
  commands, magicsys, saturate

proc getConstExpr*(m: PSym, n: PNode): PNode
  # evaluates the constant expression or returns nil if it is no constant
  # expression
proc evalOp*(m: TMagic, n, a, b, c: PNode): PNode
proc leValueConv*(a, b: PNode): bool
proc newIntNodeT*(intVal: BiggestInt, n: PNode): PNode
proc newFloatNodeT(floatVal: BiggestFloat, n: PNode): PNode
proc newStrNodeT*(strVal: string, n: PNode): PNode

# implementation

proc newIntNodeT(intVal: BiggestInt, n: PNode): PNode =
  case skipTypes(n.typ, abstractVarRange).kind
  of tyInt:
    result = newIntNode(nkIntLit, intVal)
    result.typ = getIntLitType(result)
    # hrm, this is not correct: 1 + high(int) shouldn't produce tyInt64 ...
    #setIntLitType(result)
  of tyChar:
    result = newIntNode(nkCharLit, intVal)
    result.typ = n.typ
  else:
    result = newIntNode(nkIntLit, intVal)
    result.typ = n.typ
  result.info = n.info

proc newFloatNodeT(floatVal: BiggestFloat, n: PNode): PNode = 
  result = newFloatNode(nkFloatLit, floatVal)
  if skipTypes(n.typ, abstractVarRange).kind == tyFloat:
    result.typ = getFloatLitType(result)
  else:
    result.typ = n.typ
  result.info = n.info

proc newStrNodeT(strVal: string, n: PNode): PNode = 
  result = newStrNode(nkStrLit, strVal)
  result.typ = n.typ
  result.info = n.info

proc ordinalValToString*(a: PNode): string = 
  # because $ has the param ordinal[T], `a` is not necessarily an enum, but an
  # ordinal
  var x = getInt(a)
  
  var t = skipTypes(a.typ, abstractRange)
  case t.kind
  of tyChar: 
    result = $chr(int(x) and 0xff)
  of tyEnum:
    var n = t.n
    for i in countup(0, sonsLen(n) - 1): 
      if n.sons[i].kind != nkSym: internalError(a.info, "ordinalValToString")
      var field = n.sons[i].sym
      if field.position == x: 
        if field.ast == nil: 
          return field.name.s
        else:
          return field.ast.strVal
    internalError(a.info, "no symbol for ordinal value: " & $x)
  else:
    result = $x

proc isFloatRange(t: PType): bool {.inline.} =
  result = t.kind == tyRange and t.sons[0].kind in {tyFloat..tyFloat128}

proc isIntRange(t: PType): bool {.inline.} =
  result = t.kind == tyRange and t.sons[0].kind in {
      tyInt..tyInt64, tyUInt8..tyUInt32}

proc pickIntRange(a, b: PType): PType =
  if isIntRange(a): result = a
  elif isIntRange(b): result = b
  else: result = a

proc isIntRangeOrLit(t: PType): bool =
  result = isIntRange(t) or isIntLit(t)

proc pickMinInt(n: PNode): BiggestInt =
  if n.kind in {nkIntLit..nkUInt64Lit}:
    result = n.intVal
  elif isIntLit(n.typ):
    result = n.typ.n.intVal
  elif isIntRange(n.typ):
    result = firstOrd(n.typ)
  else:
    internalError(n.info, "pickMinInt")

proc pickMaxInt(n: PNode): BiggestInt =
  if n.kind in {nkIntLit..nkUInt64Lit}:
    result = n.intVal
  elif isIntLit(n.typ):
    result = n.typ.n.intVal
  elif isIntRange(n.typ):
    result = lastOrd(n.typ)
  else:
    internalError(n.info, "pickMaxInt")

proc makeRange(typ: PType, first, last: BiggestInt): PType = 
  var n = newNode(nkRange)
  addSon(n, newIntNode(nkIntLit, min(first, last)))
  addSon(n, newIntNode(nkIntLit, max(first, last)))
  result = newType(tyRange, typ.owner)
  result.n = n
  addSonSkipIntLit(result, skipTypes(typ, {tyRange}))

proc makeRangeF(typ: PType, first, last: BiggestFloat): PType =
  var n = newNode(nkRange)
  addSon(n, newFloatNode(nkFloatLit, min(first.float, last.float)))
  addSon(n, newFloatNode(nkFloatLit, max(first.float, last.float)))
  result = newType(tyRange, typ.owner)
  result.n = n
  addSonSkipIntLit(result, skipTypes(typ, {tyRange}))

proc getIntervalType*(m: TMagic, n: PNode): PType =
  # Nimrod requires interval arithmetic for ``range`` types. Lots of tedious
  # work but the feature is very nice for reducing explicit conversions.
  result = n.typ
  
  template commutativeOp(opr: expr) {.immediate.} =
    let a = n.sons[1]
    let b = n.sons[2]
    if isIntRangeOrLit(a.typ) and isIntRangeOrLit(b.typ):
      result = makeRange(pickIntRange(a.typ, b.typ),
                         opr(pickMinInt(a), pickMinInt(b)),
                         opr(pickMaxInt(a), pickMaxInt(b)))
  
  template binaryOp(opr: expr) {.immediate.} =
    let a = n.sons[1]
    let b = n.sons[2]
    if isIntRange(a.typ) and b.kind in {nkIntLit..nkUInt64Lit}:
      result = makeRange(a.typ,
                         opr(pickMinInt(a), pickMinInt(b)),
                         opr(pickMaxInt(a), pickMaxInt(b)))
  
  case m
  of mUnaryMinusI, mUnaryMinusI64:
    let a = n.sons[1].typ
    if isIntRange(a):
      # (1..3) * (-1) == (-3.. -1)
      result = makeRange(a, 0|-|lastOrd(a), 0|-|firstOrd(a))
  of mUnaryMinusF64:
    let a = n.sons[1].typ
    if isFloatRange(a):
      result = makeRangeF(a, -getFloat(a.n.sons[1]),
                             -getFloat(a.n.sons[0]))
  of mAbsF64:
    let a = n.sons[1].typ
    if isFloatRange(a):
      # abs(-5.. 1) == (1..5)
      result = makeRangeF(a, abs(getFloat(a.n.sons[1])),
                             abs(getFloat(a.n.sons[0])))
  of mAbsI, mAbsI64:
    let a = n.sons[1].typ
    if isIntRange(a):
      result = makeRange(a, `|abs|`(getInt(a.n.sons[1])),
                            `|abs|`(getInt(a.n.sons[0])))
  of mSucc:
    let a = n.sons[1].typ
    let b = n.sons[2].typ
    if isIntRange(a) and isIntLit(b):
      # (-5.. 1) + 6 == (-5 + 6)..(-1 + 6)
      result = makeRange(a, pickMinInt(n.sons[1]) |+| pickMinInt(n.sons[2]),
                            pickMaxInt(n.sons[1]) |+| pickMaxInt(n.sons[2]))
  of mPred:
    let a = n.sons[1].typ
    let b = n.sons[2].typ
    if isIntRange(a) and isIntLit(b):
      result = makeRange(a, pickMinInt(n.sons[1]) |-| pickMinInt(n.sons[2]),
                            pickMaxInt(n.sons[1]) |-| pickMaxInt(n.sons[2]))
  of mAddI, mAddI64, mAddU:
    commutativeOp(`|+|`)
  of mMulI, mMulI64, mMulU:
    commutativeOp(`|*|`)
  of mSubI, mSubI64, mSubU:
    binaryOp(`|-|`)
  of mBitandI, mBitandI64:
    var a = n.sons[1]
    var b = n.sons[2]
    # symmetrical:
    if b.kind notin {nkIntLit..nkUInt64Lit}: swap(a, b)
    if b.kind in {nkIntLit..nkUInt64Lit}:
      let x = b.intVal|+|1
      if (x and -x) == x and x >= 0:
        result = makeRange(a.typ, 0, b.intVal)
  of mModU:
    let a = n.sons[1]
    let b = n.sons[2]
    if b.kind in {nkIntLit..nkUInt64Lit}:
      if b.intVal >= 0:
        result = makeRange(a.typ, 0, b.intVal-1)
      else:
        result = makeRange(a.typ, b.intVal+1, 0)
  of mModI, mModI64:
    # so ... if you ever wondered about modulo's signedness; this defines it:
    let a = n.sons[1]
    let b = n.sons[2]
    if b.kind in {nkIntLit..nkUInt64Lit}:
      if b.intVal >= 0:
        result = makeRange(a.typ, -(b.intVal-1), b.intVal-1)
      else:
        result = makeRange(a.typ, b.intVal+1, -(b.intVal+1))
  of mDivI, mDivI64, mDivU:
    binaryOp(`|div|`)
  of mMinI, mMinI64:
    commutativeOp(min)
  of mMaxI, mMaxI64:
    commutativeOp(max)
  else: discard
  
discard """
  mShlI, mShlI64,
  mShrI, mShrI64, mAddF64, mSubF64, mMulF64, mDivF64, mMaxF64, mMinF64
"""

proc evalIs(n, a: PNode): PNode =
  # XXX: This should use the standard isOpImpl
  internalAssert a.kind == nkSym and a.sym.kind == skType
  internalAssert n.sonsLen == 3 and
    n[2].kind in {nkStrLit..nkTripleStrLit, nkType}
  
  let t1 = a.sym.typ

  if n[2].kind in {nkStrLit..nkTripleStrLit}:
    case n[2].strVal.normalize
    of "closure":
      let t = skipTypes(t1, abstractRange)
      result = newIntNode(nkIntLit, ord(t.kind == tyProc and
                                        t.callConv == ccClosure and 
                                        tfIterator notin t.flags))
    of "iterator":
      let t = skipTypes(t1, abstractRange)
      result = newIntNode(nkIntLit, ord(t.kind == tyProc and
                                        t.callConv == ccClosure and 
                                        tfIterator in t.flags))
  else:
    # XXX semexprs.isOpImpl is slightly different and requires a context. yay.
    let t2 = n[2].typ
    var match = sameType(t1, t2)
    result = newIntNode(nkIntLit, ord(match))
  result.typ = n.typ

proc evalOp(m: TMagic, n, a, b, c: PNode): PNode = 
  # b and c may be nil
  result = nil
  case m
  of mOrd: result = newIntNodeT(getOrdValue(a), n)
  of mChr: result = newIntNodeT(getInt(a), n)
  of mUnaryMinusI, mUnaryMinusI64: result = newIntNodeT(- getInt(a), n)
  of mUnaryMinusF64: result = newFloatNodeT(- getFloat(a), n)
  of mNot: result = newIntNodeT(1 - getInt(a), n)
  of mCard: result = newIntNodeT(nimsets.cardSet(a), n)
  of mBitnotI, mBitnotI64: result = newIntNodeT(not getInt(a), n)
  of mLengthStr: result = newIntNodeT(len(getStr(a)), n)
  of mLengthArray: result = newIntNodeT(lengthOrd(a.typ), n)
  of mLengthSeq, mLengthOpenArray: result = newIntNodeT(sonsLen(a), n) # BUGFIX
  of mUnaryPlusI, mUnaryPlusI64, mUnaryPlusF64: result = a # throw `+` away
  of mToFloat, mToBiggestFloat: 
    result = newFloatNodeT(toFloat(int(getInt(a))), n)
  of mToInt, mToBiggestInt: result = newIntNodeT(system.toInt(getFloat(a)), n)
  of mAbsF64: result = newFloatNodeT(abs(getFloat(a)), n)
  of mAbsI, mAbsI64: 
    if getInt(a) >= 0: result = a
    else: result = newIntNodeT(- getInt(a), n)
  of mZe8ToI, mZe8ToI64, mZe16ToI, mZe16ToI64, mZe32ToI64, mZeIToI64: 
    # byte(-128) = 1...1..1000_0000'64 --> 0...0..1000_0000'64
    result = newIntNodeT(getInt(a) and (`shl`(1, getSize(a.typ) * 8) - 1), n)
  of mToU8: result = newIntNodeT(getInt(a) and 0x000000FF, n)
  of mToU16: result = newIntNodeT(getInt(a) and 0x0000FFFF, n)
  of mToU32: result = newIntNodeT(getInt(a) and 0x00000000FFFFFFFF'i64, n)
  of mUnaryLt: result = newIntNodeT(getOrdValue(a) - 1, n)
  of mSucc: result = newIntNodeT(getOrdValue(a) + getInt(b), n)
  of mPred: result = newIntNodeT(getOrdValue(a) - getInt(b), n)
  of mAddI, mAddI64: result = newIntNodeT(getInt(a) + getInt(b), n)
  of mSubI, mSubI64: result = newIntNodeT(getInt(a) - getInt(b), n)
  of mMulI, mMulI64: result = newIntNodeT(getInt(a) * getInt(b), n)
  of mMinI, mMinI64: 
    if getInt(a) > getInt(b): result = newIntNodeT(getInt(b), n)
    else: result = newIntNodeT(getInt(a), n)
  of mMaxI, mMaxI64: 
    if getInt(a) > getInt(b): result = newIntNodeT(getInt(a), n)
    else: result = newIntNodeT(getInt(b), n)
  of mShlI, mShlI64: 
    case skipTypes(n.typ, abstractRange).kind
    of tyInt8: result = newIntNodeT(int8(getInt(a)) shl int8(getInt(b)), n)
    of tyInt16: result = newIntNodeT(int16(getInt(a)) shl int16(getInt(b)), n)
    of tyInt32: result = newIntNodeT(int32(getInt(a)) shl int32(getInt(b)), n)
    of tyInt64, tyInt, tyUInt..tyUInt64: 
      result = newIntNodeT(`shl`(getInt(a), getInt(b)), n)
    else: internalError(n.info, "constant folding for shl")
  of mShrI, mShrI64: 
    case skipTypes(n.typ, abstractRange).kind
    of tyInt8: result = newIntNodeT(int8(getInt(a)) shr int8(getInt(b)), n)
    of tyInt16: result = newIntNodeT(int16(getInt(a)) shr int16(getInt(b)), n)
    of tyInt32: result = newIntNodeT(int32(getInt(a)) shr int32(getInt(b)), n)
    of tyInt64, tyInt, tyUInt..tyUInt64:
      result = newIntNodeT(`shr`(getInt(a), getInt(b)), n)
    else: internalError(n.info, "constant folding for shr")
  of mDivI, mDivI64: result = newIntNodeT(getInt(a) div getInt(b), n)
  of mModI, mModI64: result = newIntNodeT(getInt(a) mod getInt(b), n)
  of mAddF64: result = newFloatNodeT(getFloat(a) + getFloat(b), n)
  of mSubF64: result = newFloatNodeT(getFloat(a) - getFloat(b), n)
  of mMulF64: result = newFloatNodeT(getFloat(a) * getFloat(b), n)
  of mDivF64: 
    if getFloat(b) == 0.0: 
      if getFloat(a) == 0.0: result = newFloatNodeT(NaN, n)
      else: result = newFloatNodeT(Inf, n)
    else: 
      result = newFloatNodeT(getFloat(a) / getFloat(b), n)
  of mMaxF64: 
    if getFloat(a) > getFloat(b): result = newFloatNodeT(getFloat(a), n)
    else: result = newFloatNodeT(getFloat(b), n)
  of mMinF64: 
    if getFloat(a) > getFloat(b): result = newFloatNodeT(getFloat(b), n)
    else: result = newFloatNodeT(getFloat(a), n)
  of mIsNil: result = newIntNodeT(ord(a.kind == nkNilLit), n)
  of mLtI, mLtI64, mLtB, mLtEnum, mLtCh: 
    result = newIntNodeT(ord(getOrdValue(a) < getOrdValue(b)), n)
  of mLeI, mLeI64, mLeB, mLeEnum, mLeCh: 
    result = newIntNodeT(ord(getOrdValue(a) <= getOrdValue(b)), n)
  of mEqI, mEqI64, mEqB, mEqEnum, mEqCh: 
    result = newIntNodeT(ord(getOrdValue(a) == getOrdValue(b)), n) 
  of mLtF64: result = newIntNodeT(ord(getFloat(a) < getFloat(b)), n)
  of mLeF64: result = newIntNodeT(ord(getFloat(a) <= getFloat(b)), n)
  of mEqF64: result = newIntNodeT(ord(getFloat(a) == getFloat(b)), n) 
  of mLtStr: result = newIntNodeT(ord(getStr(a) < getStr(b)), n)
  of mLeStr: result = newIntNodeT(ord(getStr(a) <= getStr(b)), n)
  of mEqStr: result = newIntNodeT(ord(getStr(a) == getStr(b)), n)
  of mLtU, mLtU64: 
    result = newIntNodeT(ord(`<%`(getOrdValue(a), getOrdValue(b))), n)
  of mLeU, mLeU64: 
    result = newIntNodeT(ord(`<=%`(getOrdValue(a), getOrdValue(b))), n)
  of mBitandI, mBitandI64, mAnd: result = newIntNodeT(a.getInt and b.getInt, n)
  of mBitorI, mBitorI64, mOr: result = newIntNodeT(getInt(a) or getInt(b), n)
  of mBitxorI, mBitxorI64, mXor: result = newIntNodeT(a.getInt xor b.getInt, n)
  of mAddU: result = newIntNodeT(`+%`(getInt(a), getInt(b)), n)
  of mSubU: result = newIntNodeT(`-%`(getInt(a), getInt(b)), n)
  of mMulU: result = newIntNodeT(`*%`(getInt(a), getInt(b)), n)
  of mModU: result = newIntNodeT(`%%`(getInt(a), getInt(b)), n)
  of mDivU: result = newIntNodeT(`/%`(getInt(a), getInt(b)), n)
  of mLeSet: result = newIntNodeT(ord(containsSets(a, b)), n)
  of mEqSet: result = newIntNodeT(ord(equalSets(a, b)), n)
  of mLtSet: 
    result = newIntNodeT(ord(containsSets(a, b) and not equalSets(a, b)), n)
  of mMulSet: 
    result = nimsets.intersectSets(a, b)
    result.info = n.info
  of mPlusSet: 
    result = nimsets.unionSets(a, b)
    result.info = n.info
  of mMinusSet: 
    result = nimsets.diffSets(a, b)
    result.info = n.info
  of mSymDiffSet: 
    result = nimsets.symdiffSets(a, b)
    result.info = n.info
  of mConStrStr: result = newStrNodeT(getStrOrChar(a) & getStrOrChar(b), n)
  of mInSet: result = newIntNodeT(ord(inSet(a, b)), n)
  of mRepr:
    # BUGFIX: we cannot eval mRepr here for reasons that I forgot.
  of mIntToStr, mInt64ToStr: result = newStrNodeT($(getOrdValue(a)), n)
  of mBoolToStr: 
    if getOrdValue(a) == 0: result = newStrNodeT("false", n)
    else: result = newStrNodeT("true", n)
  of mCopyStr: result = newStrNodeT(substr(getStr(a), int(getOrdValue(b))), n)
  of mCopyStrLast: 
    result = newStrNodeT(substr(getStr(a), int(getOrdValue(b)), 
                                           int(getOrdValue(c))), n)
  of mFloatToStr: result = newStrNodeT($getFloat(a), n)
  of mCStrToStr, mCharToStr: result = newStrNodeT(getStrOrChar(a), n)
  of mStrToStr: result = a
  of mEnumToStr: result = newStrNodeT(ordinalValToString(a), n)
  of mArrToSeq: 
    result = copyTree(a)
    result.typ = n.typ
  of mCompileOption:
    result = newIntNodeT(ord(commands.testCompileOption(a.getStr, n.info)), n)  
  of mCompileOptionArg:
    result = newIntNodeT(ord(
      testCompileOptionArg(getStr(a), getStr(b), n.info)), n)
  of mNewString, mNewStringOfCap, 
     mExit, mInc, ast.mDec, mEcho, mSwap, mAppendStrCh, 
     mAppendStrStr, mAppendSeqElem, mSetLengthStr, mSetLengthSeq, 
     mParseExprToAst, mParseStmtToAst, mExpandToAst, mTypeTrait,
     mNLen..mNError, mEqRef, mSlurp, mStaticExec, mNGenSym: 
    discard
  of mRand:
    result = newIntNodeT(math.random(a.getInt.int), n)
  else: internalError(a.info, "evalOp(" & $m & ')')
  
proc getConstIfExpr(c: PSym, n: PNode): PNode = 
  result = nil
  for i in countup(0, sonsLen(n) - 1): 
    var it = n.sons[i]
    if it.len == 2:
      var e = getConstExpr(c, it.sons[0])
      if e == nil: return nil
      if getOrdValue(e) != 0: 
        if result == nil: 
          result = getConstExpr(c, it.sons[1])
          if result == nil: return 
    elif it.len == 1:
      if result == nil: result = getConstExpr(c, it.sons[0])
    else: internalError(it.info, "getConstIfExpr()")

proc partialAndExpr(c: PSym, n: PNode): PNode = 
  # partial evaluation
  result = n
  var a = getConstExpr(c, n.sons[1])
  var b = getConstExpr(c, n.sons[2])
  if a != nil: 
    if getInt(a) == 0: result = a
    elif b != nil: result = b
    else: result = n.sons[2]
  elif b != nil: 
    if getInt(b) == 0: result = b
    else: result = n.sons[1]
  
proc partialOrExpr(c: PSym, n: PNode): PNode = 
  # partial evaluation
  result = n
  var a = getConstExpr(c, n.sons[1])
  var b = getConstExpr(c, n.sons[2])
  if a != nil: 
    if getInt(a) != 0: result = a
    elif b != nil: result = b
    else: result = n.sons[2]
  elif b != nil: 
    if getInt(b) != 0: result = b
    else: result = n.sons[1]
  
proc leValueConv(a, b: PNode): bool = 
  result = false
  case a.kind
  of nkCharLit..nkUInt64Lit: 
    case b.kind
    of nkCharLit..nkUInt64Lit: result = a.intVal <= b.intVal
    of nkFloatLit..nkFloat128Lit: result = a.intVal <= round(b.floatVal)
    else: internalError(a.info, "leValueConv")
  of nkFloatLit..nkFloat128Lit: 
    case b.kind
    of nkFloatLit..nkFloat128Lit: result = a.floatVal <= b.floatVal
    of nkCharLit..nkUInt64Lit: result = a.floatVal <= toFloat(int(b.intVal))
    else: internalError(a.info, "leValueConv")
  else: internalError(a.info, "leValueConv")
  
proc magicCall(m: PSym, n: PNode): PNode =
  if sonsLen(n) <= 1: return

  var s = n.sons[0].sym
  var a = getConstExpr(m, n.sons[1])
  var b, c: PNode
  if a == nil: return 
  if sonsLen(n) > 2: 
    b = getConstExpr(m, n.sons[2])
    if b == nil: return 
    if sonsLen(n) > 3: 
      c = getConstExpr(m, n.sons[3])
      if c == nil: return 
  result = evalOp(s.magic, n, a, b, c)
  
proc getAppType(n: PNode): PNode =
  if gGlobalOptions.contains(optGenDynLib):
    result = newStrNodeT("lib", n)
  elif gGlobalOptions.contains(optGenStaticLib):
    result = newStrNodeT("staticlib", n)
  elif gGlobalOptions.contains(optGenGuiApp):
    result = newStrNodeT("gui", n)
  else:
    result = newStrNodeT("console", n)

proc rangeCheck(n: PNode, value: BiggestInt) =
  if value < firstOrd(n.typ) or value > lastOrd(n.typ):
    localError(n.info, errGenerated, "cannot convert " & $value &
                                     " to " & typeToString(n.typ))

proc foldConv*(n, a: PNode; check = false): PNode = 
  # XXX range checks?
  case skipTypes(n.typ, abstractRange).kind
  of tyInt..tyInt64: 
    case skipTypes(a.typ, abstractRange).kind
    of tyFloat..tyFloat64:
      result = newIntNodeT(system.toInt(getFloat(a)), n)
    of tyChar: result = newIntNodeT(getOrdValue(a), n)
    else: 
      result = a
      result.typ = n.typ
    if check: rangeCheck(n, result.intVal)
  of tyFloat..tyFloat64:
    case skipTypes(a.typ, abstractRange).kind
    of tyInt..tyInt64, tyEnum, tyBool, tyChar: 
      result = newFloatNodeT(toFloat(int(getOrdValue(a))), n)
    else:
      result = a
      result.typ = n.typ
  of tyOpenArray, tyVarargs, tyProc: 
    discard
  else: 
    result = a
    result.typ = n.typ
  
proc getArrayConstr(m: PSym, n: PNode): PNode =
  if n.kind == nkBracket:
    result = n
  else:
    result = getConstExpr(m, n)
    if result == nil: result = n
  
proc foldArrayAccess(m: PSym, n: PNode): PNode = 
  var x = getConstExpr(m, n.sons[0])
  if x == nil or x.typ.skipTypes({tyGenericInst}).kind == tyTypeDesc: return
  
  var y = getConstExpr(m, n.sons[1])
  if y == nil: return
  
  var idx = getOrdValue(y)
  case x.kind
  of nkPar: 
    if (idx >= 0) and (idx < sonsLen(x)): 
      result = x.sons[int(idx)]
      if result.kind == nkExprColonExpr: result = result.sons[1]
    else:
      localError(n.info, errIndexOutOfBounds)
  of nkBracket, nkMetaNode: 
    if (idx >= 0) and (idx < sonsLen(x)): result = x.sons[int(idx)]
    else: localError(n.info, errIndexOutOfBounds)
  of nkStrLit..nkTripleStrLit: 
    result = newNodeIT(nkCharLit, x.info, n.typ)
    if (idx >= 0) and (idx < len(x.strVal)): 
      result.intVal = ord(x.strVal[int(idx)])
    elif idx == len(x.strVal): 
      discard
    else: 
      localError(n.info, errIndexOutOfBounds)
  else: discard
  
proc foldFieldAccess(m: PSym, n: PNode): PNode =
  # a real field access; proc calls have already been transformed
  var x = getConstExpr(m, n.sons[0])
  if x == nil or x.kind notin {nkObjConstr, nkPar}: return

  var field = n.sons[1].sym
  for i in countup(ord(x.kind == nkObjConstr), sonsLen(x) - 1):
    var it = x.sons[i]
    if it.kind != nkExprColonExpr:
      # lookup per index:
      result = x.sons[field.position]
      if result.kind == nkExprColonExpr: result = result.sons[1]
      return
    if it.sons[0].sym.name.id == field.name.id: 
      result = x.sons[i].sons[1]
      return
  localError(n.info, errFieldXNotFound, field.name.s)
  
proc foldConStrStr(m: PSym, n: PNode): PNode = 
  result = newNodeIT(nkStrLit, n.info, n.typ)
  result.strVal = ""
  for i in countup(1, sonsLen(n) - 1): 
    let a = getConstExpr(m, n.sons[i])
    if a == nil: return nil
    result.strVal.add(getStrOrChar(a))

proc newSymNodeTypeDesc*(s: PSym; info: TLineInfo): PNode =
  result = newSymNode(s, info)
  result.typ = newType(tyTypeDesc, s.owner)
  result.typ.addSonSkipIntLit(s.typ)

proc getConstExpr(m: PSym, n: PNode): PNode = 
  result = nil
  case n.kind
  of nkSym: 
    var s = n.sym
    case s.kind
    of skEnumField:
      result = newIntNodeT(s.position, n)
    of skConst:
      case s.magic
      of mIsMainModule: result = newIntNodeT(ord(sfMainModule in m.flags), n)
      of mCompileDate: result = newStrNodeT(times.getDateStr(), n)
      of mCompileTime: result = newStrNodeT(times.getClockStr(), n)
      of mNimrodVersion: result = newStrNodeT(VersionAsString, n)
      of mNimrodMajor: result = newIntNodeT(VersionMajor, n)
      of mNimrodMinor: result = newIntNodeT(VersionMinor, n)
      of mNimrodPatch: result = newIntNodeT(VersionPatch, n)
      of mCpuEndian: result = newIntNodeT(ord(CPU[targetCPU].endian), n)
      of mHostOS: result = newStrNodeT(toLower(platform.OS[targetOS].name), n)
      of mHostCPU: result = newStrNodeT(platform.CPU[targetCPU].name.toLower, n)
      of mAppType: result = getAppType(n)
      of mNaN: result = newFloatNodeT(NaN, n)
      of mInf: result = newFloatNodeT(Inf, n)
      of mNegInf: result = newFloatNodeT(NegInf, n)
      else:
        if sfFakeConst notin s.flags: result = copyTree(s.ast)
    of {skProc, skMethod}:
      result = n
    of skType:
      result = newSymNodeTypeDesc(s, n.info)
    of skGenericParam:
      if s.typ.kind == tyStatic:
        if s.typ.n != nil:
          result = s.typ.n
          result.typ = s.typ.sons[0]
      else:
        result = newSymNodeTypeDesc(s, n.info)
    else: discard
  of nkCharLit..nkNilLit: 
    result = copyNode(n)
  of nkIfExpr: 
    result = getConstIfExpr(m, n)
  of nkCall, nkCommand, nkCallStrLit, nkPrefix, nkInfix: 
    if n.sons[0].kind != nkSym: return 
    var s = n.sons[0].sym
    if s.kind != skProc: return 
    try:
      case s.magic
      of mNone:
        # If it has no sideEffect, it should be evaluated. But not here.
        return
      of mSizeOf:
        var a = n.sons[1]
        if computeSize(a.typ) < 0: 
          localError(a.info, errCannotEvalXBecauseIncompletelyDefined, 
                     "sizeof")
          result = nil
        elif skipTypes(a.typ, typedescInst).kind in
             IntegralTypes+NilableTypes+{tySet}:
          #{tyArray,tyObject,tyTuple}:
          result = newIntNodeT(getSize(a.typ), n)
        else:
          result = nil
          # XXX: size computation for complex types is still wrong
      of mLow: 
        result = newIntNodeT(firstOrd(n.sons[1].typ), n)
      of mHigh: 
        if  skipTypes(n.sons[1].typ, abstractVar).kind notin
            {tyOpenArray, tyVarargs, tySequence, tyString}:
          result = newIntNodeT(lastOrd(skipTypes(n[1].typ, abstractVar)), n)
        else:
          var a = getArrayConstr(m, n.sons[1])
          if a.kind == nkBracket:
            # we can optimize it away: 
            result = newIntNodeT(sonsLen(a)-1, n)
      of mLengthOpenArray:
        var a = getArrayConstr(m, n.sons[1])
        if a.kind == nkBracket:
          # we can optimize it away! This fixes the bug ``len(134)``. 
          result = newIntNodeT(sonsLen(a), n)
        else:
          result = magicCall(m, n)
      of mLengthArray:
        # It doesn't matter if the argument is const or not for mLengthArray.
        # This fixes bug #544.
        result = newIntNodeT(lengthOrd(n.sons[1].typ), n)
      of mAstToStr:
        result = newStrNodeT(renderTree(n[1], {renderNoComments}), n)
      of mConStrStr:
        result = foldConStrStr(m, n)
      of mIs:
        let a = getConstExpr(m, n[1])
        if a != nil and a.kind == nkSym and a.sym.kind == skType:
          result = evalIs(n, a)
      else:
        result = magicCall(m, n)
    except EOverflow: 
      localError(n.info, errOverOrUnderflow)
    except EDivByZero: 
      localError(n.info, errConstantDivisionByZero)
  of nkAddr: 
    var a = getConstExpr(m, n.sons[0])
    if a != nil: 
      result = n
      n.sons[0] = a
  of nkBracket: 
    result = copyTree(n)
    for i in countup(0, sonsLen(n) - 1): 
      var a = getConstExpr(m, n.sons[i])
      if a == nil: return nil
      result.sons[i] = a
    incl(result.flags, nfAllConst)
  of nkRange: 
    var a = getConstExpr(m, n.sons[0])
    if a == nil: return 
    var b = getConstExpr(m, n.sons[1])
    if b == nil: return 
    result = copyNode(n)
    addSon(result, a)
    addSon(result, b)
  of nkCurly: 
    result = copyTree(n)
    for i in countup(0, sonsLen(n) - 1): 
      var a = getConstExpr(m, n.sons[i])
      if a == nil: return nil
      result.sons[i] = a
    incl(result.flags, nfAllConst)
  of nkObjConstr:
    result = copyTree(n)
    for i in countup(1, sonsLen(n) - 1):
      var a = getConstExpr(m, n.sons[i].sons[1])
      if a == nil: return nil
      result.sons[i].sons[1] = a
    incl(result.flags, nfAllConst)
  of nkPar:
    # tuple constructor
    result = copyTree(n)
    if (sonsLen(n) > 0) and (n.sons[0].kind == nkExprColonExpr): 
      for i in countup(0, sonsLen(n) - 1): 
        var a = getConstExpr(m, n.sons[i].sons[1])
        if a == nil: return nil
        result.sons[i].sons[1] = a
    else: 
      for i in countup(0, sonsLen(n) - 1): 
        var a = getConstExpr(m, n.sons[i])
        if a == nil: return nil
        result.sons[i] = a
    incl(result.flags, nfAllConst)
  of nkChckRangeF, nkChckRange64, nkChckRange: 
    var a = getConstExpr(m, n.sons[0])
    if a == nil: return 
    if leValueConv(n.sons[1], a) and leValueConv(a, n.sons[2]): 
      result = a              # a <= x and x <= b
      result.typ = n.typ
    else: 
      localError(n.info, errGenerated, `%`(
          msgKindToString(errIllegalConvFromXtoY), 
          [typeToString(n.sons[0].typ), typeToString(n.typ)]))
  of nkStringToCString, nkCStringToString: 
    var a = getConstExpr(m, n.sons[0])
    if a == nil: return 
    result = a
    result.typ = n.typ
  of nkHiddenStdConv, nkHiddenSubConv, nkConv: 
    var a = getConstExpr(m, n.sons[1])
    if a == nil: return
    result = foldConv(n, a, check=n.kind == nkHiddenStdConv)
  of nkCast:
    var a = getConstExpr(m, n.sons[1])
    if a == nil: return
    if n.typ.kind in NilableTypes:
      # we allow compile-time 'cast' for pointer types:
      result = a
      result.typ = n.typ
  of nkBracketExpr: result = foldArrayAccess(m, n)
  of nkDotExpr: result = foldFieldAccess(m, n)
  else:
    discard
lass="w"> ident result.info = info proc newSymNode*(sym: PSym): PNode = result = newNode(nkSym) result.sym = sym result.typ = sym.typ result.info = sym.info proc newSymNode*(sym: PSym, info: TLineInfo): PNode = result = newNode(nkSym) result.sym = sym result.typ = sym.typ result.info = info proc newNodeI*(kind: TNodeKind, info: TLineInfo): PNode = new(result) result.kind = kind result.info = info when defined(useNodeIds): result.id = gNodeId if result.id == nodeIdToDebug: echo "KIND ", result.kind writeStackTrace() inc gNodeId proc newNodeI*(kind: TNodeKind, info: TLineInfo, children: int): PNode = new(result) result.kind = kind result.info = info if children > 0: newSeq(result.sons, children) when defined(useNodeIds): result.id = gNodeId if result.id == nodeIdToDebug: echo "KIND ", result.kind writeStackTrace() inc gNodeId proc newNode*(kind: TNodeKind, info: TLineInfo, sons: TNodeSeq = @[], typ: PType = nil): PNode = new(result) result.kind = kind result.info = info result.typ = typ # XXX use shallowCopy here for ownership transfer: result.sons = sons when defined(useNodeIds): result.id = gNodeId if result.id == nodeIdToDebug: echo "KIND ", result.kind writeStackTrace() inc gNodeId proc newNodeIT*(kind: TNodeKind, info: TLineInfo, typ: PType): PNode = result = newNode(kind) result.info = info result.typ = typ proc newIntNode*(kind: TNodeKind, intVal: BiggestInt): PNode = result = newNode(kind) result.intVal = intVal proc newIntNode*(kind: TNodeKind, intVal: Int128): PNode = result = newNode(kind) result.intVal = castToInt64(intVal) proc lastSon*(n: Indexable): Indexable = n.sons[^1] proc skipTypes*(t: PType, kinds: TTypeKinds): PType = ## Used throughout the compiler code to test whether a type tree contains or ## doesn't contain a specific type/types - it is often the case that only the ## last child nodes of a type tree need to be searched. This is a really hot ## path within the compiler! result = t while result.kind in kinds: result = lastSon(result) proc newIntTypeNode*(intVal: BiggestInt, typ: PType): PNode = # this is dirty. abstractVarRange isn't defined yet and therefor it # is duplicated here. const abstractVarRange = {tyGenericInst, tyRange, tyVar, tyDistinct, tyOrdinal, tyTypeDesc, tyAlias, tyInferred, tySink, tyOwned} case skipTypes(typ, abstractVarRange).kind of tyInt: result = newNode(nkIntLit) of tyInt8: result = newNode(nkInt8Lit) of tyInt16: result = newNode(nkInt16Lit) of tyInt32: result = newNode(nkInt32Lit) of tyInt64: result = newNode(nkInt64Lit) of tyChar: result = newNode(nkCharLit) of tyUInt: result = newNode(nkUIntLit) of tyUInt8: result = newNode(nkUInt8Lit) of tyUInt16: result = newNode(nkUInt16Lit) of tyUInt32: result = newNode(nkUInt32Lit) of tyUInt64: result = newNode(nkUInt64Lit) else: # tyBool, tyEnum # XXX: does this really need to be the kind nkIntLit? result = newNode(nkIntLit) result.intVal = intVal result.typ = typ proc newIntTypeNode*(intVal: Int128, typ: PType): PNode = # XXX: introduce range check newIntTypeNode(castToInt64(intVal), typ) proc newFloatNode*(kind: TNodeKind, floatVal: BiggestFloat): PNode = result = newNode(kind) result.floatVal = floatVal proc newStrNode*(kind: TNodeKind, strVal: string): PNode = result = newNode(kind) result.strVal = strVal proc newStrNode*(strVal: string; info: TLineInfo): PNode = result = newNodeI(nkStrLit, info) result.strVal = strVal proc addSon*(father, son: PNode) = assert son != nil when not defined(nimNoNilSeqs): if isNil(father.sons): father.sons = @[] add(father.sons, son) proc newProcNode*(kind: TNodeKind, info: TLineInfo, body: PNode, params, name, pattern, genericParams, pragmas, exceptions: PNode): PNode = result = newNodeI(kind, info) result.sons = @[name, pattern, genericParams, params, pragmas, exceptions, body] const UnspecifiedLockLevel* = TLockLevel(-1'i16) MaxLockLevel* = 1000'i16 UnknownLockLevel* = TLockLevel(1001'i16) AttachedOpToStr*: array[TTypeAttachedOp, string] = ["=destroy", "=", "=sink", "=deepcopy"] proc `$`*(x: TLockLevel): string = if x.ord == UnspecifiedLockLevel.ord: result = "<unspecified>" elif x.ord == UnknownLockLevel.ord: result = "<unknown>" else: result = $int16(x) proc `$`*(s: PSym): string = if s != nil: result = s.name.s & "@" & $s.id else: result = "<nil>" proc newType*(kind: TTypeKind, owner: PSym): PType = new(result) result.kind = kind result.owner = owner result.size = -1 result.align = -1 # default alignment result.id = getID() result.uniqueId = result.id result.lockLevel = UnspecifiedLockLevel when debugIds: registerId(result) when false: if result.id == 76426: echo "KNID ", kind writeStackTrace() proc mergeLoc(a: var TLoc, b: TLoc) = if a.k == low(a.k): a.k = b.k if a.storage == low(a.storage): a.storage = b.storage a.flags = a.flags + b.flags if a.lode == nil: a.lode = b.lode if a.r == nil: a.r = b.r proc newSons*(father: Indexable, length: int) = when defined(nimNoNilSeqs): setLen(father.sons, length) else: if isNil(father.sons): newSeq(father.sons, length) else: setLen(father.sons, length) proc assignType*(dest, src: PType) = dest.kind = src.kind dest.flags = src.flags dest.callConv = src.callConv dest.n = src.n dest.size = src.size dest.align = src.align dest.attachedOps = src.attachedOps dest.lockLevel = src.lockLevel # this fixes 'type TLock = TSysLock': if src.sym != nil: if dest.sym != nil: dest.sym.flags = dest.sym.flags + (src.sym.flags-{sfExported}) if dest.sym.annex == nil: dest.sym.annex = src.sym.annex mergeLoc(dest.sym.loc, src.sym.loc) else: dest.sym = src.sym newSons(dest, len(src)) for i in 0 ..< len(src): dest.sons[i] = src.sons[i] proc copyType*(t: PType, owner: PSym, keepId: bool): PType = result = newType(t.kind, owner) assignType(result, t) if keepId: result.id = t.id else: when debugIds: registerId(result) result.sym = t.sym # backend-info should not be copied proc exactReplica*(t: PType): PType = copyType(t, t.owner, true) proc copySym*(s: PSym): PSym = result = newSym(s.kind, s.name, s.owner, s.info, s.options) #result.ast = nil # BUGFIX; was: s.ast which made problems result.typ = s.typ when debugIds: registerId(result) result.flags = s.flags result.magic = s.magic if s.kind == skModule: copyStrTable(result.tab, s.tab) result.options = s.options result.position = s.position result.loc = s.loc result.annex = s.annex # BUGFIX if result.kind in {skVar, skLet, skField}: result.guard = s.guard proc createModuleAlias*(s: PSym, newIdent: PIdent, info: TLineInfo; options: TOptions): PSym = result = newSym(s.kind, newIdent, s.owner, info, options) # keep ID! result.ast = s.ast result.id = s.id result.flags = s.flags system.shallowCopy(result.tab, s.tab) result.options = s.options result.position = s.position result.loc = s.loc result.annex = s.annex # XXX once usedGenerics is used, ensure module aliases keep working! assert s.usedGenerics.len == 0 proc initStrTable*(x: var TStrTable) = x.counter = 0 newSeq(x.data, StartSize) proc newStrTable*: TStrTable = initStrTable(result) proc initIdTable*(x: var TIdTable) = x.counter = 0 newSeq(x.data, StartSize) proc newIdTable*: TIdTable = initIdTable(result) proc resetIdTable*(x: var TIdTable) = x.counter = 0 # clear and set to old initial size: setLen(x.data, 0) setLen(x.data, StartSize) proc initObjectSet*(x: var TObjectSet) = x.counter = 0 newSeq(x.data, StartSize) proc initIdNodeTable*(x: var TIdNodeTable) = x.counter = 0 newSeq(x.data, StartSize) proc initNodeTable*(x: var TNodeTable) = x.counter = 0 newSeq(x.data, StartSize) proc skipTypes*(t: PType, kinds: TTypeKinds; maxIters: int): PType = result = t var i = maxIters while result.kind in kinds: result = lastSon(result) dec i if i == 0: return nil proc skipTypesOrNil*(t: PType, kinds: TTypeKinds): PType = ## same as skipTypes but handles 'nil' result = t while result != nil and result.kind in kinds: if result.len == 0: return nil result = lastSon(result) proc isGCedMem*(t: PType): bool {.inline.} = result = t.kind in {tyString, tyRef, tySequence} or t.kind == tyProc and t.callConv == ccClosure proc propagateToOwner*(owner, elem: PType) = const HaveTheirOwnEmpty = {tySequence, tyOpt, tySet, tyPtr, tyRef, tyProc} owner.flags = owner.flags + (elem.flags * {tfHasMeta, tfTriggersCompileTime}) if tfNotNil in elem.flags: if owner.kind in {tyGenericInst, tyGenericBody, tyGenericInvocation}: owner.flags.incl tfNotNil elif owner.kind notin HaveTheirOwnEmpty: owner.flags.incl tfNeedsInit if tfNeedsInit in elem.flags: if owner.kind in HaveTheirOwnEmpty: discard else: owner.flags.incl tfNeedsInit if elem.isMetaType: owner.flags.incl tfHasMeta if tfHasAsgn in elem.flags: let o2 = owner.skipTypes({tyGenericInst, tyAlias, tySink}) if o2.kind in {tyTuple, tyObject, tyArray, tySequence, tyOpt, tySet, tyDistinct, tyOpenArray, tyVarargs}: o2.flags.incl tfHasAsgn owner.flags.incl tfHasAsgn if tfHasOwned in elem.flags: let o2 = owner.skipTypes({tyGenericInst, tyAlias, tySink}) if o2.kind in {tyTuple, tyObject, tyArray, tySequence, tyOpt, tySet, tyDistinct, tyOpenArray, tyVarargs}: o2.flags.incl tfHasOwned owner.flags.incl tfHasOwned if owner.kind notin {tyProc, tyGenericInst, tyGenericBody, tyGenericInvocation, tyPtr}: let elemB = elem.skipTypes({tyGenericInst, tyAlias, tySink}) if elemB.isGCedMem or tfHasGCedMem in elemB.flags: # for simplicity, we propagate this flag even to generics. We then # ensure this doesn't bite us in sempass2. owner.flags.incl tfHasGCedMem proc rawAddSon*(father, son: PType) = when not defined(nimNoNilSeqs): if isNil(father.sons): father.sons = @[] add(father.sons, son) if not son.isNil: propagateToOwner(father, son) proc rawAddSonNoPropagationOfTypeFlags*(father, son: PType) = when not defined(nimNoNilSeqs): if isNil(father.sons): father.sons = @[] add(father.sons, son) proc addSonNilAllowed*(father, son: PNode) = when not defined(nimNoNilSeqs): if isNil(father.sons): father.sons = @[] add(father.sons, son) proc delSon*(father: PNode, idx: int) = when defined(nimNoNilSeqs): if father.len == 0: return else: if isNil(father.sons): return var length = len(father) for i in idx .. length - 2: father.sons[i] = father.sons[i + 1] setLen(father.sons, length - 1) proc copyNode*(src: PNode): PNode = # does not copy its sons! if src == nil: return nil result = newNode(src.kind) result.info = src.info result.typ = src.typ result.flags = src.flags * PersistentNodeFlags result.comment = src.comment when defined(useNodeIds): if result.id == nodeIdToDebug: echo "COMES FROM ", src.id case src.kind of nkCharLit..nkUInt64Lit: result.intVal = src.intVal of nkFloatLiterals: result.floatVal = src.floatVal of nkSym: result.sym = src.sym of nkIdent: result.ident = src.ident of nkStrLit..nkTripleStrLit: result.strVal = src.strVal else: discard proc shallowCopy*(src: PNode): PNode = # does not copy its sons, but provides space for them: if src == nil: return nil result = newNode(src.kind) result.info = src.info result.typ = src.typ result.flags = src.flags * PersistentNodeFlags result.comment = src.comment when defined(useNodeIds): if result.id == nodeIdToDebug: echo "COMES FROM ", src.id case src.kind of nkCharLit..nkUInt64Lit: result.intVal = src.intVal of nkFloatLiterals: result.floatVal = src.floatVal of nkSym: result.sym = src.sym of nkIdent: result.ident = src.ident of nkStrLit..nkTripleStrLit: result.strVal = src.strVal else: newSeq(result.sons, len(src)) proc copyTree*(src: PNode): PNode = # copy a whole syntax tree; performs deep copying if src == nil: return nil result = newNode(src.kind) result.info = src.info result.typ = src.typ result.flags = src.flags * PersistentNodeFlags result.comment = src.comment when defined(useNodeIds): if result.id == nodeIdToDebug: echo "COMES FROM ", src.id case src.kind of nkCharLit..nkUInt64Lit: result.intVal = src.intVal of nkFloatLiterals: result.floatVal = src.floatVal of nkSym: result.sym = src.sym of nkIdent: result.ident = src.ident of nkStrLit..nkTripleStrLit: result.strVal = src.strVal else: newSeq(result.sons, len(src)) for i in 0 ..< len(src): result.sons[i] = copyTree(src.sons[i]) proc hasSonWith*(n: PNode, kind: TNodeKind): bool = for i in 0 ..< len(n): if n.sons[i].kind == kind: return true result = false proc hasNilSon*(n: PNode): bool = for i in 0 ..< safeLen(n): if n.sons[i] == nil: return true elif hasNilSon(n.sons[i]): return true result = false proc containsNode*(n: PNode, kinds: TNodeKinds): bool = if n == nil: return case n.kind of nkEmpty..nkNilLit: result = n.kind in kinds else: for i in 0 ..< len(n): if n.kind in kinds or containsNode(n.sons[i], kinds): return true proc hasSubnodeWith*(n: PNode, kind: TNodeKind): bool = case n.kind of nkEmpty..nkNilLit: result = n.kind == kind else: for i in 0 ..< len(n): if (n.sons[i].kind == kind) or hasSubnodeWith(n.sons[i], kind): return true result = false proc getInt*(a: PNode): Int128 = case a.kind of nkCharLit, nkUIntLit..nkUInt64Lit: result = toInt128(cast[uint64](a.intVal)) of nkInt8Lit..nkInt64Lit: result = toInt128(a.intVal) of nkIntLit: # XXX: enable this assert # assert a.typ.kind notin {tyChar, tyUint..tyUInt64} result = toInt128(a.intVal) else: raiseRecoverableError("cannot extract number from invalid AST node") proc getInt64*(a: PNode): int64 {.deprecated: "use getInt".} = case a.kind of nkCharLit, nkUIntLit..nkUInt64Lit, nkIntLit..nkInt64Lit: result = a.intVal else: raiseRecoverableError("cannot extract number from invalid AST node") proc getFloat*(a: PNode): BiggestFloat = case a.kind of nkFloatLiterals: result = a.floatVal of nkCharLit, nkUIntLit..nkUInt64Lit, nkIntLit..nkInt64Lit: result = BiggestFloat a.intVal else: raiseRecoverableError("cannot extract number from invalid AST node") #doAssert false, "getFloat" #internalError(a.info, "getFloat") #result = 0.0 proc getStr*(a: PNode): string = case a.kind of nkStrLit..nkTripleStrLit: result = a.strVal of nkNilLit: # let's hope this fixes more problems than it creates: when defined(nimNoNilSeqs): result = "" else: result = nil else: raiseRecoverableError("cannot extract string from invalid AST node") #doAssert false, "getStr" #internalError(a.info, "getStr") #result = "" proc getStrOrChar*(a: PNode): string = case a.kind of nkStrLit..nkTripleStrLit: result = a.strVal of nkCharLit..nkUInt64Lit: result = $chr(int(a.intVal)) else: raiseRecoverableError("cannot extract string from invalid AST node") #doAssert false, "getStrOrChar" #internalError(a.info, "getStrOrChar") #result = "" proc isGenericRoutine*(s: PSym): bool = case s.kind of skProcKinds: result = sfFromGeneric in s.flags or (s.ast != nil and s.ast[genericParamsPos].kind != nkEmpty) else: discard proc skipGenericOwner*(s: PSym): PSym = ## Generic instantiations are owned by their originating generic ## symbol. This proc skips such owners and goes straight to the owner ## of the generic itself (the module or the enclosing proc). result = if s.kind in skProcKinds and sfFromGeneric in s.flags: s.owner.owner else: s.owner proc originatingModule*(s: PSym): PSym = result = s.owner while result.kind != skModule: result = result.owner proc isRoutine*(s: PSym): bool {.inline.} = result = s.kind in skProcKinds proc isCompileTimeProc*(s: PSym): bool {.inline.} = result = s.kind == skMacro or s.kind == skProc and sfCompileTime in s.flags proc isRunnableExamples*(n: PNode): bool = # Templates and generics don't perform symbol lookups. result = n.kind == nkSym and n.sym.magic == mRunnableExamples or n.kind == nkIdent and n.ident.s == "runnableExamples" proc requiredParams*(s: PSym): int = # Returns the number of required params (without default values) # XXX: Perhaps we can store this in the `offset` field of the # symbol instead? for i in 1 ..< s.typ.len: if s.typ.n[i].sym.ast != nil: return i - 1 return s.typ.len - 1 proc hasPattern*(s: PSym): bool {.inline.} = result = isRoutine(s) and s.ast.sons[patternPos].kind != nkEmpty iterator items*(n: PNode): PNode = for i in 0..<n.safeLen: yield n.sons[i] iterator pairs*(n: PNode): tuple[i: int, n: PNode] = for i in 0..<n.safeLen: yield (i, n.sons[i]) proc isAtom*(n: PNode): bool {.inline.} = result = n.kind >= nkNone and n.kind <= nkNilLit proc isEmptyType*(t: PType): bool {.inline.} = ## 'void' and 'stmt' types are often equivalent to 'nil' these days: result = t == nil or t.kind in {tyVoid, tyTyped} proc makeStmtList*(n: PNode): PNode = if n.kind == nkStmtList: result = n else: result = newNodeI(nkStmtList, n.info) result.add n proc skipStmtList*(n: PNode): PNode = if n.kind in {nkStmtList, nkStmtListExpr}: for i in 0 .. n.len-2: if n[i].kind notin {nkEmpty, nkCommentStmt}: return n result = n.lastSon else: result = n proc toVar*(typ: PType): PType = ## If ``typ`` is not a tyVar then it is converted into a `var <typ>` and ## returned. Otherwise ``typ`` is simply returned as-is. result = typ if typ.kind != tyVar: result = newType(tyVar, typ.owner) rawAddSon(result, typ) proc toRef*(typ: PType): PType = ## If ``typ`` is a tyObject then it is converted into a `ref <typ>` and ## returned. Otherwise ``typ`` is simply returned as-is. if typ.skipTypes({tyAlias, tyGenericInst}).kind == tyObject: result = newType(tyRef, typ.owner) rawAddSon(result, typ) proc toObject*(typ: PType): PType = ## If ``typ`` is a tyRef then its immediate son is returned (which in many ## cases should be a ``tyObject``). ## Otherwise ``typ`` is simply returned as-is. let t = typ.skipTypes({tyAlias, tyGenericInst}) if t.kind == tyRef: t.lastSon else: typ proc isImportedException*(t: PType; conf: ConfigRef): bool = assert t != nil if optNoCppExceptions in conf.globalOptions: return false let base = t.skipTypes({tyAlias, tyPtr, tyDistinct, tyGenericInst}) if base.sym != nil and {sfCompileToCpp, sfImportc} * base.sym.flags != {}: result = true proc isInfixAs*(n: PNode): bool = return n.kind == nkInfix and n[0].kind == nkIdent and n[0].ident.s == "as" proc findUnresolvedStatic*(n: PNode): PNode = if n.kind == nkSym and n.typ.kind == tyStatic and n.typ.n == nil: return n for son in n: let n = son.findUnresolvedStatic if n != nil: return n return nil when false: proc containsNil*(n: PNode): bool = # only for debugging if n.isNil: return true for i in 0 ..< n.safeLen: if n[i].containsNil: return true template hasDestructor*(t: PType): bool = {tfHasAsgn, tfHasOwned} * t.flags != {} template incompleteType*(t: PType): bool = t.sym != nil and {sfForward, sfNoForward} * t.sym.flags == {sfForward} template typeCompleted*(s: PSym) = incl s.flags, sfNoForward template getBody*(s: PSym): PNode = s.ast[bodyPos] template detailedInfo*(sym: PSym): string = sym.name.s proc isInlineIterator*(s: PSym): bool {.inline.} = s.kind == skIterator and s.typ.callConv != ccClosure proc isClosureIterator*(s: PSym): bool {.inline.} = s.kind == skIterator and s.typ.callConv == ccClosure proc isSinkParam*(s: PSym): bool {.inline.} = s.kind == skParam and (s.typ.kind == tySink or tfHasOwned in s.typ.flags) proc isSinkType*(t: PType): bool {.inline.} = t.kind == tySink or tfHasOwned in t.flags proc newProcType*(info: TLineInfo; owner: PSym): PType = result = newType(tyProc, owner) result.n = newNodeI(nkFormalParams, info) rawAddSon(result, nil) # return type # result.n[0] used to be `nkType`, but now it's `nkEffectList` because # the effects are now stored in there too ... this is a bit hacky, but as # usual we desperately try to save memory: addSon(result.n, newNodeI(nkEffectList, info)) proc addParam*(procType: PType; param: PSym) = param.position = procType.len-1 addSon(procType.n, newSymNode(param)) rawAddSon(procType, param.typ) template destructor*(t: PType): PSym = t.attachedOps[attachedDestructor] template assignment*(t: PType): PSym = t.attachedOps[attachedAsgn] template asink*(t: PType): PSym = t.attachedOps[attachedSink]