11package kicad
22
3- import "strings"
3+ import (
4+ "strconv"
5+ "strings"
6+ )
47
58// Index maps a footprint's UUID (the wire identity -- see
69// docs/architecture/session-and-protocol.md's "The object model: UUID is
@@ -10,26 +13,113 @@ import "strings"
1013// legal).
1114type Index map [string ]Node
1215
13- // BuildIndex walks root (a parsed kicad_pcb list) and indexes every
14- // footprint by its identity value. Built once during ingest so mutation
15- // lookup is O(1); ref is never used as a key, since reference designators
16- // are not unique (REF**, duplicates are legal). Footprint-only: Phase 1's
17- // MOVE/ROTATE/FLIP are only ever valid against a footprint, and existing
18- // code (e.g. Flip's own corpus tests) assumes every entry in this index is
19- // one. Phase 2's broader object lifecycle protocol (see
20- // docs/architecture/session-and-protocol.md), which
21- // needs to reach segment/via/etc. by UUID too, uses BuildFullIndex instead.
22- func BuildIndex (root Node ) Index {
23- idx := make (Index )
16+ // topLevelPathPrefix marks a synthetic, position-derived identity (see
17+ // ResolveTopLevelIdentities) so it can never collide with a real
18+ // (uuid ...)/(tstamp ...) string, which never contains a NUL byte.
19+ const topLevelPathPrefix = "\x00 path:"
20+
21+ // topLevelPathIdentity is the derived-path fallback for a root-level node
22+ // with no usable native identity: its 0-based ordinal position among ALL
23+ // of root's direct children (not just kind-matching ones, so the same
24+ // position means the same thing regardless of which caller -- BuildIndex,
25+ // BuildFullIndex, BuildSchematicIndex, internal/view -- is asking).
26+ func topLevelPathIdentity (pos int ) string {
27+ return topLevelPathPrefix + strconv .Itoa (pos )
28+ }
29+
30+ // ResolveTopLevelIdentities computes, in one pass over root's direct
31+ // children, the final identity string for every child keep accepts --
32+ // the shared rule BuildIndex, BuildFullIndex and BuildSchematicIndex all
33+ // apply, and the one internal/view must also apply when it shows/sends a
34+ // node's id externally, so a value shown to a client and a value looked up
35+ // server-side always agree.
36+ //
37+ // The rule: a node's own (uuid ...)/(tstamp ...) value when it is present
38+ // AND unique among ALL of root's children (not merely unique among
39+ // keep-matching ones -- a real uuid is meant to be globally unique, not
40+ // unique-per-kind) -- otherwise a synthetic topLevelPathIdentity fallback.
41+ //
42+ // The fallback covers two real, corpus-confirmed cases, not one:
43+ //
44+ // - No native identity at all. docs/architecture.md Part III §3.3:
45+ // filmscanner.kicad_pcb (real, MIT-licensed, on the write allowlist)
46+ // has real footprint and gr_text nodes with neither field. Previously
47+ // these were silently omitted from every Index -- untargetable by
48+ // MOVE_COMPONENT/DELETE_OBJECT/EDIT_OBJECT and invisible to
49+ // internal/view -- not merely unresolvable by a stale key.
50+ // - A native identity that collides with a sibling's.
51+ // blemoisture.kicad_pcb (real, pre-KiCad-6 `(version 20160815)`
52+ // export) has three separate real (zone ...) nodes sharing the
53+ // literal legacy placeholder (tstamp 0) -- a real identity collision
54+ // in the wild, not synthetic test data; KiCad 6 introduced per-object
55+ // UUIDs specifically because this class of bug was possible in the
56+ // older tstamp scheme. Keying on "0" as-is would silently alias all
57+ // three to one Index slot (whichever was walked last); each now gets
58+ // its own derived key instead.
59+ //
60+ // Position is stable for the life of a parsed Document: root's children
61+ // are only ever appended to, never reordered or spliced
62+ // (docs/architecture.md §3.5), and a faithful structural copy
63+ // (kicad.Document.CopyFrom, used to snapshot overlay.Base -- see
64+ // internal/session/overlay_base.go) preserves child order for the same
65+ // underlying reason byte-exact serialization requires it to. So this key
66+ // means the same thing computed against either document, for any node
67+ // present in both -- the property internal/session/overlay_base.go's
68+ // baseSnapshot depends on for every OTHER node kind already.
69+ //
70+ // Returns both directions: byIdentity for BuildIndex-family callers
71+ // (string -> Node, the shape Index already is), byNode for callers like
72+ // internal/view that hold a Node and need to show/send its id (Node is a
73+ // small comparable value -- a document pointer and an arena index -- so
74+ // it's a valid map key).
75+ func ResolveTopLevelIdentities (root Node , keep func (Node ) bool ) (byIdentity map [string ]Node , byNode map [Node ]string ) {
76+ type entry struct {
77+ node Node
78+ native string
79+ }
80+ var all []entry
81+ counts := map [string ]int {}
2482 for c := range root .Children () {
25- if c .Kind () != KindList || c .Head () != "footprint" {
83+ native := ""
84+ if c .Kind () == KindList {
85+ native = NodeIdentity (c )
86+ }
87+ if native != "" {
88+ counts [native ]++
89+ }
90+ all = append (all , entry {node : c , native : native })
91+ }
92+ byIdentity = make (map [string ]Node )
93+ byNode = make (map [Node ]string )
94+ for pos , e := range all {
95+ if ! keep (e .node ) {
2696 continue
2797 }
28- if id := NodeIdentity (c ); id != "" {
29- idx [id ] = c
98+ id := e .native
99+ if id == "" || counts [id ] > 1 {
100+ id = topLevelPathIdentity (pos )
30101 }
102+ byIdentity [id ] = e .node
103+ byNode [e .node ] = id
31104 }
32- return idx
105+ return byIdentity , byNode
106+ }
107+
108+ // BuildIndex walks root (a parsed kicad_pcb list) and indexes every
109+ // footprint by its identity value (see ResolveTopLevelIdentities for the
110+ // native-value-or-derived-path rule). Built once during ingest so
111+ // mutation lookup is O(1); ref is never used as a key, since reference
112+ // designators are not unique (REF**, duplicates are legal). Footprint-only:
113+ // Phase 1's MOVE/ROTATE/FLIP are only ever valid against a footprint, and
114+ // existing code (e.g. Flip's own corpus tests) assumes every entry in this
115+ // index is one. Phase 2's broader object lifecycle protocol (see
116+ // docs/architecture/session-and-protocol.md), which
117+ // needs to reach segment/via/etc. by UUID too, uses BuildFullIndex instead.
118+ func BuildIndex (root Node ) Index {
119+ byIdentity , _ := ResolveTopLevelIdentities (root , func (n Node ) bool {
120+ return n .Kind () == KindList && n .Head () == "footprint"
121+ })
122+ return Index (byIdentity )
33123}
34124
35125// fullyIndexedTopLevelKinds are the top-level node types Phase 2's object
@@ -62,16 +152,10 @@ var fullyIndexedTopLevelKinds = map[string]bool{
62152// (at ...) node too, so without that check a MOVE_COMPONENT sent against a
63153// via's UUID would silently succeed at the wrong semantic).
64154func BuildFullIndex (root Node ) Index {
65- idx := make (Index )
66- for c := range root .Children () {
67- if c .Kind () != KindList || ! fullyIndexedTopLevelKinds [c .Head ()] {
68- continue
69- }
70- if id := NodeIdentity (c ); id != "" {
71- idx [id ] = c
72- }
73- }
74- return idx
155+ byIdentity , _ := ResolveTopLevelIdentities (root , func (n Node ) bool {
156+ return n .Kind () == KindList && fullyIndexedTopLevelKinds [n .Head ()]
157+ })
158+ return Index (byIdentity )
75159}
76160
77161// schematicIndexedTopLevelKinds are the top-level node types Phase 3's
@@ -99,16 +183,10 @@ var schematicIndexedTopLevelKinds = map[string]bool{
99183// indexes every top-level node schsession.Session can create/delete/edit
100184// by its identity value.
101185func BuildSchematicIndex (root Node ) Index {
102- idx := make (Index )
103- for c := range root .Children () {
104- if c .Kind () != KindList || ! schematicIndexedTopLevelKinds [c .Head ()] {
105- continue
106- }
107- if id := NodeIdentity (c ); id != "" {
108- idx [id ] = c
109- }
110- }
111- return idx
186+ byIdentity , _ := ResolveTopLevelIdentities (root , func (n Node ) bool {
187+ return n .Kind () == KindList && schematicIndexedTopLevelKinds [n .Head ()]
188+ })
189+ return Index (byIdentity )
112190}
113191
114192// NodeIdentity returns a top-level node's identity value (its (uuid ...) or
0 commit comments