vm.nim 88 KB

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