vm.nim 90 KB

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