code.go raw
1 package main
2
3 import (
4 "fmt"
5 "os"
6 "strings"
7 "time"
8
9 "git.smesh.lol/go-iskra/iskra"
10 "git.smesh.lol/go-iskra/lattice"
11 )
12
13 // dbFlag pulls --db <path> out of args and returns the rest.
14 func dbFlag(args []string) (string, []string) {
15 var db string
16 rest := make([]string, 0, len(args))
17 for i := 0; i < len(args); i++ {
18 if args[i] == "--db" && i+1 < len(args) {
19 db = args[i+1]
20 i++
21 continue
22 }
23 if strings.HasPrefix(args[i], "--db=") {
24 db = strings.TrimPrefix(args[i], "--db=")
25 continue
26 }
27 rest = append(rest, args[i])
28 }
29 return db, rest
30 }
31
32 func cmdLoad(args []string) error {
33 db, args := dbFlag(args)
34 if len(args) < 1 {
35 return fmt.Errorf("usage: iskra load <corpus-dir[,corpus-dir...]> [--db <path>]")
36 }
37 dirs := strings.Split(args[0], ",")
38 start := time.Now()
39 var st *iskra.Storage
40 var err error
41 if db != "" {
42 st, err = iskra.StorageCreate(db)
43 } else {
44 t := lattice.NewTree(256)
45 st = &iskra.Storage{T: iskra.NewTree(t)}
46 }
47 if err != nil {
48 return err
49 }
50 total := 0
51 for _, dir := range dirs {
52 c, err := iskra.LoadCorpus(dir)
53 if err != nil {
54 return err
55 }
56 n, err := iskra.LoadCorpusIntoF(c, st.T, 0xFF)
57 if err != nil {
58 return err
59 }
60 total += n
61 fmt.Printf("%s: %d segments loaded\n", dir, n)
62 }
63 if err := iskra.FinalizeCorpus(st.T); err != nil {
64 return err
65 }
66 if db != "" {
67 if err := st.Flush(); err != nil {
68 return err
69 }
70 }
71 fmt.Printf("lattice: %d records, %d blocks, %d tokens, %d dict entries\n",
72 st.T.DB.RecordCount(), st.T.DB.NodeCount(), len(st.T.TokenPool), st.T.Dict.EntryCount())
73 fmt.Printf("loaded in %s\n", time.Since(start).Round(time.Millisecond))
74 printLatticeStats(st)
75 return nil
76 }
77
78 func cmdStats(args []string) error {
79 db, args := dbFlag(args)
80 if db == "" {
81 if len(args) < 1 {
82 return fmt.Errorf("usage: iskra stats <db-path>")
83 }
84 db = args[0]
85 }
86 st, err := openDB(db)
87 if err != nil {
88 return err
89 }
90 defer st.T.DB.Close()
91 printLatticeStats(st)
92 return nil
93 }
94
95 func printLatticeStats(st *iskra.Storage) {
96 t := st.T
97 fmt.Printf("records: %d blocks: %d tokens: %d dict: %d\n",
98 t.DB.RecordCount(), t.DB.NodeCount(), len(t.TokenPool), t.Dict.EntryCount())
99 stages := map[uint8]int{}
100 branches := map[lattice.Branch]int{}
101 for b := 0; b < lattice.C; b++ {
102 br := lattice.Branch(b)
103 e, err := t.DB.BranchEntries(br)
104 if err != nil {
105 continue
106 }
107 branches[br] = len(e)
108 for _, en := range e {
109 if uint64(en.RecIdx) < uint64(len(t.RecMeta)) {
110 stages[t.RecMeta[en.RecIdx].StageTag]++
111 }
112 }
113 }
114 fmt.Printf("by branch: ")
115 for b := 0; b < lattice.C; b++ {
116 fmt.Printf("%d=%d ", b, branches[lattice.Branch(b)])
117 }
118 fmt.Println()
119 fmt.Printf("by stage: ")
120 for _, s := range []uint8{0, 1, 2, 3, 4, 5} {
121 if n, ok := stages[s]; ok {
122 fmt.Printf("%s=%d ", iskra.StageName(s), n)
123 }
124 }
125 fmt.Println()
126 fmt.Printf("sig index buckets: %d\n", len(t.SigIdx))
127 }
128
129 func cmdAudit(args []string) error {
130 if len(args) < 1 {
131 return fmt.Errorf("usage: iskra audit <stdlib-dir>")
132 }
133 root := args[0]
134 found := 0
135 top, err := os.ReadDir(root)
136 if err != nil {
137 return err
138 }
139 for _, e := range top {
140 if !e.IsDir() {
141 continue
142 }
143 sub := root + "/" + e.Name()
144 if _, err := os.Stat(sub + "/ast"); err == nil {
145 rep, err := iskra.AuditCorpus(sub)
146 if err != nil {
147 return err
148 }
149 printAudit(e.Name(), rep)
150 found++
151 continue
152 }
153 inner, _ := os.ReadDir(sub)
154 for _, ie := range inner {
155 if !ie.IsDir() {
156 continue
157 }
158 p := sub + "/" + ie.Name()
159 if _, err := os.Stat(p + "/ast"); err != nil {
160 continue
161 }
162 rep, err := iskra.AuditCorpus(p)
163 if err != nil {
164 return err
165 }
166 printAudit(e.Name()+"/"+ie.Name(), rep)
167 found++
168 }
169 }
170 if found == 0 {
171 return fmt.Errorf("no corpus with an ast/ directory under %s", root)
172 }
173 return nil
174 }
175
176 func printAudit(name string, r *iskra.AuditReport) {
177 fmt.Printf("=== %s ===\n", name)
178 fmt.Printf("functions: %d\n", r.Functions)
179 fmt.Printf("self-isomorphic: %d/%d (%d%%) (self-comparison, 100 by construction for any signature)\n",
180 r.SelfIso, r.Functions, r.SelfIsoRate())
181 fmt.Printf("distinct hash24: %d/%d (%d%%)\n", r.DistinctHash24, r.Functions, r.HashUniqueness())
182 fmt.Printf("isomorphic pairs: %d/%d compared (%d%%)\n", r.IsoCollisions, r.PairsChecked, pct(r.IsoCollisions, r.PairsChecked))
183 fmt.Printf("local bindings: %d external refs: %d\n", r.TotalLocals, r.TotalExternals)
184 fmt.Printf("largest by bindings: %s (%d)\n", r.LargestFuncName, r.LargestLocals)
185 }
186
187 func pct(a, b int) int {
188 if b == 0 {
189 return 0
190 }
191 return a * 100 / b
192 }
193
194 // resolve finds a record index by name at a stage, or searches every stage.
195 func resolve(st *iskra.Storage, name string, stage uint8) (uint32, uint8, error) {
196 stages := []uint8{iskra.StageSRC, iskra.StageAST, iskra.StageIR, iskra.StageASM, iskra.StageBIN}
197 if stage != 0 {
198 stages = []uint8{stage}
199 }
200 for _, s := range stages {
201 ri, err := st.T.LookupRecIdxAny(iskra.NameKey(s, name))
202 if err != nil {
203 return lattice.NullRec, 0, err
204 }
205 if ri != lattice.NullRec {
206 return ri, s, nil
207 }
208 }
209 if stage != 0 {
210 return lattice.NullRec, stage, fmt.Errorf("%s not found at %s", name, iskra.StageName(stage))
211 }
212 return lattice.NullRec, 0, fmt.Errorf("%s not found at any stage", name)
213 }
214
215 func stageArg(s string) uint8 {
216 switch strings.ToLower(s) {
217 case "src":
218 return iskra.StageSRC
219 case "ast":
220 return iskra.StageAST
221 case "ir":
222 return iskra.StageIR
223 case "asm":
224 return iskra.StageASM
225 case "bin":
226 return iskra.StageBIN
227 }
228 return 0
229 }
230
231 func cmdLookup(args []string) error {
232 if len(args) < 2 {
233 return fmt.Errorf("usage: iskra lookup <db> <name> [stage]")
234 }
235 st, err := openDB(args[0])
236 if err != nil {
237 return err
238 }
239 defer st.T.DB.Close()
240 var stage uint8
241 if len(args) > 2 {
242 stage = stageArg(args[2])
243 }
244 ri, s, err := resolve(st, args[1], stage)
245 if err != nil {
246 return err
247 }
248 fmt.Printf("lookup %s at %s: record %d\n", args[1], iskra.StageName(s), ri)
249 if m := st.T.Meta(ri); m != nil {
250 fmt.Printf(" meta: kind %d stage %d refkind %d count %d sighash %06x content offset %d len %d\n",
251 m.Kind, m.StageTag, m.RefKind, m.Count, m.SigHash(), m.ContentOffset(), m.ContentLen())
252 }
253 branch, _ := branchOf(st, ri)
254 fmt.Printf(" branch: %d\n", branch)
255 links := st.T.StageLinksFor(branch, iskra.NameKey(s, args[1]))
256 if len(links) == 0 {
257 fmt.Println(" cross-stage links: none")
258 }
259 for _, l := range links {
260 fmt.Printf(" cross-stage: stage %s record %d form %q\n", iskra.StageName(stageOf(st, l)), l, st.T.Form(l))
261 }
262 return nil
263 }
264
265 // branchOf finds the branch a record sits in by looking it up in every branch
266 // and comparing record indices; the lattice stores no record-to-branch index.
267 func branchOf(st *iskra.Storage, ri uint32) (lattice.Branch, bool) {
268 for b := 0; b < lattice.C; b++ {
269 br := lattice.Branch(b)
270 e, err := st.T.DB.BranchEntries(br)
271 if err != nil {
272 continue
273 }
274 for _, en := range e {
275 if en.RecIdx == ri {
276 return br, true
277 }
278 }
279 }
280 return 0, false
281 }
282
283 func stageOf(st *iskra.Storage, ri uint32) uint8 {
284 if m := st.T.Meta(ri); m != nil {
285 return m.StageTag
286 }
287 return 0
288 }
289
290 func cmdLinks(args []string, dir string) error {
291 if len(args) < 2 {
292 return fmt.Errorf("usage: iskra %s <db> <name>", dir)
293 }
294 st, err := openDB(args[0])
295 if err != nil {
296 return err
297 }
298 defer st.T.DB.Close()
299 from, to := iskra.StageSRC, iskra.StageAST
300 if dir == "reverse" {
301 from, to = iskra.StageAST, iskra.StageSRC
302 }
303 ri, err := st.T.LookupRecIdxAny(iskra.NameKey(from, args[1]))
304 if err != nil {
305 return err
306 }
307 if ri == lattice.NullRec {
308 return fmt.Errorf("%s: no %s entry", args[1], iskra.StageName(from))
309 }
310 branch := kindBranch(st, ri)
311 hash := lattice.KeyHash(iskra.NameKey(from, args[1]))
312 ti, err := st.T.DB.LookupRecIdx(branch, lattice.MakeCodeKey(to, hash))
313 if err != nil {
314 return err
315 }
316 if ti == lattice.NullRec {
317 return fmt.Errorf("%s: no %s entry after %s", args[1], iskra.StageName(to), iskra.StageName(from))
318 }
319 fmt.Printf("%s -> %s: record %d\n", iskra.StageName(from), iskra.StageName(to), ti)
320 fmt.Printf("%s\n", string(st.T.Content(ti)))
321 return nil
322 }
323
324 func kindBranch(st *iskra.Storage, ri uint32) lattice.Branch {
325 if m := st.T.Meta(ri); m != nil {
326 return iskra.KindToBranch(m.Kind)
327 }
328 return lattice.Bnoun
329 }
330
331 func cmdContent(args []string) error {
332 if len(args) < 2 {
333 return fmt.Errorf("usage: iskra content <db> <name>")
334 }
335 st, err := openDB(args[0])
336 if err != nil {
337 return err
338 }
339 defer st.T.DB.Close()
340 shown := 0
341 for _, s := range []uint8{iskra.StageSRC, iskra.StageAST, iskra.StageIR, iskra.StageASM, iskra.StageBIN} {
342 ri, err := st.T.LookupRecIdxAny(iskra.NameKey(s, args[1]))
343 if err != nil {
344 return err
345 }
346 if ri == lattice.NullRec {
347 continue
348 }
349 shown++
350 body := st.T.Content(ri)
351 fmt.Printf("=== %s (record %d, %d bytes)\n%s\n", iskra.StageName(s), ri, len(body), string(body))
352 }
353 if shown == 0 {
354 return fmt.Errorf("%s not found at any stage", args[1])
355 }
356 return nil
357 }
358
359 func cmdFindSig(args []string) error {
360 if len(args) < 2 {
361 return fmt.Errorf("usage: iskra find-sig <db> <name>")
362 }
363 st, err := openDB(args[0])
364 if err != nil {
365 return err
366 }
367 defer st.T.DB.Close()
368 ri, err := st.T.LookupRecIdxAny(iskra.NameKey(iskra.StageAST, args[1]))
369 if err != nil {
370 return err
371 }
372 if ri == lattice.NullRec {
373 return fmt.Errorf("%s: no AST entry", args[1])
374 }
375 m := st.T.Meta(ri)
376 if m == nil {
377 return fmt.Errorf("%s: no metadata", args[1])
378 }
379 h := m.SigHash()
380 bucket := (uint32(m.StageTag) << 24) | h
381 matches := st.T.SigIdx[bucket]
382 fmt.Printf("%s signature hash %06x, %d same-bucket records\n", args[1], h, len(matches))
383 self := iskra.SignatureWithTypes(iskra.ExtractSymbols(string(st.T.Content(ri))))
384 for _, other := range matches {
385 if other == ri {
386 continue
387 }
388 osig := iskra.SignatureWithTypes(iskra.ExtractSymbols(string(st.T.Content(other))))
389 if self.IsIsomorphic(osig) {
390 fmt.Printf(" isomorphic: record %d\n", other)
391 } else {
392 fmt.Printf(" same hash, not isomorphic: record %d (distance %d)\n", other, iskra.GeometricDistance(self, osig))
393 }
394 }
395 return nil
396 }
397