semfold.nim 31 KB

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