vm.nim 87 KB

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