jsgen.nim 75 KB

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