vm.nim 91 KB

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