jsgen.nim 106 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206
  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, trees, magicsys, options,
  27. nversion, msgs, idents, types,
  28. ropes, wordrecg, renderer,
  29. cgmeth, lowerings, sighashes, modulegraphs, lineinfos,
  30. transf, injectdestructors, sourcemap, astmsgs, backendpragmas,
  31. mangleutils
  32. import pipelineutils
  33. import std/[json, sets, math, tables, intsets]
  34. import std/strutils except addf
  35. when defined(nimPreviewSlimSystem):
  36. import std/[assertions, syncio]
  37. import std/formatfloat
  38. type
  39. TJSGen = object of PPassContext
  40. module: PSym
  41. graph: ModuleGraph
  42. config: ConfigRef
  43. sigConflicts: CountTable[SigHash]
  44. initProc: PProc
  45. BModule = ref TJSGen
  46. TJSTypeKind = enum # necessary JS "types"
  47. etyNone, # no type
  48. etyNull, # null type
  49. etyProc, # proc type
  50. etyBool, # bool type
  51. etySeq, # Nim seq or string type
  52. etyInt, # JavaScript's int
  53. etyFloat, # JavaScript's float
  54. etyString, # JavaScript's string
  55. etyObject, # JavaScript's reference to an object
  56. etyBaseIndex # base + index needed
  57. TResKind = enum
  58. resNone, # not set
  59. resExpr, # is some complex expression
  60. resVal, # is a temporary/value/l-value
  61. resCallee # expression is callee
  62. TCompRes = object
  63. kind: TResKind
  64. typ: TJSTypeKind
  65. res: Rope # result part; index if this is an
  66. # (address, index)-tuple
  67. address: Rope # address of an (address, index)-tuple
  68. tmpLoc: Rope # tmp var which stores the (address, index)
  69. # pair to prevent multiple evals.
  70. # the tmp is initialized upon evaling the
  71. # address.
  72. # might be nil.
  73. # (see `maybeMakeTemp`)
  74. TBlock = object
  75. id: int # the ID of the label; positive means that it
  76. # has been used (i.e. the label should be emitted)
  77. isLoop: bool # whether it's a 'block' or 'while'
  78. PGlobals = ref object of RootObj
  79. typeInfo, constants, code: Rope
  80. forwarded: seq[PSym]
  81. generatedSyms: IntSet
  82. typeInfoGenerated: IntSet
  83. unique: int # for temp identifier generation
  84. inSystem: bool
  85. PProc = ref TProc
  86. TProc = object
  87. procDef: PNode
  88. prc: PSym
  89. globals, locals, body: Rope
  90. options: TOptions
  91. optionsStack: seq[TOptions]
  92. module: BModule
  93. g: PGlobals
  94. beforeRetNeeded: bool
  95. unique: int # for temp identifier generation
  96. blocks: seq[TBlock]
  97. extraIndent: int
  98. previousFileName: string # For frameInfo inside templates.
  99. # legacy: generatedParamCopies and up fields are used for jsNoLambdaLifting
  100. generatedParamCopies: IntSet
  101. up: PProc # up the call chain; required for closure support
  102. template config*(p: PProc): ConfigRef = p.module.config
  103. proc indentLine(p: PProc, r: Rope): Rope =
  104. var p = p
  105. if jsNoLambdaLifting in p.config.legacyFeatures:
  106. var ind = 0
  107. while true:
  108. inc ind, p.blocks.len + p.extraIndent
  109. if p.up == nil or p.up.prc != p.prc.owner:
  110. break
  111. p = p.up
  112. result = repeat(' ', ind*2) & r
  113. else:
  114. let ind = p.blocks.len + p.extraIndent
  115. result = repeat(' ', ind*2) & r
  116. template line(p: PProc, added: string) =
  117. p.body.add(indentLine(p, rope(added)))
  118. template lineF(p: PProc, frmt: FormatStr, args: varargs[Rope]) =
  119. p.body.add(indentLine(p, ropes.`%`(frmt, args)))
  120. template nested(p, body) =
  121. inc p.extraIndent
  122. body
  123. dec p.extraIndent
  124. proc newGlobals(): PGlobals =
  125. result = PGlobals(forwarded: @[],
  126. generatedSyms: initIntSet(),
  127. typeInfoGenerated: initIntSet()
  128. )
  129. proc initCompRes(): TCompRes =
  130. result = TCompRes(address: "", res: "",
  131. tmpLoc: "", typ: etyNone, kind: resNone
  132. )
  133. proc rdLoc(a: TCompRes): Rope {.inline.} =
  134. if a.typ != etyBaseIndex:
  135. result = a.res
  136. else:
  137. result = "$1[$2]" % [a.address, a.res]
  138. proc newProc(globals: PGlobals, module: BModule, procDef: PNode,
  139. options: TOptions): PProc =
  140. result = PProc(
  141. blocks: @[],
  142. optionsStack: if module.initProc != nil: module.initProc.optionsStack
  143. else: @[],
  144. options: options,
  145. module: module,
  146. procDef: procDef,
  147. g: globals,
  148. extraIndent: int(procDef != nil))
  149. if procDef != nil: result.prc = procDef[namePos].sym
  150. proc initProcOptions(module: BModule): TOptions =
  151. result = module.config.options
  152. if PGlobals(module.graph.backend).inSystem:
  153. result.excl(optStackTrace)
  154. proc newInitProc(globals: PGlobals, module: BModule): PProc =
  155. result = newProc(globals, module, nil, initProcOptions(module))
  156. const
  157. MappedToObject = {tyObject, tyArray, tyTuple, tyOpenArray,
  158. tySet, tyVarargs}
  159. proc mapType(typ: PType): TJSTypeKind =
  160. let t = skipTypes(typ, abstractInst)
  161. case t.kind
  162. of tyVar, tyRef, tyPtr:
  163. if skipTypes(t.elementType, abstractInst).kind in MappedToObject:
  164. result = etyObject
  165. else:
  166. result = etyBaseIndex
  167. of tyPointer:
  168. # treat a tyPointer like a typed pointer to an array of bytes
  169. result = etyBaseIndex
  170. of tyRange, tyDistinct, tyOrdinal, tyProxy, tyLent:
  171. # tyLent is no-op as JS has pass-by-reference semantics
  172. result = mapType(skipModifier t)
  173. of tyInt..tyInt64, tyUInt..tyUInt64, tyEnum, tyChar: result = etyInt
  174. of tyBool: result = etyBool
  175. of tyFloat..tyFloat128: result = etyFloat
  176. of tySet: result = etyObject # map a set to a table
  177. of tyString, tySequence: result = etySeq
  178. of tyObject, tyArray, tyTuple, tyOpenArray, tyVarargs, tyUncheckedArray:
  179. result = etyObject
  180. of tyNil: result = etyNull
  181. of tyGenericParam, tyGenericBody, tyGenericInvocation,
  182. tyNone, tyFromExpr, tyForward, tyEmpty,
  183. tyUntyped, tyTyped, tyTypeDesc, tyBuiltInTypeClass, tyCompositeTypeClass,
  184. tyAnd, tyOr, tyNot, tyAnything, tyVoid:
  185. result = etyNone
  186. of tyGenericInst, tyInferred, tyAlias, tyUserTypeClass, tyUserTypeClassInst,
  187. tySink, tyOwned:
  188. result = mapType(typ.skipModifier)
  189. of tyStatic:
  190. if t.n != nil: result = mapType(skipModifier t)
  191. else: result = etyNone
  192. of tyProc: result = etyProc
  193. of tyCstring: result = etyString
  194. of tyConcept, tyIterable:
  195. raiseAssert "unreachable"
  196. proc mapType(p: PProc; typ: PType): TJSTypeKind =
  197. result = mapType(typ)
  198. proc mangleName(m: BModule, s: PSym): Rope =
  199. proc validJsName(name: string): bool =
  200. result = true
  201. const reservedWords = ["abstract", "await", "boolean", "break", "byte",
  202. "case", "catch", "char", "class", "const", "continue", "debugger",
  203. "default", "delete", "do", "double", "else", "enum", "export", "extends",
  204. "false", "final", "finally", "float", "for", "function", "goto", "if",
  205. "implements", "import", "in", "instanceof", "int", "interface", "let",
  206. "long", "native", "new", "null", "package", "private", "protected",
  207. "public", "return", "short", "static", "super", "switch", "synchronized",
  208. "this", "throw", "throws", "transient", "true", "try", "typeof", "var",
  209. "void", "volatile", "while", "with", "yield"]
  210. case name
  211. of reservedWords:
  212. return false
  213. else:
  214. discard
  215. if name[0] in {'0'..'9'}: return false
  216. for chr in name:
  217. if chr notin {'A'..'Z','a'..'z','_','$','0'..'9'}:
  218. return false
  219. result = s.loc.snippet
  220. if result == "":
  221. if s.kind == skField and s.name.s.validJsName:
  222. result = rope(s.name.s)
  223. elif s.kind == skTemp:
  224. result = rope(mangle(s.name.s))
  225. else:
  226. var x = newStringOfCap(s.name.s.len)
  227. var i = 0
  228. while i < s.name.s.len:
  229. let c = s.name.s[i]
  230. case c
  231. of 'A'..'Z', 'a'..'z', '_', '0'..'9':
  232. x.add c
  233. else:
  234. x.add("HEX" & toHex(ord(c), 2))
  235. inc i
  236. result = rope(x)
  237. # From ES5 on reserved words can be used as object field names
  238. if s.kind != skField:
  239. if m.config.hcrOn:
  240. # When hot reloading is enabled, we must ensure that the names
  241. # of functions and types will be preserved across rebuilds:
  242. result.add(idOrSig(s, m.module.name.s, m.sigConflicts, m.config))
  243. elif s.kind == skParam:
  244. result.add mangleParamExt(s)
  245. elif s.kind in routineKinds:
  246. result.add mangleProcNameExt(m.graph, s)
  247. else:
  248. result.add("_")
  249. result.add(rope(s.id))
  250. s.loc.snippet = result
  251. proc escapeJSString(s: string): string =
  252. result = newStringOfCap(s.len + s.len shr 2)
  253. result.add("\"")
  254. for c in items(s):
  255. case c
  256. of '\l': result.add("\\n")
  257. of '\r': result.add("\\r")
  258. of '\t': result.add("\\t")
  259. of '\b': result.add("\\b")
  260. of '\a': result.add("\\a")
  261. of '\e': result.add("\\e")
  262. of '\v': result.add("\\v")
  263. of '\\': result.add("\\\\")
  264. of '\"': result.add("\\\"")
  265. else: result.add(c)
  266. result.add("\"")
  267. proc makeJSString(s: string, escapeNonAscii = true): Rope =
  268. if escapeNonAscii:
  269. result = strutils.escape(s).rope
  270. else:
  271. result = escapeJSString(s).rope
  272. proc makeJsNimStrLit(s: string): Rope =
  273. var x = newStringOfCap(4*s.len+1)
  274. x.add "["
  275. var i = 0
  276. if i < s.len:
  277. x.addInt int64(s[i])
  278. inc i
  279. while i < s.len:
  280. x.add ","
  281. x.addInt int64(s[i])
  282. inc i
  283. x.add "]"
  284. result = rope(x)
  285. include jstypes
  286. proc gen(p: PProc, n: PNode, r: var TCompRes)
  287. proc genStmt(p: PProc, n: PNode)
  288. proc genProc(oldProc: PProc, prc: PSym): Rope
  289. proc genConstant(p: PProc, c: PSym)
  290. proc useMagic(p: PProc, name: string) =
  291. if name.len == 0: return
  292. var s = magicsys.getCompilerProc(p.module.graph, name)
  293. if s != nil:
  294. internalAssert p.config, s.kind in {skProc, skFunc, skMethod, skConverter}
  295. if not p.g.generatedSyms.containsOrIncl(s.id):
  296. let code = genProc(p, s)
  297. p.g.constants.add(code)
  298. else:
  299. if p.prc != nil:
  300. globalError(p.config, p.prc.info, "system module needs: " & name)
  301. else:
  302. rawMessage(p.config, errGenerated, "system module needs: " & name)
  303. proc isSimpleExpr(p: PProc; n: PNode): bool =
  304. # calls all the way down --> can stay expression based
  305. case n.kind
  306. of nkCallKinds, nkBracketExpr, nkDotExpr, nkPar, nkTupleConstr,
  307. nkObjConstr, nkBracket, nkCurly,
  308. nkDerefExpr, nkHiddenDeref, nkAddr, nkHiddenAddr,
  309. nkConv, nkHiddenStdConv, nkHiddenSubConv:
  310. for c in n:
  311. if not p.isSimpleExpr(c): return false
  312. result = true
  313. of nkStmtListExpr:
  314. for i in 0..<n.len-1:
  315. if n[i].kind notin {nkCommentStmt, nkEmpty}: return false
  316. result = isSimpleExpr(p, n.lastSon)
  317. else:
  318. result = n.isAtom
  319. proc getTemp(p: PProc, defineInLocals: bool = true): Rope =
  320. inc(p.unique)
  321. result = "Temporary$1" % [rope(p.unique)]
  322. if defineInLocals:
  323. p.locals.add(p.indentLine("var $1;$n" % [result]))
  324. proc genAnd(p: PProc, a, b: PNode, r: var TCompRes) =
  325. assert r.kind == resNone
  326. var x, y: TCompRes = default(TCompRes)
  327. if p.isSimpleExpr(a) and p.isSimpleExpr(b):
  328. gen(p, a, x)
  329. gen(p, b, y)
  330. r.kind = resExpr
  331. r.res = "($1 && $2)" % [x.rdLoc, y.rdLoc]
  332. else:
  333. r.res = p.getTemp
  334. r.kind = resVal
  335. # while a and b:
  336. # -->
  337. # while true:
  338. # aa
  339. # if not a: tmp = false
  340. # else:
  341. # bb
  342. # tmp = b
  343. # tmp
  344. gen(p, a, x)
  345. lineF(p, "if (!$1) $2 = false; else {", [x.rdLoc, r.rdLoc])
  346. p.nested:
  347. gen(p, b, y)
  348. lineF(p, "$2 = $1;", [y.rdLoc, r.rdLoc])
  349. line(p, "}")
  350. proc genOr(p: PProc, a, b: PNode, r: var TCompRes) =
  351. assert r.kind == resNone
  352. var x, y: TCompRes = default(TCompRes)
  353. if p.isSimpleExpr(a) and p.isSimpleExpr(b):
  354. gen(p, a, x)
  355. gen(p, b, y)
  356. r.kind = resExpr
  357. r.res = "($1 || $2)" % [x.rdLoc, y.rdLoc]
  358. else:
  359. r.res = p.getTemp
  360. r.kind = resVal
  361. gen(p, a, x)
  362. lineF(p, "if ($1) $2 = true; else {", [x.rdLoc, r.rdLoc])
  363. p.nested:
  364. gen(p, b, y)
  365. lineF(p, "$2 = $1;", [y.rdLoc, r.rdLoc])
  366. line(p, "}")
  367. type
  368. TMagicFrmt = array[0..1, string]
  369. TMagicOps = array[mAddI..mStrToStr, TMagicFrmt]
  370. const # magic checked op; magic unchecked op;
  371. jsMagics: TMagicOps = [
  372. mAddI: ["addInt", ""],
  373. mSubI: ["subInt", ""],
  374. mMulI: ["mulInt", ""],
  375. mDivI: ["divInt", ""],
  376. mModI: ["modInt", ""],
  377. mSucc: ["addInt", ""],
  378. mPred: ["subInt", ""],
  379. mAddF64: ["", ""],
  380. mSubF64: ["", ""],
  381. mMulF64: ["", ""],
  382. mDivF64: ["", ""],
  383. mShrI: ["", ""],
  384. mShlI: ["", ""],
  385. mAshrI: ["", ""],
  386. mBitandI: ["", ""],
  387. mBitorI: ["", ""],
  388. mBitxorI: ["", ""],
  389. mMinI: ["nimMin", "nimMin"],
  390. mMaxI: ["nimMax", "nimMax"],
  391. mAddU: ["", ""],
  392. mSubU: ["", ""],
  393. mMulU: ["", ""],
  394. mDivU: ["", ""],
  395. mModU: ["", ""],
  396. mEqI: ["", ""],
  397. mLeI: ["", ""],
  398. mLtI: ["", ""],
  399. mEqF64: ["", ""],
  400. mLeF64: ["", ""],
  401. mLtF64: ["", ""],
  402. mLeU: ["", ""],
  403. mLtU: ["", ""],
  404. mEqEnum: ["", ""],
  405. mLeEnum: ["", ""],
  406. mLtEnum: ["", ""],
  407. mEqCh: ["", ""],
  408. mLeCh: ["", ""],
  409. mLtCh: ["", ""],
  410. mEqB: ["", ""],
  411. mLeB: ["", ""],
  412. mLtB: ["", ""],
  413. mEqRef: ["", ""],
  414. mLePtr: ["", ""],
  415. mLtPtr: ["", ""],
  416. mXor: ["", ""],
  417. mEqCString: ["", ""],
  418. mEqProc: ["", ""],
  419. mUnaryMinusI: ["negInt", ""],
  420. mUnaryMinusI64: ["negInt64", ""],
  421. mAbsI: ["absInt", ""],
  422. mNot: ["", ""],
  423. mUnaryPlusI: ["", ""],
  424. mBitnotI: ["", ""],
  425. mUnaryPlusF64: ["", ""],
  426. mUnaryMinusF64: ["", ""],
  427. mCharToStr: ["nimCharToStr", "nimCharToStr"],
  428. mBoolToStr: ["nimBoolToStr", "nimBoolToStr"],
  429. mCStrToStr: ["cstrToNimstr", "cstrToNimstr"],
  430. mStrToStr: ["", ""]]
  431. proc needsTemp(p: PProc; n: PNode): bool =
  432. # check if n contains a call to determine
  433. # if a temp should be made to prevent multiple evals
  434. result = false
  435. if n.kind in nkCallKinds + {nkTupleConstr, nkObjConstr, nkBracket, nkCurly}:
  436. return true
  437. for c in n:
  438. if needsTemp(p, c):
  439. return true
  440. proc maybeMakeTemp(p: PProc, n: PNode; x: TCompRes): tuple[a, tmp: Rope] =
  441. var
  442. a = x.rdLoc
  443. b = a
  444. if needsTemp(p, n):
  445. # if we have tmp just use it
  446. if x.tmpLoc != "" and (mapType(n.typ) == etyBaseIndex or n.kind in {nkHiddenDeref, nkDerefExpr}):
  447. b = "$1[0][$1[1]]" % [x.tmpLoc]
  448. (a: a, tmp: b)
  449. else:
  450. let tmp = p.getTemp
  451. b = tmp
  452. a = "($1 = $2, $1)" % [tmp, a]
  453. (a: a, tmp: b)
  454. else:
  455. (a: a, tmp: b)
  456. proc maybeMakeTempAssignable(p: PProc, n: PNode; x: TCompRes): tuple[a, tmp: Rope] =
  457. var
  458. a = x.rdLoc
  459. b = a
  460. if needsTemp(p, n):
  461. # if we have tmp just use it
  462. if x.tmpLoc != "" and (mapType(n.typ) == etyBaseIndex or n.kind in {nkHiddenDeref, nkDerefExpr}):
  463. b = "$1[0][$1[1]]" % [x.tmpLoc]
  464. result = (a: a, tmp: b)
  465. elif x.tmpLoc != "" and n.kind == nkBracketExpr:
  466. # genArrayAddr
  467. var
  468. address, index: TCompRes = default(TCompRes)
  469. first: Int128 = Zero
  470. gen(p, n[0], address)
  471. gen(p, n[1], index)
  472. let (m1, tmp1) = maybeMakeTemp(p, n[0], address)
  473. let typ = skipTypes(n[0].typ, abstractPtrs)
  474. if typ.kind == tyArray:
  475. first = firstOrd(p.config, typ.indexType)
  476. if optBoundsCheck in p.options:
  477. useMagic(p, "chckIndx")
  478. if first == 0: # save a couple chars
  479. index.res = "chckIndx($1, 0, ($2).length - 1)" % [index.res, tmp1]
  480. else:
  481. index.res = "chckIndx($1, $2, ($3).length + ($2) - 1) - ($2)" % [
  482. index.res, rope(first), tmp1]
  483. elif first != 0:
  484. index.res = "($1) - ($2)" % [index.res, rope(first)]
  485. else:
  486. discard # index.res = index.res
  487. let (n1, tmp2) = maybeMakeTemp(p, n[1], index)
  488. result = (a: "$1[$2]" % [m1, n1], tmp: "$1[$2]" % [tmp1, tmp2])
  489. # could also put here: nkDotExpr -> genFieldAccess, nkCheckedFieldExpr -> genCheckedFieldOp
  490. # but the uses of maybeMakeTempAssignable don't need them
  491. else:
  492. result = (a: a, tmp: b)
  493. else:
  494. result = (a: a, tmp: b)
  495. template binaryExpr(p: PProc, n: PNode, r: var TCompRes, magic, frmt: string,
  496. reassign = false) =
  497. # $1 and $2 in the `frmt` string bind to lhs and rhs of the expr,
  498. # if $3 or $4 are present they will be substituted with temps for
  499. # lhs and rhs respectively
  500. var x, y: TCompRes = default(TCompRes)
  501. useMagic(p, magic)
  502. gen(p, n[1], x)
  503. gen(p, n[2], y)
  504. var
  505. a, tmp = x.rdLoc
  506. b, tmp2 = y.rdLoc
  507. when reassign:
  508. (a, tmp) = maybeMakeTempAssignable(p, n[1], x)
  509. else:
  510. when "$3" in frmt: (a, tmp) = maybeMakeTemp(p, n[1], x)
  511. when "$4" in frmt: (b, tmp2) = maybeMakeTemp(p, n[2], y)
  512. r.res = frmt % [a, b, tmp, tmp2]
  513. r.kind = resExpr
  514. proc unsignedTrimmer(size: BiggestInt): string =
  515. case size
  516. of 1: "& 0xff"
  517. of 2: "& 0xffff"
  518. of 4: ">>> 0"
  519. else: ""
  520. proc signedTrimmer(size: BiggestInt): string =
  521. # sign extension is done by shifting to the left and then back to the right
  522. "<< $1 >> $1" % [$(32 - size * 8)]
  523. proc binaryUintExpr(p: PProc, n: PNode, r: var TCompRes, op: string,
  524. reassign: static[bool] = false) =
  525. var x, y: TCompRes = default(TCompRes)
  526. gen(p, n[1], x)
  527. gen(p, n[2], y)
  528. let size = n[1].typ.skipTypes(abstractRange).size
  529. when reassign:
  530. let (a, tmp) = maybeMakeTempAssignable(p, n[1], x)
  531. if size == 8 and optJsBigInt64 in p.config.globalOptions:
  532. r.res = "$1 = BigInt.asUintN(64, ($4 $2 $3))" % [a, rope op, y.rdLoc, tmp]
  533. else:
  534. let trimmer = unsignedTrimmer(size)
  535. r.res = "$1 = (($5 $2 $3) $4)" % [a, rope op, y.rdLoc, trimmer, tmp]
  536. else:
  537. if size == 8 and optJsBigInt64 in p.config.globalOptions:
  538. r.res = "BigInt.asUintN(64, ($1 $2 $3))" % [x.rdLoc, rope op, y.rdLoc]
  539. else:
  540. let trimmer = unsignedTrimmer(size)
  541. r.res = "(($1 $2 $3) $4)" % [x.rdLoc, rope op, y.rdLoc, trimmer]
  542. r.kind = resExpr
  543. template ternaryExpr(p: PProc, n: PNode, r: var TCompRes, magic, frmt: string) =
  544. var x, y, z: TCompRes
  545. useMagic(p, magic)
  546. gen(p, n[1], x)
  547. gen(p, n[2], y)
  548. gen(p, n[3], z)
  549. r.res = frmt % [x.rdLoc, y.rdLoc, z.rdLoc]
  550. r.kind = resExpr
  551. template unaryExpr(p: PProc, n: PNode, r: var TCompRes, magic, frmt: string) =
  552. # $1 binds to n[1], if $2 is present it will be substituted to a tmp of $1
  553. useMagic(p, magic)
  554. gen(p, n[1], r)
  555. var a, tmp = r.rdLoc
  556. if "$2" in frmt: (a, tmp) = maybeMakeTemp(p, n[1], r)
  557. r.res = frmt % [a, tmp]
  558. r.kind = resExpr
  559. proc arithAux(p: PProc, n: PNode, r: var TCompRes, op: TMagic) =
  560. var
  561. x, y: TCompRes = default(TCompRes)
  562. xLoc, yLoc: Rope = ""
  563. let i = ord(optOverflowCheck notin p.options)
  564. useMagic(p, jsMagics[op][i])
  565. if n.len > 2:
  566. gen(p, n[1], x)
  567. gen(p, n[2], y)
  568. xLoc = x.rdLoc
  569. yLoc = y.rdLoc
  570. else:
  571. gen(p, n[1], r)
  572. xLoc = r.rdLoc
  573. template applyFormat(frmt) =
  574. r.res = frmt % [xLoc, yLoc]
  575. template applyFormat(frmtA, frmtB) =
  576. if i == 0: applyFormat(frmtA) else: applyFormat(frmtB)
  577. template bitwiseExpr(op: string) =
  578. let typ = n[1].typ.skipTypes(abstractVarRange)
  579. if typ.kind in {tyUInt, tyUInt32}:
  580. r.res = "(($1 $2 $3) >>> 0)" % [xLoc, op, yLoc]
  581. else:
  582. r.res = "($1 $2 $3)" % [xLoc, op, yLoc]
  583. case op
  584. of mAddI:
  585. if i == 0:
  586. if n[1].typ.size == 8 and optJsBigInt64 in p.config.globalOptions:
  587. useMagic(p, "addInt64")
  588. applyFormat("addInt64($1, $2)")
  589. else:
  590. applyFormat("addInt($1, $2)")
  591. else:
  592. applyFormat("($1 + $2)")
  593. of mSubI:
  594. if i == 0:
  595. if n[1].typ.size == 8 and optJsBigInt64 in p.config.globalOptions:
  596. useMagic(p, "subInt64")
  597. applyFormat("subInt64($1, $2)")
  598. else:
  599. applyFormat("subInt($1, $2)")
  600. else:
  601. applyFormat("($1 - $2)")
  602. of mMulI:
  603. if i == 0:
  604. if n[1].typ.size == 8 and optJsBigInt64 in p.config.globalOptions:
  605. useMagic(p, "mulInt64")
  606. applyFormat("mulInt64($1, $2)")
  607. else:
  608. applyFormat("mulInt($1, $2)")
  609. else:
  610. applyFormat("($1 * $2)")
  611. of mDivI:
  612. if n[1].typ.size == 8 and optJsBigInt64 in p.config.globalOptions:
  613. useMagic(p, "divInt64")
  614. applyFormat("divInt64($1, $2)", "$1 / $2")
  615. else:
  616. applyFormat("divInt($1, $2)", "Math.trunc($1 / $2)")
  617. of mModI:
  618. if n[1].typ.size == 8 and optJsBigInt64 in p.config.globalOptions:
  619. useMagic(p, "modInt64")
  620. applyFormat("modInt64($1, $2)", "$1 % $2")
  621. else:
  622. applyFormat("modInt($1, $2)", "Math.trunc($1 % $2)")
  623. of mSucc:
  624. let typ = n[1].typ.skipTypes(abstractVarRange)
  625. case typ.kind
  626. of tyUInt..tyUInt32:
  627. binaryUintExpr(p, n, r, "+")
  628. of tyUInt64:
  629. if optJsBigInt64 in p.config.globalOptions:
  630. applyFormat("BigInt.asUintN(64, $1 + BigInt($2))")
  631. else: binaryUintExpr(p, n, r, "+")
  632. elif typ.kind == tyInt64 and optJsBigInt64 in p.config.globalOptions:
  633. if optOverflowCheck notin p.options:
  634. applyFormat("BigInt.asIntN(64, $1 + BigInt($2))")
  635. else: binaryExpr(p, n, r, "addInt64", "addInt64($1, BigInt($2))")
  636. else:
  637. if optOverflowCheck notin p.options: applyFormat("$1 + $2")
  638. else: binaryExpr(p, n, r, "addInt", "addInt($1, $2)")
  639. of mPred:
  640. let typ = n[1].typ.skipTypes(abstractVarRange)
  641. case typ.kind
  642. of tyUInt..tyUInt32:
  643. binaryUintExpr(p, n, r, "-")
  644. of tyUInt64:
  645. if optJsBigInt64 in p.config.globalOptions:
  646. applyFormat("BigInt.asUintN(64, $1 - BigInt($2))")
  647. else: binaryUintExpr(p, n, r, "-")
  648. elif typ.kind == tyInt64 and optJsBigInt64 in p.config.globalOptions:
  649. if optOverflowCheck notin p.options:
  650. applyFormat("BigInt.asIntN(64, $1 - BigInt($2))")
  651. else: binaryExpr(p, n, r, "subInt64", "subInt64($1, BigInt($2))")
  652. else:
  653. if optOverflowCheck notin p.options: applyFormat("$1 - $2")
  654. else: binaryExpr(p, n, r, "subInt", "subInt($1, $2)")
  655. of mAddF64: applyFormat("($1 + $2)", "($1 + $2)")
  656. of mSubF64: applyFormat("($1 - $2)", "($1 - $2)")
  657. of mMulF64: applyFormat("($1 * $2)", "($1 * $2)")
  658. of mDivF64: applyFormat("($1 / $2)", "($1 / $2)")
  659. of mShrI:
  660. let typ = n[1].typ.skipTypes(abstractVarRange)
  661. if typ.kind == tyInt64 and optJsBigInt64 in p.config.globalOptions:
  662. applyFormat("BigInt.asIntN(64, BigInt.asUintN(64, $1) >> BigInt($2))")
  663. elif typ.kind == tyUInt64 and optJsBigInt64 in p.config.globalOptions:
  664. applyFormat("($1 >> BigInt($2))")
  665. else:
  666. if typ.kind in {tyInt..tyInt32}:
  667. let trimmerU = unsignedTrimmer(typ.size)
  668. let trimmerS = signedTrimmer(typ.size)
  669. r.res = "((($1 $2) >>> $3) $4)" % [xLoc, trimmerU, yLoc, trimmerS]
  670. else:
  671. applyFormat("($1 >>> $2)")
  672. of mShlI:
  673. let typ = n[1].typ.skipTypes(abstractVarRange)
  674. if typ.size == 8:
  675. if typ.kind == tyInt64 and optJsBigInt64 in p.config.globalOptions:
  676. applyFormat("BigInt.asIntN(64, $1 << BigInt($2))")
  677. elif typ.kind == tyUInt64 and optJsBigInt64 in p.config.globalOptions:
  678. applyFormat("BigInt.asUintN(64, $1 << BigInt($2))")
  679. else:
  680. applyFormat("($1 * Math.pow(2, $2))")
  681. else:
  682. if typ.kind in {tyUInt..tyUInt32}:
  683. let trimmer = unsignedTrimmer(typ.size)
  684. r.res = "(($1 << $2) $3)" % [xLoc, yLoc, trimmer]
  685. else:
  686. let trimmer = signedTrimmer(typ.size)
  687. r.res = "(($1 << $2) $3)" % [xLoc, yLoc, trimmer]
  688. of mAshrI:
  689. let typ = n[1].typ.skipTypes(abstractVarRange)
  690. if typ.size == 8:
  691. if optJsBigInt64 in p.config.globalOptions:
  692. applyFormat("($1 >> BigInt($2))")
  693. else:
  694. applyFormat("Math.floor($1 / Math.pow(2, $2))")
  695. else:
  696. if typ.kind in {tyUInt..tyUInt32}:
  697. applyFormat("($1 >>> $2)")
  698. else:
  699. applyFormat("($1 >> $2)")
  700. of mBitandI: bitwiseExpr("&")
  701. of mBitorI: bitwiseExpr("|")
  702. of mBitxorI: bitwiseExpr("^")
  703. of mMinI: applyFormat("nimMin($1, $2)", "nimMin($1, $2)")
  704. of mMaxI: applyFormat("nimMax($1, $2)", "nimMax($1, $2)")
  705. of mAddU: applyFormat("", "")
  706. of mSubU: applyFormat("", "")
  707. of mMulU: applyFormat("", "")
  708. of mDivU: applyFormat("", "")
  709. of mModU: applyFormat("($1 % $2)", "($1 % $2)")
  710. of mEqI: applyFormat("($1 == $2)", "($1 == $2)")
  711. of mLeI: applyFormat("($1 <= $2)", "($1 <= $2)")
  712. of mLtI: applyFormat("($1 < $2)", "($1 < $2)")
  713. of mEqF64: applyFormat("($1 == $2)", "($1 == $2)")
  714. of mLeF64: applyFormat("($1 <= $2)", "($1 <= $2)")
  715. of mLtF64: applyFormat("($1 < $2)", "($1 < $2)")
  716. of mLeU: applyFormat("($1 <= $2)", "($1 <= $2)")
  717. of mLtU: applyFormat("($1 < $2)", "($1 < $2)")
  718. of mEqEnum: applyFormat("($1 == $2)", "($1 == $2)")
  719. of mLeEnum: applyFormat("($1 <= $2)", "($1 <= $2)")
  720. of mLtEnum: applyFormat("($1 < $2)", "($1 < $2)")
  721. of mEqCh: applyFormat("($1 == $2)", "($1 == $2)")
  722. of mLeCh: applyFormat("($1 <= $2)", "($1 <= $2)")
  723. of mLtCh: applyFormat("($1 < $2)", "($1 < $2)")
  724. of mEqB: applyFormat("($1 == $2)", "($1 == $2)")
  725. of mLeB: applyFormat("($1 <= $2)", "($1 <= $2)")
  726. of mLtB: applyFormat("($1 < $2)", "($1 < $2)")
  727. of mEqRef: applyFormat("($1 == $2)", "($1 == $2)")
  728. of mLePtr: applyFormat("($1 <= $2)", "($1 <= $2)")
  729. of mLtPtr: applyFormat("($1 < $2)", "($1 < $2)")
  730. of mXor: applyFormat("($1 != $2)", "($1 != $2)")
  731. of mEqCString: applyFormat("($1 == $2)", "($1 == $2)")
  732. of mEqProc: applyFormat("($1 == $2)", "($1 == $2)")
  733. of mUnaryMinusI: applyFormat("negInt($1)", "-($1)")
  734. of mUnaryMinusI64: applyFormat("negInt64($1)", "-($1)")
  735. of mAbsI:
  736. let typ = n[1].typ.skipTypes(abstractVarRange)
  737. if typ.kind == tyInt64 and optJsBigInt64 in p.config.globalOptions:
  738. useMagic(p, "absInt64")
  739. applyFormat("absInt64($1)", "absInt64($1)")
  740. else:
  741. applyFormat("absInt($1)", "Math.abs($1)")
  742. of mNot: applyFormat("!($1)", "!($1)")
  743. of mUnaryPlusI: applyFormat("+($1)", "+($1)")
  744. of mBitnotI:
  745. let typ = n[1].typ.skipTypes(abstractVarRange)
  746. if typ.kind in {tyUInt..tyUInt64}:
  747. if typ.size == 8 and optJsBigInt64 in p.config.globalOptions:
  748. applyFormat("BigInt.asUintN(64, ~($1))")
  749. else:
  750. let trimmer = unsignedTrimmer(typ.size)
  751. r.res = "(~($1) $2)" % [xLoc, trimmer]
  752. else:
  753. applyFormat("~($1)")
  754. of mUnaryPlusF64: applyFormat("+($1)", "+($1)")
  755. of mUnaryMinusF64: applyFormat("-($1)", "-($1)")
  756. of mCharToStr: applyFormat("nimCharToStr($1)", "nimCharToStr($1)")
  757. of mBoolToStr: applyFormat("nimBoolToStr($1)", "nimBoolToStr($1)")
  758. of mCStrToStr: applyFormat("cstrToNimstr($1)", "cstrToNimstr($1)")
  759. of mStrToStr, mUnown, mIsolate, mFinished: applyFormat("$1", "$1")
  760. else:
  761. assert false, $op
  762. proc arith(p: PProc, n: PNode, r: var TCompRes, op: TMagic) =
  763. case op
  764. of mAddU: binaryUintExpr(p, n, r, "+")
  765. of mSubU: binaryUintExpr(p, n, r, "-")
  766. of mMulU: binaryUintExpr(p, n, r, "*")
  767. of mDivU:
  768. binaryUintExpr(p, n, r, "/")
  769. if optJsBigInt64 notin p.config.globalOptions and
  770. n[1].typ.skipTypes(abstractRange).size == 8:
  771. # bigint / already truncates
  772. r.res = "Math.trunc($1)" % [r.res]
  773. of mDivI:
  774. arithAux(p, n, r, op)
  775. of mModI:
  776. arithAux(p, n, r, op)
  777. of mCharToStr, mBoolToStr, mCStrToStr, mStrToStr, mEnumToStr:
  778. arithAux(p, n, r, op)
  779. of mEqRef:
  780. if mapType(n[1].typ) != etyBaseIndex:
  781. arithAux(p, n, r, op)
  782. else:
  783. var x, y: TCompRes = default(TCompRes)
  784. gen(p, n[1], x)
  785. gen(p, n[2], y)
  786. r.res = "($# == $# && $# == $#)" % [x.address, y.address, x.res, y.res]
  787. of mEqProc:
  788. if skipTypes(n[1].typ, abstractInst).callConv == ccClosure:
  789. binaryExpr(p, n, r, "cmpClosures", "cmpClosures($1, $2)")
  790. else:
  791. arithAux(p, n, r, op)
  792. else:
  793. arithAux(p, n, r, op)
  794. r.kind = resExpr
  795. proc hasFrameInfo(p: PProc): bool =
  796. ({optLineTrace, optStackTrace} * p.options == {optLineTrace, optStackTrace}) and
  797. ((p.prc == nil) or not (sfPure in p.prc.flags))
  798. proc lineDir(config: ConfigRef, info: TLineInfo, line: int): Rope =
  799. "/* line $2:$3 \"$1\" */$n" % [
  800. rope(toFullPath(config, info)), rope(line), rope(info.toColumn)
  801. ]
  802. proc genLineDir(p: PProc, n: PNode) =
  803. let line = toLinenumber(n.info)
  804. if line < 0:
  805. return
  806. if optEmbedOrigSrc in p.config.globalOptions:
  807. lineF(p, "//$1$n", [sourceLine(p.config, n.info)])
  808. if optLineDir in p.options or optLineDir in p.config.options:
  809. lineF(p, "$1", [lineDir(p.config, n.info, line)])
  810. if hasFrameInfo(p):
  811. lineF(p, "F.line = $1;$n", [rope(line)])
  812. let currentFileName = toFilename(p.config, n.info)
  813. if p.previousFileName != currentFileName:
  814. lineF(p, "F.filename = $1;$n", [makeJSString(currentFileName)])
  815. p.previousFileName = currentFileName
  816. proc genWhileStmt(p: PProc, n: PNode) =
  817. var cond: TCompRes = default(TCompRes)
  818. internalAssert p.config, isEmptyType(n.typ)
  819. genLineDir(p, n)
  820. inc(p.unique)
  821. setLen(p.blocks, p.blocks.len + 1)
  822. p.blocks[^1].id = -p.unique
  823. p.blocks[^1].isLoop = true
  824. let labl = p.unique.rope
  825. lineF(p, "Label$1: while (true) {$n", [labl])
  826. p.nested: gen(p, n[0], cond)
  827. lineF(p, "if (!$1) break Label$2;$n",
  828. [cond.res, labl])
  829. p.nested: genStmt(p, n[1])
  830. lineF(p, "}$n", [labl])
  831. setLen(p.blocks, p.blocks.len - 1)
  832. proc moveInto(p: PProc, src: var TCompRes, dest: TCompRes) =
  833. if src.kind != resNone:
  834. if dest.kind != resNone:
  835. lineF(p, "$1 = $2;$n", [dest.rdLoc, src.rdLoc])
  836. else:
  837. lineF(p, "$1;$n", [src.rdLoc])
  838. src.kind = resNone
  839. src.res = ""
  840. proc genTry(p: PProc, n: PNode, r: var TCompRes) =
  841. # code to generate:
  842. #
  843. # ++excHandler;
  844. # var tmpFramePtr = framePtr;
  845. # try {
  846. # stmts;
  847. # --excHandler;
  848. # } catch (EXCEPTION) {
  849. # var prevJSError = lastJSError; lastJSError = EXCEPTION;
  850. # framePtr = tmpFramePtr;
  851. # --excHandler;
  852. # if (e.typ && e.typ == NTI433 || e.typ == NTI2321) {
  853. # stmts;
  854. # } else if (e.typ && e.typ == NTI32342) {
  855. # stmts;
  856. # } else {
  857. # stmts;
  858. # }
  859. # lastJSError = prevJSError;
  860. # } finally {
  861. # framePtr = tmpFramePtr;
  862. # stmts;
  863. # }
  864. genLineDir(p, n)
  865. if not isEmptyType(n.typ):
  866. r.kind = resVal
  867. r.res = getTemp(p)
  868. inc(p.unique)
  869. var i = 1
  870. var catchBranchesExist = n.len > 1 and n[i].kind == nkExceptBranch
  871. if catchBranchesExist:
  872. p.body.add("++excHandler;\L")
  873. var tmpFramePtr = rope"F"
  874. lineF(p, "try {$n", [])
  875. var a: TCompRes = default(TCompRes)
  876. gen(p, n[0], a)
  877. moveInto(p, a, r)
  878. var generalCatchBranchExists = false
  879. if catchBranchesExist:
  880. p.body.addf("--excHandler;$n} catch (EXCEPTION) {$n var prevJSError = lastJSError;$n" &
  881. " lastJSError = EXCEPTION;$n --excHandler;$n", [])
  882. if hasFrameInfo(p):
  883. line(p, "framePtr = $1;$n" % [tmpFramePtr])
  884. while i < n.len and n[i].kind == nkExceptBranch:
  885. if n[i].len == 1:
  886. # general except section:
  887. generalCatchBranchExists = true
  888. if i > 1: lineF(p, "else {$n", [])
  889. gen(p, n[i][0], a)
  890. moveInto(p, a, r)
  891. if i > 1: lineF(p, "}$n", [])
  892. else:
  893. var orExpr: Rope = ""
  894. var excAlias: PNode = nil
  895. useMagic(p, "isObj")
  896. for j in 0..<n[i].len - 1:
  897. var throwObj: PNode
  898. let it = n[i][j]
  899. if it.isInfixAs():
  900. throwObj = it[1]
  901. excAlias = it[2]
  902. # If this is a ``except exc as sym`` branch there must be no following
  903. # nodes
  904. doAssert orExpr == ""
  905. elif it.kind == nkType:
  906. throwObj = it
  907. else:
  908. throwObj = nil
  909. internalError(p.config, n.info, "genTryStmt")
  910. if orExpr != "": orExpr.add("||")
  911. # Generate the correct type checking code depending on whether this is a
  912. # NIM-native or a JS-native exception
  913. # if isJsObject(throwObj.typ):
  914. if isImportedException(throwObj.typ, p.config):
  915. orExpr.addf("lastJSError instanceof $1",
  916. [throwObj.typ.sym.loc.snippet])
  917. else:
  918. orExpr.addf("isObj(lastJSError.m_type, $1)",
  919. [genTypeInfo(p, throwObj.typ)])
  920. if i > 1: line(p, "else ")
  921. lineF(p, "if (lastJSError && ($1)) {$n", [orExpr])
  922. # If some branch requires a local alias introduce it here. This is needed
  923. # since JS cannot do ``catch x as y``.
  924. if excAlias != nil:
  925. excAlias.sym.loc.snippet = mangleName(p.module, excAlias.sym)
  926. lineF(p, "var $1 = lastJSError;$n", excAlias.sym.loc.snippet)
  927. gen(p, n[i][^1], a)
  928. moveInto(p, a, r)
  929. lineF(p, "}$n", [])
  930. inc(i)
  931. if catchBranchesExist:
  932. if not generalCatchBranchExists:
  933. useMagic(p, "reraiseException")
  934. line(p, "else {\L")
  935. line(p, "\treraiseException();\L")
  936. line(p, "}\L")
  937. lineF(p, "lastJSError = prevJSError;$n")
  938. line(p, "} finally {\L")
  939. if hasFrameInfo(p):
  940. line(p, "framePtr = $1;$n" % [tmpFramePtr])
  941. if i < n.len and n[i].kind == nkFinally:
  942. genStmt(p, n[i][0])
  943. line(p, "}\L")
  944. proc genRaiseStmt(p: PProc, n: PNode) =
  945. if n[0].kind != nkEmpty:
  946. var a: TCompRes = default(TCompRes)
  947. gen(p, n[0], a)
  948. let typ = skipTypes(n[0].typ, abstractPtrs)
  949. genLineDir(p, n)
  950. useMagic(p, "raiseException")
  951. lineF(p, "raiseException($1, $2);$n",
  952. [a.rdLoc, makeJSString(typ.sym.name.s)])
  953. else:
  954. genLineDir(p, n)
  955. useMagic(p, "reraiseException")
  956. line(p, "reraiseException();\L")
  957. proc genCaseJS(p: PProc, n: PNode, r: var TCompRes) =
  958. var
  959. a, b, cond, stmt: TCompRes = default(TCompRes)
  960. genLineDir(p, n)
  961. gen(p, n[0], cond)
  962. let typeKind = skipTypes(n[0].typ, abstractVar+{tyRange}).kind
  963. var transferRange = false
  964. let anyString = typeKind in {tyString, tyCstring}
  965. case typeKind
  966. of tyString:
  967. useMagic(p, "toJSStr")
  968. lineF(p, "switch (toJSStr($1)) {$n", [cond.rdLoc])
  969. of tyFloat..tyFloat128, tyInt..tyInt64, tyUInt..tyUInt64:
  970. transferRange = true
  971. else:
  972. lineF(p, "switch ($1) {$n", [cond.rdLoc])
  973. if not isEmptyType(n.typ):
  974. r.kind = resVal
  975. r.res = getTemp(p)
  976. for i in 1..<n.len:
  977. let it = n[i]
  978. let itLen = it.len
  979. case it.kind
  980. of nkOfBranch:
  981. if transferRange:
  982. if i == 1:
  983. lineF(p, "if (", [])
  984. else:
  985. lineF(p, "else if (", [])
  986. for j in 0..<itLen - 1:
  987. let e = it[j]
  988. if e.kind == nkRange:
  989. if transferRange:
  990. gen(p, e[0], a)
  991. gen(p, e[1], b)
  992. if j != itLen - 2:
  993. lineF(p, "$1 >= $2 && $1 <= $3 || $n", [cond.rdLoc, a.rdLoc, b.rdLoc])
  994. else:
  995. lineF(p, "$1 >= $2 && $1 <= $3", [cond.rdLoc, a.rdLoc, b.rdLoc])
  996. else:
  997. var v = copyNode(e[0])
  998. while v.intVal <= e[1].intVal:
  999. gen(p, v, cond)
  1000. lineF(p, "case $1:$n", [cond.rdLoc])
  1001. inc(v.intVal)
  1002. else:
  1003. if anyString:
  1004. case e.kind
  1005. of nkStrLit..nkTripleStrLit: lineF(p, "case $1:$n",
  1006. [makeJSString(e.strVal, false)])
  1007. of nkNilLit: lineF(p, "case null:$n", [])
  1008. else: internalError(p.config, e.info, "jsgen.genCaseStmt: 2")
  1009. else:
  1010. if transferRange:
  1011. gen(p, e, a)
  1012. if j != itLen - 2:
  1013. lineF(p, "$1 == $2 || $n", [cond.rdLoc, a.rdLoc])
  1014. else:
  1015. lineF(p, "$1 == $2", [cond.rdLoc, a.rdLoc])
  1016. else:
  1017. gen(p, e, a)
  1018. lineF(p, "case $1:$n", [a.rdLoc])
  1019. if transferRange:
  1020. lineF(p, "){", [])
  1021. p.nested:
  1022. gen(p, lastSon(it), stmt)
  1023. moveInto(p, stmt, r)
  1024. if transferRange:
  1025. lineF(p, "}$n", [])
  1026. else:
  1027. lineF(p, "break;$n", [])
  1028. of nkElse:
  1029. if transferRange:
  1030. lineF(p, "else{$n", [])
  1031. else:
  1032. lineF(p, "default: $n", [])
  1033. p.nested:
  1034. gen(p, it[0], stmt)
  1035. moveInto(p, stmt, r)
  1036. if transferRange:
  1037. lineF(p, "}$n", [])
  1038. else:
  1039. lineF(p, "break;$n", [])
  1040. else: internalError(p.config, it.info, "jsgen.genCaseStmt")
  1041. if not transferRange:
  1042. lineF(p, "}$n", [])
  1043. proc genBlock(p: PProc, n: PNode, r: var TCompRes) =
  1044. inc(p.unique)
  1045. let idx = p.blocks.len
  1046. if n[0].kind != nkEmpty:
  1047. # named block?
  1048. if (n[0].kind != nkSym): internalError(p.config, n.info, "genBlock")
  1049. var sym = n[0].sym
  1050. sym.loc.k = locOther
  1051. sym.position = idx+1
  1052. let labl = p.unique
  1053. lineF(p, "Label$1: {$n", [labl.rope])
  1054. setLen(p.blocks, idx + 1)
  1055. p.blocks[idx].id = - p.unique # negative because it isn't used yet
  1056. gen(p, n[1], r)
  1057. setLen(p.blocks, idx)
  1058. lineF(p, "};$n", [labl.rope])
  1059. proc genBreakStmt(p: PProc, n: PNode) =
  1060. var idx: int
  1061. genLineDir(p, n)
  1062. if n[0].kind != nkEmpty:
  1063. # named break?
  1064. assert(n[0].kind == nkSym)
  1065. let sym = n[0].sym
  1066. assert(sym.loc.k == locOther)
  1067. idx = sym.position-1
  1068. else:
  1069. # an unnamed 'break' can only break a loop after 'transf' pass:
  1070. idx = p.blocks.len - 1
  1071. while idx >= 0 and not p.blocks[idx].isLoop: dec idx
  1072. if idx < 0 or not p.blocks[idx].isLoop:
  1073. internalError(p.config, n.info, "no loop to break")
  1074. p.blocks[idx].id = abs(p.blocks[idx].id) # label is used
  1075. lineF(p, "break Label$1;$n", [rope(p.blocks[idx].id)])
  1076. proc genAsmOrEmitStmt(p: PProc, n: PNode; isAsmStmt = false) =
  1077. genLineDir(p, n)
  1078. p.body.add p.indentLine("")
  1079. let offset =
  1080. if isAsmStmt: 1 # first son is pragmas
  1081. else: 0
  1082. for i in offset..<n.len:
  1083. let it = n[i]
  1084. case it.kind
  1085. of nkStrLit..nkTripleStrLit:
  1086. p.body.add(it.strVal)
  1087. of nkSym:
  1088. let v = it.sym
  1089. # for backwards compatibility we don't deref syms here :-(
  1090. if false:
  1091. discard
  1092. else:
  1093. var r = default(TCompRes)
  1094. gen(p, it, r)
  1095. if it.typ.kind == tyPointer:
  1096. # A fat pointer is disguised as an array
  1097. r.res = r.address
  1098. r.address = ""
  1099. r.typ = etyNone
  1100. elif r.typ == etyBaseIndex:
  1101. # Deference first
  1102. r.res = "$1[$2]" % [r.address, r.res]
  1103. r.address = ""
  1104. r.typ = etyNone
  1105. p.body.add(r.rdLoc)
  1106. else:
  1107. var r: TCompRes = default(TCompRes)
  1108. gen(p, it, r)
  1109. p.body.add(r.rdLoc)
  1110. p.body.add "\L"
  1111. proc genIf(p: PProc, n: PNode, r: var TCompRes) =
  1112. var cond, stmt: TCompRes = default(TCompRes)
  1113. var toClose = 0
  1114. if not isEmptyType(n.typ):
  1115. r.kind = resVal
  1116. r.res = getTemp(p)
  1117. for i in 0..<n.len:
  1118. let it = n[i]
  1119. if it.len != 1:
  1120. if i > 0:
  1121. lineF(p, "else {$n", [])
  1122. inc(toClose)
  1123. p.nested: gen(p, it[0], cond)
  1124. lineF(p, "if ($1) {$n", [cond.rdLoc])
  1125. gen(p, it[1], stmt)
  1126. else:
  1127. # else part:
  1128. lineF(p, "else {$n", [])
  1129. p.nested: gen(p, it[0], stmt)
  1130. moveInto(p, stmt, r)
  1131. lineF(p, "}$n", [])
  1132. line(p, repeat('}', toClose) & "\L")
  1133. proc generateHeader(p: PProc, prc: PSym): Rope =
  1134. result = ""
  1135. let typ = prc.typ
  1136. if jsNoLambdaLifting notin p.config.legacyFeatures:
  1137. if typ.callConv == ccClosure:
  1138. # we treat Env as the `this` parameter of the function
  1139. # to keep it simple
  1140. let env = prc.ast[paramsPos].lastSon
  1141. assert env.kind == nkSym, "env is missing"
  1142. env.sym.loc.snippet = "this"
  1143. for i in 1..<typ.n.len:
  1144. assert(typ.n[i].kind == nkSym)
  1145. var param = typ.n[i].sym
  1146. if isCompileTimeOnly(param.typ): continue
  1147. if result != "": result.add(", ")
  1148. var name = mangleName(p.module, param)
  1149. result.add(name)
  1150. if mapType(param.typ) == etyBaseIndex:
  1151. result.add(", ")
  1152. result.add(name)
  1153. result.add("_Idx")
  1154. proc countJsParams(typ: PType): int =
  1155. result = 0
  1156. for i in 1..<typ.n.len:
  1157. assert(typ.n[i].kind == nkSym)
  1158. var param = typ.n[i].sym
  1159. if isCompileTimeOnly(param.typ): continue
  1160. if mapType(param.typ) == etyBaseIndex:
  1161. inc result, 2
  1162. else:
  1163. inc result
  1164. const
  1165. nodeKindsNeedNoCopy = {nkCharLit..nkInt64Lit, nkStrLit..nkTripleStrLit,
  1166. nkFloatLit..nkFloat64Lit, nkPar, nkStringToCString,
  1167. nkObjConstr, nkTupleConstr, nkBracket,
  1168. nkCStringToString, nkCall, nkPrefix, nkPostfix, nkInfix,
  1169. nkCommand, nkHiddenCallConv, nkCallStrLit}
  1170. proc needsNoCopy(p: PProc; y: PNode): bool =
  1171. return y.kind in nodeKindsNeedNoCopy or
  1172. ((mapType(y.typ) != etyBaseIndex or
  1173. (jsNoLambdaLifting in p.config.legacyFeatures and y.kind == nkSym and y.sym.kind == skParam)) and
  1174. (skipTypes(y.typ, abstractInst).kind in
  1175. {tyRef, tyPtr, tyLent, tyVar, tyCstring, tyProc, tyOwned, tyOpenArray} + IntegralTypes))
  1176. proc genAsgnAux(p: PProc, x, y: PNode, noCopyNeeded: bool) =
  1177. var a, b: TCompRes = default(TCompRes)
  1178. var xtyp = mapType(p, x.typ)
  1179. # disable `[]=` for cstring
  1180. if x.kind == nkBracketExpr and x.len >= 2 and x[0].typ.skipTypes(abstractInst).kind == tyCstring:
  1181. localError(p.config, x.info, "cstring doesn't support `[]=` operator")
  1182. gen(p, x, a)
  1183. genLineDir(p, y)
  1184. gen(p, y, b)
  1185. # we don't care if it's an etyBaseIndex (global) of a string, it's
  1186. # still a string that needs to be copied properly:
  1187. if x.typ.skipTypes(abstractInst).kind in {tySequence, tyString}:
  1188. xtyp = etySeq
  1189. case xtyp
  1190. of etySeq:
  1191. if x.typ.kind in {tyVar, tyLent} or (needsNoCopy(p, y) and needsNoCopy(p, x)) or noCopyNeeded:
  1192. lineF(p, "$1 = $2;$n", [a.rdLoc, b.rdLoc])
  1193. else:
  1194. useMagic(p, "nimCopy")
  1195. lineF(p, "$1 = nimCopy(null, $2, $3);$n",
  1196. [a.rdLoc, b.res, genTypeInfo(p, y.typ)])
  1197. of etyObject:
  1198. if x.typ.kind in {tyVar, tyLent, tyOpenArray, tyVarargs} or (needsNoCopy(p, y) and needsNoCopy(p, x)) or noCopyNeeded:
  1199. lineF(p, "$1 = $2;$n", [a.rdLoc, b.rdLoc])
  1200. else:
  1201. useMagic(p, "nimCopy")
  1202. # supports proc getF(): var T
  1203. if x.kind in {nkHiddenDeref, nkDerefExpr} and x[0].kind in nkCallKinds:
  1204. lineF(p, "nimCopy($1, $2, $3);$n",
  1205. [a.res, b.res, genTypeInfo(p, x.typ)])
  1206. else:
  1207. lineF(p, "$1 = nimCopy($1, $2, $3);$n",
  1208. [a.res, b.res, genTypeInfo(p, x.typ)])
  1209. of etyBaseIndex:
  1210. if a.typ != etyBaseIndex or b.typ != etyBaseIndex:
  1211. if y.kind == nkCall:
  1212. let tmp = p.getTemp(false)
  1213. lineF(p, "var $1 = $4; $2 = $1[0]; $3 = $1[1];$n", [tmp, a.address, a.res, b.rdLoc])
  1214. elif b.typ == etyBaseIndex:
  1215. lineF(p, "$# = [$#, $#];$n", [a.res, b.address, b.res])
  1216. elif b.typ == etyNone:
  1217. internalAssert p.config, b.address == ""
  1218. lineF(p, "$# = [$#, 0];$n", [a.address, b.res])
  1219. elif x.typ.kind == tyVar and y.typ.kind == tyPtr:
  1220. lineF(p, "$# = [$#, $#];$n", [a.res, b.address, b.res])
  1221. lineF(p, "$1 = $2;$n", [a.address, b.res])
  1222. lineF(p, "$1 = $2;$n", [a.rdLoc, b.rdLoc])
  1223. elif a.typ == etyBaseIndex:
  1224. # array indexing may not map to var type
  1225. if b.address != "":
  1226. lineF(p, "$1 = $2; $3 = $4;$n", [a.address, b.address, a.res, b.res])
  1227. else:
  1228. lineF(p, "$1 = $2;$n", [a.address, b.res])
  1229. else:
  1230. internalError(p.config, x.info, $("genAsgn", b.typ, a.typ))
  1231. elif b.address != "":
  1232. lineF(p, "$1 = $2; $3 = $4;$n", [a.address, b.address, a.res, b.res])
  1233. else:
  1234. lineF(p, "$1 = $2;$n", [a.address, b.res])
  1235. else:
  1236. lineF(p, "$1 = $2;$n", [a.rdLoc, b.rdLoc])
  1237. proc genAsgn(p: PProc, n: PNode) =
  1238. genAsgnAux(p, n[0], n[1], noCopyNeeded=false)
  1239. proc genFastAsgn(p: PProc, n: PNode) =
  1240. # 'shallowCopy' always produced 'noCopyNeeded = true' here but this is wrong
  1241. # for code like
  1242. # while j >= pos:
  1243. # dest[i].shallowCopy(dest[j])
  1244. # See bug #5933. So we try to be more compatible with the C backend semantics
  1245. # here for 'shallowCopy'. This is an educated guess and might require further
  1246. # changes later:
  1247. let noCopy = n[0].typ.skipTypes(abstractInst).kind in {tySequence, tyString}
  1248. genAsgnAux(p, n[0], n[1], noCopyNeeded=noCopy)
  1249. proc genSwap(p: PProc, n: PNode) =
  1250. let stmtList = lowerSwap(p.module.graph, n, p.module.idgen, if p.prc != nil: p.prc else: p.module.module)
  1251. assert stmtList.kind == nkStmtList
  1252. for i in 0..<stmtList.len:
  1253. genStmt(p, stmtList[i])
  1254. proc getFieldPosition(p: PProc; f: PNode): int =
  1255. case f.kind
  1256. of nkIntLit..nkUInt64Lit: result = int(f.intVal)
  1257. of nkSym: result = f.sym.position
  1258. else:
  1259. result = 0
  1260. internalError(p.config, f.info, "genFieldPosition")
  1261. proc genFieldAddr(p: PProc, n: PNode, r: var TCompRes) =
  1262. var a: TCompRes = default(TCompRes)
  1263. r.typ = etyBaseIndex
  1264. let b = if n.kind == nkHiddenAddr: n[0] else: n
  1265. gen(p, b[0], a)
  1266. if skipTypes(b[0].typ, abstractVarRange).kind == tyTuple:
  1267. r.res = makeJSString("Field" & $getFieldPosition(p, b[1]))
  1268. else:
  1269. if b[1].kind != nkSym: internalError(p.config, b[1].info, "genFieldAddr")
  1270. var f = b[1].sym
  1271. if f.loc.snippet == "": f.loc.snippet = mangleName(p.module, f)
  1272. r.res = makeJSString($f.loc.snippet)
  1273. internalAssert p.config, a.typ != etyBaseIndex
  1274. r.address = a.res
  1275. r.kind = resExpr
  1276. proc genFieldAccess(p: PProc, n: PNode, r: var TCompRes) =
  1277. gen(p, n[0], r)
  1278. r.typ = mapType(n.typ)
  1279. let otyp = skipTypes(n[0].typ, abstractVarRange)
  1280. template mkTemp(i: int) =
  1281. if r.typ == etyBaseIndex:
  1282. if needsTemp(p, n[i]):
  1283. let tmp = p.getTemp
  1284. r.address = "($1 = $2, $1)[0]" % [tmp, r.res]
  1285. r.res = "$1[1]" % [tmp]
  1286. r.tmpLoc = tmp
  1287. else:
  1288. r.address = "$1[0]" % [r.res]
  1289. r.res = "$1[1]" % [r.res]
  1290. if otyp.kind == tyTuple:
  1291. r.res = ("$1.Field$2") %
  1292. [r.res, getFieldPosition(p, n[1]).rope]
  1293. mkTemp(0)
  1294. else:
  1295. if n[1].kind != nkSym: internalError(p.config, n[1].info, "genFieldAccess")
  1296. var f = n[1].sym
  1297. if f.loc.snippet == "": f.loc.snippet = mangleName(p.module, f)
  1298. r.res = "$1.$2" % [r.res, f.loc.snippet]
  1299. mkTemp(1)
  1300. r.kind = resExpr
  1301. proc genAddr(p: PProc, n: PNode, r: var TCompRes)
  1302. proc genCheckedFieldOp(p: PProc, n: PNode, addrTyp: PType, r: var TCompRes) =
  1303. internalAssert p.config, n.kind == nkCheckedFieldExpr
  1304. # nkDotExpr to access the requested field
  1305. let accessExpr = n[0]
  1306. # nkCall to check if the discriminant is valid
  1307. var checkExpr = n[1]
  1308. let negCheck = checkExpr[0].sym.magic == mNot
  1309. if negCheck:
  1310. checkExpr = checkExpr[^1]
  1311. # Field symbol
  1312. var field = accessExpr[1].sym
  1313. internalAssert p.config, field.kind == skField
  1314. if field.loc.snippet == "": field.loc.snippet = mangleName(p.module, field)
  1315. # Discriminant symbol
  1316. let disc = checkExpr[2].sym
  1317. internalAssert p.config, disc.kind == skField
  1318. if disc.loc.snippet == "": disc.loc.snippet = mangleName(p.module, disc)
  1319. var setx: TCompRes = default(TCompRes)
  1320. gen(p, checkExpr[1], setx)
  1321. var obj: TCompRes = default(TCompRes)
  1322. gen(p, accessExpr[0], obj)
  1323. # Avoid evaluating the LHS twice (one to read the discriminant and one to read
  1324. # the field)
  1325. let tmp = p.getTemp()
  1326. lineF(p, "var $1 = $2;$n", tmp, obj.res)
  1327. useMagic(p, "raiseFieldError2")
  1328. useMagic(p, "makeNimstrLit")
  1329. useMagic(p, "reprDiscriminant") # no need to offset by firstOrd unlike for cgen
  1330. let msg = genFieldDefect(p.config, field.name.s, disc)
  1331. lineF(p, "if ($1[$2.$3]$4undefined) { raiseFieldError2(makeNimstrLit($5), reprDiscriminant($2.$3, $6)); }$n",
  1332. setx.res, tmp, disc.loc.snippet, if negCheck: "!==" else: "===",
  1333. makeJSString(msg), genTypeInfo(p, disc.typ))
  1334. if addrTyp != nil and mapType(p, addrTyp) == etyBaseIndex:
  1335. r.typ = etyBaseIndex
  1336. r.res = makeJSString($field.loc.snippet)
  1337. r.address = tmp
  1338. else:
  1339. r.typ = etyNone
  1340. r.res = "$1.$2" % [tmp, field.loc.snippet]
  1341. r.kind = resExpr
  1342. proc genArrayAddr(p: PProc, n: PNode, r: var TCompRes) =
  1343. var
  1344. a, b: TCompRes = default(TCompRes)
  1345. first: Int128 = Zero
  1346. r.typ = etyBaseIndex
  1347. let m = if n.kind == nkHiddenAddr: n[0] else: n
  1348. gen(p, m[0], a)
  1349. gen(p, m[1], b)
  1350. #internalAssert p.config, a.typ != etyBaseIndex and b.typ != etyBaseIndex
  1351. let (x, tmp) = maybeMakeTemp(p, m[0], a)
  1352. r.address = x
  1353. var typ = skipTypes(m[0].typ, abstractPtrs)
  1354. if typ.kind == tyArray:
  1355. first = firstOrd(p.config, typ.indexType)
  1356. if optBoundsCheck in p.options:
  1357. useMagic(p, "chckIndx")
  1358. if first == 0: # save a couple chars
  1359. r.res = "chckIndx($1, 0, ($2).length - 1)" % [b.res, tmp]
  1360. else:
  1361. r.res = "chckIndx($1, $2, ($3).length + ($2) - 1) - ($2)" % [
  1362. b.res, rope(first), tmp]
  1363. elif first != 0:
  1364. r.res = "($1) - ($2)" % [b.res, rope(first)]
  1365. else:
  1366. r.res = b.res
  1367. r.kind = resExpr
  1368. proc genArrayAccess(p: PProc, n: PNode, r: var TCompRes) =
  1369. var ty = skipTypes(n[0].typ, abstractVarRange+tyUserTypeClasses)
  1370. if ty.kind in {tyRef, tyPtr, tyLent, tyOwned}: ty = skipTypes(ty.elementType, abstractVarRange)
  1371. case ty.kind
  1372. of tyArray, tyOpenArray, tySequence, tyString, tyCstring, tyVarargs:
  1373. genArrayAddr(p, n, r)
  1374. of tyTuple:
  1375. genFieldAddr(p, n, r)
  1376. else: internalError(p.config, n.info, "expr(nkBracketExpr, " & $ty.kind & ')')
  1377. r.typ = mapType(n.typ)
  1378. if r.res == "": internalError(p.config, n.info, "genArrayAccess")
  1379. if ty.kind == tyCstring:
  1380. r.res = "$1.charCodeAt($2)" % [r.address, r.res]
  1381. elif r.typ == etyBaseIndex:
  1382. if needsTemp(p, n[0]):
  1383. let tmp = p.getTemp
  1384. r.address = "($1 = $2, $1)[0]" % [tmp, r.rdLoc]
  1385. r.res = "$1[1]" % [tmp]
  1386. r.tmpLoc = tmp
  1387. else:
  1388. let x = r.rdLoc
  1389. r.address = "$1[0]" % [x]
  1390. r.res = "$1[1]" % [x]
  1391. else:
  1392. r.res = "$1[$2]" % [r.address, r.res]
  1393. r.kind = resExpr
  1394. template isIndirect(x: PSym): bool =
  1395. let v = x
  1396. ({sfAddrTaken, sfGlobal} * v.flags != {} and
  1397. #(mapType(v.typ) != etyObject) and
  1398. {sfImportc, sfExportc} * v.flags == {} and
  1399. v.kind notin {skProc, skFunc, skConverter, skMethod, skIterator,
  1400. skConst, skTemp, skLet})
  1401. proc genSymAddr(p: PProc, n: PNode, typ: PType, r: var TCompRes) =
  1402. let s = n.sym
  1403. if s.loc.snippet == "": internalError(p.config, n.info, "genAddr: 3")
  1404. case s.kind
  1405. of skParam:
  1406. r.res = s.loc.snippet
  1407. r.address = ""
  1408. r.typ = etyNone
  1409. of skVar, skLet, skResult:
  1410. r.kind = resExpr
  1411. let jsType = mapType(p):
  1412. if typ.isNil:
  1413. n.typ
  1414. else:
  1415. typ
  1416. if jsType == etyObject:
  1417. # make addr() a no-op:
  1418. r.typ = etyNone
  1419. if isIndirect(s):
  1420. r.res = s.loc.snippet & "[0]"
  1421. else:
  1422. r.res = s.loc.snippet
  1423. r.address = ""
  1424. elif {sfGlobal, sfAddrTaken} * s.flags != {} or jsType == etyBaseIndex:
  1425. # for ease of code generation, we do not distinguish between
  1426. # sfAddrTaken and sfGlobal.
  1427. r.typ = etyBaseIndex
  1428. r.address = s.loc.snippet
  1429. r.res = rope("0")
  1430. else:
  1431. # 'var openArray' for instance produces an 'addr' but this is harmless:
  1432. gen(p, n, r)
  1433. #internalError(p.config, n.info, "genAddr: 4 " & renderTree(n))
  1434. else: internalError(p.config, n.info, $("genAddr: 2", s.kind))
  1435. proc genAddr(p: PProc, n: PNode, r: var TCompRes) =
  1436. if n.kind == nkSym:
  1437. genSymAddr(p, n, nil, r)
  1438. else:
  1439. case n[0].kind
  1440. of nkSym:
  1441. genSymAddr(p, n[0], n.typ, r)
  1442. of nkCheckedFieldExpr:
  1443. genCheckedFieldOp(p, n[0], n.typ, r)
  1444. of nkDotExpr:
  1445. if mapType(p, n.typ) == etyBaseIndex:
  1446. genFieldAddr(p, n[0], r)
  1447. else:
  1448. genFieldAccess(p, n[0], r)
  1449. of nkBracketExpr:
  1450. var ty = skipTypes(n[0].typ, abstractVarRange)
  1451. if ty.kind in MappedToObject:
  1452. gen(p, n[0], r)
  1453. else:
  1454. let kindOfIndexedExpr = skipTypes(n[0][0].typ, abstractVarRange+tyUserTypeClasses).kind
  1455. case kindOfIndexedExpr
  1456. of tyArray, tyOpenArray, tySequence, tyString, tyCstring, tyVarargs:
  1457. genArrayAddr(p, n[0], r)
  1458. of tyTuple:
  1459. genFieldAddr(p, n[0], r)
  1460. of tyGenericBody:
  1461. genAddr(p, n[^1], r)
  1462. else: internalError(p.config, n[0].info, "expr(nkBracketExpr, " & $kindOfIndexedExpr & ')')
  1463. of nkObjDownConv:
  1464. gen(p, n[0], r)
  1465. of nkHiddenDeref:
  1466. gen(p, n[0], r)
  1467. of nkDerefExpr:
  1468. var x = n[0]
  1469. if n.kind == nkHiddenAddr:
  1470. x = n[0][0]
  1471. if n.typ.skipTypes(abstractVar).kind != tyOpenArray:
  1472. x.typ = n.typ
  1473. gen(p, x, r)
  1474. of nkHiddenAddr:
  1475. gen(p, n[0], r)
  1476. of nkConv:
  1477. genAddr(p, n[0], r)
  1478. of nkStmtListExpr:
  1479. if n.len == 1: gen(p, n[0], r)
  1480. else: internalError(p.config, n[0].info, "genAddr for complex nkStmtListExpr")
  1481. of nkCallKinds:
  1482. if n[0].typ.kind == tyOpenArray:
  1483. # 'var openArray' for instance produces an 'addr' but this is harmless:
  1484. # namely toOpenArray(a, 1, 3)
  1485. gen(p, n[0], r)
  1486. else:
  1487. internalError(p.config, n[0].info, "genAddr: " & $n[0].kind)
  1488. else:
  1489. internalError(p.config, n[0].info, "genAddr: " & $n[0].kind)
  1490. proc attachProc(p: PProc; content: Rope; s: PSym) =
  1491. p.g.code.add(content)
  1492. proc attachProc(p: PProc; s: PSym) =
  1493. let newp = genProc(p, s)
  1494. attachProc(p, newp, s)
  1495. proc genProcForSymIfNeeded(p: PProc, s: PSym) =
  1496. if not p.g.generatedSyms.containsOrIncl(s.id):
  1497. if jsNoLambdaLifting in p.config.legacyFeatures:
  1498. let newp = genProc(p, s)
  1499. var owner = p
  1500. while owner != nil and owner.prc != s.owner:
  1501. owner = owner.up
  1502. if owner != nil: owner.locals.add(newp)
  1503. else: attachProc(p, newp, s)
  1504. else:
  1505. attachProc(p, s)
  1506. proc genCopyForParamIfNeeded(p: PProc, n: PNode) =
  1507. let s = n.sym
  1508. if p.prc == s.owner or needsNoCopy(p, n):
  1509. return
  1510. var owner = p.up
  1511. while true:
  1512. if owner == nil:
  1513. internalError(p.config, n.info, "couldn't find the owner proc of the closed over param: " & s.name.s)
  1514. if owner.prc == s.owner:
  1515. if not owner.generatedParamCopies.containsOrIncl(s.id):
  1516. let copy = "$1 = nimCopy(null, $1, $2);$n" % [s.loc.snippet, genTypeInfo(p, s.typ)]
  1517. owner.locals.add(owner.indentLine(copy))
  1518. return
  1519. owner = owner.up
  1520. proc genVarInit(p: PProc, v: PSym, n: PNode)
  1521. proc genSym(p: PProc, n: PNode, r: var TCompRes) =
  1522. var s = n.sym
  1523. case s.kind
  1524. of skVar, skLet, skParam, skTemp, skResult, skForVar:
  1525. if s.loc.snippet == "":
  1526. internalError(p.config, n.info, "symbol has no generated name: " & s.name.s)
  1527. if sfCompileTime in s.flags:
  1528. genVarInit(p, s, if s.astdef != nil: s.astdef else: newNodeI(nkEmpty, s.info))
  1529. if jsNoLambdaLifting in p.config.legacyFeatures and s.kind == skParam:
  1530. genCopyForParamIfNeeded(p, n)
  1531. let k = mapType(p, s.typ)
  1532. if k == etyBaseIndex:
  1533. r.typ = etyBaseIndex
  1534. if {sfAddrTaken, sfGlobal} * s.flags != {}:
  1535. if isIndirect(s):
  1536. r.address = "$1[0][0]" % [s.loc.snippet]
  1537. r.res = "$1[0][1]" % [s.loc.snippet]
  1538. else:
  1539. r.address = "$1[0]" % [s.loc.snippet]
  1540. r.res = "$1[1]" % [s.loc.snippet]
  1541. else:
  1542. r.address = s.loc.snippet
  1543. r.res = s.loc.snippet & "_Idx"
  1544. elif isIndirect(s):
  1545. r.res = "$1[0]" % [s.loc.snippet]
  1546. else:
  1547. r.res = s.loc.snippet
  1548. of skConst:
  1549. genConstant(p, s)
  1550. if s.loc.snippet == "":
  1551. internalError(p.config, n.info, "symbol has no generated name: " & s.name.s)
  1552. r.res = s.loc.snippet
  1553. of skProc, skFunc, skConverter, skMethod, skIterator:
  1554. if sfCompileTime in s.flags:
  1555. localError(p.config, n.info, "request to generate code for .compileTime proc: " &
  1556. s.name.s)
  1557. discard mangleName(p.module, s)
  1558. r.res = s.loc.snippet
  1559. if lfNoDecl in s.loc.flags or s.magic notin generatedMagics or
  1560. {sfImportc, sfInfixCall} * s.flags != {}:
  1561. discard
  1562. elif s.kind == skMethod and getBody(p.module.graph, s).kind == nkEmpty:
  1563. # we cannot produce code for the dispatcher yet:
  1564. discard
  1565. elif sfForward in s.flags:
  1566. p.g.forwarded.add(s)
  1567. else:
  1568. genProcForSymIfNeeded(p, s)
  1569. else:
  1570. if s.loc.snippet == "":
  1571. internalError(p.config, n.info, "symbol has no generated name: " & s.name.s)
  1572. if mapType(p, s.typ) == etyBaseIndex:
  1573. r.address = s.loc.snippet
  1574. r.res = s.loc.snippet & "_Idx"
  1575. else:
  1576. r.res = s.loc.snippet
  1577. r.kind = resVal
  1578. proc genDeref(p: PProc, n: PNode, r: var TCompRes) =
  1579. let it = n[0]
  1580. let t = mapType(p, it.typ)
  1581. if t == etyObject or it.typ.kind == tyLent:
  1582. gen(p, it, r)
  1583. else:
  1584. var a: TCompRes = default(TCompRes)
  1585. gen(p, it, a)
  1586. r.kind = a.kind
  1587. r.typ = mapType(p, n.typ)
  1588. if r.typ == etyBaseIndex:
  1589. let tmp = p.getTemp
  1590. r.address = "($1 = $2, $1)[0]" % [tmp, a.rdLoc]
  1591. r.res = "$1[1]" % [tmp]
  1592. r.tmpLoc = tmp
  1593. elif a.typ == etyBaseIndex:
  1594. if a.tmpLoc != "":
  1595. r.tmpLoc = a.tmpLoc
  1596. r.res = a.rdLoc
  1597. else:
  1598. internalError(p.config, n.info, "genDeref")
  1599. proc genArgNoParam(p: PProc, n: PNode, r: var TCompRes) =
  1600. var a: TCompRes = default(TCompRes)
  1601. gen(p, n, a)
  1602. if a.typ == etyBaseIndex:
  1603. r.res.add(a.address)
  1604. r.res.add(", ")
  1605. r.res.add(a.res)
  1606. else:
  1607. r.res.add(a.res)
  1608. proc genArg(p: PProc, n: PNode, param: PSym, r: var TCompRes; emitted: ptr int = nil) =
  1609. var a: TCompRes = default(TCompRes)
  1610. gen(p, n, a)
  1611. if skipTypes(param.typ, abstractVar).kind in {tyOpenArray, tyVarargs} and
  1612. a.typ == etyBaseIndex:
  1613. r.res.add("$1[$2]" % [a.address, a.res])
  1614. elif a.typ == etyBaseIndex:
  1615. r.res.add(a.address)
  1616. r.res.add(", ")
  1617. r.res.add(a.res)
  1618. if emitted != nil: inc emitted[]
  1619. elif n.typ.kind in {tyVar, tyPtr, tyRef, tyLent, tyOwned} and
  1620. n.kind in nkCallKinds and mapType(param.typ) == etyBaseIndex:
  1621. # this fixes bug #5608:
  1622. let tmp = getTemp(p)
  1623. r.res.add("($1 = $2, $1[0]), $1[1]" % [tmp, a.rdLoc])
  1624. if emitted != nil: inc emitted[]
  1625. else:
  1626. r.res.add(a.res)
  1627. proc genArgs(p: PProc, n: PNode, r: var TCompRes; start=1) =
  1628. r.res.add("(")
  1629. var hasArgs = false
  1630. var typ = skipTypes(n[0].typ, abstractInst)
  1631. assert(typ.kind == tyProc)
  1632. assert(typ.len == typ.n.len)
  1633. var emitted = start-1
  1634. for i in start..<n.len:
  1635. let it = n[i]
  1636. var paramType: PNode = nil
  1637. if i < typ.len:
  1638. assert(typ.n[i].kind == nkSym)
  1639. paramType = typ.n[i]
  1640. if paramType.typ.isCompileTimeOnly: continue
  1641. if hasArgs: r.res.add(", ")
  1642. if paramType.isNil:
  1643. genArgNoParam(p, it, r)
  1644. else:
  1645. genArg(p, it, paramType.sym, r, addr emitted)
  1646. inc emitted
  1647. hasArgs = true
  1648. r.res.add(")")
  1649. when false:
  1650. # XXX look into this:
  1651. let jsp = countJsParams(typ)
  1652. if emitted != jsp and tfVarargs notin typ.flags:
  1653. localError(p.config, n.info, "wrong number of parameters emitted; expected: " & $jsp &
  1654. " but got: " & $emitted)
  1655. r.kind = resExpr
  1656. proc genOtherArg(p: PProc; n: PNode; i: int; typ: PType;
  1657. generated: var int; r: var TCompRes) =
  1658. if i >= n.len:
  1659. globalError(p.config, n.info, "wrong importcpp pattern; expected parameter at position " & $i &
  1660. " but got only: " & $(n.len-1))
  1661. let it = n[i]
  1662. var paramType: PNode = nil
  1663. if i < typ.len:
  1664. assert(typ.n[i].kind == nkSym)
  1665. paramType = typ.n[i]
  1666. if paramType.typ.isCompileTimeOnly: return
  1667. if paramType.isNil:
  1668. genArgNoParam(p, it, r)
  1669. else:
  1670. genArg(p, it, paramType.sym, r)
  1671. inc generated
  1672. proc genPatternCall(p: PProc; n: PNode; pat: string; typ: PType;
  1673. r: var TCompRes) =
  1674. var i = 0
  1675. var j = 1
  1676. r.kind = resExpr
  1677. while i < pat.len:
  1678. case pat[i]
  1679. of '@':
  1680. var generated = 0
  1681. for k in j..<n.len:
  1682. if generated > 0: r.res.add(", ")
  1683. genOtherArg(p, n, k, typ, generated, r)
  1684. inc i
  1685. of '#':
  1686. var generated = 0
  1687. genOtherArg(p, n, j, typ, generated, r)
  1688. inc j
  1689. inc i
  1690. of '\31':
  1691. # unit separator
  1692. r.res.add("#")
  1693. inc i
  1694. of '\29':
  1695. # group separator
  1696. r.res.add("@")
  1697. inc i
  1698. else:
  1699. let start = i
  1700. while i < pat.len:
  1701. if pat[i] notin {'@', '#', '\31', '\29'}: inc(i)
  1702. else: break
  1703. if i - 1 >= start:
  1704. r.res.add(substr(pat, start, i - 1))
  1705. proc genInfixCall(p: PProc, n: PNode, r: var TCompRes) =
  1706. # don't call '$' here for efficiency:
  1707. let f = n[0].sym
  1708. if f.loc.snippet == "": f.loc.snippet = mangleName(p.module, f)
  1709. if sfInfixCall in f.flags:
  1710. let pat = $n[0].sym.loc.snippet
  1711. internalAssert p.config, pat.len > 0
  1712. if pat.contains({'#', '(', '@'}):
  1713. var typ = skipTypes(n[0].typ, abstractInst)
  1714. assert(typ.kind == tyProc)
  1715. genPatternCall(p, n, pat, typ, r)
  1716. return
  1717. if n.len != 1:
  1718. gen(p, n[1], r)
  1719. if r.typ == etyBaseIndex:
  1720. if r.address == "":
  1721. globalError(p.config, n.info, "cannot invoke with infix syntax")
  1722. r.res = "$1[$2]" % [r.address, r.res]
  1723. r.address = ""
  1724. r.typ = etyNone
  1725. r.res.add(".")
  1726. var op: TCompRes = default(TCompRes)
  1727. gen(p, n[0], op)
  1728. r.res.add(op.res)
  1729. genArgs(p, n, r, 2)
  1730. proc genCall(p: PProc, n: PNode, r: var TCompRes) =
  1731. gen(p, n[0], r)
  1732. genArgs(p, n, r)
  1733. if n.typ != nil:
  1734. let t = mapType(n.typ)
  1735. if t == etyBaseIndex:
  1736. let tmp = p.getTemp
  1737. r.address = "($1 = $2, $1)[0]" % [tmp, r.rdLoc]
  1738. r.res = "$1[1]" % [tmp]
  1739. r.tmpLoc = tmp
  1740. r.typ = t
  1741. proc genEcho(p: PProc, n: PNode, r: var TCompRes) =
  1742. let n = n[1].skipConv
  1743. internalAssert p.config, n.kind == nkBracket
  1744. useMagic(p, "toJSStr") # Used in rawEcho
  1745. useMagic(p, "rawEcho")
  1746. r.res.add("rawEcho(")
  1747. for i in 0..<n.len:
  1748. let it = n[i]
  1749. if it.typ.isCompileTimeOnly: continue
  1750. if i > 0: r.res.add(", ")
  1751. genArgNoParam(p, it, r)
  1752. r.res.add(")")
  1753. r.kind = resExpr
  1754. proc putToSeq(s: string, indirect: bool): Rope =
  1755. result = rope(s)
  1756. if indirect: result = "[$1]" % [result]
  1757. proc createVar(p: PProc, typ: PType, indirect: bool): Rope
  1758. proc createRecordVarAux(p: PProc, rec: PNode, excludedFieldIDs: IntSet, output: var Rope) =
  1759. case rec.kind
  1760. of nkRecList:
  1761. for i in 0..<rec.len:
  1762. createRecordVarAux(p, rec[i], excludedFieldIDs, output)
  1763. of nkRecCase:
  1764. createRecordVarAux(p, rec[0], excludedFieldIDs, output)
  1765. for i in 1..<rec.len:
  1766. createRecordVarAux(p, lastSon(rec[i]), excludedFieldIDs, output)
  1767. of nkSym:
  1768. # Do not produce code for void types
  1769. if isEmptyType(rec.sym.typ): return
  1770. if rec.sym.id notin excludedFieldIDs:
  1771. if output.len > 0: output.add(", ")
  1772. output.addf("$#: ", [mangleName(p.module, rec.sym)])
  1773. output.add(createVar(p, rec.sym.typ, false))
  1774. else: internalError(p.config, rec.info, "createRecordVarAux")
  1775. proc createObjInitList(p: PProc, typ: PType, excludedFieldIDs: IntSet, output: var Rope) =
  1776. var t = typ
  1777. if objHasTypeField(t):
  1778. if output.len > 0: output.add(", ")
  1779. output.addf("m_type: $1", [genTypeInfo(p, t)])
  1780. while t != nil:
  1781. t = t.skipTypes(skipPtrs)
  1782. createRecordVarAux(p, t.n, excludedFieldIDs, output)
  1783. t = t.baseClass
  1784. proc arrayTypeForElemType(conf: ConfigRef; typ: PType): string =
  1785. let typ = typ.skipTypes(abstractRange)
  1786. case typ.kind
  1787. of tyInt, tyInt32: "Int32Array"
  1788. of tyInt16: "Int16Array"
  1789. of tyInt8: "Int8Array"
  1790. of tyInt64:
  1791. if optJsBigInt64 in conf.globalOptions:
  1792. "BigInt64Array"
  1793. else:
  1794. ""
  1795. of tyUInt, tyUInt32: "Uint32Array"
  1796. of tyUInt16: "Uint16Array"
  1797. of tyUInt8, tyChar, tyBool: "Uint8Array"
  1798. of tyUInt64:
  1799. if optJsBigInt64 in conf.globalOptions:
  1800. "BigUint64Array"
  1801. else:
  1802. ""
  1803. of tyFloat32: "Float32Array"
  1804. of tyFloat64, tyFloat: "Float64Array"
  1805. of tyEnum:
  1806. case typ.size
  1807. of 1: "Uint8Array"
  1808. of 2: "Uint16Array"
  1809. of 4: "Uint32Array"
  1810. else: ""
  1811. else: ""
  1812. proc createVar(p: PProc, typ: PType, indirect: bool): Rope =
  1813. var t = skipTypes(typ, abstractInst)
  1814. case t.kind
  1815. of tyInt8..tyInt32, tyUInt8..tyUInt32, tyEnum, tyChar:
  1816. result = putToSeq("0", indirect)
  1817. of tyInt, tyUInt:
  1818. if $t.sym.loc.snippet == "bigint":
  1819. result = putToSeq("0n", indirect)
  1820. else:
  1821. result = putToSeq("0", indirect)
  1822. of tyInt64, tyUInt64:
  1823. if optJsBigInt64 in p.config.globalOptions:
  1824. result = putToSeq("0n", indirect)
  1825. else:
  1826. result = putToSeq("0", indirect)
  1827. of tyFloat..tyFloat128:
  1828. result = putToSeq("0.0", indirect)
  1829. of tyRange, tyGenericInst, tyAlias, tySink, tyOwned, tyLent:
  1830. result = createVar(p, skipModifier(typ), indirect)
  1831. of tySet:
  1832. result = putToSeq("{}", indirect)
  1833. of tyBool:
  1834. result = putToSeq("false", indirect)
  1835. of tyNil:
  1836. result = putToSeq("null", indirect)
  1837. of tyArray:
  1838. let length = toInt(lengthOrd(p.config, t))
  1839. let e = elemType(t)
  1840. let jsTyp = arrayTypeForElemType(p.config, e)
  1841. if jsTyp.len > 0:
  1842. result = "new $1($2)" % [rope(jsTyp), rope(length)]
  1843. elif length > 32:
  1844. useMagic(p, "arrayConstr")
  1845. # XXX: arrayConstr depends on nimCopy. This line shouldn't be necessary.
  1846. useMagic(p, "nimCopy")
  1847. result = "arrayConstr($1, $2, $3)" % [rope(length),
  1848. createVar(p, e, false), genTypeInfo(p, e)]
  1849. else:
  1850. result = rope("[")
  1851. var i = 0
  1852. while i < length:
  1853. if i > 0: result.add(", ")
  1854. result.add(createVar(p, e, false))
  1855. inc(i)
  1856. result.add("]")
  1857. if indirect: result = "[$1]" % [result]
  1858. of tyTuple:
  1859. result = rope("{")
  1860. for i in 0..<t.len:
  1861. if i > 0: result.add(", ")
  1862. result.addf("Field$1: $2", [i.rope,
  1863. createVar(p, t[i], false)])
  1864. result.add("}")
  1865. if indirect: result = "[$1]" % [result]
  1866. of tyObject:
  1867. var initList: Rope = ""
  1868. createObjInitList(p, t, initIntSet(), initList)
  1869. result = ("({$1})") % [initList]
  1870. if indirect: result = "[$1]" % [result]
  1871. of tyVar, tyPtr, tyRef, tyPointer:
  1872. if mapType(p, t) == etyBaseIndex:
  1873. result = putToSeq("[null, 0]", indirect)
  1874. else:
  1875. result = putToSeq("null", indirect)
  1876. of tySequence, tyString:
  1877. result = putToSeq("[]", indirect)
  1878. of tyCstring, tyProc, tyOpenArray:
  1879. result = putToSeq("null", indirect)
  1880. of tyStatic:
  1881. if t.n != nil:
  1882. result = createVar(p, skipModifier t, indirect)
  1883. else:
  1884. internalError(p.config, "createVar: " & $t.kind)
  1885. result = ""
  1886. else:
  1887. internalError(p.config, "createVar: " & $t.kind)
  1888. result = ""
  1889. template returnType: untyped = ""
  1890. proc genVarInit(p: PProc, v: PSym, n: PNode) =
  1891. var
  1892. a: TCompRes = default(TCompRes)
  1893. s: Rope
  1894. varCode: string
  1895. varName = mangleName(p.module, v)
  1896. useReloadingGuard = sfGlobal in v.flags and p.config.hcrOn
  1897. useGlobalPragmas = sfGlobal in v.flags and ({sfPure, sfThread} * v.flags != {})
  1898. if v.constraint.isNil:
  1899. if useReloadingGuard:
  1900. lineF(p, "var $1;$n", varName)
  1901. lineF(p, "if ($1 === undefined) {$n", varName)
  1902. varCode = $varName
  1903. inc p.extraIndent
  1904. elif useGlobalPragmas:
  1905. lineF(p, "if (globalThis.$1 === undefined) {$n", varName)
  1906. varCode = "globalThis." & $varName
  1907. inc p.extraIndent
  1908. else:
  1909. varCode = "var $2"
  1910. else:
  1911. # Is this really a thought through feature? this basically unused
  1912. # feature makes it impossible for almost all format strings in
  1913. # this function to be checked at compile time.
  1914. varCode = v.constraint.strVal
  1915. if n.kind == nkEmpty:
  1916. if not isIndirect(v) and
  1917. v.typ.kind in {tyVar, tyPtr, tyLent, tyRef, tyOwned} and mapType(p, v.typ) == etyBaseIndex:
  1918. lineF(p, "var $1 = null;$n", [varName])
  1919. lineF(p, "var $1_Idx = 0;$n", [varName])
  1920. else:
  1921. line(p, runtimeFormat(varCode & " = $3;$n", [returnType, varName, createVar(p, v.typ, isIndirect(v))]))
  1922. else:
  1923. gen(p, n, a)
  1924. case mapType(p, v.typ)
  1925. of etyObject, etySeq:
  1926. if v.typ.kind in {tyOpenArray, tyVarargs} or needsNoCopy(p, n):
  1927. s = a.res
  1928. else:
  1929. useMagic(p, "nimCopy")
  1930. s = "nimCopy(null, $1, $2)" % [a.res, genTypeInfo(p, n.typ)]
  1931. of etyBaseIndex:
  1932. let targetBaseIndex = {sfAddrTaken, sfGlobal} * v.flags == {}
  1933. if a.typ == etyBaseIndex:
  1934. if targetBaseIndex:
  1935. line(p, runtimeFormat(varCode & " = $3, $2_Idx = $4;$n",
  1936. [returnType, v.loc.snippet, a.address, a.res]))
  1937. else:
  1938. if isIndirect(v):
  1939. line(p, runtimeFormat(varCode & " = [[$3, $4]];$n",
  1940. [returnType, v.loc.snippet, a.address, a.res]))
  1941. else:
  1942. line(p, runtimeFormat(varCode & " = [$3, $4];$n",
  1943. [returnType, v.loc.snippet, a.address, a.res]))
  1944. else:
  1945. if targetBaseIndex:
  1946. let tmp = p.getTemp
  1947. lineF(p, "var $1 = $2, $3 = $1[0], $3_Idx = $1[1];$n",
  1948. [tmp, a.res, v.loc.snippet])
  1949. else:
  1950. line(p, runtimeFormat(varCode & " = $3;$n", [returnType, v.loc.snippet, a.res]))
  1951. return
  1952. else:
  1953. s = a.res
  1954. if isIndirect(v):
  1955. line(p, runtimeFormat(varCode & " = [$3];$n", [returnType, v.loc.snippet, s]))
  1956. else:
  1957. line(p, runtimeFormat(varCode & " = $3;$n", [returnType, v.loc.snippet, s]))
  1958. if useReloadingGuard or useGlobalPragmas:
  1959. dec p.extraIndent
  1960. lineF(p, "}$n")
  1961. proc genClosureVar(p: PProc, n: PNode) =
  1962. # assert n[2].kind != nkEmpty
  1963. # TODO: fixme transform `var env.x` into `var env.x = default()` after
  1964. # the order of transf and lambdalifting is fixed
  1965. if n[2].kind != nkEmpty:
  1966. genAsgnAux(p, n[0], n[2], false)
  1967. else:
  1968. var a: TCompRes = default(TCompRes)
  1969. gen(p, n[0], a)
  1970. line(p, runtimeFormat("$1 = $2;$n", [rdLoc(a), createVar(p, n[0].typ, false)]))
  1971. proc genVarStmt(p: PProc, n: PNode) =
  1972. for i in 0..<n.len:
  1973. var a = n[i]
  1974. if a.kind != nkCommentStmt:
  1975. if a.kind == nkVarTuple:
  1976. let unpacked = lowerTupleUnpacking(p.module.graph, a, p.module.idgen, p.prc)
  1977. genStmt(p, unpacked)
  1978. else:
  1979. assert(a.kind == nkIdentDefs)
  1980. if a[0].kind == nkSym:
  1981. var v = a[0].sym
  1982. if lfNoDecl notin v.loc.flags and sfImportc notin v.flags:
  1983. genLineDir(p, a)
  1984. if sfCompileTime notin v.flags:
  1985. genVarInit(p, v, a[2])
  1986. else:
  1987. # lazy emit, done when it's actually used.
  1988. if v.ast == nil: v.ast = a[2]
  1989. else: # closure
  1990. genClosureVar(p, a)
  1991. proc genConstant(p: PProc, c: PSym) =
  1992. if lfNoDecl notin c.loc.flags and not p.g.generatedSyms.containsOrIncl(c.id):
  1993. let oldBody = move p.body
  1994. #genLineDir(p, c.astdef)
  1995. genVarInit(p, c, c.astdef)
  1996. p.g.constants.add(p.body)
  1997. p.body = oldBody
  1998. proc genNew(p: PProc, n: PNode) =
  1999. var a: TCompRes = default(TCompRes)
  2000. gen(p, n[1], a)
  2001. var t = skipTypes(n[1].typ, abstractVar)[0]
  2002. if mapType(t) == etyObject:
  2003. lineF(p, "$1 = $2;$n", [a.rdLoc, createVar(p, t, false)])
  2004. elif a.typ == etyBaseIndex:
  2005. lineF(p, "$1 = [$3]; $2 = 0;$n", [a.address, a.res, createVar(p, t, false)])
  2006. else:
  2007. lineF(p, "$1 = [[$2], 0];$n", [a.rdLoc, createVar(p, t, false)])
  2008. proc genNewSeq(p: PProc, n: PNode) =
  2009. var x, y: TCompRes = default(TCompRes)
  2010. gen(p, n[1], x)
  2011. gen(p, n[2], y)
  2012. let t = skipTypes(n[1].typ, abstractVar)[0]
  2013. lineF(p, "$1 = new Array($2); for (var i = 0 ; i < $2 ; ++i) { $1[i] = $3; }", [
  2014. x.rdLoc, y.rdLoc, createVar(p, t, false)])
  2015. proc genOrd(p: PProc, n: PNode, r: var TCompRes) =
  2016. case skipTypes(n[1].typ, abstractVar + abstractRange).kind
  2017. of tyEnum, tyInt..tyInt32, tyUInt..tyUInt32, tyChar: gen(p, n[1], r)
  2018. of tyInt64, tyUInt64:
  2019. if optJsBigInt64 in p.config.globalOptions:
  2020. unaryExpr(p, n, r, "", "Number($1)")
  2021. else: gen(p, n[1], r)
  2022. of tyBool: unaryExpr(p, n, r, "", "($1 ? 1 : 0)")
  2023. else: internalError(p.config, n.info, "genOrd")
  2024. proc genConStrStr(p: PProc, n: PNode, r: var TCompRes) =
  2025. var a: TCompRes = default(TCompRes)
  2026. gen(p, n[1], a)
  2027. r.kind = resExpr
  2028. if skipTypes(n[1].typ, abstractVarRange).kind == tyChar:
  2029. r.res.add("[$1].concat(" % [a.res])
  2030. else:
  2031. r.res.add("($1).concat(" % [a.res])
  2032. for i in 2..<n.len - 1:
  2033. gen(p, n[i], a)
  2034. if skipTypes(n[i].typ, abstractVarRange).kind == tyChar:
  2035. r.res.add("[$1]," % [a.res])
  2036. else:
  2037. r.res.add("$1," % [a.res])
  2038. gen(p, n[^1], a)
  2039. if skipTypes(n[^1].typ, abstractVarRange).kind == tyChar:
  2040. r.res.add("[$1])" % [a.res])
  2041. else:
  2042. r.res.add("$1)" % [a.res])
  2043. proc genReprAux(p: PProc, n: PNode, r: var TCompRes, magic: string, typ: Rope = "") =
  2044. useMagic(p, magic)
  2045. r.res.add(magic & "(")
  2046. var a: TCompRes = default(TCompRes)
  2047. gen(p, n[1], a)
  2048. if magic == "reprAny":
  2049. # the pointer argument in reprAny is expandend to
  2050. # (pointedto, pointer), so we need to fill it
  2051. if a.address.len == 0:
  2052. r.res.add(a.res)
  2053. r.res.add(", null")
  2054. else:
  2055. r.res.add("$1, $2" % [a.address, a.res])
  2056. else:
  2057. r.res.add(a.res)
  2058. if typ != "":
  2059. r.res.add(", ")
  2060. r.res.add(typ)
  2061. r.res.add(")")
  2062. proc genRepr(p: PProc, n: PNode, r: var TCompRes) =
  2063. let t = skipTypes(n[1].typ, abstractVarRange)
  2064. case t.kind
  2065. of tyInt..tyInt64, tyUInt..tyUInt64:
  2066. genReprAux(p, n, r, "reprInt")
  2067. of tyChar:
  2068. genReprAux(p, n, r, "reprChar")
  2069. of tyBool:
  2070. genReprAux(p, n, r, "reprBool")
  2071. of tyFloat..tyFloat128:
  2072. genReprAux(p, n, r, "reprFloat")
  2073. of tyString:
  2074. genReprAux(p, n, r, "reprStr")
  2075. of tyEnum, tyOrdinal:
  2076. genReprAux(p, n, r, "reprEnum", genTypeInfo(p, t))
  2077. of tySet:
  2078. genReprAux(p, n, r, "reprSet", genTypeInfo(p, t))
  2079. of tyEmpty, tyVoid:
  2080. localError(p.config, n.info, "'repr' doesn't support 'void' type")
  2081. of tyPointer:
  2082. genReprAux(p, n, r, "reprPointer")
  2083. of tyOpenArray, tyVarargs:
  2084. genReprAux(p, n, r, "reprJSONStringify")
  2085. else:
  2086. genReprAux(p, n, r, "reprAny", genTypeInfo(p, t))
  2087. r.kind = resExpr
  2088. proc genOf(p: PProc, n: PNode, r: var TCompRes) =
  2089. var x: TCompRes = default(TCompRes)
  2090. let t = skipTypes(n[2].typ,
  2091. abstractVarRange+{tyRef, tyPtr, tyLent, tyTypeDesc, tyOwned})
  2092. gen(p, n[1], x)
  2093. if tfFinal in t.flags:
  2094. r.res = "($1.m_type == $2)" % [x.res, genTypeInfo(p, t)]
  2095. else:
  2096. useMagic(p, "isObj")
  2097. r.res = "isObj($1.m_type, $2)" % [x.res, genTypeInfo(p, t)]
  2098. r.kind = resExpr
  2099. proc genDefault(p: PProc, n: PNode; r: var TCompRes) =
  2100. r.res = createVar(p, n.typ, indirect = false)
  2101. r.kind = resExpr
  2102. proc genWasMoved(p: PProc, n: PNode) =
  2103. # TODO: it should be done by nir
  2104. var x: TCompRes = default(TCompRes)
  2105. gen(p, n[1], x)
  2106. if x.typ == etyBaseIndex:
  2107. lineF(p, "$1 = null, $2 = 0;$n", [x.address, x.res])
  2108. else:
  2109. var y: TCompRes = default(TCompRes)
  2110. genDefault(p, n[1], y)
  2111. let (a, _) = maybeMakeTempAssignable(p, n[1], x)
  2112. lineF(p, "$1 = $2;$n", [a, y.rdLoc])
  2113. proc genMove(p: PProc; n: PNode; r: var TCompRes) =
  2114. var a: TCompRes = default(TCompRes)
  2115. r.kind = resVal
  2116. r.res = p.getTemp()
  2117. gen(p, n[1], a)
  2118. lineF(p, "$1 = $2;$n", [r.rdLoc, a.rdLoc])
  2119. genWasMoved(p, n)
  2120. #lineF(p, "$1 = $2;$n", [dest.rdLoc, src.rdLoc])
  2121. proc genDup(p: PProc; n: PNode; r: var TCompRes) =
  2122. var a: TCompRes = default(TCompRes)
  2123. r.kind = resVal
  2124. r.res = p.getTemp()
  2125. gen(p, n[1], a)
  2126. lineF(p, "$1 = $2;$n", [r.rdLoc, a.rdLoc])
  2127. proc genJSArrayConstr(p: PProc, n: PNode, r: var TCompRes) =
  2128. var a: TCompRes = default(TCompRes)
  2129. r.res = rope("[")
  2130. r.kind = resExpr
  2131. for i in 0 ..< n.len:
  2132. if i > 0: r.res.add(", ")
  2133. gen(p, n[i], a)
  2134. if a.typ == etyBaseIndex:
  2135. r.res.addf("[$1, $2]", [a.address, a.res])
  2136. else:
  2137. if not needsNoCopy(p, n[i]):
  2138. let typ = n[i].typ.skipTypes(abstractInst)
  2139. useMagic(p, "nimCopy")
  2140. a.res = "nimCopy(null, $1, $2)" % [a.rdLoc, genTypeInfo(p, typ)]
  2141. r.res.add(a.res)
  2142. r.res.add("]")
  2143. proc genMagic(p: PProc, n: PNode, r: var TCompRes) =
  2144. var
  2145. a: TCompRes
  2146. line, filen: Rope
  2147. var op = n[0].sym.magic
  2148. case op
  2149. of mOr: genOr(p, n[1], n[2], r)
  2150. of mAnd: genAnd(p, n[1], n[2], r)
  2151. of mAddI..mStrToStr: arith(p, n, r, op)
  2152. of mRepr: genRepr(p, n, r)
  2153. of mSwap: genSwap(p, n)
  2154. of mAppendStrCh:
  2155. binaryExpr(p, n, r, "addChar",
  2156. "addChar($1, $2);")
  2157. of mAppendStrStr:
  2158. var lhs, rhs: TCompRes = default(TCompRes)
  2159. gen(p, n[1], lhs)
  2160. gen(p, n[2], rhs)
  2161. if skipTypes(n[1].typ, abstractVarRange).kind == tyCstring:
  2162. let (b, tmp) = maybeMakeTemp(p, n[2], rhs)
  2163. r.res = "if (null != $1) { if (null == $2) $2 = $3; else $2 += $3; }" %
  2164. [b, lhs.rdLoc, tmp]
  2165. else:
  2166. let (a, tmp) = maybeMakeTemp(p, n[1], lhs)
  2167. r.res = "$1.push.apply($3, $2);" % [a, rhs.rdLoc, tmp]
  2168. r.kind = resExpr
  2169. of mAppendSeqElem:
  2170. var x, y: TCompRes = default(TCompRes)
  2171. gen(p, n[1], x)
  2172. gen(p, n[2], y)
  2173. if mapType(n[2].typ) == etyBaseIndex:
  2174. let c = "[$1, $2]" % [y.address, y.res]
  2175. r.res = "$1.push($2);" % [x.rdLoc, c]
  2176. elif needsNoCopy(p, n[2]):
  2177. r.res = "$1.push($2);" % [x.rdLoc, y.rdLoc]
  2178. else:
  2179. useMagic(p, "nimCopy")
  2180. let c = getTemp(p, defineInLocals=false)
  2181. lineF(p, "var $1 = nimCopy(null, $2, $3);$n",
  2182. [c, y.rdLoc, genTypeInfo(p, n[2].typ)])
  2183. r.res = "$1.push($2);" % [x.rdLoc, c]
  2184. r.kind = resExpr
  2185. of mConStrStr:
  2186. genConStrStr(p, n, r)
  2187. of mEqStr:
  2188. binaryExpr(p, n, r, "eqStrings", "eqStrings($1, $2)")
  2189. of mLeStr:
  2190. binaryExpr(p, n, r, "cmpStrings", "(cmpStrings($1, $2) <= 0)")
  2191. of mLtStr:
  2192. binaryExpr(p, n, r, "cmpStrings", "(cmpStrings($1, $2) < 0)")
  2193. of mIsNil:
  2194. # we want to accept undefined, so we ==
  2195. if mapType(n[1].typ) != etyBaseIndex:
  2196. unaryExpr(p, n, r, "", "($1 == null)")
  2197. else:
  2198. var x: TCompRes = default(TCompRes)
  2199. gen(p, n[1], x)
  2200. r.res = "($# == null && $# === 0)" % [x.address, x.res]
  2201. of mEnumToStr: genRepr(p, n, r)
  2202. of mNew, mNewFinalize: genNew(p, n)
  2203. of mChr: gen(p, n[1], r)
  2204. of mArrToSeq:
  2205. # only array literals doesn't need copy
  2206. if n[1].kind == nkBracket:
  2207. genJSArrayConstr(p, n[1], r)
  2208. else:
  2209. var x: TCompRes = default(TCompRes)
  2210. gen(p, n[1], x)
  2211. useMagic(p, "nimCopy")
  2212. r.res = "nimCopy(null, $1, $2)" % [x.rdLoc, genTypeInfo(p, n.typ)]
  2213. of mOpenArrayToSeq:
  2214. genCall(p, n, r)
  2215. of mDestroy, mTrace: discard "ignore calls to the default destructor"
  2216. of mOrd: genOrd(p, n, r)
  2217. of mLengthStr, mLengthSeq, mLengthOpenArray, mLengthArray:
  2218. var x: TCompRes = default(TCompRes)
  2219. gen(p, n[1], x)
  2220. if skipTypes(n[1].typ, abstractInst).kind == tyCstring:
  2221. let (a, tmp) = maybeMakeTemp(p, n[1], x)
  2222. r.res = "(($1) == null ? 0 : ($2).length)" % [a, tmp]
  2223. else:
  2224. r.res = "($1).length" % [x.rdLoc]
  2225. r.kind = resExpr
  2226. of mHigh:
  2227. var x: TCompRes = default(TCompRes)
  2228. gen(p, n[1], x)
  2229. if skipTypes(n[1].typ, abstractInst).kind == tyCstring:
  2230. let (a, tmp) = maybeMakeTemp(p, n[1], x)
  2231. r.res = "(($1) == null ? -1 : ($2).length - 1)" % [a, tmp]
  2232. else:
  2233. r.res = "($1).length - 1" % [x.rdLoc]
  2234. r.kind = resExpr
  2235. of mInc:
  2236. let typ = n[1].typ.skipTypes(abstractVarRange)
  2237. case typ.kind
  2238. of tyUInt..tyUInt32:
  2239. binaryUintExpr(p, n, r, "+", true)
  2240. of tyUInt64:
  2241. if optJsBigInt64 in p.config.globalOptions:
  2242. binaryExpr(p, n, r, "", "$1 = BigInt.asUintN(64, $3 + BigInt($2))", true)
  2243. else: binaryUintExpr(p, n, r, "+", true)
  2244. elif typ.kind == tyInt64 and optJsBigInt64 in p.config.globalOptions:
  2245. if optOverflowCheck notin p.options:
  2246. binaryExpr(p, n, r, "", "$1 = BigInt.asIntN(64, $3 + BigInt($2))", true)
  2247. else: binaryExpr(p, n, r, "addInt64", "$1 = addInt64($3, BigInt($2))", true)
  2248. else:
  2249. if optOverflowCheck notin p.options: binaryExpr(p, n, r, "", "$1 += $2")
  2250. else: binaryExpr(p, n, r, "addInt", "$1 = addInt($3, $2)", true)
  2251. of ast.mDec:
  2252. let typ = n[1].typ.skipTypes(abstractVarRange)
  2253. case typ.kind
  2254. of tyUInt..tyUInt32:
  2255. binaryUintExpr(p, n, r, "-", true)
  2256. of tyUInt64:
  2257. if optJsBigInt64 in p.config.globalOptions:
  2258. binaryExpr(p, n, r, "", "$1 = BigInt.asUintN(64, $3 - BigInt($2))", true)
  2259. else: binaryUintExpr(p, n, r, "-", true)
  2260. elif typ.kind == tyInt64 and optJsBigInt64 in p.config.globalOptions:
  2261. if optOverflowCheck notin p.options:
  2262. binaryExpr(p, n, r, "", "$1 = BigInt.asIntN(64, $3 - BigInt($2))", true)
  2263. else: binaryExpr(p, n, r, "subInt64", "$1 = subInt64($3, BigInt($2))", true)
  2264. else:
  2265. if optOverflowCheck notin p.options: binaryExpr(p, n, r, "", "$1 -= $2")
  2266. else: binaryExpr(p, n, r, "subInt", "$1 = subInt($3, $2)", true)
  2267. of mSetLengthStr:
  2268. binaryExpr(p, n, r, "mnewString",
  2269. """if ($1.length < $2) { for (var i = $3.length; i < $4; ++i) $3.push(0); }
  2270. else {$3.length = $4; }""")
  2271. of mSetLengthSeq:
  2272. var x, y: TCompRes = default(TCompRes)
  2273. gen(p, n[1], x)
  2274. gen(p, n[2], y)
  2275. let t = skipTypes(n[1].typ, abstractVar)[0]
  2276. let (a, tmp) = maybeMakeTemp(p, n[1], x)
  2277. let (b, tmp2) = maybeMakeTemp(p, n[2], y)
  2278. r.res = """if ($1.length < $2) { for (var i = $4.length ; i < $5 ; ++i) $4.push($3); }
  2279. else { $4.length = $5; }""" % [a, b, createVar(p, t, false), tmp, tmp2]
  2280. r.kind = resExpr
  2281. of mCard: unaryExpr(p, n, r, "SetCard", "SetCard($1)")
  2282. of mLtSet: binaryExpr(p, n, r, "SetLt", "SetLt($1, $2)")
  2283. of mLeSet: binaryExpr(p, n, r, "SetLe", "SetLe($1, $2)")
  2284. of mEqSet: binaryExpr(p, n, r, "SetEq", "SetEq($1, $2)")
  2285. of mMulSet: binaryExpr(p, n, r, "SetMul", "SetMul($1, $2)")
  2286. of mPlusSet: binaryExpr(p, n, r, "SetPlus", "SetPlus($1, $2)")
  2287. of mMinusSet: binaryExpr(p, n, r, "SetMinus", "SetMinus($1, $2)")
  2288. of mIncl: binaryExpr(p, n, r, "", "$1[$2] = true")
  2289. of mExcl: binaryExpr(p, n, r, "", "delete $1[$2]")
  2290. of mInSet:
  2291. binaryExpr(p, n, r, "", "($1[$2] != undefined)")
  2292. of mNewSeq: genNewSeq(p, n)
  2293. of mNewSeqOfCap: unaryExpr(p, n, r, "", "[]")
  2294. of mOf: genOf(p, n, r)
  2295. of mDefault, mZeroDefault: genDefault(p, n, r)
  2296. of mWasMoved: genWasMoved(p, n)
  2297. of mEcho: genEcho(p, n, r)
  2298. of mNLen..mNError, mSlurp, mStaticExec:
  2299. localError(p.config, n.info, errXMustBeCompileTime % n[0].sym.name.s)
  2300. of mNewString: unaryExpr(p, n, r, "mnewString", "mnewString($1)")
  2301. of mNewStringOfCap:
  2302. unaryExpr(p, n, r, "mnewString", "mnewString(0)")
  2303. of mDotDot:
  2304. genProcForSymIfNeeded(p, n[0].sym)
  2305. genCall(p, n, r)
  2306. of mParseBiggestFloat:
  2307. useMagic(p, "nimParseBiggestFloat")
  2308. genCall(p, n, r)
  2309. of mSlice:
  2310. # arr.slice([begin[, end]]): 'end' is exclusive
  2311. var x, y, z: TCompRes = default(TCompRes)
  2312. gen(p, n[1], x)
  2313. gen(p, n[2], y)
  2314. gen(p, n[3], z)
  2315. r.res = "($1.slice($2, $3 + 1))" % [x.rdLoc, y.rdLoc, z.rdLoc]
  2316. r.kind = resExpr
  2317. of mMove:
  2318. genMove(p, n, r)
  2319. of mDup:
  2320. genDup(p, n, r)
  2321. of mEnsureMove:
  2322. gen(p, n[1], r)
  2323. else:
  2324. genCall(p, n, r)
  2325. #else internalError(p.config, e.info, 'genMagic: ' + magicToStr[op]);
  2326. proc genSetConstr(p: PProc, n: PNode, r: var TCompRes) =
  2327. var
  2328. a, b: TCompRes = default(TCompRes)
  2329. useMagic(p, "setConstr")
  2330. r.res = rope("setConstr(")
  2331. r.kind = resExpr
  2332. for i in 0..<n.len:
  2333. if i > 0: r.res.add(", ")
  2334. var it = n[i]
  2335. if it.kind == nkRange:
  2336. gen(p, it[0], a)
  2337. gen(p, it[1], b)
  2338. if it[0].typ.kind == tyBool:
  2339. r.res.addf("$1, $2", [a.res, b.res])
  2340. else:
  2341. r.res.addf("[$1, $2]", [a.res, b.res])
  2342. else:
  2343. gen(p, it, a)
  2344. r.res.add(a.res)
  2345. r.res.add(")")
  2346. # emit better code for constant sets:
  2347. if isDeepConstExpr(n):
  2348. inc(p.g.unique)
  2349. let tmp = rope("ConstSet") & rope(p.g.unique)
  2350. p.g.constants.addf("var $1 = $2;$n", [tmp, r.res])
  2351. r.res = tmp
  2352. proc genArrayConstr(p: PProc, n: PNode, r: var TCompRes) =
  2353. ## Constructs array or sequence.
  2354. ## Nim array of uint8..uint32, int8..int32 maps to JS typed arrays.
  2355. ## Nim sequence maps to JS array.
  2356. var t = skipTypes(n.typ, abstractInst)
  2357. let e = elemType(t)
  2358. let jsTyp = arrayTypeForElemType(p.config, e)
  2359. if skipTypes(n.typ, abstractVarRange).kind != tySequence and jsTyp.len > 0:
  2360. # generate typed array
  2361. # for example Nim generates `new Uint8Array([1, 2, 3])` for `[byte(1), 2, 3]`
  2362. # TODO use `set` or loop to initialize typed array which improves performances in some situations
  2363. var a: TCompRes = default(TCompRes)
  2364. r.res = "new $1([" % [rope(jsTyp)]
  2365. r.kind = resExpr
  2366. for i in 0 ..< n.len:
  2367. if i > 0: r.res.add(", ")
  2368. gen(p, n[i], a)
  2369. r.res.add(a.res)
  2370. r.res.add("])")
  2371. else:
  2372. genJSArrayConstr(p, n, r)
  2373. proc genTupleConstr(p: PProc, n: PNode, r: var TCompRes) =
  2374. var a: TCompRes = default(TCompRes)
  2375. r.res = rope("{")
  2376. r.kind = resExpr
  2377. for i in 0..<n.len:
  2378. if i > 0: r.res.add(", ")
  2379. var it = n[i]
  2380. if it.kind == nkExprColonExpr: it = it[1]
  2381. gen(p, it, a)
  2382. let typ = it.typ.skipTypes(abstractInst)
  2383. if a.typ == etyBaseIndex:
  2384. r.res.addf("Field$#: [$#, $#]", [i.rope, a.address, a.res])
  2385. else:
  2386. if not needsNoCopy(p, it):
  2387. useMagic(p, "nimCopy")
  2388. a.res = "nimCopy(null, $1, $2)" % [a.rdLoc, genTypeInfo(p, typ)]
  2389. r.res.addf("Field$#: $#", [i.rope, a.res])
  2390. r.res.add("}")
  2391. proc genObjConstr(p: PProc, n: PNode, r: var TCompRes) =
  2392. var a: TCompRes = default(TCompRes)
  2393. r.kind = resExpr
  2394. var initList : Rope = ""
  2395. var fieldIDs = initIntSet()
  2396. let nTyp = n.typ.skipTypes(abstractInst)
  2397. for i in 1..<n.len:
  2398. if i > 1: initList.add(", ")
  2399. var it = n[i]
  2400. internalAssert p.config, it.kind == nkExprColonExpr
  2401. let val = it[1]
  2402. gen(p, val, a)
  2403. var f = it[0].sym
  2404. if f.loc.snippet == "": f.loc.snippet = mangleName(p.module, f)
  2405. fieldIDs.incl(lookupFieldAgain(n.typ.skipTypes({tyDistinct}), f).id)
  2406. let typ = val.typ.skipTypes(abstractInst)
  2407. if a.typ == etyBaseIndex:
  2408. initList.addf("$#: [$#, $#]", [f.loc.snippet, a.address, a.res])
  2409. else:
  2410. if not needsNoCopy(p, val):
  2411. useMagic(p, "nimCopy")
  2412. a.res = "nimCopy(null, $1, $2)" % [a.rdLoc, genTypeInfo(p, typ)]
  2413. initList.addf("$#: $#", [f.loc.snippet, a.res])
  2414. let t = skipTypes(n.typ, abstractInst + skipPtrs)
  2415. createObjInitList(p, t, fieldIDs, initList)
  2416. r.res = ("{$1}") % [initList]
  2417. proc genConv(p: PProc, n: PNode, r: var TCompRes) =
  2418. var dest = skipTypes(n.typ, abstractVarRange)
  2419. var src = skipTypes(n[1].typ, abstractVarRange)
  2420. gen(p, n[1], r)
  2421. if dest.kind == src.kind:
  2422. # no-op conversion
  2423. return
  2424. let toInt = (dest.kind in tyInt..tyInt32)
  2425. let fromInt = (src.kind in tyInt..tyInt32)
  2426. let toUint = (dest.kind in tyUInt..tyUInt32)
  2427. let fromUint = (src.kind in tyUInt..tyUInt32)
  2428. if toUint and (fromInt or fromUint):
  2429. let trimmer = unsignedTrimmer(dest.size)
  2430. r.res = "($1 $2)" % [r.res, trimmer]
  2431. elif dest.kind == tyBool:
  2432. r.res = "(!!($1))" % [r.res]
  2433. r.kind = resExpr
  2434. elif toInt:
  2435. if src.kind in {tyInt64, tyUInt64} and optJsBigInt64 in p.config.globalOptions:
  2436. r.res = "Number($1)" % [r.res]
  2437. else:
  2438. r.res = "(($1) | 0)" % [r.res]
  2439. elif dest.kind == tyInt64 and optJsBigInt64 in p.config.globalOptions:
  2440. if fromInt or fromUint or src.kind in {tyBool, tyChar, tyEnum}:
  2441. r.res = "BigInt($1)" % [r.res]
  2442. elif src.kind in {tyFloat..tyFloat64}:
  2443. r.res = "BigInt(Math.trunc($1))" % [r.res]
  2444. elif src.kind == tyUInt64:
  2445. r.res = "BigInt.asIntN(64, $1)" % [r.res]
  2446. elif dest.kind == tyUInt64 and optJsBigInt64 in p.config.globalOptions:
  2447. if fromUint or src.kind in {tyBool, tyChar, tyEnum}:
  2448. r.res = "BigInt($1)" % [r.res]
  2449. elif fromInt: # could be negative
  2450. r.res = "BigInt.asUintN(64, BigInt($1))" % [r.res]
  2451. elif src.kind in {tyFloat..tyFloat64}:
  2452. r.res = "BigInt.asUintN(64, BigInt(Math.trunc($1)))" % [r.res]
  2453. elif src.kind == tyInt64:
  2454. r.res = "BigInt.asUintN(64, $1)" % [r.res]
  2455. elif toUint or dest.kind in tyFloat..tyFloat64:
  2456. if src.kind in {tyInt64, tyUInt64} and optJsBigInt64 in p.config.globalOptions:
  2457. r.res = "Number($1)" % [r.res]
  2458. else:
  2459. # TODO: What types must we handle here?
  2460. discard
  2461. proc upConv(p: PProc, n: PNode, r: var TCompRes) =
  2462. gen(p, n[0], r) # XXX
  2463. proc genRangeChck(p: PProc, n: PNode, r: var TCompRes, magic: string) =
  2464. var a, b: TCompRes = default(TCompRes)
  2465. gen(p, n[0], r)
  2466. let src = skipTypes(n[0].typ, abstractVarRange)
  2467. let dest = skipTypes(n.typ, abstractVarRange)
  2468. if optRangeCheck notin p.options:
  2469. if optJsBigInt64 in p.config.globalOptions and
  2470. dest.kind in {tyUInt..tyUInt32, tyInt..tyInt32} and
  2471. src.kind in {tyInt64, tyUInt64}:
  2472. # conversions to Number are kept
  2473. r.res = "Number($1)" % [r.res]
  2474. else:
  2475. discard
  2476. elif dest.kind in {tyUInt..tyUInt64} and checkUnsignedConversions notin p.config.legacyFeatures:
  2477. if src.kind in {tyInt64, tyUInt64} and optJsBigInt64 in p.config.globalOptions:
  2478. r.res = "BigInt.asUintN($1, $2)" % [$(dest.size * 8), r.res]
  2479. else:
  2480. r.res = "BigInt.asUintN($1, BigInt($2))" % [$(dest.size * 8), r.res]
  2481. if not (dest.kind == tyUInt64 and optJsBigInt64 in p.config.globalOptions):
  2482. r.res = "Number($1)" % [r.res]
  2483. else:
  2484. if src.kind in {tyInt64, tyUInt64} and dest.kind notin {tyInt64, tyUInt64} and optJsBigInt64 in p.config.globalOptions:
  2485. # we do a range check anyway, so it's ok if the number gets rounded
  2486. r.res = "Number($1)" % [r.res]
  2487. gen(p, n[1], a)
  2488. gen(p, n[2], b)
  2489. useMagic(p, "chckRange")
  2490. r.res = "chckRange($1, $2, $3)" % [r.res, a.res, b.res]
  2491. r.kind = resExpr
  2492. proc convStrToCStr(p: PProc, n: PNode, r: var TCompRes) =
  2493. # we do an optimization here as this is likely to slow down
  2494. # much of the code otherwise:
  2495. if n[0].kind == nkCStringToString:
  2496. gen(p, n[0][0], r)
  2497. else:
  2498. gen(p, n[0], r)
  2499. if r.res == "": internalError(p.config, n.info, "convStrToCStr")
  2500. useMagic(p, "toJSStr")
  2501. r.res = "toJSStr($1)" % [r.res]
  2502. r.kind = resExpr
  2503. proc convCStrToStr(p: PProc, n: PNode, r: var TCompRes) =
  2504. # we do an optimization here as this is likely to slow down
  2505. # much of the code otherwise:
  2506. if n[0].kind == nkStringToCString:
  2507. gen(p, n[0][0], r)
  2508. else:
  2509. gen(p, n[0], r)
  2510. if r.res == "": internalError(p.config, n.info, "convCStrToStr")
  2511. useMagic(p, "cstrToNimstr")
  2512. r.res = "cstrToNimstr($1)" % [r.res]
  2513. r.kind = resExpr
  2514. proc genReturnStmt(p: PProc, n: PNode) =
  2515. if p.procDef == nil: internalError(p.config, n.info, "genReturnStmt")
  2516. p.beforeRetNeeded = true
  2517. if n[0].kind != nkEmpty:
  2518. genStmt(p, n[0])
  2519. else:
  2520. genLineDir(p, n)
  2521. lineF(p, "break BeforeRet;$n", [])
  2522. proc frameCreate(p: PProc; procname, filename: Rope): Rope =
  2523. const frameFmt =
  2524. "var F = {procname: $1, prev: framePtr, filename: $2, line: 0};$n"
  2525. result = p.indentLine(frameFmt % [procname, filename])
  2526. result.add p.indentLine(ropes.`%`("framePtr = F;$n", []))
  2527. proc frameDestroy(p: PProc): Rope =
  2528. result = p.indentLine rope(("framePtr = F.prev;") & "\L")
  2529. proc genProcBody(p: PProc, prc: PSym): Rope =
  2530. if hasFrameInfo(p):
  2531. result = frameCreate(p,
  2532. makeJSString(prc.owner.name.s & '.' & prc.name.s),
  2533. makeJSString(toFilenameOption(p.config, prc.info.fileIndex, foStacktrace)))
  2534. else:
  2535. result = ""
  2536. if p.beforeRetNeeded:
  2537. result.add p.indentLine("BeforeRet: {\n")
  2538. result.add p.body
  2539. result.add p.indentLine("};\n")
  2540. else:
  2541. result.add(p.body)
  2542. if prc.typ.callConv == ccSysCall:
  2543. result = ("try {$n$1} catch (e) {$n" &
  2544. " alert(\"Unhandled exception:\\n\" + e.message + \"\\n\"$n}") % [result]
  2545. if hasFrameInfo(p):
  2546. result.add(frameDestroy(p))
  2547. proc optionalLine(p: Rope): Rope =
  2548. if p == "":
  2549. return ""
  2550. else:
  2551. return p & "\L"
  2552. proc genProc(oldProc: PProc, prc: PSym): Rope =
  2553. ## Generate a JS procedure ('function').
  2554. result = ""
  2555. var
  2556. resultSym: PSym
  2557. a: TCompRes = default(TCompRes)
  2558. #if gVerbosity >= 3:
  2559. # echo "BEGIN generating code for: " & prc.name.s
  2560. var p = newProc(oldProc.g, oldProc.module, prc.ast, prc.options)
  2561. p.up = oldProc
  2562. var returnStmt: Rope = ""
  2563. var resultAsgn: Rope = ""
  2564. var name = mangleName(p.module, prc)
  2565. let header = generateHeader(p, prc)
  2566. if prc.typ.returnType != nil and sfPure notin prc.flags:
  2567. resultSym = prc.ast[resultPos].sym
  2568. let mname = mangleName(p.module, resultSym)
  2569. # otherwise uses "fat pointers"
  2570. let useRawPointer = not isIndirect(resultSym) and
  2571. resultSym.typ.kind in {tyVar, tyPtr, tyLent, tyRef, tyOwned} and
  2572. mapType(p, resultSym.typ) == etyBaseIndex
  2573. if useRawPointer:
  2574. resultAsgn = p.indentLine(("var $# = null;$n") % [mname])
  2575. resultAsgn.add p.indentLine("var $#_Idx = 0;$n" % [mname])
  2576. else:
  2577. let resVar = createVar(p, resultSym.typ, isIndirect(resultSym))
  2578. resultAsgn = p.indentLine(("var $# = $#;$n") % [mname, resVar])
  2579. gen(p, prc.ast[resultPos], a)
  2580. if mapType(p, resultSym.typ) == etyBaseIndex:
  2581. returnStmt = "return [$#, $#];$n" % [a.address, a.res]
  2582. else:
  2583. returnStmt = "return $#;$n" % [a.res]
  2584. var transformedBody = transformBody(p.module.graph, p.module.idgen, prc, {})
  2585. if sfInjectDestructors in prc.flags:
  2586. transformedBody = injectDestructorCalls(p.module.graph, p.module.idgen, prc, transformedBody)
  2587. p.nested: genStmt(p, transformedBody)
  2588. if optLineDir in p.config.options:
  2589. result = lineDir(p.config, prc.info, toLinenumber(prc.info))
  2590. var def: Rope
  2591. if not prc.constraint.isNil:
  2592. def = runtimeFormat(prc.constraint.strVal & " {$n$#$#$#$#$#",
  2593. [ returnType,
  2594. name,
  2595. header,
  2596. optionalLine(p.globals),
  2597. optionalLine(p.locals),
  2598. optionalLine(resultAsgn),
  2599. optionalLine(genProcBody(p, prc)),
  2600. optionalLine(p.indentLine(returnStmt))])
  2601. else:
  2602. # if optLineDir in p.config.options:
  2603. # result.add("\L")
  2604. if p.config.hcrOn:
  2605. # Here, we introduce thunks that create the equivalent of a jump table
  2606. # for all global functions, because references to them may be stored
  2607. # in JavaScript variables. The added indirection ensures that such
  2608. # references will end up calling the reloaded code.
  2609. var thunkName = name
  2610. name = name & "IMLP"
  2611. result.add("\Lfunction $#() { return $#.apply(this, arguments); }$n" %
  2612. [thunkName, name])
  2613. def = "\Lfunction $#($#) {$n$#$#$#$#$#" %
  2614. [ name,
  2615. header,
  2616. optionalLine(p.globals),
  2617. optionalLine(p.locals),
  2618. optionalLine(resultAsgn),
  2619. optionalLine(genProcBody(p, prc)),
  2620. optionalLine(p.indentLine(returnStmt))]
  2621. dec p.extraIndent
  2622. result.add p.indentLine(def)
  2623. result.add p.indentLine("}\n")
  2624. #if gVerbosity >= 3:
  2625. # echo "END generated code for: " & prc.name.s
  2626. proc genStmt(p: PProc, n: PNode) =
  2627. var r: TCompRes = default(TCompRes)
  2628. gen(p, n, r)
  2629. if r.res != "": lineF(p, "$#;$n", [r.res])
  2630. proc genPragma(p: PProc, n: PNode) =
  2631. for i in 0..<n.len:
  2632. let it = n[i]
  2633. case whichPragma(it)
  2634. of wEmit: genAsmOrEmitStmt(p, it[1])
  2635. of wPush:
  2636. processPushBackendOption(p.optionsStack, p.options, n, i+1)
  2637. of wPop:
  2638. processPopBackendOption(p.optionsStack, p.options)
  2639. else: discard
  2640. proc genCast(p: PProc, n: PNode, r: var TCompRes) =
  2641. var dest = skipTypes(n.typ, abstractVarRange)
  2642. var src = skipTypes(n[1].typ, abstractVarRange)
  2643. gen(p, n[1], r)
  2644. if dest.kind == src.kind:
  2645. # no-op conversion
  2646. return
  2647. let toInt = (dest.kind in tyInt..tyInt32)
  2648. let toUint = (dest.kind in tyUInt..tyUInt32)
  2649. let fromInt = (src.kind in tyInt..tyInt32)
  2650. let fromUint = (src.kind in tyUInt..tyUInt32)
  2651. if toUint:
  2652. if fromInt or fromUint:
  2653. r.res = "Number(BigInt.asUintN($1, BigInt($2)))" % [$(dest.size * 8), r.res]
  2654. elif src.kind in {tyInt64, tyUInt64} and optJsBigInt64 in p.config.globalOptions:
  2655. r.res = "Number(BigInt.asUintN($1, $2))" % [$(dest.size * 8), r.res]
  2656. elif toInt:
  2657. if fromInt or fromUint:
  2658. r.res = "Number(BigInt.asIntN($1, BigInt($2)))" % [$(dest.size * 8), r.res]
  2659. elif src.kind in {tyInt64, tyUInt64} and optJsBigInt64 in p.config.globalOptions:
  2660. r.res = "Number(BigInt.asIntN($1, $2))" % [$(dest.size * 8), r.res]
  2661. elif dest.kind == tyInt64 and optJsBigInt64 in p.config.globalOptions:
  2662. if fromInt or fromUint or src.kind in {tyBool, tyChar, tyEnum}:
  2663. r.res = "BigInt($1)" % [r.res]
  2664. elif src.kind in {tyFloat..tyFloat64}:
  2665. r.res = "BigInt(Math.trunc($1))" % [r.res]
  2666. elif src.kind == tyUInt64:
  2667. r.res = "BigInt.asIntN(64, $1)" % [r.res]
  2668. elif dest.kind == tyUInt64 and optJsBigInt64 in p.config.globalOptions:
  2669. if fromUint or src.kind in {tyBool, tyChar, tyEnum}:
  2670. r.res = "BigInt($1)" % [r.res]
  2671. elif fromInt: # could be negative
  2672. r.res = "BigInt.asUintN(64, BigInt($1))" % [r.res]
  2673. elif src.kind in {tyFloat..tyFloat64}:
  2674. r.res = "BigInt.asUintN(64, BigInt(Math.trunc($1)))" % [r.res]
  2675. elif src.kind == tyInt64:
  2676. r.res = "BigInt.asUintN(64, $1)" % [r.res]
  2677. elif dest.kind in tyFloat..tyFloat64:
  2678. if src.kind in {tyInt64, tyUInt64} and optJsBigInt64 in p.config.globalOptions:
  2679. r.res = "Number($1)" % [r.res]
  2680. elif (src.kind == tyPtr and mapType(p, src) == etyObject) and dest.kind == tyPointer:
  2681. r.address = r.res
  2682. r.res = "null"
  2683. r.typ = etyBaseIndex
  2684. elif (dest.kind == tyPtr and mapType(p, dest) == etyObject) and src.kind == tyPointer:
  2685. r.res = r.address
  2686. r.typ = etyObject
  2687. proc gen(p: PProc, n: PNode, r: var TCompRes) =
  2688. r.typ = etyNone
  2689. if r.kind != resCallee: r.kind = resNone
  2690. #r.address = ""
  2691. r.res = ""
  2692. case n.kind
  2693. of nkSym:
  2694. genSym(p, n, r)
  2695. of nkCharLit..nkUInt64Lit:
  2696. case n.typ.skipTypes(abstractVarRange).kind
  2697. of tyBool:
  2698. r.res = if n.intVal == 0: rope"false" else: rope"true"
  2699. of tyUInt64:
  2700. r.res = rope($cast[BiggestUInt](n.intVal))
  2701. if optJsBigInt64 in p.config.globalOptions:
  2702. r.res.add('n')
  2703. of tyInt64:
  2704. let wrap = n.intVal < 0 # wrap negative integers with parens
  2705. if wrap: r.res.add '('
  2706. r.res.addInt n.intVal
  2707. if optJsBigInt64 in p.config.globalOptions:
  2708. r.res.add('n')
  2709. if wrap: r.res.add ')'
  2710. else:
  2711. let wrap = n.intVal < 0 # wrap negative integers with parens
  2712. if wrap: r.res.add '('
  2713. r.res.addInt n.intVal
  2714. if wrap: r.res.add ')'
  2715. r.kind = resExpr
  2716. of nkNilLit:
  2717. if isEmptyType(n.typ):
  2718. discard
  2719. elif mapType(p, n.typ) == etyBaseIndex:
  2720. r.typ = etyBaseIndex
  2721. r.address = rope"null"
  2722. r.res = rope"0"
  2723. r.kind = resExpr
  2724. else:
  2725. r.res = rope"null"
  2726. r.kind = resExpr
  2727. of nkStrLit..nkTripleStrLit:
  2728. if skipTypes(n.typ, abstractVarRange).kind == tyString:
  2729. if n.strVal.len <= 64:
  2730. r.res = makeJsNimStrLit(n.strVal)
  2731. else:
  2732. useMagic(p, "makeNimstrLit")
  2733. r.res = "makeNimstrLit($1)" % [makeJSString(n.strVal)]
  2734. else:
  2735. r.res = makeJSString(n.strVal, false)
  2736. r.kind = resExpr
  2737. of nkFloatLit..nkFloat64Lit:
  2738. let f = n.floatVal
  2739. case classify(f)
  2740. of fcNan:
  2741. if signbit(f):
  2742. r.res = rope"-NaN"
  2743. else:
  2744. r.res = rope"NaN"
  2745. of fcNegZero:
  2746. r.res = rope"-0.0"
  2747. of fcZero:
  2748. r.res = rope"0.0"
  2749. of fcInf:
  2750. r.res = rope"Infinity"
  2751. of fcNegInf:
  2752. r.res = rope"-Infinity"
  2753. else:
  2754. if n.typ.skipTypes(abstractVarRange).kind == tyFloat32:
  2755. r.res.addFloatRoundtrip(f.float32)
  2756. else:
  2757. r.res.addFloatRoundtrip(f)
  2758. r.kind = resExpr
  2759. of nkCallKinds:
  2760. if isEmptyType(n.typ):
  2761. genLineDir(p, n)
  2762. if (n[0].kind == nkSym) and (n[0].sym.magic != mNone):
  2763. genMagic(p, n, r)
  2764. elif n[0].kind == nkSym and sfInfixCall in n[0].sym.flags and
  2765. n.len >= 1:
  2766. genInfixCall(p, n, r)
  2767. else:
  2768. genCall(p, n, r)
  2769. of nkClosure:
  2770. if jsNoLambdaLifting in p.config.legacyFeatures:
  2771. gen(p, n[0], r)
  2772. else:
  2773. let tmp = getTemp(p)
  2774. var a: TCompRes = default(TCompRes)
  2775. var b: TCompRes = default(TCompRes)
  2776. gen(p, n[0], a)
  2777. gen(p, n[1], b)
  2778. lineF(p, "$1 = $2.bind($3); $1.ClP_0 = $2; $1.ClE_0 = $3;$n", [tmp, a.rdLoc, b.rdLoc])
  2779. r.res = tmp
  2780. r.kind = resVal
  2781. of nkCurly: genSetConstr(p, n, r)
  2782. of nkBracket: genArrayConstr(p, n, r)
  2783. of nkPar, nkTupleConstr: genTupleConstr(p, n, r)
  2784. of nkObjConstr: genObjConstr(p, n, r)
  2785. of nkHiddenStdConv, nkHiddenSubConv, nkConv: genConv(p, n, r)
  2786. of nkAddr, nkHiddenAddr:
  2787. if n.typ.kind in {tyLent}:
  2788. gen(p, n[0], r)
  2789. else:
  2790. genAddr(p, n, r)
  2791. of nkDerefExpr, nkHiddenDeref:
  2792. if n.typ.kind in {tyLent}:
  2793. gen(p, n[0], r)
  2794. else:
  2795. genDeref(p, n, r)
  2796. of nkBracketExpr: genArrayAccess(p, n, r)
  2797. of nkDotExpr: genFieldAccess(p, n, r)
  2798. of nkCheckedFieldExpr: genCheckedFieldOp(p, n, nil, r)
  2799. of nkObjDownConv: gen(p, n[0], r)
  2800. of nkObjUpConv: upConv(p, n, r)
  2801. of nkCast: genCast(p, n, r)
  2802. of nkChckRangeF: genRangeChck(p, n, r, "chckRangeF")
  2803. of nkChckRange64: genRangeChck(p, n, r, "chckRange64")
  2804. of nkChckRange: genRangeChck(p, n, r, "chckRange")
  2805. of nkStringToCString: convStrToCStr(p, n, r)
  2806. of nkCStringToString: convCStrToStr(p, n, r)
  2807. of nkEmpty: discard
  2808. of nkLambdaKinds:
  2809. let s = n[namePos].sym
  2810. discard mangleName(p.module, s)
  2811. r.res = s.loc.snippet
  2812. if lfNoDecl in s.loc.flags or s.magic notin generatedMagics: discard
  2813. elif not p.g.generatedSyms.containsOrIncl(s.id):
  2814. p.locals.add(genProc(p, s))
  2815. of nkType: r.res = genTypeInfo(p, n.typ)
  2816. of nkStmtList, nkStmtListExpr:
  2817. # this shows the distinction is nice for backends and should be kept
  2818. # in the frontend
  2819. let isExpr = not isEmptyType(n.typ)
  2820. for i in 0..<n.len - isExpr.ord:
  2821. genStmt(p, n[i])
  2822. if isExpr:
  2823. gen(p, lastSon(n), r)
  2824. of nkBlockStmt, nkBlockExpr: genBlock(p, n, r)
  2825. of nkIfStmt, nkIfExpr: genIf(p, n, r)
  2826. of nkWhen:
  2827. # This is "when nimvm" node
  2828. gen(p, n[1][0], r)
  2829. of nkWhileStmt: genWhileStmt(p, n)
  2830. of nkVarSection, nkLetSection: genVarStmt(p, n)
  2831. of nkConstSection: discard
  2832. of nkForStmt, nkParForStmt:
  2833. internalError(p.config, n.info, "for statement not eliminated")
  2834. of nkCaseStmt: genCaseJS(p, n, r)
  2835. of nkReturnStmt: genReturnStmt(p, n)
  2836. of nkBreakStmt: genBreakStmt(p, n)
  2837. of nkAsgn: genAsgn(p, n)
  2838. of nkFastAsgn, nkSinkAsgn: genFastAsgn(p, n)
  2839. of nkDiscardStmt:
  2840. if n[0].kind != nkEmpty:
  2841. genLineDir(p, n)
  2842. gen(p, n[0], r)
  2843. r.res = "(" & r.res & ")"
  2844. of nkAsmStmt:
  2845. warningDeprecated(p.config, n.info, "'asm' for the JS target is deprecated, use the 'emit' pragma")
  2846. genAsmOrEmitStmt(p, n, true)
  2847. of nkTryStmt, nkHiddenTryStmt: genTry(p, n, r)
  2848. of nkRaiseStmt: genRaiseStmt(p, n)
  2849. of nkTypeSection, nkCommentStmt, nkIncludeStmt,
  2850. nkImportStmt, nkImportExceptStmt, nkExportStmt, nkExportExceptStmt,
  2851. nkFromStmt, nkTemplateDef, nkMacroDef, nkIteratorDef, nkStaticStmt,
  2852. nkMixinStmt, nkBindStmt: discard
  2853. of nkPragma: genPragma(p, n)
  2854. of nkProcDef, nkFuncDef, nkMethodDef, nkConverterDef:
  2855. var s = n[namePos].sym
  2856. if {sfExportc, sfCompilerProc} * s.flags == {sfExportc}:
  2857. genSym(p, n[namePos], r)
  2858. r.res = ""
  2859. of nkGotoState, nkState:
  2860. globalError(p.config, n.info, "not implemented")
  2861. of nkBreakState:
  2862. var a: TCompRes = default(TCompRes)
  2863. if n[0].kind == nkClosure:
  2864. gen(p, n[0][1], a)
  2865. let sym = n[0][1].typ[0].n[0].sym
  2866. r.res = "(($1).$2 < 0)" % [rdLoc(a), mangleName(p.module, sym)]
  2867. else:
  2868. gen(p, n[0], a)
  2869. let sym = n[0].typ[0].n[0].sym
  2870. r.res = "((($1.ClE_0).$2) < 0)" % [rdLoc(a), mangleName(p.module, sym)]
  2871. r.kind = resExpr
  2872. of nkPragmaBlock: gen(p, n.lastSon, r)
  2873. of nkComesFrom:
  2874. discard "XXX to implement for better stack traces"
  2875. else: internalError(p.config, n.info, "gen: unknown node type: " & $n.kind)
  2876. proc newModule(g: ModuleGraph; module: PSym): BModule =
  2877. ## Create a new JS backend module node.
  2878. if g.backend == nil:
  2879. g.backend = newGlobals()
  2880. result = BModule(module: module, sigConflicts: initCountTable[SigHash](),
  2881. graph: g, config: g.config
  2882. )
  2883. if sfSystemModule in module.flags:
  2884. PGlobals(g.backend).inSystem = true
  2885. proc genHeader(): Rope =
  2886. ## Generate the JS header.
  2887. result = rope("""/* Generated by the Nim Compiler v$1 */
  2888. var framePtr = null;
  2889. var excHandler = 0;
  2890. var lastJSError = null;
  2891. """.unindent.format(VersionAsString))
  2892. proc addHcrInitGuards(p: PProc, n: PNode,
  2893. moduleLoadedVar: Rope, inInitGuard: var bool) =
  2894. if n.kind == nkStmtList:
  2895. for child in n:
  2896. addHcrInitGuards(p, child, moduleLoadedVar, inInitGuard)
  2897. else:
  2898. let stmtShouldExecute = n.kind in {
  2899. nkProcDef, nkFuncDef, nkMethodDef,nkConverterDef,
  2900. nkVarSection, nkLetSection} or nfExecuteOnReload in n.flags
  2901. if inInitGuard:
  2902. if stmtShouldExecute:
  2903. dec p.extraIndent
  2904. line(p, "}\L")
  2905. inInitGuard = false
  2906. else:
  2907. if not stmtShouldExecute:
  2908. lineF(p, "if ($1 == undefined) {$n", [moduleLoadedVar])
  2909. inc p.extraIndent
  2910. inInitGuard = true
  2911. genStmt(p, n)
  2912. proc genModule(p: PProc, n: PNode) =
  2913. ## Generate the JS module code.
  2914. ## Called for each top level node in a Nim module.
  2915. if optStackTrace in p.options:
  2916. p.body.add(frameCreate(p,
  2917. makeJSString("module " & p.module.module.name.s),
  2918. makeJSString(toFilenameOption(p.config, p.module.module.info.fileIndex, foStacktrace))))
  2919. var transformedN = transformStmt(p.module.graph, p.module.idgen, p.module.module, n)
  2920. if sfInjectDestructors in p.module.module.flags:
  2921. transformedN = injectDestructorCalls(p.module.graph, p.module.idgen, p.module.module, transformedN)
  2922. if p.config.hcrOn and n.kind == nkStmtList:
  2923. let moduleSym = p.module.module
  2924. var moduleLoadedVar = rope(moduleSym.name.s) & "_loaded" &
  2925. idOrSig(moduleSym, moduleSym.name.s, p.module.sigConflicts, p.config)
  2926. lineF(p, "var $1;$n", [moduleLoadedVar])
  2927. var inGuardedBlock = false
  2928. addHcrInitGuards(p, transformedN, moduleLoadedVar, inGuardedBlock)
  2929. if inGuardedBlock:
  2930. dec p.extraIndent
  2931. line(p, "}\L")
  2932. lineF(p, "$1 = true;$n", [moduleLoadedVar])
  2933. else:
  2934. genStmt(p, transformedN)
  2935. if optStackTrace in p.options:
  2936. p.body.add(frameDestroy(p))
  2937. proc processJSCodeGen*(b: PPassContext, n: PNode): PNode =
  2938. ## Generate JS code for a node.
  2939. result = n
  2940. let m = BModule(b)
  2941. if pipelineutils.skipCodegen(m.config, n): return n
  2942. if m.module == nil: internalError(m.config, n.info, "myProcess")
  2943. let globals = PGlobals(m.graph.backend)
  2944. var p = newInitProc(globals, m)
  2945. m.initProc = p
  2946. p.unique = globals.unique
  2947. genModule(p, n)
  2948. p.g.code.add(p.locals)
  2949. p.g.code.add(p.body)
  2950. proc wholeCode(graph: ModuleGraph; m: BModule): Rope =
  2951. ## Combine source code from all nodes.
  2952. let globals = PGlobals(graph.backend)
  2953. for prc in globals.forwarded:
  2954. if not globals.generatedSyms.containsOrIncl(prc.id):
  2955. var p = newInitProc(globals, m)
  2956. attachProc(p, prc)
  2957. generateIfMethodDispatchers(graph, m.idgen)
  2958. for prc in getDispatchers(graph):
  2959. if not globals.generatedSyms.containsOrIncl(prc.id):
  2960. var p = newInitProc(globals, m)
  2961. attachProc(p, prc)
  2962. result = globals.typeInfo & globals.constants & globals.code
  2963. proc finalJSCodeGen*(graph: ModuleGraph; b: PPassContext, n: PNode): PNode =
  2964. ## Finalize JS code generation of a Nim module.
  2965. ## Param `n` may contain nodes returned from the last module close call.
  2966. var m = BModule(b)
  2967. if sfMainModule in m.module.flags:
  2968. # Add global destructors to the module.
  2969. # This must come before the last call to `myProcess`.
  2970. for i in countdown(high(graph.globalDestructors), 0):
  2971. n.add graph.globalDestructors[i]
  2972. # Process any nodes left over from the last call to `myClose`.
  2973. result = processJSCodeGen(b, n)
  2974. # Some codegen is different (such as no stacktraces; see `initProcOptions`)
  2975. # when `std/system` is being processed.
  2976. if sfSystemModule in m.module.flags:
  2977. PGlobals(graph.backend).inSystem = false
  2978. # Check if codegen should continue before any files are generated.
  2979. # It may bail early is if too many errors have been raised.
  2980. if pipelineutils.skipCodegen(m.config, n): return n
  2981. # Nim modules are compiled into a single JS file.
  2982. # If this is the main module, then this is the final call to `myClose`.
  2983. if sfMainModule in m.module.flags:
  2984. var code = genHeader() & wholeCode(graph, m)
  2985. let outFile = m.config.prepareToWriteOutput()
  2986. # Generate an optional source map.
  2987. if optSourcemap in m.config.globalOptions:
  2988. var map: SourceMap
  2989. map = genSourceMap($code, outFile.string)
  2990. code &= "\n//# sourceMappingURL=$#.map" % [outFile.string]
  2991. writeFile(outFile.string & ".map", $(%map))
  2992. # Check if the generated JS code matches the output file, or else
  2993. # write it to the file.
  2994. if not equalsFile(code, outFile):
  2995. if not writeRope(code, outFile):
  2996. rawMessage(m.config, errCannotOpenFile, outFile.string)
  2997. proc setupJSgen*(graph: ModuleGraph; s: PSym; idgen: IdGenerator): PPassContext =
  2998. result = newModule(graph, s)
  2999. result.idgen = idgen