semfold.nim 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  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. if a.kind == nkBracket:
  274. var s = ""
  275. for b in a.sons:
  276. s.add b.getStrOrChar
  277. result = newStrNodeT(s, n, g)
  278. else:
  279. result = newStrNodeT(getStrOrChar(a), n, g)
  280. of mStrToStr: result = newStrNodeT(getStrOrChar(a), n, g)
  281. of mEnumToStr: result = newStrNodeT(ordinalValToString(a, g), n, g)
  282. of mArrToSeq:
  283. result = copyTree(a)
  284. result.typ = n.typ
  285. of mCompileOption:
  286. result = newIntNodeT(toInt128(ord(commands.testCompileOption(g.config, a.getStr, n.info))), n, idgen, g)
  287. of mCompileOptionArg:
  288. result = newIntNodeT(toInt128(ord(
  289. testCompileOptionArg(g.config, getStr(a), getStr(b), n.info))), n, idgen, g)
  290. of mEqProc:
  291. result = newIntNodeT(toInt128(ord(
  292. exprStructuralEquivalent(a, b, strictSymEquality=true))), n, idgen, g)
  293. else: discard
  294. proc getConstIfExpr(c: PSym, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode =
  295. result = nil
  296. for i in 0..<n.len:
  297. var it = n[i]
  298. if it.len == 2:
  299. var e = getConstExpr(c, it[0], idgen, g)
  300. if e == nil: return nil
  301. if getOrdValue(e) != 0:
  302. if result == nil:
  303. result = getConstExpr(c, it[1], idgen, g)
  304. if result == nil: return
  305. elif it.len == 1:
  306. if result == nil: result = getConstExpr(c, it[0], idgen, g)
  307. else: internalError(g.config, it.info, "getConstIfExpr()")
  308. proc leValueConv*(a, b: PNode): bool =
  309. result = false
  310. case a.kind
  311. of nkCharLit..nkUInt64Lit:
  312. case b.kind
  313. of nkCharLit..nkUInt64Lit: result = a.getInt <= b.getInt
  314. of nkFloatLit..nkFloat128Lit: result = a.intVal <= round(b.floatVal).int
  315. else: result = false #internalError(a.info, "leValueConv")
  316. of nkFloatLit..nkFloat128Lit:
  317. case b.kind
  318. of nkFloatLit..nkFloat128Lit: result = a.floatVal <= b.floatVal
  319. of nkCharLit..nkUInt64Lit: result = a.floatVal <= toFloat64(b.getInt)
  320. else: result = false # internalError(a.info, "leValueConv")
  321. else: result = false # internalError(a.info, "leValueConv")
  322. proc magicCall(m: PSym, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode =
  323. if n.len <= 1: return
  324. var s = n[0].sym
  325. var a = getConstExpr(m, n[1], idgen, g)
  326. var b, c: PNode
  327. if a == nil: return
  328. if n.len > 2:
  329. b = getConstExpr(m, n[2], idgen, g)
  330. if b == nil: return
  331. if n.len > 3:
  332. c = getConstExpr(m, n[3], idgen, g)
  333. if c == nil: return
  334. result = evalOp(s.magic, n, a, b, c, idgen, g)
  335. proc getAppType(n: PNode; g: ModuleGraph): PNode =
  336. if g.config.globalOptions.contains(optGenDynLib):
  337. result = newStrNodeT("lib", n, g)
  338. elif g.config.globalOptions.contains(optGenStaticLib):
  339. result = newStrNodeT("staticlib", n, g)
  340. elif g.config.globalOptions.contains(optGenGuiApp):
  341. result = newStrNodeT("gui", n, g)
  342. else:
  343. result = newStrNodeT("console", n, g)
  344. proc rangeCheck(n: PNode, value: Int128; g: ModuleGraph) =
  345. if value < firstOrd(g.config, n.typ) or value > lastOrd(g.config, n.typ):
  346. localError(g.config, n.info, "cannot convert " & $value &
  347. " to " & typeToString(n.typ))
  348. proc foldConv(n, a: PNode; idgen: IdGenerator; g: ModuleGraph; check = false): PNode =
  349. let dstTyp = skipTypes(n.typ, abstractRange - {tyTypeDesc})
  350. let srcTyp = skipTypes(a.typ, abstractRange - {tyTypeDesc})
  351. # if srcTyp.kind == tyUInt64 and "FFFFFF" in $n:
  352. # echo "n: ", n, " a: ", a
  353. # echo "from: ", srcTyp, " to: ", dstTyp, " check: ", check
  354. # echo getInt(a)
  355. # echo high(int64)
  356. # writeStackTrace()
  357. case dstTyp.kind
  358. of tyBool:
  359. case srcTyp.kind
  360. of tyFloat..tyFloat64:
  361. result = newIntNodeT(toInt128(getFloat(a) != 0.0), n, idgen, g)
  362. of tyChar, tyUInt..tyUInt64, tyInt..tyInt64:
  363. result = newIntNodeT(toInt128(a.getOrdValue != 0), n, idgen, g)
  364. of tyBool, tyEnum: # xxx shouldn't we disallow `tyEnum`?
  365. result = a
  366. result.typ = n.typ
  367. else: doAssert false, $srcTyp.kind
  368. of tyInt..tyInt64, tyUInt..tyUInt64:
  369. case srcTyp.kind
  370. of tyFloat..tyFloat64:
  371. result = newIntNodeT(toInt128(getFloat(a)), n, idgen, g)
  372. of tyChar, tyUInt..tyUInt64, tyInt..tyInt64:
  373. var val = a.getOrdValue
  374. if check: rangeCheck(n, val, g)
  375. result = newIntNodeT(val, n, idgen, g)
  376. if dstTyp.kind in {tyUInt..tyUInt64}:
  377. result.transitionIntKind(nkUIntLit)
  378. else:
  379. result = a
  380. result.typ = n.typ
  381. if check and result.kind in {nkCharLit..nkUInt64Lit}:
  382. rangeCheck(n, getInt(result), g)
  383. of tyFloat..tyFloat64:
  384. case srcTyp.kind
  385. of tyInt..tyInt64, tyUInt..tyUInt64, tyEnum, tyBool, tyChar:
  386. result = newFloatNodeT(toFloat64(getOrdValue(a)), n, g)
  387. else:
  388. result = a
  389. result.typ = n.typ
  390. of tyOpenArray, tyVarargs, tyProc, tyPointer:
  391. discard
  392. else:
  393. result = a
  394. result.typ = n.typ
  395. proc getArrayConstr(m: PSym, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode =
  396. if n.kind == nkBracket:
  397. result = n
  398. else:
  399. result = getConstExpr(m, n, idgen, g)
  400. if result == nil: result = n
  401. proc foldArrayAccess(m: PSym, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode =
  402. var x = getConstExpr(m, n[0], idgen, g)
  403. if x == nil or x.typ.skipTypes({tyGenericInst, tyAlias, tySink}).kind == tyTypeDesc:
  404. return
  405. var y = getConstExpr(m, n[1], idgen, g)
  406. if y == nil: return
  407. var idx = toInt64(getOrdValue(y))
  408. case x.kind
  409. of nkPar, nkTupleConstr:
  410. if idx >= 0 and idx < x.len:
  411. result = x.sons[idx]
  412. if result.kind == nkExprColonExpr: result = result[1]
  413. else:
  414. localError(g.config, n.info, formatErrorIndexBound(idx, x.len-1) & $n)
  415. of nkBracket:
  416. idx -= toInt64(firstOrd(g.config, x.typ))
  417. if idx >= 0 and idx < x.len: result = x[int(idx)]
  418. else: localError(g.config, n.info, formatErrorIndexBound(idx, x.len-1) & $n)
  419. of nkStrLit..nkTripleStrLit:
  420. result = newNodeIT(nkCharLit, x.info, n.typ)
  421. if idx >= 0 and idx < x.strVal.len:
  422. result.intVal = ord(x.strVal[int(idx)])
  423. else:
  424. localError(g.config, n.info, formatErrorIndexBound(idx, x.strVal.len-1) & $n)
  425. else: discard
  426. proc foldFieldAccess(m: PSym, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode =
  427. # a real field access; proc calls have already been transformed
  428. var x = getConstExpr(m, n[0], idgen, g)
  429. if x == nil or x.kind notin {nkObjConstr, nkPar, nkTupleConstr}: return
  430. var field = n[1].sym
  431. for i in ord(x.kind == nkObjConstr)..<x.len:
  432. var it = x[i]
  433. if it.kind != nkExprColonExpr:
  434. # lookup per index:
  435. result = x[field.position]
  436. if result.kind == nkExprColonExpr: result = result[1]
  437. return
  438. if it[0].sym.name.id == field.name.id:
  439. result = x[i][1]
  440. return
  441. localError(g.config, n.info, "field not found: " & field.name.s)
  442. proc foldConStrStr(m: PSym, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode =
  443. result = newNodeIT(nkStrLit, n.info, n.typ)
  444. result.strVal = ""
  445. for i in 1..<n.len:
  446. let a = getConstExpr(m, n[i], idgen, g)
  447. if a == nil: return nil
  448. result.strVal.add(getStrOrChar(a))
  449. proc newSymNodeTypeDesc*(s: PSym; idgen: IdGenerator; info: TLineInfo): PNode =
  450. result = newSymNode(s, info)
  451. if s.typ.kind != tyTypeDesc:
  452. result.typ = newType(tyTypeDesc, idgen.nextTypeId, s.owner)
  453. result.typ.addSonSkipIntLit(s.typ, idgen)
  454. else:
  455. result.typ = s.typ
  456. proc getConstExpr(m: PSym, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode =
  457. result = nil
  458. case n.kind
  459. of nkSym:
  460. var s = n.sym
  461. case s.kind
  462. of skEnumField:
  463. result = newIntNodeT(toInt128(s.position), n, idgen, g)
  464. of skConst:
  465. case s.magic
  466. of mIsMainModule: result = newIntNodeT(toInt128(ord(sfMainModule in m.flags)), n, idgen, g)
  467. of mCompileDate: result = newStrNodeT(getDateStr(), n, g)
  468. of mCompileTime: result = newStrNodeT(getClockStr(), n, g)
  469. of mCpuEndian: result = newIntNodeT(toInt128(ord(CPU[g.config.target.targetCPU].endian)), n, idgen, g)
  470. of mHostOS: result = newStrNodeT(toLowerAscii(platform.OS[g.config.target.targetOS].name), n, g)
  471. of mHostCPU: result = newStrNodeT(platform.CPU[g.config.target.targetCPU].name.toLowerAscii, n, g)
  472. of mBuildOS: result = newStrNodeT(toLowerAscii(platform.OS[g.config.target.hostOS].name), n, g)
  473. of mBuildCPU: result = newStrNodeT(platform.CPU[g.config.target.hostCPU].name.toLowerAscii, n, g)
  474. of mAppType: result = getAppType(n, g)
  475. of mIntDefine:
  476. if isDefined(g.config, s.name.s):
  477. try:
  478. result = newIntNodeT(toInt128(g.config.symbols[s.name.s].parseInt), n, idgen, g)
  479. except ValueError:
  480. localError(g.config, s.info,
  481. "{.intdefine.} const was set to an invalid integer: '" &
  482. g.config.symbols[s.name.s] & "'")
  483. else:
  484. result = copyTree(s.ast)
  485. of mStrDefine:
  486. if isDefined(g.config, s.name.s):
  487. result = newStrNodeT(g.config.symbols[s.name.s], n, g)
  488. else:
  489. result = copyTree(s.ast)
  490. of mBoolDefine:
  491. if isDefined(g.config, s.name.s):
  492. try:
  493. result = newIntNodeT(toInt128(g.config.symbols[s.name.s].parseBool.int), n, idgen, g)
  494. except ValueError:
  495. localError(g.config, s.info,
  496. "{.booldefine.} const was set to an invalid bool: '" &
  497. g.config.symbols[s.name.s] & "'")
  498. else:
  499. result = copyTree(s.ast)
  500. else:
  501. result = copyTree(s.ast)
  502. of skProc, skFunc, skMethod:
  503. result = n
  504. of skParam:
  505. if s.typ != nil and s.typ.kind == tyTypeDesc:
  506. result = newSymNodeTypeDesc(s, idgen, n.info)
  507. of skType:
  508. # XXX gensym'ed symbols can come here and cannot be resolved. This is
  509. # dirty, but correct.
  510. if s.typ != nil:
  511. result = newSymNodeTypeDesc(s, idgen, n.info)
  512. of skGenericParam:
  513. if s.typ.kind == tyStatic:
  514. if s.typ.n != nil and tfUnresolved notin s.typ.flags:
  515. result = s.typ.n
  516. result.typ = s.typ.base
  517. elif s.typ.isIntLit:
  518. result = s.typ.n
  519. else:
  520. result = newSymNodeTypeDesc(s, idgen, n.info)
  521. else: discard
  522. of nkCharLit..nkNilLit:
  523. result = copyNode(n)
  524. of nkIfExpr:
  525. result = getConstIfExpr(m, n, idgen, g)
  526. of nkCallKinds:
  527. if n[0].kind != nkSym: return
  528. var s = n[0].sym
  529. if s.kind != skProc and s.kind != skFunc: return
  530. try:
  531. case s.magic
  532. of mNone:
  533. # If it has no sideEffect, it should be evaluated. But not here.
  534. return
  535. of mLow:
  536. if skipTypes(n[1].typ, abstractVarRange).kind in tyFloat..tyFloat64:
  537. result = newFloatNodeT(firstFloat(n[1].typ), n, g)
  538. else:
  539. result = newIntNodeT(firstOrd(g.config, n[1].typ), n, idgen, g)
  540. of mHigh:
  541. if skipTypes(n[1].typ, abstractVar+{tyUserTypeClassInst}).kind notin
  542. {tySequence, tyString, tyCstring, tyOpenArray, tyVarargs}:
  543. if skipTypes(n[1].typ, abstractVarRange).kind in tyFloat..tyFloat64:
  544. result = newFloatNodeT(lastFloat(n[1].typ), n, g)
  545. else:
  546. result = newIntNodeT(lastOrd(g.config, skipTypes(n[1].typ, abstractVar)), n, idgen, g)
  547. else:
  548. var a = getArrayConstr(m, n[1], idgen, g)
  549. if a.kind == nkBracket:
  550. # we can optimize it away:
  551. result = newIntNodeT(toInt128(a.len-1), n, idgen, g)
  552. of mLengthOpenArray:
  553. var a = getArrayConstr(m, n[1], idgen, g)
  554. if a.kind == nkBracket:
  555. # we can optimize it away! This fixes the bug ``len(134)``.
  556. result = newIntNodeT(toInt128(a.len), n, idgen, g)
  557. else:
  558. result = magicCall(m, n, idgen, g)
  559. of mLengthArray:
  560. # It doesn't matter if the argument is const or not for mLengthArray.
  561. # This fixes bug #544.
  562. result = newIntNodeT(lengthOrd(g.config, n[1].typ), n, idgen, g)
  563. of mSizeOf:
  564. result = foldSizeOf(g.config, n, nil)
  565. of mAlignOf:
  566. result = foldAlignOf(g.config, n, nil)
  567. of mOffsetOf:
  568. result = foldOffsetOf(g.config, n, nil)
  569. of mAstToStr:
  570. result = newStrNodeT(renderTree(n[1], {renderNoComments}), n, g)
  571. of mConStrStr:
  572. result = foldConStrStr(m, n, idgen, g)
  573. of mIs:
  574. # The only kind of mIs node that comes here is one depending on some
  575. # generic parameter and that's (hopefully) handled at instantiation time
  576. discard
  577. else:
  578. result = magicCall(m, n, idgen, g)
  579. except OverflowDefect:
  580. localError(g.config, n.info, "over- or underflow")
  581. except DivByZeroDefect:
  582. localError(g.config, n.info, "division by zero")
  583. of nkAddr:
  584. var a = getConstExpr(m, n[0], idgen, g)
  585. if a != nil:
  586. result = n
  587. n[0] = a
  588. of nkBracket, nkCurly:
  589. result = copyNode(n)
  590. for i, son in n.pairs:
  591. var a = getConstExpr(m, son, idgen, g)
  592. if a == nil: return nil
  593. result.add a
  594. incl(result.flags, nfAllConst)
  595. of nkRange:
  596. var a = getConstExpr(m, n[0], idgen, g)
  597. if a == nil: return
  598. var b = getConstExpr(m, n[1], idgen, g)
  599. if b == nil: return
  600. result = copyNode(n)
  601. result.add a
  602. result.add b
  603. #of nkObjConstr:
  604. # result = copyTree(n)
  605. # for i in 1..<n.len:
  606. # var a = getConstExpr(m, n[i][1])
  607. # if a == nil: return nil
  608. # result[i][1] = a
  609. # incl(result.flags, nfAllConst)
  610. of nkPar, nkTupleConstr:
  611. # tuple constructor
  612. result = copyNode(n)
  613. if (n.len > 0) and (n[0].kind == nkExprColonExpr):
  614. for i, expr in n.pairs:
  615. let exprNew = copyNode(expr) # nkExprColonExpr
  616. exprNew.add expr[0]
  617. let a = getConstExpr(m, expr[1], idgen, g)
  618. if a == nil: return nil
  619. exprNew.add a
  620. result.add exprNew
  621. else:
  622. for i, expr in n.pairs:
  623. let a = getConstExpr(m, expr, idgen, g)
  624. if a == nil: return nil
  625. result.add a
  626. incl(result.flags, nfAllConst)
  627. of nkChckRangeF, nkChckRange64, nkChckRange:
  628. var a = getConstExpr(m, n[0], idgen, g)
  629. if a == nil: return
  630. if leValueConv(n[1], a) and leValueConv(a, n[2]):
  631. result = a # a <= x and x <= b
  632. result.typ = n.typ
  633. else:
  634. localError(g.config, n.info,
  635. "conversion from $1 to $2 is invalid" %
  636. [typeToString(n[0].typ), typeToString(n.typ)])
  637. of nkStringToCString, nkCStringToString:
  638. var a = getConstExpr(m, n[0], idgen, g)
  639. if a == nil: return
  640. result = a
  641. result.typ = n.typ
  642. of nkHiddenStdConv, nkHiddenSubConv, nkConv:
  643. var a = getConstExpr(m, n[1], idgen, g)
  644. if a == nil: return
  645. result = foldConv(n, a, idgen, g, check=true)
  646. of nkDerefExpr, nkHiddenDeref:
  647. let a = getConstExpr(m, n[0], idgen, g)
  648. if a != nil and a.kind == nkNilLit:
  649. result = nil
  650. #localError(g.config, n.info, "nil dereference is not allowed")
  651. of nkCast:
  652. var a = getConstExpr(m, n[1], idgen, g)
  653. if a == nil: return
  654. if n.typ != nil and n.typ.kind in NilableTypes:
  655. # we allow compile-time 'cast' for pointer types:
  656. result = a
  657. result.typ = n.typ
  658. of nkBracketExpr: result = foldArrayAccess(m, n, idgen, g)
  659. of nkDotExpr: result = foldFieldAccess(m, n, idgen, g)
  660. of nkCheckedFieldExpr:
  661. assert n[0].kind == nkDotExpr
  662. result = foldFieldAccess(m, n[0], idgen, g)
  663. of nkStmtListExpr:
  664. var i = 0
  665. while i <= n.len - 2:
  666. if n[i].kind in {nkComesFrom, nkCommentStmt, nkEmpty}: i.inc
  667. else: break
  668. if i == n.len - 1:
  669. result = getConstExpr(m, n[i], idgen, g)
  670. else:
  671. discard