semfold.nim 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  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 check: rangeCheck(n, val, g)
  392. result = newIntNodeT(val, n, idgen, g)
  393. if dstTyp.kind in {tyUInt..tyUInt64}:
  394. result.transitionIntKind(nkUIntLit)
  395. else:
  396. result = a
  397. result.typ = n.typ
  398. if check and result.kind in {nkCharLit..nkUInt64Lit}:
  399. rangeCheck(n, getInt(result), g)
  400. of tyFloat..tyFloat64:
  401. case srcTyp.kind
  402. of tyInt..tyInt64, tyUInt..tyUInt64, tyEnum, tyBool, tyChar:
  403. result = newFloatNodeT(toFloat64(getOrdValue(a)), n, g)
  404. else:
  405. result = a
  406. result.typ = n.typ
  407. of tyOpenArray, tyVarargs, tyProc, tyPointer:
  408. result = nil
  409. else:
  410. result = a
  411. result.typ = n.typ
  412. proc getArrayConstr(m: PSym, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode =
  413. if n.kind == nkBracket:
  414. result = n
  415. else:
  416. result = getConstExpr(m, n, idgen, g)
  417. if result == nil: result = n
  418. proc foldArrayAccess(m: PSym, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode =
  419. var x = getConstExpr(m, n[0], idgen, g)
  420. if x == nil or x.typ.skipTypes({tyGenericInst, tyAlias, tySink}).kind == tyTypeDesc:
  421. return
  422. var y = getConstExpr(m, n[1], idgen, g)
  423. if y == nil: return
  424. var idx = toInt64(getOrdValue(y))
  425. case x.kind
  426. of nkPar, nkTupleConstr:
  427. if idx >= 0 and idx < x.len:
  428. result = x.sons[idx]
  429. if result.kind == nkExprColonExpr: result = result[1]
  430. else:
  431. result = nil
  432. localError(g.config, n.info, formatErrorIndexBound(idx, x.len-1) & $n)
  433. of nkBracket:
  434. idx -= toInt64(firstOrd(g.config, x.typ))
  435. if idx >= 0 and idx < x.len: result = x[int(idx)]
  436. else:
  437. result = nil
  438. localError(g.config, n.info, formatErrorIndexBound(idx, x.len-1) & $n)
  439. of nkStrLit..nkTripleStrLit:
  440. result = newNodeIT(nkCharLit, x.info, n.typ)
  441. if idx >= 0 and idx < x.strVal.len:
  442. result.intVal = ord(x.strVal[int(idx)])
  443. else:
  444. localError(g.config, n.info, formatErrorIndexBound(idx, x.strVal.len-1) & $n)
  445. else: result = nil
  446. proc foldFieldAccess(m: PSym, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode =
  447. # a real field access; proc calls have already been transformed
  448. result = nil
  449. if n[1].kind != nkSym: return nil
  450. var x = getConstExpr(m, n[0], idgen, g)
  451. if x == nil or x.kind notin {nkObjConstr, nkPar, nkTupleConstr}: return
  452. var field = n[1].sym
  453. for i in ord(x.kind == nkObjConstr)..<x.len:
  454. var it = x[i]
  455. if it.kind != nkExprColonExpr:
  456. # lookup per index:
  457. result = x[field.position]
  458. if result.kind == nkExprColonExpr: result = result[1]
  459. return
  460. if it[0].sym.name.id == field.name.id:
  461. result = x[i][1]
  462. return
  463. localError(g.config, n.info, "field not found: " & field.name.s)
  464. proc foldConStrStr(m: PSym, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode =
  465. result = newNodeIT(nkStrLit, n.info, n.typ)
  466. result.strVal = ""
  467. for i in 1..<n.len:
  468. let a = getConstExpr(m, n[i], idgen, g)
  469. if a == nil: return nil
  470. result.strVal.add(getStrOrChar(a))
  471. proc newSymNodeTypeDesc*(s: PSym; idgen: IdGenerator; info: TLineInfo): PNode =
  472. result = newSymNode(s, info)
  473. if s.typ.kind != tyTypeDesc:
  474. result.typ = newType(tyTypeDesc, idgen, s.owner)
  475. result.typ.addSonSkipIntLit(s.typ, idgen)
  476. else:
  477. result.typ = s.typ
  478. proc foldDefine(m, s: PSym, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode =
  479. result = nil
  480. var name = s.name.s
  481. let prag = extractPragma(s)
  482. if prag != nil:
  483. for it in prag:
  484. if it.kind in nkPragmaCallKinds and it.len == 2 and it[0].kind == nkIdent:
  485. let word = whichKeyword(it[0].ident)
  486. if word in {wStrDefine, wIntDefine, wBoolDefine, wDefine}:
  487. # should be processed in pragmas.nim already
  488. if it[1].kind in {nkStrLit, nkRStrLit, nkTripleStrLit}:
  489. name = it[1].strVal
  490. if isDefined(g.config, name):
  491. let str = g.config.symbols[name]
  492. case s.magic
  493. of mIntDefine:
  494. try:
  495. result = newIntNodeT(toInt128(str.parseInt), n, idgen, g)
  496. except ValueError:
  497. localError(g.config, s.info,
  498. "{.intdefine.} const was set to an invalid integer: '" &
  499. str & "'")
  500. of mStrDefine:
  501. result = newStrNodeT(str, n, g)
  502. of mBoolDefine:
  503. try:
  504. result = newIntNodeT(toInt128(str.parseBool.int), n, idgen, g)
  505. except ValueError:
  506. localError(g.config, s.info,
  507. "{.booldefine.} const was set to an invalid bool: '" &
  508. str & "'")
  509. of mGenericDefine:
  510. let rawTyp = s.typ
  511. # pretend we don't support distinct types
  512. let typ = rawTyp.skipTypes(abstractVarRange-{tyDistinct})
  513. try:
  514. template intNode(value): PNode =
  515. let val = toInt128(value)
  516. rangeCheck(n, val, g)
  517. newIntNodeT(val, n, idgen, g)
  518. case typ.kind
  519. of tyString, tyCstring:
  520. result = newStrNodeT(str, n, g)
  521. of tyInt..tyInt64:
  522. result = intNode(str.parseBiggestInt)
  523. of tyUInt..tyUInt64:
  524. result = intNode(str.parseBiggestUInt)
  525. of tyBool:
  526. result = intNode(str.parseBool.int)
  527. of tyEnum:
  528. # compile time parseEnum
  529. let ident = getIdent(g.cache, str)
  530. for e in typ.n:
  531. if e.kind != nkSym: internalError(g.config, "foldDefine for enum")
  532. let es = e.sym
  533. let match =
  534. if es.ast.isNil:
  535. es.name.id == ident.id
  536. else:
  537. es.ast.strVal == str
  538. if match:
  539. result = intNode(es.position)
  540. break
  541. if result.isNil:
  542. raise newException(ValueError, "invalid enum value: " & str)
  543. else:
  544. localError(g.config, s.info, "unsupported type $1 for define '$2'" %
  545. [name, typeToString(rawTyp)])
  546. except ValueError as e:
  547. localError(g.config, s.info,
  548. "could not process define '$1' of type $2; $3" %
  549. [name, typeToString(rawTyp), e.msg])
  550. else: result = copyTree(s.astdef) # unreachable
  551. else:
  552. result = copyTree(s.astdef)
  553. if result != nil:
  554. result.info = n.info
  555. proc getConstExpr(m: PSym, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode =
  556. result = nil
  557. case n.kind
  558. of nkSym:
  559. var s = n.sym
  560. case s.kind
  561. of skEnumField:
  562. result = newIntNodeT(toInt128(s.position), n, idgen, g)
  563. of skConst:
  564. case s.magic
  565. of mIsMainModule: result = newIntNodeT(toInt128(ord(sfMainModule in m.flags)), n, idgen, g)
  566. of mCompileDate: result = newStrNodeT(getDateStr(), n, g)
  567. of mCompileTime: result = newStrNodeT(getClockStr(), n, g)
  568. of mCpuEndian: result = newIntNodeT(toInt128(ord(CPU[g.config.target.targetCPU].endian)), n, idgen, g)
  569. of mHostOS: result = newStrNodeT(toLowerAscii(platform.OS[g.config.target.targetOS].name), n, g)
  570. of mHostCPU: result = newStrNodeT(platform.CPU[g.config.target.targetCPU].name.toLowerAscii, n, g)
  571. of mBuildOS: result = newStrNodeT(toLowerAscii(platform.OS[g.config.target.hostOS].name), n, g)
  572. of mBuildCPU: result = newStrNodeT(platform.CPU[g.config.target.hostCPU].name.toLowerAscii, n, g)
  573. of mAppType: result = getAppType(n, g)
  574. of mIntDefine, mStrDefine, mBoolDefine, mGenericDefine:
  575. result = foldDefine(m, s, n, idgen, g)
  576. else:
  577. result = copyTree(s.astdef)
  578. if result != nil:
  579. result.info = n.info
  580. of skProc, skFunc, skMethod:
  581. result = n
  582. of skParam:
  583. if s.typ != nil and s.typ.kind == tyTypeDesc:
  584. result = newSymNodeTypeDesc(s, idgen, n.info)
  585. of skType:
  586. # XXX gensym'ed symbols can come here and cannot be resolved. This is
  587. # dirty, but correct.
  588. if s.typ != nil:
  589. result = newSymNodeTypeDesc(s, idgen, n.info)
  590. of skGenericParam:
  591. if s.typ.kind == tyStatic:
  592. if s.typ.n != nil and tfUnresolved notin s.typ.flags:
  593. result = s.typ.n
  594. result.typ = s.typ.base
  595. elif s.typ.isIntLit:
  596. result = s.typ.n
  597. else:
  598. result = newSymNodeTypeDesc(s, idgen, n.info)
  599. else: discard
  600. of nkCharLit..nkNilLit:
  601. result = copyNode(n)
  602. of nkIfExpr:
  603. result = getConstIfExpr(m, n, idgen, g)
  604. of nkCallKinds:
  605. if n[0].kind != nkSym: return
  606. var s = n[0].sym
  607. if s.kind != skProc and s.kind != skFunc: return
  608. try:
  609. case s.magic
  610. of mNone:
  611. # If it has no sideEffect, it should be evaluated. But not here.
  612. return
  613. of mLow:
  614. if skipTypes(n[1].typ, abstractVarRange).kind in tyFloat..tyFloat64:
  615. result = newFloatNodeT(firstFloat(n[1].typ), n, g)
  616. else:
  617. result = newIntNodeT(firstOrd(g.config, n[1].typ), n, idgen, g)
  618. of mHigh:
  619. if skipTypes(n[1].typ, abstractVar+{tyUserTypeClassInst}).kind notin
  620. {tySequence, tyString, tyCstring, tyOpenArray, tyVarargs}:
  621. if skipTypes(n[1].typ, abstractVarRange).kind in tyFloat..tyFloat64:
  622. result = newFloatNodeT(lastFloat(n[1].typ), n, g)
  623. else:
  624. result = newIntNodeT(lastOrd(g.config, skipTypes(n[1].typ, abstractVar)), n, idgen, g)
  625. else:
  626. var a = getArrayConstr(m, n[1], idgen, g)
  627. if a.kind == nkBracket:
  628. # we can optimize it away:
  629. result = newIntNodeT(toInt128(a.len-1), n, idgen, g)
  630. of mLengthOpenArray:
  631. var a = getArrayConstr(m, n[1], idgen, g)
  632. if a.kind == nkBracket:
  633. # we can optimize it away! This fixes the bug ``len(134)``.
  634. result = newIntNodeT(toInt128(a.len), n, idgen, g)
  635. else:
  636. result = magicCall(m, n, idgen, g)
  637. of mLengthArray:
  638. # It doesn't matter if the argument is const or not for mLengthArray.
  639. # This fixes bug #544.
  640. result = newIntNodeT(lengthOrd(g.config, n[1].typ), n, idgen, g)
  641. of mSizeOf:
  642. result = foldSizeOf(g.config, n, nil)
  643. of mAlignOf:
  644. result = foldAlignOf(g.config, n, nil)
  645. of mOffsetOf:
  646. result = foldOffsetOf(g.config, n, nil)
  647. of mAstToStr:
  648. result = newStrNodeT(renderTree(n[1], {renderNoComments}), n, g)
  649. of mConStrStr:
  650. result = foldConStrStr(m, n, idgen, g)
  651. of mIs:
  652. # The only kind of mIs node that comes here is one depending on some
  653. # generic parameter and that's (hopefully) handled at instantiation time
  654. discard
  655. else:
  656. result = magicCall(m, n, idgen, g)
  657. except OverflowDefect:
  658. localError(g.config, n.info, "over- or underflow")
  659. except DivByZeroDefect:
  660. localError(g.config, n.info, "division by zero")
  661. of nkAddr:
  662. var a = getConstExpr(m, n[0], idgen, g)
  663. if a != nil:
  664. result = n
  665. n[0] = a
  666. of nkBracket, nkCurly:
  667. result = copyNode(n)
  668. for son in n.items:
  669. var a = getConstExpr(m, son, idgen, g)
  670. if a == nil: return nil
  671. result.add a
  672. incl(result.flags, nfAllConst)
  673. of nkRange:
  674. var a = getConstExpr(m, n[0], idgen, g)
  675. if a == nil: return
  676. var b = getConstExpr(m, n[1], idgen, g)
  677. if b == nil: return
  678. result = copyNode(n)
  679. result.add a
  680. result.add b
  681. #of nkObjConstr:
  682. # result = copyTree(n)
  683. # for i in 1..<n.len:
  684. # var a = getConstExpr(m, n[i][1])
  685. # if a == nil: return nil
  686. # result[i][1] = a
  687. # incl(result.flags, nfAllConst)
  688. of nkPar, nkTupleConstr:
  689. # tuple constructor
  690. result = copyNode(n)
  691. if (n.len > 0) and (n[0].kind == nkExprColonExpr):
  692. for expr in n.items:
  693. let exprNew = copyNode(expr) # nkExprColonExpr
  694. exprNew.add expr[0]
  695. let a = getConstExpr(m, expr[1], idgen, g)
  696. if a == nil: return nil
  697. exprNew.add a
  698. result.add exprNew
  699. else:
  700. for expr in n.items:
  701. let a = getConstExpr(m, expr, idgen, g)
  702. if a == nil: return nil
  703. result.add a
  704. incl(result.flags, nfAllConst)
  705. of nkChckRangeF, nkChckRange64, nkChckRange:
  706. var a = getConstExpr(m, n[0], idgen, g)
  707. if a == nil: return
  708. if leValueConv(n[1], a) and leValueConv(a, n[2]):
  709. result = a # a <= x and x <= b
  710. result.typ = n.typ
  711. else:
  712. localError(g.config, n.info,
  713. "conversion from $1 to $2 is invalid" %
  714. [typeToString(n[0].typ), typeToString(n.typ)])
  715. of nkStringToCString, nkCStringToString:
  716. var a = getConstExpr(m, n[0], idgen, g)
  717. if a == nil: return
  718. result = a
  719. result.typ = n.typ
  720. of nkHiddenStdConv, nkHiddenSubConv, nkConv:
  721. var a = getConstExpr(m, n[1], idgen, g)
  722. if a == nil: return
  723. result = foldConv(n, a, idgen, g, check=true)
  724. of nkDerefExpr, nkHiddenDeref:
  725. let a = getConstExpr(m, n[0], idgen, g)
  726. if a != nil and a.kind == nkNilLit:
  727. result = nil
  728. #localError(g.config, n.info, "nil dereference is not allowed")
  729. of nkCast:
  730. var a = getConstExpr(m, n[1], idgen, g)
  731. if a == nil: return
  732. if n.typ != nil and n.typ.kind in NilableTypes:
  733. # we allow compile-time 'cast' for pointer types:
  734. result = a
  735. result.typ = n.typ
  736. of nkBracketExpr: result = foldArrayAccess(m, n, idgen, g)
  737. of nkDotExpr: result = foldFieldAccess(m, n, idgen, g)
  738. of nkCheckedFieldExpr:
  739. assert n[0].kind == nkDotExpr
  740. result = foldFieldAccess(m, n[0], idgen, g)
  741. of nkStmtListExpr:
  742. var i = 0
  743. while i <= n.len - 2:
  744. if n[i].kind in {nkComesFrom, nkCommentStmt, nkEmpty}: i.inc
  745. else: break
  746. if i == n.len - 1:
  747. result = getConstExpr(m, n[i], idgen, g)
  748. else:
  749. discard