vm.nim 88 KB

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