jsgen.nim 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528
  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 is the JavaScript code generator.
  10. discard """
  11. The JS code generator contains only 2 tricks:
  12. Trick 1
  13. -------
  14. Some locations (for example 'var int') require "fat pointers" (``etyBaseIndex``)
  15. which are pairs (array, index). The derefence operation is then 'array[index]'.
  16. Check ``mapType`` for the details.
  17. Trick 2
  18. -------
  19. It is preferable to generate '||' and '&&' if possible since that is more
  20. idiomatic and hence should be friendlier for the JS JIT implementation. However
  21. code like ``foo and (let bar = baz())`` cannot be translated this way. Instead
  22. the expressions need to be transformed into statements. ``isSimpleExpr``
  23. implements the required case distinction.
  24. """
  25. import
  26. ast, astalgo, strutils, hashes, trees, platform, magicsys, extccomp, options,
  27. nversion, nimsets, msgs, std / sha1, bitsets, idents, types, os, tables,
  28. times, ropes, math, passes, ccgutils, wordrecg, renderer,
  29. intsets, cgmeth, lowerings, sighashes, lineinfos, rodutils, pathutils, transf
  30. from modulegraphs import ModuleGraph, PPassContext
  31. type
  32. TJSGen = object of PPassContext
  33. module: PSym
  34. graph: ModuleGraph
  35. config: ConfigRef
  36. sigConflicts: CountTable[SigHash]
  37. BModule = ref TJSGen
  38. TJSTypeKind = enum # necessary JS "types"
  39. etyNone, # no type
  40. etyNull, # null type
  41. etyProc, # proc type
  42. etyBool, # bool type
  43. etySeq, # Nim seq or string type
  44. etyInt, # JavaScript's int
  45. etyFloat, # JavaScript's float
  46. etyString, # JavaScript's string
  47. etyObject, # JavaScript's reference to an object
  48. etyBaseIndex # base + index needed
  49. TResKind = enum
  50. resNone, # not set
  51. resExpr, # is some complex expression
  52. resVal, # is a temporary/value/l-value
  53. resCallee # expression is callee
  54. TCompRes = object
  55. kind: TResKind
  56. typ: TJSTypeKind
  57. res: Rope # result part; index if this is an
  58. # (address, index)-tuple
  59. address: Rope # address of an (address, index)-tuple
  60. tmpLoc: Rope # tmp var which stores the (address, index)
  61. # pair to prevent multiple evals.
  62. # the tmp is initialized upon evaling the
  63. # address.
  64. # might be nil.
  65. # (see `maybeMakeTemp`)
  66. TBlock = object
  67. id: int # the ID of the label; positive means that it
  68. # has been used (i.e. the label should be emitted)
  69. isLoop: bool # whether it's a 'block' or 'while'
  70. PGlobals = ref object of RootObj
  71. typeInfo, constants, code: Rope
  72. forwarded: seq[PSym]
  73. generatedSyms: IntSet
  74. typeInfoGenerated: IntSet
  75. classes: seq[(PType, Rope)]
  76. unique: int # for temp identifier generation
  77. PProc = ref TProc
  78. TProc = object
  79. procDef: PNode
  80. prc: PSym
  81. globals, locals, body: Rope
  82. options: TOptions
  83. module: BModule
  84. g: PGlobals
  85. beforeRetNeeded: bool
  86. unique: int # for temp identifier generation
  87. blocks: seq[TBlock]
  88. extraIndent: int
  89. up: PProc # up the call chain; required for closure support
  90. declaredGlobals: IntSet
  91. template config*(p: PProc): ConfigRef = p.module.config
  92. proc indentLine(p: PProc, r: Rope): Rope =
  93. result = r
  94. var p = p
  95. while true:
  96. for i in countup(0, p.blocks.len - 1 + p.extraIndent):
  97. prepend(result, "\t".rope)
  98. if p.up == nil or p.up.prc != p.prc.owner:
  99. break
  100. p = p.up
  101. template line(p: PProc, added: string) =
  102. add(p.body, indentLine(p, rope(added)))
  103. template line(p: PProc, added: Rope) =
  104. add(p.body, indentLine(p, added))
  105. template lineF(p: PProc, frmt: FormatStr, args: varargs[Rope]) =
  106. add(p.body, indentLine(p, ropes.`%`(frmt, args)))
  107. template nested(p, body) =
  108. inc p.extraIndent
  109. body
  110. dec p.extraIndent
  111. proc newGlobals(): PGlobals =
  112. new(result)
  113. result.forwarded = @[]
  114. result.generatedSyms = initIntSet()
  115. result.typeInfoGenerated = initIntSet()
  116. result.classes = @[]
  117. proc initCompRes(r: var TCompRes) =
  118. r.address = nil
  119. r.res = nil
  120. r.tmpLoc = nil
  121. r.typ = etyNone
  122. r.kind = resNone
  123. proc rdLoc(a: TCompRes): Rope {.inline.} =
  124. if a.typ != etyBaseIndex:
  125. result = a.res
  126. else:
  127. result = "$1[$2]" % [a.address, a.res]
  128. proc newProc(globals: PGlobals, module: BModule, procDef: PNode,
  129. options: TOptions): PProc =
  130. result = PProc(
  131. blocks: @[],
  132. options: options,
  133. module: module,
  134. procDef: procDef,
  135. g: globals,
  136. extraIndent: int(procDef != nil))
  137. if procDef != nil: result.prc = procDef.sons[namePos].sym
  138. proc declareGlobal(p: PProc; id: int; r: Rope) =
  139. if p.prc != nil and not p.declaredGlobals.containsOrIncl(id):
  140. p.locals.addf("global $1;$n", [r])
  141. const
  142. MappedToObject = {tyObject, tyArray, tyTuple, tyOpenArray,
  143. tySet, tyVarargs}
  144. proc mapType(typ: PType): TJSTypeKind =
  145. let t = skipTypes(typ, abstractInst)
  146. case t.kind
  147. of tyVar, tyRef, tyPtr, tyLent:
  148. if skipTypes(t.lastSon, abstractInst).kind in MappedToObject:
  149. result = etyObject
  150. else:
  151. result = etyBaseIndex
  152. of tyPointer:
  153. # treat a tyPointer like a typed pointer to an array of bytes
  154. result = etyBaseIndex
  155. of tyRange, tyDistinct, tyOrdinal, tyProxy:
  156. result = mapType(t.sons[0])
  157. of tyInt..tyInt64, tyUInt..tyUInt64, tyEnum, tyChar: result = etyInt
  158. of tyBool: result = etyBool
  159. of tyFloat..tyFloat128: result = etyFloat
  160. of tySet: result = etyObject # map a set to a table
  161. of tyString, tySequence, tyOpt: result = etySeq
  162. of tyObject, tyArray, tyTuple, tyOpenArray, tyVarargs, tyUncheckedArray:
  163. result = etyObject
  164. of tyNil: result = etyNull
  165. of tyGenericParam, tyGenericBody, tyGenericInvocation,
  166. tyNone, tyFromExpr, tyForward, tyEmpty,
  167. tyExpr, tyStmt, tyTypeDesc, tyBuiltInTypeClass, tyCompositeTypeClass,
  168. tyAnd, tyOr, tyNot, tyAnything, tyVoid:
  169. result = etyNone
  170. of tyGenericInst, tyInferred, tyAlias, tyUserTypeClass, tyUserTypeClassInst,
  171. tySink:
  172. result = mapType(typ.lastSon)
  173. of tyStatic:
  174. if t.n != nil: result = mapType(lastSon t)
  175. else: result = etyNone
  176. of tyProc: result = etyProc
  177. of tyCString: result = etyString
  178. of tyOptAsRef: doAssert(false, "mapType")
  179. proc mapType(p: PProc; typ: PType): TJSTypeKind =
  180. result = mapType(typ)
  181. proc mangleName(m: BModule, s: PSym): Rope =
  182. proc validJsName(name: string): bool =
  183. result = true
  184. const reservedWords = ["abstract", "await", "boolean", "break", "byte",
  185. "case", "catch", "char", "class", "const", "continue", "debugger",
  186. "default", "delete", "do", "double", "else", "enum", "export", "extends",
  187. "false", "final", "finally", "float", "for", "function", "goto", "if",
  188. "implements", "import", "in", "instanceof", "int", "interface", "let",
  189. "long", "native", "new", "null", "package", "private", "protected",
  190. "public", "return", "short", "static", "super", "switch", "synchronized",
  191. "this", "throw", "throws", "transient", "true", "try", "typeof", "var",
  192. "void", "volatile", "while", "with", "yield"]
  193. case name
  194. of reservedWords:
  195. return false
  196. else:
  197. discard
  198. if name[0] in {'0'..'9'}: return false
  199. for chr in name:
  200. if chr notin {'A'..'Z','a'..'z','_','$','0'..'9'}:
  201. return false
  202. result = s.loc.r
  203. if result == nil:
  204. if s.kind == skField and s.name.s.validJsName:
  205. result = rope(s.name.s)
  206. elif s.kind == skTemp:
  207. result = rope(mangle(s.name.s))
  208. else:
  209. var x = newStringOfCap(s.name.s.len)
  210. var i = 0
  211. while i < s.name.s.len:
  212. let c = s.name.s[i]
  213. case c
  214. of 'A'..'Z':
  215. if i > 0 and s.name.s[i-1] in {'a'..'z'}:
  216. x.add '_'
  217. x.add(chr(c.ord - 'A'.ord + 'a'.ord))
  218. of 'a'..'z', '_', '0'..'9':
  219. x.add c
  220. else:
  221. x.add("HEX" & toHex(ord(c), 2))
  222. inc i
  223. result = rope(x)
  224. # From ES5 on reserved words can be used as object field names
  225. if s.kind != skField:
  226. if optHotCodeReloading in m.config.options:
  227. # When hot reloading is enabled, we must ensure that the names
  228. # of functions and types will be preserved across rebuilds:
  229. add(result, idOrSig(s, m.module.name.s, m.sigConflicts))
  230. else:
  231. add(result, "_")
  232. add(result, rope(s.id))
  233. s.loc.r = result
  234. proc escapeJSString(s: string): string =
  235. result = newStringOfCap(s.len + s.len shr 2)
  236. result.add("\"")
  237. for c in items(s):
  238. case c
  239. of '\l': result.add("\\n")
  240. of '\r': result.add("\\r")
  241. of '\t': result.add("\\t")
  242. of '\b': result.add("\\b")
  243. of '\a': result.add("\\a")
  244. of '\e': result.add("\\e")
  245. of '\v': result.add("\\v")
  246. of '\\': result.add("\\\\")
  247. of '\"': result.add("\\\"")
  248. else: add(result, c)
  249. result.add("\"")
  250. proc makeJSString(s: string, escapeNonAscii = true): Rope =
  251. if escapeNonAscii:
  252. result = strutils.escape(s).rope
  253. else:
  254. result = escapeJSString(s).rope
  255. include jstypes
  256. proc gen(p: PProc, n: PNode, r: var TCompRes)
  257. proc genStmt(p: PProc, n: PNode)
  258. proc genProc(oldProc: PProc, prc: PSym): Rope
  259. proc genConstant(p: PProc, c: PSym)
  260. proc useMagic(p: PProc, name: string) =
  261. if name.len == 0: return
  262. var s = magicsys.getCompilerProc(p.module.graph, name)
  263. if s != nil:
  264. internalAssert p.config, s.kind in {skProc, skFunc, skMethod, skConverter}
  265. if not p.g.generatedSyms.containsOrIncl(s.id):
  266. let code = genProc(p, s)
  267. add(p.g.constants, code)
  268. else:
  269. if p.prc != nil:
  270. globalError(p.config, p.prc.info, "system module needs: " & name)
  271. else:
  272. rawMessage(p.config, errGenerated, "system module needs: " & name)
  273. proc isSimpleExpr(p: PProc; n: PNode): bool =
  274. # calls all the way down --> can stay expression based
  275. if n.kind in nkCallKinds+{nkBracketExpr, nkDotExpr, nkPar, nkTupleConstr} or
  276. (n.kind in {nkObjConstr, nkBracket, nkCurly}):
  277. for c in n:
  278. if not p.isSimpleExpr(c): return false
  279. result = true
  280. elif n.isAtom:
  281. result = true
  282. proc getTemp(p: PProc, defineInLocals: bool = true): Rope =
  283. inc(p.unique)
  284. result = "Tmp$1" % [rope(p.unique)]
  285. if defineInLocals:
  286. add(p.locals, p.indentLine("var $1;$n" % [result]))
  287. proc genAnd(p: PProc, a, b: PNode, r: var TCompRes) =
  288. assert r.kind == resNone
  289. var x, y: TCompRes
  290. if p.isSimpleExpr(a) and p.isSimpleExpr(b):
  291. gen(p, a, x)
  292. gen(p, b, y)
  293. r.kind = resExpr
  294. r.res = "($1 && $2)" % [x.rdLoc, y.rdLoc]
  295. else:
  296. r.res = p.getTemp
  297. r.kind = resVal
  298. # while a and b:
  299. # -->
  300. # while true:
  301. # aa
  302. # if not a: tmp = false
  303. # else:
  304. # bb
  305. # tmp = b
  306. # tmp
  307. gen(p, a, x)
  308. lineF(p, "if (!$1) $2 = false; else {", [x.rdLoc, r.rdLoc])
  309. p.nested:
  310. gen(p, b, y)
  311. lineF(p, "$2 = $1;", [y.rdLoc, r.rdLoc])
  312. line(p, "}")
  313. proc genOr(p: PProc, a, b: PNode, r: var TCompRes) =
  314. assert r.kind == resNone
  315. var x, y: TCompRes
  316. if p.isSimpleExpr(a) and p.isSimpleExpr(b):
  317. gen(p, a, x)
  318. gen(p, b, y)
  319. r.kind = resExpr
  320. r.res = "($1 || $2)" % [x.rdLoc, y.rdLoc]
  321. else:
  322. r.res = p.getTemp
  323. r.kind = resVal
  324. gen(p, a, x)
  325. lineF(p, "if ($1) $2 = true; else {", [x.rdLoc, r.rdLoc])
  326. p.nested:
  327. gen(p, b, y)
  328. lineF(p, "$2 = $1;", [y.rdLoc, r.rdLoc])
  329. line(p, "}")
  330. type
  331. TMagicFrmt = array[0..3, string]
  332. TMagicOps = array[mAddI..mStrToStr, TMagicFrmt]
  333. const # magic checked op; magic unchecked op; checked op; unchecked op
  334. jsOps: TMagicOps = [
  335. ["addInt", "", "addInt($1, $2)", "($1 + $2)"], # AddI
  336. ["subInt", "", "subInt($1, $2)", "($1 - $2)"], # SubI
  337. ["mulInt", "", "mulInt($1, $2)", "($1 * $2)"], # MulI
  338. ["divInt", "", "divInt($1, $2)", "Math.trunc($1 / $2)"], # DivI
  339. ["modInt", "", "modInt($1, $2)", "Math.trunc($1 % $2)"], # ModI
  340. ["addInt", "", "addInt($1, $2)", "($1 + $2)"], # Succ
  341. ["subInt", "", "subInt($1, $2)", "($1 - $2)"], # Pred
  342. ["", "", "($1 + $2)", "($1 + $2)"], # AddF64
  343. ["", "", "($1 - $2)", "($1 - $2)"], # SubF64
  344. ["", "", "($1 * $2)", "($1 * $2)"], # MulF64
  345. ["", "", "($1 / $2)", "($1 / $2)"], # DivF64
  346. ["", "", "", ""], # ShrI
  347. ["", "", "($1 << $2)", "($1 << $2)"], # ShlI
  348. ["", "", "($1 >> $2)", "($1 >> $2)"], # AshrI
  349. ["", "", "($1 & $2)", "($1 & $2)"], # BitandI
  350. ["", "", "($1 | $2)", "($1 | $2)"], # BitorI
  351. ["", "", "($1 ^ $2)", "($1 ^ $2)"], # BitxorI
  352. ["nimMin", "nimMin", "nimMin($1, $2)", "nimMin($1, $2)"], # MinI
  353. ["nimMax", "nimMax", "nimMax($1, $2)", "nimMax($1, $2)"], # MaxI
  354. ["nimMin", "nimMin", "nimMin($1, $2)", "nimMin($1, $2)"], # MinF64
  355. ["nimMax", "nimMax", "nimMax($1, $2)", "nimMax($1, $2)"], # MaxF64
  356. ["", "", "", ""], # addU
  357. ["", "", "", ""], # subU
  358. ["", "", "", ""], # mulU
  359. ["", "", "", ""], # divU
  360. ["", "", "($1 % $2)", "($1 % $2)"], # modU
  361. ["", "", "($1 == $2)", "($1 == $2)"], # EqI
  362. ["", "", "($1 <= $2)", "($1 <= $2)"], # LeI
  363. ["", "", "($1 < $2)", "($1 < $2)"], # LtI
  364. ["", "", "($1 == $2)", "($1 == $2)"], # EqF64
  365. ["", "", "($1 <= $2)", "($1 <= $2)"], # LeF64
  366. ["", "", "($1 < $2)", "($1 < $2)"], # LtF64
  367. ["", "", "($1 <= $2)", "($1 <= $2)"], # leU
  368. ["", "", "($1 < $2)", "($1 < $2)"], # ltU
  369. ["", "", "($1 <= $2)", "($1 <= $2)"], # leU64
  370. ["", "", "($1 < $2)", "($1 < $2)"], # ltU64
  371. ["", "", "($1 == $2)", "($1 == $2)"], # EqEnum
  372. ["", "", "($1 <= $2)", "($1 <= $2)"], # LeEnum
  373. ["", "", "($1 < $2)", "($1 < $2)"], # LtEnum
  374. ["", "", "($1 == $2)", "($1 == $2)"], # EqCh
  375. ["", "", "($1 <= $2)", "($1 <= $2)"], # LeCh
  376. ["", "", "($1 < $2)", "($1 < $2)"], # LtCh
  377. ["", "", "($1 == $2)", "($1 == $2)"], # EqB
  378. ["", "", "($1 <= $2)", "($1 <= $2)"], # LeB
  379. ["", "", "($1 < $2)", "($1 < $2)"], # LtB
  380. ["", "", "($1 == $2)", "($1 == $2)"], # EqRef
  381. ["", "", "($1 == $2)", "($1 == $2)"], # EqUntracedRef
  382. ["", "", "($1 <= $2)", "($1 <= $2)"], # LePtr
  383. ["", "", "($1 < $2)", "($1 < $2)"], # LtPtr
  384. ["", "", "($1 != $2)", "($1 != $2)"], # Xor
  385. ["", "", "($1 == $2)", "($1 == $2)"], # EqCString
  386. ["", "", "($1 == $2)", "($1 == $2)"], # EqProc
  387. ["negInt", "", "negInt($1)", "-($1)"], # UnaryMinusI
  388. ["negInt64", "", "negInt64($1)", "-($1)"], # UnaryMinusI64
  389. ["absInt", "", "absInt($1)", "Math.abs($1)"], # AbsI
  390. ["", "", "!($1)", "!($1)"], # Not
  391. ["", "", "+($1)", "+($1)"], # UnaryPlusI
  392. ["", "", "~($1)", "~($1)"], # BitnotI
  393. ["", "", "+($1)", "+($1)"], # UnaryPlusF64
  394. ["", "", "-($1)", "-($1)"], # UnaryMinusF64
  395. ["", "", "Math.abs($1)", "Math.abs($1)"], # AbsF64
  396. ["Ze8ToI", "Ze8ToI", "Ze8ToI($1)", "Ze8ToI($1)"], # mZe8ToI
  397. ["Ze8ToI64", "Ze8ToI64", "Ze8ToI64($1)", "Ze8ToI64($1)"], # mZe8ToI64
  398. ["Ze16ToI", "Ze16ToI", "Ze16ToI($1)", "Ze16ToI($1)"], # mZe16ToI
  399. ["Ze16ToI64", "Ze16ToI64", "Ze16ToI64($1)", "Ze16ToI64($1)"], # mZe16ToI64
  400. ["Ze32ToI64", "Ze32ToI64", "Ze32ToI64($1)", "Ze32ToI64($1)"], # mZe32ToI64
  401. ["ZeIToI64", "ZeIToI64", "ZeIToI64($1)", "ZeIToI64($1)"], # mZeIToI64
  402. ["toU8", "toU8", "toU8($1)", "toU8($1)"], # toU8
  403. ["toU16", "toU16", "toU16($1)", "toU16($1)"], # toU16
  404. ["toU32", "toU32", "toU32($1)", "toU32($1)"], # toU32
  405. ["", "", "$1", "$1"], # ToFloat
  406. ["", "", "$1", "$1"], # ToBiggestFloat
  407. ["", "", "Math.trunc($1)", "Math.trunc($1)"], # ToInt
  408. ["", "", "Math.trunc($1)", "Math.trunc($1)"], # ToBiggestInt
  409. ["nimCharToStr", "nimCharToStr", "nimCharToStr($1)", "nimCharToStr($1)"],
  410. ["nimBoolToStr", "nimBoolToStr", "nimBoolToStr($1)", "nimBoolToStr($1)"],
  411. ["cstrToNimstr", "cstrToNimstr", "cstrToNimstr(($1)+\"\")", "cstrToNimstr(($1)+\"\")"],
  412. ["cstrToNimstr", "cstrToNimstr", "cstrToNimstr(($1)+\"\")", "cstrToNimstr(($1)+\"\")"],
  413. ["cstrToNimstr", "cstrToNimstr", "cstrToNimstr(($1)+\"\")", "cstrToNimstr(($1)+\"\")"],
  414. ["cstrToNimstr", "cstrToNimstr", "cstrToNimstr($1)", "cstrToNimstr($1)"],
  415. ["", "", "$1", "$1"]]
  416. proc needsTemp(p: PProc; n: PNode): bool =
  417. # check if n contains a call to determine
  418. # if a temp should be made to prevent multiple evals
  419. if n.kind in nkCallKinds + {nkTupleConstr, nkObjConstr, nkBracket, nkCurly}:
  420. return true
  421. for c in n:
  422. if needsTemp(p, c):
  423. return true
  424. proc maybeMakeTemp(p: PProc, n: PNode; x: TCompRes): tuple[a, tmp: Rope] =
  425. var
  426. a = x.rdLoc
  427. b = a
  428. if needsTemp(p, n):
  429. # if we have tmp just use it
  430. if x.tmpLoc != nil and (mapType(n.typ) == etyBaseIndex or n.kind in {nkHiddenDeref, nkDerefExpr}):
  431. b = "$1[0][$1[1]]" % [x.tmpLoc]
  432. (a: a, tmp: b)
  433. else:
  434. let tmp = p.getTemp
  435. b = tmp
  436. a = "($1 = $2, $1)" % [tmp, a]
  437. (a: a, tmp: b)
  438. else:
  439. (a: a, tmp: b)
  440. proc binaryExpr(p: PProc, n: PNode, r: var TCompRes, magic, frmt: string) =
  441. # $1 and $2 in the `frmt` string bind to lhs and rhs of the expr,
  442. # if $3 or $4 are present they will be substituted with temps for
  443. # lhs and rhs respectively
  444. var x, y: TCompRes
  445. useMagic(p, magic)
  446. gen(p, n.sons[1], x)
  447. gen(p, n.sons[2], y)
  448. var
  449. a, tmp = x.rdLoc
  450. b, tmp2 = y.rdLoc
  451. if "$3" in frmt: (a, tmp) = maybeMakeTemp(p, n[1], x)
  452. if "$4" in frmt: (a, tmp) = maybeMakeTemp(p, n[1], x)
  453. r.res = frmt % [a, b, tmp, tmp2]
  454. r.kind = resExpr
  455. proc unsignedTrimmerJS(size: BiggestInt): Rope =
  456. case size
  457. of 1: rope"& 0xff"
  458. of 2: rope"& 0xffff"
  459. of 4: rope">>> 0"
  460. else: rope""
  461. template unsignedTrimmer(size: BiggestInt): Rope =
  462. size.unsignedTrimmerJS
  463. proc binaryUintExpr(p: PProc, n: PNode, r: var TCompRes, op: string,
  464. reassign = false) =
  465. var x, y: TCompRes
  466. gen(p, n.sons[1], x)
  467. gen(p, n.sons[2], y)
  468. let trimmer = unsignedTrimmer(n[1].typ.skipTypes(abstractRange).size)
  469. if reassign:
  470. let (a, tmp) = maybeMakeTemp(p, n[1], x)
  471. r.res = "$1 = (($5 $2 $3) $4)" % [a, rope op, y.rdLoc, trimmer, tmp]
  472. else:
  473. r.res = "(($1 $2 $3) $4)" % [x.rdLoc, rope op, y.rdLoc, trimmer]
  474. proc ternaryExpr(p: PProc, n: PNode, r: var TCompRes, magic, frmt: string) =
  475. var x, y, z: TCompRes
  476. useMagic(p, magic)
  477. gen(p, n.sons[1], x)
  478. gen(p, n.sons[2], y)
  479. gen(p, n.sons[3], z)
  480. r.res = frmt % [x.rdLoc, y.rdLoc, z.rdLoc]
  481. r.kind = resExpr
  482. proc unaryExpr(p: PProc, n: PNode, r: var TCompRes, magic, frmt: string) =
  483. # $1 binds to n[1], if $2 is present it will be substituted to a tmp of $1
  484. useMagic(p, magic)
  485. gen(p, n.sons[1], r)
  486. var a, tmp = r.rdLoc
  487. if "$2" in frmt: (a, tmp) = maybeMakeTemp(p, n[1], r)
  488. r.res = frmt % [a, tmp]
  489. r.kind = resExpr
  490. proc arithAux(p: PProc, n: PNode, r: var TCompRes, op: TMagic) =
  491. var
  492. x, y: TCompRes
  493. let i = ord(optOverflowCheck notin p.options)
  494. useMagic(p, jsOps[op][i])
  495. if sonsLen(n) > 2:
  496. gen(p, n.sons[1], x)
  497. gen(p, n.sons[2], y)
  498. r.res = jsOps[op][i + 2] % [x.rdLoc, y.rdLoc]
  499. else:
  500. gen(p, n.sons[1], r)
  501. r.res = jsOps[op][i + 2] % [r.rdLoc]
  502. proc arith(p: PProc, n: PNode, r: var TCompRes, op: TMagic) =
  503. case op
  504. of mAddU: binaryUintExpr(p, n, r, "+")
  505. of mSubU: binaryUintExpr(p, n, r, "-")
  506. of mMulU: binaryUintExpr(p, n, r, "*")
  507. of mDivU: binaryUintExpr(p, n, r, "/")
  508. of mDivI:
  509. arithAux(p, n, r, op)
  510. of mModI:
  511. arithAux(p, n, r, op)
  512. of mShrI:
  513. var x, y: TCompRes
  514. gen(p, n.sons[1], x)
  515. gen(p, n.sons[2], y)
  516. let trimmer = unsignedTrimmer(n[1].typ.skipTypes(abstractRange).size)
  517. r.res = "(($1 $2) >>> $3)" % [x.rdLoc, trimmer, y.rdLoc]
  518. of mCharToStr, mBoolToStr, mIntToStr, mInt64ToStr, mFloatToStr,
  519. mCStrToStr, mStrToStr, mEnumToStr:
  520. arithAux(p, n, r, op)
  521. of mEqRef, mEqUntracedRef:
  522. if mapType(n[1].typ) != etyBaseIndex:
  523. arithAux(p, n, r, op)
  524. else:
  525. var x, y: TCompRes
  526. gen(p, n[1], x)
  527. gen(p, n[2], y)
  528. r.res = "($# == $# && $# == $#)" % [x.address, y.address, x.res, y.res]
  529. else:
  530. arithAux(p, n, r, op)
  531. r.kind = resExpr
  532. proc hasFrameInfo(p: PProc): bool =
  533. ({optLineTrace, optStackTrace} * p.options == {optLineTrace, optStackTrace}) and
  534. ((p.prc == nil) or not (sfPure in p.prc.flags))
  535. proc genLineDir(p: PProc, n: PNode) =
  536. let line = toLinenumber(n.info)
  537. if optLineDir in p.options:
  538. lineF(p, "// line $2 \"$1\"$n",
  539. [rope(toFilename(p.config, n.info)), rope(line)])
  540. if {optStackTrace, optEndb} * p.options == {optStackTrace, optEndb} and
  541. ((p.prc == nil) or sfPure notin p.prc.flags):
  542. useMagic(p, "endb")
  543. lineF(p, "endb($1);$n", [rope(line)])
  544. elif hasFrameInfo(p):
  545. lineF(p, "F.line = $1;$n", [rope(line)])
  546. proc genWhileStmt(p: PProc, n: PNode) =
  547. var
  548. cond: TCompRes
  549. internalAssert p.config, isEmptyType(n.typ)
  550. genLineDir(p, n)
  551. inc(p.unique)
  552. var length = len(p.blocks)
  553. setLen(p.blocks, length + 1)
  554. p.blocks[length].id = -p.unique
  555. p.blocks[length].isLoop = true
  556. let labl = p.unique.rope
  557. lineF(p, "L$1: while (true) {$n", [labl])
  558. p.nested: gen(p, n.sons[0], cond)
  559. lineF(p, "if (!$1) break L$2;$n",
  560. [cond.res, labl])
  561. p.nested: genStmt(p, n.sons[1])
  562. lineF(p, "}$n", [labl])
  563. setLen(p.blocks, length)
  564. proc moveInto(p: PProc, src: var TCompRes, dest: TCompRes) =
  565. if src.kind != resNone:
  566. if dest.kind != resNone:
  567. lineF(p, "$1 = $2;$n", [dest.rdLoc, src.rdLoc])
  568. else:
  569. lineF(p, "$1;$n", [src.rdLoc])
  570. src.kind = resNone
  571. src.res = nil
  572. proc genTry(p: PProc, n: PNode, r: var TCompRes) =
  573. # code to generate:
  574. #
  575. # ++excHandler;
  576. # var tmpFramePtr = framePtr;
  577. # try {
  578. # stmts;
  579. # --excHandler;
  580. # } catch (EXC) {
  581. # var prevJSError = lastJSError; lastJSError = EXC;
  582. # framePtr = tmpFramePtr;
  583. # --excHandler;
  584. # if (e.typ && e.typ == NTI433 || e.typ == NTI2321) {
  585. # stmts;
  586. # } else if (e.typ && e.typ == NTI32342) {
  587. # stmts;
  588. # } else {
  589. # stmts;
  590. # }
  591. # lastJSError = prevJSError;
  592. # } finally {
  593. # framePtr = tmpFramePtr;
  594. # stmts;
  595. # }
  596. genLineDir(p, n)
  597. if not isEmptyType(n.typ):
  598. r.kind = resVal
  599. r.res = getTemp(p)
  600. inc(p.unique)
  601. var i = 1
  602. var length = sonsLen(n)
  603. var catchBranchesExist = length > 1 and n.sons[i].kind == nkExceptBranch
  604. if catchBranchesExist:
  605. add(p.body, "++excHandler;\L")
  606. var tmpFramePtr = rope"F"
  607. if optStackTrace notin p.options:
  608. tmpFramePtr = p.getTemp(true)
  609. line(p, tmpFramePtr & " = framePtr;\L")
  610. lineF(p, "try {$n", [])
  611. var a: TCompRes
  612. gen(p, n.sons[0], a)
  613. moveInto(p, a, r)
  614. var generalCatchBranchExists = false
  615. if catchBranchesExist:
  616. addf(p.body, "--excHandler;$n} catch (EXC) {$n var prevJSError = lastJSError;$n" &
  617. " lastJSError = EXC;$n --excHandler;$n", [])
  618. line(p, "framePtr = $1;$n" % [tmpFramePtr])
  619. while i < length and n.sons[i].kind == nkExceptBranch:
  620. let blen = sonsLen(n.sons[i])
  621. if blen == 1:
  622. # general except section:
  623. generalCatchBranchExists = true
  624. if i > 1: lineF(p, "else {$n", [])
  625. gen(p, n.sons[i].sons[0], a)
  626. moveInto(p, a, r)
  627. if i > 1: lineF(p, "}$n", [])
  628. else:
  629. var orExpr: Rope = nil
  630. var excAlias: PNode = nil
  631. useMagic(p, "isObj")
  632. for j in countup(0, blen - 2):
  633. var throwObj: PNode
  634. let it = n.sons[i].sons[j]
  635. if it.isInfixAs():
  636. throwObj = it[1]
  637. excAlias = it[2]
  638. # If this is a ``except exc as sym`` branch there must be no following
  639. # nodes
  640. doAssert orExpr == nil
  641. elif it.kind == nkType:
  642. throwObj = it
  643. else:
  644. internalError(p.config, n.info, "genTryStmt")
  645. if orExpr != nil: add(orExpr, "||")
  646. # Generate the correct type checking code depending on whether this is a
  647. # NIM-native or a JS-native exception
  648. # if isJsObject(throwObj.typ):
  649. if isImportedException(throwObj.typ, p.config):
  650. addf(orExpr, "lastJSError instanceof $1",
  651. [throwObj.typ.sym.loc.r])
  652. else:
  653. addf(orExpr, "isObj(lastJSError.m_type, $1)",
  654. [genTypeInfo(p, throwObj.typ)])
  655. if i > 1: line(p, "else ")
  656. lineF(p, "if (lastJSError && ($1)) {$n", [orExpr])
  657. # If some branch requires a local alias introduce it here. This is needed
  658. # since JS cannot do ``catch x as y``.
  659. if excAlias != nil:
  660. excAlias.sym.loc.r = mangleName(p.module, excAlias.sym)
  661. lineF(p, "var $1 = lastJSError;$n", excAlias.sym.loc.r)
  662. gen(p, n.sons[i].sons[blen - 1], a)
  663. moveInto(p, a, r)
  664. lineF(p, "}$n", [])
  665. inc(i)
  666. if catchBranchesExist:
  667. if not generalCatchBranchExists:
  668. useMagic(p, "reraiseException")
  669. line(p, "else {\L")
  670. line(p, "\treraiseException();\L")
  671. line(p, "}\L")
  672. lineF(p, "lastJSError = prevJSError;$n")
  673. line(p, "} finally {\L")
  674. line(p, "framePtr = $1;$n" % [tmpFramePtr])
  675. if i < length and n.sons[i].kind == nkFinally:
  676. genStmt(p, n.sons[i].sons[0])
  677. line(p, "}\L")
  678. proc genRaiseStmt(p: PProc, n: PNode) =
  679. if n.sons[0].kind != nkEmpty:
  680. var a: TCompRes
  681. gen(p, n.sons[0], a)
  682. let typ = skipTypes(n.sons[0].typ, abstractPtrs)
  683. genLineDir(p, n)
  684. useMagic(p, "raiseException")
  685. lineF(p, "raiseException($1, $2);$n",
  686. [a.rdLoc, makeJSString(typ.sym.name.s)])
  687. else:
  688. genLineDir(p, n)
  689. useMagic(p, "reraiseException")
  690. line(p, "reraiseException();\L")
  691. proc genCaseJS(p: PProc, n: PNode, r: var TCompRes) =
  692. var
  693. cond, stmt: TCompRes
  694. genLineDir(p, n)
  695. gen(p, n.sons[0], cond)
  696. let stringSwitch = skipTypes(n.sons[0].typ, abstractVar).kind == tyString
  697. if stringSwitch:
  698. useMagic(p, "toJSStr")
  699. lineF(p, "switch (toJSStr($1)) {$n", [cond.rdLoc])
  700. else:
  701. lineF(p, "switch ($1) {$n", [cond.rdLoc])
  702. if not isEmptyType(n.typ):
  703. r.kind = resVal
  704. r.res = getTemp(p)
  705. for i in countup(1, sonsLen(n) - 1):
  706. let it = n.sons[i]
  707. case it.kind
  708. of nkOfBranch:
  709. for j in countup(0, sonsLen(it) - 2):
  710. let e = it.sons[j]
  711. if e.kind == nkRange:
  712. var v = copyNode(e.sons[0])
  713. while v.intVal <= e.sons[1].intVal:
  714. gen(p, v, cond)
  715. lineF(p, "case $1:$n", [cond.rdLoc])
  716. inc(v.intVal)
  717. else:
  718. if stringSwitch:
  719. case e.kind
  720. of nkStrLit..nkTripleStrLit: lineF(p, "case $1:$n",
  721. [makeJSString(e.strVal, false)])
  722. else: internalError(p.config, e.info, "jsgen.genCaseStmt: 2")
  723. else:
  724. gen(p, e, cond)
  725. lineF(p, "case $1:$n", [cond.rdLoc])
  726. p.nested:
  727. gen(p, lastSon(it), stmt)
  728. moveInto(p, stmt, r)
  729. lineF(p, "break;$n", [])
  730. of nkElse:
  731. lineF(p, "default: $n", [])
  732. p.nested:
  733. gen(p, it.sons[0], stmt)
  734. moveInto(p, stmt, r)
  735. lineF(p, "break;$n", [])
  736. else: internalError(p.config, it.info, "jsgen.genCaseStmt")
  737. lineF(p, "}$n", [])
  738. proc genBlock(p: PProc, n: PNode, r: var TCompRes) =
  739. inc(p.unique)
  740. let idx = len(p.blocks)
  741. if n.sons[0].kind != nkEmpty:
  742. # named block?
  743. if (n.sons[0].kind != nkSym): internalError(p.config, n.info, "genBlock")
  744. var sym = n.sons[0].sym
  745. sym.loc.k = locOther
  746. sym.position = idx+1
  747. let labl = p.unique
  748. lineF(p, "L$1: do {$n", [labl.rope])
  749. setLen(p.blocks, idx + 1)
  750. p.blocks[idx].id = - p.unique # negative because it isn't used yet
  751. gen(p, n.sons[1], r)
  752. setLen(p.blocks, idx)
  753. lineF(p, "} while(false);$n", [labl.rope])
  754. proc genBreakStmt(p: PProc, n: PNode) =
  755. var idx: int
  756. genLineDir(p, n)
  757. if n.sons[0].kind != nkEmpty:
  758. # named break?
  759. assert(n.sons[0].kind == nkSym)
  760. let sym = n.sons[0].sym
  761. assert(sym.loc.k == locOther)
  762. idx = sym.position-1
  763. else:
  764. # an unnamed 'break' can only break a loop after 'transf' pass:
  765. idx = len(p.blocks) - 1
  766. while idx >= 0 and not p.blocks[idx].isLoop: dec idx
  767. if idx < 0 or not p.blocks[idx].isLoop:
  768. internalError(p.config, n.info, "no loop to break")
  769. p.blocks[idx].id = abs(p.blocks[idx].id) # label is used
  770. lineF(p, "break L$1;$n", [rope(p.blocks[idx].id)])
  771. proc genAsmOrEmitStmt(p: PProc, n: PNode) =
  772. genLineDir(p, n)
  773. p.body.add p.indentLine(nil)
  774. for i in countup(0, sonsLen(n) - 1):
  775. let it = n[i]
  776. case it.kind
  777. of nkStrLit..nkTripleStrLit:
  778. p.body.add(it.strVal)
  779. of nkSym:
  780. let v = it.sym
  781. # for backwards compatibility we don't deref syms here :-(
  782. if false:
  783. discard
  784. else:
  785. var r: TCompRes
  786. gen(p, it, r)
  787. if it.typ.kind == tyPointer:
  788. # A fat pointer is disguised as an array
  789. r.res = r.address
  790. r.address = nil
  791. r.typ = etyNone
  792. elif r.typ == etyBaseIndex:
  793. # Deference first
  794. r.res = "$1[$2]" % [r.address, r.res]
  795. r.address = nil
  796. r.typ = etyNone
  797. p.body.add(r.rdLoc)
  798. else:
  799. var r: TCompRes
  800. gen(p, it, r)
  801. p.body.add(r.rdLoc)
  802. p.body.add "\L"
  803. proc genIf(p: PProc, n: PNode, r: var TCompRes) =
  804. var cond, stmt: TCompRes
  805. var toClose = 0
  806. if not isEmptyType(n.typ):
  807. r.kind = resVal
  808. r.res = getTemp(p)
  809. for i in countup(0, sonsLen(n) - 1):
  810. let it = n.sons[i]
  811. if sonsLen(it) != 1:
  812. if i > 0:
  813. lineF(p, "else {$n", [])
  814. inc(toClose)
  815. p.nested: gen(p, it.sons[0], cond)
  816. lineF(p, "if ($1) {$n", [cond.rdLoc])
  817. gen(p, it.sons[1], stmt)
  818. else:
  819. # else part:
  820. lineF(p, "else {$n", [])
  821. p.nested: gen(p, it.sons[0], stmt)
  822. moveInto(p, stmt, r)
  823. lineF(p, "}$n", [])
  824. line(p, repeat('}', toClose) & "\L")
  825. proc generateHeader(p: PProc, typ: PType): Rope =
  826. result = nil
  827. for i in countup(1, sonsLen(typ.n) - 1):
  828. assert(typ.n.sons[i].kind == nkSym)
  829. var param = typ.n.sons[i].sym
  830. if isCompileTimeOnly(param.typ): continue
  831. if result != nil: add(result, ", ")
  832. var name = mangleName(p.module, param)
  833. add(result, name)
  834. if mapType(param.typ) == etyBaseIndex:
  835. add(result, ", ")
  836. add(result, name)
  837. add(result, "_Idx")
  838. proc countJsParams(typ: PType): int =
  839. for i in countup(1, sonsLen(typ.n) - 1):
  840. assert(typ.n.sons[i].kind == nkSym)
  841. var param = typ.n.sons[i].sym
  842. if isCompileTimeOnly(param.typ): continue
  843. if mapType(param.typ) == etyBaseIndex:
  844. inc result, 2
  845. else:
  846. inc result
  847. const
  848. nodeKindsNeedNoCopy = {nkCharLit..nkInt64Lit, nkStrLit..nkTripleStrLit,
  849. nkFloatLit..nkFloat64Lit, nkCurly, nkPar, nkStringToCString,
  850. nkCStringToString, nkCall, nkPrefix, nkPostfix, nkInfix,
  851. nkCommand, nkHiddenCallConv, nkCallStrLit}
  852. proc needsNoCopy(p: PProc; y: PNode): bool =
  853. # if the node is a literal object constructor we have to recursively
  854. # check the expressions passed into it
  855. case y.kind
  856. of nkObjConstr:
  857. for arg in y.sons[1..^1]:
  858. if not needsNoCopy(p, arg[1]):
  859. return false
  860. of nkTupleConstr:
  861. for arg in y.sons:
  862. var arg = arg
  863. if arg.kind == nkExprColonExpr:
  864. arg = arg[1]
  865. if not needsNoCopy(p, arg):
  866. return false
  867. of nkBracket:
  868. for arg in y.sons:
  869. if not needsNoCopy(p, arg):
  870. return false
  871. of nodeKindsNeedNoCopy:
  872. return true
  873. else:
  874. return (mapType(y.typ) != etyBaseIndex and
  875. (skipTypes(y.typ, abstractInst).kind in
  876. {tyRef, tyPtr, tyLent, tyVar, tyCString, tyProc} + IntegralTypes))
  877. return true
  878. proc genAsgnAux(p: PProc, x, y: PNode, noCopyNeeded: bool) =
  879. var a, b: TCompRes
  880. var xtyp = mapType(p, x.typ)
  881. gen(p, x, a)
  882. genLineDir(p, y)
  883. gen(p, y, b)
  884. # we don't care if it's an etyBaseIndex (global) of a string, it's
  885. # still a string that needs to be copied properly:
  886. if x.typ.skipTypes(abstractInst).kind in {tySequence, tyOpt, tyString}:
  887. xtyp = etySeq
  888. case xtyp
  889. of etySeq:
  890. if (needsNoCopy(p, y) and needsNoCopy(p, x)) or noCopyNeeded:
  891. lineF(p, "$1 = $2;$n", [a.rdLoc, b.rdLoc])
  892. else:
  893. useMagic(p, "nimCopy")
  894. lineF(p, "$1 = nimCopy(null, $2, $3);$n",
  895. [a.rdLoc, b.res, genTypeInfo(p, y.typ)])
  896. of etyObject:
  897. if (needsNoCopy(p, y) and needsNoCopy(p, x)) or noCopyNeeded:
  898. lineF(p, "$1 = $2;$n", [a.rdLoc, b.rdLoc])
  899. else:
  900. useMagic(p, "nimCopy")
  901. lineF(p, "nimCopy($1, $2, $3);$n",
  902. [a.res, b.res, genTypeInfo(p, y.typ)])
  903. of etyBaseIndex:
  904. if a.typ != etyBaseIndex or b.typ != etyBaseIndex:
  905. if y.kind == nkCall:
  906. let tmp = p.getTemp(false)
  907. lineF(p, "var $1 = $4; $2 = $1[0]; $3 = $1[1];$n", [tmp, a.address, a.res, b.rdLoc])
  908. elif b.typ == etyBaseIndex:
  909. lineF(p, "$# = [$#, $#];$n", [a.res, b.address, b.res])
  910. else:
  911. internalError(p.config, x.info, "genAsgn")
  912. else:
  913. lineF(p, "$1 = $2; $3 = $4;$n", [a.address, b.address, a.res, b.res])
  914. else:
  915. lineF(p, "$1 = $2;$n", [a.rdLoc, b.rdLoc])
  916. proc genAsgn(p: PProc, n: PNode) =
  917. genAsgnAux(p, n.sons[0], n.sons[1], noCopyNeeded=false)
  918. proc genFastAsgn(p: PProc, n: PNode) =
  919. # 'shallowCopy' always produced 'noCopyNeeded = true' here but this is wrong
  920. # for code like
  921. # while j >= pos:
  922. # dest[i].shallowCopy(dest[j])
  923. # See bug #5933. So we try to be more compatible with the C backend semantics
  924. # here for 'shallowCopy'. This is an educated guess and might require further
  925. # changes later:
  926. let noCopy = n[0].typ.skipTypes(abstractInst).kind in {tySequence, tyOpt, tyString}
  927. genAsgnAux(p, n.sons[0], n.sons[1], noCopyNeeded=noCopy)
  928. proc genSwap(p: PProc, n: PNode) =
  929. var a, b: TCompRes
  930. gen(p, n.sons[1], a)
  931. gen(p, n.sons[2], b)
  932. var tmp = p.getTemp(false)
  933. if mapType(p, skipTypes(n.sons[1].typ, abstractVar)) == etyBaseIndex:
  934. let tmp2 = p.getTemp(false)
  935. if a.typ != etyBaseIndex or b.typ != etyBaseIndex:
  936. internalError(p.config, n.info, "genSwap")
  937. lineF(p, "var $1 = $2; $2 = $3; $3 = $1;$n",
  938. [tmp, a.address, b.address])
  939. tmp = tmp2
  940. lineF(p, "var $1 = $2; $2 = $3; $3 = $1;",
  941. [tmp, a.res, b.res])
  942. proc getFieldPosition(p: PProc; f: PNode): int =
  943. case f.kind
  944. of nkIntLit..nkUInt64Lit: result = int(f.intVal)
  945. of nkSym: result = f.sym.position
  946. else: internalError(p.config, f.info, "genFieldPosition")
  947. proc genFieldAddr(p: PProc, n: PNode, r: var TCompRes) =
  948. var a: TCompRes
  949. r.typ = etyBaseIndex
  950. let b = if n.kind == nkHiddenAddr: n.sons[0] else: n
  951. gen(p, b.sons[0], a)
  952. if skipTypes(b.sons[0].typ, abstractVarRange).kind == tyTuple:
  953. r.res = makeJSString("Field" & $getFieldPosition(p, b.sons[1]))
  954. else:
  955. if b.sons[1].kind != nkSym: internalError(p.config, b.sons[1].info, "genFieldAddr")
  956. var f = b.sons[1].sym
  957. if f.loc.r == nil: f.loc.r = mangleName(p.module, f)
  958. r.res = makeJSString($f.loc.r)
  959. internalAssert p.config, a.typ != etyBaseIndex
  960. r.address = a.res
  961. r.kind = resExpr
  962. proc genFieldAccess(p: PProc, n: PNode, r: var TCompRes) =
  963. gen(p, n.sons[0], r)
  964. r.typ = mapType(n.typ)
  965. let otyp = skipTypes(n.sons[0].typ, abstractVarRange)
  966. template mkTemp(i: int) =
  967. if r.typ == etyBaseIndex:
  968. if needsTemp(p, n[i]):
  969. let tmp = p.getTemp
  970. r.address = "($1 = $2, $1)[0]" % [tmp, r.res]
  971. r.res = "$1[1]" % [tmp]
  972. r.tmpLoc = tmp
  973. else:
  974. r.address = "$1[0]" % [r.res]
  975. r.res = "$1[1]" % [r.res]
  976. if otyp.kind == tyTuple:
  977. r.res = ("$1.Field$2") %
  978. [r.res, getFieldPosition(p, n.sons[1]).rope]
  979. mkTemp(0)
  980. else:
  981. if n.sons[1].kind != nkSym: internalError(p.config, n.sons[1].info, "genFieldAccess")
  982. var f = n.sons[1].sym
  983. if f.loc.r == nil: f.loc.r = mangleName(p.module, f)
  984. r.res = "$1.$2" % [r.res, f.loc.r]
  985. mkTemp(1)
  986. r.kind = resExpr
  987. proc genAddr(p: PProc, n: PNode, r: var TCompRes)
  988. proc genCheckedFieldOp(p: PProc, n: PNode, addrTyp: PType, r: var TCompRes) =
  989. internalAssert p.config, n.kind == nkCheckedFieldExpr
  990. # nkDotExpr to access the requested field
  991. let accessExpr = n[0]
  992. # nkCall to check if the discriminant is valid
  993. var checkExpr = n[1]
  994. let negCheck = checkExpr[0].sym.magic == mNot
  995. if negCheck:
  996. checkExpr = checkExpr[^1]
  997. # Field symbol
  998. var field = accessExpr[1].sym
  999. internalAssert p.config, field.kind == skField
  1000. if field.loc.r == nil: field.loc.r = mangleName(p.module, field)
  1001. # Discriminant symbol
  1002. let disc = checkExpr[2].sym
  1003. internalAssert p.config, disc.kind == skField
  1004. if disc.loc.r == nil: disc.loc.r = mangleName(p.module, disc)
  1005. var setx: TCompRes
  1006. gen(p, checkExpr[1], setx)
  1007. var obj: TCompRes
  1008. gen(p, accessExpr[0], obj)
  1009. # Avoid evaluating the LHS twice (one to read the discriminant and one to read
  1010. # the field)
  1011. let tmp = p.getTemp()
  1012. lineF(p, "var $1 = $2;$n", tmp, obj.res)
  1013. useMagic(p, "raiseFieldError")
  1014. useMagic(p, "makeNimstrLit")
  1015. lineF(p, "if ($1[$2.$3]$4undefined) { raiseFieldError(makeNimstrLit($5)); }$n",
  1016. setx.res, tmp, disc.loc.r, if negCheck: ~"!==" else: ~"===",
  1017. makeJSString(field.name.s))
  1018. if addrTyp != nil and mapType(p, addrTyp) == etyBaseIndex:
  1019. r.typ = etyBaseIndex
  1020. r.res = makeJSString($field.loc.r)
  1021. r.address = tmp
  1022. else:
  1023. r.typ = etyNone
  1024. r.res = "$1.$2" % [tmp, field.loc.r]
  1025. r.kind = resExpr
  1026. proc genArrayAddr(p: PProc, n: PNode, r: var TCompRes) =
  1027. var
  1028. a, b: TCompRes
  1029. first: BiggestInt
  1030. r.typ = etyBaseIndex
  1031. let m = if n.kind == nkHiddenAddr: n.sons[0] else: n
  1032. gen(p, m.sons[0], a)
  1033. gen(p, m.sons[1], b)
  1034. #internalAssert p.config, a.typ != etyBaseIndex and b.typ != etyBaseIndex
  1035. let (x, tmp) = maybeMakeTemp(p, m[0], a)
  1036. r.address = x
  1037. var typ = skipTypes(m.sons[0].typ, abstractPtrs)
  1038. if typ.kind == tyArray: first = firstOrd(p.config, typ.sons[0])
  1039. else: first = 0
  1040. if optBoundsCheck in p.options:
  1041. useMagic(p, "chckIndx")
  1042. r.res = "chckIndx($1, $2, $3.length+$2-1)-$2" % [b.res, rope(first), tmp]
  1043. elif first != 0:
  1044. r.res = "($1)-$2" % [b.res, rope(first)]
  1045. else:
  1046. r.res = b.res
  1047. r.kind = resExpr
  1048. proc genArrayAccess(p: PProc, n: PNode, r: var TCompRes) =
  1049. var ty = skipTypes(n.sons[0].typ, abstractVarRange)
  1050. if ty.kind in {tyRef, tyPtr, tyLent}: ty = skipTypes(ty.lastSon, abstractVarRange)
  1051. case ty.kind
  1052. of tyArray, tyOpenArray, tySequence, tyString, tyCString, tyVarargs:
  1053. genArrayAddr(p, n, r)
  1054. of tyTuple:
  1055. genFieldAddr(p, n, r)
  1056. else: internalError(p.config, n.info, "expr(nkBracketExpr, " & $ty.kind & ')')
  1057. r.typ = mapType(n.typ)
  1058. if r.res == nil: internalError(p.config, n.info, "genArrayAccess")
  1059. if ty.kind == tyCString:
  1060. r.res = "$1.charCodeAt($2)" % [r.address, r.res]
  1061. elif r.typ == etyBaseIndex:
  1062. if needsTemp(p, n[0]):
  1063. let tmp = p.getTemp
  1064. r.address = "($1 = $2, $1)[0]" % [tmp, r.rdLoc]
  1065. r.res = "$1[1]" % [tmp]
  1066. r.tmpLoc = tmp
  1067. else:
  1068. let x = r.rdLoc
  1069. r.address = "$1[0]" % [x]
  1070. r.res = "$1[1]" % [x]
  1071. else:
  1072. r.res = "$1[$2]" % [r.address, r.res]
  1073. r.kind = resExpr
  1074. template isIndirect(x: PSym): bool =
  1075. let v = x
  1076. ({sfAddrTaken, sfGlobal} * v.flags != {} and
  1077. #(mapType(v.typ) != etyObject) and
  1078. {sfImportc, sfVolatile, sfExportc} * v.flags == {} and
  1079. v.kind notin {skProc, skFunc, skConverter, skMethod, skIterator,
  1080. skConst, skTemp, skLet})
  1081. proc genAddr(p: PProc, n: PNode, r: var TCompRes) =
  1082. case n.sons[0].kind
  1083. of nkSym:
  1084. let s = n.sons[0].sym
  1085. if s.loc.r == nil: internalError(p.config, n.info, "genAddr: 3")
  1086. case s.kind
  1087. of skVar, skLet, skResult:
  1088. r.kind = resExpr
  1089. let jsType = mapType(p, n.typ)
  1090. if jsType == etyObject:
  1091. # make addr() a no-op:
  1092. r.typ = etyNone
  1093. if isIndirect(s):
  1094. r.res = s.loc.r & "[0]"
  1095. else:
  1096. r.res = s.loc.r
  1097. r.address = nil
  1098. elif {sfGlobal, sfAddrTaken} * s.flags != {} or jsType == etyBaseIndex:
  1099. # for ease of code generation, we do not distinguish between
  1100. # sfAddrTaken and sfGlobal.
  1101. r.typ = etyBaseIndex
  1102. r.address = s.loc.r
  1103. r.res = rope("0")
  1104. else:
  1105. # 'var openArray' for instance produces an 'addr' but this is harmless:
  1106. gen(p, n.sons[0], r)
  1107. #internalError(p.config, n.info, "genAddr: 4 " & renderTree(n))
  1108. else: internalError(p.config, n.info, "genAddr: 2")
  1109. of nkCheckedFieldExpr:
  1110. genCheckedFieldOp(p, n[0], n.typ, r)
  1111. of nkDotExpr:
  1112. if mapType(p, n.typ) == etyBaseIndex:
  1113. genFieldAddr(p, n.sons[0], r)
  1114. else:
  1115. genFieldAccess(p, n.sons[0], r)
  1116. of nkBracketExpr:
  1117. var ty = skipTypes(n.sons[0].typ, abstractVarRange)
  1118. if ty.kind in MappedToObject:
  1119. gen(p, n.sons[0], r)
  1120. else:
  1121. let kindOfIndexedExpr = skipTypes(n.sons[0].sons[0].typ, abstractVarRange).kind
  1122. case kindOfIndexedExpr
  1123. of tyArray, tyOpenArray, tySequence, tyString, tyCString, tyVarargs:
  1124. genArrayAddr(p, n.sons[0], r)
  1125. of tyTuple:
  1126. genFieldAddr(p, n.sons[0], r)
  1127. else: internalError(p.config, n.sons[0].info, "expr(nkBracketExpr, " & $kindOfIndexedExpr & ')')
  1128. of nkObjDownConv:
  1129. gen(p, n.sons[0], r)
  1130. of nkHiddenDeref:
  1131. gen(p, n.sons[0].sons[0], r)
  1132. else: internalError(p.config, n.sons[0].info, "genAddr: " & $n.sons[0].kind)
  1133. proc thisParam(p: PProc; typ: PType): PType =
  1134. discard
  1135. proc attachProc(p: PProc; content: Rope; s: PSym) =
  1136. let otyp = thisParam(p, s.typ)
  1137. if otyp != nil:
  1138. for i, cls in p.g.classes:
  1139. if sameType(cls[0], otyp):
  1140. add(p.g.classes[i][1], content)
  1141. return
  1142. p.g.classes.add((otyp, content))
  1143. else:
  1144. add(p.g.code, content)
  1145. proc attachProc(p: PProc; s: PSym) =
  1146. let newp = genProc(p, s)
  1147. attachProc(p, newp, s)
  1148. proc genProcForSymIfNeeded(p: PProc, s: PSym) =
  1149. if not p.g.generatedSyms.containsOrIncl(s.id):
  1150. let newp = genProc(p, s)
  1151. var owner = p
  1152. while owner != nil and owner.prc != s.owner:
  1153. owner = owner.up
  1154. if owner != nil: add(owner.locals, newp)
  1155. else: attachProc(p, newp, s)
  1156. proc genSym(p: PProc, n: PNode, r: var TCompRes) =
  1157. var s = n.sym
  1158. case s.kind
  1159. of skVar, skLet, skParam, skTemp, skResult, skForVar:
  1160. if s.loc.r == nil:
  1161. internalError(p.config, n.info, "symbol has no generated name: " & s.name.s)
  1162. let k = mapType(p, s.typ)
  1163. if k == etyBaseIndex:
  1164. r.typ = etyBaseIndex
  1165. if {sfAddrTaken, sfGlobal} * s.flags != {}:
  1166. if isIndirect(s):
  1167. r.address = "$1[0][0]" % [s.loc.r]
  1168. r.res = "$1[0][1]" % [s.loc.r]
  1169. else:
  1170. r.address = "$1[0]" % [s.loc.r]
  1171. r.res = "$1[1]" % [s.loc.r]
  1172. else:
  1173. r.address = s.loc.r
  1174. r.res = s.loc.r & "_Idx"
  1175. elif isIndirect(s):
  1176. r.res = "$1[0]" % [s.loc.r]
  1177. else:
  1178. r.res = s.loc.r
  1179. of skConst:
  1180. genConstant(p, s)
  1181. if s.loc.r == nil:
  1182. internalError(p.config, n.info, "symbol has no generated name: " & s.name.s)
  1183. r.res = s.loc.r
  1184. of skProc, skFunc, skConverter, skMethod:
  1185. discard mangleName(p.module, s)
  1186. r.res = s.loc.r
  1187. if lfNoDecl in s.loc.flags or s.magic != mNone or
  1188. {sfImportc, sfInfixCall} * s.flags != {}:
  1189. discard
  1190. elif s.kind == skMethod and s.getBody.kind == nkEmpty:
  1191. # we cannot produce code for the dispatcher yet:
  1192. discard
  1193. elif sfForward in s.flags:
  1194. p.g.forwarded.add(s)
  1195. else:
  1196. genProcForSymIfNeeded(p, s)
  1197. else:
  1198. if s.loc.r == nil:
  1199. internalError(p.config, n.info, "symbol has no generated name: " & s.name.s)
  1200. r.res = s.loc.r
  1201. r.kind = resVal
  1202. proc genDeref(p: PProc, n: PNode, r: var TCompRes) =
  1203. let it = n.sons[0]
  1204. let t = mapType(p, it.typ)
  1205. if t == etyObject:
  1206. gen(p, it, r)
  1207. else:
  1208. var a: TCompRes
  1209. gen(p, it, a)
  1210. r.kind = a.kind
  1211. r.typ = mapType(p, n.typ)
  1212. if r.typ == etyBaseIndex:
  1213. let tmp = p.getTemp
  1214. r.address = "($1 = $2, $1)[0]" % [tmp, a.rdLoc]
  1215. r.res = "$1[1]" % [tmp]
  1216. r.tmpLoc = tmp
  1217. elif a.typ == etyBaseIndex:
  1218. if a.tmpLoc != nil:
  1219. r.tmpLoc = a.tmpLoc
  1220. r.res = a.rdLoc
  1221. else:
  1222. internalError(p.config, n.info, "genDeref")
  1223. proc genArgNoParam(p: PProc, n: PNode, r: var TCompRes) =
  1224. var a: TCompRes
  1225. gen(p, n, a)
  1226. if a.typ == etyBaseIndex:
  1227. add(r.res, a.address)
  1228. add(r.res, ", ")
  1229. add(r.res, a.res)
  1230. else:
  1231. add(r.res, a.res)
  1232. proc genArg(p: PProc, n: PNode, param: PSym, r: var TCompRes; emitted: ptr int = nil) =
  1233. var a: TCompRes
  1234. gen(p, n, a)
  1235. if skipTypes(param.typ, abstractVar).kind in {tyOpenArray, tyVarargs} and
  1236. a.typ == etyBaseIndex:
  1237. add(r.res, "$1[$2]" % [a.address, a.res])
  1238. elif a.typ == etyBaseIndex:
  1239. add(r.res, a.address)
  1240. add(r.res, ", ")
  1241. add(r.res, a.res)
  1242. if emitted != nil: inc emitted[]
  1243. elif n.typ.kind in {tyVar, tyPtr, tyRef, tyLent} and n.kind in nkCallKinds and mapType(param.typ) == etyBaseIndex:
  1244. # this fixes bug #5608:
  1245. let tmp = getTemp(p)
  1246. add(r.res, "($1 = $2, $1[0]), $1[1]" % [tmp, a.rdLoc])
  1247. if emitted != nil: inc emitted[]
  1248. else:
  1249. add(r.res, a.res)
  1250. proc genArgs(p: PProc, n: PNode, r: var TCompRes; start=1) =
  1251. add(r.res, "(")
  1252. var hasArgs = false
  1253. var typ = skipTypes(n.sons[0].typ, abstractInst)
  1254. assert(typ.kind == tyProc)
  1255. assert(sonsLen(typ) == sonsLen(typ.n))
  1256. var emitted = start-1
  1257. for i in countup(start, sonsLen(n) - 1):
  1258. let it = n.sons[i]
  1259. var paramType: PNode = nil
  1260. if i < sonsLen(typ):
  1261. assert(typ.n.sons[i].kind == nkSym)
  1262. paramType = typ.n.sons[i]
  1263. if paramType.typ.isCompileTimeOnly: continue
  1264. if hasArgs: add(r.res, ", ")
  1265. if paramType.isNil:
  1266. genArgNoParam(p, it, r)
  1267. else:
  1268. genArg(p, it, paramType.sym, r, addr emitted)
  1269. inc emitted
  1270. hasArgs = true
  1271. add(r.res, ")")
  1272. when false:
  1273. # XXX look into this:
  1274. let jsp = countJsParams(typ)
  1275. if emitted != jsp and tfVarargs notin typ.flags:
  1276. localError(p.config, n.info, "wrong number of parameters emitted; expected: " & $jsp &
  1277. " but got: " & $emitted)
  1278. r.kind = resExpr
  1279. proc genOtherArg(p: PProc; n: PNode; i: int; typ: PType;
  1280. generated: var int; r: var TCompRes) =
  1281. if i >= n.len:
  1282. globalError(p.config, n.info, "wrong importcpp pattern; expected parameter at position " & $i &
  1283. " but got only: " & $(n.len-1))
  1284. let it = n[i]
  1285. var paramType: PNode = nil
  1286. if i < sonsLen(typ):
  1287. assert(typ.n.sons[i].kind == nkSym)
  1288. paramType = typ.n.sons[i]
  1289. if paramType.typ.isCompileTimeOnly: return
  1290. if paramType.isNil:
  1291. genArgNoParam(p, it, r)
  1292. else:
  1293. genArg(p, it, paramType.sym, r)
  1294. inc generated
  1295. proc genPatternCall(p: PProc; n: PNode; pat: string; typ: PType;
  1296. r: var TCompRes) =
  1297. var i = 0
  1298. var j = 1
  1299. r.kind = resExpr
  1300. while i < pat.len:
  1301. case pat[i]
  1302. of '@':
  1303. var generated = 0
  1304. for k in j ..< n.len:
  1305. if generated > 0: add(r.res, ", ")
  1306. genOtherArg(p, n, k, typ, generated, r)
  1307. inc i
  1308. of '#':
  1309. var generated = 0
  1310. genOtherArg(p, n, j, typ, generated, r)
  1311. inc j
  1312. inc i
  1313. of '\31':
  1314. # unit separator
  1315. add(r.res, "#")
  1316. inc i
  1317. of '\29':
  1318. # group separator
  1319. add(r.res, "@")
  1320. inc i
  1321. else:
  1322. let start = i
  1323. while i < pat.len:
  1324. if pat[i] notin {'@', '#', '\31', '\29'}: inc(i)
  1325. else: break
  1326. if i - 1 >= start:
  1327. add(r.res, substr(pat, start, i - 1))
  1328. proc genInfixCall(p: PProc, n: PNode, r: var TCompRes) =
  1329. # don't call '$' here for efficiency:
  1330. let f = n[0].sym
  1331. if f.loc.r == nil: f.loc.r = mangleName(p.module, f)
  1332. if sfInfixCall in f.flags:
  1333. let pat = n.sons[0].sym.loc.r.data
  1334. internalAssert p.config, pat.len > 0
  1335. if pat.contains({'#', '(', '@'}):
  1336. var typ = skipTypes(n.sons[0].typ, abstractInst)
  1337. assert(typ.kind == tyProc)
  1338. genPatternCall(p, n, pat, typ, r)
  1339. return
  1340. if n.len != 1:
  1341. gen(p, n.sons[1], r)
  1342. if r.typ == etyBaseIndex:
  1343. if r.address == nil:
  1344. globalError(p.config, n.info, "cannot invoke with infix syntax")
  1345. r.res = "$1[$2]" % [r.address, r.res]
  1346. r.address = nil
  1347. r.typ = etyNone
  1348. add(r.res, ".")
  1349. var op: TCompRes
  1350. gen(p, n.sons[0], op)
  1351. add(r.res, op.res)
  1352. genArgs(p, n, r, 2)
  1353. proc genCall(p: PProc, n: PNode, r: var TCompRes) =
  1354. if n.sons[0].kind == nkSym and thisParam(p, n.sons[0].typ) != nil:
  1355. genInfixCall(p, n, r)
  1356. return
  1357. gen(p, n.sons[0], r)
  1358. genArgs(p, n, r)
  1359. if n.typ != nil:
  1360. let t = mapType(n.typ)
  1361. if t == etyBaseIndex:
  1362. let tmp = p.getTemp
  1363. r.address = "($1 = $2, $1)[0]" % [tmp, r.rdLoc]
  1364. r.res = "$1[1]" % [tmp]
  1365. r.tmpLoc = tmp
  1366. r.typ = t
  1367. proc genEcho(p: PProc, n: PNode, r: var TCompRes) =
  1368. let n = n[1].skipConv
  1369. internalAssert p.config, n.kind == nkBracket
  1370. useMagic(p, "toJSStr") # Used in rawEcho
  1371. useMagic(p, "rawEcho")
  1372. add(r.res, "rawEcho(")
  1373. for i in countup(0, sonsLen(n) - 1):
  1374. let it = n.sons[i]
  1375. if it.typ.isCompileTimeOnly: continue
  1376. if i > 0: add(r.res, ", ")
  1377. genArgNoParam(p, it, r)
  1378. add(r.res, ")")
  1379. r.kind = resExpr
  1380. proc putToSeq(s: string, indirect: bool): Rope =
  1381. result = rope(s)
  1382. if indirect: result = "[$1]" % [result]
  1383. proc createVar(p: PProc, typ: PType, indirect: bool): Rope
  1384. proc createRecordVarAux(p: PProc, rec: PNode, excludedFieldIDs: IntSet, output: var Rope) =
  1385. case rec.kind
  1386. of nkRecList:
  1387. for i in countup(0, sonsLen(rec) - 1):
  1388. createRecordVarAux(p, rec.sons[i], excludedFieldIDs, output)
  1389. of nkRecCase:
  1390. createRecordVarAux(p, rec.sons[0], excludedFieldIDs, output)
  1391. for i in countup(1, sonsLen(rec) - 1):
  1392. createRecordVarAux(p, lastSon(rec.sons[i]), excludedFieldIDs, output)
  1393. of nkSym:
  1394. if rec.sym.id notin excludedFieldIDs:
  1395. if output.len > 0: output.add(", ")
  1396. output.addf("$#: ", [mangleName(p.module, rec.sym)])
  1397. output.add(createVar(p, rec.sym.typ, false))
  1398. else: internalError(p.config, rec.info, "createRecordVarAux")
  1399. proc createObjInitList(p: PProc, typ: PType, excludedFieldIDs: IntSet, output: var Rope) =
  1400. var t = typ
  1401. if objHasTypeField(t):
  1402. if output.len > 0: output.add(", ")
  1403. addf(output, "m_type: $1", [genTypeInfo(p, t)])
  1404. while t != nil:
  1405. t = t.skipTypes(skipPtrs)
  1406. createRecordVarAux(p, t.n, excludedFieldIDs, output)
  1407. t = t.sons[0]
  1408. proc arrayTypeForElemType(typ: PType): string =
  1409. # XXX This should also support tyEnum and tyBool
  1410. case typ.kind
  1411. of tyInt, tyInt32: "Int32Array"
  1412. of tyInt16: "Int16Array"
  1413. of tyInt8: "Int8Array"
  1414. of tyUint, tyUint32: "Uint32Array"
  1415. of tyUint16: "Uint16Array"
  1416. of tyUint8: "Uint8Array"
  1417. of tyFloat32: "Float32Array"
  1418. of tyFloat64, tyFloat: "Float64Array"
  1419. else: ""
  1420. proc createVar(p: PProc, typ: PType, indirect: bool): Rope =
  1421. var t = skipTypes(typ, abstractInst)
  1422. case t.kind
  1423. of tyInt..tyInt64, tyUInt..tyUInt64, tyEnum, tyChar:
  1424. result = putToSeq("0", indirect)
  1425. of tyFloat..tyFloat128:
  1426. result = putToSeq("0.0", indirect)
  1427. of tyRange, tyGenericInst, tyAlias, tySink:
  1428. result = createVar(p, lastSon(typ), indirect)
  1429. of tySet:
  1430. result = putToSeq("{}", indirect)
  1431. of tyBool:
  1432. result = putToSeq("false", indirect)
  1433. of tyArray:
  1434. let length = int(lengthOrd(p.config, t))
  1435. let e = elemType(t)
  1436. let jsTyp = arrayTypeForElemType(e)
  1437. if jsTyp.len > 0:
  1438. result = "new $1($2)" % [rope(jsTyp), rope(length)]
  1439. elif length > 32:
  1440. useMagic(p, "arrayConstr")
  1441. # XXX: arrayConstr depends on nimCopy. This line shouldn't be necessary.
  1442. useMagic(p, "nimCopy")
  1443. result = "arrayConstr($1, $2, $3)" % [rope(length),
  1444. createVar(p, e, false), genTypeInfo(p, e)]
  1445. else:
  1446. result = rope("[")
  1447. var i = 0
  1448. while i < length:
  1449. if i > 0: add(result, ", ")
  1450. add(result, createVar(p, e, false))
  1451. inc(i)
  1452. add(result, "]")
  1453. if indirect: result = "[$1]" % [result]
  1454. of tyTuple:
  1455. result = rope("{")
  1456. for i in 0..<t.sonsLen:
  1457. if i > 0: add(result, ", ")
  1458. addf(result, "Field$1: $2", [i.rope,
  1459. createVar(p, t.sons[i], false)])
  1460. add(result, "}")
  1461. if indirect: result = "[$1]" % [result]
  1462. of tyObject:
  1463. var initList: Rope
  1464. createObjInitList(p, t, initIntSet(), initList)
  1465. result = ("{$1}") % [initList]
  1466. if indirect: result = "[$1]" % [result]
  1467. of tyVar, tyPtr, tyLent, tyRef, tyPointer:
  1468. if mapType(p, t) == etyBaseIndex:
  1469. result = putToSeq("[null, 0]", indirect)
  1470. else:
  1471. result = putToSeq("null", indirect)
  1472. of tySequence, tyOpt, tyString, tyCString, tyProc:
  1473. result = putToSeq("null", indirect)
  1474. of tyStatic:
  1475. if t.n != nil:
  1476. result = createVar(p, lastSon t, indirect)
  1477. else:
  1478. internalError(p.config, "createVar: " & $t.kind)
  1479. result = nil
  1480. else:
  1481. internalError(p.config, "createVar: " & $t.kind)
  1482. result = nil
  1483. template returnType: untyped =
  1484. ~""
  1485. proc genVarInit(p: PProc, v: PSym, n: PNode) =
  1486. var
  1487. a: TCompRes
  1488. s: Rope
  1489. varCode: string
  1490. varName = mangleName(p.module, v)
  1491. useReloadingGuard = sfGlobal in v.flags and optHotCodeReloading in p.config.options
  1492. if v.constraint.isNil:
  1493. if useReloadingGuard:
  1494. lineF(p, "var $1;$n", varName)
  1495. lineF(p, "if ($1 === undefined) {$n", varName)
  1496. varCode = $varName
  1497. else:
  1498. varCode = "var $2"
  1499. else:
  1500. varCode = v.constraint.strVal
  1501. if n.kind == nkEmpty:
  1502. if not isIndirect(v) and
  1503. v.typ.kind in {tyVar, tyPtr, tyLent, tyRef} and mapType(p, v.typ) == etyBaseIndex:
  1504. lineF(p, "var $1 = null;$n", [varName])
  1505. lineF(p, "var $1_Idx = 0;$n", [varName])
  1506. else:
  1507. lineF(p, varCode & " = $3;$n",
  1508. [returnType, varName, createVar(p, v.typ, isIndirect(v))])
  1509. else:
  1510. gen(p, n, a)
  1511. case mapType(p, v.typ)
  1512. of etyObject, etySeq:
  1513. if needsNoCopy(p, n):
  1514. s = a.res
  1515. else:
  1516. useMagic(p, "nimCopy")
  1517. s = "nimCopy(null, $1, $2)" % [a.res, genTypeInfo(p, n.typ)]
  1518. of etyBaseIndex:
  1519. let targetBaseIndex = {sfAddrTaken, sfGlobal} * v.flags == {}
  1520. if a.typ == etyBaseIndex:
  1521. if targetBaseIndex:
  1522. lineF(p, varCode & " = $3, $2_Idx = $4;$n",
  1523. [returnType, v.loc.r, a.address, a.res])
  1524. else:
  1525. if isIndirect(v):
  1526. lineF(p, varCode & " = [[$3, $4]];$n",
  1527. [returnType, v.loc.r, a.address, a.res])
  1528. else:
  1529. lineF(p, varCode & " = [$3, $4];$n",
  1530. [returnType, v.loc.r, a.address, a.res])
  1531. else:
  1532. if targetBaseIndex:
  1533. let tmp = p.getTemp
  1534. lineF(p, "var $1 = $2, $3 = $1[0], $3_Idx = $1[1];$n",
  1535. [tmp, a.res, v.loc.r])
  1536. else:
  1537. lineF(p, varCode & " = $3;$n", [returnType, v.loc.r, a.res])
  1538. return
  1539. else:
  1540. s = a.res
  1541. if isIndirect(v):
  1542. lineF(p, varCode & " = [$3];$n", [returnType, v.loc.r, s])
  1543. else:
  1544. lineF(p, varCode & " = $3;$n", [returnType, v.loc.r, s])
  1545. if useReloadingGuard:
  1546. lineF(p, "}$n")
  1547. proc genVarStmt(p: PProc, n: PNode) =
  1548. for i in countup(0, sonsLen(n) - 1):
  1549. var a = n.sons[i]
  1550. if a.kind != nkCommentStmt:
  1551. if a.kind == nkVarTuple:
  1552. let unpacked = lowerTupleUnpacking(p.module.graph, a, p.prc)
  1553. genStmt(p, unpacked)
  1554. else:
  1555. assert(a.kind == nkIdentDefs)
  1556. assert(a.sons[0].kind == nkSym)
  1557. var v = a.sons[0].sym
  1558. if lfNoDecl notin v.loc.flags and sfImportc notin v.flags:
  1559. genLineDir(p, a)
  1560. genVarInit(p, v, a.sons[2])
  1561. proc genConstant(p: PProc, c: PSym) =
  1562. if lfNoDecl notin c.loc.flags and not p.g.generatedSyms.containsOrIncl(c.id):
  1563. let oldBody = p.body
  1564. p.body = nil
  1565. #genLineDir(p, c.ast)
  1566. genVarInit(p, c, c.ast)
  1567. add(p.g.constants, p.body)
  1568. p.body = oldBody
  1569. proc genNew(p: PProc, n: PNode) =
  1570. var a: TCompRes
  1571. gen(p, n.sons[1], a)
  1572. var t = skipTypes(n.sons[1].typ, abstractVar).sons[0]
  1573. if mapType(t) == etyObject:
  1574. lineF(p, "$1 = $2;$n", [a.rdLoc, createVar(p, t, false)])
  1575. elif a.typ == etyBaseIndex:
  1576. lineF(p, "$1 = [$3]; $2 = 0;$n", [a.address, a.res, createVar(p, t, false)])
  1577. else:
  1578. lineF(p, "$1 = [[$2], 0];$n", [a.rdLoc, createVar(p, t, false)])
  1579. proc genNewSeq(p: PProc, n: PNode) =
  1580. var x, y: TCompRes
  1581. gen(p, n.sons[1], x)
  1582. gen(p, n.sons[2], y)
  1583. let t = skipTypes(n.sons[1].typ, abstractVar).sons[0]
  1584. lineF(p, "$1 = new Array($2); for (var i=0;i<$2;++i) {$1[i]=$3;}", [
  1585. x.rdLoc, y.rdLoc, createVar(p, t, false)])
  1586. proc genOrd(p: PProc, n: PNode, r: var TCompRes) =
  1587. case skipTypes(n.sons[1].typ, abstractVar).kind
  1588. of tyEnum, tyInt..tyUInt64, tyChar: gen(p, n.sons[1], r)
  1589. of tyBool: unaryExpr(p, n, r, "", "($1 ? 1:0)")
  1590. else: internalError(p.config, n.info, "genOrd")
  1591. proc genConStrStr(p: PProc, n: PNode, r: var TCompRes) =
  1592. var a: TCompRes
  1593. gen(p, n.sons[1], a)
  1594. r.kind = resExpr
  1595. if skipTypes(n.sons[1].typ, abstractVarRange).kind == tyChar:
  1596. r.res.add("[$1].concat(" % [a.res])
  1597. else:
  1598. r.res.add("($1 || []).concat(" % [a.res])
  1599. for i in countup(2, sonsLen(n) - 2):
  1600. gen(p, n.sons[i], a)
  1601. if skipTypes(n.sons[i].typ, abstractVarRange).kind == tyChar:
  1602. r.res.add("[$1]," % [a.res])
  1603. else:
  1604. r.res.add("$1 || []," % [a.res])
  1605. gen(p, n.sons[sonsLen(n) - 1], a)
  1606. if skipTypes(n.sons[sonsLen(n) - 1].typ, abstractVarRange).kind == tyChar:
  1607. r.res.add("[$1])" % [a.res])
  1608. else:
  1609. r.res.add("$1 || [])" % [a.res])
  1610. proc genToArray(p: PProc; n: PNode; r: var TCompRes) =
  1611. # we map mArray to PHP's array constructor, a mild hack:
  1612. var a, b: TCompRes
  1613. r.kind = resExpr
  1614. r.res = rope("array(")
  1615. let x = skipConv(n[1])
  1616. if x.kind == nkBracket:
  1617. for i in countup(0, x.len - 1):
  1618. let it = x[i]
  1619. if it.kind in {nkPar, nkTupleConstr} and it.len == 2:
  1620. if i > 0: r.res.add(", ")
  1621. gen(p, it[0], a)
  1622. gen(p, it[1], b)
  1623. r.res.add("$# => $#" % [a.rdLoc, b.rdLoc])
  1624. else:
  1625. localError(p.config, it.info, "'toArray' needs tuple constructors")
  1626. else:
  1627. localError(p.config, x.info, "'toArray' needs an array literal")
  1628. r.res.add(")")
  1629. proc genReprAux(p: PProc, n: PNode, r: var TCompRes, magic: string, typ: Rope = nil) =
  1630. useMagic(p, magic)
  1631. add(r.res, magic & "(")
  1632. var a: TCompRes
  1633. gen(p, n.sons[1], a)
  1634. if magic == "reprAny":
  1635. # the pointer argument in reprAny is expandend to
  1636. # (pointedto, pointer), so we need to fill it
  1637. if a.address.isNil:
  1638. add(r.res, a.res)
  1639. add(r.res, ", null")
  1640. else:
  1641. add(r.res, "$1, $2" % [a.address, a.res])
  1642. else:
  1643. add(r.res, a.res)
  1644. if not typ.isNil:
  1645. add(r.res, ", ")
  1646. add(r.res, typ)
  1647. add(r.res, ")")
  1648. proc genRepr(p: PProc, n: PNode, r: var TCompRes) =
  1649. let t = skipTypes(n.sons[1].typ, abstractVarRange)
  1650. case t.kind:
  1651. of tyInt..tyInt64, tyUInt..tyUInt64:
  1652. genReprAux(p, n, r, "reprInt")
  1653. of tyChar:
  1654. genReprAux(p, n, r, "reprChar")
  1655. of tyBool:
  1656. genReprAux(p, n, r, "reprBool")
  1657. of tyFloat..tyFloat128:
  1658. genReprAux(p, n, r, "reprFloat")
  1659. of tyString:
  1660. genReprAux(p, n, r, "reprStr")
  1661. of tyEnum, tyOrdinal:
  1662. genReprAux(p, n, r, "reprEnum", genTypeInfo(p, t))
  1663. of tySet:
  1664. genReprAux(p, n, r, "reprSet", genTypeInfo(p, t))
  1665. of tyEmpty, tyVoid:
  1666. localError(p.config, n.info, "'repr' doesn't support 'void' type")
  1667. of tyPointer:
  1668. genReprAux(p, n, r, "reprPointer")
  1669. of tyOpenArray, tyVarargs:
  1670. genReprAux(p, n, r, "reprJSONStringify")
  1671. else:
  1672. genReprAux(p, n, r, "reprAny", genTypeInfo(p, t))
  1673. proc genOf(p: PProc, n: PNode, r: var TCompRes) =
  1674. var x: TCompRes
  1675. let t = skipTypes(n.sons[2].typ, abstractVarRange+{tyRef, tyPtr, tyLent, tyTypeDesc})
  1676. gen(p, n.sons[1], x)
  1677. if tfFinal in t.flags:
  1678. r.res = "($1.m_type == $2)" % [x.res, genTypeInfo(p, t)]
  1679. else:
  1680. useMagic(p, "isObj")
  1681. r.res = "isObj($1.m_type, $2)" % [x.res, genTypeInfo(p, t)]
  1682. r.kind = resExpr
  1683. proc genReset(p: PProc, n: PNode) =
  1684. var x: TCompRes
  1685. useMagic(p, "genericReset")
  1686. gen(p, n.sons[1], x)
  1687. if x.typ == etyBaseIndex:
  1688. lineF(p, "$1 = null, $2 = 0;$n", [x.address, x.res])
  1689. else:
  1690. let (a, tmp) = maybeMakeTemp(p, n[1], x)
  1691. lineF(p, "$1 = genericReset($3, $2);$n", [a,
  1692. genTypeInfo(p, n.sons[1].typ), tmp])
  1693. proc genMagic(p: PProc, n: PNode, r: var TCompRes) =
  1694. var
  1695. a: TCompRes
  1696. line, filen: Rope
  1697. var op = n.sons[0].sym.magic
  1698. case op
  1699. of mOr: genOr(p, n.sons[1], n.sons[2], r)
  1700. of mAnd: genAnd(p, n.sons[1], n.sons[2], r)
  1701. of mAddI..mStrToStr: arith(p, n, r, op)
  1702. of mRepr: genRepr(p, n, r)
  1703. of mSwap: genSwap(p, n)
  1704. of mUnaryLt:
  1705. # XXX: range checking?
  1706. if not (optOverflowCheck in p.options): unaryExpr(p, n, r, "", "$1 - 1")
  1707. else: unaryExpr(p, n, r, "subInt", "subInt($1, 1)")
  1708. of mAppendStrCh:
  1709. binaryExpr(p, n, r, "addChar",
  1710. "if ($1 != null) { addChar($3, $2); } else { $3 = [$2]; }")
  1711. of mAppendStrStr:
  1712. var lhs, rhs: TCompRes
  1713. gen(p, n[1], lhs)
  1714. gen(p, n[2], rhs)
  1715. let rhsIsLit = n[2].kind in nkStrKinds
  1716. let (a, tmp) = maybeMakeTemp(p, n[1], lhs)
  1717. if skipTypes(n.sons[1].typ, abstractVarRange).kind == tyCString:
  1718. r.res = "if ($1 != null) { $4 += $2; } else { $4 = $2$3; }" % [
  1719. a, rhs.rdLoc, if rhsIsLit: nil else: ~".slice()", tmp]
  1720. else:
  1721. r.res = "if ($1 != null) { $4 = ($4).concat($2); } else { $4 = $2$3; }" % [
  1722. lhs.rdLoc, rhs.rdLoc, if rhsIsLit: nil else: ~".slice()", tmp]
  1723. r.kind = resExpr
  1724. of mAppendSeqElem:
  1725. var x, y: TCompRes
  1726. gen(p, n.sons[1], x)
  1727. gen(p, n.sons[2], y)
  1728. let (a, tmp) = maybeMakeTemp(p, n[1], x)
  1729. if mapType(n[2].typ) == etyBaseIndex:
  1730. let c = "[$1, $2]" % [y.address, y.res]
  1731. r.res = "if ($1 != null) { $3.push($2); } else { $3 = [$2]; }" % [a, c, tmp]
  1732. elif needsNoCopy(p, n[2]):
  1733. r.res = "if ($1 != null) { $3.push($2); } else { $3 = [$2]; }" % [a, y.rdLoc, tmp]
  1734. else:
  1735. useMagic(p, "nimCopy")
  1736. let c = getTemp(p, defineInLocals=false)
  1737. lineF(p, "var $1 = nimCopy(null, $2, $3);$n",
  1738. [c, y.rdLoc, genTypeInfo(p, n[2].typ)])
  1739. r.res = "if ($1 != null) { $3.push($2); } else { $3 = [$2]; }" % [a, c, tmp]
  1740. r.kind = resExpr
  1741. of mConStrStr:
  1742. genConStrStr(p, n, r)
  1743. of mEqStr:
  1744. binaryExpr(p, n, r, "eqStrings", "eqStrings($1, $2)")
  1745. of mLeStr:
  1746. binaryExpr(p, n, r, "cmpStrings", "(cmpStrings($1, $2) <= 0)")
  1747. of mLtStr:
  1748. binaryExpr(p, n, r, "cmpStrings", "(cmpStrings($1, $2) < 0)")
  1749. of mIsNil:
  1750. if mapType(n[1].typ) != etyBaseIndex:
  1751. unaryExpr(p, n, r, "", "($1 === null)")
  1752. else:
  1753. var x: TCompRes
  1754. gen(p, n[1], x)
  1755. r.res = "($# === null && $# === 0)" % [x.address, x.res]
  1756. of mEnumToStr: genRepr(p, n, r)
  1757. of mNew, mNewFinalize: genNew(p, n)
  1758. of mChr: gen(p, n.sons[1], r)
  1759. of mArrToSeq:
  1760. if needsNoCopy(p, n.sons[1]):
  1761. gen(p, n.sons[1], r)
  1762. else:
  1763. var x: TCompRes
  1764. gen(p, n.sons[1], x)
  1765. useMagic(p, "nimCopy")
  1766. r.res = "nimCopy(null, $1, $2)" % [x.rdLoc, genTypeInfo(p, n.typ)]
  1767. of mDestroy: discard "ignore calls to the default destructor"
  1768. of mOrd: genOrd(p, n, r)
  1769. of mLengthStr, mLengthSeq, mLengthOpenArray, mLengthArray:
  1770. unaryExpr(p, n, r, "", "($1 != null ? $2.length : 0)")
  1771. of mXLenStr, mXLenSeq:
  1772. unaryExpr(p, n, r, "", "$1.length")
  1773. of mHigh:
  1774. unaryExpr(p, n, r, "", "($1 != null ? ($2.length-1) : -1)")
  1775. of mInc:
  1776. if n[1].typ.skipTypes(abstractRange).kind in tyUInt .. tyUInt64:
  1777. binaryUintExpr(p, n, r, "+", true)
  1778. else:
  1779. if optOverflowCheck notin p.options: binaryExpr(p, n, r, "", "$1 += $2")
  1780. else: binaryExpr(p, n, r, "addInt", "$1 = addInt($3, $2)")
  1781. of ast.mDec:
  1782. if n[1].typ.skipTypes(abstractRange).kind in tyUInt .. tyUInt64:
  1783. binaryUintExpr(p, n, r, "-", true)
  1784. else:
  1785. if optOverflowCheck notin p.options: binaryExpr(p, n, r, "", "$1 -= $2")
  1786. else: binaryExpr(p, n, r, "subInt", "$1 = subInt($3, $2)")
  1787. of mSetLengthStr:
  1788. binaryExpr(p, n, r, "mnewString", "($1 === null ? $3 = mnewString($2) : $3.length = $2)")
  1789. of mSetLengthSeq:
  1790. var x, y: TCompRes
  1791. gen(p, n.sons[1], x)
  1792. gen(p, n.sons[2], y)
  1793. let t = skipTypes(n.sons[1].typ, abstractVar).sons[0]
  1794. let (a, tmp) = maybeMakeTemp(p, n[1], x)
  1795. let (b, tmp2) = maybeMakeTemp(p, n[2], y)
  1796. r.res = """if ($1 === null) $4 = [];
  1797. if ($4.length < $2) { for (var i=$4.length;i<$5;++i) $4.push($3); }
  1798. else { $4.length = $5; }""" % [a, b, createVar(p, t, false), tmp, tmp2]
  1799. r.kind = resExpr
  1800. of mCard: unaryExpr(p, n, r, "SetCard", "SetCard($1)")
  1801. of mLtSet: binaryExpr(p, n, r, "SetLt", "SetLt($1, $2)")
  1802. of mLeSet: binaryExpr(p, n, r, "SetLe", "SetLe($1, $2)")
  1803. of mEqSet: binaryExpr(p, n, r, "SetEq", "SetEq($1, $2)")
  1804. of mMulSet: binaryExpr(p, n, r, "SetMul", "SetMul($1, $2)")
  1805. of mPlusSet: binaryExpr(p, n, r, "SetPlus", "SetPlus($1, $2)")
  1806. of mMinusSet: binaryExpr(p, n, r, "SetMinus", "SetMinus($1, $2)")
  1807. of mIncl: binaryExpr(p, n, r, "", "$1[$2] = true")
  1808. of mExcl: binaryExpr(p, n, r, "", "delete $1[$2]")
  1809. of mInSet:
  1810. binaryExpr(p, n, r, "", "($1[$2] != undefined)")
  1811. of mNewSeq: genNewSeq(p, n)
  1812. of mNewSeqOfCap: unaryExpr(p, n, r, "", "[]")
  1813. of mOf: genOf(p, n, r)
  1814. of mReset: genReset(p, n)
  1815. of mEcho: genEcho(p, n, r)
  1816. of mNLen..mNError, mSlurp, mStaticExec:
  1817. localError(p.config, n.info, errXMustBeCompileTime % n.sons[0].sym.name.s)
  1818. of mCopyStr:
  1819. binaryExpr(p, n, r, "", "($1.slice($2))")
  1820. of mNewString: unaryExpr(p, n, r, "mnewString", "mnewString($1)")
  1821. of mNewStringOfCap:
  1822. unaryExpr(p, n, r, "mnewString", "mnewString(0)")
  1823. of mDotDot:
  1824. genProcForSymIfNeeded(p, n.sons[0].sym)
  1825. genCall(p, n, r)
  1826. of mParseBiggestFloat:
  1827. useMagic(p, "nimParseBiggestFloat")
  1828. genCall(p, n, r)
  1829. of mArray:
  1830. genCall(p, n, r)
  1831. else:
  1832. genCall(p, n, r)
  1833. #else internalError(p.config, e.info, 'genMagic: ' + magicToStr[op]);
  1834. proc genSetConstr(p: PProc, n: PNode, r: var TCompRes) =
  1835. var
  1836. a, b: TCompRes
  1837. useMagic(p, "setConstr")
  1838. r.res = rope("setConstr(")
  1839. r.kind = resExpr
  1840. for i in countup(0, sonsLen(n) - 1):
  1841. if i > 0: add(r.res, ", ")
  1842. var it = n.sons[i]
  1843. if it.kind == nkRange:
  1844. gen(p, it.sons[0], a)
  1845. gen(p, it.sons[1], b)
  1846. addf(r.res, "[$1, $2]", [a.res, b.res])
  1847. else:
  1848. gen(p, it, a)
  1849. add(r.res, a.res)
  1850. add(r.res, ")")
  1851. # emit better code for constant sets:
  1852. if isDeepConstExpr(n):
  1853. inc(p.g.unique)
  1854. let tmp = rope("ConstSet") & rope(p.g.unique)
  1855. addf(p.g.constants, "var $1 = $2;$n", [tmp, r.res])
  1856. r.res = tmp
  1857. proc genArrayConstr(p: PProc, n: PNode, r: var TCompRes) =
  1858. var a: TCompRes
  1859. r.res = rope("[")
  1860. r.kind = resExpr
  1861. for i in countup(0, sonsLen(n) - 1):
  1862. if i > 0: add(r.res, ", ")
  1863. gen(p, n.sons[i], a)
  1864. if a.typ == etyBaseIndex:
  1865. addf(r.res, "[$1, $2]", [a.address, a.res])
  1866. else:
  1867. add(r.res, a.res)
  1868. add(r.res, "]")
  1869. proc genTupleConstr(p: PProc, n: PNode, r: var TCompRes) =
  1870. var a: TCompRes
  1871. r.res = rope("{")
  1872. r.kind = resExpr
  1873. for i in countup(0, sonsLen(n) - 1):
  1874. if i > 0: add(r.res, ", ")
  1875. var it = n.sons[i]
  1876. if it.kind == nkExprColonExpr: it = it.sons[1]
  1877. gen(p, it, a)
  1878. if a.typ == etyBaseIndex:
  1879. addf(r.res, "Field$#: [$#, $#]", [i.rope, a.address, a.res])
  1880. else:
  1881. addf(r.res, "Field$#: $#", [i.rope, a.res])
  1882. r.res.add("}")
  1883. proc genObjConstr(p: PProc, n: PNode, r: var TCompRes) =
  1884. var a: TCompRes
  1885. r.kind = resExpr
  1886. var initList : Rope
  1887. var fieldIDs = initIntSet()
  1888. for i in countup(1, sonsLen(n) - 1):
  1889. if i > 1: add(initList, ", ")
  1890. var it = n.sons[i]
  1891. internalAssert p.config, it.kind == nkExprColonExpr
  1892. let val = it.sons[1]
  1893. gen(p, val, a)
  1894. var f = it.sons[0].sym
  1895. if f.loc.r == nil: f.loc.r = mangleName(p.module, f)
  1896. fieldIDs.incl(f.id)
  1897. let typ = val.typ.skipTypes(abstractInst)
  1898. if (typ.kind in IntegralTypes+{tyCstring, tyRef, tyPtr} and
  1899. mapType(p, typ) != etyBaseIndex) or
  1900. a.typ == etyBaseIndex or
  1901. needsNoCopy(p, it.sons[1]):
  1902. discard
  1903. else:
  1904. useMagic(p, "nimCopy")
  1905. a.res = "nimCopy(null, $1, $2)" % [a.rdLoc, genTypeInfo(p, typ)]
  1906. if a.typ == etyBaseIndex:
  1907. addf(initList, "$#: [$#, $#]", [f.loc.r, a.address, a.res])
  1908. else:
  1909. addf(initList, "$#: $#", [f.loc.r, a.res])
  1910. let t = skipTypes(n.typ, abstractInst + skipPtrs)
  1911. createObjInitList(p, t, fieldIDs, initList)
  1912. r.res = ("{$1}") % [initList]
  1913. proc genConv(p: PProc, n: PNode, r: var TCompRes) =
  1914. var dest = skipTypes(n.typ, abstractVarRange)
  1915. var src = skipTypes(n.sons[1].typ, abstractVarRange)
  1916. gen(p, n.sons[1], r)
  1917. if dest.kind == src.kind:
  1918. # no-op conversion
  1919. return
  1920. case dest.kind:
  1921. of tyBool:
  1922. r.res = "(!!($1))" % [r.res]
  1923. r.kind = resExpr
  1924. of tyInt:
  1925. r.res = "(($1)|0)" % [r.res]
  1926. else:
  1927. # TODO: What types must we handle here?
  1928. discard
  1929. proc upConv(p: PProc, n: PNode, r: var TCompRes) =
  1930. gen(p, n.sons[0], r) # XXX
  1931. proc genRangeChck(p: PProc, n: PNode, r: var TCompRes, magic: string) =
  1932. var a, b: TCompRes
  1933. gen(p, n.sons[0], r)
  1934. if optRangeCheck in p.options:
  1935. gen(p, n.sons[1], a)
  1936. gen(p, n.sons[2], b)
  1937. useMagic(p, "chckRange")
  1938. r.res = "chckRange($1, $2, $3)" % [r.res, a.res, b.res]
  1939. r.kind = resExpr
  1940. proc convStrToCStr(p: PProc, n: PNode, r: var TCompRes) =
  1941. # we do an optimization here as this is likely to slow down
  1942. # much of the code otherwise:
  1943. if n.sons[0].kind == nkCStringToString:
  1944. gen(p, n.sons[0].sons[0], r)
  1945. else:
  1946. gen(p, n.sons[0], r)
  1947. if r.res == nil: internalError(p.config, n.info, "convStrToCStr")
  1948. useMagic(p, "toJSStr")
  1949. r.res = "toJSStr($1)" % [r.res]
  1950. r.kind = resExpr
  1951. proc convCStrToStr(p: PProc, n: PNode, r: var TCompRes) =
  1952. # we do an optimization here as this is likely to slow down
  1953. # much of the code otherwise:
  1954. if n.sons[0].kind == nkStringToCString:
  1955. gen(p, n.sons[0].sons[0], r)
  1956. else:
  1957. gen(p, n.sons[0], r)
  1958. if r.res == nil: internalError(p.config, n.info, "convCStrToStr")
  1959. useMagic(p, "cstrToNimstr")
  1960. r.res = "cstrToNimstr($1)" % [r.res]
  1961. r.kind = resExpr
  1962. proc genReturnStmt(p: PProc, n: PNode) =
  1963. if p.procDef == nil: internalError(p.config, n.info, "genReturnStmt")
  1964. p.beforeRetNeeded = true
  1965. if n.sons[0].kind != nkEmpty:
  1966. genStmt(p, n.sons[0])
  1967. else:
  1968. genLineDir(p, n)
  1969. lineF(p, "break BeforeRet;$n", [])
  1970. proc frameCreate(p: PProc; procname, filename: Rope): Rope =
  1971. let frameFmt =
  1972. "var F={procname:$1,prev:framePtr,filename:$2,line:0};$n"
  1973. result = p.indentLine(frameFmt % [procname, filename])
  1974. result.add p.indentLine(ropes.`%`("framePtr = F;$n", []))
  1975. proc frameDestroy(p: PProc): Rope =
  1976. result = p.indentLine rope(("framePtr = F.prev;") & "\L")
  1977. proc genProcBody(p: PProc, prc: PSym): Rope =
  1978. if hasFrameInfo(p):
  1979. result = frameCreate(p,
  1980. makeJSString(prc.owner.name.s & '.' & prc.name.s),
  1981. makeJSString(toFilename(p.config, prc.info)))
  1982. else:
  1983. result = nil
  1984. if p.beforeRetNeeded:
  1985. result.add p.indentLine(~"BeforeRet: do {$n")
  1986. result.add p.body
  1987. result.add p.indentLine(~"} while (false);$n")
  1988. else:
  1989. add(result, p.body)
  1990. if prc.typ.callConv == ccSysCall:
  1991. result = ("try {$n$1} catch (e) {$n" &
  1992. " alert(\"Unhandled exception:\\n\" + e.message + \"\\n\"$n}") % [result]
  1993. if hasFrameInfo(p):
  1994. add(result, frameDestroy(p))
  1995. proc optionaLine(p: Rope): Rope =
  1996. if p == nil:
  1997. return nil
  1998. else:
  1999. return p & "\L"
  2000. proc genProc(oldProc: PProc, prc: PSym): Rope =
  2001. var
  2002. resultSym: PSym
  2003. a: TCompRes
  2004. #if gVerbosity >= 3:
  2005. # echo "BEGIN generating code for: " & prc.name.s
  2006. var p = newProc(oldProc.g, oldProc.module, prc.ast, prc.options)
  2007. p.up = oldProc
  2008. var returnStmt: Rope = nil
  2009. var resultAsgn: Rope = nil
  2010. var name = mangleName(p.module, prc)
  2011. let header = generateHeader(p, prc.typ)
  2012. if prc.typ.sons[0] != nil and sfPure notin prc.flags:
  2013. resultSym = prc.ast.sons[resultPos].sym
  2014. let mname = mangleName(p.module, resultSym)
  2015. if not isindirect(resultSym) and
  2016. resultSym.typ.kind in {tyVar, tyPtr, tyLent, tyRef} and
  2017. mapType(p, resultSym.typ) == etyBaseIndex:
  2018. resultAsgn = p.indentLine(("var $# = null;$n") % [mname])
  2019. resultAsgn.add p.indentLine("var $#_Idx = 0;$n" % [mname])
  2020. else:
  2021. let resVar = createVar(p, resultSym.typ, isIndirect(resultSym))
  2022. resultAsgn = p.indentLine(("var $# = $#;$n") % [mname, resVar])
  2023. gen(p, prc.ast.sons[resultPos], a)
  2024. if mapType(p, resultSym.typ) == etyBaseIndex:
  2025. returnStmt = "return [$#, $#];$n" % [a.address, a.res]
  2026. else:
  2027. returnStmt = "return $#;$n" % [a.res]
  2028. let transformed_body = transformBody(oldProc.module.graph, prc, cache = false)
  2029. p.nested: genStmt(p, transformed_body)
  2030. var def: Rope
  2031. if not prc.constraint.isNil:
  2032. def = (prc.constraint.strVal & " {$n$#$#$#$#$#") %
  2033. [ returnType,
  2034. name,
  2035. header,
  2036. optionaLine(p.globals),
  2037. optionaLine(p.locals),
  2038. optionaLine(resultAsgn),
  2039. optionaLine(genProcBody(p, prc)),
  2040. optionaLine(p.indentLine(returnStmt))]
  2041. else:
  2042. result = ~"\L"
  2043. if optHotCodeReloading in p.config.options:
  2044. # Here, we introduce thunks that create the equivalent of a jump table
  2045. # for all global functions, because references to them may be stored
  2046. # in JavaScript variables. The added indirection ensures that such
  2047. # references will end up calling the reloaded code.
  2048. var thunkName = name
  2049. name = name & "IMLP"
  2050. result.add("function $#() { return $#.apply(this, arguments); }$n" %
  2051. [thunkName, name])
  2052. def = "function $#($#) {$n$#$#$#$#$#" %
  2053. [ name,
  2054. header,
  2055. optionaLine(p.globals),
  2056. optionaLine(p.locals),
  2057. optionaLine(resultAsgn),
  2058. optionaLine(genProcBody(p, prc)),
  2059. optionaLine(p.indentLine(returnStmt))]
  2060. dec p.extraIndent
  2061. result.add p.indentLine(def)
  2062. result.add p.indentLine(~"}$n")
  2063. #if gVerbosity >= 3:
  2064. # echo "END generated code for: " & prc.name.s
  2065. proc genStmt(p: PProc, n: PNode) =
  2066. var r: TCompRes
  2067. gen(p, n, r)
  2068. if r.res != nil: lineF(p, "$#;$n", [r.res])
  2069. proc genPragma(p: PProc, n: PNode) =
  2070. for it in n.sons:
  2071. case whichPragma(it)
  2072. of wEmit: genAsmOrEmitStmt(p, it.sons[1])
  2073. else: discard
  2074. proc genCast(p: PProc, n: PNode, r: var TCompRes) =
  2075. var dest = skipTypes(n.typ, abstractVarRange)
  2076. var src = skipTypes(n.sons[1].typ, abstractVarRange)
  2077. gen(p, n.sons[1], r)
  2078. if dest.kind == src.kind:
  2079. # no-op conversion
  2080. return
  2081. let toInt = (dest.kind in tyInt..tyInt32)
  2082. let toUint = (dest.kind in tyUInt..tyUInt32)
  2083. let fromInt = (src.kind in tyInt..tyInt32)
  2084. let fromUint = (src.kind in tyUInt..tyUInt32)
  2085. if toUint and (fromInt or fromUint):
  2086. let trimmer = unsignedTrimmer(dest.size)
  2087. r.res = "($1 $2)" % [r.res, trimmer]
  2088. elif toInt:
  2089. if fromInt:
  2090. let trimmer = unsignedTrimmer(dest.size)
  2091. r.res = "($1 $2)" % [r.res, trimmer]
  2092. elif fromUint:
  2093. if src.size == 4 and dest.size == 4:
  2094. # XXX prevent multi evaluations
  2095. r.res = "($1|0)" % [r.res]
  2096. else:
  2097. let trimmer = unsignedTrimmer(dest.size)
  2098. let minuend = case dest.size
  2099. of 1: "0xfe"
  2100. of 2: "0xfffe"
  2101. of 4: "0xfffffffe"
  2102. else: ""
  2103. r.res = "($1 - ($2 $3))" % [rope minuend, r.res, trimmer]
  2104. elif (src.kind == tyPtr and mapType(p, src) == etyObject) and dest.kind == tyPointer:
  2105. r.address = r.res
  2106. r.res = ~"null"
  2107. r.typ = etyBaseIndex
  2108. elif (dest.kind == tyPtr and mapType(p, dest) == etyObject) and src.kind == tyPointer:
  2109. r.res = r.address
  2110. r.typ = etyObject
  2111. proc gen(p: PProc, n: PNode, r: var TCompRes) =
  2112. r.typ = etyNone
  2113. if r.kind != resCallee: r.kind = resNone
  2114. #r.address = nil
  2115. r.res = nil
  2116. case n.kind
  2117. of nkSym:
  2118. genSym(p, n, r)
  2119. of nkCharLit..nkUInt64Lit:
  2120. if n.typ.kind == tyBool:
  2121. r.res = if n.intVal == 0: rope"false" else: rope"true"
  2122. else:
  2123. r.res = rope(n.intVal)
  2124. r.kind = resExpr
  2125. of nkNilLit:
  2126. if isEmptyType(n.typ):
  2127. discard
  2128. elif mapType(p, n.typ) == etyBaseIndex:
  2129. r.typ = etyBaseIndex
  2130. r.address = rope"null"
  2131. r.res = rope"0"
  2132. r.kind = resExpr
  2133. else:
  2134. r.res = rope"null"
  2135. r.kind = resExpr
  2136. of nkStrLit..nkTripleStrLit:
  2137. if skipTypes(n.typ, abstractVarRange).kind == tyString:
  2138. if n.strVal.len != 0:
  2139. useMagic(p, "makeNimstrLit")
  2140. r.res = "makeNimstrLit($1)" % [makeJSString(n.strVal)]
  2141. else:
  2142. r.res = rope"[]"
  2143. else:
  2144. r.res = makeJSString(n.strVal, false)
  2145. r.kind = resExpr
  2146. of nkFloatLit..nkFloat64Lit:
  2147. let f = n.floatVal
  2148. case classify(f)
  2149. of fcNaN:
  2150. r.res = rope"NaN"
  2151. of fcNegZero:
  2152. r.res = rope"-0.0"
  2153. of fcZero:
  2154. r.res = rope"0.0"
  2155. of fcInf:
  2156. r.res = rope"Infinity"
  2157. of fcNegInf:
  2158. r.res = rope"-Infinity"
  2159. else: r.res = rope(f.toStrMaxPrecision)
  2160. r.kind = resExpr
  2161. of nkCallKinds:
  2162. if isEmptyType(n.typ): genLineDir(p, n)
  2163. if (n.sons[0].kind == nkSym) and (n.sons[0].sym.magic != mNone):
  2164. genMagic(p, n, r)
  2165. elif n.sons[0].kind == nkSym and sfInfixCall in n.sons[0].sym.flags and
  2166. n.len >= 1:
  2167. genInfixCall(p, n, r)
  2168. else:
  2169. genCall(p, n, r)
  2170. of nkClosure: gen(p, n[0], r)
  2171. of nkCurly: genSetConstr(p, n, r)
  2172. of nkBracket: genArrayConstr(p, n, r)
  2173. of nkPar, nkTupleConstr: genTupleConstr(p, n, r)
  2174. of nkObjConstr: genObjConstr(p, n, r)
  2175. of nkHiddenStdConv, nkHiddenSubConv, nkConv: genConv(p, n, r)
  2176. of nkAddr, nkHiddenAddr:
  2177. genAddr(p, n, r)
  2178. of nkDerefExpr, nkHiddenDeref: genDeref(p, n, r)
  2179. of nkBracketExpr: genArrayAccess(p, n, r)
  2180. of nkDotExpr: genFieldAccess(p, n, r)
  2181. of nkCheckedFieldExpr: genCheckedFieldOp(p, n, nil, r)
  2182. of nkObjDownConv: gen(p, n.sons[0], r)
  2183. of nkObjUpConv: upConv(p, n, r)
  2184. of nkCast: genCast(p, n, r)
  2185. of nkChckRangeF: genRangeChck(p, n, r, "chckRangeF")
  2186. of nkChckRange64: genRangeChck(p, n, r, "chckRange64")
  2187. of nkChckRange: genRangeChck(p, n, r, "chckRange")
  2188. of nkStringToCString: convStrToCStr(p, n, r)
  2189. of nkCStringToString: convCStrToStr(p, n, r)
  2190. of nkEmpty: discard
  2191. of nkLambdaKinds:
  2192. let s = n.sons[namePos].sym
  2193. discard mangleName(p.module, s)
  2194. r.res = s.loc.r
  2195. if lfNoDecl in s.loc.flags or s.magic != mNone: discard
  2196. elif not p.g.generatedSyms.containsOrIncl(s.id):
  2197. add(p.locals, genProc(p, s))
  2198. of nkType: r.res = genTypeInfo(p, n.typ)
  2199. of nkStmtList, nkStmtListExpr:
  2200. # this shows the distinction is nice for backends and should be kept
  2201. # in the frontend
  2202. let isExpr = not isEmptyType(n.typ)
  2203. for i in countup(0, sonsLen(n) - 1 - isExpr.ord):
  2204. genStmt(p, n.sons[i])
  2205. if isExpr:
  2206. gen(p, lastSon(n), r)
  2207. of nkBlockStmt, nkBlockExpr: genBlock(p, n, r)
  2208. of nkIfStmt, nkIfExpr: genIf(p, n, r)
  2209. of nkWhen:
  2210. # This is "when nimvm" node
  2211. gen(p, n.sons[1].sons[0], r)
  2212. of nkWhileStmt: genWhileStmt(p, n)
  2213. of nkVarSection, nkLetSection: genVarStmt(p, n)
  2214. of nkConstSection: discard
  2215. of nkForStmt, nkParForStmt:
  2216. internalError(p.config, n.info, "for statement not eliminated")
  2217. of nkCaseStmt: genCaseJS(p, n, r)
  2218. of nkReturnStmt: genReturnStmt(p, n)
  2219. of nkBreakStmt: genBreakStmt(p, n)
  2220. of nkAsgn: genAsgn(p, n)
  2221. of nkFastAsgn: genFastAsgn(p, n)
  2222. of nkDiscardStmt:
  2223. if n.sons[0].kind != nkEmpty:
  2224. genLineDir(p, n)
  2225. gen(p, n.sons[0], r)
  2226. of nkAsmStmt: genAsmOrEmitStmt(p, n)
  2227. of nkTryStmt: genTry(p, n, r)
  2228. of nkRaiseStmt: genRaiseStmt(p, n)
  2229. of nkTypeSection, nkCommentStmt, nkIteratorDef, nkIncludeStmt,
  2230. nkImportStmt, nkImportExceptStmt, nkExportStmt, nkExportExceptStmt,
  2231. nkFromStmt, nkTemplateDef, nkMacroDef, nkStaticStmt: discard
  2232. of nkPragma: genPragma(p, n)
  2233. of nkProcDef, nkFuncDef, nkMethodDef, nkConverterDef:
  2234. var s = n.sons[namePos].sym
  2235. if {sfExportc, sfCompilerProc} * s.flags == {sfExportc}:
  2236. genSym(p, n.sons[namePos], r)
  2237. r.res = nil
  2238. of nkGotoState, nkState:
  2239. internalError(p.config, n.info, "first class iterators not implemented")
  2240. of nkPragmaBlock: gen(p, n.lastSon, r)
  2241. of nkComesFrom:
  2242. discard "XXX to implement for better stack traces"
  2243. else: internalError(p.config, n.info, "gen: unknown node type: " & $n.kind)
  2244. proc newModule(g: ModuleGraph; module: PSym): BModule =
  2245. new(result)
  2246. result.module = module
  2247. result.sigConflicts = initCountTable[SigHash]()
  2248. if g.backend == nil:
  2249. g.backend = newGlobals()
  2250. result.graph = g
  2251. result.config = g.config
  2252. proc genHeader(): Rope =
  2253. result = (
  2254. "/* Generated by the Nim Compiler v$1 */$n" &
  2255. "/* (c) " & copyrightYear & " Andreas Rumpf */$n$n" &
  2256. "var framePtr = null;$n" &
  2257. "var excHandler = 0;$n" &
  2258. "var lastJSError = null;$n" &
  2259. "if (typeof Int8Array === 'undefined') Int8Array = Array;$n" &
  2260. "if (typeof Int16Array === 'undefined') Int16Array = Array;$n" &
  2261. "if (typeof Int32Array === 'undefined') Int32Array = Array;$n" &
  2262. "if (typeof Uint8Array === 'undefined') Uint8Array = Array;$n" &
  2263. "if (typeof Uint16Array === 'undefined') Uint16Array = Array;$n" &
  2264. "if (typeof Uint32Array === 'undefined') Uint32Array = Array;$n" &
  2265. "if (typeof Float32Array === 'undefined') Float32Array = Array;$n" &
  2266. "if (typeof Float64Array === 'undefined') Float64Array = Array;$n") %
  2267. [rope(VersionAsString)]
  2268. proc genModule(p: PProc, n: PNode) =
  2269. if optStackTrace in p.options:
  2270. add(p.body, frameCreate(p,
  2271. makeJSString("module " & p.module.module.name.s),
  2272. makeJSString(toFilename(p.config, p.module.module.info))))
  2273. let n_transformed = transformStmt(p.module.graph, p.module.module, n)
  2274. genStmt(p, n_transformed)
  2275. if optStackTrace in p.options:
  2276. add(p.body, frameDestroy(p))
  2277. proc myProcess(b: PPassContext, n: PNode): PNode =
  2278. result = n
  2279. let m = BModule(b)
  2280. if passes.skipCodegen(m.config, n): return n
  2281. if m.module == nil: internalError(m.config, n.info, "myProcess")
  2282. let globals = PGlobals(m.graph.backend)
  2283. var p = newProc(globals, m, nil, m.module.options)
  2284. p.unique = globals.unique
  2285. genModule(p, n)
  2286. add(p.g.code, p.locals)
  2287. add(p.g.code, p.body)
  2288. proc wholeCode(graph: ModuleGraph; m: BModule): Rope =
  2289. let globals = PGlobals(graph.backend)
  2290. for prc in globals.forwarded:
  2291. if not globals.generatedSyms.containsOrIncl(prc.id):
  2292. var p = newProc(globals, m, nil, m.module.options)
  2293. attachProc(p, prc)
  2294. var disp = generateMethodDispatchers(graph)
  2295. for i in 0..sonsLen(disp)-1:
  2296. let prc = disp.sons[i].sym
  2297. if not globals.generatedSyms.containsOrIncl(prc.id):
  2298. var p = newProc(globals, m, nil, m.module.options)
  2299. attachProc(p, prc)
  2300. result = globals.typeInfo & globals.constants & globals.code
  2301. proc getClassName(t: PType): Rope =
  2302. var s = t.sym
  2303. if s.isNil or sfAnon in s.flags:
  2304. s = skipTypes(t, abstractPtrs).sym
  2305. if s.isNil or sfAnon in s.flags:
  2306. doAssert(false, "cannot retrieve class name")
  2307. if s.loc.r != nil: result = s.loc.r
  2308. else: result = rope(s.name.s)
  2309. proc genClass(conf: ConfigRef; obj: PType; content: Rope; ext: string) =
  2310. let cls = getClassName(obj)
  2311. let t = skipTypes(obj, abstractPtrs)
  2312. let extends = if t.kind == tyObject and t.sons[0] != nil:
  2313. " extends " & getClassName(t.sons[0])
  2314. else: nil
  2315. let result = ("<?php$n" &
  2316. "/* Generated by the Nim Compiler v$# */$n" &
  2317. "/* (c) " & copyrightYear & " Andreas Rumpf */$n$n" &
  2318. "require_once \"nimsystem.php\";$n" &
  2319. "class $#$# {$n$#$n}$n") %
  2320. [rope(VersionAsString), cls, extends, content]
  2321. let outfile = changeFileExt(completeCFilePath(conf, AbsoluteFile($cls)), ext)
  2322. discard writeRopeIfNotEqual(result, outfile)
  2323. proc myClose(graph: ModuleGraph; b: PPassContext, n: PNode): PNode =
  2324. result = myProcess(b, n)
  2325. var m = BModule(b)
  2326. if passes.skipCodegen(m.config, n): return n
  2327. if sfMainModule in m.module.flags:
  2328. let globals = PGlobals(graph.backend)
  2329. let ext = "js"
  2330. let f = if globals.classes.len == 0: toFilename(m.config, FileIndex m.module.position)
  2331. else: "nimsystem"
  2332. let code = wholeCode(graph, m)
  2333. let outfile =
  2334. if not m.config.outFile.isEmpty:
  2335. if m.config.outFile.string.isAbsolute: m.config.outFile
  2336. else: AbsoluteFile(getCurrentDir() / m.config.outFile.string)
  2337. else:
  2338. changeFileExt(completeCFilePath(m.config, AbsoluteFile f), ext)
  2339. let (outDir, _, _) = splitFile(outfile)
  2340. if not outDir.isEmpty:
  2341. createDir(outDir)
  2342. discard writeRopeIfNotEqual(genHeader() & code, outfile)
  2343. for obj, content in items(globals.classes):
  2344. genClass(m.config, obj, content, ext)
  2345. proc myOpen(graph: ModuleGraph; s: PSym): PPassContext =
  2346. result = newModule(graph, s)
  2347. const JSgenPass* = makePass(myOpen, myProcess, myClose)