symbols.go raw
1 package iskra
2
3 import (
4 "bytes"
5 "sort"
6 )
7
8 // Symbol kinds.
9 const (
10 SymDecl uint8 = 1
11 SymRef uint8 = 2
12 SymParam uint8 = 3
13 )
14
15 // Symbol is one named occurrence in an AST dump.
16 type Symbol struct {
17 Name string
18 Depth int32
19 Kind uint8
20 }
21
22 // SymbolTable is the flat symbol stream of one function, plus its declared
23 // types and the reference-sequence fingerprint.
24 type SymbolTable struct {
25 Symbols []Symbol
26 Counts map[string]int32
27 ParamTypes []string
28 ResultTypes []string
29 RecvType string
30 RefSeqHash uint64
31 }
32
33 // ExternalRef is a name referenced but never declared in the function.
34 type ExternalRef struct {
35 Name string
36 RefCount int32
37 Depths []int32
38 }
39
40 // Binding is one declaration and the depths of its references.
41 type Binding struct {
42 DeclDepth int32
43 RefDepths []int32
44 }
45
46 // BindingGraph is the full binding structure of a function.
47 type BindingGraph struct {
48 Bindings []Binding
49 Externals []ExternalRef
50 }
51
52 // LocalSig is one binding in the order-erased signature.
53 type LocalSig struct {
54 DeclDepth int32
55 RefDepths []int32
56 }
57
58 // ExternSig is one external in the order-erased signature.
59 type ExternSig struct {
60 RefCount int32
61 Depths []int32
62 }
63
64 // BindingSignature is the order- and name-erased fingerprint.
65 type BindingSignature struct {
66 Locals []LocalSig
67 Externs []ExternSig
68 ParamTypes []string
69 ResultTypes []string
70 RecvType string
71 ExternNames []string
72 RefSeqHash uint64
73 }
74
75 // ExtractSymbols parses a .mx AST dump into a symbol table. symbols.mx
76 // ExtractSymbols, line for line.
77 func ExtractSymbols(astDump string) *SymbolTable {
78 st := &SymbolTable{Counts: make(map[string]int32)}
79 lines := bytes.Split([]byte(astDump), []byte("\n"))
80 inParams, inResults := false, false
81 sectionDepth := int32(-1)
82 paramOrd := map[string]int32{}
83 resultOrd := map[string]int32{}
84 localOrd := map[string]int32{}
85 var refSeq []byte
86
87 for _, line := range lines {
88 if len(line) == 0 {
89 continue
90 }
91 d := countIndent(line)
92 trimmed := bytes.TrimSpace(line)
93 if (inParams || inResults) && d <= sectionDepth {
94 inParams, inResults = false, false
95 }
96 switch {
97 case bytes.HasPrefix(trimmed, []byte("FuncDecl ")):
98 name := string(trimmed[9:])
99 if idx := bytes.IndexByte(trimmed[9:], ' '); idx >= 0 {
100 name = string(trimmed[9 : 9+idx])
101 }
102 addSym(st, name, d, SymDecl)
103 if ri := bytes.Index(trimmed, []byte("recv=")); ri >= 0 {
104 rt := trimmed[ri+5:]
105 if si := bytes.IndexByte(rt, ' '); si >= 0 {
106 rt = rt[:si]
107 }
108 st.RecvType = string(rt)
109 }
110 case bytes.HasPrefix(trimmed, []byte("Params")):
111 inParams, inResults, sectionDepth = true, false, d
112 case bytes.HasPrefix(trimmed, []byte("Results")):
113 inResults, inParams, sectionDepth = true, false, d
114 case inParams && d > sectionDepth:
115 if typeName := extractTypeFromParamLine(trimmed); typeName != "" {
116 st.ParamTypes = append(st.ParamTypes, typeName)
117 }
118 for _, n := range extractParamNames(trimmed) {
119 paramOrd[n] = int32(len(paramOrd))
120 }
121 parseParamLine(st, trimmed, d)
122 case inResults && d > sectionDepth:
123 if typeName := extractTypeFromParamLine(trimmed); typeName != "" {
124 st.ResultTypes = append(st.ResultTypes, typeName)
125 }
126 if isParamLine(trimmed) {
127 for _, n := range extractParamNames(trimmed) {
128 resultOrd[n] = int32(len(resultOrd))
129 }
130 parseParamLine(st, trimmed, d)
131 }
132 case bytes.HasPrefix(trimmed, []byte("Assign ")):
133 rest := trimmed[7:]
134 if spIdx := bytes.IndexByte(rest, ' '); spIdx > 0 {
135 for _, p := range bytes.Split(rest[:spIdx], []byte(",")) {
136 nm := string(bytes.TrimSpace(p))
137 if nm == "" {
138 continue
139 }
140 if _, ok := localOrd[nm]; ok {
141 continue
142 }
143 if _, ok := paramOrd[nm]; ok {
144 continue
145 }
146 if _, ok := resultOrd[nm]; ok {
147 continue
148 }
149 localOrd[nm] = int32(len(localOrd))
150 }
151 }
152 refSeq = appendRefFingerprint(refSeq, trimmed, paramOrd, resultOrd, localOrd)
153 parseAssign(st, trimmed, d)
154 case bytes.HasPrefix(trimmed, []byte("Return")):
155 refSeq = appendRefFingerprint(refSeq, trimmed, paramOrd, resultOrd, localOrd)
156 parseRefs(st, trimmed, d)
157 case bytes.HasPrefix(trimmed, []byte("If")):
158 refSeq = appendRefFingerprint(refSeq, trimmed, paramOrd, resultOrd, localOrd)
159 parseRefs(st, trimmed, d)
160 case bytes.HasPrefix(trimmed, []byte("For")):
161 refSeq = appendRefFingerprint(refSeq, trimmed, paramOrd, resultOrd, localOrd)
162 parseRefs(st, trimmed, d)
163 case bytes.HasPrefix(trimmed, []byte("Range ")):
164 refSeq = appendRefFingerprint(refSeq, trimmed, paramOrd, resultOrd, localOrd)
165 parseRefs(st, trimmed, d)
166 case bytes.HasPrefix(trimmed, []byte("Expr ")):
167 refSeq = appendRefFingerprint(refSeq, trimmed, paramOrd, resultOrd, localOrd)
168 parseRefs(st, trimmed, d)
169 case bytes.HasPrefix(trimmed, []byte("Case")):
170 refSeq = appendRefFingerprint(refSeq, trimmed, paramOrd, resultOrd, localOrd)
171 parseRefs(st, trimmed, d)
172 case bytes.HasPrefix(trimmed, []byte("Switch")):
173 refSeq = appendRefFingerprint(refSeq, trimmed, paramOrd, resultOrd, localOrd)
174 parseRefs(st, trimmed, d)
175 case bytes.HasPrefix(trimmed, []byte("Value ")):
176 parseParamLine(st, trimmed[6:], d)
177 case isParamLine(trimmed):
178 parseParamLine(st, trimmed, d)
179 }
180 }
181 if len(refSeq) > 0 && !allSeparators(refSeq) {
182 st.RefSeqHash = fnvHash64(refSeq)
183 }
184 return st
185 }
186
187 // ExtractBindings resolves references to the nearest declaration of the name,
188 // in symbol order. This is the one-pass approximation symbols.mx uses: it
189 // registers every declaration and every parameter first, then walks the refs.
190 func ExtractBindings(st *SymbolTable) *BindingGraph {
191 bg := &BindingGraph{}
192 localIdx := make(map[string]int32)
193 extIdx := make(map[string]int32)
194 for _, sym := range st.Symbols {
195 if sym.Kind == SymDecl || sym.Kind == SymParam {
196 localIdx[sym.Name] = int32(len(bg.Bindings))
197 bg.Bindings = append(bg.Bindings, Binding{DeclDepth: sym.Depth})
198 }
199 }
200 for _, sym := range st.Symbols {
201 if sym.Kind != SymRef {
202 continue
203 }
204 if idx, ok := localIdx[sym.Name]; ok {
205 bg.Bindings[idx].RefDepths = append(bg.Bindings[idx].RefDepths, sym.Depth)
206 continue
207 }
208 if ei, ok := extIdx[sym.Name]; ok {
209 bg.Externals[ei].RefCount++
210 bg.Externals[ei].Depths = append(bg.Externals[ei].Depths, sym.Depth)
211 continue
212 }
213 extIdx[sym.Name] = int32(len(bg.Externals))
214 bg.Externals = append(bg.Externals, ExternalRef{Name: sym.Name, RefCount: 1, Depths: []int32{sym.Depth}})
215 }
216 return bg
217 }
218
219 // Signature erases names and orders the bindings.
220 func (bg *BindingGraph) Signature() *BindingSignature {
221 sig := &BindingSignature{}
222 for _, b := range bg.Bindings {
223 depths := append([]int32{}, b.RefDepths...)
224 sort.Slice(depths, func(i, j int) bool { return depths[i] < depths[j] })
225 sig.Locals = append(sig.Locals, LocalSig{DeclDepth: b.DeclDepth, RefDepths: depths})
226 }
227 for _, e := range bg.Externals {
228 depths := append([]int32{}, e.Depths...)
229 sort.Slice(depths, func(i, j int) bool { return depths[i] < depths[j] })
230 sig.Externs = append(sig.Externs, ExternSig{RefCount: e.RefCount, Depths: depths})
231 }
232 sort.SliceStable(sig.Locals, func(i, j int) bool { return cmpLocalSig(sig.Locals[i], sig.Locals[j]) < 0 })
233 sort.SliceStable(sig.Externs, func(i, j int) bool { return cmpExternSig(sig.Externs[i], sig.Externs[j]) < 0 })
234 return sig
235 }
236
237 // SignatureWithTypes is Signature plus the declared types, the receiver and
238 // the sorted external names, as InsertSegment stores for the AST stage.
239 func SignatureWithTypes(st *SymbolTable) *BindingSignature {
240 bg := ExtractBindings(st)
241 sig := bg.Signature()
242 sig.ParamTypes = append(sig.ParamTypes, st.ParamTypes...)
243 sig.ResultTypes = append(sig.ResultTypes, st.ResultTypes...)
244 sig.RecvType = st.RecvType
245 for _, e := range bg.Externals {
246 sig.ExternNames = append(sig.ExternNames, e.Name)
247 }
248 sort.Strings(sig.ExternNames)
249 sig.RefSeqHash = st.RefSeqHash
250 return sig
251 }
252
253 // IsIsomorphic compares two signatures field for field.
254 func (a *BindingSignature) IsIsomorphic(b *BindingSignature) bool {
255 if len(a.Locals) != len(b.Locals) || len(a.Externs) != len(b.Externs) {
256 return false
257 }
258 for i := range a.Locals {
259 if a.Locals[i].DeclDepth != b.Locals[i].DeclDepth || !int32sEqual(a.Locals[i].RefDepths, b.Locals[i].RefDepths) {
260 return false
261 }
262 }
263 for i := range a.Externs {
264 if a.Externs[i].RefCount != b.Externs[i].RefCount || !int32sEqual(a.Externs[i].Depths, b.Externs[i].Depths) {
265 return false
266 }
267 }
268 if !stringsEqual(a.ParamTypes, b.ParamTypes) || !stringsEqual(a.ResultTypes, b.ResultTypes) {
269 return false
270 }
271 if a.RecvType != b.RecvType || !stringsEqual(a.ExternNames, b.ExternNames) {
272 return false
273 }
274 if a.RefSeqHash != 0 && b.RefSeqHash != 0 && a.RefSeqHash != b.RefSeqHash {
275 return false
276 }
277 return true
278 }
279
280 // GeometricDistance is the divergence between two signatures, 0 for
281 // isomorphic.
282 func GeometricDistance(a, b *BindingSignature) int32 {
283 var dist int32
284 minL := len(a.Locals)
285 if len(b.Locals) < minL {
286 minL = len(b.Locals)
287 }
288 for i := 0; i < minL; i++ {
289 if a.Locals[i].DeclDepth != b.Locals[i].DeclDepth {
290 dist++
291 }
292 dist += int32SliceDistance(a.Locals[i].RefDepths, b.Locals[i].RefDepths)
293 }
294 if len(a.Locals) > len(b.Locals) {
295 dist += int32(len(a.Locals) - len(b.Locals))
296 } else {
297 dist += int32(len(b.Locals) - len(a.Locals))
298 }
299 minE := len(a.Externs)
300 if len(b.Externs) < minE {
301 minE = len(b.Externs)
302 }
303 for i := 0; i < minE; i++ {
304 d := a.Externs[i].RefCount - b.Externs[i].RefCount
305 if d < 0 {
306 d = -d
307 }
308 dist += d + int32SliceDistance(a.Externs[i].Depths, b.Externs[i].Depths)
309 }
310 if len(a.Externs) > len(b.Externs) {
311 dist += int32(len(a.Externs) - len(b.Externs))
312 } else {
313 dist += int32(len(b.Externs) - len(a.Externs))
314 }
315 return dist
316 }
317
318 // SignatureHash24 is the 24-bit fast-rejection hash of a signature.
319 func SignatureHash24(sig *BindingSignature) uint32 {
320 h := uint32(0x811c9dc5)
321 mix := func(b byte) {
322 h ^= uint32(b)
323 h *= 0x01000193
324 }
325 mix(byte(len(sig.Locals)))
326 for _, l := range sig.Locals {
327 mix(byte(l.DeclDepth))
328 mix(byte(l.DeclDepth >> 8))
329 mix(byte(len(l.RefDepths)))
330 for _, d := range l.RefDepths {
331 mix(byte(d))
332 mix(byte(d >> 8))
333 }
334 }
335 mix(byte(len(sig.Externs)))
336 for _, e := range sig.Externs {
337 mix(byte(e.RefCount))
338 mix(byte(e.RefCount >> 8))
339 for _, d := range e.Depths {
340 mix(byte(d))
341 mix(byte(d >> 8))
342 }
343 }
344 for _, c := range []byte(sig.RecvType) {
345 mix(c)
346 }
347 for _, name := range sig.ExternNames {
348 for _, c := range []byte(name) {
349 mix(c)
350 }
351 mix(0xFF)
352 }
353 for i := 0; i < 8; i++ {
354 mix(byte(sig.RefSeqHash >> (8 * uint(i))))
355 }
356 return h & 0xFFFFFF
357 }
358
359 func countIndent(line []byte) int32 {
360 var n int32
361 i := 0
362 for i+1 < len(line) && line[i] == ' ' && line[i+1] == ' ' {
363 n++
364 i += 2
365 }
366 return n
367 }
368
369 func isParamLine(trimmed []byte) bool {
370 if len(trimmed) == 0 {
371 return false
372 }
373 if trimmed[0] >= 'a' && trimmed[0] <= 'z' {
374 return bytes.IndexByte(trimmed, ' ') > 0
375 }
376 return false
377 }
378
379 func parseParamLine(st *SymbolTable, trimmed []byte, depth int32) {
380 idx := bytes.IndexByte(trimmed, ' ')
381 if idx <= 0 {
382 return
383 }
384 for _, p := range bytes.Split(trimmed[:idx], []byte(",")) {
385 if p = bytes.TrimSpace(p); len(p) > 0 {
386 addSym(st, string(p), depth, SymParam)
387 }
388 }
389 }
390
391 func parseAssign(st *SymbolTable, trimmed []byte, depth int32) {
392 rest := trimmed[7:]
393 spIdx := bytes.IndexByte(rest, ' ')
394 if spIdx <= 0 {
395 return
396 }
397 for _, p := range bytes.Split(rest[:spIdx], []byte(",")) {
398 if p = bytes.TrimSpace(p); len(p) > 0 {
399 addSym(st, string(p), depth, SymDecl)
400 }
401 }
402 parseRefs(st, trimmed, depth)
403 }
404
405 func parseRefs(st *SymbolTable, trimmed []byte, depth int32) {
406 start := bytes.IndexByte(trimmed, '[')
407 if start < 0 {
408 return
409 }
410 rel := bytes.IndexByte(trimmed[start:], ']')
411 if rel < 0 {
412 return
413 }
414 for _, p := range bytes.Split(trimmed[start+1:start+rel], []byte(",")) {
415 if p = bytes.TrimSpace(p); len(p) > 0 {
416 addSym(st, string(p), depth, SymRef)
417 }
418 }
419 }
420
421 func addSym(st *SymbolTable, name string, depth int32, kind uint8) {
422 st.Symbols = append(st.Symbols, Symbol{Name: name, Depth: depth, Kind: kind})
423 st.Counts[name]++
424 }
425
426 func extractParamNames(line []byte) []string {
427 idx := bytes.IndexByte(line, ' ')
428 if idx <= 0 {
429 return nil
430 }
431 var names []string
432 for _, p := range bytes.Split(line[:idx], []byte(",")) {
433 p = bytes.TrimSpace(p)
434 if len(p) > 0 && p[0] >= 'a' && p[0] <= 'z' {
435 names = append(names, string(p))
436 }
437 }
438 return names
439 }
440
441 func extractTypeFromParamLine(line []byte) string {
442 idx := bytes.IndexByte(line, ' ')
443 if idx < 0 {
444 return string(line)
445 }
446 before := line[:idx]
447 if before[0] == '[' || before[0] == '*' || bytes.HasPrefix(before, []byte("map")) ||
448 bytes.HasPrefix(before, []byte("chan")) || bytes.HasPrefix(before, []byte("func")) {
449 return string(line)
450 }
451 return string(line[idx+1:])
452 }
453
454 func appendRefFingerprint(seq, line []byte, paramOrd, resultOrd, localOrd map[string]int32) []byte {
455 start := bytes.IndexByte(line, '[')
456 if start < 0 {
457 return append(seq, '|')
458 }
459 rel := bytes.IndexByte(line[start:], ']')
460 if rel < 0 {
461 return append(seq, '|')
462 }
463 for i, p := range bytes.Split(line[start+1:start+rel], []byte(",")) {
464 p = bytes.TrimSpace(p)
465 if i > 0 {
466 seq = append(seq, ',')
467 }
468 name := string(p)
469 switch {
470 case has(paramOrd, name):
471 seq = append(seq, 'P')
472 seq = append(seq, intToStr(paramOrd[name])...)
473 case has(resultOrd, name):
474 seq = append(seq, 'R')
475 seq = append(seq, intToStr(resultOrd[name])...)
476 case has(localOrd, name):
477 seq = append(seq, 'L')
478 seq = append(seq, intToStr(localOrd[name])...)
479 default:
480 seq = append(seq, p...)
481 }
482 }
483 return append(seq, '|')
484 }
485
486 func has(m map[string]int32, k string) bool { _, ok := m[k]; return ok }
487
488 func allSeparators(b []byte) bool {
489 for _, c := range b {
490 if c != '|' {
491 return false
492 }
493 }
494 return true
495 }
496
497 func fnvHash64(data []byte) uint64 {
498 h := uint64(0xcbf29ce484222325)
499 for _, b := range data {
500 h ^= uint64(b)
501 h *= 0x100000001b3
502 }
503 return h
504 }
505
506 func intToStr(v int32) string {
507 if v == 0 {
508 return "0"
509 }
510 var buf [12]byte
511 i := len(buf)
512 neg := v < 0
513 if neg {
514 v = -v
515 }
516 for v > 0 {
517 i--
518 buf[i] = byte('0' + v%10)
519 v /= 10
520 }
521 if neg {
522 i--
523 buf[i] = '-'
524 }
525 return string(buf[i:])
526 }
527
528 func int32sEqual(a, b []int32) bool {
529 if len(a) != len(b) {
530 return false
531 }
532 for i := range a {
533 if a[i] != b[i] {
534 return false
535 }
536 }
537 return true
538 }
539
540 func stringsEqual(a, b []string) bool {
541 if len(a) != len(b) {
542 return false
543 }
544 for i := range a {
545 if a[i] != b[i] {
546 return false
547 }
548 }
549 return true
550 }
551
552 func int32SliceDistance(a, b []int32) int32 {
553 var dist int32
554 minN := len(a)
555 if len(b) < minN {
556 minN = len(b)
557 }
558 for i := 0; i < minN; i++ {
559 d := a[i] - b[i]
560 if d < 0 {
561 d = -d
562 }
563 dist += d
564 }
565 if len(a) > len(b) {
566 dist += int32(len(a) - len(b))
567 } else {
568 dist += int32(len(b) - len(a))
569 }
570 return dist
571 }
572
573 func cmpLocalSig(a, b LocalSig) int {
574 if a.DeclDepth != b.DeclDepth {
575 if a.DeclDepth < b.DeclDepth {
576 return -1
577 }
578 return 1
579 }
580 if len(a.RefDepths) != len(b.RefDepths) {
581 return len(a.RefDepths) - len(b.RefDepths)
582 }
583 for i := range a.RefDepths {
584 if a.RefDepths[i] != b.RefDepths[i] {
585 if a.RefDepths[i] < b.RefDepths[i] {
586 return -1
587 }
588 return 1
589 }
590 }
591 return 0
592 }
593
594 func cmpExternSig(a, b ExternSig) int {
595 if a.RefCount != b.RefCount {
596 if a.RefCount < b.RefCount {
597 return -1
598 }
599 return 1
600 }
601 if len(a.Depths) != len(b.Depths) {
602 return len(a.Depths) - len(b.Depths)
603 }
604 for i := range a.Depths {
605 if a.Depths[i] != b.Depths[i] {
606 if a.Depths[i] < b.Depths[i] {
607 return -1
608 }
609 return 1
610 }
611 }
612 return 0
613 }
614