@knowvah/dot-engine 2.12.1 → 2.12.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/dist/api/builder.d.ts +7 -1
  2. package/dist/api/builder.d.ts.map +1 -1
  3. package/dist/api.js +14 -7
  4. package/dist/api.js.map +2 -2
  5. package/dist/common/edge-label-init.d.ts +26 -1
  6. package/dist/common/edge-label-init.d.ts.map +1 -1
  7. package/dist/common/nodeinit.d.ts +16 -2
  8. package/dist/common/nodeinit.d.ts.map +1 -1
  9. package/dist/common/splines-path-begin.d.ts.map +1 -1
  10. package/dist/common/splines-path-end.d.ts.map +1 -1
  11. package/dist/gvc/context.d.ts +8 -0
  12. package/dist/gvc/context.d.ts.map +1 -1
  13. package/dist/gvc/emit-gates.d.ts +5 -10
  14. package/dist/gvc/emit-gates.d.ts.map +1 -1
  15. package/dist/gvc/emit-xdot.d.ts +7 -6
  16. package/dist/gvc/emit-xdot.d.ts.map +1 -1
  17. package/dist/gvc/job.d.ts +5 -2
  18. package/dist/gvc/job.d.ts.map +1 -1
  19. package/dist/gvc/viewport.d.ts +10 -5
  20. package/dist/gvc/viewport.d.ts.map +1 -1
  21. package/dist/index.js +361 -194
  22. package/dist/index.js.map +4 -4
  23. package/dist/layout/dot/edge-route.d.ts +7 -3
  24. package/dist/layout/dot/edge-route.d.ts.map +1 -1
  25. package/dist/layout/dot/fastgr.d.ts +5 -3
  26. package/dist/layout/dot/fastgr.d.ts.map +1 -1
  27. package/dist/layout/dot/flat-adj-record.d.ts +22 -0
  28. package/dist/layout/dot/flat-adj-record.d.ts.map +1 -0
  29. package/dist/layout/dot/init.d.ts +49 -9
  30. package/dist/layout/dot/init.d.ts.map +1 -1
  31. package/dist/layout/dot/mincross-build.d.ts +6 -0
  32. package/dist/layout/dot/mincross-build.d.ts.map +1 -1
  33. package/dist/layout/dot/position-aux.d.ts +7 -1
  34. package/dist/layout/dot/position-aux.d.ts.map +1 -1
  35. package/dist/layout/dot/splines-clone.d.ts +2 -1
  36. package/dist/layout/dot/splines-clone.d.ts.map +1 -1
  37. package/dist/layout/dot/splines-flat-labeled.d.ts.map +1 -1
  38. package/dist/layout/dot/splines-flat.d.ts +18 -0
  39. package/dist/layout/dot/splines-flat.d.ts.map +1 -1
  40. package/dist/layout/dot/splines-groups.d.ts.map +1 -1
  41. package/dist/layout/fdp/ports.d.ts.map +1 -1
  42. package/dist/layout/neato/conjgrad-mkernel.d.ts.map +1 -1
  43. package/dist/layout/neato/sgd.d.ts.map +1 -1
  44. package/dist/model/cgraph-ops.d.ts +10 -2
  45. package/dist/model/cgraph-ops.d.ts.map +1 -1
  46. package/dist/model/edge.d.ts +7 -2
  47. package/dist/model/edge.d.ts.map +1 -1
  48. package/dist/model/edgeInfo.d.ts +17 -2
  49. package/dist/model/edgeInfo.d.ts.map +1 -1
  50. package/dist/model/graph.d.ts +4 -3
  51. package/dist/model/graph.d.ts.map +1 -1
  52. package/dist/model/lazy-attrs.d.ts.map +1 -1
  53. package/dist/parser/builder.d.ts.map +1 -1
  54. package/dist/render/dot/agwrite.d.ts +5 -1
  55. package/dist/render/dot/agwrite.d.ts.map +1 -1
  56. package/dist/render/dot/attrs.d.ts +15 -4
  57. package/dist/render/dot/attrs.d.ts.map +1 -1
  58. package/dist/render/dot/write-back.d.ts +14 -0
  59. package/dist/render/dot/write-back.d.ts.map +1 -1
  60. package/dist/render/dot/xdot-ops.d.ts +20 -29
  61. package/dist/render/dot/xdot-ops.d.ts.map +1 -1
  62. package/dist/render/dot.d.ts +4 -2
  63. package/dist/render/dot.d.ts.map +1 -1
  64. package/dist/render/json-cluster-edge.d.ts +17 -4
  65. package/dist/render/json-cluster-edge.d.ts.map +1 -1
  66. package/dist/render/json-nonfinite.d.ts +17 -0
  67. package/dist/render/json-nonfinite.d.ts.map +1 -0
  68. package/dist/render/json.d.ts +4 -0
  69. package/dist/render/json.d.ts.map +1 -1
  70. package/dist/render/map.d.ts +3 -0
  71. package/dist/render/map.d.ts.map +1 -1
  72. package/dist/render/svg-graph.d.ts.map +1 -1
  73. package/dist/render/svg-id.d.ts +10 -1
  74. package/dist/render/svg-id.d.ts.map +1 -1
  75. package/dist/render/svg.d.ts +3 -1
  76. package/dist/render/svg.d.ts.map +1 -1
  77. package/dist/render.js +360 -193
  78. package/dist/render.js.map +4 -4
  79. package/dist/util/bsd-qsort.d.ts.map +1 -1
  80. package/dist/xdot/parse.d.ts.map +1 -1
  81. package/dist/xdot/strtod.d.ts +23 -0
  82. package/dist/xdot/strtod.d.ts.map +1 -0
  83. package/package.json +1 -1
  84. package/src/api/builder.ts +8 -2
  85. package/src/common/edge-label-init.ts +43 -17
  86. package/src/common/nodeinit.ts +28 -8
  87. package/src/common/splines-path-begin.ts +4 -3
  88. package/src/common/splines-path-end.ts +4 -3
  89. package/src/gvc/context.ts +8 -0
  90. package/src/gvc/device.ts +6 -6
  91. package/src/gvc/emit-gates.ts +6 -15
  92. package/src/gvc/emit-xdot.ts +10 -11
  93. package/src/gvc/job.ts +5 -2
  94. package/src/gvc/viewport.ts +13 -7
  95. package/src/layout/dot/__fixtures__/flat-adj-aux-syms.native-16.1.json +1210 -0
  96. package/src/layout/dot/edge-route.ts +44 -49
  97. package/src/layout/dot/fastgr.ts +9 -3
  98. package/src/layout/dot/flat-adj-record.ts +68 -0
  99. package/src/layout/dot/init.ts +59 -13
  100. package/src/layout/dot/mincross-build.ts +14 -1
  101. package/src/layout/dot/position-aux.ts +10 -3
  102. package/src/layout/dot/splines-clone.ts +8 -2
  103. package/src/layout/dot/splines-flat-labeled.ts +3 -2
  104. package/src/layout/dot/splines-flat.ts +9 -19
  105. package/src/layout/dot/splines-groups.ts +5 -3
  106. package/src/layout/fdp/ports.ts +6 -2
  107. package/src/layout/neato/conjgrad-mkernel.ts +6 -2
  108. package/src/layout/neato/sgd.ts +2 -1
  109. package/src/model/cgraph-ops.ts +4 -3
  110. package/src/model/edge.ts +11 -4
  111. package/src/model/edgeInfo.ts +18 -2
  112. package/src/model/graph.ts +4 -3
  113. package/src/model/lazy-attrs.ts +3 -1
  114. package/src/parser/builder.ts +12 -3
  115. package/src/render/dot/agwrite.ts +10 -3
  116. package/src/render/dot/attrs.ts +18 -7
  117. package/src/render/dot/write-back.ts +27 -3
  118. package/src/render/dot/xdot-ops.ts +25 -56
  119. package/src/render/dot.ts +7 -5
  120. package/src/render/json-cluster-edge.ts +42 -5
  121. package/src/render/json-nonfinite.ts +51 -0
  122. package/src/render/json.ts +23 -26
  123. package/src/render/map.ts +3 -0
  124. package/src/render/svg-graph.ts +3 -15
  125. package/src/render/svg-id.ts +11 -2
  126. package/src/render/svg.ts +4 -1
  127. package/src/util/bsd-qsort.ts +2 -1
  128. package/src/xdot/parse.ts +9 -19
  129. package/src/xdot/strtod.ts +167 -0
@@ -28,6 +28,8 @@
28
28
  * conformance bar is the semantic `compare-json` comparator (±0.01, colors /
29
29
  * fonts canonicalized). `stoj`/`ind` are retained as the C-faithful string
30
30
  * helpers referenced by the unit tests.
31
+ * A non-finite draw coordinate prints as C's `%.03f` token (`inf`, `-inf`,
32
+ * `nan`), so such a document is not valid JSON, exactly as native's is not.
31
33
  *
32
34
  * @see plugin/core/gvrender_core_json.c
33
35
  */
@@ -41,15 +43,16 @@ import type { RendererPlugin } from '../gvc/context.js';
41
43
  import type { RenderJob } from '../gvc/job.js';
42
44
  import type { XdotOp, XdotColor } from '../xdot/types.js';
43
45
  import type { TextlabelT, FieldT } from '../common/types.js';
44
- import { printNum, gfmt5, XdotRenderer, type XdotDraws } from './dot.js';
45
- import { attachAttrs } from './dot/write-back.js';
46
- import { attachBeforeWriteWithClusterEdges as attachFirst, clusterNodeGid, jsonNodes } from './json-cluster-edge.js';
46
+ import { gfmt5, XdotRenderer, type XdotDraws } from './dot.js';
47
+ import { attachAttrs, nodeLayoutAttrs } from './dot/write-back.js';
48
+ import { attachBeforeWriteWithClusterEdges as attachFirst, jsonNodes, labelSubgs, lookupCluster } from './json-cluster-edge.js';
47
49
  import { attrsWithoutLayoutBb } from '../gvc/layout-bb.js';
48
50
  import { CHAR_LATIN1 } from '../common/graph-init.js';
49
51
  import { parse } from '../parser/index.js';
50
52
  import { render as deviceRender } from '../gvc/device.js';
51
53
  import { createDefaultContext } from '../gvc/default-context.js';
52
54
  import { parseXDot } from '../xdot/index.js';
55
+ import { stringifyJsonTree } from './json-nonfinite.js';
53
56
  import { isHtmlValue, htmlValueContent } from '../common/html-string.js';
54
57
 
55
58
  // ---------------------------------------------------------------------------
@@ -219,10 +222,10 @@ function canonicalRootEdges(g: Graph): Array<{ e: Edge; key: string }> {
219
222
  const counter = new Map<string, number>();
220
223
  for (const [, n] of g.nodes) {
221
224
  for (const e of n.outEdges(g)) {
222
- const base = e.tail.name + '' + e.head.name;
225
+ const base = e.tail.name + '\0' + e.head.name;
223
226
  const occ = counter.get(base) ?? 0;
224
227
  counter.set(base, occ + 1);
225
- out.push({ e, key: base + '' + occ });
228
+ out.push({ e, key: base + '\0' + occ });
226
229
  }
227
230
  }
228
231
  return out;
@@ -310,7 +313,7 @@ interface BuildCtx {
310
313
  subgGid: Map<Graph, number>;
311
314
  nodeGid: Map<Node, number>;
312
315
  edgeGid: Map<Edge, number>;
313
- /** All subgraphs in DFS preorder (the flat top-level "objects" ordering). */
316
+ /** The subgraphs below the rendered graph in DFS preorder (the flat top-level "objects" ordering). */
314
317
  dfsSubs: Graph[];
315
318
  /** True once any edge (or edge default) declares `label`: cgraph then carries
316
319
  * a global `label` edge symbol, and write_attrs emits `label` (its value or
@@ -358,26 +361,19 @@ function isEdgeLabelDeclared(g: Graph): boolean {
358
361
  return walk(g);
359
362
  }
360
363
 
361
- /** DFS preorder over the subgraph tree. @see label_subgs recursion order */
362
- function dfsSubgraphs(g: Graph, out: Graph[]): void {
363
- for (const [, sg] of g.subgraphs) {
364
- out.push(sg);
365
- dfsSubgraphs(sg, out);
366
- }
367
- }
368
-
369
364
  /** Assign every object its `_gvid`, mirroring write_graph's top-level pass:
370
365
  * subgraphs DFS-preorder 0..sgcnt-1, then nodes sgcnt.., then edges 0.. in
371
366
  * agfstnode/agfstout order. @see plugin/core/gvrender_core_json.c:write_graph */
372
367
  function assignIds(g: Graph, doXDot: boolean, draws?: DrawLookup): BuildCtx {
373
368
  const dfsSubs: Graph[] = [];
374
- dfsSubgraphs(g, dfsSubs);
369
+ const clusters = new Map<string, number>();
370
+ const sgcnt = labelSubgs(g, 0, clusters, dfsSubs);
375
371
  const subgGid = new Map<Graph, number>();
376
372
  dfsSubs.forEach((sg, i) => subgGid.set(sg, i));
377
- const sgcnt = dfsSubs.length;
373
+ if (dfsSubs[0] === g) dfsSubs.shift(); // a subgraph render: label_subgs numbers g, write_subgs lists below it
378
374
  const nodeGid = new Map<Node, number>();
379
375
  let ncnt = 0;
380
- for (const [, n] of g.nodes) nodeGid.set(n, n.info.clustnode ? clusterNodeGid(n, dfsSubs) : sgcnt + ncnt++);
376
+ for (const [, n] of g.nodes) nodeGid.set(n, n.info.clustnode ? lookupCluster(clusters, n.name) : sgcnt + ncnt++);
381
377
  const edgeGid = new Map<Edge, number>();
382
378
  let ecnt = 0;
383
379
  for (const { e } of canonicalRootEdges(g)) edgeGid.set(e, ecnt++);
@@ -397,9 +393,9 @@ function assignIds(g: Graph, doXDot: boolean, draws?: DrawLookup): BuildCtx {
397
393
  * Emit an object's attributes into `o`, mirroring C's write_attrs: `agxget`
398
394
  * returns HTML-string content with the marker stripped, empty non-`label`
399
395
  * values are skipped, and xdot draw attrs are re-serialized as op arrays.
400
- * `base` carries user/inherited attrs; `overlay` (from the xdot re-render)
401
- * supplies the post-layout `pos`/`width`/`height`/`bb`/draw strings and wins
402
- * on conflict.
396
+ * `base` is the object's own attrs: user/inherited values and the draw strings the input or an
397
+ * earlier render stored, which an object this render does not draw prints as agxget would.
398
+ * `overlay` (the xdot re-render: `pos`/`width`/`height`/`bb`/draw strings) wins on conflict.
403
399
  */
404
400
  function emitAttrs(
405
401
  o: JObj,
@@ -522,11 +518,10 @@ function buildNodeObject(n: Node, ctx: BuildCtx): JObj {
522
518
  const eff = nodeEffectiveAttrs(n);
523
519
  const xd = ctx.draws?.node.get(n.name);
524
520
  if (xd === undefined) {
525
- // Fallback (json0 / hand-built graph): synthesize the layout attrs the
526
- // xdot render would otherwise supply, from the laid-out node.
527
- eff.set('pos', printNum(n.info.coord.x) + ',' + printNum(n.info.coord.y));
528
- eff.set('width', printNum(n.info.width));
529
- eff.set('height', printNum(n.info.height));
521
+ // Fallback (json0 / hand-built graph): no xdot render supplies the layout
522
+ // attrs, so take the strings attach_attrs writes (output.c:296-309).
523
+ const layout = nodeLayoutAttrs(n);
524
+ eff.set('pos', layout.pos).set('width', layout.width).set('height', layout.height);
530
525
  }
531
526
  emitAttrs(o, eff, xd, ctx);
532
527
  attachNodeRects(o, n);
@@ -653,13 +648,15 @@ function latin1Reencode(s: string): string {
653
648
  export function buildJson(g: Graph, doXDot: boolean, preDraws?: DrawLookup): string {
654
649
  const draws = doXDot ? (preDraws ?? collectDrawLookup(g)) : undefined;
655
650
  const ctx = assignIds(g, doXDot, draws);
656
- return JSON.stringify(buildGraphObject(g, true, ctx), null, 2) + '\n';
651
+ return stringifyJsonTree(buildGraphObject(g, true, ctx)) + '\n';
657
652
  }
658
653
 
659
654
  /** Everything the JSON writers leave to the graph walk: they write once, at the end. */
660
655
  abstract class JsonRendererBase {
661
656
  /** @see plugin/core/gvplugin_core.c registration table */
662
657
  readonly quality = 0;
658
+ /** @see plugin/core/gvrender_core_json.c:745 render_features_json (default pad) */
659
+ readonly defaultPad = 0;
663
660
  beginNode(_n: Node, _job: RenderJob): void { /* no-op */ }
664
661
  endNode(_n: Node, _job: RenderJob): void { /* no-op */ }
665
662
  beginEdge(_e: Edge, _job: RenderJob): void { /* no-op */ }
package/src/render/map.ts CHANGED
@@ -540,6 +540,7 @@ export function mapOutputImap(
540
540
  export class PlainRenderer implements RendererPlugin {
541
541
  readonly type = 'plain';
542
542
  readonly quality = 0;
543
+ readonly defaultPad = 0; // @see plugin/core/gvrender_core_dot.c:734 render_features_dot
543
544
 
544
545
  beginGraph(_g: Graph, _job: RenderJob): void { /* no-op */ }
545
546
  endGraph(g: Graph, job: RenderJob): void { writePlain(g, job, false); }
@@ -562,6 +563,7 @@ export class PlainRenderer implements RendererPlugin {
562
563
  export class PlainExtRenderer implements RendererPlugin {
563
564
  readonly type = 'plain-ext';
564
565
  readonly quality = 0;
566
+ readonly defaultPad = 0; // @see plugin/core/gvrender_core_dot.c:734 render_features_dot
565
567
 
566
568
  beginGraph(_g: Graph, _job: RenderJob): void { /* no-op */ }
567
569
  endGraph(g: Graph, job: RenderJob): void { writePlain(g, job, true); }
@@ -637,6 +639,7 @@ function anchorOf(url: string | null, tooltip: string | null, target: string | n
637
639
  abstract class MapRendererBase implements RendererPlugin {
638
640
  abstract readonly type: string;
639
641
  readonly quality = 0;
642
+ readonly defaultPad = 4; // @see plugin/core/gvrender_core_map.c:244 render_features_map
640
643
  protected abstract readonly isCmapx: boolean;
641
644
  protected abstract readonly mapPolygon: boolean;
642
645
  private mapCtx: MapCtx | null = null;
@@ -18,7 +18,7 @@ import { createObjState, ObjType } from '../gvc/job.js';
18
18
  import { FillType } from '../gvc/context.js';
19
19
  import { escapeXml, escapeXmlTitle, svgComment } from './svg-helpers.js';
20
20
  import { resolveRenderColor, colorPaint } from './color-resolve.js';
21
- import { svgGraphClass } from './svg-id.js';
21
+ import { svgGraphClass, svgGraphId } from './svg-id.js';
22
22
  import { parseGradientSpec } from '../common/htmltable-emit-fill.js';
23
23
  import { findStopColor, parseStyleFlags } from '../common/style-resolve.js';
24
24
  import { croundNarrow32 } from '../common/arith.js';
@@ -232,18 +232,6 @@ function bgGradientPts(clip: Box): Point[] {
232
232
  ];
233
233
  }
234
234
 
235
- /**
236
- * Object id of the graph being emitted, as getObjId builds it for an AGRAPH:
237
- * the DOT `id` attr wins; else "graph" + AGSEQ. The graph being emitted is
238
- * job->gvc->g, i.e. `root == obj`, so neither the `<gid>_` prefix nor the
239
- * "clust" prefix applies. The root's AGSEQ is 0; a subgraph rendered after
240
- * its own layout carries its creation sequence among subgraphs.
241
- * @see lib/common/emit.c:getObjId
242
- */
243
- function graphObjId(g: Graph, job: RenderJob): string {
244
- return job.objId(g.attrs.get('id'), 'graph' + g.seq, true);
245
- }
246
-
247
235
  /**
248
236
  * Write background polygon element with gradient fill url reference.
249
237
  * Coords identical to emitGraphBackground; only fill changes.
@@ -281,7 +269,7 @@ function writeGradientPolygon(clip: Box, id: string, job: RenderJob): void {
281
269
  */
282
270
  function emitGradientBackground(g: Graph, clip: Box, spec: BgGradientSpec, job: RenderJob): void {
283
271
  const obj = createObjState(ObjType.RootGraph);
284
- obj.id = graphObjId(g, job);
272
+ obj.id = svgGraphId(g, job);
285
273
  obj.fillColor = resolveRenderColor(spec.fillColor);
286
274
  obj.stopColor = resolveRenderColor(spec.stopColor);
287
275
  obj.gradientFrac = spec.frac;
@@ -421,7 +409,7 @@ export function svgBeginPage(g: Graph, job: RenderJob): void {
421
409
  : -clip.ll.x + job.margin.x / z;
422
410
  const ty = clip.ur.y + job.margin.y / z;
423
411
  emitGraphGroupOpen(
424
- job.idLayerPrefix() + graphObjId(g, job),
412
+ job.idLayerPrefix() + svgGraphId(g, job),
425
413
  svgGraphClass(g),
426
414
  tx, ty, job,
427
415
  );
@@ -50,9 +50,18 @@ export function svgClusterId(sg: Graph, job: RenderJob): string {
50
50
  return job.objId(sg.attrs.get('id'), 'clust' + sg.seq);
51
51
  }
52
52
 
53
- /** SVG id for the root graph group: DOT `id` attr, else `graph0` (no prefix). */
53
+ /**
54
+ * Object id of the graph being emitted, as getObjId builds it for an AGRAPH:
55
+ * the DOT `id` attr wins; else `graph<AGSEQ>`. The graph being emitted is
56
+ * job->gvc->g, i.e. `root == obj`, so neither the `<gid>_` prefix nor the
57
+ * "clust" prefix applies. The root's AGSEQ is 0; a subgraph rendered after
58
+ * its own layout carries its creation sequence among subgraphs. It names the
59
+ * top group, the gradients, the graph anchor and map area (obj->id) and the
60
+ * base of the graph label's HTML anchor ids.
61
+ * @see lib/common/emit.c:getObjId
62
+ */
54
63
  export function svgGraphId(g: Graph, job: RenderJob): string {
55
- return job.objId(g.attrs.get('id'), 'graph0', true);
64
+ return job.objId(g.attrs.get('id'), 'graph' + g.seq, true);
56
65
  }
57
66
 
58
67
  /** `class="node[ <class>]"`, reading the inherited DOT `class` attribute. */
package/src/render/svg.ts CHANGED
@@ -53,6 +53,7 @@ import {
53
53
  emitParallelEdgePaths,
54
54
  escapeXml,
55
55
  emitPoints,
56
+ SVG_PAD,
56
57
  } from './svg-helpers.js';
57
58
  import { emitArrowOps } from './svg-arrow-ops.js';
58
59
  import { resolveRenderColor, colorOpacity, colorPaint } from './color-resolve.js';
@@ -93,6 +94,8 @@ export class SvgRenderer implements RendererPlugin {
93
94
  readonly type = 'svg';
94
95
  /** @see plugin/core/gvplugin_core.c registration table */
95
96
  readonly quality = 0;
97
+ /** @see plugin/core/gvrender_core_svg.c:810 render_features_svg (default pad) */
98
+ readonly defaultPad = SVG_PAD;
96
99
  /** Whether the current edge's <g> group was opened (deferred-emit state). */
97
100
  private edgeGroupOpen = false;
98
101
 
@@ -116,7 +119,7 @@ export class SvgRenderer implements RendererPlugin {
116
119
  /**
117
120
  * Close the edge group. Edge graphics (path + arrowhead) are emitted here
118
121
  * because the full spline is available on e.info.spl only after layout has
119
- * run routeDotEdges.
122
+ * routed the edges.
120
123
  *
121
124
  * For multi-color edges (color="c1:c2:…"), emits parallel offset Béziers
122
125
  * (one per color, SEP=2.0 apart) then arrows in headcolor/tailcolor.
@@ -8,7 +8,8 @@
8
8
  * (`lib/util/list.c:gv_list_sort_`). libc `qsort` is **not stable**: it reorders
9
9
  * comparator-equal elements in an implementation-defined permutation. Most port
10
10
  * sort sites can use JS's stable `Array.prototype.sort` because their comparator
11
- * never reports a tie (e.g. `edge-order.ts`). Where ties DO occur AND the
11
+ * never reports a tie (e.g. `routeCurvedGroup`'s sort of distinct originals by
12
+ * creation seq, `splines-groups.ts`). Where ties DO occur AND the
12
13
  * downstream result depends on their order, a stable sort diverges from the C
13
14
  * oracle.
14
15
  *
package/src/xdot/parse.ts CHANGED
@@ -12,6 +12,7 @@ import type {
12
12
  XdotRadialGrad, XdotColorStop, OpFunctions,
13
13
  } from "./types.js";
14
14
  import { XDOT_PARSE_ERROR } from "./types.js";
15
+ import { isSpace, scanStrtod } from "./strtod.js";
15
16
 
16
17
  /** ULONG_MAX on an LP64 target: strtoul saturation value. */
17
18
  const ULONG_MAX = 0xffff_ffff_ffff_ffffn;
@@ -21,8 +22,9 @@ type OpResult = { op: XdotOp; pos: number } | "error";
21
22
  type OpMaybeResult = OpResult | null;
22
23
 
23
24
  class XdotParser {
25
+ /** @see lib/util/gv_ctype.h:gv_isspace */
24
26
  static isWs(c: string): boolean {
25
- return c === " " || c === "\t" || c === "\n" || c === "\r";
27
+ return isSpace(c);
26
28
  }
27
29
 
28
30
  static skipWs(s: string, pos: number): number {
@@ -35,25 +37,13 @@ class XdotParser {
35
37
  return i;
36
38
  }
37
39
 
38
- static consumeExponent(s: string, i: number): number {
39
- if (i < s.length && (s[i] === "e" || s[i] === "E")) {
40
- i++;
41
- if (i < s.length && (s[i] === "+" || s[i] === "-")) i++;
42
- i = XdotParser.consumeDigits(s, i);
43
- }
44
- return i;
45
- }
46
-
40
+ /**
41
+ * C reads every xdot double with strtod, so a number may be a decimal, a
42
+ * hex float, inf/infinity or nan/nan(...); null is C's `p == s`.
43
+ * @see lib/xdot/xdot.c:parseReal
44
+ */
47
45
  static parseReal(s: string, pos: number): PR<number> {
48
- let i = XdotParser.skipWs(s, pos);
49
- const start = i;
50
- if (i < s.length && (s[i] === "-" || s[i] === "+")) i++;
51
- const digStart = i;
52
- i = XdotParser.consumeDigits(s, i);
53
- if (i < s.length && s[i] === ".") { i++; i = XdotParser.consumeDigits(s, i); }
54
- i = XdotParser.consumeExponent(s, i);
55
- if (i === start || i === digStart) return null;
56
- return { val: parseFloat(s.slice(start, i)), pos: i };
46
+ return scanStrtod(s, pos);
57
47
  }
58
48
 
59
49
  static parseInt_(s: string, pos: number): PR<number> {
@@ -0,0 +1,167 @@
1
+ // SPDX-License-Identifier: EPL-2.0
2
+ /**
3
+ * The number scan C's xdot parser gets from libc strtod. parseReal, parseRect
4
+ * and parsePolyline all read their doubles with strtod, so an xdot string may
5
+ * hold anything strtod accepts: a decimal, a hexadecimal float, `inf` or
6
+ * `infinity`, and `nan` or `nan(...)`. The grammar is the oracle platform's
7
+ * (macOS libc), which takes any characters between `nan(` and the first `)`.
8
+ * @see lib/xdot/xdot.c:parseReal
9
+ */
10
+
11
+ /** A scanned number and the offset just past it, or null when none starts here. */
12
+ export type Scan = { val: number; pos: number } | null;
13
+
14
+ const INF_WORD = "inf";
15
+ const INF_TAIL = "inity";
16
+ const NAN_WORD = "nan";
17
+
18
+ /** Bits in a double's significand, the smallest and largest binary exponents. */
19
+ const SIGNIFICAND_BITS = 53;
20
+ const MIN_SUBNORMAL_EXP = -1074;
21
+ const MAX_BINARY_EXP = 1023;
22
+ const MIN_NORMAL_EXP = -1022;
23
+ const EXP_BIAS = 1023;
24
+ /** 2^52: an exponent field sits above the 52 fraction bits. */
25
+ const FRACTION_SCALE = 2n ** 52n;
26
+ const HEX_DIGIT_BITS = 4n;
27
+
28
+ /** @see lib/util/gv_ctype.h:gv_isspace */
29
+ export function isSpace(c: string): boolean {
30
+ return c === " " || (c >= "\t" && c <= "\r");
31
+ }
32
+
33
+ function isDecDigit(c: string): boolean {
34
+ return c >= "0" && c <= "9";
35
+ }
36
+
37
+ function isHexDigit(c: string): boolean {
38
+ return isDecDigit(c) || (c >= "a" && c <= "f") || (c >= "A" && c <= "F");
39
+ }
40
+
41
+ function skipWhile(s: string, i: number, pred: (c: string) => boolean): number {
42
+ while (i < s.length && pred(s[i])) i++;
43
+ return i;
44
+ }
45
+
46
+ function matchesWord(s: string, i: number, word: string): boolean {
47
+ return s.slice(i, i + word.length).toLowerCase() === word;
48
+ }
49
+
50
+ /**
51
+ * The end of an exponent starting at `i`, or `i` when the marker is missing
52
+ * or no digit follows it: strtod("1e+") is 1 and stops at the `e`.
53
+ */
54
+ function exponentEnd(s: string, i: number, marker: string): number {
55
+ if (i >= s.length || s[i].toLowerCase() !== marker) return i;
56
+ let j = i + 1;
57
+ if (s[j] === "+" || s[j] === "-") j++;
58
+ const end = skipWhile(s, j, isDecDigit);
59
+ return end === j ? i : end;
60
+ }
61
+
62
+ /** 2^q as a double, exact for every q a double can hold (-1074..1023). */
63
+ function pow2(q: number): number {
64
+ let bits = BigInt(q + EXP_BIAS) * FRACTION_SCALE;
65
+ if (q < MIN_NORMAL_EXP) bits = 2n ** BigInt(q - MIN_SUBNORMAL_EXP);
66
+ return new Float64Array(new BigUint64Array([bits]).buffer)[0];
67
+ }
68
+
69
+ /** m / 2^shift rounded to nearest, ties to even; exact when shift <= 0. */
70
+ function shiftRoundHalfEven(m: bigint, shift: bigint): bigint {
71
+ if (shift <= 0n) return m << -shift;
72
+ const kept = m >> shift;
73
+ const rem = m - (kept << shift);
74
+ const half = 1n << (shift - 1n);
75
+ const roundUp = rem > half || (rem === half && (kept & 1n) === 1n);
76
+ return roundUp ? kept + 1n : kept;
77
+ }
78
+
79
+ /**
80
+ * m * 2^e2 as the nearest double, ties to even, as strtod rounds a hex float:
81
+ * 53 bits for a normal result, fewer in the subnormal range, infinity above
82
+ * the largest double and zero below half the smallest.
83
+ */
84
+ function hexToDouble(m: bigint, e2: bigint): number {
85
+ if (m === 0n) return 0;
86
+ // The exponent of the leading bit; bigint, since the text may carry an
87
+ // exponent of any length.
88
+ const top = BigInt(m.toString(2).length - 1) + e2;
89
+ if (top > BigInt(MAX_BINARY_EXP)) return Infinity;
90
+ if (top < BigInt(MIN_SUBNORMAL_EXP - 1)) return 0;
91
+ const q = Math.max(Number(top) - (SIGNIFICAND_BITS - 1), MIN_SUBNORMAL_EXP);
92
+ // A significand rounded up to 2^53 at the top exponent overflows to
93
+ // infinity in the multiplication, as strtod does.
94
+ return Number(shiftRoundHalfEven(m, BigInt(q) - e2)) * pow2(q);
95
+ }
96
+
97
+ /**
98
+ * A hexadecimal float whose "0x" starts at `i`: hex digits, an optional `.`
99
+ * and hex digits, an optional `p[sign]digits`. Null when no hex digit follows
100
+ * the prefix; strtod then reads the leading "0" as a decimal.
101
+ */
102
+ function scanHex(s: string, i: number): Scan {
103
+ const intStart = i + 2;
104
+ const intEnd = skipWhile(s, intStart, isHexDigit);
105
+ const hasDot = s[intEnd] === ".";
106
+ const end = hasDot ? skipWhile(s, intEnd + 1, isHexDigit) : intEnd;
107
+ const digits = s.slice(intStart, intEnd) + (hasDot ? s.slice(intEnd + 1, end) : "");
108
+ if (digits.length === 0) return null;
109
+ const fracDigits = BigInt(hasDot ? end - intEnd - 1 : 0);
110
+ const expEnd = exponentEnd(s, end, "p");
111
+ const exp = expEnd > end ? BigInt(s.slice(end + 1, expEnd)) : 0n;
112
+ const val = hexToDouble(BigInt(`0x${digits}`), exp - HEX_DIGIT_BITS * fracDigits);
113
+ return { val, pos: expEnd };
114
+ }
115
+
116
+ /**
117
+ * A decimal: digits with an optional `.`, at least one digit in all, and an
118
+ * optional `e[sign]digits`. parseFloat rounds the scanned text correctly, as
119
+ * strtod does, and overflows to infinity.
120
+ */
121
+ function scanDecimal(s: string, i: number): Scan {
122
+ const intEnd = skipWhile(s, i, isDecDigit);
123
+ const hasDot = s[intEnd] === ".";
124
+ const mantEnd = hasDot ? skipWhile(s, intEnd + 1, isDecDigit) : intEnd;
125
+ const digitCount = mantEnd - i - (hasDot ? 1 : 0);
126
+ if (digitCount === 0) return null;
127
+ const end = exponentEnd(s, mantEnd, "e");
128
+ return { val: parseFloat(s.slice(i, end)), pos: end };
129
+ }
130
+
131
+ /**
132
+ * `inf` or `infinity`, and `nan` or `nan(...)`, case-insensitive. The
133
+ * parenthesized part is taken only when a `)` closes it.
134
+ */
135
+ function scanSpecial(s: string, i: number): Scan {
136
+ if (matchesWord(s, i, INF_WORD)) {
137
+ const tail = i + INF_WORD.length;
138
+ return { val: Infinity, pos: matchesWord(s, tail, INF_TAIL) ? tail + INF_TAIL.length : tail };
139
+ }
140
+ if (!matchesWord(s, i, NAN_WORD)) return null;
141
+ const end = i + NAN_WORD.length;
142
+ const close = s[end] === "(" ? s.indexOf(")", end) : -1;
143
+ return { val: NaN, pos: close === -1 ? end : close + 1 };
144
+ }
145
+
146
+ function scanMagnitude(s: string, i: number): Scan {
147
+ if (s[i] === "0" && (s[i + 1] === "x" || s[i + 1] === "X")) {
148
+ const hex = scanHex(s, i);
149
+ if (hex !== null) return hex;
150
+ }
151
+ return scanDecimal(s, i) ?? scanSpecial(s, i);
152
+ }
153
+
154
+ /**
155
+ * strtod(s + pos, &end): skips whitespace, takes an optional sign, then the
156
+ * longest number strtod accepts. Null when no conversion is possible, which
157
+ * is C's `end == s`.
158
+ * @see lib/xdot/xdot.c:parseReal
159
+ */
160
+ export function scanStrtod(s: string, pos: number): Scan {
161
+ let i = skipWhile(s, pos, isSpace);
162
+ const negative = s[i] === "-";
163
+ if (negative || s[i] === "+") i++;
164
+ const mag = scanMagnitude(s, i);
165
+ if (mag === null) return null;
166
+ return { val: negative ? -mag.val : mag.val, pos: mag.pos };
167
+ }