semfold.nim 31 KB

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