vm.nim 90 KB

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