jsgen.nim 75 KB

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