vm.nim 88 KB

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