semfold.nim 31 KB

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