vm.nim 89 KB

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