vm.nim 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509
  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. if regs[rb].node.kind == nkNilLit:
  943. regs[ra].intVal = -imm
  944. else:
  945. regs[ra].intVal = regs[rb].node.strVal.cstring.len - imm
  946. of opcIncl:
  947. decodeB(rkNode)
  948. let b = regs[rb].regToNode
  949. if not inSet(regs[ra].node, b):
  950. regs[ra].node.add copyTree(b)
  951. of opcInclRange:
  952. decodeBC(rkNode)
  953. var r = newNode(nkRange)
  954. r.add regs[rb].regToNode
  955. r.add regs[rc].regToNode
  956. regs[ra].node.add r.copyTree
  957. of opcExcl:
  958. decodeB(rkNode)
  959. var b = newNodeIT(nkCurly, regs[ra].node.info, regs[ra].node.typ)
  960. b.add regs[rb].regToNode
  961. var r = diffSets(c.config, regs[ra].node, b)
  962. discardSons(regs[ra].node)
  963. for i in 0..<r.len: regs[ra].node.add r[i]
  964. of opcCard:
  965. decodeB(rkInt)
  966. regs[ra].intVal = nimsets.cardSet(c.config, regs[rb].node)
  967. of opcMulInt:
  968. decodeBC(rkInt)
  969. let
  970. bVal = regs[rb].intVal
  971. cVal = regs[rc].intVal
  972. product = bVal *% cVal
  973. floatProd = toBiggestFloat(bVal) * toBiggestFloat(cVal)
  974. resAsFloat = toBiggestFloat(product)
  975. if resAsFloat == floatProd:
  976. regs[ra].intVal = product
  977. elif 32.0 * abs(resAsFloat - floatProd) <= abs(floatProd):
  978. regs[ra].intVal = product
  979. else:
  980. stackTrace(c, tos, pc, errOverOrUnderflow)
  981. of opcDivInt:
  982. decodeBC(rkInt)
  983. if regs[rc].intVal == 0: stackTrace(c, tos, pc, errConstantDivisionByZero)
  984. else: regs[ra].intVal = regs[rb].intVal div regs[rc].intVal
  985. of opcModInt:
  986. decodeBC(rkInt)
  987. if regs[rc].intVal == 0: stackTrace(c, tos, pc, errConstantDivisionByZero)
  988. else: regs[ra].intVal = regs[rb].intVal mod regs[rc].intVal
  989. of opcAddFloat:
  990. decodeBC(rkFloat)
  991. regs[ra].floatVal = regs[rb].floatVal + regs[rc].floatVal
  992. of opcSubFloat:
  993. decodeBC(rkFloat)
  994. regs[ra].floatVal = regs[rb].floatVal - regs[rc].floatVal
  995. of opcMulFloat:
  996. decodeBC(rkFloat)
  997. regs[ra].floatVal = regs[rb].floatVal * regs[rc].floatVal
  998. of opcDivFloat:
  999. decodeBC(rkFloat)
  1000. regs[ra].floatVal = regs[rb].floatVal / regs[rc].floatVal
  1001. of opcShrInt:
  1002. decodeBC(rkInt)
  1003. let b = cast[uint64](regs[rb].intVal)
  1004. let c = cast[uint64](regs[rc].intVal)
  1005. let a = cast[int64](b shr c)
  1006. regs[ra].intVal = a
  1007. of opcShlInt:
  1008. decodeBC(rkInt)
  1009. regs[ra].intVal = regs[rb].intVal shl regs[rc].intVal
  1010. of opcAshrInt:
  1011. decodeBC(rkInt)
  1012. regs[ra].intVal = ashr(regs[rb].intVal, regs[rc].intVal)
  1013. of opcBitandInt:
  1014. decodeBC(rkInt)
  1015. regs[ra].intVal = regs[rb].intVal and regs[rc].intVal
  1016. of opcBitorInt:
  1017. decodeBC(rkInt)
  1018. regs[ra].intVal = regs[rb].intVal or regs[rc].intVal
  1019. of opcBitxorInt:
  1020. decodeBC(rkInt)
  1021. regs[ra].intVal = regs[rb].intVal xor regs[rc].intVal
  1022. of opcAddu:
  1023. decodeBC(rkInt)
  1024. regs[ra].intVal = regs[rb].intVal +% regs[rc].intVal
  1025. of opcSubu:
  1026. decodeBC(rkInt)
  1027. regs[ra].intVal = regs[rb].intVal -% regs[rc].intVal
  1028. of opcMulu:
  1029. decodeBC(rkInt)
  1030. regs[ra].intVal = regs[rb].intVal *% regs[rc].intVal
  1031. of opcDivu:
  1032. decodeBC(rkInt)
  1033. regs[ra].intVal = regs[rb].intVal /% regs[rc].intVal
  1034. of opcModu:
  1035. decodeBC(rkInt)
  1036. regs[ra].intVal = regs[rb].intVal %% regs[rc].intVal
  1037. of opcEqInt:
  1038. decodeBC(rkInt)
  1039. regs[ra].intVal = ord(regs[rb].intVal == regs[rc].intVal)
  1040. of opcLeInt:
  1041. decodeBC(rkInt)
  1042. regs[ra].intVal = ord(regs[rb].intVal <= regs[rc].intVal)
  1043. of opcLtInt:
  1044. decodeBC(rkInt)
  1045. regs[ra].intVal = ord(regs[rb].intVal < regs[rc].intVal)
  1046. of opcEqFloat:
  1047. decodeBC(rkInt)
  1048. regs[ra].intVal = ord(regs[rb].floatVal == regs[rc].floatVal)
  1049. of opcLeFloat:
  1050. decodeBC(rkInt)
  1051. regs[ra].intVal = ord(regs[rb].floatVal <= regs[rc].floatVal)
  1052. of opcLtFloat:
  1053. decodeBC(rkInt)
  1054. regs[ra].intVal = ord(regs[rb].floatVal < regs[rc].floatVal)
  1055. of opcLeu:
  1056. decodeBC(rkInt)
  1057. regs[ra].intVal = ord(regs[rb].intVal <=% regs[rc].intVal)
  1058. of opcLtu:
  1059. decodeBC(rkInt)
  1060. regs[ra].intVal = ord(regs[rb].intVal <% regs[rc].intVal)
  1061. of opcEqRef:
  1062. var ret = false
  1063. decodeBC(rkInt)
  1064. template getTyp(n): untyped =
  1065. n.typ.skipTypes(abstractInst)
  1066. template skipRegisterAddr(n: TFullReg): TFullReg =
  1067. var tmp = n
  1068. while tmp.kind == rkRegisterAddr:
  1069. tmp = tmp.regAddr[]
  1070. tmp
  1071. proc ptrEquality(n1: ptr PNode, n2: PNode): bool =
  1072. ## true if n2.intVal represents a ptr equal to n1
  1073. let p1 = cast[int](n1)
  1074. case n2.kind
  1075. of nkNilLit: return p1 == 0
  1076. of nkIntLit: # TODO: nkPtrLit
  1077. # for example, n1.kind == nkFloatLit (ptr float)
  1078. # the problem is that n1.typ == nil so we can't compare n1.typ and n2.typ
  1079. # this is the best we can do (pending making sure we assign a valid n1.typ to nodeAddr's)
  1080. let t2 = n2.getTyp
  1081. return t2.kind in PtrLikeKinds and n2.intVal == p1
  1082. else: return false
  1083. let rbReg = skipRegisterAddr(regs[rb])
  1084. let rcReg = skipRegisterAddr(regs[rc])
  1085. if rbReg.kind == rkNodeAddr:
  1086. if rcReg.kind == rkNodeAddr:
  1087. ret = rbReg.nodeAddr == rcReg.nodeAddr
  1088. else:
  1089. ret = ptrEquality(rbReg.nodeAddr, rcReg.node)
  1090. elif rcReg.kind == rkNodeAddr:
  1091. ret = ptrEquality(rcReg.nodeAddr, rbReg.node)
  1092. else:
  1093. let nb = rbReg.node
  1094. let nc = rcReg.node
  1095. if nb.kind != nc.kind: discard
  1096. elif (nb == nc) or (nb.kind == nkNilLit): ret = true # intentional
  1097. elif nb.kind in {nkSym, nkTupleConstr, nkClosure} and nb.typ != nil and nb.typ.kind == tyProc and sameConstant(nb, nc):
  1098. ret = true
  1099. # this also takes care of procvar's, represented as nkTupleConstr, e.g. (nil, nil)
  1100. elif nb.kind == nkIntLit and nc.kind == nkIntLit and nb.intVal == nc.intVal: # TODO: nkPtrLit
  1101. let tb = nb.getTyp
  1102. let tc = nc.getTyp
  1103. ret = tb.kind in PtrLikeKinds and tc.kind == tb.kind
  1104. regs[ra].intVal = ord(ret)
  1105. of opcEqNimNode:
  1106. decodeBC(rkInt)
  1107. regs[ra].intVal =
  1108. ord(exprStructuralEquivalent(regs[rb].node, regs[rc].node,
  1109. strictSymEquality=true))
  1110. of opcSameNodeType:
  1111. decodeBC(rkInt)
  1112. regs[ra].intVal = ord(regs[rb].node.typ.sameTypeOrNil(regs[rc].node.typ, {ExactTypeDescValues, ExactGenericParams}))
  1113. # The types should exactly match which is why we pass `{ExactTypeDescValues..ExactGcSafety}`.
  1114. of opcXor:
  1115. decodeBC(rkInt)
  1116. regs[ra].intVal = ord(regs[rb].intVal != regs[rc].intVal)
  1117. of opcNot:
  1118. decodeB(rkInt)
  1119. assert regs[rb].kind == rkInt
  1120. regs[ra].intVal = 1 - regs[rb].intVal
  1121. of opcUnaryMinusInt:
  1122. decodeB(rkInt)
  1123. assert regs[rb].kind == rkInt
  1124. let val = regs[rb].intVal
  1125. if val != int64.low:
  1126. regs[ra].intVal = -val
  1127. else:
  1128. stackTrace(c, tos, pc, errOverOrUnderflow)
  1129. of opcUnaryMinusFloat:
  1130. decodeB(rkFloat)
  1131. assert regs[rb].kind == rkFloat
  1132. regs[ra].floatVal = -regs[rb].floatVal
  1133. of opcBitnotInt:
  1134. decodeB(rkInt)
  1135. assert regs[rb].kind == rkInt
  1136. regs[ra].intVal = not regs[rb].intVal
  1137. of opcEqStr:
  1138. decodeBC(rkInt)
  1139. regs[ra].intVal = ord(regs[rb].node.strVal == regs[rc].node.strVal)
  1140. of opcEqCString:
  1141. decodeBC(rkInt)
  1142. let bNil = regs[rb].node.kind == nkNilLit
  1143. let cNil = regs[rc].node.kind == nkNilLit
  1144. regs[ra].intVal = ord((bNil and cNil) or
  1145. (not bNil and not cNil and regs[rb].node.strVal == regs[rc].node.strVal))
  1146. of opcLeStr:
  1147. decodeBC(rkInt)
  1148. regs[ra].intVal = ord(regs[rb].node.strVal <= regs[rc].node.strVal)
  1149. of opcLtStr:
  1150. decodeBC(rkInt)
  1151. regs[ra].intVal = ord(regs[rb].node.strVal < regs[rc].node.strVal)
  1152. of opcLeSet:
  1153. decodeBC(rkInt)
  1154. regs[ra].intVal = ord(containsSets(c.config, regs[rb].node, regs[rc].node))
  1155. of opcEqSet:
  1156. decodeBC(rkInt)
  1157. regs[ra].intVal = ord(equalSets(c.config, regs[rb].node, regs[rc].node))
  1158. of opcLtSet:
  1159. decodeBC(rkInt)
  1160. let a = regs[rb].node
  1161. let b = regs[rc].node
  1162. regs[ra].intVal = ord(containsSets(c.config, a, b) and not equalSets(c.config, a, b))
  1163. of opcMulSet:
  1164. decodeBC(rkNode)
  1165. createSet(regs[ra])
  1166. move(regs[ra].node.sons,
  1167. nimsets.intersectSets(c.config, regs[rb].node, regs[rc].node).sons)
  1168. of opcPlusSet:
  1169. decodeBC(rkNode)
  1170. createSet(regs[ra])
  1171. move(regs[ra].node.sons,
  1172. nimsets.unionSets(c.config, regs[rb].node, regs[rc].node).sons)
  1173. of opcMinusSet:
  1174. decodeBC(rkNode)
  1175. createSet(regs[ra])
  1176. move(regs[ra].node.sons,
  1177. nimsets.diffSets(c.config, regs[rb].node, regs[rc].node).sons)
  1178. of opcConcatStr:
  1179. decodeBC(rkNode)
  1180. createStr regs[ra]
  1181. regs[ra].node.strVal = getstr(regs[rb])
  1182. for i in rb+1..rb+rc-1:
  1183. regs[ra].node.strVal.add getstr(regs[i])
  1184. of opcAddStrCh:
  1185. decodeB(rkNode)
  1186. regs[ra].node.strVal.add(regs[rb].intVal.chr)
  1187. of opcAddStrStr:
  1188. decodeB(rkNode)
  1189. regs[ra].node.strVal.add(regs[rb].node.strVal)
  1190. of opcAddSeqElem:
  1191. decodeB(rkNode)
  1192. if regs[ra].node.kind == nkBracket:
  1193. regs[ra].node.add(copyValue(regs[rb].regToNode))
  1194. else:
  1195. stackTrace(c, tos, pc, errNilAccess)
  1196. of opcGetImpl:
  1197. decodeB(rkNode)
  1198. var a = regs[rb].node
  1199. if a.kind == nkVarTy: a = a[0]
  1200. if a.kind == nkSym:
  1201. regs[ra].node = if a.sym.ast.isNil: newNode(nkNilLit)
  1202. else: copyTree(a.sym.ast)
  1203. regs[ra].node.flags.incl nfIsRef
  1204. else:
  1205. stackTrace(c, tos, pc, "node is not a symbol")
  1206. of opcGetImplTransf:
  1207. decodeB(rkNode)
  1208. let a = regs[rb].node
  1209. if a.kind == nkSym:
  1210. regs[ra].node =
  1211. if a.sym.ast.isNil:
  1212. newNode(nkNilLit)
  1213. else:
  1214. let ast = a.sym.ast.shallowCopy
  1215. for i in 0..<a.sym.ast.len:
  1216. ast[i] = a.sym.ast[i]
  1217. ast[bodyPos] = transformBody(c.graph, c.idgen, a.sym, useCache, force=true)
  1218. ast.copyTree()
  1219. of opcSymOwner:
  1220. decodeB(rkNode)
  1221. let a = regs[rb].node
  1222. if a.kind == nkSym:
  1223. regs[ra].node = if a.sym.owner.isNil: newNode(nkNilLit)
  1224. else: newSymNode(a.sym.skipGenericOwner)
  1225. regs[ra].node.flags.incl nfIsRef
  1226. else:
  1227. stackTrace(c, tos, pc, "node is not a symbol")
  1228. of opcSymIsInstantiationOf:
  1229. decodeBC(rkInt)
  1230. let a = regs[rb].node
  1231. let b = regs[rc].node
  1232. if a.kind == nkSym and a.sym.kind in skProcKinds and
  1233. b.kind == nkSym and b.sym.kind in skProcKinds:
  1234. regs[ra].intVal =
  1235. if sfFromGeneric in a.sym.flags and a.sym.instantiatedFrom == b.sym: 1
  1236. else: 0
  1237. else:
  1238. stackTrace(c, tos, pc, "node is not a proc symbol")
  1239. of opcEcho:
  1240. let rb = instr.regB
  1241. template fn(s) = msgWriteln(c.config, s, {msgStdout, msgNoUnitSep})
  1242. if rb == 1: fn(regs[ra].node.strVal)
  1243. else:
  1244. var outp = ""
  1245. for i in ra..ra+rb-1:
  1246. #if regs[i].kind != rkNode: debug regs[i]
  1247. outp.add(regs[i].node.strVal)
  1248. fn(outp)
  1249. of opcContainsSet:
  1250. decodeBC(rkInt)
  1251. regs[ra].intVal = ord(inSet(regs[rb].node, regs[rc].regToNode))
  1252. of opcParseFloat:
  1253. decodeBC(rkInt)
  1254. var rcAddr = addr(regs[rc])
  1255. if rcAddr.kind == rkRegisterAddr: rcAddr = rcAddr.regAddr
  1256. elif regs[rc].kind != rkFloat:
  1257. regs[rc] = TFullReg(kind: rkFloat)
  1258. let coll = regs[rb].node
  1259. case coll.kind
  1260. of nkTupleConstr:
  1261. let
  1262. data = coll[0]
  1263. left = coll[1].intVal
  1264. right = coll[2].intVal
  1265. case data.kind
  1266. of nkStrKinds:
  1267. regs[ra].intVal = parseBiggestFloat(data.strVal.toOpenArray(int left, int right), rcAddr.floatVal)
  1268. of nkBracket:
  1269. var s = newStringOfCap(right - left + 1)
  1270. for i in left..right:
  1271. s.add char data[int i].intVal
  1272. regs[ra].intVal = parseBiggestFloat(s, rcAddr.floatVal)
  1273. else:
  1274. internalError(c.config, c.debug[pc], "opcParseFloat: Incorrectly created openarray")
  1275. else:
  1276. regs[ra].intVal = parseBiggestFloat(regs[ra].node.strVal, rcAddr.floatVal)
  1277. of opcRangeChck:
  1278. let rb = instr.regB
  1279. let rc = instr.regC
  1280. if not (leValueConv(regs[rb].regToNode, regs[ra].regToNode) and
  1281. leValueConv(regs[ra].regToNode, regs[rc].regToNode)):
  1282. stackTrace(c, tos, pc,
  1283. errIllegalConvFromXtoY % [
  1284. $regs[ra].regToNode, "[" & $regs[rb].regToNode & ".." & $regs[rc].regToNode & "]"])
  1285. of opcIndCall, opcIndCallAsgn:
  1286. # dest = call regStart, n; where regStart = fn, arg1, ...
  1287. let rb = instr.regB
  1288. let rc = instr.regC
  1289. let bb = regs[rb].node
  1290. let isClosure = bb.kind == nkTupleConstr
  1291. let prc = if not isClosure: bb.sym else: bb[0].sym
  1292. if prc.offset < -1:
  1293. # it's a callback:
  1294. c.callbacks[-prc.offset-2](
  1295. VmArgs(ra: ra, rb: rb, rc: rc, slots: cast[ptr UncheckedArray[TFullReg]](addr regs[0]),
  1296. currentException: c.currentExceptionA,
  1297. currentLineInfo: c.debug[pc])
  1298. )
  1299. elif importcCond(c, prc):
  1300. if compiletimeFFI notin c.config.features:
  1301. globalError(c.config, c.debug[pc], "VM not allowed to do FFI, see `compiletimeFFI`")
  1302. # we pass 'tos.slots' instead of 'regs' so that the compiler can keep
  1303. # 'regs' in a register:
  1304. when hasFFI:
  1305. if prc.position - 1 < 0:
  1306. globalError(c.config, c.debug[pc],
  1307. "VM call invalid: prc.position: " & $prc.position)
  1308. let prcValue = c.globals[prc.position-1]
  1309. if prcValue.kind == nkEmpty:
  1310. globalError(c.config, c.debug[pc], "cannot run " & prc.name.s)
  1311. var slots2: TNodeSeq = newSeq[PNode](tos.slots.len)
  1312. for i in 0..<tos.slots.len:
  1313. slots2[i] = regToNode(tos.slots[i])
  1314. let newValue = callForeignFunction(c.config, prcValue, prc.typ, slots2,
  1315. rb+1, rc-1, c.debug[pc])
  1316. if newValue.kind != nkEmpty:
  1317. assert instr.opcode == opcIndCallAsgn
  1318. putIntoReg(regs[ra], newValue)
  1319. else:
  1320. globalError(c.config, c.debug[pc], "VM not built with FFI support")
  1321. elif prc.kind != skTemplate:
  1322. let newPc = compile(c, prc)
  1323. # tricky: a recursion is also a jump back, so we use the same
  1324. # logic as for loops:
  1325. if newPc < pc: handleJmpBack()
  1326. #echo "new pc ", newPc, " calling: ", prc.name.s
  1327. var newFrame = PStackFrame(prc: prc, comesFrom: pc, next: tos)
  1328. newSeq(newFrame.slots, prc.offset+ord(isClosure))
  1329. if not isEmptyType(prc.typ[0]):
  1330. putIntoReg(newFrame.slots[0], getNullValue(prc.typ[0], prc.info, c.config))
  1331. for i in 1..rc-1:
  1332. newFrame.slots[i] = regs[rb+i]
  1333. if isClosure:
  1334. newFrame.slots[rc] = TFullReg(kind: rkNode, node: regs[rb].node[1])
  1335. tos = newFrame
  1336. updateRegsAlias
  1337. # -1 for the following 'inc pc'
  1338. pc = newPc-1
  1339. else:
  1340. # for 'getAst' support we need to support template expansion here:
  1341. let genSymOwner = if tos.next != nil and tos.next.prc != nil:
  1342. tos.next.prc
  1343. else:
  1344. c.module
  1345. var macroCall = newNodeI(nkCall, c.debug[pc])
  1346. macroCall.add(newSymNode(prc))
  1347. for i in 1..rc-1:
  1348. let node = regs[rb+i].regToNode
  1349. node.info = c.debug[pc]
  1350. if prc.typ[i].kind notin {tyTyped, tyUntyped}:
  1351. node.annotateType(prc.typ[i], c.config)
  1352. macroCall.add(node)
  1353. var a = evalTemplate(macroCall, prc, genSymOwner, c.config, c.cache, c.templInstCounter, c.idgen)
  1354. if a.kind == nkStmtList and a.len == 1: a = a[0]
  1355. a.recSetFlagIsRef
  1356. ensureKind(rkNode)
  1357. regs[ra].node = a
  1358. of opcTJmp:
  1359. # jump Bx if A != 0
  1360. let rbx = instr.regBx - wordExcess - 1 # -1 for the following 'inc pc'
  1361. if regs[ra].intVal != 0:
  1362. inc pc, rbx
  1363. of opcFJmp:
  1364. # jump Bx if A == 0
  1365. let rbx = instr.regBx - wordExcess - 1 # -1 for the following 'inc pc'
  1366. if regs[ra].intVal == 0:
  1367. inc pc, rbx
  1368. of opcJmp:
  1369. # jump Bx
  1370. let rbx = instr.regBx - wordExcess - 1 # -1 for the following 'inc pc'
  1371. inc pc, rbx
  1372. of opcJmpBack:
  1373. let rbx = instr.regBx - wordExcess - 1 # -1 for the following 'inc pc'
  1374. inc pc, rbx
  1375. handleJmpBack()
  1376. of opcBranch:
  1377. # we know the next instruction is a 'fjmp':
  1378. let branch = c.constants[instr.regBx-wordExcess]
  1379. var cond = false
  1380. for j in 0..<branch.len - 1:
  1381. if overlap(regs[ra].regToNode, branch[j]):
  1382. cond = true
  1383. break
  1384. assert c.code[pc+1].opcode == opcFJmp
  1385. inc pc
  1386. # we skip this instruction so that the final 'inc(pc)' skips
  1387. # the following jump
  1388. if not cond:
  1389. let instr2 = c.code[pc]
  1390. let rbx = instr2.regBx - wordExcess - 1 # -1 for the following 'inc pc'
  1391. inc pc, rbx
  1392. of opcTry:
  1393. let rbx = instr.regBx - wordExcess
  1394. tos.pushSafePoint(pc + rbx)
  1395. assert c.code[pc+rbx].opcode in {opcExcept, opcFinally}
  1396. of opcExcept:
  1397. # This opcode is never executed, it only holds information for the
  1398. # exception handling routines.
  1399. raiseAssert "unreachable"
  1400. of opcFinally:
  1401. # Pop the last safepoint introduced by a opcTry. This opcode is only
  1402. # executed _iff_ no exception was raised in the body of the `try`
  1403. # statement hence the need to pop the safepoint here.
  1404. doAssert(savedPC < 0)
  1405. tos.popSafePoint()
  1406. of opcFinallyEnd:
  1407. # The control flow may not resume at the next instruction since we may be
  1408. # raising an exception or performing a cleanup.
  1409. if savedPC >= 0:
  1410. pc = savedPC - 1
  1411. savedPC = -1
  1412. if tos != savedFrame:
  1413. tos = savedFrame
  1414. updateRegsAlias
  1415. of opcRaise:
  1416. let raised =
  1417. # Empty `raise` statement - reraise current exception
  1418. if regs[ra].kind == rkNone:
  1419. c.currentExceptionA
  1420. else:
  1421. regs[ra].node
  1422. c.currentExceptionA = raised
  1423. # Set the `name` field of the exception
  1424. var exceptionNameNode = newStrNode(nkStrLit, c.currentExceptionA.typ.sym.name.s)
  1425. if c.currentExceptionA[2].kind == nkExprColonExpr:
  1426. exceptionNameNode.typ = c.currentExceptionA[2][1].typ
  1427. c.currentExceptionA[2][1] = exceptionNameNode
  1428. else:
  1429. exceptionNameNode.typ = c.currentExceptionA[2].typ
  1430. c.currentExceptionA[2] = exceptionNameNode
  1431. c.exceptionInstr = pc
  1432. var frame = tos
  1433. var jumpTo = findExceptionHandler(c, frame, raised)
  1434. while jumpTo.why == ExceptionGotoUnhandled and not frame.next.isNil:
  1435. frame = frame.next
  1436. jumpTo = findExceptionHandler(c, frame, raised)
  1437. case jumpTo.why
  1438. of ExceptionGotoHandler:
  1439. # Jump to the handler, do nothing when the `finally` block ends.
  1440. savedPC = -1
  1441. pc = jumpTo.where - 1
  1442. if tos != frame:
  1443. tos = frame
  1444. updateRegsAlias
  1445. of ExceptionGotoFinally:
  1446. # Jump to the `finally` block first then re-jump here to continue the
  1447. # traversal of the exception chain
  1448. savedPC = pc
  1449. savedFrame = tos
  1450. pc = jumpTo.where - 1
  1451. if tos != frame:
  1452. tos = frame
  1453. updateRegsAlias
  1454. of ExceptionGotoUnhandled:
  1455. # Nobody handled this exception, error out.
  1456. bailOut(c, tos)
  1457. of opcNew:
  1458. ensureKind(rkNode)
  1459. let typ = c.types[instr.regBx - wordExcess]
  1460. regs[ra].node = getNullValue(typ, c.debug[pc], c.config)
  1461. regs[ra].node.flags.incl nfIsRef
  1462. of opcNewSeq:
  1463. let typ = c.types[instr.regBx - wordExcess]
  1464. inc pc
  1465. ensureKind(rkNode)
  1466. let instr2 = c.code[pc]
  1467. let count = regs[instr2.regA].intVal.int
  1468. regs[ra].node = newNodeI(nkBracket, c.debug[pc])
  1469. regs[ra].node.typ = typ
  1470. newSeq(regs[ra].node.sons, count)
  1471. for i in 0..<count:
  1472. regs[ra].node[i] = getNullValue(typ[0], c.debug[pc], c.config)
  1473. of opcNewStr:
  1474. decodeB(rkNode)
  1475. regs[ra].node = newNodeI(nkStrLit, c.debug[pc])
  1476. regs[ra].node.strVal = newString(regs[rb].intVal.int)
  1477. of opcLdImmInt:
  1478. # dest = immediate value
  1479. decodeBx(rkInt)
  1480. regs[ra].intVal = rbx
  1481. of opcLdNull:
  1482. ensureKind(rkNode)
  1483. let typ = c.types[instr.regBx - wordExcess]
  1484. regs[ra].node = getNullValue(typ, c.debug[pc], c.config)
  1485. # opcLdNull really is the gist of the VM's problems: should it load
  1486. # a fresh null to regs[ra].node or to regs[ra].node[]? This really
  1487. # depends on whether regs[ra] represents the variable itself or whether
  1488. # it holds the indirection! Due to the way registers are re-used we cannot
  1489. # say for sure here! --> The codegen has to deal with it
  1490. # via 'genAsgnPatch'.
  1491. of opcLdNullReg:
  1492. let typ = c.types[instr.regBx - wordExcess]
  1493. if typ.skipTypes(abstractInst+{tyRange}-{tyTypeDesc}).kind in {
  1494. tyFloat..tyFloat128}:
  1495. ensureKind(rkFloat)
  1496. regs[ra].floatVal = 0.0
  1497. else:
  1498. ensureKind(rkInt)
  1499. regs[ra].intVal = 0
  1500. of opcLdConst:
  1501. let rb = instr.regBx - wordExcess
  1502. let cnst = c.constants[rb]
  1503. if fitsRegister(cnst.typ):
  1504. reset(regs[ra])
  1505. putIntoReg(regs[ra], cnst)
  1506. else:
  1507. ensureKind(rkNode)
  1508. regs[ra].node = cnst
  1509. of opcAsgnConst:
  1510. let rb = instr.regBx - wordExcess
  1511. let cnst = c.constants[rb]
  1512. if fitsRegister(cnst.typ):
  1513. putIntoReg(regs[ra], cnst)
  1514. else:
  1515. ensureKind(rkNode)
  1516. regs[ra].node = cnst.copyTree
  1517. of opcLdGlobal:
  1518. let rb = instr.regBx - wordExcess - 1
  1519. ensureKind(rkNode)
  1520. regs[ra].node = c.globals[rb]
  1521. of opcLdGlobalDerefFFI:
  1522. let rb = instr.regBx - wordExcess - 1
  1523. let node = c.globals[rb]
  1524. let typ = node.typ
  1525. doAssert node.kind == nkIntLit, $(node.kind)
  1526. if typ.kind == tyPtr:
  1527. ensureKind(rkNode)
  1528. # use nkPtrLit once this is added
  1529. let node2 = newNodeIT(nkIntLit, c.debug[pc], typ)
  1530. node2.intVal = cast[ptr int](node.intVal)[]
  1531. node2.flags.incl nfIsPtr
  1532. regs[ra].node = node2
  1533. elif not derefPtrToReg(node.intVal, typ, regs[ra], isAssign = false):
  1534. stackTrace(c, tos, pc, "opcLdDeref unsupported type: " & $(typeToString(typ), typ[0].kind))
  1535. of opcLdGlobalAddrDerefFFI:
  1536. let rb = instr.regBx - wordExcess - 1
  1537. let node = c.globals[rb]
  1538. let typ = node.typ
  1539. var node2 = newNodeIT(nkIntLit, node.info, typ)
  1540. node2.intVal = node.intVal
  1541. node2.flags.incl nfIsPtr
  1542. ensureKind(rkNode)
  1543. regs[ra].node = node2
  1544. of opcLdGlobalAddr:
  1545. let rb = instr.regBx - wordExcess - 1
  1546. ensureKind(rkNodeAddr)
  1547. regs[ra].nodeAddr = addr(c.globals[rb])
  1548. of opcRepr:
  1549. decodeB(rkNode)
  1550. createStr regs[ra]
  1551. regs[ra].node.strVal = renderTree(regs[rb].regToNode, {renderNoComments, renderDocComments, renderNonExportedFields})
  1552. of opcQuit:
  1553. if c.mode in {emRepl, emStaticExpr, emStaticStmt}:
  1554. message(c.config, c.debug[pc], hintQuitCalled)
  1555. msgQuit(int8(toInt(getOrdValue(regs[ra].regToNode, onError = toInt128(1)))))
  1556. else:
  1557. return TFullReg(kind: rkNone)
  1558. of opcInvalidField:
  1559. let msg = regs[ra].node.strVal
  1560. let disc = regs[instr.regB].regToNode
  1561. let msg2 = formatFieldDefect(msg, $disc)
  1562. stackTrace(c, tos, pc, msg2)
  1563. of opcSetLenStr:
  1564. decodeB(rkNode)
  1565. #createStrKeepNode regs[ra]
  1566. regs[ra].node.strVal.setLen(regs[rb].intVal.int)
  1567. of opcOf:
  1568. decodeBC(rkInt)
  1569. let typ = c.types[regs[rc].intVal.int]
  1570. regs[ra].intVal = ord(inheritanceDiff(regs[rb].node.typ, typ) <= 0)
  1571. of opcIs:
  1572. decodeBC(rkInt)
  1573. let t1 = regs[rb].node.typ.skipTypes({tyTypeDesc})
  1574. let t2 = c.types[regs[rc].intVal.int]
  1575. # XXX: This should use the standard isOpImpl
  1576. let match = if t2.kind == tyUserTypeClass: true
  1577. else: sameType(t1, t2)
  1578. regs[ra].intVal = ord(match)
  1579. of opcSetLenSeq:
  1580. decodeB(rkNode)
  1581. let newLen = regs[rb].intVal.int
  1582. if regs[ra].node.isNil: stackTrace(c, tos, pc, errNilAccess)
  1583. else: c.setLenSeq(regs[ra].node, newLen, c.debug[pc])
  1584. of opcNarrowS:
  1585. decodeB(rkInt)
  1586. let min = -(1.BiggestInt shl (rb-1))
  1587. let max = (1.BiggestInt shl (rb-1))-1
  1588. if regs[ra].intVal < min or regs[ra].intVal > max:
  1589. stackTrace(c, tos, pc, "unhandled exception: value out of range")
  1590. of opcNarrowU:
  1591. decodeB(rkInt)
  1592. regs[ra].intVal = regs[ra].intVal and ((1'i64 shl rb)-1)
  1593. of opcSignExtend:
  1594. # like opcNarrowS, but no out of range possible
  1595. decodeB(rkInt)
  1596. let imm = 64 - rb
  1597. regs[ra].intVal = ashr(regs[ra].intVal shl imm, imm)
  1598. of opcIsNil:
  1599. decodeB(rkInt)
  1600. let node = regs[rb].node
  1601. regs[ra].intVal = ord(
  1602. # Note that `nfIsRef` + `nkNilLit` represents an allocated
  1603. # reference with the value `nil`, so `isNil` should be false!
  1604. (node.kind == nkNilLit and nfIsRef notin node.flags) or
  1605. (not node.typ.isNil and node.typ.kind == tyProc and
  1606. node.typ.callConv == ccClosure and node.safeLen > 0 and
  1607. node[0].kind == nkNilLit and node[1].kind == nkNilLit))
  1608. of opcNBindSym:
  1609. # cannot use this simple check
  1610. # if dynamicBindSym notin c.config.features:
  1611. # bindSym with static input
  1612. decodeBx(rkNode)
  1613. regs[ra].node = copyTree(c.constants[rbx])
  1614. regs[ra].node.flags.incl nfIsRef
  1615. of opcNDynBindSym:
  1616. # experimental bindSym
  1617. let
  1618. rb = instr.regB
  1619. rc = instr.regC
  1620. idx = int(regs[rb+rc-1].intVal)
  1621. callback = c.callbacks[idx]
  1622. args = VmArgs(ra: ra, rb: rb, rc: rc, slots: cast[ptr UncheckedArray[TFullReg]](addr regs[0]),
  1623. currentException: c.currentExceptionA,
  1624. currentLineInfo: c.debug[pc])
  1625. callback(args)
  1626. regs[ra].node.flags.incl nfIsRef
  1627. of opcNChild:
  1628. decodeBC(rkNode)
  1629. let idx = regs[rc].intVal.int
  1630. let src = regs[rb].node
  1631. if src.kind in {nkEmpty..nkNilLit}:
  1632. stackTrace(c, tos, pc, "cannot get child of node kind: n" & $src.kind)
  1633. elif idx >=% src.len:
  1634. stackTrace(c, tos, pc, formatErrorIndexBound(idx, src.len-1))
  1635. else:
  1636. regs[ra].node = src[idx]
  1637. of opcNSetChild:
  1638. decodeBC(rkNode)
  1639. let idx = regs[rb].intVal.int
  1640. var dest = regs[ra].node
  1641. if nfSem in dest.flags and allowSemcheckedAstModification notin c.config.legacyFeatures:
  1642. stackTrace(c, tos, pc, "typechecked nodes may not be modified")
  1643. elif dest.kind in {nkEmpty..nkNilLit}:
  1644. stackTrace(c, tos, pc, "cannot set child of node kind: n" & $dest.kind)
  1645. elif idx >=% dest.len:
  1646. stackTrace(c, tos, pc, formatErrorIndexBound(idx, dest.len-1))
  1647. else:
  1648. dest[idx] = regs[rc].node
  1649. of opcNAdd:
  1650. decodeBC(rkNode)
  1651. var u = regs[rb].node
  1652. if nfSem in u.flags and allowSemcheckedAstModification notin c.config.legacyFeatures:
  1653. stackTrace(c, tos, pc, "typechecked nodes may not be modified")
  1654. elif u.kind in {nkEmpty..nkNilLit}:
  1655. stackTrace(c, tos, pc, "cannot add to node kind: n" & $u.kind)
  1656. else:
  1657. u.add(regs[rc].node)
  1658. regs[ra].node = u
  1659. of opcNAddMultiple:
  1660. decodeBC(rkNode)
  1661. let x = regs[rc].node
  1662. var u = regs[rb].node
  1663. if nfSem in u.flags and allowSemcheckedAstModification notin c.config.legacyFeatures:
  1664. stackTrace(c, tos, pc, "typechecked nodes may not be modified")
  1665. elif u.kind in {nkEmpty..nkNilLit}:
  1666. stackTrace(c, tos, pc, "cannot add to node kind: n" & $u.kind)
  1667. else:
  1668. for i in 0..<x.len: u.add(x[i])
  1669. regs[ra].node = u
  1670. of opcNKind:
  1671. decodeB(rkInt)
  1672. regs[ra].intVal = ord(regs[rb].node.kind)
  1673. c.comesFromHeuristic = regs[rb].node.info
  1674. of opcNSymKind:
  1675. decodeB(rkInt)
  1676. let a = regs[rb].node
  1677. if a.kind == nkSym:
  1678. regs[ra].intVal = ord(a.sym.kind)
  1679. else:
  1680. stackTrace(c, tos, pc, "node is not a symbol")
  1681. c.comesFromHeuristic = regs[rb].node.info
  1682. of opcNIntVal:
  1683. decodeB(rkInt)
  1684. let a = regs[rb].node
  1685. if a.kind in {nkCharLit..nkUInt64Lit}:
  1686. regs[ra].intVal = a.intVal
  1687. elif a.kind == nkSym and a.sym.kind == skEnumField:
  1688. regs[ra].intVal = a.sym.position
  1689. else:
  1690. stackTrace(c, tos, pc, errFieldXNotFound & "intVal")
  1691. of opcNFloatVal:
  1692. decodeB(rkFloat)
  1693. let a = regs[rb].node
  1694. case a.kind
  1695. of nkFloatLit..nkFloat64Lit: regs[ra].floatVal = a.floatVal
  1696. else: stackTrace(c, tos, pc, errFieldXNotFound & "floatVal")
  1697. of opcNSymbol:
  1698. decodeB(rkNode)
  1699. let a = regs[rb].node
  1700. if a.kind == nkSym:
  1701. regs[ra].node = copyNode(a)
  1702. else:
  1703. stackTrace(c, tos, pc, errFieldXNotFound & "symbol")
  1704. of opcNIdent:
  1705. decodeB(rkNode)
  1706. let a = regs[rb].node
  1707. if a.kind == nkIdent:
  1708. regs[ra].node = copyNode(a)
  1709. else:
  1710. stackTrace(c, tos, pc, errFieldXNotFound & "ident")
  1711. of opcNodeId:
  1712. decodeB(rkInt)
  1713. when defined(useNodeIds):
  1714. regs[ra].intVal = regs[rb].node.id
  1715. else:
  1716. regs[ra].intVal = -1
  1717. of opcNGetType:
  1718. let rb = instr.regB
  1719. let rc = instr.regC
  1720. case rc
  1721. of 0:
  1722. # getType opcode:
  1723. ensureKind(rkNode)
  1724. if regs[rb].kind == rkNode and regs[rb].node.typ != nil:
  1725. regs[ra].node = opMapTypeToAst(c.cache, regs[rb].node.typ, c.debug[pc], c.idgen)
  1726. elif regs[rb].kind == rkNode and regs[rb].node.kind == nkSym and regs[rb].node.sym.typ != nil:
  1727. regs[ra].node = opMapTypeToAst(c.cache, regs[rb].node.sym.typ, c.debug[pc], c.idgen)
  1728. else:
  1729. stackTrace(c, tos, pc, "node has no type")
  1730. of 1:
  1731. # typeKind opcode:
  1732. ensureKind(rkInt)
  1733. if regs[rb].kind == rkNode and regs[rb].node.typ != nil:
  1734. regs[ra].intVal = ord(regs[rb].node.typ.kind)
  1735. elif regs[rb].kind == rkNode and regs[rb].node.kind == nkSym and regs[rb].node.sym.typ != nil:
  1736. regs[ra].intVal = ord(regs[rb].node.sym.typ.kind)
  1737. #else:
  1738. # stackTrace(c, tos, pc, "node has no type")
  1739. of 2:
  1740. # getTypeInst opcode:
  1741. ensureKind(rkNode)
  1742. if regs[rb].kind == rkNode and regs[rb].node.typ != nil:
  1743. regs[ra].node = opMapTypeInstToAst(c.cache, regs[rb].node.typ, c.debug[pc], c.idgen)
  1744. elif regs[rb].kind == rkNode and regs[rb].node.kind == nkSym and regs[rb].node.sym.typ != nil:
  1745. regs[ra].node = opMapTypeInstToAst(c.cache, regs[rb].node.sym.typ, c.debug[pc], c.idgen)
  1746. else:
  1747. stackTrace(c, tos, pc, "node has no type")
  1748. else:
  1749. # getTypeImpl opcode:
  1750. ensureKind(rkNode)
  1751. if regs[rb].kind == rkNode and regs[rb].node.typ != nil:
  1752. regs[ra].node = opMapTypeImplToAst(c.cache, regs[rb].node.typ, c.debug[pc], c.idgen)
  1753. elif regs[rb].kind == rkNode and regs[rb].node.kind == nkSym and regs[rb].node.sym.typ != nil:
  1754. regs[ra].node = opMapTypeImplToAst(c.cache, regs[rb].node.sym.typ, c.debug[pc], c.idgen)
  1755. else:
  1756. stackTrace(c, tos, pc, "node has no type")
  1757. of opcNGetSize:
  1758. decodeBImm(rkInt)
  1759. let n = regs[rb].node
  1760. case imm
  1761. of 0: # size
  1762. if n.typ == nil:
  1763. stackTrace(c, tos, pc, "node has no type")
  1764. else:
  1765. regs[ra].intVal = getSize(c.config, n.typ)
  1766. of 1: # align
  1767. if n.typ == nil:
  1768. stackTrace(c, tos, pc, "node has no type")
  1769. else:
  1770. regs[ra].intVal = getAlign(c.config, n.typ)
  1771. else: # offset
  1772. if n.kind != nkSym:
  1773. stackTrace(c, tos, pc, "node is not a symbol")
  1774. elif n.sym.kind != skField:
  1775. stackTrace(c, tos, pc, "symbol is not a field (nskField)")
  1776. else:
  1777. regs[ra].intVal = n.sym.offset
  1778. of opcNStrVal:
  1779. decodeB(rkNode)
  1780. createStr regs[ra]
  1781. let a = regs[rb].node
  1782. case a.kind
  1783. of nkStrLit..nkTripleStrLit:
  1784. regs[ra].node.strVal = a.strVal
  1785. of nkCommentStmt:
  1786. regs[ra].node.strVal = a.comment
  1787. of nkIdent:
  1788. regs[ra].node.strVal = a.ident.s
  1789. of nkSym:
  1790. regs[ra].node.strVal = a.sym.name.s
  1791. else:
  1792. stackTrace(c, tos, pc, errFieldXNotFound & "strVal")
  1793. of opcNSigHash:
  1794. decodeB(rkNode)
  1795. createStr regs[ra]
  1796. if regs[rb].node.kind != nkSym:
  1797. stackTrace(c, tos, pc, "node is not a symbol")
  1798. else:
  1799. regs[ra].node.strVal = $sigHash(regs[rb].node.sym, c.config)
  1800. of opcSlurp:
  1801. decodeB(rkNode)
  1802. createStr regs[ra]
  1803. regs[ra].node.strVal = opSlurp(regs[rb].node.strVal, c.debug[pc],
  1804. c.module, c.config)
  1805. of opcGorge:
  1806. decodeBC(rkNode)
  1807. inc pc
  1808. let rd = c.code[pc].regA
  1809. createStr regs[ra]
  1810. if defined(nimsuggest) or c.config.cmd == cmdCheck:
  1811. discard "don't run staticExec for 'nim suggest'"
  1812. regs[ra].node.strVal = ""
  1813. else:
  1814. when defined(nimcore):
  1815. regs[ra].node.strVal = opGorge(regs[rb].node.strVal,
  1816. regs[rc].node.strVal, regs[rd].node.strVal,
  1817. c.debug[pc], c.config)[0]
  1818. else:
  1819. regs[ra].node.strVal = ""
  1820. globalError(c.config, c.debug[pc], "VM is not built with 'gorge' support")
  1821. of opcNError, opcNWarning, opcNHint:
  1822. decodeB(rkNode)
  1823. let a = regs[ra].node
  1824. let b = regs[rb].node
  1825. let info = if b.kind == nkNilLit: c.debug[pc] else: b.info
  1826. if instr.opcode == opcNError:
  1827. stackTrace(c, tos, pc, a.strVal, info)
  1828. elif instr.opcode == opcNWarning:
  1829. message(c.config, info, warnUser, a.strVal)
  1830. elif instr.opcode == opcNHint:
  1831. message(c.config, info, hintUser, a.strVal)
  1832. of opcParseExprToAst:
  1833. decodeBC(rkNode)
  1834. var error: string = ""
  1835. let ast = parseString(regs[rb].node.strVal, c.cache, c.config,
  1836. regs[rc].node.strVal, 0,
  1837. proc (conf: ConfigRef; info: TLineInfo; msg: TMsgKind; arg: string) =
  1838. if error.len == 0 and msg <= errMax:
  1839. error = formatMsg(conf, info, msg, arg))
  1840. if error.len > 0:
  1841. c.errorFlag = error
  1842. elif ast.len != 1:
  1843. c.errorFlag = formatMsg(c.config, c.debug[pc], errGenerated,
  1844. "expected expression, but got multiple statements")
  1845. else:
  1846. regs[ra].node = ast[0]
  1847. of opcParseStmtToAst:
  1848. decodeBC(rkNode)
  1849. var error: string = ""
  1850. let ast = parseString(regs[rb].node.strVal, c.cache, c.config,
  1851. regs[rc].node.strVal, 0,
  1852. proc (conf: ConfigRef; info: TLineInfo; msg: TMsgKind; arg: string) =
  1853. if error.len == 0 and msg <= errMax:
  1854. error = formatMsg(conf, info, msg, arg))
  1855. if error.len > 0:
  1856. c.errorFlag = error
  1857. else:
  1858. regs[ra].node = ast
  1859. of opcQueryErrorFlag:
  1860. createStr regs[ra]
  1861. regs[ra].node.strVal = c.errorFlag
  1862. c.errorFlag.setLen 0
  1863. of opcCallSite:
  1864. ensureKind(rkNode)
  1865. if c.callsite != nil: regs[ra].node = c.callsite
  1866. else: stackTrace(c, tos, pc, errFieldXNotFound & "callsite")
  1867. of opcNGetLineInfo:
  1868. decodeBImm(rkNode)
  1869. let n = regs[rb].node
  1870. case imm
  1871. of 0: # getFile
  1872. regs[ra].node = newStrNode(nkStrLit, toFullPath(c.config, n.info))
  1873. of 1: # getLine
  1874. regs[ra].node = newIntNode(nkIntLit, n.info.line.int)
  1875. of 2: # getColumn
  1876. regs[ra].node = newIntNode(nkIntLit, n.info.col.int)
  1877. else:
  1878. internalAssert c.config, false
  1879. regs[ra].node.info = n.info
  1880. regs[ra].node.typ = n.typ
  1881. of opcNCopyLineInfo:
  1882. decodeB(rkNode)
  1883. regs[ra].node.info = regs[rb].node.info
  1884. of opcNSetLineInfoLine:
  1885. decodeB(rkNode)
  1886. regs[ra].node.info.line = regs[rb].intVal.uint16
  1887. of opcNSetLineInfoColumn:
  1888. decodeB(rkNode)
  1889. regs[ra].node.info.col = regs[rb].intVal.int16
  1890. of opcNSetLineInfoFile:
  1891. decodeB(rkNode)
  1892. regs[ra].node.info.fileIndex =
  1893. fileInfoIdx(c.config, RelativeFile regs[rb].node.strVal)
  1894. of opcEqIdent:
  1895. decodeBC(rkInt)
  1896. # aliases for shorter and easier to understand code below
  1897. var aNode = regs[rb].node
  1898. var bNode = regs[rc].node
  1899. # Skipping both, `nkPostfix` and `nkAccQuoted` for both
  1900. # arguments. `nkPostfix` exists only to tag exported symbols
  1901. # and therefor it can be safely skipped. Nim has no postfix
  1902. # operator. `nkAccQuoted` is used to quote an identifier that
  1903. # wouldn't be allowed to use in an unquoted context.
  1904. if aNode.kind == nkPostfix:
  1905. aNode = aNode[1]
  1906. if aNode.kind == nkAccQuoted:
  1907. aNode = aNode[0]
  1908. if bNode.kind == nkPostfix:
  1909. bNode = bNode[1]
  1910. if bNode.kind == nkAccQuoted:
  1911. bNode = bNode[0]
  1912. # These vars are of type `cstring` to prevent unnecessary string copy.
  1913. var aStrVal: cstring = nil
  1914. var bStrVal: cstring = nil
  1915. # extract strVal from argument ``a``
  1916. case aNode.kind
  1917. of nkStrLit..nkTripleStrLit:
  1918. aStrVal = aNode.strVal.cstring
  1919. of nkIdent:
  1920. aStrVal = aNode.ident.s.cstring
  1921. of nkSym:
  1922. aStrVal = aNode.sym.name.s.cstring
  1923. of nkOpenSymChoice, nkClosedSymChoice:
  1924. aStrVal = aNode[0].sym.name.s.cstring
  1925. else:
  1926. discard
  1927. # extract strVal from argument ``b``
  1928. case bNode.kind
  1929. of nkStrLit..nkTripleStrLit:
  1930. bStrVal = bNode.strVal.cstring
  1931. of nkIdent:
  1932. bStrVal = bNode.ident.s.cstring
  1933. of nkSym:
  1934. bStrVal = bNode.sym.name.s.cstring
  1935. of nkOpenSymChoice, nkClosedSymChoice:
  1936. bStrVal = bNode[0].sym.name.s.cstring
  1937. else:
  1938. discard
  1939. regs[ra].intVal =
  1940. if aStrVal != nil and bStrVal != nil:
  1941. ord(idents.cmpIgnoreStyle(aStrVal, bStrVal, high(int)) == 0)
  1942. else:
  1943. 0
  1944. of opcStrToIdent:
  1945. decodeB(rkNode)
  1946. if regs[rb].node.kind notin {nkStrLit..nkTripleStrLit}:
  1947. stackTrace(c, tos, pc, errFieldXNotFound & "strVal")
  1948. else:
  1949. regs[ra].node = newNodeI(nkIdent, c.debug[pc])
  1950. regs[ra].node.ident = getIdent(c.cache, regs[rb].node.strVal)
  1951. regs[ra].node.flags.incl nfIsRef
  1952. of opcSetType:
  1953. let typ = c.types[instr.regBx - wordExcess]
  1954. if regs[ra].kind != rkNode:
  1955. let temp = regToNode(regs[ra])
  1956. ensureKind(rkNode)
  1957. regs[ra].node = temp
  1958. regs[ra].node.info = c.debug[pc]
  1959. regs[ra].node.typ = typ
  1960. of opcConv:
  1961. let rb = instr.regB
  1962. inc pc
  1963. let desttyp = c.types[c.code[pc].regBx - wordExcess]
  1964. inc pc
  1965. let srctyp = c.types[c.code[pc].regBx - wordExcess]
  1966. if opConv(c, regs[ra], regs[rb], desttyp, srctyp):
  1967. stackTrace(c, tos, pc,
  1968. errIllegalConvFromXtoY % [
  1969. typeToString(srctyp), typeToString(desttyp)])
  1970. of opcCast:
  1971. let rb = instr.regB
  1972. inc pc
  1973. let desttyp = c.types[c.code[pc].regBx - wordExcess]
  1974. inc pc
  1975. let srctyp = c.types[c.code[pc].regBx - wordExcess]
  1976. when hasFFI:
  1977. let dest = fficast(c.config, regs[rb].node, desttyp)
  1978. # todo: check whether this is correct
  1979. # asgnRef(regs[ra], dest)
  1980. putIntoReg(regs[ra], dest)
  1981. else:
  1982. globalError(c.config, c.debug[pc], "cannot evaluate cast")
  1983. of opcNSetIntVal:
  1984. decodeB(rkNode)
  1985. var dest = regs[ra].node
  1986. if dest.kind in {nkCharLit..nkUInt64Lit} and
  1987. regs[rb].kind in {rkInt}:
  1988. dest.intVal = regs[rb].intVal
  1989. elif dest.kind == nkSym and dest.sym.kind == skEnumField:
  1990. stackTrace(c, tos, pc, "`intVal` cannot be changed for an enum symbol.")
  1991. else:
  1992. stackTrace(c, tos, pc, errFieldXNotFound & "intVal")
  1993. of opcNSetFloatVal:
  1994. decodeB(rkNode)
  1995. var dest = regs[ra].node
  1996. if dest.kind in {nkFloatLit..nkFloat64Lit} and
  1997. regs[rb].kind in {rkFloat}:
  1998. dest.floatVal = regs[rb].floatVal
  1999. else:
  2000. stackTrace(c, tos, pc, errFieldXNotFound & "floatVal")
  2001. of opcNSetSymbol:
  2002. decodeB(rkNode)
  2003. var dest = regs[ra].node
  2004. if dest.kind == nkSym and regs[rb].node.kind == nkSym:
  2005. dest.sym = regs[rb].node.sym
  2006. else:
  2007. stackTrace(c, tos, pc, errFieldXNotFound & "symbol")
  2008. of opcNSetIdent:
  2009. decodeB(rkNode)
  2010. var dest = regs[ra].node
  2011. if dest.kind == nkIdent and regs[rb].node.kind == nkIdent:
  2012. dest.ident = regs[rb].node.ident
  2013. else:
  2014. stackTrace(c, tos, pc, errFieldXNotFound & "ident")
  2015. of opcNSetStrVal:
  2016. decodeB(rkNode)
  2017. var dest = regs[ra].node
  2018. if dest.kind in {nkStrLit..nkTripleStrLit} and
  2019. regs[rb].kind in {rkNode}:
  2020. dest.strVal = regs[rb].node.strVal
  2021. elif dest.kind == nkCommentStmt and regs[rb].kind in {rkNode}:
  2022. dest.comment = regs[rb].node.strVal
  2023. else:
  2024. stackTrace(c, tos, pc, errFieldXNotFound & "strVal")
  2025. of opcNNewNimNode:
  2026. decodeBC(rkNode)
  2027. var k = regs[rb].intVal
  2028. if k < 0 or k > ord(high(TNodeKind)):
  2029. internalError(c.config, c.debug[pc],
  2030. "request to create a NimNode of invalid kind")
  2031. let cc = regs[rc].node
  2032. let x = newNodeI(TNodeKind(int(k)),
  2033. if cc.kind != nkNilLit:
  2034. cc.info
  2035. elif c.comesFromHeuristic.line != 0'u16:
  2036. c.comesFromHeuristic
  2037. elif c.callsite != nil and c.callsite.safeLen > 1:
  2038. c.callsite[1].info
  2039. else:
  2040. c.debug[pc])
  2041. x.flags.incl nfIsRef
  2042. # prevent crashes in the compiler resulting from wrong macros:
  2043. if x.kind == nkIdent: x.ident = c.cache.emptyIdent
  2044. regs[ra].node = x
  2045. of opcNCopyNimNode:
  2046. decodeB(rkNode)
  2047. regs[ra].node = copyNode(regs[rb].node)
  2048. of opcNCopyNimTree:
  2049. decodeB(rkNode)
  2050. regs[ra].node = copyTree(regs[rb].node)
  2051. of opcNDel:
  2052. decodeBC(rkNode)
  2053. let bb = regs[rb].intVal.int
  2054. for i in 0..<regs[rc].intVal.int:
  2055. delSon(regs[ra].node, bb)
  2056. of opcGenSym:
  2057. decodeBC(rkNode)
  2058. let k = regs[rb].intVal
  2059. let name = if regs[rc].node.strVal.len == 0: ":tmp"
  2060. else: regs[rc].node.strVal
  2061. if k < 0 or k > ord(high(TSymKind)):
  2062. internalError(c.config, c.debug[pc], "request to create symbol of invalid kind")
  2063. var sym = newSym(k.TSymKind, getIdent(c.cache, name), c.idgen, c.module.owner, c.debug[pc])
  2064. incl(sym.flags, sfGenSym)
  2065. regs[ra].node = newSymNode(sym)
  2066. regs[ra].node.flags.incl nfIsRef
  2067. of opcNccValue:
  2068. decodeB(rkInt)
  2069. let destKey {.cursor.} = regs[rb].node.strVal
  2070. regs[ra].intVal = getOrDefault(c.graph.cacheCounters, destKey)
  2071. of opcNccInc:
  2072. let g = c.graph
  2073. declBC()
  2074. let destKey {.cursor.} = regs[rb].node.strVal
  2075. let by = regs[rc].intVal
  2076. let v = getOrDefault(g.cacheCounters, destKey)
  2077. g.cacheCounters[destKey] = v+by
  2078. recordInc(c, c.debug[pc], destKey, by)
  2079. of opcNcsAdd:
  2080. let g = c.graph
  2081. declBC()
  2082. let destKey {.cursor.} = regs[rb].node.strVal
  2083. let val = regs[rc].node
  2084. if not contains(g.cacheSeqs, destKey):
  2085. g.cacheSeqs[destKey] = newTree(nkStmtList, val)
  2086. else:
  2087. g.cacheSeqs[destKey].add val
  2088. recordAdd(c, c.debug[pc], destKey, val)
  2089. of opcNcsIncl:
  2090. let g = c.graph
  2091. declBC()
  2092. let destKey {.cursor.} = regs[rb].node.strVal
  2093. let val = regs[rc].node
  2094. if not contains(g.cacheSeqs, destKey):
  2095. g.cacheSeqs[destKey] = newTree(nkStmtList, val)
  2096. else:
  2097. block search:
  2098. for existing in g.cacheSeqs[destKey]:
  2099. if exprStructuralEquivalent(existing, val, strictSymEquality=true):
  2100. break search
  2101. g.cacheSeqs[destKey].add val
  2102. recordIncl(c, c.debug[pc], destKey, val)
  2103. of opcNcsLen:
  2104. let g = c.graph
  2105. decodeB(rkInt)
  2106. let destKey {.cursor.} = regs[rb].node.strVal
  2107. regs[ra].intVal =
  2108. if contains(g.cacheSeqs, destKey): g.cacheSeqs[destKey].len else: 0
  2109. of opcNcsAt:
  2110. let g = c.graph
  2111. decodeBC(rkNode)
  2112. let idx = regs[rc].intVal
  2113. let destKey {.cursor.} = regs[rb].node.strVal
  2114. if contains(g.cacheSeqs, destKey) and idx <% g.cacheSeqs[destKey].len:
  2115. regs[ra].node = g.cacheSeqs[destKey][idx.int]
  2116. else:
  2117. stackTrace(c, tos, pc, formatErrorIndexBound(idx, g.cacheSeqs[destKey].len-1))
  2118. of opcNctPut:
  2119. let g = c.graph
  2120. let destKey {.cursor.} = regs[ra].node.strVal
  2121. let key {.cursor.} = regs[instr.regB].node.strVal
  2122. let val = regs[instr.regC].node
  2123. if not contains(g.cacheTables, destKey):
  2124. g.cacheTables[destKey] = initBTree[string, PNode]()
  2125. if not contains(g.cacheTables[destKey], key):
  2126. g.cacheTables[destKey].add(key, val)
  2127. recordPut(c, c.debug[pc], destKey, key, val)
  2128. else:
  2129. stackTrace(c, tos, pc, "key already exists: " & key)
  2130. of opcNctLen:
  2131. let g = c.graph
  2132. decodeB(rkInt)
  2133. let destKey {.cursor.} = regs[rb].node.strVal
  2134. regs[ra].intVal =
  2135. if contains(g.cacheTables, destKey): g.cacheTables[destKey].len else: 0
  2136. of opcNctGet:
  2137. let g = c.graph
  2138. decodeBC(rkNode)
  2139. let destKey {.cursor.} = regs[rb].node.strVal
  2140. let key {.cursor.} = regs[rc].node.strVal
  2141. if contains(g.cacheTables, destKey):
  2142. if contains(g.cacheTables[destKey], key):
  2143. regs[ra].node = getOrDefault(g.cacheTables[destKey], key)
  2144. else:
  2145. stackTrace(c, tos, pc, "key does not exist: " & key)
  2146. else:
  2147. stackTrace(c, tos, pc, "key does not exist: " & destKey)
  2148. of opcNctHasNext:
  2149. let g = c.graph
  2150. decodeBC(rkInt)
  2151. let destKey {.cursor.} = regs[rb].node.strVal
  2152. regs[ra].intVal =
  2153. if g.cacheTables.contains(destKey):
  2154. ord(btrees.hasNext(g.cacheTables[destKey], regs[rc].intVal.int))
  2155. else:
  2156. 0
  2157. of opcNctNext:
  2158. let g = c.graph
  2159. decodeBC(rkNode)
  2160. let destKey {.cursor.} = regs[rb].node.strVal
  2161. let index = regs[rc].intVal
  2162. if contains(g.cacheTables, destKey):
  2163. let (k, v, nextIndex) = btrees.next(g.cacheTables[destKey], index.int)
  2164. regs[ra].node = newTree(nkTupleConstr, newStrNode(k, c.debug[pc]), v,
  2165. newIntNode(nkIntLit, nextIndex))
  2166. else:
  2167. stackTrace(c, tos, pc, "key does not exist: " & destKey)
  2168. of opcTypeTrait:
  2169. # XXX only supports 'name' for now; we can use regC to encode the
  2170. # type trait operation
  2171. decodeB(rkNode)
  2172. var typ = regs[rb].node.typ
  2173. internalAssert c.config, typ != nil
  2174. while typ.kind == tyTypeDesc and typ.len > 0: typ = typ[0]
  2175. createStr regs[ra]
  2176. regs[ra].node.strVal = typ.typeToString(preferExported)
  2177. c.profiler.leave(c)
  2178. inc pc
  2179. proc execute(c: PCtx, start: int): PNode =
  2180. var tos = PStackFrame(prc: nil, comesFrom: 0, next: nil)
  2181. newSeq(tos.slots, c.prc.regInfo.len)
  2182. result = rawExecute(c, start, tos).regToNode
  2183. proc execProc*(c: PCtx; sym: PSym; args: openArray[PNode]): PNode =
  2184. c.loopIterations = c.config.maxLoopIterationsVM
  2185. if sym.kind in routineKinds:
  2186. if sym.typ.len-1 != args.len:
  2187. result = nil
  2188. localError(c.config, sym.info,
  2189. "NimScript: expected $# arguments, but got $#" % [
  2190. $(sym.typ.len-1), $args.len])
  2191. else:
  2192. let start = genProc(c, sym)
  2193. var tos = PStackFrame(prc: sym, comesFrom: 0, next: nil)
  2194. let maxSlots = sym.offset
  2195. newSeq(tos.slots, maxSlots)
  2196. # setup parameters:
  2197. if not isEmptyType(sym.typ[0]) or sym.kind == skMacro:
  2198. putIntoReg(tos.slots[0], getNullValue(sym.typ[0], sym.info, c.config))
  2199. # XXX We could perform some type checking here.
  2200. for i in 1..<sym.typ.len:
  2201. putIntoReg(tos.slots[i], args[i-1])
  2202. result = rawExecute(c, start, tos).regToNode
  2203. else:
  2204. result = nil
  2205. localError(c.config, sym.info,
  2206. "NimScript: attempt to call non-routine: " & sym.name.s)
  2207. proc evalStmt*(c: PCtx, n: PNode) =
  2208. let n = transformExpr(c.graph, c.idgen, c.module, n)
  2209. let start = genStmt(c, n)
  2210. # execute new instructions; this redundant opcEof check saves us lots
  2211. # of allocations in 'execute':
  2212. if c.code[start].opcode != opcEof:
  2213. discard execute(c, start)
  2214. proc evalExpr*(c: PCtx, n: PNode): PNode =
  2215. # deadcode
  2216. # `nim --eval:"expr"` might've used it at some point for idetools; could
  2217. # be revived for nimsuggest
  2218. let n = transformExpr(c.graph, c.idgen, c.module, n)
  2219. let start = genExpr(c, n)
  2220. assert c.code[start].opcode != opcEof
  2221. result = execute(c, start)
  2222. proc getGlobalValue*(c: PCtx; s: PSym): PNode =
  2223. internalAssert c.config, s.kind in {skLet, skVar} and sfGlobal in s.flags
  2224. result = c.globals[s.position-1]
  2225. proc setGlobalValue*(c: PCtx; s: PSym, val: PNode) =
  2226. ## Does not do type checking so ensure the `val` matches the `s.typ`
  2227. internalAssert c.config, s.kind in {skLet, skVar} and sfGlobal in s.flags
  2228. c.globals[s.position-1] = val
  2229. include vmops
  2230. proc setupGlobalCtx*(module: PSym; graph: ModuleGraph; idgen: IdGenerator) =
  2231. if graph.vm.isNil:
  2232. graph.vm = newCtx(module, graph.cache, graph, idgen)
  2233. registerAdditionalOps(PCtx graph.vm)
  2234. else:
  2235. refresh(PCtx graph.vm, module, idgen)
  2236. proc setupEvalGen*(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext =
  2237. #var c = newEvalContext(module, emRepl)
  2238. #c.features = {allowCast, allowInfiniteLoops}
  2239. #pushStackFrame(c, newStackFrame())
  2240. # XXX produce a new 'globals' environment here:
  2241. setupGlobalCtx(module, graph, idgen)
  2242. result = PCtx graph.vm
  2243. proc interpreterCode*(c: PPassContext, n: PNode): PNode =
  2244. let c = PCtx(c)
  2245. # don't eval errornous code:
  2246. if c.oldErrorCount == c.config.errorCounter:
  2247. evalStmt(c, n)
  2248. result = newNodeI(nkEmpty, n.info)
  2249. else:
  2250. result = n
  2251. c.oldErrorCount = c.config.errorCounter
  2252. proc evalConstExprAux(module: PSym; idgen: IdGenerator;
  2253. g: ModuleGraph; prc: PSym, n: PNode,
  2254. mode: TEvalMode): PNode =
  2255. when defined(nimsuggest):
  2256. if g.config.expandDone():
  2257. return n
  2258. #if g.config.errorCounter > 0: return n
  2259. let n = transformExpr(g, idgen, module, n)
  2260. setupGlobalCtx(module, g, idgen)
  2261. var c = PCtx g.vm
  2262. let oldMode = c.mode
  2263. c.mode = mode
  2264. let start = genExpr(c, n, requiresValue = mode!=emStaticStmt)
  2265. if c.code[start].opcode == opcEof: return newNodeI(nkEmpty, n.info)
  2266. assert c.code[start].opcode != opcEof
  2267. when debugEchoCode: c.echoCode start
  2268. var tos = PStackFrame(prc: prc, comesFrom: 0, next: nil)
  2269. newSeq(tos.slots, c.prc.regInfo.len)
  2270. #for i in 0..<c.prc.regInfo.len: tos.slots[i] = newNode(nkEmpty)
  2271. result = rawExecute(c, start, tos).regToNode
  2272. if result.info.col < 0: result.info = n.info
  2273. c.mode = oldMode
  2274. proc evalConstExpr*(module: PSym; idgen: IdGenerator; g: ModuleGraph; e: PNode): PNode =
  2275. result = evalConstExprAux(module, idgen, g, nil, e, emConst)
  2276. proc evalStaticExpr*(module: PSym; idgen: IdGenerator; g: ModuleGraph; e: PNode, prc: PSym): PNode =
  2277. result = evalConstExprAux(module, idgen, g, prc, e, emStaticExpr)
  2278. proc evalStaticStmt*(module: PSym; idgen: IdGenerator; g: ModuleGraph; e: PNode, prc: PSym) =
  2279. discard evalConstExprAux(module, idgen, g, prc, e, emStaticStmt)
  2280. proc setupCompileTimeVar*(module: PSym; idgen: IdGenerator; g: ModuleGraph; n: PNode) =
  2281. discard evalConstExprAux(module, idgen, g, nil, n, emStaticStmt)
  2282. proc prepareVMValue(arg: PNode): PNode =
  2283. ## strip nkExprColonExpr from tuple values recursively. That is how
  2284. ## they are expected to be stored in the VM.
  2285. # Early abort without copy. No transformation takes place.
  2286. if arg.kind in nkLiterals:
  2287. return arg
  2288. if arg.kind == nkExprColonExpr and arg[0].typ != nil and
  2289. arg[0].typ.sym != nil and arg[0].typ.sym.magic == mPNimrodNode:
  2290. # Poor mans way of protecting static NimNodes
  2291. # XXX: Maybe we need a nkNimNode?
  2292. return arg
  2293. result = copyNode(arg)
  2294. if arg.kind == nkTupleConstr:
  2295. for child in arg:
  2296. if child.kind == nkExprColonExpr:
  2297. result.add prepareVMValue(child[1])
  2298. else:
  2299. result.add prepareVMValue(child)
  2300. else:
  2301. for child in arg:
  2302. result.add prepareVMValue(child)
  2303. proc setupMacroParam(x: PNode, typ: PType): TFullReg =
  2304. case typ.kind
  2305. of tyStatic:
  2306. result = TFullReg(kind: rkNone)
  2307. putIntoReg(result, prepareVMValue(x))
  2308. else:
  2309. var n = x
  2310. if n.kind in {nkHiddenSubConv, nkHiddenStdConv}: n = n[1]
  2311. n.flags.incl nfIsRef
  2312. n.typ = x.typ
  2313. result = TFullReg(kind: rkNode, node: n)
  2314. iterator genericParamsInMacroCall*(macroSym: PSym, call: PNode): (PSym, PNode) =
  2315. let gp = macroSym.ast[genericParamsPos]
  2316. for i in 0..<gp.len:
  2317. let genericParam = gp[i].sym
  2318. let posInCall = macroSym.typ.len + i
  2319. if posInCall < call.len:
  2320. yield (genericParam, call[posInCall])
  2321. # to prevent endless recursion in macro instantiation
  2322. const evalMacroLimit = 1000
  2323. #proc errorNode(idgen: IdGenerator; owner: PSym, n: PNode): PNode =
  2324. # result = newNodeI(nkEmpty, n.info)
  2325. # result.typ = newType(tyError, nextTypeId idgen, owner)
  2326. # result.typ.flags.incl tfCheckedForDestructor
  2327. proc evalMacroCall*(module: PSym; idgen: IdGenerator; g: ModuleGraph; templInstCounter: ref int;
  2328. n, nOrig: PNode, sym: PSym): PNode =
  2329. #if g.config.errorCounter > 0: return errorNode(idgen, module, n)
  2330. # XXX globalError() is ugly here, but I don't know a better solution for now
  2331. inc(g.config.evalMacroCounter)
  2332. if g.config.evalMacroCounter > evalMacroLimit:
  2333. globalError(g.config, n.info, "macro instantiation too nested")
  2334. # immediate macros can bypass any type and arity checking so we check the
  2335. # arity here too:
  2336. if sym.typ.len > n.safeLen and sym.typ.len > 1:
  2337. globalError(g.config, n.info, "in call '$#' got $#, but expected $# argument(s)" % [
  2338. n.renderTree, $(n.safeLen-1), $(sym.typ.len-1)])
  2339. setupGlobalCtx(module, g, idgen)
  2340. var c = PCtx g.vm
  2341. let oldMode = c.mode
  2342. c.mode = emStaticStmt
  2343. c.comesFromHeuristic.line = 0'u16
  2344. c.callsite = nOrig
  2345. c.templInstCounter = templInstCounter
  2346. let start = genProc(c, sym)
  2347. var tos = PStackFrame(prc: sym, comesFrom: 0, next: nil)
  2348. let maxSlots = sym.offset
  2349. newSeq(tos.slots, maxSlots)
  2350. # setup arguments:
  2351. var L = n.safeLen
  2352. if L == 0: L = 1
  2353. # This is wrong for tests/reject/tind1.nim where the passed 'else' part
  2354. # doesn't end up in the parameter:
  2355. #InternalAssert tos.slots.len >= L
  2356. # return value:
  2357. tos.slots[0] = TFullReg(kind: rkNode, node: newNodeI(nkEmpty, n.info))
  2358. # setup parameters:
  2359. for i in 1..<sym.typ.len:
  2360. tos.slots[i] = setupMacroParam(n[i], sym.typ[i])
  2361. let gp = sym.ast[genericParamsPos]
  2362. for i in 0..<gp.len:
  2363. let idx = sym.typ.len + i
  2364. if idx < n.len:
  2365. tos.slots[idx] = setupMacroParam(n[idx], gp[i].sym.typ)
  2366. else:
  2367. dec(g.config.evalMacroCounter)
  2368. c.callsite = nil
  2369. localError(c.config, n.info, "expected " & $gp.len &
  2370. " generic parameter(s)")
  2371. # temporary storage:
  2372. #for i in L..<maxSlots: tos.slots[i] = newNode(nkEmpty)
  2373. result = rawExecute(c, start, tos).regToNode
  2374. if result.info.line < 0: result.info = n.info
  2375. if cyclicTree(result): globalError(c.config, n.info, "macro produced a cyclic tree")
  2376. dec(g.config.evalMacroCounter)
  2377. c.callsite = nil
  2378. c.mode = oldMode