semfold.nim 31 KB

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