semfold.nim 28 KB

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