semfold.nim 28 KB

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