vm.nim 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498
  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 file implements the new evaluation engine for Nim code.
  10. ## An instruction is 1-3 int32s in memory, it is a register based VM.
  11. import
  12. std/[strutils, tables, parseutils],
  13. msgs, vmdef, vmgen, nimsets, types, passes,
  14. parser, vmdeps, idents, trees, renderer, options, transf,
  15. vmmarshal, gorgeimpl, lineinfos, btrees, macrocacheimpl,
  16. modulegraphs, sighashes, int128, vmprofiler
  17. import ast except getstr
  18. from semfold import leValueConv, ordinalValToString
  19. from evaltempl import evalTemplate
  20. from magicsys import getSysType
  21. const
  22. traceCode = defined(nimVMDebug)
  23. when hasFFI:
  24. import evalffi
  25. proc stackTraceAux(c: PCtx; x: PStackFrame; pc: int; recursionLimit=100) =
  26. if x != nil:
  27. if recursionLimit == 0:
  28. var calls = 0
  29. var x = x
  30. while x != nil:
  31. inc calls
  32. x = x.next
  33. msgWriteln(c.config, $calls & " calls omitted\n", {msgNoUnitSep})
  34. return
  35. stackTraceAux(c, x.next, x.comesFrom, recursionLimit-1)
  36. var info = c.debug[pc]
  37. # we now use a format similar to the one in lib/system/excpt.nim
  38. var s = ""
  39. # todo: factor with quotedFilename
  40. if optExcessiveStackTrace in c.config.globalOptions:
  41. s = toFullPath(c.config, info)
  42. else:
  43. s = toFilename(c.config, info)
  44. var line = toLinenumber(info)
  45. var col = toColumn(info)
  46. if line > 0:
  47. s.add('(')
  48. s.add($line)
  49. s.add(", ")
  50. s.add($(col + ColOffset))
  51. s.add(')')
  52. if x.prc != nil:
  53. for k in 1..max(1, 25-s.len): s.add(' ')
  54. s.add(x.prc.name.s)
  55. msgWriteln(c.config, s, {msgNoUnitSep})
  56. proc stackTraceImpl(c: PCtx, tos: PStackFrame, pc: int,
  57. msg: string, lineInfo: TLineInfo, infoOrigin: InstantiationInfo) {.noinline.} =
  58. # noinline to avoid code bloat
  59. msgWriteln(c.config, "stack trace: (most recent call last)", {msgNoUnitSep})
  60. stackTraceAux(c, tos, pc)
  61. let action = if c.mode == emRepl: doRaise else: doNothing
  62. # XXX test if we want 'globalError' for every mode
  63. let lineInfo = if lineInfo == TLineInfo.default: c.debug[pc] else: lineInfo
  64. liMessage(c.config, lineInfo, errGenerated, msg, action, infoOrigin)
  65. template stackTrace(c: PCtx, tos: PStackFrame, pc: int,
  66. msg: string, lineInfo: TLineInfo = TLineInfo.default) =
  67. stackTraceImpl(c, tos, pc, msg, lineInfo, instantiationInfo(-2, fullPaths = true))
  68. return
  69. proc bailOut(c: PCtx; tos: PStackFrame) =
  70. stackTrace(c, tos, c.exceptionInstr, "unhandled exception: " &
  71. c.currentExceptionA[3].skipColon.strVal &
  72. " [" & c.currentExceptionA[2].skipColon.strVal & "]")
  73. when not defined(nimComputedGoto):
  74. {.pragma: computedGoto.}
  75. proc ensureKind(n: var TFullReg, k: TRegisterKind) {.inline.} =
  76. if n.kind != k:
  77. n = TFullReg(kind: k)
  78. template ensureKind(k: untyped) {.dirty.} =
  79. ensureKind(regs[ra], k)
  80. template decodeB(k: untyped) {.dirty.} =
  81. let rb = instr.regB
  82. ensureKind(k)
  83. template decodeBC(k: untyped) {.dirty.} =
  84. let rb = instr.regB
  85. let rc = instr.regC
  86. ensureKind(k)
  87. template declBC() {.dirty.} =
  88. let rb = instr.regB
  89. let rc = instr.regC
  90. template decodeBImm(k: untyped) {.dirty.} =
  91. let rb = instr.regB
  92. let imm = instr.regC - byteExcess
  93. ensureKind(k)
  94. template decodeBx(k: untyped) {.dirty.} =
  95. let rbx = instr.regBx - wordExcess
  96. ensureKind(k)
  97. template move(a, b: untyped) {.dirty.} = system.shallowCopy(a, b)
  98. # XXX fix minor 'shallowCopy' overloading bug in compiler
  99. proc derefPtrToReg(address: BiggestInt, typ: PType, r: var TFullReg, isAssign: bool): bool =
  100. # nim bug: `isAssign: static bool` doesn't work, giving odd compiler error
  101. template fun(field, typ, rkind) =
  102. if isAssign:
  103. cast[ptr typ](address)[] = typ(r.field)
  104. else:
  105. r.ensureKind(rkind)
  106. let val = cast[ptr typ](address)[]
  107. when typ is SomeInteger | char:
  108. r.field = BiggestInt(val)
  109. else:
  110. r.field = val
  111. return true
  112. ## see also typeinfo.getBiggestInt
  113. case typ.kind
  114. of tyChar: fun(intVal, char, rkInt)
  115. of tyInt: fun(intVal, int, rkInt)
  116. of tyInt8: fun(intVal, int8, rkInt)
  117. of tyInt16: fun(intVal, int16, rkInt)
  118. of tyInt32: fun(intVal, int32, rkInt)
  119. of tyInt64: fun(intVal, int64, rkInt)
  120. of tyUInt: fun(intVal, uint, rkInt)
  121. of tyUInt8: fun(intVal, uint8, rkInt)
  122. of tyUInt16: fun(intVal, uint16, rkInt)
  123. of tyUInt32: fun(intVal, uint32, rkInt)
  124. of tyUInt64: fun(intVal, uint64, rkInt) # note: differs from typeinfo.getBiggestInt
  125. of tyFloat: fun(floatVal, float, rkFloat)
  126. of tyFloat32: fun(floatVal, float32, rkFloat)
  127. of tyFloat64: fun(floatVal, float64, rkFloat)
  128. else: return false
  129. proc createStrKeepNode(x: var TFullReg; keepNode=true) =
  130. if x.node.isNil or not keepNode:
  131. x.node = newNode(nkStrLit)
  132. elif x.node.kind == nkNilLit and keepNode:
  133. when defined(useNodeIds):
  134. let id = x.node.id
  135. x.node[] = TNode(kind: nkStrLit)
  136. when defined(useNodeIds):
  137. x.node.id = id
  138. elif x.node.kind notin {nkStrLit..nkTripleStrLit} or
  139. nfAllConst in x.node.flags:
  140. # XXX this is hacky; tests/txmlgen triggers it:
  141. x.node = newNode(nkStrLit)
  142. # It not only hackey, it is also wrong for tgentemplate. The primary
  143. # cause of bugs like these is that the VM does not properly distinguish
  144. # between variable definitions (var foo = e) and variable updates (foo = e).
  145. include vmhooks
  146. template createStr(x) =
  147. x.node = newNode(nkStrLit)
  148. template createSet(x) =
  149. x.node = newNode(nkCurly)
  150. proc moveConst(x: var TFullReg, y: TFullReg) =
  151. x.ensureKind(y.kind)
  152. case x.kind
  153. of rkNone: discard
  154. of rkInt: x.intVal = y.intVal
  155. of rkFloat: x.floatVal = y.floatVal
  156. of rkNode: x.node = y.node
  157. of rkRegisterAddr: x.regAddr = y.regAddr
  158. of rkNodeAddr: x.nodeAddr = y.nodeAddr
  159. # this seems to be the best way to model the reference semantics
  160. # of system.NimNode:
  161. template asgnRef(x, y: untyped) = moveConst(x, y)
  162. proc copyValue(src: PNode): PNode =
  163. if src == nil or nfIsRef in src.flags:
  164. return src
  165. result = newNode(src.kind)
  166. result.info = src.info
  167. result.typ = src.typ
  168. result.flags = src.flags * PersistentNodeFlags
  169. result.comment = src.comment
  170. when defined(useNodeIds):
  171. if result.id == nodeIdToDebug:
  172. echo "COMES FROM ", src.id
  173. case src.kind
  174. of nkCharLit..nkUInt64Lit: result.intVal = src.intVal
  175. of nkFloatLit..nkFloat128Lit: result.floatVal = src.floatVal
  176. of nkSym: result.sym = src.sym
  177. of nkIdent: result.ident = src.ident
  178. of nkStrLit..nkTripleStrLit: result.strVal = src.strVal
  179. else:
  180. newSeq(result.sons, src.len)
  181. for i in 0..<src.len:
  182. result[i] = copyValue(src[i])
  183. proc asgnComplex(x: var TFullReg, y: TFullReg) =
  184. x.ensureKind(y.kind)
  185. case x.kind
  186. of rkNone: discard
  187. of rkInt: x.intVal = y.intVal
  188. of rkFloat: x.floatVal = y.floatVal
  189. of rkNode: x.node = copyValue(y.node)
  190. of rkRegisterAddr: x.regAddr = y.regAddr
  191. of rkNodeAddr: x.nodeAddr = y.nodeAddr
  192. proc fastAsgnComplex(x: var TFullReg, y: TFullReg) =
  193. x.ensureKind(y.kind)
  194. case x.kind
  195. of rkNone: discard
  196. of rkInt: x.intVal = y.intVal
  197. of rkFloat: x.floatVal = y.floatVal
  198. of rkNode: x.node = y.node
  199. of rkRegisterAddr: x.regAddr = y.regAddr
  200. of rkNodeAddr: x.nodeAddr = y.nodeAddr
  201. proc writeField(n: var PNode, x: TFullReg) =
  202. case x.kind
  203. of rkNone: discard
  204. of rkInt:
  205. if n.kind == nkNilLit:
  206. n[] = TNode(kind: nkIntLit) # ideally, `nkPtrLit`
  207. n.intVal = x.intVal
  208. of rkFloat: n.floatVal = x.floatVal
  209. of rkNode: n = copyValue(x.node)
  210. of rkRegisterAddr: writeField(n, x.regAddr[])
  211. of rkNodeAddr: n = x.nodeAddr[]
  212. proc putIntoReg(dest: var TFullReg; n: PNode) =
  213. case n.kind
  214. of nkStrLit..nkTripleStrLit:
  215. dest = TFullReg(kind: rkNode, node: newStrNode(nkStrLit, n.strVal))
  216. of nkIntLit: # use `nkPtrLit` once this is added
  217. if dest.kind == rkNode: dest.node = n
  218. elif n.typ != nil and n.typ.kind in PtrLikeKinds:
  219. dest = TFullReg(kind: rkNode, node: n)
  220. else:
  221. dest = TFullReg(kind: rkInt, intVal: n.intVal)
  222. of {nkCharLit..nkUInt64Lit} - {nkIntLit}:
  223. dest = TFullReg(kind: rkInt, intVal: n.intVal)
  224. of nkFloatLit..nkFloat128Lit:
  225. dest = TFullReg(kind: rkFloat, floatVal: n.floatVal)
  226. else:
  227. dest = TFullReg(kind: rkNode, node: n)
  228. proc regToNode(x: TFullReg): PNode =
  229. case x.kind
  230. of rkNone: result = newNode(nkEmpty)
  231. of rkInt: result = newNode(nkIntLit); result.intVal = x.intVal
  232. of rkFloat: result = newNode(nkFloatLit); result.floatVal = x.floatVal
  233. of rkNode: result = x.node
  234. of rkRegisterAddr: result = regToNode(x.regAddr[])
  235. of rkNodeAddr: result = x.nodeAddr[]
  236. template getstr(a: untyped): untyped =
  237. (if a.kind == rkNode: a.node.strVal else: $chr(int(a.intVal)))
  238. proc pushSafePoint(f: PStackFrame; pc: int) =
  239. f.safePoints.add(pc)
  240. proc popSafePoint(f: PStackFrame) =
  241. discard f.safePoints.pop()
  242. type
  243. ExceptionGoto = enum
  244. ExceptionGotoHandler,
  245. ExceptionGotoFinally,
  246. ExceptionGotoUnhandled
  247. proc findExceptionHandler(c: PCtx, f: PStackFrame, exc: PNode):
  248. tuple[why: ExceptionGoto, where: int] =
  249. let raisedType = exc.typ.skipTypes(abstractPtrs)
  250. while f.safePoints.len > 0:
  251. var pc = f.safePoints.pop()
  252. var matched = false
  253. var pcEndExcept = pc
  254. # Scan the chain of exceptions starting at pc.
  255. # The structure is the following:
  256. # pc - opcExcept, <end of this block>
  257. # - opcExcept, <pattern1>
  258. # - opcExcept, <pattern2>
  259. # ...
  260. # - opcExcept, <patternN>
  261. # - Exception handler body
  262. # - ... more opcExcept blocks may follow
  263. # - ... an optional opcFinally block may follow
  264. #
  265. # Note that the exception handler body already contains a jump to the
  266. # finally block or, if that's not present, to the point where the execution
  267. # should continue.
  268. # Also note that opcFinally blocks are the last in the chain.
  269. while c.code[pc].opcode == opcExcept:
  270. # Where this Except block ends
  271. pcEndExcept = pc + c.code[pc].regBx - wordExcess
  272. inc pc
  273. # A series of opcExcept follows for each exception type matched
  274. while c.code[pc].opcode == opcExcept:
  275. let excIndex = c.code[pc].regBx - wordExcess
  276. let exceptType =
  277. if excIndex > 0: c.types[excIndex].skipTypes(abstractPtrs)
  278. else: nil
  279. # echo typeToString(exceptType), " ", typeToString(raisedType)
  280. # Determine if the exception type matches the pattern
  281. if exceptType.isNil or inheritanceDiff(raisedType, exceptType) <= 0:
  282. matched = true
  283. break
  284. inc pc
  285. # Skip any further ``except`` pattern and find the first instruction of
  286. # the handler body
  287. while c.code[pc].opcode == opcExcept:
  288. inc pc
  289. if matched:
  290. break
  291. # If no handler in this chain is able to catch this exception we check if
  292. # the "parent" chains are able to. If this chain ends with a `finally`
  293. # block we must execute it before continuing.
  294. pc = pcEndExcept
  295. # Where the handler body starts
  296. let pcBody = pc
  297. if matched:
  298. return (ExceptionGotoHandler, pcBody)
  299. elif c.code[pc].opcode == opcFinally:
  300. # The +1 here is here because we don't want to execute it since we've
  301. # already pop'd this statepoint from the stack.
  302. return (ExceptionGotoFinally, pc + 1)
  303. return (ExceptionGotoUnhandled, 0)
  304. proc cleanUpOnReturn(c: PCtx; f: PStackFrame): int =
  305. # Walk up the chain of safepoints and return the PC of the first `finally`
  306. # block we find or -1 if no such block is found.
  307. # Note that the safepoint is removed once the function returns!
  308. result = -1
  309. # Traverse the stack starting from the end in order to execute the blocks in
  310. # the intended order
  311. for i in 1..f.safePoints.len:
  312. var pc = f.safePoints[^i]
  313. # Skip the `except` blocks
  314. while c.code[pc].opcode == opcExcept:
  315. pc += c.code[pc].regBx - wordExcess
  316. if c.code[pc].opcode == opcFinally:
  317. discard f.safePoints.pop
  318. return pc + 1
  319. proc opConv(c: PCtx; dest: var TFullReg, src: TFullReg, desttyp, srctyp: PType): bool =
  320. if desttyp.kind == tyString:
  321. dest.ensureKind(rkNode)
  322. dest.node = newNode(nkStrLit)
  323. let styp = srctyp.skipTypes(abstractRange)
  324. case styp.kind
  325. of tyEnum:
  326. let n = styp.n
  327. let x = src.intVal.int
  328. if x <% n.len and (let f = n[x].sym; f.position == x):
  329. dest.node.strVal = if f.ast.isNil: f.name.s else: f.ast.strVal
  330. else:
  331. for i in 0..<n.len:
  332. if n[i].kind != nkSym: internalError(c.config, "opConv for enum")
  333. let f = n[i].sym
  334. if f.position == x:
  335. dest.node.strVal = if f.ast.isNil: f.name.s else: f.ast.strVal
  336. return
  337. dest.node.strVal = styp.sym.name.s & " " & $x
  338. of tyInt..tyInt64:
  339. dest.node.strVal = $src.intVal
  340. of tyUInt..tyUInt64:
  341. dest.node.strVal = $uint64(src.intVal)
  342. of tyBool:
  343. dest.node.strVal = if src.intVal == 0: "false" else: "true"
  344. of tyFloat..tyFloat128:
  345. dest.node.strVal = $src.floatVal
  346. of tyString:
  347. dest.node.strVal = src.node.strVal
  348. of tyCstring:
  349. if src.node.kind == nkBracket:
  350. # Array of chars
  351. var strVal = ""
  352. for son in src.node.sons:
  353. let c = char(son.intVal)
  354. if c == '\0': break
  355. strVal.add(c)
  356. dest.node.strVal = strVal
  357. else:
  358. dest.node.strVal = src.node.strVal
  359. of tyChar:
  360. dest.node.strVal = $chr(src.intVal)
  361. else:
  362. internalError(c.config, "cannot convert to string " & desttyp.typeToString)
  363. else:
  364. let desttyp = skipTypes(desttyp, abstractVarRange)
  365. case desttyp.kind
  366. of tyInt..tyInt64:
  367. dest.ensureKind(rkInt)
  368. case skipTypes(srctyp, abstractRange).kind
  369. of tyFloat..tyFloat64:
  370. dest.intVal = int(src.floatVal)
  371. else:
  372. dest.intVal = src.intVal
  373. if toInt128(dest.intVal) < firstOrd(c.config, desttyp) or toInt128(dest.intVal) > lastOrd(c.config, desttyp):
  374. return true
  375. of tyUInt..tyUInt64:
  376. dest.ensureKind(rkInt)
  377. let styp = srctyp.skipTypes(abstractRange) # skip distinct types(dest type could do this too if needed)
  378. case styp.kind
  379. of tyFloat..tyFloat64:
  380. dest.intVal = int(src.floatVal)
  381. else:
  382. let srcSize = getSize(c.config, styp)
  383. let destSize = getSize(c.config, desttyp)
  384. let srcDist = (sizeof(src.intVal) - srcSize) * 8
  385. let destDist = (sizeof(dest.intVal) - destSize) * 8
  386. var value = cast[BiggestUInt](src.intVal)
  387. value = (value shl srcDist) shr srcDist
  388. value = (value shl destDist) shr destDist
  389. dest.intVal = cast[BiggestInt](value)
  390. of tyBool:
  391. dest.ensureKind(rkInt)
  392. dest.intVal =
  393. case skipTypes(srctyp, abstractRange).kind
  394. of tyFloat..tyFloat64: int(src.floatVal != 0.0)
  395. else: int(src.intVal != 0)
  396. of tyFloat..tyFloat64:
  397. dest.ensureKind(rkFloat)
  398. let srcKind = skipTypes(srctyp, abstractRange).kind
  399. case srcKind
  400. of tyInt..tyInt64, tyUInt..tyUInt64, tyEnum, tyBool, tyChar:
  401. dest.floatVal = toBiggestFloat(src.intVal)
  402. elif src.kind == rkInt:
  403. dest.floatVal = toBiggestFloat(src.intVal)
  404. else:
  405. dest.floatVal = src.floatVal
  406. of tyObject:
  407. if srctyp.skipTypes(abstractVarRange).kind != tyObject:
  408. internalError(c.config, "invalid object-to-object conversion")
  409. # A object-to-object conversion is essentially a no-op
  410. moveConst(dest, src)
  411. else:
  412. asgnComplex(dest, src)
  413. proc compile(c: PCtx, s: PSym): int =
  414. result = vmgen.genProc(c, s)
  415. when debugEchoCode: c.echoCode result
  416. #c.echoCode
  417. template handleJmpBack() {.dirty.} =
  418. if c.loopIterations <= 0:
  419. if allowInfiniteLoops in c.features:
  420. c.loopIterations = c.config.maxLoopIterationsVM
  421. else:
  422. msgWriteln(c.config, "stack trace: (most recent call last)", {msgNoUnitSep})
  423. stackTraceAux(c, tos, pc)
  424. globalError(c.config, c.debug[pc], errTooManyIterations % $c.config.maxLoopIterationsVM)
  425. dec(c.loopIterations)
  426. proc recSetFlagIsRef(arg: PNode) =
  427. if arg.kind notin {nkStrLit..nkTripleStrLit}:
  428. arg.flags.incl(nfIsRef)
  429. for i in 0..<arg.safeLen:
  430. arg[i].recSetFlagIsRef
  431. proc setLenSeq(c: PCtx; node: PNode; newLen: int; info: TLineInfo) =
  432. let typ = node.typ.skipTypes(abstractInst+{tyRange}-{tyTypeDesc})
  433. let oldLen = node.len
  434. setLen(node.sons, newLen)
  435. if oldLen < newLen:
  436. for i in oldLen..<newLen:
  437. node[i] = getNullValue(typ[0], info, c.config)
  438. const
  439. errNilAccess = "attempt to access a nil address"
  440. errOverOrUnderflow = "over- or underflow"
  441. errConstantDivisionByZero = "division by zero"
  442. errIllegalConvFromXtoY = "illegal conversion from '$1' to '$2'"
  443. errTooManyIterations = "interpretation requires too many iterations; " &
  444. "if you are sure this is not a bug in your code, compile with `--maxLoopIterationsVM:number` (current value: $1)"
  445. errFieldXNotFound = "node lacks field: "
  446. template maybeHandlePtr(node2: PNode, reg: TFullReg, isAssign2: bool): bool =
  447. let node = node2 # prevent double evaluation
  448. if node.kind == nkNilLit:
  449. stackTrace(c, tos, pc, errNilAccess)
  450. let typ = node.typ
  451. if nfIsPtr in node.flags or (typ != nil and typ.kind == tyPtr):
  452. assert node.kind == nkIntLit, $(node.kind)
  453. assert typ != nil
  454. let typ2 = if typ.kind == tyPtr: typ[0] else: typ
  455. if not derefPtrToReg(node.intVal, typ2, reg, isAssign = isAssign2):
  456. # tyObject not supported in this context
  457. stackTrace(c, tos, pc, "deref unsupported ptr type: " & $(typeToString(typ), typ.kind))
  458. true
  459. else:
  460. false
  461. when not defined(nimHasSinkInference):
  462. {.pragma: nosinks.}
  463. template takeAddress(reg, source) =
  464. reg.nodeAddr = addr source
  465. GC_ref source
  466. proc takeCharAddress(c: PCtx, src: PNode, index: BiggestInt, pc: int): TFullReg =
  467. let typ = newType(tyPtr, nextTypeId c.idgen, c.module.owner)
  468. typ.add getSysType(c.graph, c.debug[pc], tyChar)
  469. var node = newNodeIT(nkIntLit, c.debug[pc], typ) # xxx nkPtrLit
  470. node.intVal = cast[int](src.strVal[index].addr)
  471. node.flags.incl nfIsPtr
  472. TFullReg(kind: rkNode, node: node)
  473. proc rawExecute(c: PCtx, start: int, tos: PStackFrame): TFullReg =
  474. var pc = start
  475. var tos = tos
  476. # Used to keep track of where the execution is resumed.
  477. var savedPC = -1
  478. var savedFrame: PStackFrame
  479. when defined(gcArc) or defined(gcOrc):
  480. template updateRegsAlias = discard
  481. template regs: untyped = tos.slots
  482. else:
  483. template updateRegsAlias =
  484. move(regs, tos.slots)
  485. var regs: seq[TFullReg] # alias to tos.slots for performance
  486. updateRegsAlias
  487. #echo "NEW RUN ------------------------"
  488. while true:
  489. #{.computedGoto.}
  490. let instr = c.code[pc]
  491. let ra = instr.regA
  492. when traceCode:
  493. template regDescr(name, r): string =
  494. let kind = if r < regs.len: $regs[r].kind else: ""
  495. let ret = name & ": " & $r & " " & $kind
  496. alignLeft(ret, 15)
  497. echo "PC:$pc $opcode $ra $rb $rc" % [
  498. "pc", $pc, "opcode", alignLeft($c.code[pc].opcode, 15),
  499. "ra", regDescr("ra", ra), "rb", regDescr("rb", instr.regB),
  500. "rc", regDescr("rc", instr.regC)]
  501. if c.config.isVmTrace:
  502. # unlike nimVMDebug, this doesn't require re-compiling nim and is controlled by user code
  503. let info = c.debug[pc]
  504. # other useful variables: c.loopIterations
  505. echo "$# [$#] $#" % [c.config$info, $instr.opcode, c.config.sourceLine(info)]
  506. c.profiler.enter(c, tos)
  507. case instr.opcode
  508. of opcEof: return regs[ra]
  509. of opcRet:
  510. let newPc = c.cleanUpOnReturn(tos)
  511. # Perform any cleanup action before returning
  512. if newPc < 0:
  513. pc = tos.comesFrom
  514. let retVal = regs[0]
  515. tos = tos.next
  516. if tos.isNil:
  517. return retVal
  518. updateRegsAlias
  519. assert c.code[pc].opcode in {opcIndCall, opcIndCallAsgn}
  520. if c.code[pc].opcode == opcIndCallAsgn:
  521. regs[c.code[pc].regA] = retVal
  522. else:
  523. savedPC = pc
  524. savedFrame = tos
  525. # The -1 is needed because at the end of the loop we increment `pc`
  526. pc = newPc - 1
  527. of opcYldYoid: assert false
  528. of opcYldVal: assert false
  529. of opcAsgnInt:
  530. decodeB(rkInt)
  531. regs[ra].intVal = regs[rb].intVal
  532. of opcAsgnFloat:
  533. decodeB(rkFloat)
  534. regs[ra].floatVal = regs[rb].floatVal
  535. of opcCastFloatToInt32:
  536. let rb = instr.regB
  537. ensureKind(rkInt)
  538. regs[ra].intVal = cast[int32](float32(regs[rb].floatVal))
  539. of opcCastFloatToInt64:
  540. let rb = instr.regB
  541. ensureKind(rkInt)
  542. regs[ra].intVal = cast[int64](regs[rb].floatVal)
  543. of opcCastIntToFloat32:
  544. let rb = instr.regB
  545. ensureKind(rkFloat)
  546. regs[ra].floatVal = cast[float32](regs[rb].intVal)
  547. of opcCastIntToFloat64:
  548. let rb = instr.regB
  549. ensureKind(rkFloat)
  550. regs[ra].floatVal = cast[float64](regs[rb].intVal)
  551. of opcCastPtrToInt: # RENAME opcCastPtrOrRefToInt
  552. decodeBImm(rkInt)
  553. case imm
  554. of 1: # PtrLikeKinds
  555. case regs[rb].kind
  556. of rkNode:
  557. regs[ra].intVal = cast[int](regs[rb].node.intVal)
  558. of rkNodeAddr:
  559. regs[ra].intVal = cast[int](regs[rb].nodeAddr)
  560. else:
  561. stackTrace(c, tos, pc, "opcCastPtrToInt: got " & $regs[rb].kind)
  562. of 2: # tyRef
  563. regs[ra].intVal = cast[int](regs[rb].node)
  564. else: assert false, $imm
  565. of opcCastIntToPtr:
  566. let rb = instr.regB
  567. let typ = regs[ra].node.typ
  568. let node2 = newNodeIT(nkIntLit, c.debug[pc], typ)
  569. case regs[rb].kind
  570. of rkInt: node2.intVal = regs[rb].intVal
  571. of rkNode:
  572. if regs[rb].node.typ.kind notin PtrLikeKinds:
  573. stackTrace(c, tos, pc, "opcCastIntToPtr: regs[rb].node.typ: " & $regs[rb].node.typ.kind)
  574. node2.intVal = regs[rb].node.intVal
  575. else: stackTrace(c, tos, pc, "opcCastIntToPtr: regs[rb].kind: " & $regs[rb].kind)
  576. regs[ra].node = node2
  577. of opcAsgnComplex:
  578. asgnComplex(regs[ra], regs[instr.regB])
  579. of opcFastAsgnComplex:
  580. fastAsgnComplex(regs[ra], regs[instr.regB])
  581. of opcAsgnRef:
  582. asgnRef(regs[ra], regs[instr.regB])
  583. of opcNodeToReg:
  584. let ra = instr.regA
  585. let rb = instr.regB
  586. # opcLdDeref might already have loaded it into a register. XXX Let's hope
  587. # this is still correct this way:
  588. if regs[rb].kind != rkNode:
  589. regs[ra] = regs[rb]
  590. else:
  591. assert regs[rb].kind == rkNode
  592. let nb = regs[rb].node
  593. case nb.kind
  594. of nkCharLit..nkUInt64Lit:
  595. ensureKind(rkInt)
  596. regs[ra].intVal = nb.intVal
  597. of nkFloatLit..nkFloat64Lit:
  598. ensureKind(rkFloat)
  599. regs[ra].floatVal = nb.floatVal
  600. else:
  601. ensureKind(rkNode)
  602. regs[ra].node = nb
  603. of opcSlice:
  604. # A bodge, but this takes in `toOpenArray(rb, rc, rc)` and emits
  605. # nkTupleConstr(x, y, z) into the `regs[ra]`. These can later be used for calculating the slice we have taken.
  606. decodeBC(rkNode)
  607. let
  608. collection = regs[ra].node
  609. leftInd = regs[rb].intVal
  610. rightInd = regs[rc].intVal
  611. proc rangeCheck(left, right: BiggestInt, safeLen: BiggestInt) =
  612. if left < 0:
  613. stackTrace(c, tos, pc, formatErrorIndexBound(left, safeLen))
  614. if right > safeLen:
  615. stackTrace(c, tos, pc, formatErrorIndexBound(right, safeLen))
  616. case collection.kind
  617. of nkTupleConstr: # slice of a slice
  618. let safeLen = collection[2].intVal - collection[1].intVal
  619. rangeCheck(leftInd, rightInd, safeLen)
  620. let
  621. leftInd = leftInd + collection[1].intVal # Slice is from the start of the old
  622. rightInd = rightInd + collection[1].intVal
  623. regs[ra].node = newTree(
  624. nkTupleConstr,
  625. collection[0],
  626. newIntNode(nkIntLit, BiggestInt leftInd),
  627. newIntNode(nkIntLit, BiggestInt rightInd)
  628. )
  629. else:
  630. let safeLen = safeArrLen(collection) - 1
  631. rangeCheck(leftInd, rightInd, safeLen)
  632. regs[ra].node = newTree(
  633. nkTupleConstr,
  634. collection,
  635. newIntNode(nkIntLit, BiggestInt leftInd),
  636. newIntNode(nkIntLit, BiggestInt rightInd)
  637. )
  638. of opcLdArr:
  639. # a = b[c]
  640. decodeBC(rkNode)
  641. if regs[rc].intVal > high(int):
  642. stackTrace(c, tos, pc, formatErrorIndexBound(regs[rc].intVal, high(int)))
  643. let idx = regs[rc].intVal.int
  644. let src = regs[rb].node
  645. case src.kind
  646. of nkTupleConstr: # refer to `of opcSlice`
  647. let
  648. left = src[1].intVal
  649. right = src[2].intVal
  650. realIndex = left + idx
  651. if idx in 0..(right - left):
  652. case src[0].kind
  653. of nkStrKinds:
  654. regs[ra].node = newIntNode(nkCharLit, ord src[0].strVal[int realIndex])
  655. of nkBracket:
  656. regs[ra].node = src[0][int realIndex]
  657. else:
  658. stackTrace(c, tos, pc, "opcLdArr internal error")
  659. else:
  660. stackTrace(c, tos, pc, formatErrorIndexBound(idx, int right))
  661. of nkStrLit..nkTripleStrLit:
  662. if idx <% src.strVal.len:
  663. regs[ra].node = newNodeI(nkCharLit, c.debug[pc])
  664. regs[ra].node.intVal = src.strVal[idx].ord
  665. else:
  666. stackTrace(c, tos, pc, formatErrorIndexBound(idx, src.strVal.len-1))
  667. elif src.kind notin {nkEmpty..nkFloat128Lit} and idx <% src.len:
  668. regs[ra].node = src[idx]
  669. else:
  670. stackTrace(c, tos, pc, formatErrorIndexBound(idx, src.safeLen-1))
  671. of opcLdArrAddr:
  672. # a = addr(b[c])
  673. decodeBC(rkNodeAddr)
  674. if regs[rc].intVal > high(int):
  675. stackTrace(c, tos, pc, formatErrorIndexBound(regs[rc].intVal, high(int)))
  676. let idx = regs[rc].intVal.int
  677. let src = if regs[rb].kind == rkNode: regs[rb].node else: regs[rb].nodeAddr[]
  678. case src.kind
  679. of nkTupleConstr:
  680. let
  681. left = src[1].intVal
  682. right = src[2].intVal
  683. realIndex = left + idx
  684. if idx in 0..(right - left): # Refer to `opcSlice`
  685. case src[0].kind
  686. of nkStrKinds:
  687. regs[ra] = takeCharAddress(c, src[0], realIndex, pc)
  688. of nkBracket:
  689. takeAddress regs[ra], src.sons[0].sons[realIndex]
  690. else:
  691. stackTrace(c, tos, pc, "opcLdArrAddr internal error")
  692. else:
  693. stackTrace(c, tos, pc, formatErrorIndexBound(idx, int right))
  694. else:
  695. if src.kind notin {nkEmpty..nkTripleStrLit} and idx <% src.len:
  696. takeAddress regs[ra], src.sons[idx]
  697. elif src.kind in nkStrKinds and idx <% src.strVal.len:
  698. regs[ra] = takeCharAddress(c, src, idx, pc)
  699. else:
  700. stackTrace(c, tos, pc, formatErrorIndexBound(idx, src.safeLen-1))
  701. of opcLdStrIdx:
  702. decodeBC(rkInt)
  703. let idx = regs[rc].intVal.int
  704. let s = regs[rb].node.strVal
  705. if idx <% s.len:
  706. regs[ra].intVal = s[idx].ord
  707. else:
  708. stackTrace(c, tos, pc, formatErrorIndexBound(idx, s.len-1))
  709. of opcLdStrIdxAddr:
  710. # a = addr(b[c]); similar to opcLdArrAddr
  711. decodeBC(rkNode)
  712. if regs[rc].intVal > high(int):
  713. stackTrace(c, tos, pc, formatErrorIndexBound(regs[rc].intVal, high(int)))
  714. let idx = regs[rc].intVal.int
  715. let s = regs[rb].node.strVal.addr # or `byaddr`
  716. if idx <% s[].len:
  717. regs[ra] = takeCharAddress(c, regs[rb].node, idx, pc)
  718. else:
  719. stackTrace(c, tos, pc, formatErrorIndexBound(idx, s[].len-1))
  720. of opcWrArr:
  721. # a[b] = c
  722. decodeBC(rkNode)
  723. let idx = regs[rb].intVal.int
  724. let arr = regs[ra].node
  725. case arr.kind
  726. of nkTupleConstr: # refer to `opcSlice`
  727. let
  728. src = arr[0]
  729. left = arr[1].intVal
  730. right = arr[2].intVal
  731. realIndex = left + idx
  732. if idx in 0..(right - left):
  733. case src.kind
  734. of nkStrKinds:
  735. src.strVal[int(realIndex)] = char(regs[rc].intVal)
  736. of nkBracket:
  737. src[int(realIndex)] = regs[rc].node
  738. else:
  739. stackTrace(c, tos, pc, "opcWrArr internal error")
  740. else:
  741. stackTrace(c, tos, pc, formatErrorIndexBound(idx, int right))
  742. of {nkStrLit..nkTripleStrLit}:
  743. if idx <% arr.strVal.len:
  744. arr.strVal[idx] = chr(regs[rc].intVal)
  745. else:
  746. stackTrace(c, tos, pc, formatErrorIndexBound(idx, arr.strVal.len-1))
  747. elif idx <% arr.len:
  748. writeField(arr[idx], regs[rc])
  749. else:
  750. stackTrace(c, tos, pc, formatErrorIndexBound(idx, arr.safeLen-1))
  751. of opcLdObj:
  752. # a = b.c
  753. decodeBC(rkNode)
  754. let src = if regs[rb].kind == rkNode: regs[rb].node else: regs[rb].nodeAddr[]
  755. case src.kind
  756. of nkEmpty..nkNilLit:
  757. # for nkPtrLit, this could be supported in the future, use something like:
  758. # derefPtrToReg(src.intVal + offsetof(src.typ, rc), typ_field, regs[ra], isAssign = false)
  759. # where we compute the offset in bytes for field rc
  760. stackTrace(c, tos, pc, errNilAccess & " " & $("kind", src.kind, "typ", typeToString(src.typ), "rc", rc))
  761. of nkObjConstr:
  762. let n = src[rc + 1].skipColon
  763. regs[ra].node = n
  764. else:
  765. let n = src[rc]
  766. regs[ra].node = n
  767. of opcLdObjAddr:
  768. # a = addr(b.c)
  769. decodeBC(rkNodeAddr)
  770. let src = if regs[rb].kind == rkNode: regs[rb].node else: regs[rb].nodeAddr[]
  771. case src.kind
  772. of nkEmpty..nkNilLit:
  773. stackTrace(c, tos, pc, errNilAccess)
  774. of nkObjConstr:
  775. let n = src.sons[rc + 1]
  776. if n.kind == nkExprColonExpr:
  777. takeAddress regs[ra], n.sons[1]
  778. else:
  779. takeAddress regs[ra], src.sons[rc + 1]
  780. else:
  781. takeAddress regs[ra], src.sons[rc]
  782. of opcWrObj:
  783. # a.b = c
  784. decodeBC(rkNode)
  785. assert regs[ra].node != nil
  786. let shiftedRb = rb + ord(regs[ra].node.kind == nkObjConstr)
  787. let dest = regs[ra].node
  788. if dest.kind == nkNilLit:
  789. stackTrace(c, tos, pc, errNilAccess)
  790. elif dest[shiftedRb].kind == nkExprColonExpr:
  791. writeField(dest[shiftedRb][1], regs[rc])
  792. else:
  793. writeField(dest[shiftedRb], regs[rc])
  794. of opcWrStrIdx:
  795. decodeBC(rkNode)
  796. let idx = regs[rb].intVal.int
  797. if idx <% regs[ra].node.strVal.len:
  798. regs[ra].node.strVal[idx] = chr(regs[rc].intVal)
  799. else:
  800. stackTrace(c, tos, pc, formatErrorIndexBound(idx, regs[ra].node.strVal.len-1))
  801. of opcAddrReg:
  802. decodeB(rkRegisterAddr)
  803. regs[ra].regAddr = addr(regs[rb])
  804. of opcAddrNode:
  805. decodeB(rkNodeAddr)
  806. case regs[rb].kind
  807. of rkNode:
  808. takeAddress regs[ra], regs[rb].node
  809. of rkNodeAddr: # bug #14339
  810. regs[ra].nodeAddr = regs[rb].nodeAddr
  811. else:
  812. stackTrace(c, tos, pc, "limited VM support for 'addr', got kind: " & $regs[rb].kind)
  813. of opcLdDeref:
  814. # a = b[]
  815. let ra = instr.regA
  816. let rb = instr.regB
  817. case regs[rb].kind
  818. of rkNodeAddr:
  819. ensureKind(rkNode)
  820. regs[ra].node = regs[rb].nodeAddr[]
  821. of rkRegisterAddr:
  822. ensureKind(regs[rb].regAddr.kind)
  823. regs[ra] = regs[rb].regAddr[]
  824. of rkNode:
  825. if regs[rb].node.kind == nkRefTy:
  826. regs[ra].node = regs[rb].node[0]
  827. elif not maybeHandlePtr(regs[rb].node, regs[ra], false):
  828. ## e.g.: typ.kind = tyObject
  829. ensureKind(rkNode)
  830. regs[ra].node = regs[rb].node
  831. else:
  832. stackTrace(c, tos, pc, errNilAccess & " kind: " & $regs[rb].kind)
  833. of opcWrDeref:
  834. # a[] = c; b unused
  835. let ra = instr.regA
  836. let rc = instr.regC
  837. case regs[ra].kind
  838. of rkNodeAddr:
  839. let n = regs[rc].regToNode
  840. # `var object` parameters are sent as rkNodeAddr. When they are mutated
  841. # vmgen generates opcWrDeref, which means that we must dereference
  842. # twice.
  843. # TODO: This should likely be handled differently in vmgen.
  844. let nAddr = regs[ra].nodeAddr
  845. if nAddr[] == nil: stackTrace(c, tos, pc, "opcWrDeref internal error") # refs bug #16613
  846. if (nfIsRef notin nAddr[].flags and nfIsRef notin n.flags): nAddr[][] = n[]
  847. else: nAddr[] = n
  848. of rkRegisterAddr: regs[ra].regAddr[] = regs[rc]
  849. of rkNode:
  850. # xxx: also check for nkRefTy as in opcLdDeref?
  851. if not maybeHandlePtr(regs[ra].node, regs[rc], true):
  852. regs[ra].node[] = regs[rc].regToNode[]
  853. regs[ra].node.flags.incl nfIsRef
  854. else: stackTrace(c, tos, pc, errNilAccess)
  855. of opcAddInt:
  856. decodeBC(rkInt)
  857. let
  858. bVal = regs[rb].intVal
  859. cVal = regs[rc].intVal
  860. sum = bVal +% cVal
  861. if (sum xor bVal) >= 0 or (sum xor cVal) >= 0:
  862. regs[ra].intVal = sum
  863. else:
  864. stackTrace(c, tos, pc, errOverOrUnderflow)
  865. of opcAddImmInt:
  866. decodeBImm(rkInt)
  867. #message(c.config, c.debug[pc], warnUser, "came here")
  868. #debug regs[rb].node
  869. let
  870. bVal = regs[rb].intVal
  871. cVal = imm
  872. sum = bVal +% cVal
  873. if (sum xor bVal) >= 0 or (sum xor cVal) >= 0:
  874. regs[ra].intVal = sum
  875. else:
  876. stackTrace(c, tos, pc, errOverOrUnderflow)
  877. of opcSubInt:
  878. decodeBC(rkInt)
  879. let
  880. bVal = regs[rb].intVal
  881. cVal = regs[rc].intVal
  882. diff = bVal -% cVal
  883. if (diff xor bVal) >= 0 or (diff xor not cVal) >= 0:
  884. regs[ra].intVal = diff
  885. else:
  886. stackTrace(c, tos, pc, errOverOrUnderflow)
  887. of opcSubImmInt:
  888. decodeBImm(rkInt)
  889. let
  890. bVal = regs[rb].intVal
  891. cVal = imm
  892. diff = bVal -% cVal
  893. if (diff xor bVal) >= 0 or (diff xor not cVal) >= 0:
  894. regs[ra].intVal = diff
  895. else:
  896. stackTrace(c, tos, pc, errOverOrUnderflow)
  897. of opcLenSeq:
  898. decodeBImm(rkInt)
  899. #assert regs[rb].kind == nkBracket
  900. let
  901. high = (imm and 1) # discard flags
  902. node = regs[rb].node
  903. if (imm and nimNodeFlag) != 0:
  904. # used by mNLen (NimNode.len)
  905. regs[ra].intVal = regs[rb].node.safeLen - high
  906. else:
  907. case node.kind
  908. of nkTupleConstr: # refer to `of opcSlice`
  909. regs[ra].intVal = node[2].intVal - node[1].intVal + 1 - high
  910. else:
  911. # safeArrLen also return string node len
  912. # used when string is passed as openArray in VM
  913. regs[ra].intVal = node.safeArrLen - high
  914. of opcLenStr:
  915. decodeBImm(rkInt)
  916. assert regs[rb].kind == rkNode
  917. regs[ra].intVal = regs[rb].node.strVal.len - imm
  918. of opcLenCstring:
  919. decodeBImm(rkInt)
  920. assert regs[rb].kind == rkNode
  921. if regs[rb].node.kind == nkNilLit:
  922. regs[ra].intVal = -imm
  923. else:
  924. regs[ra].intVal = regs[rb].node.strVal.cstring.len - imm
  925. of opcIncl:
  926. decodeB(rkNode)
  927. let b = regs[rb].regToNode
  928. if not inSet(regs[ra].node, b):
  929. regs[ra].node.add copyTree(b)
  930. of opcInclRange:
  931. decodeBC(rkNode)
  932. var r = newNode(nkRange)
  933. r.add regs[rb].regToNode
  934. r.add regs[rc].regToNode
  935. regs[ra].node.add r.copyTree
  936. of opcExcl:
  937. decodeB(rkNode)
  938. var b = newNodeIT(nkCurly, regs[ra].node.info, regs[ra].node.typ)
  939. b.add regs[rb].regToNode
  940. var r = diffSets(c.config, regs[ra].node, b)
  941. discardSons(regs[ra].node)
  942. for i in 0..<r.len: regs[ra].node.add r[i]
  943. of opcCard:
  944. decodeB(rkInt)
  945. regs[ra].intVal = nimsets.cardSet(c.config, regs[rb].node)
  946. of opcMulInt:
  947. decodeBC(rkInt)
  948. let
  949. bVal = regs[rb].intVal
  950. cVal = regs[rc].intVal
  951. product = bVal *% cVal
  952. floatProd = toBiggestFloat(bVal) * toBiggestFloat(cVal)
  953. resAsFloat = toBiggestFloat(product)
  954. if resAsFloat == floatProd:
  955. regs[ra].intVal = product
  956. elif 32.0 * abs(resAsFloat - floatProd) <= abs(floatProd):
  957. regs[ra].intVal = product
  958. else:
  959. stackTrace(c, tos, pc, errOverOrUnderflow)
  960. of opcDivInt:
  961. decodeBC(rkInt)
  962. if regs[rc].intVal == 0: stackTrace(c, tos, pc, errConstantDivisionByZero)
  963. else: regs[ra].intVal = regs[rb].intVal div regs[rc].intVal
  964. of opcModInt:
  965. decodeBC(rkInt)
  966. if regs[rc].intVal == 0: stackTrace(c, tos, pc, errConstantDivisionByZero)
  967. else: regs[ra].intVal = regs[rb].intVal mod regs[rc].intVal
  968. of opcAddFloat:
  969. decodeBC(rkFloat)
  970. regs[ra].floatVal = regs[rb].floatVal + regs[rc].floatVal
  971. of opcSubFloat:
  972. decodeBC(rkFloat)
  973. regs[ra].floatVal = regs[rb].floatVal - regs[rc].floatVal
  974. of opcMulFloat:
  975. decodeBC(rkFloat)
  976. regs[ra].floatVal = regs[rb].floatVal * regs[rc].floatVal
  977. of opcDivFloat:
  978. decodeBC(rkFloat)
  979. regs[ra].floatVal = regs[rb].floatVal / regs[rc].floatVal
  980. of opcShrInt:
  981. decodeBC(rkInt)
  982. let b = cast[uint64](regs[rb].intVal)
  983. let c = cast[uint64](regs[rc].intVal)
  984. let a = cast[int64](b shr c)
  985. regs[ra].intVal = a
  986. of opcShlInt:
  987. decodeBC(rkInt)
  988. regs[ra].intVal = regs[rb].intVal shl regs[rc].intVal
  989. of opcAshrInt:
  990. decodeBC(rkInt)
  991. regs[ra].intVal = ashr(regs[rb].intVal, regs[rc].intVal)
  992. of opcBitandInt:
  993. decodeBC(rkInt)
  994. regs[ra].intVal = regs[rb].intVal and regs[rc].intVal
  995. of opcBitorInt:
  996. decodeBC(rkInt)
  997. regs[ra].intVal = regs[rb].intVal or regs[rc].intVal
  998. of opcBitxorInt:
  999. decodeBC(rkInt)
  1000. regs[ra].intVal = regs[rb].intVal xor regs[rc].intVal
  1001. of opcAddu:
  1002. decodeBC(rkInt)
  1003. regs[ra].intVal = regs[rb].intVal +% regs[rc].intVal
  1004. of opcSubu:
  1005. decodeBC(rkInt)
  1006. regs[ra].intVal = regs[rb].intVal -% regs[rc].intVal
  1007. of opcMulu:
  1008. decodeBC(rkInt)
  1009. regs[ra].intVal = regs[rb].intVal *% regs[rc].intVal
  1010. of opcDivu:
  1011. decodeBC(rkInt)
  1012. regs[ra].intVal = regs[rb].intVal /% regs[rc].intVal
  1013. of opcModu:
  1014. decodeBC(rkInt)
  1015. regs[ra].intVal = regs[rb].intVal %% regs[rc].intVal
  1016. of opcEqInt:
  1017. decodeBC(rkInt)
  1018. regs[ra].intVal = ord(regs[rb].intVal == regs[rc].intVal)
  1019. of opcLeInt:
  1020. decodeBC(rkInt)
  1021. regs[ra].intVal = ord(regs[rb].intVal <= regs[rc].intVal)
  1022. of opcLtInt:
  1023. decodeBC(rkInt)
  1024. regs[ra].intVal = ord(regs[rb].intVal < regs[rc].intVal)
  1025. of opcEqFloat:
  1026. decodeBC(rkInt)
  1027. regs[ra].intVal = ord(regs[rb].floatVal == regs[rc].floatVal)
  1028. of opcLeFloat:
  1029. decodeBC(rkInt)
  1030. regs[ra].intVal = ord(regs[rb].floatVal <= regs[rc].floatVal)
  1031. of opcLtFloat:
  1032. decodeBC(rkInt)
  1033. regs[ra].intVal = ord(regs[rb].floatVal < regs[rc].floatVal)
  1034. of opcLeu:
  1035. decodeBC(rkInt)
  1036. regs[ra].intVal = ord(regs[rb].intVal <=% regs[rc].intVal)
  1037. of opcLtu:
  1038. decodeBC(rkInt)
  1039. regs[ra].intVal = ord(regs[rb].intVal <% regs[rc].intVal)
  1040. of opcEqRef:
  1041. var ret = false
  1042. decodeBC(rkInt)
  1043. template getTyp(n): untyped =
  1044. n.typ.skipTypes(abstractInst)
  1045. template skipRegisterAddr(n: TFullReg): TFullReg =
  1046. var tmp = n
  1047. while tmp.kind == rkRegisterAddr:
  1048. tmp = tmp.regAddr[]
  1049. tmp
  1050. proc ptrEquality(n1: ptr PNode, n2: PNode): bool =
  1051. ## true if n2.intVal represents a ptr equal to n1
  1052. let p1 = cast[int](n1)
  1053. case n2.kind
  1054. of nkNilLit: return p1 == 0
  1055. of nkIntLit: # TODO: nkPtrLit
  1056. # for example, n1.kind == nkFloatLit (ptr float)
  1057. # the problem is that n1.typ == nil so we can't compare n1.typ and n2.typ
  1058. # this is the best we can do (pending making sure we assign a valid n1.typ to nodeAddr's)
  1059. let t2 = n2.getTyp
  1060. return t2.kind in PtrLikeKinds and n2.intVal == p1
  1061. else: return false
  1062. let rbReg = skipRegisterAddr(regs[rb])
  1063. let rcReg = skipRegisterAddr(regs[rc])
  1064. if rbReg.kind == rkNodeAddr:
  1065. if rcReg.kind == rkNodeAddr:
  1066. ret = rbReg.nodeAddr == rcReg.nodeAddr
  1067. else:
  1068. ret = ptrEquality(rbReg.nodeAddr, rcReg.node)
  1069. elif rcReg.kind == rkNodeAddr:
  1070. ret = ptrEquality(rcReg.nodeAddr, rbReg.node)
  1071. else:
  1072. let nb = rbReg.node
  1073. let nc = rcReg.node
  1074. if nb.kind != nc.kind: discard
  1075. elif (nb == nc) or (nb.kind == nkNilLit): ret = true # intentional
  1076. elif nb.kind in {nkSym, nkTupleConstr, nkClosure} and nb.typ != nil and nb.typ.kind == tyProc and sameConstant(nb, nc):
  1077. ret = true
  1078. # this also takes care of procvar's, represented as nkTupleConstr, e.g. (nil, nil)
  1079. elif nb.kind == nkIntLit and nc.kind == nkIntLit and nb.intVal == nc.intVal: # TODO: nkPtrLit
  1080. let tb = nb.getTyp
  1081. let tc = nc.getTyp
  1082. ret = tb.kind in PtrLikeKinds and tc.kind == tb.kind
  1083. regs[ra].intVal = ord(ret)
  1084. of opcEqNimNode:
  1085. decodeBC(rkInt)
  1086. regs[ra].intVal =
  1087. ord(exprStructuralEquivalent(regs[rb].node, regs[rc].node,
  1088. strictSymEquality=true))
  1089. of opcSameNodeType:
  1090. decodeBC(rkInt)
  1091. regs[ra].intVal = ord(regs[rb].node.typ.sameTypeOrNil(regs[rc].node.typ, {ExactTypeDescValues, ExactGenericParams}))
  1092. # The types should exactly match which is why we pass `{ExactTypeDescValues..ExactGcSafety}`.
  1093. of opcXor:
  1094. decodeBC(rkInt)
  1095. regs[ra].intVal = ord(regs[rb].intVal != regs[rc].intVal)
  1096. of opcNot:
  1097. decodeB(rkInt)
  1098. assert regs[rb].kind == rkInt
  1099. regs[ra].intVal = 1 - regs[rb].intVal
  1100. of opcUnaryMinusInt:
  1101. decodeB(rkInt)
  1102. assert regs[rb].kind == rkInt
  1103. let val = regs[rb].intVal
  1104. if val != int64.low:
  1105. regs[ra].intVal = -val
  1106. else:
  1107. stackTrace(c, tos, pc, errOverOrUnderflow)
  1108. of opcUnaryMinusFloat:
  1109. decodeB(rkFloat)
  1110. assert regs[rb].kind == rkFloat
  1111. regs[ra].floatVal = -regs[rb].floatVal
  1112. of opcBitnotInt:
  1113. decodeB(rkInt)
  1114. assert regs[rb].kind == rkInt
  1115. regs[ra].intVal = not regs[rb].intVal
  1116. of opcEqStr:
  1117. decodeBC(rkInt)
  1118. regs[ra].intVal = ord(regs[rb].node.strVal == regs[rc].node.strVal)
  1119. of opcEqCString:
  1120. decodeBC(rkInt)
  1121. let bNil = regs[rb].node.kind == nkNilLit
  1122. let cNil = regs[rc].node.kind == nkNilLit
  1123. regs[ra].intVal = ord((bNil and cNil) or
  1124. (not bNil and not cNil and regs[rb].node.strVal == regs[rc].node.strVal))
  1125. of opcLeStr:
  1126. decodeBC(rkInt)
  1127. regs[ra].intVal = ord(regs[rb].node.strVal <= regs[rc].node.strVal)
  1128. of opcLtStr:
  1129. decodeBC(rkInt)
  1130. regs[ra].intVal = ord(regs[rb].node.strVal < regs[rc].node.strVal)
  1131. of opcLeSet:
  1132. decodeBC(rkInt)
  1133. regs[ra].intVal = ord(containsSets(c.config, regs[rb].node, regs[rc].node))
  1134. of opcEqSet:
  1135. decodeBC(rkInt)
  1136. regs[ra].intVal = ord(equalSets(c.config, regs[rb].node, regs[rc].node))
  1137. of opcLtSet:
  1138. decodeBC(rkInt)
  1139. let a = regs[rb].node
  1140. let b = regs[rc].node
  1141. regs[ra].intVal = ord(containsSets(c.config, a, b) and not equalSets(c.config, a, b))
  1142. of opcMulSet:
  1143. decodeBC(rkNode)
  1144. createSet(regs[ra])
  1145. move(regs[ra].node.sons,
  1146. nimsets.intersectSets(c.config, regs[rb].node, regs[rc].node).sons)
  1147. of opcPlusSet:
  1148. decodeBC(rkNode)
  1149. createSet(regs[ra])
  1150. move(regs[ra].node.sons,
  1151. nimsets.unionSets(c.config, regs[rb].node, regs[rc].node).sons)
  1152. of opcMinusSet:
  1153. decodeBC(rkNode)
  1154. createSet(regs[ra])
  1155. move(regs[ra].node.sons,
  1156. nimsets.diffSets(c.config, regs[rb].node, regs[rc].node).sons)
  1157. of opcConcatStr:
  1158. decodeBC(rkNode)
  1159. createStr regs[ra]
  1160. regs[ra].node.strVal = getstr(regs[rb])
  1161. for i in rb+1..rb+rc-1:
  1162. regs[ra].node.strVal.add getstr(regs[i])
  1163. of opcAddStrCh:
  1164. decodeB(rkNode)
  1165. regs[ra].node.strVal.add(regs[rb].intVal.chr)
  1166. of opcAddStrStr:
  1167. decodeB(rkNode)
  1168. regs[ra].node.strVal.add(regs[rb].node.strVal)
  1169. of opcAddSeqElem:
  1170. decodeB(rkNode)
  1171. if regs[ra].node.kind == nkBracket:
  1172. regs[ra].node.add(copyValue(regs[rb].regToNode))
  1173. else:
  1174. stackTrace(c, tos, pc, errNilAccess)
  1175. of opcGetImpl:
  1176. decodeB(rkNode)
  1177. var a = regs[rb].node
  1178. if a.kind == nkVarTy: a = a[0]
  1179. if a.kind == nkSym:
  1180. regs[ra].node = if a.sym.ast.isNil: newNode(nkNilLit)
  1181. else: copyTree(a.sym.ast)
  1182. regs[ra].node.flags.incl nfIsRef
  1183. else:
  1184. stackTrace(c, tos, pc, "node is not a symbol")
  1185. of opcGetImplTransf:
  1186. decodeB(rkNode)
  1187. let a = regs[rb].node
  1188. if a.kind == nkSym:
  1189. regs[ra].node =
  1190. if a.sym.ast.isNil:
  1191. newNode(nkNilLit)
  1192. else:
  1193. let ast = a.sym.ast.shallowCopy
  1194. for i in 0..<a.sym.ast.len:
  1195. ast[i] = a.sym.ast[i]
  1196. ast[bodyPos] = transformBody(c.graph, c.idgen, a.sym, cache=true)
  1197. ast.copyTree()
  1198. of opcSymOwner:
  1199. decodeB(rkNode)
  1200. let a = regs[rb].node
  1201. if a.kind == nkSym:
  1202. regs[ra].node = if a.sym.owner.isNil: newNode(nkNilLit)
  1203. else: newSymNode(a.sym.skipGenericOwner)
  1204. regs[ra].node.flags.incl nfIsRef
  1205. else:
  1206. stackTrace(c, tos, pc, "node is not a symbol")
  1207. of opcSymIsInstantiationOf:
  1208. decodeBC(rkInt)
  1209. let a = regs[rb].node
  1210. let b = regs[rc].node
  1211. if a.kind == nkSym and a.sym.kind in skProcKinds and
  1212. b.kind == nkSym and b.sym.kind in skProcKinds:
  1213. regs[ra].intVal =
  1214. if sfFromGeneric in a.sym.flags and a.sym.owner == b.sym: 1
  1215. else: 0
  1216. else:
  1217. stackTrace(c, tos, pc, "node is not a proc symbol")
  1218. of opcEcho:
  1219. let rb = instr.regB
  1220. template fn(s) = msgWriteln(c.config, s, {msgStdout, msgNoUnitSep})
  1221. if rb == 1: fn(regs[ra].node.strVal)
  1222. else:
  1223. var outp = ""
  1224. for i in ra..ra+rb-1:
  1225. #if regs[i].kind != rkNode: debug regs[i]
  1226. outp.add(regs[i].node.strVal)
  1227. fn(outp)
  1228. of opcContainsSet:
  1229. decodeBC(rkInt)
  1230. regs[ra].intVal = ord(inSet(regs[rb].node, regs[rc].regToNode))
  1231. of opcSubStr:
  1232. decodeBC(rkNode)
  1233. inc pc
  1234. assert c.code[pc].opcode == opcSubStr
  1235. let rd = c.code[pc].regA
  1236. createStr regs[ra]
  1237. regs[ra].node.strVal = substr(regs[rb].node.strVal,
  1238. regs[rc].intVal.int, regs[rd].intVal.int)
  1239. of opcParseFloat:
  1240. decodeBC(rkInt)
  1241. inc pc
  1242. assert c.code[pc].opcode == opcParseFloat
  1243. let rd = c.code[pc].regA
  1244. var rcAddr = addr(regs[rc])
  1245. if rcAddr.kind == rkRegisterAddr: rcAddr = rcAddr.regAddr
  1246. elif regs[rc].kind != rkFloat:
  1247. regs[rc] = TFullReg(kind: rkFloat)
  1248. regs[ra].intVal = parseBiggestFloat(regs[rb].node.strVal,
  1249. rcAddr.floatVal, regs[rd].intVal.int)
  1250. of opcRangeChck:
  1251. let rb = instr.regB
  1252. let rc = instr.regC
  1253. if not (leValueConv(regs[rb].regToNode, regs[ra].regToNode) and
  1254. leValueConv(regs[ra].regToNode, regs[rc].regToNode)):
  1255. stackTrace(c, tos, pc,
  1256. errIllegalConvFromXtoY % [
  1257. $regs[ra].regToNode, "[" & $regs[rb].regToNode & ".." & $regs[rc].regToNode & "]"])
  1258. of opcIndCall, opcIndCallAsgn:
  1259. # dest = call regStart, n; where regStart = fn, arg1, ...
  1260. let rb = instr.regB
  1261. let rc = instr.regC
  1262. let bb = regs[rb].node
  1263. let isClosure = bb.kind == nkTupleConstr
  1264. let prc = if not isClosure: bb.sym else: bb[0].sym
  1265. if prc.offset < -1:
  1266. # it's a callback:
  1267. c.callbacks[-prc.offset-2].value(
  1268. VmArgs(ra: ra, rb: rb, rc: rc, slots: cast[ptr UncheckedArray[TFullReg]](addr regs[0]),
  1269. currentException: c.currentExceptionA,
  1270. currentLineInfo: c.debug[pc]))
  1271. elif importcCond(c, prc):
  1272. if compiletimeFFI notin c.config.features:
  1273. globalError(c.config, c.debug[pc], "VM not allowed to do FFI, see `compiletimeFFI`")
  1274. # we pass 'tos.slots' instead of 'regs' so that the compiler can keep
  1275. # 'regs' in a register:
  1276. when hasFFI:
  1277. if prc.position - 1 < 0:
  1278. globalError(c.config, c.debug[pc],
  1279. "VM call invalid: prc.position: " & $prc.position)
  1280. let prcValue = c.globals[prc.position-1]
  1281. if prcValue.kind == nkEmpty:
  1282. globalError(c.config, c.debug[pc], "cannot run " & prc.name.s)
  1283. var slots2: TNodeSeq
  1284. slots2.setLen(tos.slots.len)
  1285. for i in 0..<tos.slots.len:
  1286. slots2[i] = regToNode(tos.slots[i])
  1287. let newValue = callForeignFunction(c.config, prcValue, prc.typ, slots2,
  1288. rb+1, rc-1, c.debug[pc])
  1289. if newValue.kind != nkEmpty:
  1290. assert instr.opcode == opcIndCallAsgn
  1291. putIntoReg(regs[ra], newValue)
  1292. else:
  1293. globalError(c.config, c.debug[pc], "VM not built with FFI support")
  1294. elif prc.kind != skTemplate:
  1295. let newPc = compile(c, prc)
  1296. # tricky: a recursion is also a jump back, so we use the same
  1297. # logic as for loops:
  1298. if newPc < pc: handleJmpBack()
  1299. #echo "new pc ", newPc, " calling: ", prc.name.s
  1300. var newFrame = PStackFrame(prc: prc, comesFrom: pc, next: tos)
  1301. newSeq(newFrame.slots, prc.offset+ord(isClosure))
  1302. if not isEmptyType(prc.typ[0]):
  1303. putIntoReg(newFrame.slots[0], getNullValue(prc.typ[0], prc.info, c.config))
  1304. for i in 1..rc-1:
  1305. newFrame.slots[i] = regs[rb+i]
  1306. if isClosure:
  1307. newFrame.slots[rc] = TFullReg(kind: rkNode, node: regs[rb].node[1])
  1308. tos = newFrame
  1309. updateRegsAlias
  1310. # -1 for the following 'inc pc'
  1311. pc = newPc-1
  1312. else:
  1313. # for 'getAst' support we need to support template expansion here:
  1314. let genSymOwner = if tos.next != nil and tos.next.prc != nil:
  1315. tos.next.prc
  1316. else:
  1317. c.module
  1318. var macroCall = newNodeI(nkCall, c.debug[pc])
  1319. macroCall.add(newSymNode(prc))
  1320. for i in 1..rc-1:
  1321. let node = regs[rb+i].regToNode
  1322. node.info = c.debug[pc]
  1323. macroCall.add(node)
  1324. var a = evalTemplate(macroCall, prc, genSymOwner, c.config, c.cache, c.templInstCounter, c.idgen)
  1325. if a.kind == nkStmtList and a.len == 1: a = a[0]
  1326. a.recSetFlagIsRef
  1327. ensureKind(rkNode)
  1328. regs[ra].node = a
  1329. of opcTJmp:
  1330. # jump Bx if A != 0
  1331. let rbx = instr.regBx - wordExcess - 1 # -1 for the following 'inc pc'
  1332. if regs[ra].intVal != 0:
  1333. inc pc, rbx
  1334. of opcFJmp:
  1335. # jump Bx if A == 0
  1336. let rbx = instr.regBx - wordExcess - 1 # -1 for the following 'inc pc'
  1337. if regs[ra].intVal == 0:
  1338. inc pc, rbx
  1339. of opcJmp:
  1340. # jump Bx
  1341. let rbx = instr.regBx - wordExcess - 1 # -1 for the following 'inc pc'
  1342. inc pc, rbx
  1343. of opcJmpBack:
  1344. let rbx = instr.regBx - wordExcess - 1 # -1 for the following 'inc pc'
  1345. inc pc, rbx
  1346. handleJmpBack()
  1347. of opcBranch:
  1348. # we know the next instruction is a 'fjmp':
  1349. let branch = c.constants[instr.regBx-wordExcess]
  1350. var cond = false
  1351. for j in 0..<branch.len - 1:
  1352. if overlap(regs[ra].regToNode, branch[j]):
  1353. cond = true
  1354. break
  1355. assert c.code[pc+1].opcode == opcFJmp
  1356. inc pc
  1357. # we skip this instruction so that the final 'inc(pc)' skips
  1358. # the following jump
  1359. if not cond:
  1360. let instr2 = c.code[pc]
  1361. let rbx = instr2.regBx - wordExcess - 1 # -1 for the following 'inc pc'
  1362. inc pc, rbx
  1363. of opcTry:
  1364. let rbx = instr.regBx - wordExcess
  1365. tos.pushSafePoint(pc + rbx)
  1366. assert c.code[pc+rbx].opcode in {opcExcept, opcFinally}
  1367. of opcExcept:
  1368. # This opcode is never executed, it only holds information for the
  1369. # exception handling routines.
  1370. doAssert(false)
  1371. of opcFinally:
  1372. # Pop the last safepoint introduced by a opcTry. This opcode is only
  1373. # executed _iff_ no exception was raised in the body of the `try`
  1374. # statement hence the need to pop the safepoint here.
  1375. doAssert(savedPC < 0)
  1376. tos.popSafePoint()
  1377. of opcFinallyEnd:
  1378. # The control flow may not resume at the next instruction since we may be
  1379. # raising an exception or performing a cleanup.
  1380. if savedPC >= 0:
  1381. pc = savedPC - 1
  1382. savedPC = -1
  1383. if tos != savedFrame:
  1384. tos = savedFrame
  1385. updateRegsAlias
  1386. of opcRaise:
  1387. let raised =
  1388. # Empty `raise` statement - reraise current exception
  1389. if regs[ra].kind == rkNone:
  1390. c.currentExceptionA
  1391. else:
  1392. regs[ra].node
  1393. c.currentExceptionA = raised
  1394. # Set the `name` field of the exception
  1395. var exceptionNameNode = newStrNode(nkStrLit, c.currentExceptionA.typ.sym.name.s)
  1396. if c.currentExceptionA[2].kind == nkExprColonExpr:
  1397. exceptionNameNode.typ = c.currentExceptionA[2][1].typ
  1398. c.currentExceptionA[2][1] = exceptionNameNode
  1399. else:
  1400. exceptionNameNode.typ = c.currentExceptionA[2].typ
  1401. c.currentExceptionA[2] = exceptionNameNode
  1402. c.exceptionInstr = pc
  1403. var frame = tos
  1404. var jumpTo = findExceptionHandler(c, frame, raised)
  1405. while jumpTo.why == ExceptionGotoUnhandled and not frame.next.isNil:
  1406. frame = frame.next
  1407. jumpTo = findExceptionHandler(c, frame, raised)
  1408. case jumpTo.why:
  1409. of ExceptionGotoHandler:
  1410. # Jump to the handler, do nothing when the `finally` block ends.
  1411. savedPC = -1
  1412. pc = jumpTo.where - 1
  1413. if tos != frame:
  1414. tos = frame
  1415. updateRegsAlias
  1416. of ExceptionGotoFinally:
  1417. # Jump to the `finally` block first then re-jump here to continue the
  1418. # traversal of the exception chain
  1419. savedPC = pc
  1420. savedFrame = tos
  1421. pc = jumpTo.where - 1
  1422. if tos != frame:
  1423. tos = frame
  1424. updateRegsAlias
  1425. of ExceptionGotoUnhandled:
  1426. # Nobody handled this exception, error out.
  1427. bailOut(c, tos)
  1428. of opcNew:
  1429. ensureKind(rkNode)
  1430. let typ = c.types[instr.regBx - wordExcess]
  1431. regs[ra].node = getNullValue(typ, c.debug[pc], c.config)
  1432. regs[ra].node.flags.incl nfIsRef
  1433. of opcNewSeq:
  1434. let typ = c.types[instr.regBx - wordExcess]
  1435. inc pc
  1436. ensureKind(rkNode)
  1437. let instr2 = c.code[pc]
  1438. let count = regs[instr2.regA].intVal.int
  1439. regs[ra].node = newNodeI(nkBracket, c.debug[pc])
  1440. regs[ra].node.typ = typ
  1441. newSeq(regs[ra].node.sons, count)
  1442. for i in 0..<count:
  1443. regs[ra].node[i] = getNullValue(typ[0], c.debug[pc], c.config)
  1444. of opcNewStr:
  1445. decodeB(rkNode)
  1446. regs[ra].node = newNodeI(nkStrLit, c.debug[pc])
  1447. regs[ra].node.strVal = newString(regs[rb].intVal.int)
  1448. of opcLdImmInt:
  1449. # dest = immediate value
  1450. decodeBx(rkInt)
  1451. regs[ra].intVal = rbx
  1452. of opcLdNull:
  1453. ensureKind(rkNode)
  1454. let typ = c.types[instr.regBx - wordExcess]
  1455. regs[ra].node = getNullValue(typ, c.debug[pc], c.config)
  1456. # opcLdNull really is the gist of the VM's problems: should it load
  1457. # a fresh null to regs[ra].node or to regs[ra].node[]? This really
  1458. # depends on whether regs[ra] represents the variable itself or whether
  1459. # it holds the indirection! Due to the way registers are re-used we cannot
  1460. # say for sure here! --> The codegen has to deal with it
  1461. # via 'genAsgnPatch'.
  1462. of opcLdNullReg:
  1463. let typ = c.types[instr.regBx - wordExcess]
  1464. if typ.skipTypes(abstractInst+{tyRange}-{tyTypeDesc}).kind in {
  1465. tyFloat..tyFloat128}:
  1466. ensureKind(rkFloat)
  1467. regs[ra].floatVal = 0.0
  1468. else:
  1469. ensureKind(rkInt)
  1470. regs[ra].intVal = 0
  1471. of opcLdConst:
  1472. let rb = instr.regBx - wordExcess
  1473. let cnst = c.constants[rb]
  1474. if fitsRegister(cnst.typ):
  1475. reset(regs[ra])
  1476. putIntoReg(regs[ra], cnst)
  1477. else:
  1478. ensureKind(rkNode)
  1479. regs[ra].node = cnst
  1480. of opcAsgnConst:
  1481. let rb = instr.regBx - wordExcess
  1482. let cnst = c.constants[rb]
  1483. if fitsRegister(cnst.typ):
  1484. putIntoReg(regs[ra], cnst)
  1485. else:
  1486. ensureKind(rkNode)
  1487. regs[ra].node = cnst.copyTree
  1488. of opcLdGlobal:
  1489. let rb = instr.regBx - wordExcess - 1
  1490. ensureKind(rkNode)
  1491. regs[ra].node = c.globals[rb]
  1492. of opcLdGlobalDerefFFI:
  1493. let rb = instr.regBx - wordExcess - 1
  1494. let node = c.globals[rb]
  1495. let typ = node.typ
  1496. doAssert node.kind == nkIntLit, $(node.kind)
  1497. if typ.kind == tyPtr:
  1498. ensureKind(rkNode)
  1499. # use nkPtrLit once this is added
  1500. let node2 = newNodeIT(nkIntLit, c.debug[pc], typ)
  1501. node2.intVal = cast[ptr int](node.intVal)[]
  1502. node2.flags.incl nfIsPtr
  1503. regs[ra].node = node2
  1504. elif not derefPtrToReg(node.intVal, typ, regs[ra], isAssign = false):
  1505. stackTrace(c, tos, pc, "opcLdDeref unsupported type: " & $(typeToString(typ), typ[0].kind))
  1506. of opcLdGlobalAddrDerefFFI:
  1507. let rb = instr.regBx - wordExcess - 1
  1508. let node = c.globals[rb]
  1509. let typ = node.typ
  1510. var node2 = newNodeIT(nkIntLit, node.info, typ)
  1511. node2.intVal = node.intVal
  1512. node2.flags.incl nfIsPtr
  1513. ensureKind(rkNode)
  1514. regs[ra].node = node2
  1515. of opcLdGlobalAddr:
  1516. let rb = instr.regBx - wordExcess - 1
  1517. ensureKind(rkNodeAddr)
  1518. regs[ra].nodeAddr = addr(c.globals[rb])
  1519. of opcRepr:
  1520. decodeB(rkNode)
  1521. createStr regs[ra]
  1522. regs[ra].node.strVal = renderTree(regs[rb].regToNode, {renderNoComments, renderDocComments})
  1523. of opcQuit:
  1524. if c.mode in {emRepl, emStaticExpr, emStaticStmt}:
  1525. message(c.config, c.debug[pc], hintQuitCalled)
  1526. msgQuit(int8(toInt(getOrdValue(regs[ra].regToNode, onError = toInt128(1)))))
  1527. else:
  1528. return TFullReg(kind: rkNone)
  1529. of opcInvalidField:
  1530. let msg = regs[ra].node.strVal
  1531. let disc = regs[instr.regB].regToNode
  1532. let msg2 = formatFieldDefect(msg, $disc)
  1533. stackTrace(c, tos, pc, msg2)
  1534. of opcSetLenStr:
  1535. decodeB(rkNode)
  1536. #createStrKeepNode regs[ra]
  1537. regs[ra].node.strVal.setLen(regs[rb].intVal.int)
  1538. of opcOf:
  1539. decodeBC(rkInt)
  1540. let typ = c.types[regs[rc].intVal.int]
  1541. regs[ra].intVal = ord(inheritanceDiff(regs[rb].node.typ, typ) <= 0)
  1542. of opcIs:
  1543. decodeBC(rkInt)
  1544. let t1 = regs[rb].node.typ.skipTypes({tyTypeDesc})
  1545. let t2 = c.types[regs[rc].intVal.int]
  1546. # XXX: This should use the standard isOpImpl
  1547. let match = if t2.kind == tyUserTypeClass: true
  1548. else: sameType(t1, t2)
  1549. regs[ra].intVal = ord(match)
  1550. of opcSetLenSeq:
  1551. decodeB(rkNode)
  1552. let newLen = regs[rb].intVal.int
  1553. if regs[ra].node.isNil: stackTrace(c, tos, pc, errNilAccess)
  1554. else: c.setLenSeq(regs[ra].node, newLen, c.debug[pc])
  1555. of opcNarrowS:
  1556. decodeB(rkInt)
  1557. let min = -(1.BiggestInt shl (rb-1))
  1558. let max = (1.BiggestInt shl (rb-1))-1
  1559. if regs[ra].intVal < min or regs[ra].intVal > max:
  1560. stackTrace(c, tos, pc, "unhandled exception: value out of range")
  1561. of opcNarrowU:
  1562. decodeB(rkInt)
  1563. regs[ra].intVal = regs[ra].intVal and ((1'i64 shl rb)-1)
  1564. of opcSignExtend:
  1565. # like opcNarrowS, but no out of range possible
  1566. decodeB(rkInt)
  1567. let imm = 64 - rb
  1568. regs[ra].intVal = ashr(regs[ra].intVal shl imm, imm)
  1569. of opcIsNil:
  1570. decodeB(rkInt)
  1571. let node = regs[rb].node
  1572. regs[ra].intVal = ord(
  1573. # Note that `nfIsRef` + `nkNilLit` represents an allocated
  1574. # reference with the value `nil`, so `isNil` should be false!
  1575. (node.kind == nkNilLit and nfIsRef notin node.flags) or
  1576. (not node.typ.isNil and node.typ.kind == tyProc and
  1577. node.typ.callConv == ccClosure and node.safeLen > 0 and
  1578. node[0].kind == nkNilLit and node[1].kind == nkNilLit))
  1579. of opcNBindSym:
  1580. # cannot use this simple check
  1581. # if dynamicBindSym notin c.config.features:
  1582. # bindSym with static input
  1583. decodeBx(rkNode)
  1584. regs[ra].node = copyTree(c.constants[rbx])
  1585. regs[ra].node.flags.incl nfIsRef
  1586. of opcNDynBindSym:
  1587. # experimental bindSym
  1588. let
  1589. rb = instr.regB
  1590. rc = instr.regC
  1591. idx = int(regs[rb+rc-1].intVal)
  1592. callback = c.callbacks[idx].value
  1593. args = VmArgs(ra: ra, rb: rb, rc: rc, slots: cast[ptr UncheckedArray[TFullReg]](addr regs[0]),
  1594. currentException: c.currentExceptionA,
  1595. currentLineInfo: c.debug[pc])
  1596. callback(args)
  1597. regs[ra].node.flags.incl nfIsRef
  1598. of opcNChild:
  1599. decodeBC(rkNode)
  1600. let idx = regs[rc].intVal.int
  1601. let src = regs[rb].node
  1602. if src.kind in {nkEmpty..nkNilLit}:
  1603. stackTrace(c, tos, pc, "cannot get child of node kind: n" & $src.kind)
  1604. elif idx >=% src.len:
  1605. stackTrace(c, tos, pc, formatErrorIndexBound(idx, src.len-1))
  1606. else:
  1607. regs[ra].node = src[idx]
  1608. of opcNSetChild:
  1609. decodeBC(rkNode)
  1610. let idx = regs[rb].intVal.int
  1611. var dest = regs[ra].node
  1612. if nfSem in dest.flags and allowSemcheckedAstModification notin c.config.legacyFeatures:
  1613. stackTrace(c, tos, pc, "typechecked nodes may not be modified")
  1614. elif dest.kind in {nkEmpty..nkNilLit}:
  1615. stackTrace(c, tos, pc, "cannot set child of node kind: n" & $dest.kind)
  1616. elif idx >=% dest.len:
  1617. stackTrace(c, tos, pc, formatErrorIndexBound(idx, dest.len-1))
  1618. else:
  1619. dest[idx] = regs[rc].node
  1620. of opcNAdd:
  1621. decodeBC(rkNode)
  1622. var u = regs[rb].node
  1623. if nfSem in u.flags and allowSemcheckedAstModification notin c.config.legacyFeatures:
  1624. stackTrace(c, tos, pc, "typechecked nodes may not be modified")
  1625. elif u.kind in {nkEmpty..nkNilLit}:
  1626. stackTrace(c, tos, pc, "cannot add to node kind: n" & $u.kind)
  1627. else:
  1628. u.add(regs[rc].node)
  1629. regs[ra].node = u
  1630. of opcNAddMultiple:
  1631. decodeBC(rkNode)
  1632. let x = regs[rc].node
  1633. var u = regs[rb].node
  1634. if nfSem in u.flags and allowSemcheckedAstModification notin c.config.legacyFeatures:
  1635. stackTrace(c, tos, pc, "typechecked nodes may not be modified")
  1636. elif u.kind in {nkEmpty..nkNilLit}:
  1637. stackTrace(c, tos, pc, "cannot add to node kind: n" & $u.kind)
  1638. else:
  1639. for i in 0..<x.len: u.add(x[i])
  1640. regs[ra].node = u
  1641. of opcNKind:
  1642. decodeB(rkInt)
  1643. regs[ra].intVal = ord(regs[rb].node.kind)
  1644. c.comesFromHeuristic = regs[rb].node.info
  1645. of opcNSymKind:
  1646. decodeB(rkInt)
  1647. let a = regs[rb].node
  1648. if a.kind == nkSym:
  1649. regs[ra].intVal = ord(a.sym.kind)
  1650. else:
  1651. stackTrace(c, tos, pc, "node is not a symbol")
  1652. c.comesFromHeuristic = regs[rb].node.info
  1653. of opcNIntVal:
  1654. decodeB(rkInt)
  1655. let a = regs[rb].node
  1656. if a.kind in {nkCharLit..nkUInt64Lit}:
  1657. regs[ra].intVal = a.intVal
  1658. elif a.kind == nkSym and a.sym.kind == skEnumField:
  1659. regs[ra].intVal = a.sym.position
  1660. else:
  1661. stackTrace(c, tos, pc, errFieldXNotFound & "intVal")
  1662. of opcNFloatVal:
  1663. decodeB(rkFloat)
  1664. let a = regs[rb].node
  1665. case a.kind
  1666. of nkFloatLit..nkFloat64Lit: regs[ra].floatVal = a.floatVal
  1667. else: stackTrace(c, tos, pc, errFieldXNotFound & "floatVal")
  1668. of opcNSymbol:
  1669. decodeB(rkNode)
  1670. let a = regs[rb].node
  1671. if a.kind == nkSym:
  1672. regs[ra].node = copyNode(a)
  1673. else:
  1674. stackTrace(c, tos, pc, errFieldXNotFound & "symbol")
  1675. of opcNIdent:
  1676. decodeB(rkNode)
  1677. let a = regs[rb].node
  1678. if a.kind == nkIdent:
  1679. regs[ra].node = copyNode(a)
  1680. else:
  1681. stackTrace(c, tos, pc, errFieldXNotFound & "ident")
  1682. of opcNodeId:
  1683. decodeB(rkInt)
  1684. when defined(useNodeIds):
  1685. regs[ra].intVal = regs[rb].node.id
  1686. else:
  1687. regs[ra].intVal = -1
  1688. of opcNGetType:
  1689. let rb = instr.regB
  1690. let rc = instr.regC
  1691. case rc
  1692. of 0:
  1693. # getType opcode:
  1694. ensureKind(rkNode)
  1695. if regs[rb].kind == rkNode and regs[rb].node.typ != nil:
  1696. regs[ra].node = opMapTypeToAst(c.cache, regs[rb].node.typ, c.debug[pc], c.idgen)
  1697. elif regs[rb].kind == rkNode and regs[rb].node.kind == nkSym and regs[rb].node.sym.typ != nil:
  1698. regs[ra].node = opMapTypeToAst(c.cache, regs[rb].node.sym.typ, c.debug[pc], c.idgen)
  1699. else:
  1700. stackTrace(c, tos, pc, "node has no type")
  1701. of 1:
  1702. # typeKind opcode:
  1703. ensureKind(rkInt)
  1704. if regs[rb].kind == rkNode and regs[rb].node.typ != nil:
  1705. regs[ra].intVal = ord(regs[rb].node.typ.kind)
  1706. elif regs[rb].kind == rkNode and regs[rb].node.kind == nkSym and regs[rb].node.sym.typ != nil:
  1707. regs[ra].intVal = ord(regs[rb].node.sym.typ.kind)
  1708. #else:
  1709. # stackTrace(c, tos, pc, "node has no type")
  1710. of 2:
  1711. # getTypeInst opcode:
  1712. ensureKind(rkNode)
  1713. if regs[rb].kind == rkNode and regs[rb].node.typ != nil:
  1714. regs[ra].node = opMapTypeInstToAst(c.cache, regs[rb].node.typ, c.debug[pc], c.idgen)
  1715. elif regs[rb].kind == rkNode and regs[rb].node.kind == nkSym and regs[rb].node.sym.typ != nil:
  1716. regs[ra].node = opMapTypeInstToAst(c.cache, regs[rb].node.sym.typ, c.debug[pc], c.idgen)
  1717. else:
  1718. stackTrace(c, tos, pc, "node has no type")
  1719. else:
  1720. # getTypeImpl opcode:
  1721. ensureKind(rkNode)
  1722. if regs[rb].kind == rkNode and regs[rb].node.typ != nil:
  1723. regs[ra].node = opMapTypeImplToAst(c.cache, regs[rb].node.typ, c.debug[pc], c.idgen)
  1724. elif regs[rb].kind == rkNode and regs[rb].node.kind == nkSym and regs[rb].node.sym.typ != nil:
  1725. regs[ra].node = opMapTypeImplToAst(c.cache, regs[rb].node.sym.typ, c.debug[pc], c.idgen)
  1726. else:
  1727. stackTrace(c, tos, pc, "node has no type")
  1728. of opcNGetSize:
  1729. decodeBImm(rkInt)
  1730. let n = regs[rb].node
  1731. case imm
  1732. of 0: # size
  1733. if n.typ == nil:
  1734. stackTrace(c, tos, pc, "node has no type")
  1735. else:
  1736. regs[ra].intVal = getSize(c.config, n.typ)
  1737. of 1: # align
  1738. if n.typ == nil:
  1739. stackTrace(c, tos, pc, "node has no type")
  1740. else:
  1741. regs[ra].intVal = getAlign(c.config, n.typ)
  1742. else: # offset
  1743. if n.kind != nkSym:
  1744. stackTrace(c, tos, pc, "node is not a symbol")
  1745. elif n.sym.kind != skField:
  1746. stackTrace(c, tos, pc, "symbol is not a field (nskField)")
  1747. else:
  1748. regs[ra].intVal = n.sym.offset
  1749. of opcNStrVal:
  1750. decodeB(rkNode)
  1751. createStr regs[ra]
  1752. let a = regs[rb].node
  1753. case a.kind
  1754. of nkStrLit..nkTripleStrLit:
  1755. regs[ra].node.strVal = a.strVal
  1756. of nkCommentStmt:
  1757. regs[ra].node.strVal = a.comment
  1758. of nkIdent:
  1759. regs[ra].node.strVal = a.ident.s
  1760. of nkSym:
  1761. regs[ra].node.strVal = a.sym.name.s
  1762. else:
  1763. stackTrace(c, tos, pc, errFieldXNotFound & "strVal")
  1764. of opcNSigHash:
  1765. decodeB(rkNode)
  1766. createStr regs[ra]
  1767. if regs[rb].node.kind != nkSym:
  1768. stackTrace(c, tos, pc, "node is not a symbol")
  1769. else:
  1770. regs[ra].node.strVal = $sigHash(regs[rb].node.sym, c.config)
  1771. of opcSlurp:
  1772. decodeB(rkNode)
  1773. createStr regs[ra]
  1774. regs[ra].node.strVal = opSlurp(regs[rb].node.strVal, c.debug[pc],
  1775. c.module, c.config)
  1776. of opcGorge:
  1777. decodeBC(rkNode)
  1778. inc pc
  1779. let rd = c.code[pc].regA
  1780. createStr regs[ra]
  1781. if defined(nimsuggest) or c.config.cmd == cmdCheck:
  1782. discard "don't run staticExec for 'nim suggest'"
  1783. regs[ra].node.strVal = ""
  1784. else:
  1785. when defined(nimcore):
  1786. regs[ra].node.strVal = opGorge(regs[rb].node.strVal,
  1787. regs[rc].node.strVal, regs[rd].node.strVal,
  1788. c.debug[pc], c.config)[0]
  1789. else:
  1790. regs[ra].node.strVal = ""
  1791. globalError(c.config, c.debug[pc], "VM is not built with 'gorge' support")
  1792. of opcNError, opcNWarning, opcNHint:
  1793. decodeB(rkNode)
  1794. let a = regs[ra].node
  1795. let b = regs[rb].node
  1796. let info = if b.kind == nkNilLit: c.debug[pc] else: b.info
  1797. if instr.opcode == opcNError:
  1798. stackTrace(c, tos, pc, a.strVal, info)
  1799. elif instr.opcode == opcNWarning:
  1800. message(c.config, info, warnUser, a.strVal)
  1801. elif instr.opcode == opcNHint:
  1802. message(c.config, info, hintUser, a.strVal)
  1803. of opcParseExprToAst:
  1804. decodeB(rkNode)
  1805. # c.debug[pc].line.int - countLines(regs[rb].strVal) ?
  1806. var error: string
  1807. let ast = parseString(regs[rb].node.strVal, c.cache, c.config,
  1808. toFullPath(c.config, c.debug[pc]), c.debug[pc].line.int,
  1809. proc (conf: ConfigRef; info: TLineInfo; msg: TMsgKind; arg: string) {.nosinks.} =
  1810. if error.len == 0 and msg <= errMax:
  1811. error = formatMsg(conf, info, msg, arg))
  1812. if error.len > 0:
  1813. c.errorFlag = error
  1814. elif ast.len != 1:
  1815. c.errorFlag = formatMsg(c.config, c.debug[pc], errGenerated,
  1816. "expected expression, but got multiple statements")
  1817. else:
  1818. regs[ra].node = ast[0]
  1819. of opcParseStmtToAst:
  1820. decodeB(rkNode)
  1821. var error: string
  1822. let ast = parseString(regs[rb].node.strVal, c.cache, c.config,
  1823. toFullPath(c.config, c.debug[pc]), c.debug[pc].line.int,
  1824. proc (conf: ConfigRef; info: TLineInfo; msg: TMsgKind; arg: string) {.nosinks.} =
  1825. if error.len == 0 and msg <= errMax:
  1826. error = formatMsg(conf, info, msg, arg))
  1827. if error.len > 0:
  1828. c.errorFlag = error
  1829. else:
  1830. regs[ra].node = ast
  1831. of opcQueryErrorFlag:
  1832. createStr regs[ra]
  1833. regs[ra].node.strVal = c.errorFlag
  1834. c.errorFlag.setLen 0
  1835. of opcCallSite:
  1836. ensureKind(rkNode)
  1837. if c.callsite != nil: regs[ra].node = c.callsite
  1838. else: stackTrace(c, tos, pc, errFieldXNotFound & "callsite")
  1839. of opcNGetLineInfo:
  1840. decodeBImm(rkNode)
  1841. let n = regs[rb].node
  1842. case imm
  1843. of 0: # getFile
  1844. regs[ra].node = newStrNode(nkStrLit, toFullPath(c.config, n.info))
  1845. of 1: # getLine
  1846. regs[ra].node = newIntNode(nkIntLit, n.info.line.int)
  1847. of 2: # getColumn
  1848. regs[ra].node = newIntNode(nkIntLit, n.info.col.int)
  1849. else:
  1850. internalAssert c.config, false
  1851. regs[ra].node.info = n.info
  1852. regs[ra].node.typ = n.typ
  1853. of opcNCopyLineInfo:
  1854. decodeB(rkNode)
  1855. regs[ra].node.info = regs[rb].node.info
  1856. of opcNSetLineInfoLine:
  1857. decodeB(rkNode)
  1858. regs[ra].node.info.line = regs[rb].intVal.uint16
  1859. of opcNSetLineInfoColumn:
  1860. decodeB(rkNode)
  1861. regs[ra].node.info.col = regs[rb].intVal.int16
  1862. of opcNSetLineInfoFile:
  1863. decodeB(rkNode)
  1864. regs[ra].node.info.fileIndex =
  1865. fileInfoIdx(c.config, RelativeFile regs[rb].node.strVal)
  1866. of opcEqIdent:
  1867. decodeBC(rkInt)
  1868. # aliases for shorter and easier to understand code below
  1869. var aNode = regs[rb].node
  1870. var bNode = regs[rc].node
  1871. # Skipping both, `nkPostfix` and `nkAccQuoted` for both
  1872. # arguments. `nkPostfix` exists only to tag exported symbols
  1873. # and therefor it can be safely skipped. Nim has no postfix
  1874. # operator. `nkAccQuoted` is used to quote an identifier that
  1875. # wouldn't be allowed to use in an unquoted context.
  1876. if aNode.kind == nkPostfix:
  1877. aNode = aNode[1]
  1878. if aNode.kind == nkAccQuoted:
  1879. aNode = aNode[0]
  1880. if bNode.kind == nkPostfix:
  1881. bNode = bNode[1]
  1882. if bNode.kind == nkAccQuoted:
  1883. bNode = bNode[0]
  1884. # These vars are of type `cstring` to prevent unnecessary string copy.
  1885. var aStrVal: cstring = nil
  1886. var bStrVal: cstring = nil
  1887. # extract strVal from argument ``a``
  1888. case aNode.kind
  1889. of nkStrLit..nkTripleStrLit:
  1890. aStrVal = aNode.strVal.cstring
  1891. of nkIdent:
  1892. aStrVal = aNode.ident.s.cstring
  1893. of nkSym:
  1894. aStrVal = aNode.sym.name.s.cstring
  1895. of nkOpenSymChoice, nkClosedSymChoice:
  1896. aStrVal = aNode[0].sym.name.s.cstring
  1897. else:
  1898. discard
  1899. # extract strVal from argument ``b``
  1900. case bNode.kind
  1901. of nkStrLit..nkTripleStrLit:
  1902. bStrVal = bNode.strVal.cstring
  1903. of nkIdent:
  1904. bStrVal = bNode.ident.s.cstring
  1905. of nkSym:
  1906. bStrVal = bNode.sym.name.s.cstring
  1907. of nkOpenSymChoice, nkClosedSymChoice:
  1908. bStrVal = bNode[0].sym.name.s.cstring
  1909. else:
  1910. discard
  1911. regs[ra].intVal =
  1912. if aStrVal != nil and bStrVal != nil:
  1913. ord(idents.cmpIgnoreStyle(aStrVal, bStrVal, high(int)) == 0)
  1914. else:
  1915. 0
  1916. of opcStrToIdent:
  1917. decodeB(rkNode)
  1918. if regs[rb].node.kind notin {nkStrLit..nkTripleStrLit}:
  1919. stackTrace(c, tos, pc, errFieldXNotFound & "strVal")
  1920. else:
  1921. regs[ra].node = newNodeI(nkIdent, c.debug[pc])
  1922. regs[ra].node.ident = getIdent(c.cache, regs[rb].node.strVal)
  1923. regs[ra].node.flags.incl nfIsRef
  1924. of opcSetType:
  1925. let typ = c.types[instr.regBx - wordExcess]
  1926. if regs[ra].kind != rkNode:
  1927. let temp = regToNode(regs[ra])
  1928. ensureKind(rkNode)
  1929. regs[ra].node = temp
  1930. regs[ra].node.info = c.debug[pc]
  1931. regs[ra].node.typ = typ
  1932. of opcConv:
  1933. let rb = instr.regB
  1934. inc pc
  1935. let desttyp = c.types[c.code[pc].regBx - wordExcess]
  1936. inc pc
  1937. let srctyp = c.types[c.code[pc].regBx - wordExcess]
  1938. if opConv(c, regs[ra], regs[rb], desttyp, srctyp):
  1939. stackTrace(c, tos, pc,
  1940. errIllegalConvFromXtoY % [
  1941. typeToString(srctyp), typeToString(desttyp)])
  1942. of opcCast:
  1943. let rb = instr.regB
  1944. inc pc
  1945. let desttyp = c.types[c.code[pc].regBx - wordExcess]
  1946. inc pc
  1947. let srctyp = c.types[c.code[pc].regBx - wordExcess]
  1948. when hasFFI:
  1949. let dest = fficast(c.config, regs[rb].node, desttyp)
  1950. # todo: check whether this is correct
  1951. # asgnRef(regs[ra], dest)
  1952. putIntoReg(regs[ra], dest)
  1953. else:
  1954. globalError(c.config, c.debug[pc], "cannot evaluate cast")
  1955. of opcNSetIntVal:
  1956. decodeB(rkNode)
  1957. var dest = regs[ra].node
  1958. if dest.kind in {nkCharLit..nkUInt64Lit} and
  1959. regs[rb].kind in {rkInt}:
  1960. dest.intVal = regs[rb].intVal
  1961. elif dest.kind == nkSym and dest.sym.kind == skEnumField:
  1962. stackTrace(c, tos, pc, "`intVal` cannot be changed for an enum symbol.")
  1963. else:
  1964. stackTrace(c, tos, pc, errFieldXNotFound & "intVal")
  1965. of opcNSetFloatVal:
  1966. decodeB(rkNode)
  1967. var dest = regs[ra].node
  1968. if dest.kind in {nkFloatLit..nkFloat64Lit} and
  1969. regs[rb].kind in {rkFloat}:
  1970. dest.floatVal = regs[rb].floatVal
  1971. else:
  1972. stackTrace(c, tos, pc, errFieldXNotFound & "floatVal")
  1973. of opcNSetSymbol:
  1974. decodeB(rkNode)
  1975. var dest = regs[ra].node
  1976. if dest.kind == nkSym and regs[rb].node.kind == nkSym:
  1977. dest.sym = regs[rb].node.sym
  1978. else:
  1979. stackTrace(c, tos, pc, errFieldXNotFound & "symbol")
  1980. of opcNSetIdent:
  1981. decodeB(rkNode)
  1982. var dest = regs[ra].node
  1983. if dest.kind == nkIdent and regs[rb].node.kind == nkIdent:
  1984. dest.ident = regs[rb].node.ident
  1985. else:
  1986. stackTrace(c, tos, pc, errFieldXNotFound & "ident")
  1987. of opcNSetType:
  1988. decodeB(rkNode)
  1989. let b = regs[rb].node
  1990. internalAssert c.config, b.kind == nkSym and b.sym.kind == skType
  1991. internalAssert c.config, regs[ra].node != nil
  1992. regs[ra].node.typ = b.sym.typ
  1993. of opcNSetStrVal:
  1994. decodeB(rkNode)
  1995. var dest = regs[ra].node
  1996. if dest.kind in {nkStrLit..nkTripleStrLit} and
  1997. regs[rb].kind in {rkNode}:
  1998. dest.strVal = regs[rb].node.strVal
  1999. elif dest.kind == nkCommentStmt and regs[rb].kind in {rkNode}:
  2000. dest.comment = regs[rb].node.strVal
  2001. else:
  2002. stackTrace(c, tos, pc, errFieldXNotFound & "strVal")
  2003. of opcNNewNimNode:
  2004. decodeBC(rkNode)
  2005. var k = regs[rb].intVal
  2006. if k < 0 or k > ord(high(TNodeKind)):
  2007. internalError(c.config, c.debug[pc],
  2008. "request to create a NimNode of invalid kind")
  2009. let cc = regs[rc].node
  2010. let x = newNodeI(TNodeKind(int(k)),
  2011. if cc.kind != nkNilLit:
  2012. cc.info
  2013. elif c.comesFromHeuristic.line != 0'u16:
  2014. c.comesFromHeuristic
  2015. elif c.callsite != nil and c.callsite.safeLen > 1:
  2016. c.callsite[1].info
  2017. else:
  2018. c.debug[pc])
  2019. x.flags.incl nfIsRef
  2020. # prevent crashes in the compiler resulting from wrong macros:
  2021. if x.kind == nkIdent: x.ident = c.cache.emptyIdent
  2022. regs[ra].node = x
  2023. of opcNCopyNimNode:
  2024. decodeB(rkNode)
  2025. regs[ra].node = copyNode(regs[rb].node)
  2026. of opcNCopyNimTree:
  2027. decodeB(rkNode)
  2028. regs[ra].node = copyTree(regs[rb].node)
  2029. of opcNDel:
  2030. decodeBC(rkNode)
  2031. let bb = regs[rb].intVal.int
  2032. for i in 0..<regs[rc].intVal.int:
  2033. delSon(regs[ra].node, bb)
  2034. of opcGenSym:
  2035. decodeBC(rkNode)
  2036. let k = regs[rb].intVal
  2037. let name = if regs[rc].node.strVal.len == 0: ":tmp"
  2038. else: regs[rc].node.strVal
  2039. if k < 0 or k > ord(high(TSymKind)):
  2040. internalError(c.config, c.debug[pc], "request to create symbol of invalid kind")
  2041. var sym = newSym(k.TSymKind, getIdent(c.cache, name), nextSymId c.idgen, c.module.owner, c.debug[pc])
  2042. incl(sym.flags, sfGenSym)
  2043. regs[ra].node = newSymNode(sym)
  2044. regs[ra].node.flags.incl nfIsRef
  2045. of opcNccValue:
  2046. decodeB(rkInt)
  2047. let destKey = regs[rb].node.strVal
  2048. regs[ra].intVal = getOrDefault(c.graph.cacheCounters, destKey)
  2049. of opcNccInc:
  2050. let g = c.graph
  2051. declBC()
  2052. let destKey = regs[rb].node.strVal
  2053. let by = regs[rc].intVal
  2054. let v = getOrDefault(g.cacheCounters, destKey)
  2055. g.cacheCounters[destKey] = v+by
  2056. recordInc(c, c.debug[pc], destKey, by)
  2057. of opcNcsAdd:
  2058. let g = c.graph
  2059. declBC()
  2060. let destKey = regs[rb].node.strVal
  2061. let val = regs[rc].node
  2062. if not contains(g.cacheSeqs, destKey):
  2063. g.cacheSeqs[destKey] = newTree(nkStmtList, val)
  2064. else:
  2065. g.cacheSeqs[destKey].add val
  2066. recordAdd(c, c.debug[pc], destKey, val)
  2067. of opcNcsIncl:
  2068. let g = c.graph
  2069. declBC()
  2070. let destKey = regs[rb].node.strVal
  2071. let val = regs[rc].node
  2072. if not contains(g.cacheSeqs, destKey):
  2073. g.cacheSeqs[destKey] = newTree(nkStmtList, val)
  2074. else:
  2075. block search:
  2076. for existing in g.cacheSeqs[destKey]:
  2077. if exprStructuralEquivalent(existing, val, strictSymEquality=true):
  2078. break search
  2079. g.cacheSeqs[destKey].add val
  2080. recordIncl(c, c.debug[pc], destKey, val)
  2081. of opcNcsLen:
  2082. let g = c.graph
  2083. decodeB(rkInt)
  2084. let destKey = regs[rb].node.strVal
  2085. regs[ra].intVal =
  2086. if contains(g.cacheSeqs, destKey): g.cacheSeqs[destKey].len else: 0
  2087. of opcNcsAt:
  2088. let g = c.graph
  2089. decodeBC(rkNode)
  2090. let idx = regs[rc].intVal
  2091. let destKey = regs[rb].node.strVal
  2092. if contains(g.cacheSeqs, destKey) and idx <% g.cacheSeqs[destKey].len:
  2093. regs[ra].node = g.cacheSeqs[destKey][idx.int]
  2094. else:
  2095. stackTrace(c, tos, pc, formatErrorIndexBound(idx, g.cacheSeqs[destKey].len-1))
  2096. of opcNctPut:
  2097. let g = c.graph
  2098. let destKey = regs[ra].node.strVal
  2099. let key = regs[instr.regB].node.strVal
  2100. let val = regs[instr.regC].node
  2101. if not contains(g.cacheTables, destKey):
  2102. g.cacheTables[destKey] = initBTree[string, PNode]()
  2103. if not contains(g.cacheTables[destKey], key):
  2104. g.cacheTables[destKey].add(key, val)
  2105. recordPut(c, c.debug[pc], destKey, key, val)
  2106. else:
  2107. stackTrace(c, tos, pc, "key already exists: " & key)
  2108. of opcNctLen:
  2109. let g = c.graph
  2110. decodeB(rkInt)
  2111. let destKey = regs[rb].node.strVal
  2112. regs[ra].intVal =
  2113. if contains(g.cacheTables, destKey): g.cacheTables[destKey].len else: 0
  2114. of opcNctGet:
  2115. let g = c.graph
  2116. decodeBC(rkNode)
  2117. let destKey = regs[rb].node.strVal
  2118. let key = regs[rc].node.strVal
  2119. if contains(g.cacheTables, destKey):
  2120. if contains(g.cacheTables[destKey], key):
  2121. regs[ra].node = getOrDefault(g.cacheTables[destKey], key)
  2122. else:
  2123. stackTrace(c, tos, pc, "key does not exist: " & key)
  2124. else:
  2125. stackTrace(c, tos, pc, "key does not exist: " & destKey)
  2126. of opcNctHasNext:
  2127. let g = c.graph
  2128. decodeBC(rkInt)
  2129. let destKey = regs[rb].node.strVal
  2130. regs[ra].intVal =
  2131. if g.cacheTables.contains(destKey):
  2132. ord(btrees.hasNext(g.cacheTables[destKey], regs[rc].intVal.int))
  2133. else:
  2134. 0
  2135. of opcNctNext:
  2136. let g = c.graph
  2137. decodeBC(rkNode)
  2138. let destKey = regs[rb].node.strVal
  2139. let index = regs[rc].intVal
  2140. if contains(g.cacheTables, destKey):
  2141. let (k, v, nextIndex) = btrees.next(g.cacheTables[destKey], index.int)
  2142. regs[ra].node = newTree(nkTupleConstr, newStrNode(k, c.debug[pc]), v,
  2143. newIntNode(nkIntLit, nextIndex))
  2144. else:
  2145. stackTrace(c, tos, pc, "key does not exist: " & destKey)
  2146. of opcTypeTrait:
  2147. # XXX only supports 'name' for now; we can use regC to encode the
  2148. # type trait operation
  2149. decodeB(rkNode)
  2150. var typ = regs[rb].node.typ
  2151. internalAssert c.config, typ != nil
  2152. while typ.kind == tyTypeDesc and typ.len > 0: typ = typ[0]
  2153. createStr regs[ra]
  2154. regs[ra].node.strVal = typ.typeToString(preferExported)
  2155. of opcMarshalLoad:
  2156. let ra = instr.regA
  2157. let rb = instr.regB
  2158. inc pc
  2159. let typ = c.types[c.code[pc].regBx - wordExcess]
  2160. putIntoReg(regs[ra], loadAny(regs[rb].node.strVal, typ, c.cache, c.config, c.idgen))
  2161. of opcMarshalStore:
  2162. decodeB(rkNode)
  2163. inc pc
  2164. let typ = c.types[c.code[pc].regBx - wordExcess]
  2165. createStrKeepNode(regs[ra])
  2166. storeAny(regs[ra].node.strVal, typ, regs[rb].regToNode, c.config)
  2167. c.profiler.leave(c)
  2168. inc pc
  2169. proc execute(c: PCtx, start: int): PNode =
  2170. var tos = PStackFrame(prc: nil, comesFrom: 0, next: nil)
  2171. newSeq(tos.slots, c.prc.regInfo.len)
  2172. result = rawExecute(c, start, tos).regToNode
  2173. proc execProc*(c: PCtx; sym: PSym; args: openArray[PNode]): PNode =
  2174. c.loopIterations = c.config.maxLoopIterationsVM
  2175. if sym.kind in routineKinds:
  2176. if sym.typ.len-1 != args.len:
  2177. localError(c.config, sym.info,
  2178. "NimScript: expected $# arguments, but got $#" % [
  2179. $(sym.typ.len-1), $args.len])
  2180. else:
  2181. let start = genProc(c, sym)
  2182. var tos = PStackFrame(prc: sym, comesFrom: 0, next: nil)
  2183. let maxSlots = sym.offset
  2184. newSeq(tos.slots, maxSlots)
  2185. # setup parameters:
  2186. if not isEmptyType(sym.typ[0]) or sym.kind == skMacro:
  2187. putIntoReg(tos.slots[0], getNullValue(sym.typ[0], sym.info, c.config))
  2188. # XXX We could perform some type checking here.
  2189. for i in 1..<sym.typ.len:
  2190. putIntoReg(tos.slots[i], args[i-1])
  2191. result = rawExecute(c, start, tos).regToNode
  2192. else:
  2193. localError(c.config, sym.info,
  2194. "NimScript: attempt to call non-routine: " & sym.name.s)
  2195. proc evalStmt*(c: PCtx, n: PNode) =
  2196. let n = transformExpr(c.graph, c.idgen, c.module, n)
  2197. let start = genStmt(c, n)
  2198. # execute new instructions; this redundant opcEof check saves us lots
  2199. # of allocations in 'execute':
  2200. if c.code[start].opcode != opcEof:
  2201. discard execute(c, start)
  2202. proc evalExpr*(c: PCtx, n: PNode): PNode =
  2203. # deadcode
  2204. # `nim --eval:"expr"` might've used it at some point for idetools; could
  2205. # be revived for nimsuggest
  2206. let n = transformExpr(c.graph, c.idgen, c.module, n)
  2207. let start = genExpr(c, n)
  2208. assert c.code[start].opcode != opcEof
  2209. result = execute(c, start)
  2210. proc getGlobalValue*(c: PCtx; s: PSym): PNode =
  2211. internalAssert c.config, s.kind in {skLet, skVar} and sfGlobal in s.flags
  2212. result = c.globals[s.position-1]
  2213. proc setGlobalValue*(c: PCtx; s: PSym, val: PNode) =
  2214. ## Does not do type checking so ensure the `val` matches the `s.typ`
  2215. internalAssert c.config, s.kind in {skLet, skVar} and sfGlobal in s.flags
  2216. c.globals[s.position-1] = val
  2217. include vmops
  2218. proc setupGlobalCtx*(module: PSym; graph: ModuleGraph; idgen: IdGenerator) =
  2219. if graph.vm.isNil:
  2220. graph.vm = newCtx(module, graph.cache, graph, idgen)
  2221. registerAdditionalOps(PCtx graph.vm)
  2222. else:
  2223. refresh(PCtx graph.vm, module, idgen)
  2224. proc myOpen(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext {.nosinks.} =
  2225. #var c = newEvalContext(module, emRepl)
  2226. #c.features = {allowCast, allowInfiniteLoops}
  2227. #pushStackFrame(c, newStackFrame())
  2228. # XXX produce a new 'globals' environment here:
  2229. setupGlobalCtx(module, graph, idgen)
  2230. result = PCtx graph.vm
  2231. proc myProcess(c: PPassContext, n: PNode): PNode =
  2232. let c = PCtx(c)
  2233. # don't eval errornous code:
  2234. if c.oldErrorCount == c.config.errorCounter:
  2235. evalStmt(c, n)
  2236. result = newNodeI(nkEmpty, n.info)
  2237. else:
  2238. result = n
  2239. c.oldErrorCount = c.config.errorCounter
  2240. proc myClose(graph: ModuleGraph; c: PPassContext, n: PNode): PNode =
  2241. result = myProcess(c, n)
  2242. const evalPass* = makePass(myOpen, myProcess, myClose)
  2243. proc evalConstExprAux(module: PSym; idgen: IdGenerator;
  2244. g: ModuleGraph; prc: PSym, n: PNode,
  2245. mode: TEvalMode): PNode =
  2246. when defined(nimsuggest):
  2247. if g.config.expandDone():
  2248. return n
  2249. #if g.config.errorCounter > 0: return n
  2250. let n = transformExpr(g, idgen, module, n)
  2251. setupGlobalCtx(module, g, idgen)
  2252. var c = PCtx g.vm
  2253. let oldMode = c.mode
  2254. c.mode = mode
  2255. let start = genExpr(c, n, requiresValue = mode!=emStaticStmt)
  2256. if c.code[start].opcode == opcEof: return newNodeI(nkEmpty, n.info)
  2257. assert c.code[start].opcode != opcEof
  2258. when debugEchoCode: c.echoCode start
  2259. var tos = PStackFrame(prc: prc, comesFrom: 0, next: nil)
  2260. newSeq(tos.slots, c.prc.regInfo.len)
  2261. #for i in 0..<c.prc.regInfo.len: tos.slots[i] = newNode(nkEmpty)
  2262. result = rawExecute(c, start, tos).regToNode
  2263. if result.info.col < 0: result.info = n.info
  2264. c.mode = oldMode
  2265. proc evalConstExpr*(module: PSym; idgen: IdGenerator; g: ModuleGraph; e: PNode): PNode =
  2266. result = evalConstExprAux(module, idgen, g, nil, e, emConst)
  2267. proc evalStaticExpr*(module: PSym; idgen: IdGenerator; g: ModuleGraph; e: PNode, prc: PSym): PNode =
  2268. result = evalConstExprAux(module, idgen, g, prc, e, emStaticExpr)
  2269. proc evalStaticStmt*(module: PSym; idgen: IdGenerator; g: ModuleGraph; e: PNode, prc: PSym) =
  2270. discard evalConstExprAux(module, idgen, g, prc, e, emStaticStmt)
  2271. proc setupCompileTimeVar*(module: PSym; idgen: IdGenerator; g: ModuleGraph; n: PNode) =
  2272. discard evalConstExprAux(module, idgen, g, nil, n, emStaticStmt)
  2273. proc prepareVMValue(arg: PNode): PNode =
  2274. ## strip nkExprColonExpr from tuple values recursively. That is how
  2275. ## they are expected to be stored in the VM.
  2276. # Early abort without copy. No transformation takes place.
  2277. if arg.kind in nkLiterals:
  2278. return arg
  2279. if arg.kind == nkExprColonExpr and arg[0].typ != nil and
  2280. arg[0].typ.sym != nil and arg[0].typ.sym.magic == mPNimrodNode:
  2281. # Poor mans way of protecting static NimNodes
  2282. # XXX: Maybe we need a nkNimNode?
  2283. return arg
  2284. result = copyNode(arg)
  2285. if arg.kind == nkTupleConstr:
  2286. for child in arg:
  2287. if child.kind == nkExprColonExpr:
  2288. result.add prepareVMValue(child[1])
  2289. else:
  2290. result.add prepareVMValue(child)
  2291. else:
  2292. for child in arg:
  2293. result.add prepareVMValue(child)
  2294. proc setupMacroParam(x: PNode, typ: PType): TFullReg =
  2295. case typ.kind
  2296. of tyStatic:
  2297. putIntoReg(result, prepareVMValue(x))
  2298. else:
  2299. var n = x
  2300. if n.kind in {nkHiddenSubConv, nkHiddenStdConv}: n = n[1]
  2301. n.flags.incl nfIsRef
  2302. n.typ = x.typ
  2303. result = TFullReg(kind: rkNode, node: n)
  2304. iterator genericParamsInMacroCall*(macroSym: PSym, call: PNode): (PSym, PNode) =
  2305. let gp = macroSym.ast[genericParamsPos]
  2306. for i in 0..<gp.len:
  2307. let genericParam = gp[i].sym
  2308. let posInCall = macroSym.typ.len + i
  2309. if posInCall < call.len:
  2310. yield (genericParam, call[posInCall])
  2311. # to prevent endless recursion in macro instantiation
  2312. const evalMacroLimit = 1000
  2313. #proc errorNode(idgen: IdGenerator; owner: PSym, n: PNode): PNode =
  2314. # result = newNodeI(nkEmpty, n.info)
  2315. # result.typ = newType(tyError, nextTypeId idgen, owner)
  2316. # result.typ.flags.incl tfCheckedForDestructor
  2317. proc evalMacroCall*(module: PSym; idgen: IdGenerator; g: ModuleGraph; templInstCounter: ref int;
  2318. n, nOrig: PNode, sym: PSym): PNode =
  2319. #if g.config.errorCounter > 0: return errorNode(idgen, module, n)
  2320. # XXX globalError() is ugly here, but I don't know a better solution for now
  2321. inc(g.config.evalMacroCounter)
  2322. if g.config.evalMacroCounter > evalMacroLimit:
  2323. globalError(g.config, n.info, "macro instantiation too nested")
  2324. # immediate macros can bypass any type and arity checking so we check the
  2325. # arity here too:
  2326. if sym.typ.len > n.safeLen and sym.typ.len > 1:
  2327. globalError(g.config, n.info, "in call '$#' got $#, but expected $# argument(s)" % [
  2328. n.renderTree, $(n.safeLen-1), $(sym.typ.len-1)])
  2329. setupGlobalCtx(module, g, idgen)
  2330. var c = PCtx g.vm
  2331. let oldMode = c.mode
  2332. c.mode = emStaticStmt
  2333. c.comesFromHeuristic.line = 0'u16
  2334. c.callsite = nOrig
  2335. c.templInstCounter = templInstCounter
  2336. let start = genProc(c, sym)
  2337. var tos = PStackFrame(prc: sym, comesFrom: 0, next: nil)
  2338. let maxSlots = sym.offset
  2339. newSeq(tos.slots, maxSlots)
  2340. # setup arguments:
  2341. var L = n.safeLen
  2342. if L == 0: L = 1
  2343. # This is wrong for tests/reject/tind1.nim where the passed 'else' part
  2344. # doesn't end up in the parameter:
  2345. #InternalAssert tos.slots.len >= L
  2346. # return value:
  2347. tos.slots[0] = TFullReg(kind: rkNode, node: newNodeI(nkEmpty, n.info))
  2348. # setup parameters:
  2349. for i in 1..<sym.typ.len:
  2350. tos.slots[i] = setupMacroParam(n[i], sym.typ[i])
  2351. let gp = sym.ast[genericParamsPos]
  2352. for i in 0..<gp.len:
  2353. let idx = sym.typ.len + i
  2354. if idx < n.len:
  2355. tos.slots[idx] = setupMacroParam(n[idx], gp[i].sym.typ)
  2356. else:
  2357. dec(g.config.evalMacroCounter)
  2358. c.callsite = nil
  2359. localError(c.config, n.info, "expected " & $gp.len &
  2360. " generic parameter(s)")
  2361. # temporary storage:
  2362. #for i in L..<maxSlots: tos.slots[i] = newNode(nkEmpty)
  2363. result = rawExecute(c, start, tos).regToNode
  2364. if result.info.line < 0: result.info = n.info
  2365. if cyclicTree(result): globalError(c.config, n.info, "macro produced a cyclic tree")
  2366. dec(g.config.evalMacroCounter)
  2367. c.callsite = nil
  2368. c.mode = oldMode