vm.nim 92 KB

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