gitoriaLog in with ident

calendar

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit2881119f2881119fcalendar mission 001 (4/4): code order — README layout + same-output test, STATUS, LOG, report; tests/letcount.py (sub-folders), tests/realdata-baseline.mjs, tests/realdata-compare.pymre2881119f/plugins/web/compile.hl

51.0 KB

  1. // plugins/web/compile.hl — THE FRAMEWORK COMPILES EACH COMPONENT.
  2. //
  3. // Mission 313 (the creator, 15 Sep 14:30: "clientside interpreter + table against
  4. // component code per component, no tables needed"). The old hl:web ships ONE generic client
  5. // that walks a tree the seed carries: it pairs elements with nodes, asks a table which
  6. // members each element shows, asks `view.value` what each bound spot holds, and does it
  7. // again on every paint. hl:web ships the ANSWERS instead — this file writes each
  8. // component's own code, once, where the old hl:web would have walked.
  9. //
  10. // WHAT IS EMITTED, per component, beside the class `hlJs` compiled:
  11. //
  12. // v(c,m,o,host,i,rows,rk,fill,cr,opt) the component's View, unrolled: one
  13. // statement per element, per handler, per
  14. // bound spot. `cr` false CLAIMS the server's
  15. // DOM (take host.children[i], step on), `cr`
  16. // true CREATES it — the two walks the old hl:web
  17. // spells out separately, which differ only in
  18. // where an element comes from.
  19. // b["<for site>"] one `for` body — the row factory the keyed
  20. // region builds a row with.
  21. // t/e["<if site>"] an `if`'s two branches.
  22. // f["<reference site>"] the fragment this component writes into a
  23. // child's `slot` — built in THIS frame, which
  24. // is why it is this component's code.
  25. // p["<element site>"] the paint statements: `p` writes what one
  26. // member feeds (the old hl:web's paint(&m,s,name)),
  27. // `r` rewrites a row's element where the DOM
  28. // does not already hold it (rowPaint).
  29. //
  30. // The generated code calls a FIXED runtime (client.hl) for everything that is not this
  31. // component: the mount records, the keyed region diff, the binding edges, the
  32. // derivations, the socket, navigation. It never looks anything up in a table — the
  33. // names, the sites and the write sets are written into the statements.
  34. //
  35. // It is TEXT the framework produces, served from memory beside the module (WebFramework
  36. // `module`), never a JavaScript file under plugins/.
  37. import { newline, tab } from './view.hl'
  38. import HlwView from './view.hl'
  39. // ---- the emitted half --------------------------------------------------------------
  40. module(gen, key, nodes, fnTable) {
  41. fns = [] // the sub-walks: row bodies, if branches, fills
  42. done = {}
  43. rowVars = []
  44. tbl = tableOf(gen, key) // what the language says about this file, read once
  45. regions = regionIndex(tbl) // a `for`'s list reads, an `if`'s condition reads
  46. // A SHELL'S VIEW IS A `body` ELEMENT and the document already has one: the walk runs
  47. // against document.body itself, so the root list is that element's children and the
  48. // element only takes the marks a region rebuild on it would need.
  49. let roots = nodes
  50. let bodySite = null
  51. if (nodes.length == 1 && nodes[0].k == 'el' && nodes[0].tag == 'body') {
  52. roots = nodes[0].children
  53. bodySite = nodes[0].site
  54. }
  55. let root = walkTop(key, roots)
  56. if (bodySite != null) {
  57. root = root.replace('let r=rows;', 'let r=rows;await c.markHost(m,host,' + str(bodySite) + ');')
  58. }
  59. let src = ';(function(){var g=(typeof globalThis!=="undefined"?globalThis:window);'
  60. src = src + 'var C=(g.__hlC=g.__hlC||{});'
  61. // the element a claim takes or a create makes — the one shape both walks share; a create
  62. // inside an svg (or an svg itself) is made in the SVG namespace, as the parser makes it
  63. // THE PRELUDE, one per module: the element a claim takes or a create makes, and the
  64. // two reads. A read written out in full — `(r["title"]!=null?r["title"]:inst["title"])`
  65. // — is 45 bytes and a component's View holds dozens of them; named, it is 16. The
  66. // rule is the same rule (a `for` row variable in scope wins over a member of the
  67. // same name, and a field path walks into it), spelled once.
  68. // A claim also moves the host's CURSOR — the last node the walk took there — which is
  69. // where a text leaf and a region's mark are looked for next (client.hl `leafNode`,
  70. // `markAt`).
  71. src = src + 'function A(cr,host,i,tag){if(cr){if(tag==="svg"||(host.namespaceURI==="http://www.w3.org/2000/svg"&&host.localName.toLowerCase()!=="foreignobject")){return document.createElementNS("http://www.w3.org/2000/svg",tag);}return document.createElement(tag);}var e=host.children[i];if(e!=null){host.__hlCur=e;}return e;}'
  72. src = src + 'function S(v){return v==null?"":""+v;}'
  73. src = src + 'async function X(t,r,q){return await g.__hlX(t,q,r);}'
  74. src = src + 'function RV(r,q,n){return r[n]!=null?r[n]:q[n];}'
  75. src = src + 'function RF(r,q,n,p){var v=RV(r,q,n);for(var k=0;k<p.length;k++){if(v==null)return null;v=v[p[k]];}return v;}'
  76. src = src + 'var B={},T={},E={},F={},P={};'
  77. // ONE FUNCTION PER LIST, however many sites reach it: a nested walk is written once
  78. // and named — emitting it per site made the reference app's home page 215 KB of the
  79. // same code over and over.
  80. let wi = 0
  81. for (f of fns) {
  82. wi = wi + 1
  83. let name = 'w' + wi
  84. src = src + 'var ' + name + '=' + f.src + ';'
  85. for (site of f.sites) { src = src + f.slot + '[' + str(site) + ']=' + name + ';' }
  86. }
  87. let paints = []
  88. collectPaints(&paints, roots)
  89. for (e of paints) { src = src + 'P[' + str(e.site) + ']={p:' + e.paint + ',r:' + e.row + '};' }
  90. src = src + 'C[' + str(key) + ']={v:' + root + ',b:B,t:T,e:E,f:F,p:P'
  91. // THE ANSWERS A LOOKUP STILL NEEDS, and only those. A local event's write set stands
  92. // at its own listener and a region's names at its own region — written into the
  93. // call. These three are asked for by NAME at run time and cannot be: an inbound
  94. // frame names its event, a routine handed down names the member that holds it, and
  95. // a write set names the derivations that follow it.
  96. src = src + ',ev:' + eventMap() + ',mw:' + memberMap() + ',dv:' + derivList() + ',fn:' + fnMap(fnTable) + '};'
  97. return src + '})();' + newline
  98. }
  99. tbl = null
  100. regions = {}
  101. // WHAT A FUNCTION VALUE WRITES, by the site it was made at (tickets #98, #99): the
  102. // module announces a function's return with its site, and the browser repaints this
  103. // set — the members it writes, closed over the methods it calls and the events it
  104. // emits, the same closure a handler's set gets. A function that writes nothing has
  105. // no entry.
  106. fnMap(fns) {
  107. let bySite = {}
  108. if (fns != null) {
  109. for (f of fns) {
  110. let names = closeWrites(tbl, f.writes, f.reads)
  111. if (names.length > 0) { bySite[f.site] = names }
  112. }
  113. }
  114. return mapOf(bySite)
  115. }
  116. // what a DECLARED handler writes, by event: one entry per event name, unioned
  117. eventMap() {
  118. let byEvent = {}
  119. for (h of tbl.handlers) {
  120. if (!h.nested) {
  121. let have = byEvent[h.event] == null ? [] : byEvent[h.event]
  122. for (w of closeWrites(tbl, h.writes, h.reads)) { if (!have.includes(w)) { have.push(w) } }
  123. byEvent[h.event] = have
  124. }
  125. }
  126. return mapOf(byEvent)
  127. }
  128. // A MEMBER HOLDING A ROUTINE: what calling it writes is what its initializer writes
  129. memberMap() {
  130. let byName = {}
  131. for (m of tbl.members) {
  132. if (m.nodes != null) { byName[m.name] = memberNames(m.nodes.writes) }
  133. }
  134. return mapOf(byName)
  135. }
  136. // EVERY INITIALIZER, IN DECLARATION ORDER, with the members it reads — the whole of
  137. // what a derivation needs; the class carries the computation itself as `__derive__`.
  138. // `srv` (written only when true, same rule as `isStatic` on a read — every byte here
  139. // ships to the browser) marks a SERVER REFERENCE SITE (COMPONENTS.md §9.1/§9.3): an
  140. // initializer that calls an imported class (`import Store from './store.hl'`, then
  141. // `Store.chatsOf(…)` — `hlDenotes`'s own `kind: 'class'`, not a second resolution).
  142. // It is evaluated per request, on the SERVER, and its value ships into the page as
  143. // state; `client.hl`'s `moved()` must never call it locally — routger's `conversations
  144. // = … ? store.chatsOf(session.user.id) : []` reached `hl:time`, which ships no client
  145. // half, the moment a session sync (0b17f65b) made `session` move in the browser and
  146. // `moved()` re-ran every derivation that reads it. A fresh value for a server
  147. // reference site ships in `sync` instead (WebFramework.hl `serverSyncNames`).
  148. derivList() {
  149. let src = '['
  150. let first = true
  151. for (d of tbl.derivations) {
  152. if (!first) { src = src + ',' }
  153. first = false
  154. src = src + '{name:' + str(d.name) + ',site:' + str(d.site) + ',reads:' + list(memberNames(d.reads))
  155. if (d.serverSite) { src = src + ',srv:true' }
  156. src = src + '}'
  157. }
  158. return src + ']'
  159. }
  160. // does this read list (RAW — hlDenotes's own kind per name, before `memberNames`
  161. // narrows it to members) reach an imported class or a braced static of one — the two
  162. // forms COMPONENTS.md §9.1/§9.3 calls "a call on an imported class" (`import Store
  163. // from './store.hl'`, `Store.noteRows()`, OR the form the maintained demos actually
  164. // use, `import { postRow } from './store.hl'`, `postRow(id)`)? See `derivList` above.
  165. serverSite(reads) {
  166. if (reads == null) { return false }
  167. for (r of reads) { if (r.kind == 'class' || r.kind == 'import') { return true } }
  168. return false
  169. }
  170. mapOf(byName) {
  171. let src = '{'
  172. let first = true
  173. for (k of byName.keys()) {
  174. if (!first) { src = src + ',' }
  175. first = false
  176. src = src + str(k) + ':' + list(byName[k])
  177. }
  178. return src + '}'
  179. }
  180. // the write set and the read set of the handler at this site, closed over the methods
  181. // it calls and the handlers it emits to — computed here, written into the listener
  182. handlerSets(site) {
  183. for (h of tbl.handlers) {
  184. if (h.nested && h.site == site) {
  185. return list(closeWrites(tbl, h.writes, h.reads)) + ',' + list(closeReads(tbl, h.reads))
  186. }
  187. }
  188. return '[],[]'
  189. }
  190. regionNamesAt(site) {
  191. let names = regions[site]
  192. return list(names == null ? [] : names)
  193. }
  194. fns = []
  195. // ---- the walk, unrolled ------------------------------------------------------------
  196. // `top` marks the View's own root list: an element there is a COMPOSITION ROOT — a
  197. // reference above may have overwritten some of its events and put classes on it, which
  198. // is what `opt` carries (the old hl:web's rootOverwrites and withRootClasses).
  199. walk(key, nodes) {
  200. return plain(key, nodes)
  201. }
  202. // a list's walk
  203. plain(key, nodes) {
  204. let body = ''
  205. for (n of nodes) { body = body + node(key, n, false, false) }
  206. return 'async function(c,m,o,host,i,rows,rk,fill,cr,opt){let inst=m.instance;let r=rows;' + body + 'return i;}'
  207. }
  208. // the View's own root list, whose elements are composition roots
  209. walkTop(key, nodes) {
  210. let body = ''
  211. for (n of nodes) { body = body + node(key, n, true, false) }
  212. return 'async function(c,m,o,host,i,rows,rk,fill,cr,opt){let inst=m.instance;let r=rows;' + body + 'return i;}'
  213. }
  214. // a sub-walk, registered under its own site so the runtime can reach it by name
  215. // A SUB-WALK IS WRITTEN ONCE, however often the compile reaches its list.
  216. sub(key, nodes, slot, site) {
  217. if (done[slot + ' ' + site] != null) { return null }
  218. done[slot + ' ' + site] = true
  219. fns.push({ slot = slot; sites = [site]; src = walk(key, nodes); })
  220. return null
  221. }
  222. done = {}
  223. node(key, n, top, filterOns) {
  224. if (n.k == 'el') { return elNode(key, n, top) }
  225. if (n.k == 'text') { return 'if(cr){host.appendChild(document.createTextNode(' + str(n.text) + '));}else{await c.leafAt(host,false,i,null,' + str(n.text) + ');}' }
  226. if (n.k == 'on') {
  227. // A REFERENCE ABOVE MAY HAVE OVERWRITTEN THIS EVENT on the composition root:
  228. // the root's own handler for it is dropped and the reference's stands instead
  229. // (the old hl:web's withoutOns, which applies to the root element's direct children).
  230. let guard = filterOns ? 'if(!(opt&&opt.over&&opt.over.indexOf(' + str(n.event) + ')>=0)){' : '{'
  231. return guard + 'await c.onAt(m,host,' + str(n.event) + ',' + str(n.site) + ',rows,' + handlerSets(n.site) + ');}'
  232. }
  233. if (n.k == 'member' && n.name == 'slot') {
  234. // the SHELL's slot is where the route component hangs; a child's slot is the
  235. // fragment its host wrote, and the host's frame builds it
  236. return 'if(m.isShell){i=await c.slotShell(m,host,i,cr);}else if(fill!=null){i=await c.slotFill(m,o,host,i,fill,cr);}'
  237. }
  238. // A TEXT LEAF STANDING IN A LIST — an `if` branch, a `for` body — beside elements or
  239. // alone: its own text node, and a site of the member it reads (or of the row it
  240. // stands in), painted by rewriting that node.
  241. if (n.k == 'member' || n.k == 'field' || n.k == 'expr') {
  242. let names = readNames(n)
  243. return 'await c.textAt(m,host,cr,async function(inst,r){return ' + textRead(n) + ';},' + list(names) + ',rows,rk);'
  244. }
  245. if (n.k == 'for') {
  246. // THE ROW VARIABLE IS IN SCOPE INSIDE THE BODY, and a read of it is the ROW's,
  247. // not a member of the instance — the language resolves it that way and the site
  248. // sets must say the same, or a member of the same name would paint the row.
  249. rowVars.push(n.row)
  250. sub(key, n.body, 'B', n.site)
  251. rowVars.pop()
  252. return 'i=await c.forAt(m,o,host,i,' + str(n.site) + ',' + str(n.row) + ',function(inst,r){return ' + rawRead(n.list) + ';},rows,rk,fill,cr,' + regionNamesAt(n.site) + ');'
  253. }
  254. if (n.k == 'if') {
  255. sub(key, n.then, 'T', n.site)
  256. sub(key, n.other, 'E', n.site)
  257. return 'i=await c.ifAt(m,o,host,i,' + str(n.site) + ',function(inst,r){return ' + rawRead(n.cond) + ';},rows,rk,fill,cr,' + regionNamesAt(n.site) + ');'
  258. }
  259. if (n.k == 'component') {
  260. if (n.fill != null && n.fill.length > 0) { sub(key, n.fill, 'F', n.site) }
  261. return 'i=await c.kidAt(m,host,i,' + kidSpec(n) + ',rows,rk,fill,cr,opt);'
  262. }
  263. return ''
  264. }
  265. // ---- an element --------------------------------------------------------------------
  266. elNode(key, n, top) {
  267. let src = '{let el=A(cr,host,i,' + str(n.tag) + ');if(!cr){i=i+1;}'
  268. src = src + 'if(el==null){await c.acqFail(' + str(n.tag) + ',host);}else{'
  269. // the attributes, on the walk that BUILDS the element (a claim takes the server's)
  270. src = src + 'if(cr){' + createAttrs(n) + (top ? 'await c.rootClasses(el,opt);' : '') + 'host.appendChild(el);}'
  271. src = src + 'el.__hlRows=rows;el.__hlSite=' + str(n.site) + ';el.__hlKey=' + str(key) + ';'
  272. // the element's own named entries, for the literal a handler on it fires
  273. src = src + 'el.__hlLit=function(inst,r){return ' + litNamed(n) + ';};'
  274. let names = siteNames(n)
  275. let valueMember = 'null'
  276. for (a of n.attrs) { if (a.member != null && a.name == 'value') { valueMember = str(a.member) } }
  277. let sited = ''
  278. if (names.length > 0 || valueMember != 'null') {
  279. sited = 'await c.siteAt(m,el,' + list(names) + ',' + str(n.site) + ',' + valueMember + ',' + (n.tag == 'select' ? 'true' : 'false') + ',rows);'
  280. }
  281. let kids = ''
  282. // AN ELEMENT THAT HOLDS ONLY TEXT is painted whole (`textContent`, see the paints):
  283. // built, it gets that text as one node; claimed, the server's is taken as it stands
  284. let whole = textOf(n)
  285. if (whole != null) {
  286. kids = 'if(cr){host.appendChild(document.createTextNode(' + whole + '));}'
  287. for (c of n.children) { if (c.k == 'on') { kids = kids + node(key, c, false, top) } }
  288. }
  289. else if (mixed(n)) { kids = mixedKids(key, n, top) }
  290. else { for (c of n.children) { kids = kids + node(key, c, false, top) } }
  291. let inner = '{let host=el;let i=0;' + kids + '}'
  292. // A SELECT IS SITED AFTER ITS OPTIONS: the member decides which option stands, and
  293. // the read-back that `siteAt` does reports nothing before they exist.
  294. if (n.tag == 'select') { src = src + inner + (selectValue(n) == 'null' ? '' : 'if(cr){await c.applySelectAt(m,el,' + selectValue(n) + ');}') + sited }
  295. else { src = src + sited + inner }
  296. return src + '}}'
  297. }
  298. // A TEXT LEAF BESIDE AN ELEMENT OR A REGION (ticket #86 follow-up): `td { d.n if (…) {…} }`
  299. // cannot be painted through `textContent`, which would wipe the branch. Each RUN of
  300. // adjacent leaves is one text node, held on the element (`__hlLeaves`, by the run's
  301. // index) where the walk builds or claims it, and the paints rewrite that node alone.
  302. mixed(n) {
  303. if (textOf(n) != null) { return false }
  304. for (c of n.children) { if (isReadNode(c)) { return true } }
  305. return false
  306. }
  307. isLeaf(c) { return c.k == 'text' || isReadNode(c) }
  308. // a node that shows a value read at render time: a member, a field path, or an expression
  309. isReadNode(c) { return (c.k == 'member' || c.k == 'field' || c.k == 'expr') && c.name != 'slot' }
  310. // the members whose move repaints a read (`Style` and a `for` row variable are not members
  311. // of the instance), and the guard a paint writes for them
  312. readNames(c) {
  313. let out = []
  314. for (nm of (c.k == 'expr' ? c.names : [c.name])) {
  315. if (nm != 'Style' && !rowVars.includes(nm) && !out.includes(nm)) { out.push(nm) }
  316. }
  317. return out
  318. }
  319. guardOf(c) {
  320. let g = ''
  321. for (nm of readNames(c)) { g = g + (g == '' ? '' : '||') + 'n===' + str(nm) }
  322. return g
  323. }
  324. // the runs of adjacent leaves, in order; an `on` renders nothing and splits none
  325. runsOf(n) {
  326. let out = []
  327. let run = []
  328. for (c of n.children) {
  329. if (isLeaf(c)) { run.push(c) }
  330. else if (c.k != 'on') {
  331. if (run.length > 0) { out.push(run) }
  332. run = []
  333. }
  334. }
  335. if (run.length > 0) { out.push(run) }
  336. return out
  337. }
  338. runText(run) {
  339. let src = '""'
  340. for (c of run) { src = src + '+(' + (c.k == 'text' ? str(c.text) : textRead(c)) + ')' }
  341. return src
  342. }
  343. runFeeds(run) {
  344. for (c of run) { if (c.k != 'text') { return true } }
  345. return false
  346. }
  347. mixedKids(key, n, top) {
  348. let kids = ''
  349. let run = []
  350. let k = 0
  351. for (c of n.children) {
  352. if (isLeaf(c)) { run.push(c) }
  353. else {
  354. if (c.k != 'on' && run.length > 0) { kids = kids + leafRun(run, k) k = k + 1 run = [] }
  355. kids = kids + node(key, c, false, top)
  356. }
  357. }
  358. if (run.length > 0) { kids = kids + leafRun(run, k) }
  359. return kids
  360. }
  361. // EVERY CALL INTO THE CLIENT IS AWAITED: its methods are async in the browser, and one
  362. // not awaited runs its DOM work after the walk has gone on — a built leaf then lands
  363. // after the elements that follow it (ticket #104).
  364. leafRun(run, k) {
  365. if (!runFeeds(run)) { return 'if(cr){host.appendChild(document.createTextNode(' + runText(run) + '));}else{await c.leafAt(host,false,i,null,' + runText(run) + ');}' }
  366. return 'await c.leafAt(host,cr,i,' + k + ',' + runText(run) + ');'
  367. }
  368. // the attributes an element is BUILT with — a bound one written in, a literal one as it
  369. // stands. `value` is a property once the page is live and an attribute as the control's
  370. // default; a textarea has no value attribute at all and a select's value is an option.
  371. createAttrs(n) {
  372. let src = ''
  373. for (a of n.attrs) {
  374. if (isBool(a)) {
  375. src = src + '{' + boolWrite(a, rawRead(a.member != null ? { k = 'member'; name = a.member; } : a.ref)) + '}'
  376. } else {
  377. let rd = a.member != null ? readOf({ k = 'member'; name = a.member; }) : (a.ref != null ? readOf(a.ref) : str(a.text))
  378. src = src + '{let v=' + rd + ';'
  379. if (a.extra != null) { src = src + 'v=v+" "+' + str(a.extra) + ';' }
  380. if (n.tag == 'select' && a.name == 'value') { src = src + '}' }
  381. else if (a.name == 'value') {
  382. src = src + 'if(el.value!=null){el.value=v;' + (n.tag == 'textarea' ? '' : 'el.setAttribute("value",v);') + '}else{el.setAttribute("value",v);}}'
  383. } else { src = src + 'el.setAttribute(' + str(a.name) + ',v);}' }
  384. }
  385. }
  386. if (boundValue(n)) { src = src + 'el.setAttribute("autocomplete","off");' }
  387. return src
  388. }
  389. // a BOUND boolean attribute — a literal one was decided at build (WebFramework `element`)
  390. isBool(a) {
  391. return (a.member != null || a.ref != null) && v.isBoolAttr(a.name)
  392. }
  393. // A BOUND BOOLEAN ATTRIBUTE, WRITTEN (ticket #33): set when the value is on, REMOVED when
  394. // it is off — the markup's rule (view.boolAttrs) — and the DOM property with it, because
  395. // once the page is live `checked` is the property and the attribute only its default.
  396. boolWrite(a, raw) {
  397. let prop = a.name == 'readonly' ? 'readOnly' : a.name
  398. return 'let on=!!' + raw + ';if(on){el.setAttribute(' + str(a.name) + ',"");}else if(el.removeAttribute){el.removeAttribute(' + str(a.name) + ');}if(' + str(prop) + ' in el&&el[' + str(prop) + ']!==on){el[' + str(prop) + ']=on;}'
  399. }
  400. // view.hl's `boundValue`, to the letter: a FORM CONTROL whose `value` reads a member or
  401. // a field, and not one the author gave an `autocomplete` of its own
  402. boundValue(n) {
  403. if (n.tag != 'input' && n.tag != 'textarea' && n.tag != 'select') { return false }
  404. let bound = false
  405. for (a of n.attrs) {
  406. if (a.name == 'autocomplete') { return false }
  407. if (a.name == 'value' && (a.member != null || a.ref != null)) { bound = true }
  408. }
  409. return bound
  410. }
  411. selectValue(n) {
  412. for (a of n.attrs) {
  413. if (a.name == 'value') {
  414. if (a.member != null) { return readOf({ k = 'member'; name = a.member; }) }
  415. if (a.ref != null) { return readOf(a.ref) }
  416. return str(a.text)
  417. }
  418. }
  419. return 'null'
  420. }
  421. // the element's own entries as the literal sees them — its attributes by name, then the
  422. // `for` row variables in scope (the row rides on the value)
  423. litNamed(n) {
  424. let src = '{'
  425. let first = true
  426. for (a of n.attrs) {
  427. if (!first) { src = src + ',' }
  428. first = false
  429. let v = a.member != null ? rawRead({ k = 'member'; name = a.member; }) : (a.ref != null ? rawRead(a.ref) : str(a.text))
  430. src = src + str(a.name) + ':' + v
  431. }
  432. return src + '}'
  433. }
  434. // the reference's own description, written at its use site: what it binds, what it
  435. // overwrites, the classes the host's `#Child` rule puts on it
  436. kidSpec(n) {
  437. let src = '{key:' + str(n.key) + ',kid:' + str(kidKeyOf(n)) + ',site:' + str(n.site) + ',fill:' + ((n.fill != null && n.fill.length > 0) ? 'true' : 'false')
  438. src = src + ',bindings:['
  439. let first = true
  440. for (b of n.bindings) {
  441. if (!first) { src = src + ',' }
  442. first = false
  443. src = src + '{name:' + str(b.name) + ',member:' + (b.member == null ? 'null' : str(b.member))
  444. src = src + ',ref:' + (b.ref == null ? 'null' : 'function(inst,r){return ' + rawRead(b.ref) + ';}')
  445. src = src + ',refName:' + (b.ref == null ? 'null' : str(b.ref.name))
  446. src = src + ',text:' + (b.text == null ? 'null' : 'true') + ',value:' + (b.text == null ? 'null' : refLiteral(b)) + '}'
  447. }
  448. src = src + '],ons:['
  449. first = true
  450. for (o of n.ons) {
  451. if (!first) { src = src + ',' }
  452. first = false
  453. src = src + '{event:' + str(o.event) + ',site:' + str(o.site) + ',sets:[' + handlerSets(o.site) + ']}'
  454. }
  455. src = src + '],classes:' + list(n.classes == null ? [] : n.classes) + '}'
  456. return src
  457. }
  458. // view.hl's kidKey: the reference's path, joined — the key the server mounted it under
  459. kidKeyOf(n) {
  460. let out = ''
  461. for (p of n.path) { out = out + '/' + p }
  462. return out
  463. }
  464. // the value a literal binding carries — view.refValue, folded at compile time
  465. refLiteral(b) {
  466. if (b.kind == 'folded') { return jsValue(b.value) }
  467. if (b.kind == 'number') { return '' + b.text }
  468. if (b.kind == 'boolean') { return b.text == 'true' ? 'true' : 'false' }
  469. if (b.kind == 'null_literal') { return 'null' }
  470. return str(b.text)
  471. }
  472. jsValue(v) {
  473. if (v == null) { return 'null' }
  474. if (hlTypeName(v) == 'String') { return str(v) }
  475. if (hlTypeName(v) == 'Boolean') { return v ? 'true' : 'false' }
  476. if (hlTypeName(v) == 'Number') { return '' + v }
  477. return JSON.stringify(v)
  478. }
  479. // ---- the site set: what this element SHOWS ------------------------------------------
  480. // The old hl:web asked the module's table which members the element at this site reads. The
  481. // answer is a fact about the View, so it is written in: the members its bound
  482. // attributes and its text leaves name. `Style` is folded into a class name at build and
  483. // the shell's `slot` is swapped by navigation — neither is ever painted, and neither is
  484. // a member read that reaches here (a `for` row variable resolves to its row).
  485. siteNames(n) {
  486. let out = []
  487. for (a of n.attrs) {
  488. if (a.member != null && a.member != 'Style' && !rowVars.includes(a.member) && !out.includes(a.member)) { out.push(a.member) }
  489. // A FIELD OF A MEMBER (`value = f.title`, ticket #93) is a read of the member:
  490. // a write to `f.title`, or a new `f`, moves `f`, and this element repaints
  491. if (a.ref != null && a.ref.name != 'Style' && !rowVars.includes(a.ref.name) && !out.includes(a.ref.name)) { out.push(a.ref.name) }
  492. }
  493. for (c of n.children) {
  494. if (isReadNode(c)) {
  495. for (nm of readNames(c)) { if (!out.includes(nm)) { out.push(nm) } }
  496. }
  497. }
  498. return out
  499. }
  500. rowVars = []
  501. // ---- the paints ---------------------------------------------------------------------
  502. collectPaints(&out, nodes) {
  503. for (n of nodes) {
  504. if (n.k == 'el') {
  505. let paint = paintFn(n)
  506. let row = rowFn(n)
  507. if (paint != null || row != 'null') {
  508. out.push({ site = n.site; paint = paint == null ? 'null' : paint; row = row; })
  509. }
  510. collectPaints(&out, n.children)
  511. } else if (n.k == 'for') { collectPaints(&out, n.body) }
  512. else if (n.k == 'if') { collectPaints(&out, n.then) collectPaints(&out, n.other) }
  513. else if (n.k == 'component') { if (n.fill != null) { collectPaints(&out, n.fill) } }
  514. }
  515. return null
  516. }
  517. // `paint(&m, s, name)`, compiled: the bound attributes under the member each reads, and
  518. // the text where the member that moved stands among the leaves.
  519. paintFn(n) {
  520. let body = ''
  521. for (a of n.attrs) {
  522. if (a.member != null) {
  523. body = body + 'if(n===' + str(a.member) + '){' + attrWrite(n, a, readOf({ k = 'member'; name = a.member; })) + '}'
  524. } else if (a.ref != null) {
  525. // a field of a member paints when the MEMBER moves (ticket #93)
  526. body = body + 'if(n===' + str(a.ref.name) + '){' + attrWrite(n, a, readOf(a.ref)) + '}'
  527. }
  528. }
  529. let text = textOf(n)
  530. if (text != null) {
  531. let guard = ''
  532. for (c of n.children) {
  533. if (isReadNode(c)) {
  534. let g = guardOf(c)
  535. if (g != '') {
  536. if (guard != '') { guard = guard + '||' }
  537. guard = guard + g
  538. }
  539. }
  540. }
  541. if (guard != '') { body = body + 'if(' + guard + '){el.textContent=' + text + ';}' }
  542. } else if (mixed(n)) {
  543. let k = 0
  544. for (run of runsOf(n)) {
  545. let guard = ''
  546. for (c of run) {
  547. if (c.k != 'text') {
  548. let g = guardOf(c)
  549. if (g != '') {
  550. if (guard != '') { guard = guard + '||' }
  551. guard = guard + g
  552. }
  553. }
  554. }
  555. if (guard != '') { body = body + 'if((' + guard + ')&&el.__hlLeaves&&el.__hlLeaves[' + k + ']){el.__hlLeaves[' + k + '].data=' + runText(run) + ';}' }
  556. k = k + 1
  557. }
  558. }
  559. if (body == '') { return null }
  560. return 'async function(el,inst,r,n){' + body + '}'
  561. }
  562. // `rowPaint(&m, el)`, compiled: every bound spot, written only where the DOM does not
  563. // already hold it — which is why a push into 2000 rows costs the 1999 nothing.
  564. rowFn(n) {
  565. let body = ''
  566. for (a of n.attrs) {
  567. if (isBool(a)) {
  568. body = body + '{' + boolWrite(a, rawRead(a.member != null ? { k = 'member'; name = a.member; } : a.ref)) + '}'
  569. } else if (a.member != null || a.ref != null) {
  570. let one = 'let v=' + readOf(a.member != null ? { k = 'member'; name = a.member; } : a.ref) + ';'
  571. if (a.extra != null) { one = one + 'v=v+" "+' + str(a.extra) + ';' }
  572. if (n.tag == 'select' && a.name == 'value') { one = one + 'if(el.value!==v){el.value=v;}' }
  573. else {
  574. one = one + 'if(el.getAttribute(' + str(a.name) + ')!==v){el.setAttribute(' + str(a.name) + ',v);}'
  575. if (a.name == 'value') { one = one + 'if(el.value!=null&&el.value!==v){el.value=v;}' }
  576. }
  577. body = body + '{' + one + '}'
  578. }
  579. }
  580. let text = textOf(n)
  581. let feeds = false
  582. for (c of n.children) { if (isReadNode(c)) { feeds = true } }
  583. if (text != null && feeds) { body = body + '{let t=' + text + ';if(el.textContent!==t){el.textContent=t;}}' }
  584. if (text == null && feeds) {
  585. let k = 0
  586. for (run of runsOf(n)) {
  587. if (runFeeds(run)) { body = body + '{let x=el.__hlLeaves&&el.__hlLeaves[' + k + '];let t=' + runText(run) + ';if(x&&x.data!==t){x.data=t;}}' }
  588. k = k + 1
  589. }
  590. }
  591. if (body == '') { return 'null' }
  592. return 'async function(el,inst,r){' + body + '}'
  593. }
  594. attrWrite(n, a, v) {
  595. if (isBool(a)) { return boolWrite(a, rawRead(a.member != null ? { k = 'member'; name = a.member; } : a.ref)) }
  596. let src = 'let v=' + v + ';'
  597. if (a.extra != null) { src = src + 'v=v+" "+' + str(a.extra) + ';' }
  598. if (n.tag == 'select' && a.name == 'value') { return src + 'el.value=v;' }
  599. src = src + 'el.setAttribute(' + str(a.name) + ',v);'
  600. if (a.name == 'value') { src = src + 'if(el.value!=null){el.value=v;}' }
  601. return src
  602. }
  603. textOf(n) {
  604. let parts = []
  605. let content = 0
  606. let feeds = false
  607. for (c of n.children) {
  608. if (c.k != 'on') {
  609. content = content + 1
  610. if (c.k == 'text') { parts.push(str(c.text)) }
  611. else if (isReadNode(c)) { parts.push(textRead(c)) feeds = true }
  612. }
  613. }
  614. if (!feeds) { return null }
  615. if (parts.length != content) { return null }
  616. let src = '""'
  617. for (p of parts) { src = src + '+(' + p + ')' }
  618. return src
  619. }
  620. // ---- a read, written in ---------------------------------------------------------------
  621. // `view.value`'s own rule as an expression: a `for` row variable in scope wins over a
  622. // member of the same name, and a field path walks into it. `readOf` answers the STRING
  623. // the DOM takes; `rawRead` the value itself (a binding, a list, a condition).
  624. readOf(node) { return '(""+' + rawRead(node) + ')' }
  625. // A READ SHOWN AS TEXT: null is no text, as the server writes it (view.hl `escape`)
  626. textRead(node) { return 'S(' + rawRead(node) + ')' }
  627. rawRead(node) {
  628. if (node == null) { return 'null' }
  629. if (node.k == 'text') { return node.kind == 'folded' && hlTypeName(node.value) == 'Hybrid' ? JSON.stringify(node.value) : str(node.text) }
  630. if (node.k == 'expr') { return '(await X(' + JSON.stringify(node.x) + ',r,inst))' }
  631. if (node.k != 'field') { return 'RV(r,inst,' + str(node.name) + ')' }
  632. return 'RF(r,inst,' + str(node.name) + ',' + list(node.path) + ')'
  633. }
  634. list(names) {
  635. let src = '['
  636. let first = true
  637. for (n of names) {
  638. if (!first) { src = src + ',' }
  639. first = false
  640. src = src + str(n)
  641. }
  642. return src + ']'
  643. }
  644. // a JavaScript string literal — JSON's escaping is a subset of JavaScript's, so a
  645. // source text's quotes, newlines and backslashes survive into the statement unchanged
  646. str(s) {
  647. if (s == null) { return '""' }
  648. return JSON.stringify('' + s)
  649. }
  650. // ---- WHAT THE LANGUAGE SAYS ABOUT THIS FILE, read HERE and written into the code ----
  651. // The old hl:web shipped the language's answers to the browser as data: `hlJs` writes each file's
  652. // members, handlers and methods — every node of every initializer, with the names it
  653. // reads — into the module, and the client reduces that table on every boot. The answers
  654. // are facts about the source, so this file asks for them once, at compile time, and
  655. // writes the RESULT into the statements: a handler's write set stands at the listener
  656. // that needs it, a region's names at the region, the derivations as a list of what to
  657. // re-run. The module carries no table at all (WebFramework `module` drops the one the
  658. // emitter writes).
  659. //
  660. // The reflection is the framework's own analysis generation — the same `gen` the View
  661. // trees come from. Nothing starts a second one: a handle is only valid inside the
  662. // generation that made it.
  663. tableOf(gen, key) {
  664. let members = []
  665. let derivations = []
  666. let handlers = []
  667. let methods = []
  668. for (m of hlMembers(gen, key)) {
  669. let entry = { name = m.name; nodes = null; }
  670. if (m.hasValue) {
  671. let n = syntaxTree(gen, key, m.node)
  672. entry.nodes = n
  673. derivations.push({ name = m.name; site = n.site; reads = n.reads; serverSite = serverSite(n.reads); })
  674. nestedHandlers(&handlers, n)
  675. }
  676. members.push(entry)
  677. }
  678. for (h of hlEvents(gen, key).handles) {
  679. let n = syntaxTree(gen, key, h.node)
  680. handlers.push({ event = h.event; site = n.site; reads = n.reads; writes = n.writes; nested = false; })
  681. }
  682. for (mm of hlMethods(gen, key)) {
  683. if (!mm.inlineHandler) {
  684. let n = syntaxTree(gen, key, mm.node)
  685. methods.push({ name = mm.name; reads = n.reads; writes = n.writes; })
  686. }
  687. }
  688. // A SERVER REFERENCE SITE IS ONE THROUGH A LOCAL HELPER TOO (#121): an initializer
  689. // that calls a method or static of this class which calls the import still reaches
  690. // the server only, so it is never re-derived in the browser either.
  691. let post = []
  692. for (d of derivations) {
  693. post.push({ name = d.name; site = d.site; reads = d.reads; serverSite = d.serverSite || reachesServerSite(members, methods, d.reads); })
  694. }
  695. return { members = members; derivations = post; handlers = handlers; methods = methods; }
  696. }
  697. // does a read list reach an imported class THROUGH this class's own methods and statics,
  698. // transitively — the walk of `closeReads`, over the helpers a derivation calls
  699. reachesServerSite(members, methods, reads) {
  700. let queue = []
  701. if (reads != null) {
  702. for (r of reads) {
  703. if (r.kind == 'method' || (r.kind == 'member' && r.isStatic == true)) { queue.push(r.kind + ' ' + r.name) }
  704. }
  705. }
  706. let seen = {}
  707. while (queue.length > 0) {
  708. let at = queue.shift()
  709. if (seen[at] == null) {
  710. seen[at] = true
  711. let sp = at.indexOf(' ')
  712. let kind = at.slice(0, sp)
  713. let name = at.slice(sp + 1)
  714. let hop = []
  715. if (kind == 'method') { for (mm of methods) { if (mm.name == name) { hop = mm.reads } } }
  716. else { for (mb of members) { if (mb.name == name && mb.nodes != null) { hop = nodeReads(mb.nodes) } } }
  717. if (serverSite(hop)) { return true }
  718. for (r of hop) {
  719. if (r.kind == 'method' || (r.kind == 'member' && r.isStatic == true)) { queue.push(r.kind + ' ' + r.name) }
  720. }
  721. }
  722. }
  723. return false
  724. }
  725. // A NESTED `on` IS A DOM HANDLER, filed under its own site — the id the View node
  726. // carries. Its body is not the literal's syntax, so the node answers for it and the
  727. // walk stops there.
  728. nestedHandlers(&into, n) {
  729. if (n == null) { return null }
  730. if (n.tag == 'on_statement') {
  731. into.push({ event = n.event; site = n.site; reads = n.reads; writes = n.writes; nested = true; })
  732. return null
  733. }
  734. for (c of [n.value, n.list, n.body, n.condition, n.consequent, n.alternate, n.object, n.property, n.callee, n.left, n.right, n.operand]) {
  735. if (c != null) { nestedHandlers(&into, c) }
  736. }
  737. for (l of [n.entries, n.args, n.elements]) {
  738. if (l != null) { for (c of l) { nestedHandlers(&into, c) } }
  739. }
  740. return null
  741. }
  742. // the site with its file's base name: everything after the last '/'. The path part
  743. // is not "up to the first ':'" — a package key has a colon of its own
  744. // ('hl:markdown/Markdown.hl:24:3'), and that reading left a package component's
  745. // sites unshortened, so its regions found no reads and never repainted (#111)
  746. shortSite(site) {
  747. if (site == null) { return null }
  748. let cut = site.lastIndexOf('/')
  749. if (cut < 0) { return site }
  750. return site.slice(cut + 1)
  751. }
  752. // the syntax of one node, recursively — hl:core/AST's `tree`, read off the framework's
  753. // own generation instead of starting one of its own
  754. syntaxTree(gen, key, node) {
  755. let n = hlSyntax(gen, key, node)
  756. if (n == null) { return null }
  757. // A SITE IS NAMED BY THE FILE'S BASE NAME. The reflection answers with the project
  758. // key ('components/sort_list.hl:77:26'); the View tree, the emitter's own
  759. // `__derive__` branches and every site this framework writes use the base name
  760. // ('sort_list.hl:77:26'). One spelling, or a lookup by site finds nothing.
  761. let out = { tag = n.tag; site = shortSite(n.site); reads = n.reads; writes = n.writes; }
  762. if (n.tag == 'object_expression') {
  763. let kids = []
  764. for (h of n.entries) { kids.push(syntaxTree(gen, key, h)) }
  765. out.entries = kids
  766. } else if (n.tag == 'object_property') {
  767. out.key = n.key
  768. out.value = syntaxTree(gen, key, n.value)
  769. } else if (n.tag == 'view_for') {
  770. out.list = syntaxTree(gen, key, n.list)
  771. out.body = syntaxTree(gen, key, n.body)
  772. } else if (n.tag == 'view_if') {
  773. out.condition = syntaxTree(gen, key, n.condition)
  774. out.consequent = syntaxTree(gen, key, n.consequent)
  775. out.alternate = syntaxTree(gen, key, n.alternate)
  776. } else if (n.tag == 'on_statement') {
  777. out.event = n.event
  778. } else if (n.tag == 'member_expression') {
  779. out.object = syntaxTree(gen, key, n.object)
  780. out.property = syntaxTree(gen, key, n.property)
  781. } else if (n.tag == 'call_expression') {
  782. out.callee = syntaxTree(gen, key, n.callee)
  783. let args = []
  784. for (h of n.args) { args.push(syntaxTree(gen, key, h)) }
  785. out.args = args
  786. } else if (n.tag == 'binary_expression') {
  787. out.left = syntaxTree(gen, key, n.left)
  788. out.right = syntaxTree(gen, key, n.right)
  789. } else if (n.tag == 'unary_expression') {
  790. out.operand = syntaxTree(gen, key, n.operand)
  791. } else if (n.tag == 'conditional_expression') {
  792. out.condition = syntaxTree(gen, key, n.condition)
  793. out.consequent = syntaxTree(gen, key, n.consequent)
  794. out.alternate = syntaxTree(gen, key, n.alternate)
  795. } else if (n.tag == 'array_expression') {
  796. let els = []
  797. for (h of n.elements) { els.push(syntaxTree(gen, key, h)) }
  798. out.elements = els
  799. }
  800. return out
  801. }
  802. // ---- the reductions the browser used to make on every boot --------------------------
  803. // A `for`'s names are what its list reads, an `if`'s what its condition reads — filed
  804. // under the region's own site.
  805. regionIndex(t) {
  806. let idx = {}
  807. for (m of t.members) { if (m.nodes != null) { indexRegions(&idx, m.nodes) } }
  808. return idx
  809. }
  810. indexRegions(&idx, n) {
  811. if (n == null) { return null }
  812. if (n.tag == 'view_for') {
  813. idx[n.site] = memberNames(nodeReads(n.list))
  814. indexRegions(&idx, n.body)
  815. return null
  816. }
  817. if (n.tag == 'view_if') {
  818. idx[n.site] = memberNames(nodeReads(n.condition))
  819. indexRegions(&idx, n.consequent)
  820. indexRegions(&idx, n.alternate)
  821. return null
  822. }
  823. if (n.tag == 'on_statement') { return null }
  824. for (c of [n.value, n.list, n.body, n.condition, n.consequent, n.alternate, n.object, n.property, n.callee, n.left, n.right, n.operand]) {
  825. if (c != null) { indexRegions(&idx, c) }
  826. }
  827. for (l of [n.entries, n.args, n.elements]) {
  828. if (l != null) { for (c of l) { indexRegions(&idx, c) } }
  829. }
  830. return null
  831. }
  832. // the member reads of a read list — the language resolved every name, so this is a
  833. // filter and not a second resolution
  834. memberNames(reads) {
  835. let out = []
  836. if (reads == null) { return out }
  837. for (r of reads) {
  838. if (r.kind == 'member' && r.isStatic != true && !out.includes(r.name)) { out.push(r.name) }
  839. }
  840. return out
  841. }
  842. nodeReads(n) {
  843. if (n == null) { return [] }
  844. if (n.reads != null) { return n.reads }
  845. let out = []
  846. for (c of [n.value, n.list, n.body, n.condition, n.consequent, n.alternate, n.object, n.property, n.callee, n.left, n.right, n.operand]) {
  847. if (c != null) { for (r of nodeReads(c)) { out.push(r) } }
  848. }
  849. for (l of [n.entries, n.args, n.elements]) {
  850. if (l != null) { for (c of l) { for (r of nodeReads(c)) { out.push(r) } } }
  851. }
  852. return out
  853. }
  854. // A ROUTINE'S WRITES, PLUS THE WRITES OF EVERYTHING IT REACHES — the method it calls
  855. // and the handler it emits to, transitively. Both are READS the language resolved, so
  856. // this is a walk of its answer and never a guess.
  857. closeWrites(t, writes, reads) {
  858. let out = memberNames(writes)
  859. let queue = []
  860. reached(&queue, reads)
  861. let seen = {}
  862. while (queue.length > 0) {
  863. let at = queue.shift()
  864. if (seen[at] == null) {
  865. seen[at] = true
  866. let sp = at.indexOf(' ')
  867. let kind = at.slice(0, sp)
  868. let name = at.slice(sp + 1)
  869. for (mm of t.methods) {
  870. if (kind == 'method' && mm.name == name) {
  871. for (w of memberNames(mm.writes)) { if (!out.includes(w)) { out.push(w) } }
  872. reached(&queue, mm.reads)
  873. }
  874. }
  875. for (h of t.handlers) {
  876. if (kind == 'handler' && !h.nested && h.event == name) {
  877. for (w of memberNames(h.writes)) { if (!out.includes(w)) { out.push(w) } }
  878. reached(&queue, h.reads)
  879. }
  880. }
  881. for (mb of t.members) {
  882. if (kind == 'member' && mb.name == name && mb.nodes != null) {
  883. for (w of memberNames(mb.nodes.writes)) { if (!out.includes(w)) { out.push(w) } }
  884. reached(&queue, nodeReads(mb.nodes))
  885. }
  886. }
  887. }
  888. }
  889. return out
  890. }
  891. // the mirror: a handler's reads plus the reads of everything it reaches — the
  892. // candidates for a routine a host handed down, whose writes only the host's table names
  893. closeReads(t, reads) {
  894. let out = memberNames(reads)
  895. let queue = []
  896. reached(&queue, reads)
  897. let seen = {}
  898. while (queue.length > 0) {
  899. let at = queue.shift()
  900. if (seen[at] == null) {
  901. seen[at] = true
  902. let sp = at.indexOf(' ')
  903. let kind = at.slice(0, sp)
  904. let name = at.slice(sp + 1)
  905. for (mm of t.methods) {
  906. if (kind == 'method' && mm.name == name) {
  907. for (r of memberNames(mm.reads)) { if (!out.includes(r)) { out.push(r) } }
  908. reached(&queue, mm.reads)
  909. }
  910. }
  911. for (h of t.handlers) {
  912. if (kind == 'handler' && !h.nested && h.event == name) {
  913. for (r of memberNames(h.reads)) { if (!out.includes(r)) { out.push(r) } }
  914. reached(&queue, h.reads)
  915. }
  916. }
  917. for (mb of t.members) {
  918. if (kind == 'member' && mb.name == name && mb.nodes != null) {
  919. for (r of memberNames(nodeReads(mb.nodes))) { if (!out.includes(r)) { out.push(r) } }
  920. reached(&queue, nodeReads(mb.nodes))
  921. }
  922. }
  923. }
  924. }
  925. return out
  926. }
  927. reached(&queue, reads) {
  928. if (reads == null) { return null }
  929. for (r of reads) {
  930. if (r.kind == 'method' || r.kind == 'handler' || (r.kind == 'member' && r.isStatic != true)) { queue.push(r.kind + ' ' + r.name) }
  931. }
  932. return null
  933. }
  934. // ---- THE SERVER RENDER, COMPILED --------------------------------------------------
  935. // The old hl:web rendered a page by WALKING the View tree per request: for every node it asks
  936. // what kind it is, for every element it builds the attribute string, and it decides the
  937. // indentation of every line again, on every request, for every one of the 121 mounts a
  938. // page may hold. Every one of those decisions is a fact about the View.
  939. //
  940. // So a component's render is compiled ONCE into a list of STEPS — constant text, and a
  941. // read with its own closure — and a request is a concatenation. The structure (tags,
  942. // static attributes, the readable form's line breaks, which element is a block) is
  943. // decided at compile time; only the values are asked for per request.
  944. //
  945. // KEYED BY THE INDENT IT IS RENDERED AT, because that is the only thing about a
  946. // component's HTML that its caller decides: the shell renders at one tab, the page at
  947. // the depth the slot stands, a fill compactly (null). An app has a handful of those.
  948. serverSteps(key, nodes, indent, classes, slotted) {
  949. let ck = key + '|' + (indent == null ? '~' : indent) + '|' + joinList(classes) + '|' + (slotted ? '1' : '0')
  950. if (steps[ck] == null) {
  951. steps[ck] = blockSteps(classes == null || classes.length == 0 ? nodes : v.withRootClasses(nodes, classes), indent, slotted)
  952. }
  953. return steps[ck]
  954. }
  955. // A `slot` THE HOST FILLED COUNTS AS CONTENT, and an empty one does not — the one
  956. // thing about a component's shape its caller decides, so it is part of the key.
  957. staticVoid = [ 'area' 'base' 'br' 'col' 'embed' 'hr' 'img' 'input' 'link' 'meta' 'source' 'track' 'wbr' ]
  958. staticVerbatim = [ 'textarea' 'pre' 'script' 'style' ]
  959. blocky(n, slotted) {
  960. if (staticVerbatim.includes(n.tag)) { return false }
  961. if (n.children.length == 0) { return false }
  962. for (c of n.children) {
  963. if (c.k == 'text' || c.k == 'field' || c.k == 'expr') { return false }
  964. if (c.k == 'member' && !(c.name == 'slot' && slotted)) { return false }
  965. }
  966. return true
  967. }
  968. steps = {}
  969. v = new HlwView
  970. joinList(l) {
  971. if (l == null) { return '' }
  972. let out = ''
  973. for (c of l) { out = out + ',' + c }
  974. return out
  975. }
  976. // `render(nodes, …, indent)`: the readable form puts each element on its own line at
  977. // `indent`, the compact one writes them end to end.
  978. blockSteps(nodes, indent, slotted) {
  979. let out = []
  980. for (n of nodes) {
  981. if (indent != null) {
  982. if (n.k == 'el') { push(&out, { k = 's'; v = newline + indent; }) nodeSteps(&out, n, indent, slotted) }
  983. else if (n.k == 'component') { nodeSteps(&out, n, indent, slotted) }
  984. else if (n.k == 'for') { forSteps(&out, n, indent, slotted) }
  985. else if (n.k == 'if') { ifSteps(&out, n, indent, slotted) }
  986. else if (n.k == 'member' && n.name == 'slot') { push(&out, { k = 'slotline'; v = newline + indent; }) }
  987. else if (n.k != 'on') { nodeSteps(&out, n, indent, slotted) }
  988. } else {
  989. nodeSteps(&out, n, null, slotted)
  990. }
  991. }
  992. return out
  993. }
  994. forSteps(&out, n, indent, slotted) {
  995. out.push({ k = 'for'; row = n.row; read = readFn(n.list); body = blockSteps(n.body, indent, slotted); })
  996. return null
  997. }
  998. ifSteps(&out, n, indent, slotted) {
  999. out.push({ k = 'if'; read = readFn(n.cond); then = blockSteps(n.then, indent, slotted); other = blockSteps(n.other, indent, slotted); })
  1000. return null
  1001. }
  1002. // one node's steps — `html(node, …)`, decided once
  1003. nodeSteps(&out, n, indent, slotted) {
  1004. if (n.k == 'text') { push(&out, { k = 's'; v = v.escape(n.text); }) return null }
  1005. if (n.k == 'on') { return null }
  1006. if (n.k == 'member' && n.name == 'slot') { out.push({ k = 'slot'; }) return null }
  1007. if (n.k == 'member' || n.k == 'field' || n.k == 'expr') { out.push({ k = 'r'; read = readFn(n); }) return null }
  1008. if (n.k == 'for') { forSteps(&out, n, indent, slotted) return null }
  1009. if (n.k == 'if') { ifSteps(&out, n, indent, slotted) return null }
  1010. if (n.k == 'component') {
  1011. out.push({ k = 'kid'; path = n.path; cls = n.cls; key = n.key; classes = n.classes; indent = indent;
  1012. fill = (n.fill == null || n.fill.length == 0) ? null : blockSteps(n.fill, null, slotted); })
  1013. return null
  1014. }
  1015. if (n.k == 'el') { elSteps(&out, n, indent, slotted) return null }
  1016. push(&out, { k = 's'; v = '<!-- ' + n.tag + ' not rendered yet -->'; })
  1017. return null
  1018. }
  1019. elSteps(&out, n, indent, slotted) {
  1020. let attrs = []
  1021. let valueRead = null // a textarea's value is its content
  1022. let selRead = null // a select's value selects an option
  1023. for (a of n.attrs) {
  1024. if (n.tag == 'textarea' && a.name == 'value') { valueRead = attrRead(a) }
  1025. else if (n.tag == 'select' && a.name == 'value') { selRead = attrRead(a) }
  1026. // a bound BOOLEAN attribute is its presence (ticket #33): ` checked=""` or nothing
  1027. else if ((a.member != null || a.ref != null) && v.isBoolAttr(a.name)) { attrs.push({ k = 'b'; name = a.name; read = attrRead(a); }) }
  1028. else if (a.member != null || a.ref != null) {
  1029. push(&attrs, { k = 's'; v = ' ' + a.name + '="'; })
  1030. attrs.push({ k = 'r'; read = attrRead(a); })
  1031. push(&attrs, { k = 's'; v = v.extraOf(a) + '"'; })
  1032. } else {
  1033. push(&attrs, { k = 's'; v = ' ' + a.name + '="' + v.escape(a.text) + '"'; })
  1034. }
  1035. }
  1036. if (v.boundValue(n)) { push(&attrs, { k = 's'; v = ' autocomplete="off"'; }) }
  1037. // the children, in the form this element takes: a block puts them one per line
  1038. let kids = []
  1039. if (indent != null && blocky(n, slotted)) {
  1040. kids = blockSteps(n.children, indent + tab, slotted)
  1041. push(&kids, { k = 's'; v = newline + indent; })
  1042. } else {
  1043. kids = blockSteps(n.children, null, slotted)
  1044. }
  1045. if (valueRead != null) { kids = [{ k = 'r'; read = valueRead; }] }
  1046. // AN OPTION IS THE ONE ELEMENT WHOSE OWN TAG DEPENDS ON THE VALUE ABOVE IT: it
  1047. // carries `selected` when its value is the select's. Everything else is settled.
  1048. if (n.tag == 'option') {
  1049. out.push({ k = 'opt'; attrs = attrs; body = kids; ov = optionRead(n); })
  1050. return null
  1051. }
  1052. push(&out, { k = 's'; v = '<' + n.tag; })
  1053. for (a of attrs) { push(&out, a) }
  1054. if (staticVoid.includes(n.tag)) { push(&out, { k = 's'; v = '>'; }) return null }
  1055. push(&out, { k = 's'; v = '>'; })
  1056. // A SELECT HANDS ITS VALUE TO ITS OPTIONS, however deep they stand: its children
  1057. // run under it, and it is the only element that changes anything for them.
  1058. if (n.tag == 'select') { out.push({ k = 'sel'; read = selRead; body = kids; }) }
  1059. else { for (kk of kids) { push(&out, kk) } }
  1060. push(&out, { k = 's'; v = '</' + n.tag + '>'; })
  1061. return null
  1062. }
  1063. // CONSTANT TEXT MERGES. Two literal steps in a row are one string decided at compile
  1064. // time — which is what makes a request a concatenation of a handful of pieces instead
  1065. // of one per node.
  1066. push(&out, step) {
  1067. if (step.k == 's' && out.length > 0 && out[out.length - 1].k == 's') {
  1068. let last = out[out.length - 1]
  1069. last.v = last.v + step.v
  1070. out[out.length - 1] = last
  1071. return null
  1072. }
  1073. out.push(step)
  1074. return null
  1075. }
  1076. // ---- the reads, each with its own closure ------------------------------------------
  1077. // `view.value`'s rule, split once: a `for` row variable in scope wins over a member of
  1078. // the same name, and a field path walks into it. The closure holds the name — there is
  1079. // no node to look at per request.
  1080. readFn(node) {
  1081. if (node == null) { return (inst, rows) => { return null } }
  1082. if (node.k == 'text') { let t = v.refValue(node) return (inst, rows) => { return t } }
  1083. if (node.k == 'expr') { let x = node.x return (inst, rows) => { return v.evalExpr(x, inst, rows) } }
  1084. let name = node.name
  1085. if (node.k != 'field') {
  1086. return (inst, rows) => { return rows[name] != null ? rows[name] : inst[name] }
  1087. }
  1088. let path = node.path
  1089. return (inst, rows) => {
  1090. let val = rows[name] != null ? rows[name] : inst[name]
  1091. for (f of path) {
  1092. if (val == null) { return null }
  1093. val = val[f]
  1094. }
  1095. return val
  1096. }
  1097. }
  1098. attrRead(a) {
  1099. if (a.member != null) { return readFn({ k = 'member'; name = a.member; }) }
  1100. if (a.ref != null) { return readFn(a.ref) }
  1101. let t = a.text
  1102. return (inst, rows) => { return t }
  1103. }
  1104. // an option's own value: its `value` attribute, or null when it has none (the browser
  1105. // then reports its text, and the run compares against what it rendered)
  1106. optionRead(n) {
  1107. for (a of n.attrs) {
  1108. if (a.name == 'value') { return attrRead(a) }
  1109. }
  1110. return null
  1111. }
  1112. // ---- the run: a concatenation ------------------------------------------------------
  1113. // EVERY REGION IS WRITTEN BETWEEN TWO MARKS (tickets #103, #104): an `if` around the
  1114. // branch that stands, a `for` around its rows and each row around its own nodes. The
  1115. // client claims them as they are and builds the same ones, and a region's nodes are
  1116. // exactly what stands between its two marks — nothing it holds has to be remembered
  1117. // node by node, and text beside a region can never run into the region's text.
  1118. markOpen = '<!--[-->'
  1119. markClose = '<!--]-->'
  1120. // THE PIECES ARE JOINED ONCE, AT THE END (ticket #127). `out = out + piece` copied
  1121. // the whole page so far for every piece: a 3.5 MB page of 2000 rows allocated 2.3 GB
  1122. // in growing copies, 7 GB per render all told — 12 s a load once the collector ran
  1123. // by bytes (#126), where the joined pieces take 2.5 s.
  1124. runSteps(list, &inst, &rows, &ctx) {
  1125. let out = []
  1126. for (s of list) {
  1127. if (s.k == 's') { out.push(s.v) }
  1128. else if (s.k == 'r') { let f = s.read out.push(v.escape(f(&inst, &rows))) }
  1129. else if (s.k == 'b') { let f = s.read if (v.boolOn(f(&inst, &rows))) { out.push(' ' + s.name + '=""') } }
  1130. else if (s.k == 'slot') { if (ctx.slot != null) { out.push(ctx.slot) } }
  1131. else if (s.k == 'slotline') { if (ctx.slot != null) { out.push(s.v + ctx.slot) } }
  1132. else if (s.k == 'for') {
  1133. let f = s.read
  1134. let list2 = f(&inst, &rows)
  1135. out.push(markOpen)
  1136. if (list2 != null) {
  1137. let ri = 0
  1138. for (entry of list2) {
  1139. let inner = rows + {}
  1140. inner[s.row] = entry
  1141. let rc = v.rowCtx(&ctx, &entry, ri)
  1142. out.push(markOpen + runSteps(s.body, &inst, &inner, &rc) + markClose)
  1143. ri = ri + 1
  1144. }
  1145. }
  1146. out.push(markClose)
  1147. }
  1148. else if (s.k == 'if') {
  1149. let f = s.read
  1150. if (f(&inst, &rows)) { out.push(markOpen + runSteps(s.then, &inst, &rows, &ctx) + markClose) }
  1151. else { out.push(markOpen + runSteps(s.other, &inst, &rows, &ctx) + markClose) }
  1152. }
  1153. else if (s.k == 'opt') {
  1154. let head = runSteps(s.attrs, &inst, &rows, &ctx)
  1155. let body = runSteps(s.body, &inst, &rows, &ctx)
  1156. let mark = ''
  1157. if (ctx.sel != null) {
  1158. let ov = body
  1159. if (s.ov != null) { let f = s.ov ov = '' + f(&inst, &rows) }
  1160. if (ov == ctx.sel) { mark = ' selected' }
  1161. }
  1162. out.push('<option' + head + mark + '>' + body + '</option>')
  1163. }
  1164. else if (s.k == 'sel') {
  1165. let f = s.read
  1166. let inner = ctx + {}
  1167. inner.sel = f == null ? null : '' + f(&inst, &rows)
  1168. out.push(runSteps(s.body, &inst, &rows, &inner))
  1169. }
  1170. else if (s.k == 'kid') {
  1171. let kid = ctx.kids[v.kidKeyIn(s.path, ctx)]
  1172. if (kid == null) { out.push('<!-- ' + s.cls + ' not mounted -->') }
  1173. else {
  1174. let fillText = s.fill == null ? null : runSteps(s.fill, &inst, &rows, &ctx)
  1175. let kidCtx = { slot = fillText; kids = kid.kids; }
  1176. let kidInst = kid.page
  1177. let empty = {}
  1178. out.push(runSteps(serverSteps(s.key, kid.view, s.indent, s.classes, fillText != null), &kidInst, &empty, &kidCtx))
  1179. }
  1180. }
  1181. }
  1182. return out.join('')
  1183. }

Branches

Latest commits

  • 2881119fcalendar mission 001 (4/4): code order — README layout + same-output test, STATUS, LOG, report; tests/letcount.py (sub-folders), tests/realdata-baseline.mjs, tests/realdata-compare.pymre
  • 3b2a4cd0calendar mission 001 (3/4): code order — let only where reassigned (147 dropped incl. components/month-view; 110 left: 67 reassigned, 43 loop-bound); gates 78/0 (3 of 4 runs; 1 known 'next month' flake) + 18/0, live-data run = step 2mre
  • f5ce6b1dcalendar mission 001 (2/4): code order — topics, map, thin faces: lib/util.hl, lib/events(-helpers).hl (+calendarView/settingsView/soonOf), lib/settings.hl, lib/users.hl (+userOfLoginCode, tagOf), lib/api(-helpers).hl; project.hl = map; login route takes &req/&sessions (failed-login reason now kept); gates 78/0 + 18/0mre
  • c6fbd011calendar mission 001 (1/4): code order — files moved: lib/events.hl, lib/users.hl, components/styles.hl (imports only); gates 78/0 + 18/0, live-data run identicalmre
  • d6c59290calendar: Hybriel master 06617221 (plugin allocators 3a781359 + 413f60e4, mpackdb 2cb7ae5e, http1 773de63e); gates 78/0 + 18/0mre
  • 7bd0337ccalendar: Hybriel master 190aa11d (fc838894 GC correctness, #126 closure scopes, #127); gates 78/0 + 18/0mre
  • ff41310ccalendar: Hybriel master 8efba065 (#126 memory, #48 lambda copy; audit: no & needed)mre
  • 14ba08c7antcolony#40: mission references point to the moved missionsmre
  • 99c73346antcolony#40: history (LOG.md), worker briefs (missions/) and reports moved here from antcolony, numbered per project; old numbers in antcolony docs/mission-map.mdmre
  • 76edaa62calendar: Hybriel master ff51cf46 (re-vendor round, static workaround removed)mre
  • 90a3fc2cdeploy.sh: back up live storage/.sessions/.env before every deploy (newest 5 kept)mre
  • 6722b72ddeploy.sh: never send .git or .gitignore to Byrodinmre
  • be099807State of 2026-09-27, before the move to gitoriamre