vm.nim 84 KB

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