jsgen.nim 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360
  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. 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, tyUncheckedArray:
  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 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. if catchBranchesExist:
  567. addf(p.body, "--excHandler;$n} catch (EXC) {$n var prevJSError = lastJSError;$n" &
  568. " lastJSError = EXC;$n --excHandler;$n", [])
  569. line(p, "framePtr = $1;$n" % [tmpFramePtr])
  570. while i < length and n.sons[i].kind == nkExceptBranch:
  571. let blen = sonsLen(n.sons[i])
  572. if blen == 1:
  573. # general except section:
  574. generalCatchBranchExists = true
  575. if i > 1: lineF(p, "else {$n", [])
  576. gen(p, n.sons[i].sons[0], a)
  577. moveInto(p, a, r)
  578. if i > 1: lineF(p, "}$n", [])
  579. else:
  580. var orExpr: Rope = nil
  581. var excAlias: PNode = nil
  582. useMagic(p, "isObj")
  583. for j in countup(0, blen - 2):
  584. var throwObj: PNode
  585. let it = n.sons[i].sons[j]
  586. if it.isInfixAs():
  587. throwObj = it[1]
  588. excAlias = it[2]
  589. # If this is a ``except exc as sym`` branch there must be no following
  590. # nodes
  591. doAssert orExpr == nil
  592. elif it.kind == nkType:
  593. throwObj = it
  594. else:
  595. internalError(p.config, n.info, "genTryStmt")
  596. if orExpr != nil: add(orExpr, "||")
  597. # Generate the correct type checking code depending on whether this is a
  598. # NIM-native or a JS-native exception
  599. # if isJsObject(throwObj.typ):
  600. if isImportedException(throwObj.typ, p.config):
  601. addf(orExpr, "lastJSError instanceof $1",
  602. [throwObj.typ.sym.loc.r])
  603. else:
  604. addf(orExpr, "isObj(lastJSError.m_type, $1)",
  605. [genTypeInfo(p, throwObj.typ)])
  606. if i > 1: line(p, "else ")
  607. lineF(p, "if (lastJSError && ($1)) {$n", [orExpr])
  608. # If some branch requires a local alias introduce it here. This is needed
  609. # since JS cannot do ``catch x as y``.
  610. if excAlias != nil:
  611. excAlias.sym.loc.r = mangleName(p.module, excAlias.sym)
  612. lineF(p, "var $1 = lastJSError;$n", excAlias.sym.loc.r)
  613. gen(p, n.sons[i].sons[blen - 1], a)
  614. moveInto(p, a, r)
  615. lineF(p, "}$n", [])
  616. inc(i)
  617. if catchBranchesExist:
  618. if not generalCatchBranchExists:
  619. useMagic(p, "reraiseException")
  620. line(p, "else {\L")
  621. line(p, "\treraiseException();\L")
  622. line(p, "}\L")
  623. lineF(p, "lastJSError = prevJSError;$n")
  624. line(p, "} finally {\L")
  625. line(p, "framePtr = $1;$n" % [tmpFramePtr])
  626. if i < length and n.sons[i].kind == nkFinally:
  627. genStmt(p, n.sons[i].sons[0])
  628. line(p, "}\L")
  629. proc genRaiseStmt(p: PProc, n: PNode) =
  630. if n.sons[0].kind != nkEmpty:
  631. var a: TCompRes
  632. gen(p, n.sons[0], a)
  633. let typ = skipTypes(n.sons[0].typ, abstractPtrs)
  634. genLineDir(p, n)
  635. useMagic(p, "raiseException")
  636. lineF(p, "raiseException($1, $2);$n",
  637. [a.rdLoc, makeJSString(typ.sym.name.s)])
  638. else:
  639. genLineDir(p, n)
  640. useMagic(p, "reraiseException")
  641. line(p, "reraiseException();\L")
  642. proc genCaseJS(p: PProc, n: PNode, r: var TCompRes) =
  643. var
  644. cond, stmt: TCompRes
  645. genLineDir(p, n)
  646. gen(p, n.sons[0], cond)
  647. let stringSwitch = skipTypes(n.sons[0].typ, abstractVar).kind == tyString
  648. if stringSwitch:
  649. useMagic(p, "toJSStr")
  650. lineF(p, "switch (toJSStr($1)) {$n", [cond.rdLoc])
  651. else:
  652. lineF(p, "switch ($1) {$n", [cond.rdLoc])
  653. if not isEmptyType(n.typ):
  654. r.kind = resVal
  655. r.res = getTemp(p)
  656. for i in countup(1, sonsLen(n) - 1):
  657. let it = n.sons[i]
  658. case it.kind
  659. of nkOfBranch:
  660. for j in countup(0, sonsLen(it) - 2):
  661. let e = it.sons[j]
  662. if e.kind == nkRange:
  663. var v = copyNode(e.sons[0])
  664. while v.intVal <= e.sons[1].intVal:
  665. gen(p, v, cond)
  666. lineF(p, "case $1:$n", [cond.rdLoc])
  667. inc(v.intVal)
  668. else:
  669. if stringSwitch:
  670. case e.kind
  671. of nkStrLit..nkTripleStrLit: lineF(p, "case $1:$n",
  672. [makeJSString(e.strVal, false)])
  673. else: internalError(p.config, e.info, "jsgen.genCaseStmt: 2")
  674. else:
  675. gen(p, e, cond)
  676. lineF(p, "case $1:$n", [cond.rdLoc])
  677. p.nested:
  678. gen(p, lastSon(it), stmt)
  679. moveInto(p, stmt, r)
  680. lineF(p, "break;$n", [])
  681. of nkElse:
  682. lineF(p, "default: $n", [])
  683. p.nested:
  684. gen(p, it.sons[0], stmt)
  685. moveInto(p, stmt, r)
  686. lineF(p, "break;$n", [])
  687. else: internalError(p.config, it.info, "jsgen.genCaseStmt")
  688. lineF(p, "}$n", [])
  689. proc genBlock(p: PProc, n: PNode, r: var TCompRes) =
  690. inc(p.unique)
  691. let idx = len(p.blocks)
  692. if n.sons[0].kind != nkEmpty:
  693. # named block?
  694. if (n.sons[0].kind != nkSym): internalError(p.config, n.info, "genBlock")
  695. var sym = n.sons[0].sym
  696. sym.loc.k = locOther
  697. sym.position = idx+1
  698. let labl = p.unique
  699. lineF(p, "L$1: do {$n", [labl.rope])
  700. setLen(p.blocks, idx + 1)
  701. p.blocks[idx].id = - p.unique # negative because it isn't used yet
  702. gen(p, n.sons[1], r)
  703. setLen(p.blocks, idx)
  704. lineF(p, "} while(false);$n", [labl.rope])
  705. proc genBreakStmt(p: PProc, n: PNode) =
  706. var idx: int
  707. genLineDir(p, n)
  708. if n.sons[0].kind != nkEmpty:
  709. # named break?
  710. assert(n.sons[0].kind == nkSym)
  711. let sym = n.sons[0].sym
  712. assert(sym.loc.k == locOther)
  713. idx = sym.position-1
  714. else:
  715. # an unnamed 'break' can only break a loop after 'transf' pass:
  716. idx = len(p.blocks) - 1
  717. while idx >= 0 and not p.blocks[idx].isLoop: dec idx
  718. if idx < 0 or not p.blocks[idx].isLoop:
  719. internalError(p.config, n.info, "no loop to break")
  720. p.blocks[idx].id = abs(p.blocks[idx].id) # label is used
  721. lineF(p, "break L$1;$n", [rope(p.blocks[idx].id)])
  722. proc genAsmOrEmitStmt(p: PProc, n: PNode) =
  723. genLineDir(p, n)
  724. p.body.add p.indentLine(nil)
  725. for i in countup(0, sonsLen(n) - 1):
  726. let it = n[i]
  727. case it.kind
  728. of nkStrLit..nkTripleStrLit:
  729. p.body.add(it.strVal)
  730. of nkSym:
  731. let v = it.sym
  732. # for backwards compatibility we don't deref syms here :-(
  733. if false:
  734. discard
  735. else:
  736. var r: TCompRes
  737. gen(p, it, r)
  738. if it.typ.kind == tyPointer:
  739. # A fat pointer is disguised as an array
  740. r.res = r.address
  741. r.address = nil
  742. elif r.typ == etyBaseIndex:
  743. # Deference first
  744. r.res = "$1[$2]" % [r.address, r.res]
  745. r.address = nil
  746. r.typ = etyNone
  747. p.body.add(r.rdLoc)
  748. else:
  749. var r: TCompRes
  750. gen(p, it, r)
  751. p.body.add(r.rdLoc)
  752. p.body.add "\L"
  753. proc genIf(p: PProc, n: PNode, r: var TCompRes) =
  754. var cond, stmt: TCompRes
  755. var toClose = 0
  756. if not isEmptyType(n.typ):
  757. r.kind = resVal
  758. r.res = getTemp(p)
  759. for i in countup(0, sonsLen(n) - 1):
  760. let it = n.sons[i]
  761. if sonsLen(it) != 1:
  762. if i > 0:
  763. lineF(p, "else {$n", [])
  764. inc(toClose)
  765. p.nested: gen(p, it.sons[0], cond)
  766. lineF(p, "if ($1) {$n", [cond.rdLoc])
  767. gen(p, it.sons[1], stmt)
  768. else:
  769. # else part:
  770. lineF(p, "else {$n", [])
  771. p.nested: gen(p, it.sons[0], stmt)
  772. moveInto(p, stmt, r)
  773. lineF(p, "}$n", [])
  774. line(p, repeat('}', toClose) & "\L")
  775. proc generateHeader(p: PProc, typ: PType): Rope =
  776. result = nil
  777. for i in countup(1, sonsLen(typ.n) - 1):
  778. assert(typ.n.sons[i].kind == nkSym)
  779. var param = typ.n.sons[i].sym
  780. if isCompileTimeOnly(param.typ): continue
  781. if result != nil: add(result, ", ")
  782. var name = mangleName(p.module, param)
  783. add(result, name)
  784. if mapType(param.typ) == etyBaseIndex:
  785. add(result, ", ")
  786. add(result, name)
  787. add(result, "_Idx")
  788. proc countJsParams(typ: PType): int =
  789. for i in countup(1, sonsLen(typ.n) - 1):
  790. assert(typ.n.sons[i].kind == nkSym)
  791. var param = typ.n.sons[i].sym
  792. if isCompileTimeOnly(param.typ): continue
  793. if mapType(param.typ) == etyBaseIndex:
  794. inc result, 2
  795. else:
  796. inc result
  797. const
  798. nodeKindsNeedNoCopy = {nkCharLit..nkInt64Lit, nkStrLit..nkTripleStrLit,
  799. nkFloatLit..nkFloat64Lit, nkCurly, nkPar, nkTupleConstr, nkObjConstr, nkStringToCString,
  800. nkCStringToString, nkCall, nkPrefix, nkPostfix, nkInfix,
  801. nkCommand, nkHiddenCallConv, nkCallStrLit}
  802. proc needsNoCopy(p: PProc; y: PNode): bool =
  803. result = (y.kind in nodeKindsNeedNoCopy) or
  804. (skipTypes(y.typ, abstractInst).kind in {tyRef, tyPtr, tyLent, tyVar})
  805. proc genAsgnAux(p: PProc, x, y: PNode, noCopyNeeded: bool) =
  806. var a, b: TCompRes
  807. var xtyp = mapType(p, x.typ)
  808. if x.kind == nkHiddenDeref and x.sons[0].kind == nkCall and xtyp != etyObject:
  809. gen(p, x.sons[0], a)
  810. let tmp = p.getTemp(false)
  811. lineF(p, "var $1 = $2;$n", [tmp, a.rdLoc])
  812. a.res = "$1[0][$1[1]]" % [tmp]
  813. else:
  814. gen(p, x, a)
  815. genLineDir(p, y)
  816. gen(p, y, b)
  817. # we don't care if it's an etyBaseIndex (global) of a string, it's
  818. # still a string that needs to be copied properly:
  819. if x.typ.skipTypes(abstractInst).kind in {tySequence, tyOpt, tyString}:
  820. xtyp = etySeq
  821. case xtyp
  822. of etySeq:
  823. if (needsNoCopy(p, y) and needsNoCopy(p, x)) or noCopyNeeded:
  824. lineF(p, "$1 = $2;$n", [a.rdLoc, b.rdLoc])
  825. else:
  826. useMagic(p, "nimCopy")
  827. lineF(p, "$1 = nimCopy(null, $2, $3);$n",
  828. [a.rdLoc, b.res, genTypeInfo(p, y.typ)])
  829. of etyObject:
  830. if (needsNoCopy(p, y) and needsNoCopy(p, x)) or noCopyNeeded:
  831. lineF(p, "$1 = $2;$n", [a.rdLoc, b.rdLoc])
  832. else:
  833. useMagic(p, "nimCopy")
  834. lineF(p, "nimCopy($1, $2, $3);$n",
  835. [a.res, b.res, genTypeInfo(p, y.typ)])
  836. of etyBaseIndex:
  837. if a.typ != etyBaseIndex or b.typ != etyBaseIndex:
  838. if y.kind == nkCall:
  839. let tmp = p.getTemp(false)
  840. lineF(p, "var $1 = $4; $2 = $1[0]; $3 = $1[1];$n", [tmp, a.address, a.res, b.rdLoc])
  841. elif b.typ == etyBaseIndex:
  842. lineF(p, "$# = $#;$n", [a.res, b.rdLoc])
  843. else:
  844. internalError(p.config, x.info, "genAsgn")
  845. else:
  846. lineF(p, "$1 = $2; $3 = $4;$n", [a.address, b.address, a.res, b.res])
  847. else:
  848. lineF(p, "$1 = $2;$n", [a.res, b.res])
  849. proc genAsgn(p: PProc, n: PNode) =
  850. genAsgnAux(p, n.sons[0], n.sons[1], noCopyNeeded=false)
  851. proc genFastAsgn(p: PProc, n: PNode) =
  852. # 'shallowCopy' always produced 'noCopyNeeded = true' here but this is wrong
  853. # for code like
  854. # while j >= pos:
  855. # dest[i].shallowCopy(dest[j])
  856. # See bug #5933. So we try to be more compatible with the C backend semantics
  857. # here for 'shallowCopy'. This is an educated guess and might require further
  858. # changes later:
  859. let noCopy = n[0].typ.skipTypes(abstractInst).kind in {tySequence, tyOpt, tyString}
  860. genAsgnAux(p, n.sons[0], n.sons[1], noCopyNeeded=noCopy)
  861. proc genSwap(p: PProc, n: PNode) =
  862. var a, b: TCompRes
  863. gen(p, n.sons[1], a)
  864. gen(p, n.sons[2], b)
  865. var tmp = p.getTemp(false)
  866. if mapType(p, skipTypes(n.sons[1].typ, abstractVar)) == etyBaseIndex:
  867. let tmp2 = p.getTemp(false)
  868. if a.typ != etyBaseIndex or b.typ != etyBaseIndex:
  869. internalError(p.config, n.info, "genSwap")
  870. lineF(p, "var $1 = $2; $2 = $3; $3 = $1;$n",
  871. [tmp, a.address, b.address])
  872. tmp = tmp2
  873. lineF(p, "var $1 = $2; $2 = $3; $3 = $1;",
  874. [tmp, a.res, b.res])
  875. proc getFieldPosition(p: PProc; f: PNode): int =
  876. case f.kind
  877. of nkIntLit..nkUInt64Lit: result = int(f.intVal)
  878. of nkSym: result = f.sym.position
  879. else: internalError(p.config, f.info, "genFieldPosition")
  880. proc genFieldAddr(p: PProc, n: PNode, r: var TCompRes) =
  881. var a: TCompRes
  882. r.typ = etyBaseIndex
  883. let b = if n.kind == nkHiddenAddr: n.sons[0] else: n
  884. gen(p, b.sons[0], a)
  885. if skipTypes(b.sons[0].typ, abstractVarRange).kind == tyTuple:
  886. r.res = makeJSString("Field" & $getFieldPosition(p, b.sons[1]))
  887. else:
  888. if b.sons[1].kind != nkSym: internalError(p.config, b.sons[1].info, "genFieldAddr")
  889. var f = b.sons[1].sym
  890. if f.loc.r == nil: f.loc.r = mangleName(p.module, f)
  891. r.res = makeJSString($f.loc.r)
  892. internalAssert p.config, a.typ != etyBaseIndex
  893. r.address = a.res
  894. r.kind = resExpr
  895. proc genFieldAccess(p: PProc, n: PNode, r: var TCompRes) =
  896. r.typ = etyNone
  897. gen(p, n.sons[0], r)
  898. let otyp = skipTypes(n.sons[0].typ, abstractVarRange)
  899. if otyp.kind == tyTuple:
  900. r.res = ("$1.Field$2") %
  901. [r.res, getFieldPosition(p, n.sons[1]).rope]
  902. else:
  903. if n.sons[1].kind != nkSym: internalError(p.config, n.sons[1].info, "genFieldAccess")
  904. var f = n.sons[1].sym
  905. if f.loc.r == nil: f.loc.r = mangleName(p.module, f)
  906. r.res = "$1.$2" % [r.res, f.loc.r]
  907. r.kind = resExpr
  908. proc genAddr(p: PProc, n: PNode, r: var TCompRes)
  909. proc genCheckedFieldOp(p: PProc, n: PNode, addrTyp: PType, r: var TCompRes) =
  910. internalAssert p.config, n.kind == nkCheckedFieldExpr
  911. # nkDotExpr to access the requested field
  912. let accessExpr = n[0]
  913. # nkCall to check if the discriminant is valid
  914. var checkExpr = n[1]
  915. let negCheck = checkExpr[0].sym.magic == mNot
  916. if negCheck:
  917. checkExpr = checkExpr[^1]
  918. # Field symbol
  919. var field = accessExpr[1].sym
  920. internalAssert p.config, field.kind == skField
  921. if field.loc.r == nil: field.loc.r = mangleName(p.module, field)
  922. # Discriminant symbol
  923. let disc = checkExpr[2].sym
  924. internalAssert p.config, disc.kind == skField
  925. if disc.loc.r == nil: disc.loc.r = mangleName(p.module, disc)
  926. var setx: TCompRes
  927. gen(p, checkExpr[1], setx)
  928. var obj: TCompRes
  929. gen(p, accessExpr[0], obj)
  930. # Avoid evaluating the LHS twice (one to read the discriminant and one to read
  931. # the field)
  932. let tmp = p.getTemp()
  933. lineF(p, "var $1 = $2;$n", tmp, obj.res)
  934. useMagic(p, "raiseFieldError")
  935. useMagic(p, "makeNimstrLit")
  936. lineF(p, "if ($1[$2.$3]$4undefined) { raiseFieldError(makeNimstrLit($5)); }$n",
  937. setx.res, tmp, disc.loc.r, if negCheck: ~"!==" else: ~"===",
  938. makeJSString(field.name.s))
  939. if addrTyp != nil and mapType(p, addrTyp) == etyBaseIndex:
  940. r.typ = etyBaseIndex
  941. r.res = makeJSString($field.loc.r)
  942. r.address = tmp
  943. else:
  944. r.typ = etyNone
  945. r.res = "$1.$2" % [tmp, field.loc.r]
  946. r.kind = resExpr
  947. proc genArrayAddr(p: PProc, n: PNode, r: var TCompRes) =
  948. var
  949. a, b: TCompRes
  950. first: BiggestInt
  951. r.typ = etyBaseIndex
  952. let m = if n.kind == nkHiddenAddr: n.sons[0] else: n
  953. gen(p, m.sons[0], a)
  954. gen(p, m.sons[1], b)
  955. internalAssert p.config, a.typ != etyBaseIndex and b.typ != etyBaseIndex
  956. r.address = a.res
  957. var typ = skipTypes(m.sons[0].typ, abstractPtrs)
  958. if typ.kind == tyArray: first = firstOrd(p.config, typ.sons[0])
  959. else: first = 0
  960. if optBoundsCheck in p.options:
  961. useMagic(p, "chckIndx")
  962. r.res = "chckIndx($1, $2, $3.length+$2-1)-$2" % [b.res, rope(first), a.res]
  963. elif first != 0:
  964. r.res = "($1)-$2" % [b.res, rope(first)]
  965. else:
  966. r.res = b.res
  967. r.kind = resExpr
  968. proc genArrayAccess(p: PProc, n: PNode, r: var TCompRes) =
  969. var ty = skipTypes(n.sons[0].typ, abstractVarRange)
  970. if ty.kind in {tyRef, tyPtr, tyLent}: ty = skipTypes(ty.lastSon, abstractVarRange)
  971. case ty.kind
  972. of tyArray, tyOpenArray, tySequence, tyString, tyCString, tyVarargs:
  973. genArrayAddr(p, n, r)
  974. of tyTuple:
  975. genFieldAddr(p, n, r)
  976. else: internalError(p.config, n.info, "expr(nkBracketExpr, " & $ty.kind & ')')
  977. r.typ = etyNone
  978. if r.res == nil: internalError(p.config, n.info, "genArrayAccess")
  979. if ty.kind == tyCString:
  980. r.res = "$1.charCodeAt($2)" % [r.address, r.res]
  981. else:
  982. r.res = "$1[$2]" % [r.address, r.res]
  983. r.address = nil
  984. r.kind = resExpr
  985. template isIndirect(x: PSym): bool =
  986. let v = x
  987. ({sfAddrTaken, sfGlobal} * v.flags != {} and
  988. #(mapType(v.typ) != etyObject) and
  989. {sfImportc, sfVolatile, sfExportc} * v.flags == {} and
  990. v.kind notin {skProc, skFunc, skConverter, skMethod, skIterator,
  991. skConst, skTemp, skLet})
  992. proc genAddr(p: PProc, n: PNode, r: var TCompRes) =
  993. case n.sons[0].kind
  994. of nkSym:
  995. let s = n.sons[0].sym
  996. if s.loc.r == nil: internalError(p.config, n.info, "genAddr: 3")
  997. case s.kind
  998. of skVar, skLet, skResult:
  999. r.kind = resExpr
  1000. let jsType = mapType(p, n.typ)
  1001. if jsType == etyObject:
  1002. # make addr() a no-op:
  1003. r.typ = etyNone
  1004. if isIndirect(s):
  1005. r.res = s.loc.r & "[0]"
  1006. else:
  1007. r.res = s.loc.r
  1008. r.address = nil
  1009. elif {sfGlobal, sfAddrTaken} * s.flags != {} or jsType == etyBaseIndex:
  1010. # for ease of code generation, we do not distinguish between
  1011. # sfAddrTaken and sfGlobal.
  1012. r.typ = etyBaseIndex
  1013. r.address = s.loc.r
  1014. r.res = rope("0")
  1015. else:
  1016. # 'var openArray' for instance produces an 'addr' but this is harmless:
  1017. gen(p, n.sons[0], r)
  1018. #internalError(p.config, n.info, "genAddr: 4 " & renderTree(n))
  1019. else: internalError(p.config, n.info, "genAddr: 2")
  1020. of nkCheckedFieldExpr:
  1021. genCheckedFieldOp(p, n[0], n.typ, r)
  1022. of nkDotExpr:
  1023. if mapType(p, n.typ) == etyBaseIndex:
  1024. genFieldAddr(p, n.sons[0], r)
  1025. else:
  1026. genFieldAccess(p, n.sons[0], r)
  1027. of nkBracketExpr:
  1028. var ty = skipTypes(n.sons[0].typ, abstractVarRange)
  1029. if ty.kind in MappedToObject:
  1030. gen(p, n.sons[0], r)
  1031. else:
  1032. let kindOfIndexedExpr = skipTypes(n.sons[0].sons[0].typ, abstractVarRange).kind
  1033. case kindOfIndexedExpr
  1034. of tyArray, tyOpenArray, tySequence, tyString, tyCString, tyVarargs:
  1035. genArrayAddr(p, n.sons[0], r)
  1036. of tyTuple:
  1037. genFieldAddr(p, n.sons[0], r)
  1038. else: internalError(p.config, n.sons[0].info, "expr(nkBracketExpr, " & $kindOfIndexedExpr & ')')
  1039. of nkObjDownConv:
  1040. gen(p, n.sons[0], r)
  1041. of nkHiddenDeref:
  1042. gen(p, n.sons[0].sons[0], r)
  1043. else: internalError(p.config, n.sons[0].info, "genAddr: " & $n.sons[0].kind)
  1044. proc thisParam(p: PProc; typ: PType): PType =
  1045. discard
  1046. proc attachProc(p: PProc; content: Rope; s: PSym) =
  1047. let otyp = thisParam(p, s.typ)
  1048. if otyp != nil:
  1049. for i, cls in p.g.classes:
  1050. if sameType(cls[0], otyp):
  1051. add(p.g.classes[i][1], content)
  1052. return
  1053. p.g.classes.add((otyp, content))
  1054. else:
  1055. add(p.g.code, content)
  1056. proc attachProc(p: PProc; s: PSym) =
  1057. let newp = genProc(p, s)
  1058. attachProc(p, newp, s)
  1059. proc genProcForSymIfNeeded(p: PProc, s: PSym) =
  1060. if not p.g.generatedSyms.containsOrIncl(s.id):
  1061. let newp = genProc(p, s)
  1062. var owner = p
  1063. while owner != nil and owner.prc != s.owner:
  1064. owner = owner.up
  1065. if owner != nil: add(owner.locals, newp)
  1066. else: attachProc(p, newp, s)
  1067. proc genSym(p: PProc, n: PNode, r: var TCompRes) =
  1068. var s = n.sym
  1069. case s.kind
  1070. of skVar, skLet, skParam, skTemp, skResult, skForVar:
  1071. if s.loc.r == nil:
  1072. internalError(p.config, n.info, "symbol has no generated name: " & s.name.s)
  1073. let k = mapType(p, s.typ)
  1074. if k == etyBaseIndex:
  1075. r.typ = etyBaseIndex
  1076. if {sfAddrTaken, sfGlobal} * s.flags != {}:
  1077. r.address = "$1[0]" % [s.loc.r]
  1078. r.res = "$1[1]" % [s.loc.r]
  1079. else:
  1080. r.address = s.loc.r
  1081. r.res = s.loc.r & "_Idx"
  1082. elif isIndirect(s):
  1083. r.res = "$1[0]" % [s.loc.r]
  1084. else:
  1085. r.res = s.loc.r
  1086. of skConst:
  1087. genConstant(p, s)
  1088. if s.loc.r == nil:
  1089. internalError(p.config, n.info, "symbol has no generated name: " & s.name.s)
  1090. r.res = s.loc.r
  1091. of skProc, skFunc, skConverter, skMethod:
  1092. discard mangleName(p.module, s)
  1093. r.res = s.loc.r
  1094. if lfNoDecl in s.loc.flags or s.magic != mNone or
  1095. {sfImportc, sfInfixCall} * s.flags != {}:
  1096. discard
  1097. elif s.kind == skMethod and s.getBody.kind == nkEmpty:
  1098. # we cannot produce code for the dispatcher yet:
  1099. discard
  1100. elif sfForward in s.flags:
  1101. p.g.forwarded.add(s)
  1102. else:
  1103. genProcForSymIfNeeded(p, s)
  1104. else:
  1105. if s.loc.r == nil:
  1106. internalError(p.config, n.info, "symbol has no generated name: " & s.name.s)
  1107. r.res = s.loc.r
  1108. r.kind = resVal
  1109. proc genDeref(p: PProc, n: PNode, r: var TCompRes) =
  1110. let it = n.sons[0]
  1111. let t = mapType(p, it.typ)
  1112. if t == etyObject:
  1113. gen(p, it, r)
  1114. else:
  1115. var a: TCompRes
  1116. gen(p, it, a)
  1117. r.kind = resExpr
  1118. if a.typ == etyBaseIndex:
  1119. r.res = "$1[$2]" % [a.address, a.res]
  1120. elif it.kind == nkCall:
  1121. let tmp = p.getTemp
  1122. r.res = "($1 = $2, $1[0])[$1[1]]" % [tmp, a.res]
  1123. elif t == etyBaseIndex:
  1124. r.res = "$1[0]" % [a.res]
  1125. else:
  1126. internalError(p.config, n.info, "genDeref")
  1127. proc genArgNoParam(p: PProc, n: PNode, r: var TCompRes) =
  1128. var a: TCompRes
  1129. gen(p, n, a)
  1130. if a.typ == etyBaseIndex:
  1131. add(r.res, a.address)
  1132. add(r.res, ", ")
  1133. add(r.res, a.res)
  1134. else:
  1135. add(r.res, a.res)
  1136. proc genArg(p: PProc, n: PNode, param: PSym, r: var TCompRes; emitted: ptr int = nil) =
  1137. var a: TCompRes
  1138. gen(p, n, a)
  1139. if skipTypes(param.typ, abstractVar).kind in {tyOpenArray, tyVarargs} and
  1140. a.typ == etyBaseIndex:
  1141. add(r.res, "$1[$2]" % [a.address, a.res])
  1142. elif a.typ == etyBaseIndex:
  1143. add(r.res, a.address)
  1144. add(r.res, ", ")
  1145. add(r.res, a.res)
  1146. if emitted != nil: inc emitted[]
  1147. elif n.typ.kind in {tyVar, tyLent} and n.kind in nkCallKinds and mapType(param.typ) == etyBaseIndex:
  1148. # this fixes bug #5608:
  1149. let tmp = getTemp(p)
  1150. add(r.res, "($1 = $2, $1[0]), $1[1]" % [tmp, a.rdLoc])
  1151. if emitted != nil: inc emitted[]
  1152. else:
  1153. add(r.res, a.res)
  1154. proc genArgs(p: PProc, n: PNode, r: var TCompRes; start=1) =
  1155. add(r.res, "(")
  1156. var hasArgs = false
  1157. var typ = skipTypes(n.sons[0].typ, abstractInst)
  1158. assert(typ.kind == tyProc)
  1159. assert(sonsLen(typ) == sonsLen(typ.n))
  1160. var emitted = start-1
  1161. for i in countup(start, sonsLen(n) - 1):
  1162. let it = n.sons[i]
  1163. var paramType: PNode = nil
  1164. if i < sonsLen(typ):
  1165. assert(typ.n.sons[i].kind == nkSym)
  1166. paramType = typ.n.sons[i]
  1167. if paramType.typ.isCompileTimeOnly: continue
  1168. if hasArgs: add(r.res, ", ")
  1169. if paramType.isNil:
  1170. genArgNoParam(p, it, r)
  1171. else:
  1172. genArg(p, it, paramType.sym, r, addr emitted)
  1173. inc emitted
  1174. hasArgs = true
  1175. add(r.res, ")")
  1176. when false:
  1177. # XXX look into this:
  1178. let jsp = countJsParams(typ)
  1179. if emitted != jsp and tfVarargs notin typ.flags:
  1180. localError(p.config, n.info, "wrong number of parameters emitted; expected: " & $jsp &
  1181. " but got: " & $emitted)
  1182. r.kind = resExpr
  1183. proc genOtherArg(p: PProc; n: PNode; i: int; typ: PType;
  1184. generated: var int; r: var TCompRes) =
  1185. if i >= n.len:
  1186. globalError(p.config, n.info, "wrong importcpp pattern; expected parameter at position " & $i &
  1187. " but got only: " & $(n.len-1))
  1188. let it = n[i]
  1189. var paramType: PNode = nil
  1190. if i < sonsLen(typ):
  1191. assert(typ.n.sons[i].kind == nkSym)
  1192. paramType = typ.n.sons[i]
  1193. if paramType.typ.isCompileTimeOnly: return
  1194. if paramType.isNil:
  1195. genArgNoParam(p, it, r)
  1196. else:
  1197. genArg(p, it, paramType.sym, r)
  1198. inc generated
  1199. proc genPatternCall(p: PProc; n: PNode; pat: string; typ: PType;
  1200. r: var TCompRes) =
  1201. var i = 0
  1202. var j = 1
  1203. r.kind = resExpr
  1204. while i < pat.len:
  1205. case pat[i]
  1206. of '@':
  1207. var generated = 0
  1208. for k in j ..< n.len:
  1209. if generated > 0: add(r.res, ", ")
  1210. genOtherArg(p, n, k, typ, generated, r)
  1211. inc i
  1212. of '#':
  1213. var generated = 0
  1214. genOtherArg(p, n, j, typ, generated, r)
  1215. inc j
  1216. inc i
  1217. of '\31':
  1218. # unit separator
  1219. add(r.res, "#")
  1220. inc i
  1221. of '\29':
  1222. # group separator
  1223. add(r.res, "@")
  1224. inc i
  1225. else:
  1226. let start = i
  1227. while i < pat.len:
  1228. if pat[i] notin {'@', '#', '\31', '\29'}: inc(i)
  1229. else: break
  1230. if i - 1 >= start:
  1231. add(r.res, substr(pat, start, i - 1))
  1232. proc genInfixCall(p: PProc, n: PNode, r: var TCompRes) =
  1233. # don't call '$' here for efficiency:
  1234. let f = n[0].sym
  1235. if f.loc.r == nil: f.loc.r = mangleName(p.module, f)
  1236. if sfInfixCall in f.flags:
  1237. let pat = n.sons[0].sym.loc.r.data
  1238. internalAssert p.config, pat.len > 0
  1239. if pat.contains({'#', '(', '@'}):
  1240. var typ = skipTypes(n.sons[0].typ, abstractInst)
  1241. assert(typ.kind == tyProc)
  1242. genPatternCall(p, n, pat, typ, r)
  1243. return
  1244. if n.len != 1:
  1245. gen(p, n.sons[1], r)
  1246. if r.typ == etyBaseIndex:
  1247. if r.address == nil:
  1248. globalError(p.config, n.info, "cannot invoke with infix syntax")
  1249. r.res = "$1[$2]" % [r.address, r.res]
  1250. r.address = nil
  1251. r.typ = etyNone
  1252. add(r.res, ".")
  1253. var op: TCompRes
  1254. gen(p, n.sons[0], op)
  1255. add(r.res, op.res)
  1256. genArgs(p, n, r, 2)
  1257. proc genCall(p: PProc, n: PNode, r: var TCompRes) =
  1258. if n.sons[0].kind == nkSym and thisParam(p, n.sons[0].typ) != nil:
  1259. genInfixCall(p, n, r)
  1260. return
  1261. gen(p, n.sons[0], r)
  1262. genArgs(p, n, r)
  1263. proc genEcho(p: PProc, n: PNode, r: var TCompRes) =
  1264. let n = n[1].skipConv
  1265. internalAssert p.config, n.kind == nkBracket
  1266. useMagic(p, "toJSStr") # Used in rawEcho
  1267. useMagic(p, "rawEcho")
  1268. add(r.res, "rawEcho(")
  1269. for i in countup(0, sonsLen(n) - 1):
  1270. let it = n.sons[i]
  1271. if it.typ.isCompileTimeOnly: continue
  1272. if i > 0: add(r.res, ", ")
  1273. genArgNoParam(p, it, r)
  1274. add(r.res, ")")
  1275. r.kind = resExpr
  1276. proc putToSeq(s: string, indirect: bool): Rope =
  1277. result = rope(s)
  1278. if indirect: result = "[$1]" % [result]
  1279. proc createVar(p: PProc, typ: PType, indirect: bool): Rope
  1280. proc createRecordVarAux(p: PProc, rec: PNode, excludedFieldIDs: IntSet, output: var Rope) =
  1281. case rec.kind
  1282. of nkRecList:
  1283. for i in countup(0, sonsLen(rec) - 1):
  1284. createRecordVarAux(p, rec.sons[i], excludedFieldIDs, output)
  1285. of nkRecCase:
  1286. createRecordVarAux(p, rec.sons[0], excludedFieldIDs, output)
  1287. for i in countup(1, sonsLen(rec) - 1):
  1288. createRecordVarAux(p, lastSon(rec.sons[i]), excludedFieldIDs, output)
  1289. of nkSym:
  1290. if rec.sym.id notin excludedFieldIDs:
  1291. if output.len > 0: output.add(", ")
  1292. output.addf("$#: ", [mangleName(p.module, rec.sym)])
  1293. output.add(createVar(p, rec.sym.typ, false))
  1294. else: internalError(p.config, rec.info, "createRecordVarAux")
  1295. proc createObjInitList(p: PProc, typ: PType, excludedFieldIDs: IntSet, output: var Rope) =
  1296. var t = typ
  1297. if objHasTypeField(t):
  1298. if output.len > 0: output.add(", ")
  1299. addf(output, "m_type: $1", [genTypeInfo(p, t)])
  1300. while t != nil:
  1301. t = t.skipTypes(skipPtrs)
  1302. createRecordVarAux(p, t.n, excludedFieldIDs, output)
  1303. t = t.sons[0]
  1304. proc arrayTypeForElemType(typ: PType): string =
  1305. # XXX This should also support tyEnum and tyBool
  1306. case typ.kind
  1307. of tyInt, tyInt32: "Int32Array"
  1308. of tyInt16: "Int16Array"
  1309. of tyInt8: "Int8Array"
  1310. of tyUint, tyUint32: "Uint32Array"
  1311. of tyUint16: "Uint16Array"
  1312. of tyUint8: "Uint8Array"
  1313. of tyFloat32: "Float32Array"
  1314. of tyFloat64, tyFloat: "Float64Array"
  1315. else: ""
  1316. proc createVar(p: PProc, typ: PType, indirect: bool): Rope =
  1317. var t = skipTypes(typ, abstractInst)
  1318. case t.kind
  1319. of tyInt..tyInt64, tyUInt..tyUInt64, tyEnum, tyChar:
  1320. result = putToSeq("0", indirect)
  1321. of tyFloat..tyFloat128:
  1322. result = putToSeq("0.0", indirect)
  1323. of tyRange, tyGenericInst, tyAlias, tySink:
  1324. result = createVar(p, lastSon(typ), indirect)
  1325. of tySet:
  1326. result = putToSeq("{}", indirect)
  1327. of tyBool:
  1328. result = putToSeq("false", indirect)
  1329. of tyArray:
  1330. let length = int(lengthOrd(p.config, t))
  1331. let e = elemType(t)
  1332. let jsTyp = arrayTypeForElemType(e)
  1333. if jsTyp.len > 0:
  1334. result = "new $1($2)" % [rope(jsTyp), rope(length)]
  1335. elif length > 32:
  1336. useMagic(p, "arrayConstr")
  1337. # XXX: arrayConstr depends on nimCopy. This line shouldn't be necessary.
  1338. useMagic(p, "nimCopy")
  1339. result = "arrayConstr($1, $2, $3)" % [rope(length),
  1340. createVar(p, e, false), genTypeInfo(p, e)]
  1341. else:
  1342. result = rope("[")
  1343. var i = 0
  1344. while i < length:
  1345. if i > 0: add(result, ", ")
  1346. add(result, createVar(p, e, false))
  1347. inc(i)
  1348. add(result, "]")
  1349. if indirect: result = "[$1]" % [result]
  1350. of tyTuple:
  1351. result = rope("{")
  1352. for i in 0..<t.sonsLen:
  1353. if i > 0: add(result, ", ")
  1354. addf(result, "Field$1: $2", [i.rope,
  1355. createVar(p, t.sons[i], false)])
  1356. add(result, "}")
  1357. if indirect: result = "[$1]" % [result]
  1358. of tyObject:
  1359. var initList: Rope
  1360. createObjInitList(p, t, initIntSet(), initList)
  1361. result = ("{$1}") % [initList]
  1362. if indirect: result = "[$1]" % [result]
  1363. of tyVar, tyPtr, tyLent, tyRef:
  1364. if mapType(p, t) == etyBaseIndex:
  1365. result = putToSeq("[null, 0]", indirect)
  1366. else:
  1367. result = putToSeq("null", indirect)
  1368. of tySequence, tyOpt, tyString, tyCString, tyPointer, tyProc:
  1369. result = putToSeq("null", indirect)
  1370. of tyStatic:
  1371. if t.n != nil:
  1372. result = createVar(p, lastSon t, indirect)
  1373. else:
  1374. internalError(p.config, "createVar: " & $t.kind)
  1375. result = nil
  1376. else:
  1377. internalError(p.config, "createVar: " & $t.kind)
  1378. result = nil
  1379. template returnType: untyped =
  1380. ~""
  1381. proc genVarInit(p: PProc, v: PSym, n: PNode) =
  1382. var
  1383. a: TCompRes
  1384. s: Rope
  1385. varCode: string
  1386. varName = mangleName(p.module, v)
  1387. useReloadingGuard = sfGlobal in v.flags and optHotCodeReloading in p.config.options
  1388. if v.constraint.isNil:
  1389. if useReloadingGuard:
  1390. lineF(p, "var $1;$n", varName)
  1391. lineF(p, "if ($1 === undefined) {$n", varName)
  1392. varCode = $varName
  1393. else:
  1394. varCode = "var $2"
  1395. else:
  1396. varCode = v.constraint.strVal
  1397. if n.kind == nkEmpty:
  1398. lineF(p, varCode & " = $3;$n",
  1399. [returnType, varName, createVar(p, v.typ, isIndirect(v))])
  1400. if v.typ.kind in {tyVar, tyPtr, tyLent, tyRef} and mapType(p, v.typ) == etyBaseIndex:
  1401. lineF(p, "var $1_Idx = 0;$n", [varName])
  1402. else:
  1403. gen(p, n, a)
  1404. case mapType(p, v.typ)
  1405. of etyObject, etySeq:
  1406. if needsNoCopy(p, n):
  1407. s = a.res
  1408. else:
  1409. useMagic(p, "nimCopy")
  1410. s = "nimCopy(null, $1, $2)" % [a.res, genTypeInfo(p, n.typ)]
  1411. of etyBaseIndex:
  1412. let targetBaseIndex = {sfAddrTaken, sfGlobal} * v.flags == {}
  1413. if a.typ == etyBaseIndex:
  1414. if targetBaseIndex:
  1415. lineF(p, varCode & " = $3, $2_Idx = $4;$n",
  1416. [returnType, v.loc.r, a.address, a.res])
  1417. else:
  1418. lineF(p, varCode & " = [$3, $4];$n",
  1419. [returnType, v.loc.r, a.address, a.res])
  1420. else:
  1421. if targetBaseIndex:
  1422. let tmp = p.getTemp
  1423. lineF(p, "var $1 = $2, $3 = $1[0], $3_Idx = $1[1];$n",
  1424. [tmp, a.res, v.loc.r])
  1425. else:
  1426. lineF(p, varCode & " = $3;$n", [returnType, v.loc.r, a.res])
  1427. return
  1428. else:
  1429. s = a.res
  1430. if isIndirect(v):
  1431. lineF(p, varCode & " = [$3];$n", [returnType, v.loc.r, s])
  1432. else:
  1433. lineF(p, varCode & " = $3;$n", [returnType, v.loc.r, s])
  1434. if useReloadingGuard:
  1435. lineF(p, "}$n")
  1436. proc genVarStmt(p: PProc, n: PNode) =
  1437. for i in countup(0, sonsLen(n) - 1):
  1438. var a = n.sons[i]
  1439. if a.kind != nkCommentStmt:
  1440. if a.kind == nkVarTuple:
  1441. let unpacked = lowerTupleUnpacking(p.module.graph, a, p.prc)
  1442. genStmt(p, unpacked)
  1443. else:
  1444. assert(a.kind == nkIdentDefs)
  1445. assert(a.sons[0].kind == nkSym)
  1446. var v = a.sons[0].sym
  1447. if lfNoDecl notin v.loc.flags and sfImportc notin v.flags:
  1448. genLineDir(p, a)
  1449. genVarInit(p, v, a.sons[2])
  1450. proc genConstant(p: PProc, c: PSym) =
  1451. if lfNoDecl notin c.loc.flags and not p.g.generatedSyms.containsOrIncl(c.id):
  1452. let oldBody = p.body
  1453. p.body = nil
  1454. #genLineDir(p, c.ast)
  1455. genVarInit(p, c, c.ast)
  1456. add(p.g.constants, p.body)
  1457. p.body = oldBody
  1458. proc genNew(p: PProc, n: PNode) =
  1459. var a: TCompRes
  1460. gen(p, n.sons[1], a)
  1461. var t = skipTypes(n.sons[1].typ, abstractVar).sons[0]
  1462. lineF(p, "$1 = $2;$n", [a.res, createVar(p, t, false)])
  1463. proc genNewSeq(p: PProc, n: PNode) =
  1464. var x, y: TCompRes
  1465. gen(p, n.sons[1], x)
  1466. gen(p, n.sons[2], y)
  1467. let t = skipTypes(n.sons[1].typ, abstractVar).sons[0]
  1468. lineF(p, "$1 = new Array($2); for (var i=0;i<$2;++i) {$1[i]=$3;}", [
  1469. x.rdLoc, y.rdLoc, createVar(p, t, false)])
  1470. proc genOrd(p: PProc, n: PNode, r: var TCompRes) =
  1471. case skipTypes(n.sons[1].typ, abstractVar).kind
  1472. of tyEnum, tyInt..tyUInt64, tyChar: gen(p, n.sons[1], r)
  1473. of tyBool: unaryExpr(p, n, r, "", "($1 ? 1:0)")
  1474. else: internalError(p.config, n.info, "genOrd")
  1475. proc genConStrStr(p: PProc, n: PNode, r: var TCompRes) =
  1476. var a: TCompRes
  1477. gen(p, n.sons[1], a)
  1478. r.kind = resExpr
  1479. if skipTypes(n.sons[1].typ, abstractVarRange).kind == tyChar:
  1480. r.res.add("[$1].concat(" % [a.res])
  1481. else:
  1482. r.res.add("($1).concat(" % [a.res])
  1483. for i in countup(2, sonsLen(n) - 2):
  1484. gen(p, n.sons[i], a)
  1485. if skipTypes(n.sons[i].typ, abstractVarRange).kind == tyChar:
  1486. r.res.add("[$1]," % [a.res])
  1487. else:
  1488. r.res.add("$1," % [a.res])
  1489. gen(p, n.sons[sonsLen(n) - 1], a)
  1490. if skipTypes(n.sons[sonsLen(n) - 1].typ, abstractVarRange).kind == tyChar:
  1491. r.res.add("[$1])" % [a.res])
  1492. else:
  1493. r.res.add("$1)" % [a.res])
  1494. proc genToArray(p: PProc; n: PNode; r: var TCompRes) =
  1495. # we map mArray to PHP's array constructor, a mild hack:
  1496. var a, b: TCompRes
  1497. r.kind = resExpr
  1498. r.res = rope("array(")
  1499. let x = skipConv(n[1])
  1500. if x.kind == nkBracket:
  1501. for i in countup(0, x.len - 1):
  1502. let it = x[i]
  1503. if it.kind in {nkPar, nkTupleConstr} and it.len == 2:
  1504. if i > 0: r.res.add(", ")
  1505. gen(p, it[0], a)
  1506. gen(p, it[1], b)
  1507. r.res.add("$# => $#" % [a.rdLoc, b.rdLoc])
  1508. else:
  1509. localError(p.config, it.info, "'toArray' needs tuple constructors")
  1510. else:
  1511. localError(p.config, x.info, "'toArray' needs an array literal")
  1512. r.res.add(")")
  1513. proc genReprAux(p: PProc, n: PNode, r: var TCompRes, magic: string, typ: Rope = nil) =
  1514. useMagic(p, magic)
  1515. add(r.res, magic & "(")
  1516. var a: TCompRes
  1517. gen(p, n.sons[1], a)
  1518. if magic == "reprAny":
  1519. # the pointer argument in reprAny is expandend to
  1520. # (pointedto, pointer), so we need to fill it
  1521. if a.address.isNil:
  1522. add(r.res, a.res)
  1523. add(r.res, ", null")
  1524. else:
  1525. add(r.res, "$1, $2" % [a.address, a.res])
  1526. else:
  1527. add(r.res, a.res)
  1528. if not typ.isNil:
  1529. add(r.res, ", ")
  1530. add(r.res, typ)
  1531. add(r.res, ")")
  1532. proc genRepr(p: PProc, n: PNode, r: var TCompRes) =
  1533. let t = skipTypes(n.sons[1].typ, abstractVarRange)
  1534. case t.kind:
  1535. of tyInt..tyInt64, tyUInt..tyUInt64:
  1536. genReprAux(p, n, r, "reprInt")
  1537. of tyChar:
  1538. genReprAux(p, n, r, "reprChar")
  1539. of tyBool:
  1540. genReprAux(p, n, r, "reprBool")
  1541. of tyFloat..tyFloat128:
  1542. genReprAux(p, n, r, "reprFloat")
  1543. of tyString:
  1544. genReprAux(p, n, r, "reprStr")
  1545. of tyEnum, tyOrdinal:
  1546. genReprAux(p, n, r, "reprEnum", genTypeInfo(p, t))
  1547. of tySet:
  1548. genReprAux(p, n, r, "reprSet", genTypeInfo(p, t))
  1549. of tyEmpty, tyVoid:
  1550. localError(p.config, n.info, "'repr' doesn't support 'void' type")
  1551. of tyPointer:
  1552. genReprAux(p, n, r, "reprPointer")
  1553. of tyOpenArray, tyVarargs:
  1554. genReprAux(p, n, r, "reprJSONStringify")
  1555. else:
  1556. genReprAux(p, n, r, "reprAny", genTypeInfo(p, t))
  1557. proc genOf(p: PProc, n: PNode, r: var TCompRes) =
  1558. var x: TCompRes
  1559. let t = skipTypes(n.sons[2].typ, abstractVarRange+{tyRef, tyPtr, tyLent, tyTypeDesc})
  1560. gen(p, n.sons[1], x)
  1561. if tfFinal in t.flags:
  1562. r.res = "($1.m_type == $2)" % [x.res, genTypeInfo(p, t)]
  1563. else:
  1564. useMagic(p, "isObj")
  1565. r.res = "isObj($1.m_type, $2)" % [x.res, genTypeInfo(p, t)]
  1566. r.kind = resExpr
  1567. proc genReset(p: PProc, n: PNode) =
  1568. var x: TCompRes
  1569. useMagic(p, "genericReset")
  1570. gen(p, n.sons[1], x)
  1571. addf(p.body, "$1 = genericReset($1, $2);$n", [x.res,
  1572. genTypeInfo(p, n.sons[1].typ)])
  1573. proc genMagic(p: PProc, n: PNode, r: var TCompRes) =
  1574. var
  1575. a: TCompRes
  1576. line, filen: Rope
  1577. var op = n.sons[0].sym.magic
  1578. case op
  1579. of mOr: genOr(p, n.sons[1], n.sons[2], r)
  1580. of mAnd: genAnd(p, n.sons[1], n.sons[2], r)
  1581. of mAddI..mStrToStr: arith(p, n, r, op)
  1582. of mRepr: genRepr(p, n, r)
  1583. of mSwap: genSwap(p, n)
  1584. of mUnaryLt:
  1585. # XXX: range checking?
  1586. if not (optOverflowCheck in p.options): unaryExpr(p, n, r, "", "$1 - 1")
  1587. else: unaryExpr(p, n, r, "subInt", "subInt($1, 1)")
  1588. of mAppendStrCh:
  1589. binaryExpr(p, n, r, "addChar",
  1590. "if ($1 != null) { addChar($1, $2); } else { $1 = [$2]; }")
  1591. of mAppendStrStr:
  1592. var lhs, rhs: TCompRes
  1593. gen(p, n[1], lhs)
  1594. gen(p, n[2], rhs)
  1595. let rhsIsLit = n[2].kind in nkStrKinds
  1596. if skipTypes(n.sons[1].typ, abstractVarRange).kind == tyCString:
  1597. r.res = "if ($1 != null) { $1 += $2; } else { $1 = $2$3; }" % [
  1598. lhs.rdLoc, rhs.rdLoc, if rhsIsLit: nil else: ~".slice()"]
  1599. else:
  1600. r.res = "if ($1 != null) { $1 = ($1).concat($2); } else { $1 = $2$3; }" % [
  1601. lhs.rdLoc, rhs.rdLoc, if rhsIsLit: nil else: ~".slice()"]
  1602. r.kind = resExpr
  1603. of mAppendSeqElem:
  1604. var x, y: TCompRes
  1605. gen(p, n.sons[1], x)
  1606. gen(p, n.sons[2], y)
  1607. if needsNoCopy(p, n[2]):
  1608. r.res = "if ($1 != null) { $1.push($2); } else { $1 = [$2]; }" % [x.rdLoc, y.rdLoc]
  1609. else:
  1610. useMagic(p, "nimCopy")
  1611. let c = getTemp(p, defineInLocals=false)
  1612. lineF(p, "var $1 = nimCopy(null, $2, $3);$n",
  1613. [c, y.rdLoc, genTypeInfo(p, n[2].typ)])
  1614. r.res = "if ($1 != null) { $1.push($2); } else { $1 = [$2]; }" % [x.rdLoc, c]
  1615. r.kind = resExpr
  1616. of mConStrStr:
  1617. genConStrStr(p, n, r)
  1618. of mEqStr:
  1619. binaryExpr(p, n, r, "eqStrings", "eqStrings($1, $2)")
  1620. of mLeStr:
  1621. binaryExpr(p, n, r, "cmpStrings", "(cmpStrings($1, $2) <= 0)")
  1622. of mLtStr:
  1623. binaryExpr(p, n, r, "cmpStrings", "(cmpStrings($1, $2) < 0)")
  1624. of mIsNil: unaryExpr(p, n, r, "", "($1 === null)")
  1625. of mEnumToStr: genRepr(p, n, r)
  1626. of mNew, mNewFinalize: genNew(p, n)
  1627. of mChr, mArrToSeq: gen(p, n.sons[1], r) # nothing to do
  1628. of mOrd: genOrd(p, n, r)
  1629. of mLengthStr, mLengthSeq, mLengthOpenArray, mLengthArray:
  1630. unaryExpr(p, n, r, "", "($1 != null ? $1.length : 0)")
  1631. of mXLenStr, mXLenSeq:
  1632. unaryExpr(p, n, r, "", "$1.length")
  1633. of mHigh:
  1634. unaryExpr(p, n, r, "", "($1 != null ? ($1.length-1) : -1)")
  1635. of mInc:
  1636. if n[1].typ.skipTypes(abstractRange).kind in tyUInt .. tyUInt64:
  1637. binaryUintExpr(p, n, r, "+", true)
  1638. else:
  1639. if optOverflowCheck notin p.options: binaryExpr(p, n, r, "", "$1 += $2")
  1640. else: binaryExpr(p, n, r, "addInt", "$1 = addInt($1, $2)")
  1641. of ast.mDec:
  1642. if n[1].typ.skipTypes(abstractRange).kind in tyUInt .. tyUInt64:
  1643. binaryUintExpr(p, n, r, "-", true)
  1644. else:
  1645. if optOverflowCheck notin p.options: binaryExpr(p, n, r, "", "$1 -= $2")
  1646. else: binaryExpr(p, n, r, "subInt", "$1 = subInt($1, $2)")
  1647. of mSetLengthStr:
  1648. binaryExpr(p, n, r, "", "$1.length = $2")
  1649. of mSetLengthSeq:
  1650. var x, y: TCompRes
  1651. gen(p, n.sons[1], x)
  1652. gen(p, n.sons[2], y)
  1653. let t = skipTypes(n.sons[1].typ, abstractVar).sons[0]
  1654. r.res = """if ($1.length < $2) { for (var i=$1.length;i<$2;++i) $1.push($3); }
  1655. else { $1.length = $2; }""" % [x.rdLoc, y.rdLoc, createVar(p, t, false)]
  1656. r.kind = resExpr
  1657. of mCard: unaryExpr(p, n, r, "SetCard", "SetCard($1)")
  1658. of mLtSet: binaryExpr(p, n, r, "SetLt", "SetLt($1, $2)")
  1659. of mLeSet: binaryExpr(p, n, r, "SetLe", "SetLe($1, $2)")
  1660. of mEqSet: binaryExpr(p, n, r, "SetEq", "SetEq($1, $2)")
  1661. of mMulSet: binaryExpr(p, n, r, "SetMul", "SetMul($1, $2)")
  1662. of mPlusSet: binaryExpr(p, n, r, "SetPlus", "SetPlus($1, $2)")
  1663. of mMinusSet: binaryExpr(p, n, r, "SetMinus", "SetMinus($1, $2)")
  1664. of mIncl: binaryExpr(p, n, r, "", "$1[$2] = true")
  1665. of mExcl: binaryExpr(p, n, r, "", "delete $1[$2]")
  1666. of mInSet:
  1667. binaryExpr(p, n, r, "", "($1[$2] != undefined)")
  1668. of mNewSeq: genNewSeq(p, n)
  1669. of mNewSeqOfCap: unaryExpr(p, n, r, "", "[]")
  1670. of mOf: genOf(p, n, r)
  1671. of mReset: genReset(p, n)
  1672. of mEcho: genEcho(p, n, r)
  1673. of mNLen..mNError, mSlurp, mStaticExec:
  1674. localError(p.config, n.info, errXMustBeCompileTime % n.sons[0].sym.name.s)
  1675. of mCopyStr:
  1676. binaryExpr(p, n, r, "", "($1.slice($2))")
  1677. of mNewString: unaryExpr(p, n, r, "mnewString", "mnewString($1)")
  1678. of mNewStringOfCap:
  1679. unaryExpr(p, n, r, "mnewString", "mnewString(0)")
  1680. of mDotDot:
  1681. genProcForSymIfNeeded(p, n.sons[0].sym)
  1682. genCall(p, n, r)
  1683. of mParseBiggestFloat:
  1684. useMagic(p, "nimParseBiggestFloat")
  1685. genCall(p, n, r)
  1686. of mArray:
  1687. genCall(p, n, r)
  1688. else:
  1689. genCall(p, n, r)
  1690. #else internalError(p.config, e.info, 'genMagic: ' + magicToStr[op]);
  1691. proc genSetConstr(p: PProc, n: PNode, r: var TCompRes) =
  1692. var
  1693. a, b: TCompRes
  1694. useMagic(p, "setConstr")
  1695. r.res = rope("setConstr(")
  1696. r.kind = resExpr
  1697. for i in countup(0, sonsLen(n) - 1):
  1698. if i > 0: add(r.res, ", ")
  1699. var it = n.sons[i]
  1700. if it.kind == nkRange:
  1701. gen(p, it.sons[0], a)
  1702. gen(p, it.sons[1], b)
  1703. addf(r.res, "[$1, $2]", [a.res, b.res])
  1704. else:
  1705. gen(p, it, a)
  1706. add(r.res, a.res)
  1707. add(r.res, ")")
  1708. # emit better code for constant sets:
  1709. if isDeepConstExpr(n):
  1710. inc(p.g.unique)
  1711. let tmp = rope("ConstSet") & rope(p.g.unique)
  1712. addf(p.g.constants, "var $1 = $2;$n", [tmp, r.res])
  1713. r.res = tmp
  1714. proc genArrayConstr(p: PProc, n: PNode, r: var TCompRes) =
  1715. var a: TCompRes
  1716. r.res = rope("[")
  1717. r.kind = resExpr
  1718. for i in countup(0, sonsLen(n) - 1):
  1719. if i > 0: add(r.res, ", ")
  1720. gen(p, n.sons[i], a)
  1721. add(r.res, a.res)
  1722. add(r.res, "]")
  1723. proc genTupleConstr(p: PProc, n: PNode, r: var TCompRes) =
  1724. var a: TCompRes
  1725. r.res = rope("{")
  1726. r.kind = resExpr
  1727. for i in countup(0, sonsLen(n) - 1):
  1728. if i > 0: add(r.res, ", ")
  1729. var it = n.sons[i]
  1730. if it.kind == nkExprColonExpr: it = it.sons[1]
  1731. gen(p, it, a)
  1732. addf(r.res, "Field$#: $#", [i.rope, a.res])
  1733. r.res.add("}")
  1734. proc genObjConstr(p: PProc, n: PNode, r: var TCompRes) =
  1735. var a: TCompRes
  1736. r.kind = resExpr
  1737. var initList : Rope
  1738. var fieldIDs = initIntSet()
  1739. for i in countup(1, sonsLen(n) - 1):
  1740. if i > 1: add(initList, ", ")
  1741. var it = n.sons[i]
  1742. internalAssert p.config, it.kind == nkExprColonExpr
  1743. let val = it.sons[1]
  1744. gen(p, val, a)
  1745. var f = it.sons[0].sym
  1746. if f.loc.r == nil: f.loc.r = mangleName(p.module, f)
  1747. fieldIDs.incl(f.id)
  1748. let typ = val.typ.skipTypes(abstractInst)
  1749. if (typ.kind in IntegralTypes+{tyCstring, tyRef, tyPtr} and
  1750. mapType(p, typ) != etyBaseIndex) or needsNoCopy(p, it.sons[1]):
  1751. discard
  1752. else:
  1753. useMagic(p, "nimCopy")
  1754. a.res = "nimCopy(null, $1, $2)" % [a.rdLoc, genTypeInfo(p, typ)]
  1755. addf(initList, "$#: $#", [f.loc.r, a.res])
  1756. let t = skipTypes(n.typ, abstractInst + skipPtrs)
  1757. createObjInitList(p, t, fieldIDs, initList)
  1758. r.res = ("{$1}") % [initList]
  1759. proc genConv(p: PProc, n: PNode, r: var TCompRes) =
  1760. var dest = skipTypes(n.typ, abstractVarRange)
  1761. var src = skipTypes(n.sons[1].typ, abstractVarRange)
  1762. gen(p, n.sons[1], r)
  1763. if dest.kind == src.kind:
  1764. # no-op conversion
  1765. return
  1766. case dest.kind:
  1767. of tyBool:
  1768. r.res = "(!!($1))" % [r.res]
  1769. r.kind = resExpr
  1770. of tyInt:
  1771. r.res = "(($1)|0)" % [r.res]
  1772. else:
  1773. # TODO: What types must we handle here?
  1774. discard
  1775. proc upConv(p: PProc, n: PNode, r: var TCompRes) =
  1776. gen(p, n.sons[0], r) # XXX
  1777. proc genRangeChck(p: PProc, n: PNode, r: var TCompRes, magic: string) =
  1778. var a, b: TCompRes
  1779. gen(p, n.sons[0], r)
  1780. if optRangeCheck in p.options:
  1781. gen(p, n.sons[1], a)
  1782. gen(p, n.sons[2], b)
  1783. useMagic(p, "chckRange")
  1784. r.res = "chckRange($1, $2, $3)" % [r.res, a.res, b.res]
  1785. r.kind = resExpr
  1786. proc convStrToCStr(p: PProc, n: PNode, r: var TCompRes) =
  1787. # we do an optimization here as this is likely to slow down
  1788. # much of the code otherwise:
  1789. if n.sons[0].kind == nkCStringToString:
  1790. gen(p, n.sons[0].sons[0], r)
  1791. else:
  1792. gen(p, n.sons[0], r)
  1793. if r.res == nil: internalError(p.config, n.info, "convStrToCStr")
  1794. useMagic(p, "toJSStr")
  1795. r.res = "toJSStr($1)" % [r.res]
  1796. r.kind = resExpr
  1797. proc convCStrToStr(p: PProc, n: PNode, r: var TCompRes) =
  1798. # we do an optimization here as this is likely to slow down
  1799. # much of the code otherwise:
  1800. if n.sons[0].kind == nkStringToCString:
  1801. gen(p, n.sons[0].sons[0], r)
  1802. else:
  1803. gen(p, n.sons[0], r)
  1804. if r.res == nil: internalError(p.config, n.info, "convCStrToStr")
  1805. useMagic(p, "cstrToNimstr")
  1806. r.res = "cstrToNimstr($1)" % [r.res]
  1807. r.kind = resExpr
  1808. proc genReturnStmt(p: PProc, n: PNode) =
  1809. if p.procDef == nil: internalError(p.config, n.info, "genReturnStmt")
  1810. p.beforeRetNeeded = true
  1811. if n.sons[0].kind != nkEmpty:
  1812. genStmt(p, n.sons[0])
  1813. else:
  1814. genLineDir(p, n)
  1815. lineF(p, "break BeforeRet;$n", [])
  1816. proc frameCreate(p: PProc; procname, filename: Rope): Rope =
  1817. let frameFmt =
  1818. "var F={procname:$1,prev:framePtr,filename:$2,line:0};$n"
  1819. result = p.indentLine(frameFmt % [procname, filename])
  1820. result.add p.indentLine(ropes.`%`("framePtr = F;$n", []))
  1821. proc frameDestroy(p: PProc): Rope =
  1822. result = p.indentLine rope(("framePtr = F.prev;") & "\L")
  1823. proc genProcBody(p: PProc, prc: PSym): Rope =
  1824. if hasFrameInfo(p):
  1825. result = frameCreate(p,
  1826. makeJSString(prc.owner.name.s & '.' & prc.name.s),
  1827. makeJSString(toFilename(p.config, prc.info)))
  1828. else:
  1829. result = nil
  1830. if p.beforeRetNeeded:
  1831. result.add p.indentLine(~"BeforeRet: do {$n")
  1832. result.add p.body
  1833. result.add p.indentLine(~"} while (false);$n")
  1834. else:
  1835. add(result, p.body)
  1836. if prc.typ.callConv == ccSysCall:
  1837. result = ("try {$n$1} catch (e) {$n" &
  1838. " alert(\"Unhandled exception:\\n\" + e.message + \"\\n\"$n}") % [result]
  1839. if hasFrameInfo(p):
  1840. add(result, frameDestroy(p))
  1841. proc optionaLine(p: Rope): Rope =
  1842. if p == nil:
  1843. return nil
  1844. else:
  1845. return p & "\L"
  1846. proc genProc(oldProc: PProc, prc: PSym): Rope =
  1847. var
  1848. resultSym: PSym
  1849. a: TCompRes
  1850. #if gVerbosity >= 3:
  1851. # echo "BEGIN generating code for: " & prc.name.s
  1852. var p = newProc(oldProc.g, oldProc.module, prc.ast, prc.options)
  1853. p.up = oldProc
  1854. var returnStmt: Rope = nil
  1855. var resultAsgn: Rope = nil
  1856. var name = mangleName(p.module, prc)
  1857. let header = generateHeader(p, prc.typ)
  1858. if prc.typ.sons[0] != nil and sfPure notin prc.flags:
  1859. resultSym = prc.ast.sons[resultPos].sym
  1860. let mname = mangleName(p.module, resultSym)
  1861. let resVar = createVar(p, resultSym.typ, isIndirect(resultSym))
  1862. resultAsgn = p.indentLine(("var $# = $#;$n") % [mname, resVar])
  1863. if resultSym.typ.kind in {tyVar, tyPtr, tyLent, tyRef} and
  1864. mapType(p, resultSym.typ) == etyBaseIndex:
  1865. resultAsgn.add p.indentLine("var $#_Idx = 0;$n" % [mname])
  1866. gen(p, prc.ast.sons[resultPos], a)
  1867. if mapType(p, resultSym.typ) == etyBaseIndex:
  1868. returnStmt = "return [$#, $#];$n" % [a.address, a.res]
  1869. else:
  1870. returnStmt = "return $#;$n" % [a.res]
  1871. let transformed_body = transformBody(oldProc.module.graph, prc, cache = false)
  1872. p.nested: genStmt(p, transformed_body)
  1873. var def: Rope
  1874. if not prc.constraint.isNil:
  1875. def = (prc.constraint.strVal & " {$n$#$#$#$#$#") %
  1876. [ returnType,
  1877. name,
  1878. header,
  1879. optionaLine(p.globals),
  1880. optionaLine(p.locals),
  1881. optionaLine(resultAsgn),
  1882. optionaLine(genProcBody(p, prc)),
  1883. optionaLine(p.indentLine(returnStmt))]
  1884. else:
  1885. result = ~"\L"
  1886. if optHotCodeReloading in p.config.options:
  1887. # Here, we introduce thunks that create the equivalent of a jump table
  1888. # for all global functions, because references to them may be stored
  1889. # in JavaScript variables. The added indirection ensures that such
  1890. # references will end up calling the reloaded code.
  1891. var thunkName = name
  1892. name = name & "IMLP"
  1893. result.add("function $#() { return $#.apply(this, arguments); }$n" %
  1894. [thunkName, name])
  1895. def = "function $#($#) {$n$#$#$#$#$#" %
  1896. [ name,
  1897. header,
  1898. optionaLine(p.globals),
  1899. optionaLine(p.locals),
  1900. optionaLine(resultAsgn),
  1901. optionaLine(genProcBody(p, prc)),
  1902. optionaLine(p.indentLine(returnStmt))]
  1903. dec p.extraIndent
  1904. result.add p.indentLine(def)
  1905. result.add p.indentLine(~"}$n")
  1906. #if gVerbosity >= 3:
  1907. # echo "END generated code for: " & prc.name.s
  1908. proc genStmt(p: PProc, n: PNode) =
  1909. var r: TCompRes
  1910. gen(p, n, r)
  1911. if r.res != nil: lineF(p, "$#;$n", [r.res])
  1912. proc genPragma(p: PProc, n: PNode) =
  1913. for it in n.sons:
  1914. case whichPragma(it)
  1915. of wEmit: genAsmOrEmitStmt(p, it.sons[1])
  1916. else: discard
  1917. proc genCast(p: PProc, n: PNode, r: var TCompRes) =
  1918. var dest = skipTypes(n.typ, abstractVarRange)
  1919. var src = skipTypes(n.sons[1].typ, abstractVarRange)
  1920. gen(p, n.sons[1], r)
  1921. if dest.kind == src.kind:
  1922. # no-op conversion
  1923. return
  1924. let toInt = (dest.kind in tyInt..tyInt32)
  1925. let toUint = (dest.kind in tyUInt..tyUInt32)
  1926. let fromInt = (src.kind in tyInt..tyInt32)
  1927. let fromUint = (src.kind in tyUInt..tyUInt32)
  1928. if toUint and (fromInt or fromUint):
  1929. let trimmer = unsignedTrimmer(dest.size)
  1930. r.res = "($1 $2)" % [r.res, trimmer]
  1931. elif toInt:
  1932. if fromInt:
  1933. let trimmer = unsignedTrimmer(dest.size)
  1934. r.res = "($1 $2)" % [r.res, trimmer]
  1935. elif fromUint:
  1936. if src.size == 4 and dest.size == 4:
  1937. # XXX prevent multi evaluations
  1938. r.res = "($1|0)" % [r.res]
  1939. else:
  1940. let trimmer = unsignedTrimmer(dest.size)
  1941. let minuend = case dest.size
  1942. of 1: "0xfe"
  1943. of 2: "0xfffe"
  1944. of 4: "0xfffffffe"
  1945. else: ""
  1946. r.res = "($1 - ($2 $3))" % [rope minuend, r.res, trimmer]
  1947. proc gen(p: PProc, n: PNode, r: var TCompRes) =
  1948. r.typ = etyNone
  1949. if r.kind != resCallee: r.kind = resNone
  1950. #r.address = nil
  1951. r.res = nil
  1952. case n.kind
  1953. of nkSym:
  1954. genSym(p, n, r)
  1955. of nkCharLit..nkUInt64Lit:
  1956. if n.typ.kind == tyBool:
  1957. r.res = if n.intVal == 0: rope"false" else: rope"true"
  1958. else:
  1959. r.res = rope(n.intVal)
  1960. r.kind = resExpr
  1961. of nkNilLit:
  1962. if isEmptyType(n.typ):
  1963. discard
  1964. elif mapType(p, n.typ) == etyBaseIndex:
  1965. r.typ = etyBaseIndex
  1966. r.address = rope"null"
  1967. r.res = rope"0"
  1968. r.kind = resExpr
  1969. else:
  1970. r.res = rope"null"
  1971. r.kind = resExpr
  1972. of nkStrLit..nkTripleStrLit:
  1973. if skipTypes(n.typ, abstractVarRange).kind == tyString:
  1974. if n.strVal.len != 0:
  1975. useMagic(p, "makeNimstrLit")
  1976. r.res = "makeNimstrLit($1)" % [makeJSString(n.strVal)]
  1977. else:
  1978. r.res = rope"[]"
  1979. else:
  1980. r.res = makeJSString(n.strVal, false)
  1981. r.kind = resExpr
  1982. of nkFloatLit..nkFloat64Lit:
  1983. let f = n.floatVal
  1984. case classify(f)
  1985. of fcNaN:
  1986. r.res = rope"NaN"
  1987. of fcNegZero:
  1988. r.res = rope"-0.0"
  1989. of fcZero:
  1990. r.res = rope"0.0"
  1991. of fcInf:
  1992. r.res = rope"Infinity"
  1993. of fcNegInf:
  1994. r.res = rope"-Infinity"
  1995. else: r.res = rope(f.toStrMaxPrecision)
  1996. r.kind = resExpr
  1997. of nkCallKinds:
  1998. if isEmptyType(n.typ): genLineDir(p, n)
  1999. if (n.sons[0].kind == nkSym) and (n.sons[0].sym.magic != mNone):
  2000. genMagic(p, n, r)
  2001. elif n.sons[0].kind == nkSym and sfInfixCall in n.sons[0].sym.flags and
  2002. n.len >= 1:
  2003. genInfixCall(p, n, r)
  2004. else:
  2005. genCall(p, n, r)
  2006. of nkClosure: gen(p, n[0], r)
  2007. of nkCurly: genSetConstr(p, n, r)
  2008. of nkBracket: genArrayConstr(p, n, r)
  2009. of nkPar, nkTupleConstr: genTupleConstr(p, n, r)
  2010. of nkObjConstr: genObjConstr(p, n, r)
  2011. of nkHiddenStdConv, nkHiddenSubConv, nkConv: genConv(p, n, r)
  2012. of nkAddr, nkHiddenAddr:
  2013. genAddr(p, n, r)
  2014. of nkDerefExpr, nkHiddenDeref: genDeref(p, n, r)
  2015. of nkBracketExpr: genArrayAccess(p, n, r)
  2016. of nkDotExpr: genFieldAccess(p, n, r)
  2017. of nkCheckedFieldExpr: genCheckedFieldOp(p, n, nil, r)
  2018. of nkObjDownConv: gen(p, n.sons[0], r)
  2019. of nkObjUpConv: upConv(p, n, r)
  2020. of nkCast: genCast(p, n, r)
  2021. of nkChckRangeF: genRangeChck(p, n, r, "chckRangeF")
  2022. of nkChckRange64: genRangeChck(p, n, r, "chckRange64")
  2023. of nkChckRange: genRangeChck(p, n, r, "chckRange")
  2024. of nkStringToCString: convStrToCStr(p, n, r)
  2025. of nkCStringToString: convCStrToStr(p, n, r)
  2026. of nkEmpty: discard
  2027. of nkLambdaKinds:
  2028. let s = n.sons[namePos].sym
  2029. discard mangleName(p.module, s)
  2030. r.res = s.loc.r
  2031. if lfNoDecl in s.loc.flags or s.magic != mNone: discard
  2032. elif not p.g.generatedSyms.containsOrIncl(s.id):
  2033. add(p.locals, genProc(p, s))
  2034. of nkType: r.res = genTypeInfo(p, n.typ)
  2035. of nkStmtList, nkStmtListExpr:
  2036. # this shows the distinction is nice for backends and should be kept
  2037. # in the frontend
  2038. let isExpr = not isEmptyType(n.typ)
  2039. for i in countup(0, sonsLen(n) - 1 - isExpr.ord):
  2040. genStmt(p, n.sons[i])
  2041. if isExpr:
  2042. gen(p, lastSon(n), r)
  2043. of nkBlockStmt, nkBlockExpr: genBlock(p, n, r)
  2044. of nkIfStmt, nkIfExpr: genIf(p, n, r)
  2045. of nkWhen:
  2046. # This is "when nimvm" node
  2047. gen(p, n.sons[1].sons[0], r)
  2048. of nkWhileStmt: genWhileStmt(p, n)
  2049. of nkVarSection, nkLetSection: genVarStmt(p, n)
  2050. of nkConstSection: discard
  2051. of nkForStmt, nkParForStmt:
  2052. internalError(p.config, n.info, "for statement not eliminated")
  2053. of nkCaseStmt: genCaseJS(p, n, r)
  2054. of nkReturnStmt: genReturnStmt(p, n)
  2055. of nkBreakStmt: genBreakStmt(p, n)
  2056. of nkAsgn: genAsgn(p, n)
  2057. of nkFastAsgn: genFastAsgn(p, n)
  2058. of nkDiscardStmt:
  2059. if n.sons[0].kind != nkEmpty:
  2060. genLineDir(p, n)
  2061. gen(p, n.sons[0], r)
  2062. of nkAsmStmt: genAsmOrEmitStmt(p, n)
  2063. of nkTryStmt: genTry(p, n, r)
  2064. of nkRaiseStmt: genRaiseStmt(p, n)
  2065. of nkTypeSection, nkCommentStmt, nkIteratorDef, nkIncludeStmt,
  2066. nkImportStmt, nkImportExceptStmt, nkExportStmt, nkExportExceptStmt,
  2067. nkFromStmt, nkTemplateDef, nkMacroDef, nkStaticStmt: discard
  2068. of nkPragma: genPragma(p, n)
  2069. of nkProcDef, nkFuncDef, nkMethodDef, nkConverterDef:
  2070. var s = n.sons[namePos].sym
  2071. if {sfExportc, sfCompilerProc} * s.flags == {sfExportc}:
  2072. genSym(p, n.sons[namePos], r)
  2073. r.res = nil
  2074. of nkGotoState, nkState:
  2075. internalError(p.config, n.info, "first class iterators not implemented")
  2076. of nkPragmaBlock: gen(p, n.lastSon, r)
  2077. of nkComesFrom:
  2078. discard "XXX to implement for better stack traces"
  2079. else: internalError(p.config, n.info, "gen: unknown node type: " & $n.kind)
  2080. proc newModule(g: ModuleGraph; module: PSym): BModule =
  2081. new(result)
  2082. result.module = module
  2083. result.sigConflicts = initCountTable[SigHash]()
  2084. if g.backend == nil:
  2085. g.backend = newGlobals()
  2086. result.graph = g
  2087. result.config = g.config
  2088. proc genHeader(): Rope =
  2089. result = (
  2090. "/* Generated by the Nim Compiler v$1 */$n" &
  2091. "/* (c) " & copyrightYear & " Andreas Rumpf */$n$n" &
  2092. "var framePtr = null;$n" &
  2093. "var excHandler = 0;$n" &
  2094. "var lastJSError = null;$n" &
  2095. "if (typeof Int8Array === 'undefined') Int8Array = Array;$n" &
  2096. "if (typeof Int16Array === 'undefined') Int16Array = Array;$n" &
  2097. "if (typeof Int32Array === 'undefined') Int32Array = Array;$n" &
  2098. "if (typeof Uint8Array === 'undefined') Uint8Array = Array;$n" &
  2099. "if (typeof Uint16Array === 'undefined') Uint16Array = Array;$n" &
  2100. "if (typeof Uint32Array === 'undefined') Uint32Array = Array;$n" &
  2101. "if (typeof Float32Array === 'undefined') Float32Array = Array;$n" &
  2102. "if (typeof Float64Array === 'undefined') Float64Array = Array;$n") %
  2103. [rope(VersionAsString)]
  2104. proc genModule(p: PProc, n: PNode) =
  2105. if optStackTrace in p.options:
  2106. add(p.body, frameCreate(p,
  2107. makeJSString("module " & p.module.module.name.s),
  2108. makeJSString(toFilename(p.config, p.module.module.info))))
  2109. let n_transformed = transformStmt(p.module.graph, p.module.module, n)
  2110. genStmt(p, n_transformed)
  2111. if optStackTrace in p.options:
  2112. add(p.body, frameDestroy(p))
  2113. proc myProcess(b: PPassContext, n: PNode): PNode =
  2114. result = n
  2115. let m = BModule(b)
  2116. if passes.skipCodegen(m.config, n): return n
  2117. if m.module == nil: internalError(m.config, n.info, "myProcess")
  2118. let globals = PGlobals(m.graph.backend)
  2119. var p = newProc(globals, m, nil, m.module.options)
  2120. p.unique = globals.unique
  2121. genModule(p, n)
  2122. add(p.g.code, p.locals)
  2123. add(p.g.code, p.body)
  2124. proc wholeCode(graph: ModuleGraph; m: BModule): Rope =
  2125. let globals = PGlobals(graph.backend)
  2126. for prc in globals.forwarded:
  2127. if not globals.generatedSyms.containsOrIncl(prc.id):
  2128. var p = newProc(globals, m, nil, m.module.options)
  2129. attachProc(p, prc)
  2130. var disp = generateMethodDispatchers(graph)
  2131. for i in 0..sonsLen(disp)-1:
  2132. let prc = disp.sons[i].sym
  2133. if not globals.generatedSyms.containsOrIncl(prc.id):
  2134. var p = newProc(globals, m, nil, m.module.options)
  2135. attachProc(p, prc)
  2136. result = globals.typeInfo & globals.constants & globals.code
  2137. proc getClassName(t: PType): Rope =
  2138. var s = t.sym
  2139. if s.isNil or sfAnon in s.flags:
  2140. s = skipTypes(t, abstractPtrs).sym
  2141. if s.isNil or sfAnon in s.flags:
  2142. doAssert(false, "cannot retrieve class name")
  2143. if s.loc.r != nil: result = s.loc.r
  2144. else: result = rope(s.name.s)
  2145. proc genClass(conf: ConfigRef; obj: PType; content: Rope; ext: string) =
  2146. let cls = getClassName(obj)
  2147. let t = skipTypes(obj, abstractPtrs)
  2148. let extends = if t.kind == tyObject and t.sons[0] != nil:
  2149. " extends " & getClassName(t.sons[0])
  2150. else: nil
  2151. let result = ("<?php$n" &
  2152. "/* Generated by the Nim Compiler v$# */$n" &
  2153. "/* (c) " & copyrightYear & " Andreas Rumpf */$n$n" &
  2154. "require_once \"nimsystem.php\";$n" &
  2155. "class $#$# {$n$#$n}$n") %
  2156. [rope(VersionAsString), cls, extends, content]
  2157. let outfile = changeFileExt(completeCFilePath(conf, AbsoluteFile($cls)), ext)
  2158. discard writeRopeIfNotEqual(result, outfile)
  2159. proc myClose(graph: ModuleGraph; b: PPassContext, n: PNode): PNode =
  2160. result = myProcess(b, n)
  2161. var m = BModule(b)
  2162. if passes.skipCodegen(m.config, n): return n
  2163. if sfMainModule in m.module.flags:
  2164. let globals = PGlobals(graph.backend)
  2165. let ext = "js"
  2166. let f = if globals.classes.len == 0: toFilename(m.config, FileIndex m.module.position)
  2167. else: "nimsystem"
  2168. let code = wholeCode(graph, m)
  2169. let outfile =
  2170. if not m.config.outFile.isEmpty:
  2171. if m.config.outFile.string.isAbsolute: m.config.outFile
  2172. else: AbsoluteFile(getCurrentDir() / m.config.outFile.string)
  2173. else:
  2174. changeFileExt(completeCFilePath(m.config, AbsoluteFile f), ext)
  2175. let (outDir, _, _) = splitFile(outfile)
  2176. if not outDir.isEmpty:
  2177. createDir(outDir)
  2178. discard writeRopeIfNotEqual(genHeader() & code, outfile)
  2179. for obj, content in items(globals.classes):
  2180. genClass(m.config, obj, content, ext)
  2181. proc myOpen(graph: ModuleGraph; s: PSym): PPassContext =
  2182. result = newModule(graph, s)
  2183. const JSgenPass* = makePass(myOpen, myProcess, myClose)