semfold.nim 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # this module folds constants; used by semantic checking phase
  10. # and evaluation phase
  11. import
  12. strutils, options, ast, trees, nimsets,
  13. platform, math, msgs, idents, renderer, types,
  14. commands, magicsys, modulegraphs, strtabs, lineinfos
  15. proc errorType*(g: ModuleGraph): PType =
  16. ## creates a type representing an error state
  17. result = newType(tyError, nextId(g.idgen), g.owners[^1])
  18. result.flags.incl tfCheckedForDestructor
  19. proc newIntNodeT*(intVal: Int128, n: PNode; g: ModuleGraph): PNode =
  20. result = newIntTypeNode(intVal, n.typ)
  21. # See bug #6989. 'pred' et al only produce an int literal type if the
  22. # original type was 'int', not a distinct int etc.
  23. if n.typ.kind == tyInt:
  24. # access cache for the int lit type
  25. result.typ = getIntLitType(g, result)
  26. result.info = n.info
  27. proc newFloatNodeT*(floatVal: BiggestFloat, n: PNode; g: ModuleGraph): PNode =
  28. if n.typ.skipTypes(abstractInst).kind == tyFloat32:
  29. result = newFloatNode(nkFloat32Lit, floatVal)
  30. else:
  31. result = newFloatNode(nkFloatLit, floatVal)
  32. result.typ = n.typ
  33. result.info = n.info
  34. proc newStrNodeT*(strVal: string, n: PNode; g: ModuleGraph): PNode =
  35. result = newStrNode(nkStrLit, strVal)
  36. result.typ = n.typ
  37. result.info = n.info
  38. proc getConstExpr*(m: PSym, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode
  39. # evaluates the constant expression or returns nil if it is no constant
  40. # expression
  41. proc evalOp*(m: TMagic, n, a, b, c: PNode; g: ModuleGraph): PNode
  42. proc checkInRange(conf: ConfigRef; n: PNode, res: Int128): bool =
  43. res in firstOrd(conf, n.typ)..lastOrd(conf, n.typ)
  44. proc foldAdd(a, b: Int128, n: PNode; g: ModuleGraph): PNode =
  45. let res = a + b
  46. if checkInRange(g.config, n, res):
  47. result = newIntNodeT(res, n, g)
  48. proc foldSub(a, b: Int128, n: PNode; g: ModuleGraph): PNode =
  49. let res = a - b
  50. if checkInRange(g.config, n, res):
  51. result = newIntNodeT(res, n, g)
  52. proc foldUnarySub(a: Int128, n: PNode, g: ModuleGraph): PNode =
  53. if a != firstOrd(g.config, n.typ):
  54. result = newIntNodeT(-a, n, g)
  55. proc foldAbs(a: Int128, n: PNode; g: ModuleGraph): PNode =
  56. if a != firstOrd(g.config, n.typ):
  57. result = newIntNodeT(abs(a), n, g)
  58. proc foldMul(a, b: Int128, n: PNode; g: ModuleGraph): PNode =
  59. let res = a * b
  60. if checkInRange(g.config, n, res):
  61. return newIntNodeT(res, n, g)
  62. proc ordinalValToString*(a: PNode; g: ModuleGraph): string =
  63. # because $ has the param ordinal[T], `a` is not necessarily an enum, but an
  64. # ordinal
  65. var x = getInt(a)
  66. var t = skipTypes(a.typ, abstractRange)
  67. case t.kind
  68. of tyChar:
  69. result = $chr(toInt64(x) and 0xff)
  70. of tyEnum:
  71. var n = t.n
  72. for i in 0..<n.len:
  73. if n[i].kind != nkSym: internalError(g.config, a.info, "ordinalValToString")
  74. var field = n[i].sym
  75. if field.position == x:
  76. if field.ast == nil:
  77. return field.name.s
  78. else:
  79. return field.ast.strVal
  80. localError(g.config, a.info,
  81. "Cannot convert int literal to $1. The value is invalid." %
  82. [typeToString(t)])
  83. else:
  84. result = $x
  85. proc isFloatRange(t: PType): bool {.inline.} =
  86. result = t.kind == tyRange and t[0].kind in {tyFloat..tyFloat128}
  87. proc isIntRange(t: PType): bool {.inline.} =
  88. result = t.kind == tyRange and t[0].kind in {
  89. tyInt..tyInt64, tyUInt8..tyUInt32}
  90. proc pickIntRange(a, b: PType): PType =
  91. if isIntRange(a): result = a
  92. elif isIntRange(b): result = b
  93. else: result = a
  94. proc isIntRangeOrLit(t: PType): bool =
  95. result = isIntRange(t) or isIntLit(t)
  96. proc evalOp(m: TMagic, n, a, b, c: PNode; g: ModuleGraph): PNode =
  97. # b and c may be nil
  98. result = nil
  99. case m
  100. of mOrd: result = newIntNodeT(getOrdValue(a), n, g)
  101. of mChr: result = newIntNodeT(getInt(a), n, g)
  102. of mUnaryMinusI, mUnaryMinusI64: result = foldUnarySub(getInt(a), n, g)
  103. of mUnaryMinusF64: result = newFloatNodeT(-getFloat(a), n, g)
  104. of mNot: result = newIntNodeT(One - getInt(a), n, g)
  105. of mCard: result = newIntNodeT(toInt128(nimsets.cardSet(g.config, a)), n, g)
  106. of mBitnotI:
  107. if n.typ.isUnsigned:
  108. result = newIntNodeT(bitnot(getInt(a)).maskBytes(int(n.typ.size)), n, g)
  109. else:
  110. result = newIntNodeT(bitnot(getInt(a)), n, g)
  111. of mLengthArray: result = newIntNodeT(lengthOrd(g.config, a.typ), n, g)
  112. of mLengthSeq, mLengthOpenArray, mLengthStr:
  113. if a.kind == nkNilLit:
  114. result = newIntNodeT(Zero, n, g)
  115. elif a.kind in {nkStrLit..nkTripleStrLit}:
  116. result = newIntNodeT(toInt128(a.strVal.len), n, g)
  117. else:
  118. result = newIntNodeT(toInt128(a.len), n, g)
  119. of mUnaryPlusI, mUnaryPlusF64: result = a # throw `+` away
  120. # XXX: Hides overflow/underflow
  121. of mAbsI: result = foldAbs(getInt(a), n, g)
  122. of mSucc: result = foldAdd(getOrdValue(a), getInt(b), n, g)
  123. of mPred: result = foldSub(getOrdValue(a), getInt(b), n, g)
  124. of mAddI: result = foldAdd(getInt(a), getInt(b), n, g)
  125. of mSubI: result = foldSub(getInt(a), getInt(b), n, g)
  126. of mMulI: result = foldMul(getInt(a), getInt(b), n, g)
  127. of mMinI:
  128. let argA = getInt(a)
  129. let argB = getInt(b)
  130. result = newIntNodeT(if argA < argB: argA else: argB, n, g)
  131. of mMaxI:
  132. let argA = getInt(a)
  133. let argB = getInt(b)
  134. result = newIntNodeT(if argA > argB: argA else: argB, n, g)
  135. of mShlI:
  136. case skipTypes(n.typ, abstractRange).kind
  137. of tyInt8: result = newIntNodeT(toInt128(toInt8(getInt(a)) shl toInt64(getInt(b))), n, g)
  138. of tyInt16: result = newIntNodeT(toInt128(toInt16(getInt(a)) shl toInt64(getInt(b))), n, g)
  139. of tyInt32: result = newIntNodeT(toInt128(toInt32(getInt(a)) shl toInt64(getInt(b))), n, g)
  140. of tyInt64: result = newIntNodeT(toInt128(toInt64(getInt(a)) shl toInt64(getInt(b))), n, g)
  141. of tyInt:
  142. if g.config.target.intSize == 4:
  143. result = newIntNodeT(toInt128(toInt32(getInt(a)) shl toInt64(getInt(b))), n, g)
  144. else:
  145. result = newIntNodeT(toInt128(toInt64(getInt(a)) shl toInt64(getInt(b))), n, g)
  146. of tyUInt8: result = newIntNodeT(toInt128(toUInt8(getInt(a)) shl toInt64(getInt(b))), n, g)
  147. of tyUInt16: result = newIntNodeT(toInt128(toUInt16(getInt(a)) shl toInt64(getInt(b))), n, g)
  148. of tyUInt32: result = newIntNodeT(toInt128(toUInt32(getInt(a)) shl toInt64(getInt(b))), n, g)
  149. of tyUInt64: result = newIntNodeT(toInt128(toUInt64(getInt(a)) shl toInt64(getInt(b))), n, g)
  150. of tyUInt:
  151. if g.config.target.intSize == 4:
  152. result = newIntNodeT(toInt128(toUInt32(getInt(a)) shl toInt64(getInt(b))), n, g)
  153. else:
  154. result = newIntNodeT(toInt128(toUInt64(getInt(a)) shl toInt64(getInt(b))), n, g)
  155. else: internalError(g.config, n.info, "constant folding for shl")
  156. of mShrI:
  157. var a = cast[uint64](getInt(a))
  158. let b = cast[uint64](getInt(b))
  159. # To support the ``-d:nimOldShiftRight`` flag, we need to mask the
  160. # signed integers to cut off the extended sign bit in the internal
  161. # representation.
  162. if 0'u64 < b: # do not cut off the sign extension, when there is
  163. # no bit shifting happening.
  164. case skipTypes(n.typ, abstractRange).kind
  165. of tyInt8: a = a and 0xff'u64
  166. of tyInt16: a = a and 0xffff'u64
  167. of tyInt32: a = a and 0xffffffff'u64
  168. of tyInt:
  169. if g.config.target.intSize == 4:
  170. a = a and 0xffffffff'u64
  171. else:
  172. # unsigned and 64 bit integers don't need masking
  173. discard
  174. let c = cast[BiggestInt](a shr b)
  175. result = newIntNodeT(toInt128(c), n, g)
  176. of mAshrI:
  177. case skipTypes(n.typ, abstractRange).kind
  178. of tyInt8: result = newIntNodeT(toInt128(ashr(toInt8(getInt(a)), toInt8(getInt(b)))), n, g)
  179. of tyInt16: result = newIntNodeT(toInt128(ashr(toInt16(getInt(a)), toInt16(getInt(b)))), n, g)
  180. of tyInt32: result = newIntNodeT(toInt128(ashr(toInt32(getInt(a)), toInt32(getInt(b)))), n, g)
  181. of tyInt64, tyInt:
  182. result = newIntNodeT(toInt128(ashr(toInt64(getInt(a)), toInt64(getInt(b)))), n, g)
  183. else: internalError(g.config, n.info, "constant folding for ashr")
  184. of mDivI:
  185. let argA = getInt(a)
  186. let argB = getInt(b)
  187. if argB != Zero and (argA != firstOrd(g.config, n.typ) or argB != NegOne):
  188. result = newIntNodeT(argA div argB, n, g)
  189. of mModI:
  190. let argA = getInt(a)
  191. let argB = getInt(b)
  192. if argB != Zero and (argA != firstOrd(g.config, n.typ) or argB != NegOne):
  193. result = newIntNodeT(argA mod argB, n, g)
  194. of mAddF64: result = newFloatNodeT(getFloat(a) + getFloat(b), n, g)
  195. of mSubF64: result = newFloatNodeT(getFloat(a) - getFloat(b), n, g)
  196. of mMulF64: result = newFloatNodeT(getFloat(a) * getFloat(b), n, g)
  197. of mDivF64:
  198. result = newFloatNodeT(getFloat(a) / getFloat(b), n, g)
  199. of mIsNil: result = newIntNodeT(toInt128(ord(a.kind == nkNilLit)), n, g)
  200. of mLtI, mLtB, mLtEnum, mLtCh:
  201. result = newIntNodeT(toInt128(ord(getOrdValue(a) < getOrdValue(b))), n, g)
  202. of mLeI, mLeB, mLeEnum, mLeCh:
  203. result = newIntNodeT(toInt128(ord(getOrdValue(a) <= getOrdValue(b))), n, g)
  204. of mEqI, mEqB, mEqEnum, mEqCh:
  205. result = newIntNodeT(toInt128(ord(getOrdValue(a) == getOrdValue(b))), n, g)
  206. of mLtF64: result = newIntNodeT(toInt128(ord(getFloat(a) < getFloat(b))), n, g)
  207. of mLeF64: result = newIntNodeT(toInt128(ord(getFloat(a) <= getFloat(b))), n, g)
  208. of mEqF64: result = newIntNodeT(toInt128(ord(getFloat(a) == getFloat(b))), n, g)
  209. of mLtStr: result = newIntNodeT(toInt128(ord(getStr(a) < getStr(b))), n, g)
  210. of mLeStr: result = newIntNodeT(toInt128(ord(getStr(a) <= getStr(b))), n, g)
  211. of mEqStr: result = newIntNodeT(toInt128(ord(getStr(a) == getStr(b))), n, g)
  212. of mLtU:
  213. result = newIntNodeT(toInt128(ord(`<%`(toInt64(getOrdValue(a)), toInt64(getOrdValue(b))))), n, g)
  214. of mLeU:
  215. result = newIntNodeT(toInt128(ord(`<=%`(toInt64(getOrdValue(a)), toInt64(getOrdValue(b))))), n, g)
  216. of mBitandI, mAnd: result = newIntNodeT(bitand(a.getInt, b.getInt), n, g)
  217. of mBitorI, mOr: result = newIntNodeT(bitor(getInt(a), getInt(b)), n, g)
  218. of mBitxorI, mXor: result = newIntNodeT(bitxor(getInt(a), getInt(b)), n, g)
  219. of mAddU:
  220. let val = maskBytes(getInt(a) + getInt(b), int(n.typ.size))
  221. result = newIntNodeT(val, n, g)
  222. of mSubU:
  223. let val = maskBytes(getInt(a) - getInt(b), int(n.typ.size))
  224. result = newIntNodeT(val, n, g)
  225. # echo "subU: ", val, " n: ", n, " result: ", val
  226. of mMulU:
  227. let val = maskBytes(getInt(a) * getInt(b), int(n.typ.size))
  228. result = newIntNodeT(val, n, g)
  229. of mModU:
  230. let argA = maskBytes(getInt(a), int(a.typ.size))
  231. let argB = maskBytes(getInt(b), int(a.typ.size))
  232. if argB != Zero:
  233. result = newIntNodeT(argA mod argB, n, g)
  234. of mDivU:
  235. let argA = maskBytes(getInt(a), int(a.typ.size))
  236. let argB = maskBytes(getInt(b), int(a.typ.size))
  237. if argB != Zero:
  238. result = newIntNodeT(argA div argB, n, g)
  239. of mLeSet: result = newIntNodeT(toInt128(ord(containsSets(g.config, a, b))), n, g)
  240. of mEqSet: result = newIntNodeT(toInt128(ord(equalSets(g.config, a, b))), n, g)
  241. of mLtSet:
  242. result = newIntNodeT(toInt128(ord(
  243. containsSets(g.config, a, b) and not equalSets(g.config, a, b))), n, g)
  244. of mMulSet:
  245. result = nimsets.intersectSets(g.config, a, b)
  246. result.info = n.info
  247. of mPlusSet:
  248. result = nimsets.unionSets(g.config, a, b)
  249. result.info = n.info
  250. of mMinusSet:
  251. result = nimsets.diffSets(g.config, a, b)
  252. result.info = n.info
  253. of mConStrStr: result = newStrNodeT(getStrOrChar(a) & getStrOrChar(b), n, g)
  254. of mInSet: result = newIntNodeT(toInt128(ord(inSet(a, b))), n, g)
  255. of mRepr:
  256. # BUGFIX: we cannot eval mRepr here for reasons that I forgot.
  257. discard
  258. of mIntToStr, mInt64ToStr: result = newStrNodeT($(getOrdValue(a)), n, g)
  259. of mBoolToStr:
  260. if getOrdValue(a) == 0: result = newStrNodeT("false", n, g)
  261. else: result = newStrNodeT("true", n, g)
  262. of mFloatToStr: result = newStrNodeT($getFloat(a), n, g)
  263. of mCStrToStr, mCharToStr:
  264. if a.kind == nkBracket:
  265. var s = ""
  266. for b in a.sons:
  267. s.add b.getStrOrChar
  268. result = newStrNodeT(s, n, g)
  269. else:
  270. result = newStrNodeT(getStrOrChar(a), n, g)
  271. of mStrToStr: result = newStrNodeT(getStrOrChar(a), n, g)
  272. of mEnumToStr: result = newStrNodeT(ordinalValToString(a, g), n, g)
  273. of mArrToSeq:
  274. result = copyTree(a)
  275. result.typ = n.typ
  276. of mCompileOption:
  277. result = newIntNodeT(toInt128(ord(commands.testCompileOption(g.config, a.getStr, n.info))), n, g)
  278. of mCompileOptionArg:
  279. result = newIntNodeT(toInt128(ord(
  280. testCompileOptionArg(g.config, getStr(a), getStr(b), n.info))), n, g)
  281. of mEqProc:
  282. result = newIntNodeT(toInt128(ord(
  283. exprStructuralEquivalent(a, b, strictSymEquality=true))), n, g)
  284. else: discard
  285. proc getConstIfExpr(c: PSym, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode =
  286. result = nil
  287. for i in 0..<n.len:
  288. var it = n[i]
  289. if it.len == 2:
  290. var e = getConstExpr(c, it[0], idgen, g)
  291. if e == nil: return nil
  292. if getOrdValue(e) != 0:
  293. if result == nil:
  294. result = getConstExpr(c, it[1], idgen, g)
  295. if result == nil: return
  296. elif it.len == 1:
  297. if result == nil: result = getConstExpr(c, it[0], idgen, g)
  298. else: internalError(g.config, it.info, "getConstIfExpr()")
  299. proc leValueConv*(a, b: PNode): bool =
  300. result = false
  301. case a.kind
  302. of nkCharLit..nkUInt64Lit:
  303. case b.kind
  304. of nkCharLit..nkUInt64Lit: result = a.getInt <= b.getInt
  305. of nkFloatLit..nkFloat128Lit: result = a.intVal <= round(b.floatVal).int
  306. else: result = false #internalError(a.info, "leValueConv")
  307. of nkFloatLit..nkFloat128Lit:
  308. case b.kind
  309. of nkFloatLit..nkFloat128Lit: result = a.floatVal <= b.floatVal
  310. of nkCharLit..nkUInt64Lit: result = a.floatVal <= toFloat64(b.getInt)
  311. else: result = false # internalError(a.info, "leValueConv")
  312. else: result = false # internalError(a.info, "leValueConv")
  313. proc magicCall(m: PSym, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode =
  314. if n.len <= 1: return
  315. var s = n[0].sym
  316. var a = getConstExpr(m, n[1], idgen, g)
  317. var b, c: PNode
  318. if a == nil: return
  319. if n.len > 2:
  320. b = getConstExpr(m, n[2], idgen, g)
  321. if b == nil: return
  322. if n.len > 3:
  323. c = getConstExpr(m, n[3], idgen, g)
  324. if c == nil: return
  325. result = evalOp(s.magic, n, a, b, c, g)
  326. proc getAppType(n: PNode; g: ModuleGraph): PNode =
  327. if g.config.globalOptions.contains(optGenDynLib):
  328. result = newStrNodeT("lib", n, g)
  329. elif g.config.globalOptions.contains(optGenStaticLib):
  330. result = newStrNodeT("staticlib", n, g)
  331. elif g.config.globalOptions.contains(optGenGuiApp):
  332. result = newStrNodeT("gui", n, g)
  333. else:
  334. result = newStrNodeT("console", n, g)
  335. proc rangeCheck(n: PNode, value: Int128; g: ModuleGraph) =
  336. if value < firstOrd(g.config, n.typ) or value > lastOrd(g.config, n.typ):
  337. localError(g.config, n.info, "cannot convert " & $value &
  338. " to " & typeToString(n.typ))
  339. proc foldConv(n, a: PNode; g: ModuleGraph; check = false): PNode =
  340. let dstTyp = skipTypes(n.typ, abstractRange - {tyTypeDesc})
  341. let srcTyp = skipTypes(a.typ, abstractRange - {tyTypeDesc})
  342. # if srcTyp.kind == tyUInt64 and "FFFFFF" in $n:
  343. # echo "n: ", n, " a: ", a
  344. # echo "from: ", srcTyp, " to: ", dstTyp, " check: ", check
  345. # echo getInt(a)
  346. # echo high(int64)
  347. # writeStackTrace()
  348. case dstTyp.kind
  349. of tyBool:
  350. case srcTyp.kind
  351. of tyFloat..tyFloat64:
  352. result = newIntNodeT(toInt128(getFloat(a) != 0.0), n, g)
  353. of tyChar, tyUInt..tyUInt64, tyInt..tyInt64:
  354. result = newIntNodeT(toInt128(a.getOrdValue != 0), n, g)
  355. of tyBool, tyEnum: # xxx shouldn't we disallow `tyEnum`?
  356. result = a
  357. result.typ = n.typ
  358. else: doAssert false, $srcTyp.kind
  359. of tyInt..tyInt64, tyUInt..tyUInt64:
  360. case srcTyp.kind
  361. of tyFloat..tyFloat64:
  362. result = newIntNodeT(toInt128(getFloat(a)), n, g)
  363. of tyChar, tyUInt..tyUInt64, tyInt..tyInt64:
  364. var val = a.getOrdValue
  365. if check: rangeCheck(n, val, g)
  366. result = newIntNodeT(val, n, g)
  367. if dstTyp.kind in {tyUInt..tyUInt64}:
  368. result.transitionIntKind(nkUIntLit)
  369. else:
  370. result = a
  371. result.typ = n.typ
  372. if check and result.kind in {nkCharLit..nkUInt64Lit}:
  373. rangeCheck(n, getInt(result), g)
  374. of tyFloat..tyFloat64:
  375. case srcTyp.kind
  376. of tyInt..tyInt64, tyEnum, tyBool, tyChar:
  377. result = newFloatNodeT(toFloat64(getOrdValue(a)), n, g)
  378. else:
  379. result = a
  380. result.typ = n.typ
  381. of tyOpenArray, tyVarargs, tyProc, tyPointer:
  382. discard
  383. else:
  384. result = a
  385. result.typ = n.typ
  386. proc getArrayConstr(m: PSym, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode =
  387. if n.kind == nkBracket:
  388. result = n
  389. else:
  390. result = getConstExpr(m, n, idgen, g)
  391. if result == nil: result = n
  392. proc foldArrayAccess(m: PSym, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode =
  393. var x = getConstExpr(m, n[0], idgen, g)
  394. if x == nil or x.typ.skipTypes({tyGenericInst, tyAlias, tySink}).kind == tyTypeDesc:
  395. return
  396. var y = getConstExpr(m, n[1], idgen, g)
  397. if y == nil: return
  398. var idx = toInt64(getOrdValue(y))
  399. case x.kind
  400. of nkPar, nkTupleConstr:
  401. if idx >= 0 and idx < x.len:
  402. result = x.sons[idx]
  403. if result.kind == nkExprColonExpr: result = result[1]
  404. else:
  405. localError(g.config, n.info, formatErrorIndexBound(idx, x.len-1) & $n)
  406. of nkBracket:
  407. idx -= toInt64(firstOrd(g.config, x.typ))
  408. if idx >= 0 and idx < x.len: result = x[int(idx)]
  409. else: localError(g.config, n.info, formatErrorIndexBound(idx, x.len-1) & $n)
  410. of nkStrLit..nkTripleStrLit:
  411. result = newNodeIT(nkCharLit, x.info, n.typ)
  412. if idx >= 0 and idx < x.strVal.len:
  413. result.intVal = ord(x.strVal[int(idx)])
  414. else:
  415. localError(g.config, n.info, formatErrorIndexBound(idx, x.strVal.len-1) & $n)
  416. else: discard
  417. proc foldFieldAccess(m: PSym, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode =
  418. # a real field access; proc calls have already been transformed
  419. var x = getConstExpr(m, n[0], idgen, g)
  420. if x == nil or x.kind notin {nkObjConstr, nkPar, nkTupleConstr}: return
  421. var field = n[1].sym
  422. for i in ord(x.kind == nkObjConstr)..<x.len:
  423. var it = x[i]
  424. if it.kind != nkExprColonExpr:
  425. # lookup per index:
  426. result = x[field.position]
  427. if result.kind == nkExprColonExpr: result = result[1]
  428. return
  429. if it[0].sym.name.id == field.name.id:
  430. result = x[i][1]
  431. return
  432. localError(g.config, n.info, "field not found: " & field.name.s)
  433. proc foldConStrStr(m: PSym, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode =
  434. result = newNodeIT(nkStrLit, n.info, n.typ)
  435. result.strVal = ""
  436. for i in 1..<n.len:
  437. let a = getConstExpr(m, n[i], idgen, g)
  438. if a == nil: return nil
  439. result.strVal.add(getStrOrChar(a))
  440. proc newSymNodeTypeDesc*(s: PSym; idgen: IdGenerator; info: TLineInfo): PNode =
  441. result = newSymNode(s, info)
  442. if s.typ.kind != tyTypeDesc:
  443. result.typ = newType(tyTypeDesc, idgen.nextId, s.owner)
  444. result.typ.addSonSkipIntLit(s.typ, idgen)
  445. else:
  446. result.typ = s.typ
  447. proc getConstExpr(m: PSym, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode =
  448. result = nil
  449. case n.kind
  450. of nkSym:
  451. var s = n.sym
  452. case s.kind
  453. of skEnumField:
  454. result = newIntNodeT(toInt128(s.position), n, g)
  455. of skConst:
  456. case s.magic
  457. of mIsMainModule: result = newIntNodeT(toInt128(ord(sfMainModule in m.flags)), n, g)
  458. of mCompileDate: result = newStrNodeT(getDateStr(), n, g)
  459. of mCompileTime: result = newStrNodeT(getClockStr(), n, g)
  460. of mCpuEndian: result = newIntNodeT(toInt128(ord(CPU[g.config.target.targetCPU].endian)), n, g)
  461. of mHostOS: result = newStrNodeT(toLowerAscii(platform.OS[g.config.target.targetOS].name), n, g)
  462. of mHostCPU: result = newStrNodeT(platform.CPU[g.config.target.targetCPU].name.toLowerAscii, n, g)
  463. of mBuildOS: result = newStrNodeT(toLowerAscii(platform.OS[g.config.target.hostOS].name), n, g)
  464. of mBuildCPU: result = newStrNodeT(platform.CPU[g.config.target.hostCPU].name.toLowerAscii, n, g)
  465. of mAppType: result = getAppType(n, g)
  466. of mIntDefine:
  467. if isDefined(g.config, s.name.s):
  468. try:
  469. result = newIntNodeT(toInt128(g.config.symbols[s.name.s].parseInt), n, g)
  470. except ValueError:
  471. localError(g.config, s.info,
  472. "{.intdefine.} const was set to an invalid integer: '" &
  473. g.config.symbols[s.name.s] & "'")
  474. else:
  475. result = copyTree(s.ast)
  476. of mStrDefine:
  477. if isDefined(g.config, s.name.s):
  478. result = newStrNodeT(g.config.symbols[s.name.s], n, g)
  479. else:
  480. result = copyTree(s.ast)
  481. of mBoolDefine:
  482. if isDefined(g.config, s.name.s):
  483. try:
  484. result = newIntNodeT(toInt128(g.config.symbols[s.name.s].parseBool.int), n, g)
  485. except ValueError:
  486. localError(g.config, s.info,
  487. "{.booldefine.} const was set to an invalid bool: '" &
  488. g.config.symbols[s.name.s] & "'")
  489. else:
  490. result = copyTree(s.ast)
  491. else:
  492. result = copyTree(s.ast)
  493. of skProc, skFunc, skMethod:
  494. result = n
  495. of skParam:
  496. if s.typ != nil and s.typ.kind == tyTypeDesc:
  497. result = newSymNodeTypeDesc(s, idgen, n.info)
  498. of skType:
  499. # XXX gensym'ed symbols can come here and cannot be resolved. This is
  500. # dirty, but correct.
  501. if s.typ != nil:
  502. result = newSymNodeTypeDesc(s, idgen, n.info)
  503. of skGenericParam:
  504. if s.typ.kind == tyStatic:
  505. if s.typ.n != nil and tfUnresolved notin s.typ.flags:
  506. result = s.typ.n
  507. result.typ = s.typ.base
  508. elif s.typ.isIntLit:
  509. result = s.typ.n
  510. else:
  511. result = newSymNodeTypeDesc(s, idgen, n.info)
  512. else: discard
  513. of nkCharLit..nkNilLit:
  514. result = copyNode(n)
  515. of nkIfExpr:
  516. result = getConstIfExpr(m, n, idgen, g)
  517. of nkCallKinds:
  518. if n[0].kind != nkSym: return
  519. var s = n[0].sym
  520. if s.kind != skProc and s.kind != skFunc: return
  521. try:
  522. case s.magic
  523. of mNone:
  524. # If it has no sideEffect, it should be evaluated. But not here.
  525. return
  526. of mLow:
  527. if skipTypes(n[1].typ, abstractVarRange).kind in tyFloat..tyFloat64:
  528. result = newFloatNodeT(firstFloat(n[1].typ), n, g)
  529. else:
  530. result = newIntNodeT(firstOrd(g.config, n[1].typ), n, g)
  531. of mHigh:
  532. if skipTypes(n[1].typ, abstractVar+{tyUserTypeClassInst}).kind notin
  533. {tySequence, tyString, tyCString, tyOpenArray, tyVarargs}:
  534. if skipTypes(n[1].typ, abstractVarRange).kind in tyFloat..tyFloat64:
  535. result = newFloatNodeT(lastFloat(n[1].typ), n, g)
  536. else:
  537. result = newIntNodeT(lastOrd(g.config, skipTypes(n[1].typ, abstractVar)), n, g)
  538. else:
  539. var a = getArrayConstr(m, n[1], idgen, g)
  540. if a.kind == nkBracket:
  541. # we can optimize it away:
  542. result = newIntNodeT(toInt128(a.len-1), n, g)
  543. of mLengthOpenArray:
  544. var a = getArrayConstr(m, n[1], idgen, g)
  545. if a.kind == nkBracket:
  546. # we can optimize it away! This fixes the bug ``len(134)``.
  547. result = newIntNodeT(toInt128(a.len), n, g)
  548. else:
  549. result = magicCall(m, n, idgen, g)
  550. of mLengthArray:
  551. # It doesn't matter if the argument is const or not for mLengthArray.
  552. # This fixes bug #544.
  553. result = newIntNodeT(lengthOrd(g.config, n[1].typ), n, g)
  554. of mSizeOf:
  555. result = foldSizeOf(g.config, n, nil)
  556. of mAlignOf:
  557. result = foldAlignOf(g.config, n, nil)
  558. of mOffsetOf:
  559. result = foldOffsetOf(g.config, n, nil)
  560. of mAstToStr:
  561. result = newStrNodeT(renderTree(n[1], {renderNoComments}), n, g)
  562. of mConStrStr:
  563. result = foldConStrStr(m, n, idgen, g)
  564. of mIs:
  565. # The only kind of mIs node that comes here is one depending on some
  566. # generic parameter and that's (hopefully) handled at instantiation time
  567. discard
  568. else:
  569. result = magicCall(m, n, idgen, g)
  570. except OverflowDefect:
  571. localError(g.config, n.info, "over- or underflow")
  572. except DivByZeroDefect:
  573. localError(g.config, n.info, "division by zero")
  574. of nkAddr:
  575. var a = getConstExpr(m, n[0], idgen, g)
  576. if a != nil:
  577. result = n
  578. n[0] = a
  579. of nkBracket, nkCurly:
  580. result = copyNode(n)
  581. for i, son in n.pairs:
  582. var a = getConstExpr(m, son, idgen, g)
  583. if a == nil: return nil
  584. result.add a
  585. incl(result.flags, nfAllConst)
  586. of nkRange:
  587. var a = getConstExpr(m, n[0], idgen, g)
  588. if a == nil: return
  589. var b = getConstExpr(m, n[1], idgen, g)
  590. if b == nil: return
  591. result = copyNode(n)
  592. result.add a
  593. result.add b
  594. #of nkObjConstr:
  595. # result = copyTree(n)
  596. # for i in 1..<n.len:
  597. # var a = getConstExpr(m, n[i][1])
  598. # if a == nil: return nil
  599. # result[i][1] = a
  600. # incl(result.flags, nfAllConst)
  601. of nkPar, nkTupleConstr:
  602. # tuple constructor
  603. result = copyNode(n)
  604. if (n.len > 0) and (n[0].kind == nkExprColonExpr):
  605. for i, expr in n.pairs:
  606. let exprNew = copyNode(expr) # nkExprColonExpr
  607. exprNew.add expr[0]
  608. let a = getConstExpr(m, expr[1], idgen, g)
  609. if a == nil: return nil
  610. exprNew.add a
  611. result.add exprNew
  612. else:
  613. for i, expr in n.pairs:
  614. let a = getConstExpr(m, expr, idgen, g)
  615. if a == nil: return nil
  616. result.add a
  617. incl(result.flags, nfAllConst)
  618. of nkChckRangeF, nkChckRange64, nkChckRange:
  619. var a = getConstExpr(m, n[0], idgen, g)
  620. if a == nil: return
  621. if leValueConv(n[1], a) and leValueConv(a, n[2]):
  622. result = a # a <= x and x <= b
  623. result.typ = n.typ
  624. else:
  625. localError(g.config, n.info,
  626. "conversion from $1 to $2 is invalid" %
  627. [typeToString(n[0].typ), typeToString(n.typ)])
  628. of nkStringToCString, nkCStringToString:
  629. var a = getConstExpr(m, n[0], idgen, g)
  630. if a == nil: return
  631. result = a
  632. result.typ = n.typ
  633. of nkHiddenStdConv, nkHiddenSubConv, nkConv:
  634. var a = getConstExpr(m, n[1], idgen, g)
  635. if a == nil: return
  636. result = foldConv(n, a, g, check=true)
  637. of nkDerefExpr, nkHiddenDeref:
  638. let a = getConstExpr(m, n[0], idgen, g)
  639. if a != nil and a.kind == nkNilLit:
  640. localError(g.config, n.info, "nil dereference is not allowed")
  641. of nkCast:
  642. var a = getConstExpr(m, n[1], idgen, g)
  643. if a == nil: return
  644. if n.typ != nil and n.typ.kind in NilableTypes:
  645. # we allow compile-time 'cast' for pointer types:
  646. result = a
  647. result.typ = n.typ
  648. of nkBracketExpr: result = foldArrayAccess(m, n, idgen, g)
  649. of nkDotExpr: result = foldFieldAccess(m, n, idgen, g)
  650. of nkCheckedFieldExpr:
  651. result = foldFieldAccess(m, n[0], idgen, g)
  652. of nkStmtListExpr:
  653. var i = 0
  654. while i <= n.len - 2:
  655. if n[i].kind in {nkComesFrom, nkCommentStmt, nkEmpty}: i.inc
  656. else: break
  657. if i == n.len - 1:
  658. result = getConstExpr(m, n[i], idgen, g)
  659. else:
  660. discard