@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
@@ -12,6 +12,7 @@
12
12
  */
13
13
 
14
14
  import { InternalError } from '../../errors.js';
15
+ import { fma } from '../../common/fma.js';
15
16
  import type { Graph } from '../../model/graph.js';
16
17
  import type { Node } from '../../model/node.js';
17
18
  import type { Edge } from '../../model/edge.js';
@@ -76,7 +77,8 @@ export function getEdgeList(n: Node, g: Graph): Erec[] {
76
77
  const m = e.head === n ? e.tail : e.head;
77
78
  const dx = m.info.pos![0]! - n.info.pos![0]!;
78
79
  const dy = m.info.pos![1]! - n.info.pos![1]!;
79
- erecs.push({ e, alpha: Math.atan2(dy, dx), dist2: dx * dx + dy * dy });
80
+ // contracted (-ffp-contract=on): fmadd of the first product
81
+ erecs.push({ e, alpha: Math.atan2(dy, dx), dist2: fma(dx, dx, dy * dy) });
80
82
  }
81
83
  if (erecs.length !== deg) {
82
84
  throw new InternalError(`fdp getEdgeList: ${erecs.length} edges vs deg ${deg}`);
@@ -107,7 +109,9 @@ export function genPorts(
107
109
  const fwd = n.id < other.id;
108
110
  const fan = fwd
109
111
  ? { i: idx, inc: 1, angle: er.alpha, delta }
110
- : { i: idx + cnt - 1, inc: -1, angle: er.alpha + delta * (cnt - 1), delta: -delta };
112
+ : { // contracted (-ffp-contract=on): angle += delta * (cnt - 1) is one fmadd
113
+ i: idx + cnt - 1, inc: -1, angle: fma(delta, cnt - 1, er.alpha), delta: -delta,
114
+ };
111
115
 
112
116
  fillPorts(n, e, pp, fan);
113
117
  return idx + cnt;
@@ -24,8 +24,12 @@ const fr = Math.fround;
24
24
  /** Width of the vectorised reduction block of `right_mult_with_vector_ff`. */
25
25
  const RIGHT_MULT_BLOCK = 16;
26
26
 
27
- /** The unexpected-zero-residual diagnostic. @see lib/neatogen/conjgrad.c */
28
- const ZERO_LENGTH_MESSAGE = 'conjugate_gradient: unexpected length 0 vector\n';
27
+ /**
28
+ * The unexpected-zero-residual diagnostic, without C's trailing `\n`: the
29
+ * port's agerr writers finish the line themselves (`common/agerr.ts`).
30
+ * @see lib/neatogen/conjgrad.c:65
31
+ */
32
+ const ZERO_LENGTH_MESSAGE = 'conjugate_gradient: unexpected length 0 vector';
29
33
 
30
34
  /**
31
35
  * `result = packed_matrix * vector` for the packed upper triangle of a
@@ -15,6 +15,7 @@ import { setEdgeLen } from './edge-len.js';
15
15
  import { rkNewState, rkSeed, rkInterval } from '../../util/mt19937.js';
16
16
  import type { RkState } from '../../util/mt19937.js';
17
17
  import { drand48 } from '../../common/random.js';
18
+ import { libmHypot } from '../../common/libm-hypot.js';
18
19
  import { lateDouble } from '../../common/nodeinit.js';
19
20
  import { checkStart, parseStart, INIT_RANDOM, INIT_REGULAR } from './start.js';
20
21
  import { jitter3d, ndimOf } from './init-dim.js';
@@ -343,7 +344,7 @@ export function sgdIteration(
343
344
  const mu = Math.min(eta * t.w, 1);
344
345
  const dx = pos[2 * t.i] - pos[2 * t.j];
345
346
  const dy = pos[2 * t.i + 1] - pos[2 * t.j + 1];
346
- const mag = Math.hypot(dx, dy);
347
+ const mag = libmHypot(dx, dy);
347
348
  if (mag === 0) continue;
348
349
  const r = (mu * (mag - t.d)) / (2 * mag);
349
350
  const rx = r * dx;
@@ -24,7 +24,7 @@ import { Node } from './node.js';
24
24
  * @see lib/cgraph/cghdr.h:LOCALNAMEPREFIX
25
25
  * @see lib/cgraph/id.c:aginternalmapprint
26
26
  */
27
- const LOCALNAMEPREFIX = '%';
27
+ export const LOCALNAMEPREFIX = '%';
28
28
 
29
29
  /**
30
30
  * cgraph's id for the first anonymous object, which an anonymous root graph is
@@ -37,8 +37,9 @@ const ANONYMOUS_ROOT_ID = 1;
37
37
  * Graph name as `agnameof` returns it: the DOT name, or `%<id>` for an
38
38
  * anonymous graph. The port stores `''` for an anonymous root (dot/xdot
39
39
  * re-serialization must not print the `%` name), so it is restored here.
40
- * Anonymous subgraph ids are not tracked; callers pass the root, as C's
41
- * neato message sites do.
40
+ * An anonymous subgraph already carries its `%N` name (the parser allocates
41
+ * it), so only the root needs restoring; the dot writer passes either, and
42
+ * the neato message sites pass the root, as C's do.
42
43
  * @see lib/cgraph/id.c:agnameof
43
44
  */
44
45
  export function agNameOf(g: Graph): string {
package/src/model/edge.ts CHANGED
@@ -9,7 +9,7 @@
9
9
 
10
10
  import type { Node } from './node.js';
11
11
  import { EMPTY_ATTRS } from './lazy-attrs.js';
12
- import { type EdgeInfo, makeEdgeInfo, makePort } from './edgeInfo.js';
12
+ import { type EdgeInfo, AUX_EDGE_PORT, makeEdgeInfo, makePort } from './edgeInfo.js';
13
13
 
14
14
  /**
15
15
  * Represents an abstract edge in the graph, corresponding to Agedgepair_t.
@@ -93,13 +93,20 @@ export class Edge {
93
93
  */
94
94
  info: EdgeInfo;
95
95
 
96
- /** @see lib/cgraph/edge.c:agedge */
97
- constructor(tail: Node, head: Node, name: string, lazyAttrs = false) {
96
+ /**
97
+ * `auxPorts` is for dot's auxiliary edges only: both ends take the shared
98
+ * {@link AUX_EDGE_PORT} in place of a private port each.
99
+ * @see lib/cgraph/edge.c:agedge
100
+ * @see lib/dotgen/position.c:make_aux_edge
101
+ */
102
+ constructor(tail: Node, head: Node, name: string, lazyAttrs = false, auxPorts = false) {
98
103
  this.seq = Edge._nextSeq++;
99
104
  this.tail = tail;
100
105
  this.head = head;
101
106
  this.name = name;
102
107
  this.attrs = lazyAttrs ? EMPTY_ATTRS : new Map();
103
- this.info = makeEdgeInfo(makePort(), makePort());
108
+ this.info = auxPorts
109
+ ? makeEdgeInfo(AUX_EDGE_PORT, AUX_EDGE_PORT)
110
+ : makeEdgeInfo(makePort(), makePort());
104
111
  }
105
112
  }
@@ -173,8 +173,9 @@ export interface EdgeInfo {
173
173
 
174
174
  /**
175
175
  * Routing attempted and routesplines failed: the edge is LOST exactly as in
176
- * C (no spline installed, map_edge warns, emit skips). Port-only bookkeeping
177
- * so the routeDotEdges backstop does not re-attempt an edge C routes once.
176
+ * C (no spline installed, map_edge warns, emit skips). Port-only bookkeeping:
177
+ * routeLoneEdge skips a lost edge, so a later call in the same routing pass
178
+ * does not re-attempt an edge C routes once; beginRoutingPass clears it.
178
179
  * @see lib/common/routespl.c:routesplines (NULL), lib/common/postproc.c:map_edge
179
180
  */
180
181
  lost?: boolean;
@@ -391,6 +392,21 @@ export function makePort(): Port {
391
392
  };
392
393
  }
393
394
 
395
+ /**
396
+ * The default port both ends of every auxiliary edge share.
397
+ *
398
+ * C's make_aux_edge zero-allocates one Agedgeinfo_t, so an aux edge's
399
+ * ED_tail_port and ED_head_port are two structs inside that block, and nothing
400
+ * writes them before remove_aux_edges frees the edge. A makePort() pair per aux
401
+ * edge stood for those 96 inline bytes with 352 B of separate objects (two
402
+ * ports, two points, four boxed doubles), on a structure separate_subclust
403
+ * builds once per pair of sibling clusters (16.3 M on tests/2475_1.dot). It
404
+ * carries makePort()'s values and is frozen with its point, so a write throws
405
+ * rather than reaching every aux edge.
406
+ * @see lib/dotgen/position.c:make_aux_edge
407
+ */
408
+ export const AUX_EDGE_PORT: Port = Object.freeze({ ...makePort(), p: Object.freeze({ x: 0, y: 0 }) });
409
+
394
410
  /**
395
411
  * Constructs a minimal EdgeInfo with required port fields initialized.
396
412
  *
@@ -48,9 +48,10 @@ export class Graph {
48
48
  * True when the graph was declared with NO name (`digraph {`), as opposed to
49
49
  * an explicit empty name (`digraph "" {`). Both store `name === ''`, but
50
50
  * cgraph gives the truly-anonymous root the internal id `%1` (agnameof) while
51
- * the empty-named one keeps `""`. Only the imagemap `<map id/name>` reads this
52
- * (map.ts:mapGraphName); dot/xdot re-serialization keeps `name` so an
53
- * anonymous root round-trips as `digraph {`, not `digraph %1 {`.
51
+ * the empty-named one keeps `""`. Read through `agNameOf` by the imagemap
52
+ * `<map id/name>`, the neato messages and the dot/xdot writer's header,
53
+ * which prints `digraph {` for an anonymous root and `digraph "" {` for the
54
+ * empty-named one. `name` stays `''` for both.
54
55
  * @see lib/cgraph/id.c:idmap (anon → `%1`) ; lib/cgraph/agraph.c:agnameof
55
56
  */
56
57
  readonly anonymous: boolean;
@@ -1,7 +1,8 @@
1
1
  // SPDX-License-Identifier: EPL-2.0
2
2
 
3
3
  /**
4
- * Shared empty attribute map for dot virtual nodes/edges (AD-12).
4
+ * Shared empty attribute map for dot virtual nodes/edges (AD-12) and for
5
+ * auxiliary edges (make_aux_edge, issue #145).
5
6
  *
6
7
  * C virtual nodes/edges carry no attribute record; allocating an empty `Map`
7
8
  * per object cost ~372 B per virtual pair. Virtual objects start with this
@@ -9,6 +10,7 @@
9
10
  * through {@link ownAttrs}, which materialises a private `Map`. A direct
10
11
  * mutation of the shared map throws rather than leaking into every virtual.
11
12
  * @see lib/dotgen/fastgr.c:virtual_node
13
+ * @see lib/dotgen/position.c:make_aux_edge
12
14
  */
13
15
 
14
16
  class SharedEmptyAttrs extends Map<string, string> {
@@ -10,6 +10,7 @@ import { Graph, type GraphKind } from '../model/graph.js';
10
10
  import { Node } from '../model/node.js';
11
11
  import { Edge } from '../model/edge.js';
12
12
  import { assignSubgSeq } from '../model/cgraph-ops.js';
13
+ import { htmlValueContent, isHtmlValue } from '../common/html-string.js';
13
14
  import type {
14
15
  AttrPair,
15
16
  NodeId,
@@ -475,12 +476,20 @@ export function buildFromAst(ast: ParsedGraph): Graph {
475
476
  else kind = 'undirected';
476
477
  // ast.id is null for a nameless root (`digraph {`) and '' for an explicit
477
478
  // empty name (`digraph "" {`); only the former is anonymous in cgraph (→ `%1`).
478
- const graph = new Graph(ast.id ?? '', kind, ast.id == null);
479
+ // An html-like root name (`digraph <h g> {`) is plain text: the lexer interns
480
+ // it with agstrdup_html before the graph exists, so agopen's idmap finds no
481
+ // html ref in the new graph's dictionary and copies it as text. Node and
482
+ // subgraph names are interned in the graph and keep the flag.
483
+ // @see lib/cgraph/scan.l:233, lib/cgraph/id.c:52, lib/cgraph/refstr.c:agstrdup
484
+ const id = ast.id ?? '';
485
+ const graph = new Graph(isHtmlValue(id) ? htmlValueContent(id) : id, kind, ast.id == null);
479
486
  // An unnamed root graph is itself anonymous in cgraph (agopen with no name),
480
487
  // consuming anon id 1 before any statement — so the first anonymous subgraph is
481
- // %3, not %1 (a named root leaves the counter at 0 → first subgraph %1).
488
+ // %3, not %1 (a named root leaves the counter at 0 → first subgraph %1). A root
489
+ // named `""` is named: idmap maps the string and leaves the counter alone, so
490
+ // the test is for null, not for a falsy id.
482
491
  // @see lib/cgraph/graph.c:agopen, lib/cgraph/id.c:idmap
483
- if (!ast.id) processor.advanceAnonId();
492
+ if (ast.id == null) processor.advanceAnonId();
484
493
  buildGraph(ast.stmts, graph, graph, ast.directed, processor);
485
494
  return graph;
486
495
  }
@@ -17,6 +17,7 @@
17
17
  import type { Graph } from '../../model/graph.js';
18
18
  import type { Node } from '../../model/node.js';
19
19
  import type { Edge } from '../../model/edge.js';
20
+ import { LOCALNAMEPREFIX, agNameOf } from '../../model/cgraph-ops.js';
20
21
  import type { TextlabelT, FieldT, ShapeDesc } from '../../common/types.js';
21
22
  import { agstrcanon, agstrcanonText } from '../map.js';
22
23
  import { isHtmlValue } from '../../common/html-string.js';
@@ -93,9 +94,13 @@ export abstract class DotWriterBase {
93
94
  return ix0 + 1;
94
95
  }
95
96
 
96
- /** A subgraph is anonymous when its name is empty or a `%N` local name. */
97
+ /** A graph is anonymous when `agnameof` gives a `%` local name: a nameless
98
+ * root (`%1`), a nameless subgraph (the parser names it `%N`), or a name
99
+ * that itself starts with `%`. A graph named `""` is named: cgraph maps `""`
100
+ * as a name, so it keeps its header and is never inlined.
101
+ * @see write.c:is_anonymous ; write.c:write_hdr ; lib/cgraph/id.c:idmap */
97
102
  private isAnonymous(g: Graph): boolean {
98
- return g.name.length === 0 || g.name.charCodeAt(0) === 0x25 /* % */;
103
+ return agNameOf(g).startsWith(LOCALNAMEPREFIX);
99
104
  }
100
105
 
101
106
  /** A graph carries a `bb` attribute when it is the root or has a layout bb
@@ -155,7 +160,9 @@ export abstract class DotWriterBase {
155
160
  if (top) {
156
161
  const strict = g.kind === 'strict-directed' || g.kind === 'strict-undirected' ? 'strict ' : '';
157
162
  const kw = isDirected(g) ? 'digraph' : 'graph';
158
- const nm = g.name.length > 0 && !this.isAnonymous(g) ? xdotId(g.name) + ' ' : '';
163
+ // The root's name is '' both when it has none (agnameof: `%1`, not
164
+ // printed) and when it is named `""` (printed as `""`).
165
+ const nm = this.isAnonymous(g) ? '' : xdotId(g.name) + ' ';
159
166
  ctx.out.push(strict + kw + ' ' + nm + '{\n');
160
167
  ctx.level++;
161
168
  } else {
@@ -16,7 +16,7 @@ import { IGNORED } from '../../layout/dot/rank.js';
16
16
  import { agstrcanon } from '../map.js';
17
17
  import { POINTS_PER_INCH } from '../../model/geom.js';
18
18
  import type { TextlabelT, FieldT } from '../../common/types.js';
19
- import { agcanonEscape, gfmt2, gfmt5, lpStr } from './xdot-ops.js';
19
+ import { gfmt2, gfmt5, lpStr } from './xdot-ops.js';
20
20
 
21
21
  /**
22
22
  * C's `attach_attrs` edge loop skips IGNORED edges and edges with no spline
@@ -356,10 +356,19 @@ export function nodeDictParts(g: Graph, top: boolean): string[] {
356
356
  return dictParts(defs);
357
357
  }
358
358
 
359
+ /**
360
+ * A node or edge attribute the layout did not overwrite: the input's own value,
361
+ * written as agwrite writes every value, `name=` + `agstrcanon(value)` — an
362
+ * html value as `<...>`, a plain one quoted only when it needs it and broken
363
+ * with backslash-newline at `Max_outputline`. An absent or empty value prints
364
+ * nothing.
365
+ * @see lib/cgraph/write.c:write_nondefault_attrs (502-504)
366
+ * @see lib/cgraph/write.c:_write_canonstr
367
+ */
359
368
  export function echoAttr(attrs: Map<string, string>, key: string): string[] {
360
369
  const v = attrs.get(key);
361
370
  if (v === undefined || v.length === 0) return [];
362
- return [key + '="' + agcanonEscape(v) + '"'];
371
+ return [`${key}=${agstrcanon(v)}`];
363
372
  }
364
373
 
365
374
  /**
@@ -385,16 +394,18 @@ export function writeDictSkips(v: string, inherited: string | undefined): boolea
385
394
 
386
395
  /**
387
396
  * `echoAttr` for a GRAPH attribute the layout did not overwrite — same as
388
- * echoAttr except an EMPTY value can still be emitted, per `writeDictSkips`.
389
- * So a re-fed dot output whose `{rank=same}` block carries `bb=""`/`lp=""`
390
- * under a boxed, labelled cluster echoes both back verbatim
391
- * (tests/share/KW91.gv).
397
+ * echoAttr (the value goes through `agstrcanon`, as write_dict's does) except
398
+ * an EMPTY value can still be emitted, per `writeDictSkips`. So a re-fed dot
399
+ * output whose `{rank=same}` block carries `bb=""`/`lp=""` under a boxed,
400
+ * labelled cluster echoes both back verbatim (tests/share/KW91.gv).
401
+ * @see lib/cgraph/write.c:write_dict (290-292)
402
+ * @see lib/cgraph/write.c:_write_canonstr
392
403
  */
393
404
  export function echoGraphAttr(g: Graph, key: string): string[] {
394
405
  const v = g.attrs.get(key);
395
406
  if (v === undefined) return [];
396
407
  if (writeDictSkips(v, g.graphDefaultsSnapshot?.get(key))) return [];
397
- return [key + '="' + agcanonEscape(v) + '"'];
408
+ return [`${key}=${agstrcanon(v)}`];
398
409
  }
399
410
 
400
411
  /**
@@ -29,13 +29,37 @@ const POINTS_PER_INCH = 72;
29
29
  /** The draw strings of one object, or undefined for an object drawn with none. */
30
30
  type DrawsOf = (obj: Node | Edge | Graph) => XdotDraws | undefined;
31
31
 
32
+ /** The three strings attach_attrs writes on every node. */
33
+ export interface NodeLayoutAttrs {
34
+ readonly pos: string;
35
+ readonly height: string;
36
+ readonly width: string;
37
+ }
38
+
39
+ /**
40
+ * A laid-out node's `pos`, `height` and `width` as attach_attrs prints them:
41
+ * `%.5g` of ND_coord (every coordinate when `odim >= 3`), PS2INCH(ND_ht) and
42
+ * PS2INCH(ND_lw + ND_rw). Pure: the write-back and json0, which has no xdot
43
+ * render to read them from, both take their values here.
44
+ * @see lib/common/output.c:296-309
45
+ */
46
+ export function nodeLayoutAttrs(n: Node): NodeLayoutAttrs {
47
+ const info = n.info;
48
+ return {
49
+ pos: nodePosRaw(n),
50
+ height: gfmt5(info.ht / POINTS_PER_INCH),
51
+ width: gfmt5((info.lw + info.rw) / POINTS_PER_INCH),
52
+ };
53
+ }
54
+
32
55
  /** @see lib/common/output.c:296-317 */
33
56
  function attachNode(n: Node): void {
34
57
  const attrs = ownAttrs(n);
35
58
  const info = n.info;
36
- attrs.set('pos', nodePosRaw(n));
37
- attrs.set('height', gfmt5(info.ht / POINTS_PER_INCH));
38
- attrs.set('width', gfmt5((info.lw + info.rw) / POINTS_PER_INCH));
59
+ const layout = nodeLayoutAttrs(n);
60
+ attrs.set('pos', layout.pos);
61
+ attrs.set('height', layout.height);
62
+ attrs.set('width', layout.width);
39
63
  const xlabel = info.xlabel as TextlabelT | undefined;
40
64
  if (xlabel?.set) attrs.set('xlp', lpStr(xlabel.pos));
41
65
  if ((info.shape as ShapeDesc | undefined)?.name === 'record') {
@@ -13,6 +13,8 @@ import { colorxlate } from '../../common/color.js';
13
13
  import { getGradientPoints } from '../svg-gradient.js';
14
14
  import { EmitState, toFixed2HalfEven } from '../../gvc/job.js';
15
15
  import { printfSig, printfFixed } from '../../util/printf-round.js';
16
+ import { isHtmlValue } from '../../common/html-string.js';
17
+ import { agstrcanon } from '../map.js';
16
18
 
17
19
  // ---------------------------------------------------------------------------
18
20
  // Constants
@@ -296,31 +298,34 @@ export function xdotStrOp(prefix: string, s: string): string {
296
298
  }
297
299
 
298
300
  /**
299
- * Quote a DOT identifier unless it is a bare id or numeral, mirroring agwrite's
300
- * agcanonStr so the serialized graph reparses (the comparator reparses both
301
- * sides). Only `"` is escaped (→ `\"`); a `\` is left as-is — it is already the
302
- * start of a stored escape like `\n`/`\l` that agcanonStr keeps verbatim, so
303
- * doubling it (`\\n`) would change the name (`a\n(b\n"c")` must stay `a\n…`, not
304
- * `a\\n…`). Over-quoting a value native leaves bare is harmless: both parse to
305
- * the same name. @see lib/cgraph/write.c:_agstrcanon (escapes '"', keeps '\')
301
+ * Canonicalize a node, edge-endpoint or graph/subgraph name for `-Tdot`/`-Txdot`
302
+ * as agwrite does: `write_nodename` and `write_hdr` both print the name through
303
+ * `write_canonstr`, i.e. `agstrcanon` with the html check on. So a name is bare
304
+ * when it is an id or numeral, quoted when it is a keyword or holds any other
305
+ * byte, wrapped at `Max_outputline`, and angle-bracketed when it is html-like.
306
+ * A `\` is copied verbatim: it is already the start of a stored escape like
307
+ * `\n`/`\l`, so doubling it would change the name.
308
+ * @see lib/cgraph/write.c:write_nodename
309
+ * @see lib/cgraph/write.c:write_hdr
310
+ * @see lib/cgraph/write.c:write_canonstr
306
311
  *
307
- * ONE DELIBERATE DIVERGENCE from _agstrcanon: an ODD trailing backslash run is
308
- * padded to even. C copies it verbatim and appends the closing quote, so a name
309
- * ending in a single `\` serializes as `"a\"` — the backslash escapes the quote
310
- * and the output does not reparse. The DOT lexer cannot produce such a name
311
- * (source `"a\"` never terminates), so this is unreachable from any file and no
312
- * corpus id changes; it is reachable only through the programmatic API, where a
313
- * caller supplies the string directly. Padding costs a name that round-trips to
314
- * `a\\` instead of `a\`, which beats emitting a document that cannot be parsed.
312
+ * ONE DELIBERATE DIVERGENCE from _agstrcanon: an ODD trailing backslash run on
313
+ * a non-html name is padded to even. C copies it verbatim and appends the
314
+ * closing quote, so a name ending in a single `\` serializes as `"a\"` — the
315
+ * backslash escapes the quote and the output does not reparse. The DOT lexer
316
+ * cannot produce such a name (source `"a\"` never terminates), so this is
317
+ * unreachable from any file and no corpus id changes; it is reachable only
318
+ * through the programmatic API, where a caller supplies the string directly.
319
+ * Padding costs a name that round-trips to `a\\` instead of `a\`, which beats
320
+ * emitting a document that cannot be parsed. An html name is never padded: C
321
+ * prints `<a\>` and that reparses.
315
322
  * @see CodeQL "Incomplete string escaping or encoding" — the alert's own remedy
316
323
  * (escape every `\`) is wrong here and breaks `\n`/`\l` parity.
317
324
  */
318
325
  export function xdotId(s: string): string {
319
- if (/^[A-Za-z_][A-Za-z_0-9]*$/.test(s)) return s;
320
- if (/^-?(\.[0-9]+|[0-9]+(\.[0-9]*)?)$/.test(s)) return s;
321
- const body = s.replace(/"/g, '\\"');
322
- const trailingBackslashes = /\\*$/.exec(body)![0].length;
323
- return '"' + body + (trailingBackslashes % 2 === 1 ? '\\' : '') + '"';
326
+ if (isHtmlValue(s)) return agstrcanon(s);
327
+ const oddTrailingRun = /\\*$/.exec(s)![0].length % 2 === 1;
328
+ return agstrcanon(oddTrailingRun ? `${s}\\` : s);
324
329
  }
325
330
 
326
331
  /**
@@ -385,42 +390,6 @@ export function escBackslash(s: string): string {
385
390
  return s.replace(/\\/g, '\\\\');
386
391
  }
387
392
 
388
- /** True if s[i..] starts an escape sequence agcanonStr keeps verbatim: a `\`
389
- * followed by one of E G H L N T l n r \ ". @see lib/cgraph/write.c:is_escape */
390
- export function isEscapeSeq(s: string, i: number): boolean {
391
- if (s[i] !== '\\') return false;
392
- const n = s[i + 1];
393
- return n === 'E' || n === 'G' || n === 'H' || n === 'L' || n === 'N' || n === 'T'
394
- || n === 'l' || n === 'n' || n === 'r' || n === '\\' || n === '"';
395
- }
396
-
397
- /**
398
- * Escape a value for a DOT attribute exactly as agwrite's agcanonStr does: a `"`
399
- * becomes `\"` ONLY when it is not already part of an escape sequence, so an
400
- * existing `\"` or `\\` in the value is passed through verbatim rather than
401
- * double-escaped. For an already-backslash-doubled value (node/edge/graph labels,
402
- * post put_escaping_backslashes) this is identical to a naive `"`→`\"` — every
403
- * `"` follows a doubled `\\`, so none are ever part_of_escape. For raw cluster
404
- * labels (agset, no put_escaping) it preserves the source `\"`/`\\` unchanged.
405
- * @see lib/cgraph/write.c:_agstrcanon (135-167)
406
- */
407
- export function agcanonEscape(s: string): string {
408
- let out = '';
409
- let partOfEscape = false;
410
- for (let i = 0; i < s.length; i++) {
411
- const c = s[i]!;
412
- if (c === '"' && !partOfEscape) {
413
- out += '\\';
414
- } else if (!partOfEscape && isEscapeSeq(s, i)) {
415
- partOfEscape = true;
416
- } else {
417
- partOfEscape = false;
418
- }
419
- out += c;
420
- }
421
- return out;
422
- }
423
-
424
393
  /** Trim a "%.3f" fixed string like C's agxbuf_trim_zeros (trailing 0s + dot). */
425
394
  export function trimFixed3(v: number): string {
426
395
  let s = v.toFixed(3);
package/src/render/dot.ts CHANGED
@@ -68,6 +68,8 @@ export class XdotRenderer extends EdgeDrawBase implements RendererPlugin {
68
68
  readonly type: string = 'xdot';
69
69
  /** @see plugin/core/gvplugin_core.c registration table */
70
70
  readonly quality = 0;
71
+ /** `-Tdot` too (`:734`). @see plugin/core/gvrender_core_dot.c:745 render_features_xdot */
72
+ readonly defaultPad = 0;
71
73
 
72
74
  /**
73
75
  * Whether this format attaches the xdot draw attributes before agwrite.
@@ -104,8 +106,8 @@ export class XdotRenderer extends EdgeDrawBase implements RendererPlugin {
104
106
  this.clusters = [];
105
107
  }
106
108
 
107
- /** The last render's draw strings by ORIGINAL object: what `-Tjson` reads via agxget.
108
- * The DOT-text round-trip cannot represent draw text containing `"` (id 2239). */
109
+ /** This render's draw strings by ORIGINAL object. `-Tjson` lays them over the re-parsed xdot text,
110
+ * which cannot represent draw text containing `"` (id 2239); stored strings reach it by that text. */
109
111
  drawStringsByObject(): ReadonlyMap<Node | Edge | Graph, XdotDraws> {
110
112
  return this.draws;
111
113
  }
@@ -139,8 +141,8 @@ export class XdotRenderer extends EdgeDrawBase implements RendererPlugin {
139
141
  if (fillSpec === 'transparent') fillSpec = 'white';
140
142
  // The canvas fill covers job->clip, which setup_page derives from the focus
141
143
  // and page size: bb ± pad (xdot's default pad is 0), and nan for an infinite
142
- // bb. @see emit.c:1559-1562 setup_page · gvrender_core_dot.c:739 (default_pad)
143
- const c = deviceClip(g, this, job);
144
+ // bb. @see emit.c:1559-1562 setup_page · gvrender_core_dot.c:745 (default_pad)
145
+ const c = deviceClip(g, job);
144
146
  const corners: Point[] = [
145
147
  { x: c.ll.x, y: c.ll.y }, { x: c.ll.x, y: c.ur.y }, { x: c.ur.x, y: c.ur.y }, { x: c.ur.x, y: c.ll.y },
146
148
  ];
@@ -301,7 +303,7 @@ export class XdotRenderer extends EdgeDrawBase implements RendererPlugin {
301
303
  if (draw) set.draw = draw;
302
304
  // Cluster labels are stored via plain agxset (xdot_end_cluster:286), NOT
303
305
  // put_escaping_backslashes like node/edge/graph labels — so NO escBackslash.
304
- // The source `\"`/`\\` in the label survive as-is through agcanonEscape on
306
+ // The source `\"`/`\\` in the label survive as-is through agstrcanonText on
305
307
  // serialize (drawAttr). @see gvrender_core_dot.c:286
306
308
  if (ldraw) set.ldraw = ldraw;
307
309
  }
@@ -9,10 +9,17 @@
9
9
  * the same helper. A graph with no cluster edges keeps the usual order (attach
10
10
  * after the write): nothing there can differ.
11
11
  *
12
+ * Also the json cluster map: write_graph's top pass numbers the subgraphs and
13
+ * maps each cluster's name to its gid (label_subgs, insert), which is where a
14
+ * cluster node's gid comes from (lookup) and where a repeated cluster name is
15
+ * warned about.
16
+ *
12
17
  * @see plugin/core/gvrender_core_json.c:json_begin_graph
18
+ * @see plugin/core/gvrender_core_json.c:write_graph
13
19
  * @see lib/common/output.c:403 (if (HAS_CLUST_EDGE(g)) undoClusterEdges(g))
14
20
  */
15
21
 
22
+ import { agwarningf } from '../common/agerr.js';
16
23
  import { undoRenderedClusterEdges } from '../gvc/layout-reset.js';
17
24
  import { isACluster } from '../layout/dot/rank.js';
18
25
  import type { Graph } from '../model/graph.js';
@@ -41,10 +48,40 @@ export function jsonNodes(g: Graph): Node[] {
41
48
  }
42
49
 
43
50
  /**
44
- * A cluster node's `_gvid`: that of the first cluster of its name, as write_graph's
45
- * `lookup(map, agnameof(np))` finds it, or -1 when there is none.
46
- * @see plugin/core/gvrender_core_json.c:658 lookup, label_subgs
51
+ * The gid mapped to cluster `name`, or -1 when there is none.
52
+ * @see plugin/core/gvrender_core_json.c:lookup
53
+ */
54
+ export function lookupCluster(map: ReadonlyMap<string, number>, name: string): number {
55
+ return map.get(name) ?? -1;
56
+ }
57
+
58
+ /**
59
+ * Maps cluster `name` to gid `v`. The first entry of a name is kept; a later
60
+ * one with another value is warned about and dropped.
61
+ * @see plugin/core/gvrender_core_json.c:insert
62
+ */
63
+ export function insertCluster(map: Map<string, number>, name: string, v: number): void {
64
+ const ip = map.get(name);
65
+ if (ip !== undefined) {
66
+ if (ip !== v) agwarningf(`Duplicate cluster name "${name}"`);
67
+ return;
68
+ }
69
+ map.set(name, v);
70
+ }
71
+
72
+ /**
73
+ * Numbers `g`'s subgraphs in DFS preorder from `lbl` (C's `GD_gid(g) = lbl++`;
74
+ * here a subgraph's gid is its index in `out`) and maps each cluster's name to
75
+ * its gid. Returns the next label: the subgraph count when called on the root
76
+ * with 0.
77
+ * @see plugin/core/gvrender_core_json.c:label_subgs
47
78
  */
48
- export function clusterNodeGid(n: Node, dfsSubs: readonly Graph[]): number {
49
- return dfsSubs.findIndex((sg) => sg.name === n.name && isACluster(sg));
79
+ export function labelSubgs(g: Graph, lbl: number, map: Map<string, number>, out: Graph[]): number {
80
+ if (g !== g.root) {
81
+ const gid = lbl++;
82
+ out.push(g);
83
+ if (isACluster(g)) insertCluster(map, g.name, gid);
84
+ }
85
+ for (const [, sg] of g.subgraphs) lbl = labelSubgs(sg, lbl, map, out);
86
+ return lbl;
50
87
  }
@@ -0,0 +1,51 @@
1
+ // SPDX-License-Identifier: EPL-2.0
2
+ /**
3
+ * The json writers' serialization step. C prints every draw-op number with
4
+ * `%.03f`, and on the oracle platform (macOS libc) that prints a non-finite
5
+ * double as the bare token `inf`, `-inf` or `nan` (a negative NaN prints
6
+ * `nan` too). `JSON.stringify` would print `null`, so the tree is serialized
7
+ * with those tokens instead. A document that holds one is not valid JSON,
8
+ * exactly as native's is not; a tree with no non-finite number serializes
9
+ * byte for byte as `JSON.stringify(tree, null, 2)`.
10
+ * @see plugin/core/gvrender_core_json.c:write_polyline (%.03f)
11
+ */
12
+
13
+ const JSON_INDENT = 2;
14
+
15
+ const INF_TOKEN = 'inf';
16
+ const NEG_INF_TOKEN = '-inf';
17
+ const NAN_TOKEN = 'nan';
18
+
19
+ /**
20
+ * Brackets a token while it travels through JSON.stringify as a string. A C
21
+ * string cannot hold NUL, so no attribute value cgraph could store spells a
22
+ * bracketed token.
23
+ */
24
+ const MARK = '\u0000';
25
+ /** MARK as JSON.stringify escapes it. */
26
+ const ESCAPED_MARK = JSON.stringify(MARK).slice(1, -1).replace(/\\/g, '\\\\');
27
+ /** A whole string value that is one bracketed token. */
28
+ const QUOTED_TOKEN = new RegExp(
29
+ `"${ESCAPED_MARK}(${INF_TOKEN}|${NEG_INF_TOKEN}|${NAN_TOKEN})${ESCAPED_MARK}"`, 'g',
30
+ );
31
+
32
+ /** What C's `%.03f` prints for a non-finite double. */
33
+ function nonFiniteToken(v: number): string {
34
+ if (Number.isNaN(v)) return NAN_TOKEN;
35
+ return v > 0 ? INF_TOKEN : NEG_INF_TOKEN;
36
+ }
37
+
38
+ /**
39
+ * `JSON.stringify(tree, null, 2)`, except that a non-finite number prints as
40
+ * C's `%.03f` token.
41
+ * @see plugin/core/gvrender_core_json.c:write_polyline (%.03f)
42
+ */
43
+ export function stringifyJsonTree(tree: unknown): string {
44
+ let sawNonFinite = false;
45
+ const text = JSON.stringify(tree, (_key, v: unknown) => {
46
+ if (typeof v !== 'number' || Number.isFinite(v)) return v;
47
+ sawNonFinite = true;
48
+ return `${MARK}${nonFiniteToken(v)}${MARK}`;
49
+ }, JSON_INDENT);
50
+ return sawNonFinite ? text.replace(QUOTED_TOKEN, '$1') : text;
51
+ }