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