package iskra import ( "bytes" "sort" ) // Symbol kinds. const ( SymDecl uint8 = 1 SymRef uint8 = 2 SymParam uint8 = 3 ) // Symbol is one named occurrence in an AST dump. type Symbol struct { Name string Depth int32 Kind uint8 } // SymbolTable is the flat symbol stream of one function, plus its declared // types and the reference-sequence fingerprint. type SymbolTable struct { Symbols []Symbol Counts map[string]int32 ParamTypes []string ResultTypes []string RecvType string RefSeqHash uint64 } // ExternalRef is a name referenced but never declared in the function. type ExternalRef struct { Name string RefCount int32 Depths []int32 } // Binding is one declaration and the depths of its references. type Binding struct { DeclDepth int32 RefDepths []int32 } // BindingGraph is the full binding structure of a function. type BindingGraph struct { Bindings []Binding Externals []ExternalRef } // LocalSig is one binding in the order-erased signature. type LocalSig struct { DeclDepth int32 RefDepths []int32 } // ExternSig is one external in the order-erased signature. type ExternSig struct { RefCount int32 Depths []int32 } // BindingSignature is the order- and name-erased fingerprint. type BindingSignature struct { Locals []LocalSig Externs []ExternSig ParamTypes []string ResultTypes []string RecvType string ExternNames []string RefSeqHash uint64 } // ExtractSymbols parses a .mx AST dump into a symbol table. symbols.mx // ExtractSymbols, line for line. func ExtractSymbols(astDump string) *SymbolTable { st := &SymbolTable{Counts: make(map[string]int32)} lines := bytes.Split([]byte(astDump), []byte("\n")) inParams, inResults := false, false sectionDepth := int32(-1) paramOrd := map[string]int32{} resultOrd := map[string]int32{} localOrd := map[string]int32{} var refSeq []byte for _, line := range lines { if len(line) == 0 { continue } d := countIndent(line) trimmed := bytes.TrimSpace(line) if (inParams || inResults) && d <= sectionDepth { inParams, inResults = false, false } switch { case bytes.HasPrefix(trimmed, []byte("FuncDecl ")): name := string(trimmed[9:]) if idx := bytes.IndexByte(trimmed[9:], ' '); idx >= 0 { name = string(trimmed[9 : 9+idx]) } addSym(st, name, d, SymDecl) if ri := bytes.Index(trimmed, []byte("recv=")); ri >= 0 { rt := trimmed[ri+5:] if si := bytes.IndexByte(rt, ' '); si >= 0 { rt = rt[:si] } st.RecvType = string(rt) } case bytes.HasPrefix(trimmed, []byte("Params")): inParams, inResults, sectionDepth = true, false, d case bytes.HasPrefix(trimmed, []byte("Results")): inResults, inParams, sectionDepth = true, false, d case inParams && d > sectionDepth: if typeName := extractTypeFromParamLine(trimmed); typeName != "" { st.ParamTypes = append(st.ParamTypes, typeName) } for _, n := range extractParamNames(trimmed) { paramOrd[n] = int32(len(paramOrd)) } parseParamLine(st, trimmed, d) case inResults && d > sectionDepth: if typeName := extractTypeFromParamLine(trimmed); typeName != "" { st.ResultTypes = append(st.ResultTypes, typeName) } if isParamLine(trimmed) { for _, n := range extractParamNames(trimmed) { resultOrd[n] = int32(len(resultOrd)) } parseParamLine(st, trimmed, d) } case bytes.HasPrefix(trimmed, []byte("Assign ")): rest := trimmed[7:] if spIdx := bytes.IndexByte(rest, ' '); spIdx > 0 { for _, p := range bytes.Split(rest[:spIdx], []byte(",")) { nm := string(bytes.TrimSpace(p)) if nm == "" { continue } if _, ok := localOrd[nm]; ok { continue } if _, ok := paramOrd[nm]; ok { continue } if _, ok := resultOrd[nm]; ok { continue } localOrd[nm] = int32(len(localOrd)) } } refSeq = appendRefFingerprint(refSeq, trimmed, paramOrd, resultOrd, localOrd) parseAssign(st, trimmed, d) case bytes.HasPrefix(trimmed, []byte("Return")): refSeq = appendRefFingerprint(refSeq, trimmed, paramOrd, resultOrd, localOrd) parseRefs(st, trimmed, d) case bytes.HasPrefix(trimmed, []byte("If")): refSeq = appendRefFingerprint(refSeq, trimmed, paramOrd, resultOrd, localOrd) parseRefs(st, trimmed, d) case bytes.HasPrefix(trimmed, []byte("For")): refSeq = appendRefFingerprint(refSeq, trimmed, paramOrd, resultOrd, localOrd) parseRefs(st, trimmed, d) case bytes.HasPrefix(trimmed, []byte("Range ")): refSeq = appendRefFingerprint(refSeq, trimmed, paramOrd, resultOrd, localOrd) parseRefs(st, trimmed, d) case bytes.HasPrefix(trimmed, []byte("Expr ")): refSeq = appendRefFingerprint(refSeq, trimmed, paramOrd, resultOrd, localOrd) parseRefs(st, trimmed, d) case bytes.HasPrefix(trimmed, []byte("Case")): refSeq = appendRefFingerprint(refSeq, trimmed, paramOrd, resultOrd, localOrd) parseRefs(st, trimmed, d) case bytes.HasPrefix(trimmed, []byte("Switch")): refSeq = appendRefFingerprint(refSeq, trimmed, paramOrd, resultOrd, localOrd) parseRefs(st, trimmed, d) case bytes.HasPrefix(trimmed, []byte("Value ")): parseParamLine(st, trimmed[6:], d) case isParamLine(trimmed): parseParamLine(st, trimmed, d) } } if len(refSeq) > 0 && !allSeparators(refSeq) { st.RefSeqHash = fnvHash64(refSeq) } return st } // ExtractBindings resolves references to the nearest declaration of the name, // in symbol order. This is the one-pass approximation symbols.mx uses: it // registers every declaration and every parameter first, then walks the refs. func ExtractBindings(st *SymbolTable) *BindingGraph { bg := &BindingGraph{} localIdx := make(map[string]int32) extIdx := make(map[string]int32) for _, sym := range st.Symbols { if sym.Kind == SymDecl || sym.Kind == SymParam { localIdx[sym.Name] = int32(len(bg.Bindings)) bg.Bindings = append(bg.Bindings, Binding{DeclDepth: sym.Depth}) } } for _, sym := range st.Symbols { if sym.Kind != SymRef { continue } if idx, ok := localIdx[sym.Name]; ok { bg.Bindings[idx].RefDepths = append(bg.Bindings[idx].RefDepths, sym.Depth) continue } if ei, ok := extIdx[sym.Name]; ok { bg.Externals[ei].RefCount++ bg.Externals[ei].Depths = append(bg.Externals[ei].Depths, sym.Depth) continue } extIdx[sym.Name] = int32(len(bg.Externals)) bg.Externals = append(bg.Externals, ExternalRef{Name: sym.Name, RefCount: 1, Depths: []int32{sym.Depth}}) } return bg } // Signature erases names and orders the bindings. func (bg *BindingGraph) Signature() *BindingSignature { sig := &BindingSignature{} for _, b := range bg.Bindings { depths := append([]int32{}, b.RefDepths...) sort.Slice(depths, func(i, j int) bool { return depths[i] < depths[j] }) sig.Locals = append(sig.Locals, LocalSig{DeclDepth: b.DeclDepth, RefDepths: depths}) } for _, e := range bg.Externals { depths := append([]int32{}, e.Depths...) sort.Slice(depths, func(i, j int) bool { return depths[i] < depths[j] }) sig.Externs = append(sig.Externs, ExternSig{RefCount: e.RefCount, Depths: depths}) } sort.SliceStable(sig.Locals, func(i, j int) bool { return cmpLocalSig(sig.Locals[i], sig.Locals[j]) < 0 }) sort.SliceStable(sig.Externs, func(i, j int) bool { return cmpExternSig(sig.Externs[i], sig.Externs[j]) < 0 }) return sig } // SignatureWithTypes is Signature plus the declared types, the receiver and // the sorted external names, as InsertSegment stores for the AST stage. func SignatureWithTypes(st *SymbolTable) *BindingSignature { bg := ExtractBindings(st) sig := bg.Signature() sig.ParamTypes = append(sig.ParamTypes, st.ParamTypes...) sig.ResultTypes = append(sig.ResultTypes, st.ResultTypes...) sig.RecvType = st.RecvType for _, e := range bg.Externals { sig.ExternNames = append(sig.ExternNames, e.Name) } sort.Strings(sig.ExternNames) sig.RefSeqHash = st.RefSeqHash return sig } // IsIsomorphic compares two signatures field for field. func (a *BindingSignature) IsIsomorphic(b *BindingSignature) bool { if len(a.Locals) != len(b.Locals) || len(a.Externs) != len(b.Externs) { return false } for i := range a.Locals { if a.Locals[i].DeclDepth != b.Locals[i].DeclDepth || !int32sEqual(a.Locals[i].RefDepths, b.Locals[i].RefDepths) { return false } } for i := range a.Externs { if a.Externs[i].RefCount != b.Externs[i].RefCount || !int32sEqual(a.Externs[i].Depths, b.Externs[i].Depths) { return false } } if !stringsEqual(a.ParamTypes, b.ParamTypes) || !stringsEqual(a.ResultTypes, b.ResultTypes) { return false } if a.RecvType != b.RecvType || !stringsEqual(a.ExternNames, b.ExternNames) { return false } if a.RefSeqHash != 0 && b.RefSeqHash != 0 && a.RefSeqHash != b.RefSeqHash { return false } return true } // GeometricDistance is the divergence between two signatures, 0 for // isomorphic. func GeometricDistance(a, b *BindingSignature) int32 { var dist int32 minL := len(a.Locals) if len(b.Locals) < minL { minL = len(b.Locals) } for i := 0; i < minL; i++ { if a.Locals[i].DeclDepth != b.Locals[i].DeclDepth { dist++ } dist += int32SliceDistance(a.Locals[i].RefDepths, b.Locals[i].RefDepths) } if len(a.Locals) > len(b.Locals) { dist += int32(len(a.Locals) - len(b.Locals)) } else { dist += int32(len(b.Locals) - len(a.Locals)) } minE := len(a.Externs) if len(b.Externs) < minE { minE = len(b.Externs) } for i := 0; i < minE; i++ { d := a.Externs[i].RefCount - b.Externs[i].RefCount if d < 0 { d = -d } dist += d + int32SliceDistance(a.Externs[i].Depths, b.Externs[i].Depths) } if len(a.Externs) > len(b.Externs) { dist += int32(len(a.Externs) - len(b.Externs)) } else { dist += int32(len(b.Externs) - len(a.Externs)) } return dist } // SignatureHash24 is the 24-bit fast-rejection hash of a signature. func SignatureHash24(sig *BindingSignature) uint32 { h := uint32(0x811c9dc5) mix := func(b byte) { h ^= uint32(b) h *= 0x01000193 } mix(byte(len(sig.Locals))) for _, l := range sig.Locals { mix(byte(l.DeclDepth)) mix(byte(l.DeclDepth >> 8)) mix(byte(len(l.RefDepths))) for _, d := range l.RefDepths { mix(byte(d)) mix(byte(d >> 8)) } } mix(byte(len(sig.Externs))) for _, e := range sig.Externs { mix(byte(e.RefCount)) mix(byte(e.RefCount >> 8)) for _, d := range e.Depths { mix(byte(d)) mix(byte(d >> 8)) } } for _, c := range []byte(sig.RecvType) { mix(c) } for _, name := range sig.ExternNames { for _, c := range []byte(name) { mix(c) } mix(0xFF) } for i := 0; i < 8; i++ { mix(byte(sig.RefSeqHash >> (8 * uint(i)))) } return h & 0xFFFFFF } func countIndent(line []byte) int32 { var n int32 i := 0 for i+1 < len(line) && line[i] == ' ' && line[i+1] == ' ' { n++ i += 2 } return n } func isParamLine(trimmed []byte) bool { if len(trimmed) == 0 { return false } if trimmed[0] >= 'a' && trimmed[0] <= 'z' { return bytes.IndexByte(trimmed, ' ') > 0 } return false } func parseParamLine(st *SymbolTable, trimmed []byte, depth int32) { idx := bytes.IndexByte(trimmed, ' ') if idx <= 0 { return } for _, p := range bytes.Split(trimmed[:idx], []byte(",")) { if p = bytes.TrimSpace(p); len(p) > 0 { addSym(st, string(p), depth, SymParam) } } } func parseAssign(st *SymbolTable, trimmed []byte, depth int32) { rest := trimmed[7:] spIdx := bytes.IndexByte(rest, ' ') if spIdx <= 0 { return } for _, p := range bytes.Split(rest[:spIdx], []byte(",")) { if p = bytes.TrimSpace(p); len(p) > 0 { addSym(st, string(p), depth, SymDecl) } } parseRefs(st, trimmed, depth) } func parseRefs(st *SymbolTable, trimmed []byte, depth int32) { start := bytes.IndexByte(trimmed, '[') if start < 0 { return } rel := bytes.IndexByte(trimmed[start:], ']') if rel < 0 { return } for _, p := range bytes.Split(trimmed[start+1:start+rel], []byte(",")) { if p = bytes.TrimSpace(p); len(p) > 0 { addSym(st, string(p), depth, SymRef) } } } func addSym(st *SymbolTable, name string, depth int32, kind uint8) { st.Symbols = append(st.Symbols, Symbol{Name: name, Depth: depth, Kind: kind}) st.Counts[name]++ } func extractParamNames(line []byte) []string { idx := bytes.IndexByte(line, ' ') if idx <= 0 { return nil } var names []string for _, p := range bytes.Split(line[:idx], []byte(",")) { p = bytes.TrimSpace(p) if len(p) > 0 && p[0] >= 'a' && p[0] <= 'z' { names = append(names, string(p)) } } return names } func extractTypeFromParamLine(line []byte) string { idx := bytes.IndexByte(line, ' ') if idx < 0 { return string(line) } before := line[:idx] if before[0] == '[' || before[0] == '*' || bytes.HasPrefix(before, []byte("map")) || bytes.HasPrefix(before, []byte("chan")) || bytes.HasPrefix(before, []byte("func")) { return string(line) } return string(line[idx+1:]) } func appendRefFingerprint(seq, line []byte, paramOrd, resultOrd, localOrd map[string]int32) []byte { start := bytes.IndexByte(line, '[') if start < 0 { return append(seq, '|') } rel := bytes.IndexByte(line[start:], ']') if rel < 0 { return append(seq, '|') } for i, p := range bytes.Split(line[start+1:start+rel], []byte(",")) { p = bytes.TrimSpace(p) if i > 0 { seq = append(seq, ',') } name := string(p) switch { case has(paramOrd, name): seq = append(seq, 'P') seq = append(seq, intToStr(paramOrd[name])...) case has(resultOrd, name): seq = append(seq, 'R') seq = append(seq, intToStr(resultOrd[name])...) case has(localOrd, name): seq = append(seq, 'L') seq = append(seq, intToStr(localOrd[name])...) default: seq = append(seq, p...) } } return append(seq, '|') } func has(m map[string]int32, k string) bool { _, ok := m[k]; return ok } func allSeparators(b []byte) bool { for _, c := range b { if c != '|' { return false } } return true } func fnvHash64(data []byte) uint64 { h := uint64(0xcbf29ce484222325) for _, b := range data { h ^= uint64(b) h *= 0x100000001b3 } return h } func intToStr(v int32) string { if v == 0 { return "0" } var buf [12]byte i := len(buf) neg := v < 0 if neg { v = -v } for v > 0 { i-- buf[i] = byte('0' + v%10) v /= 10 } if neg { i-- buf[i] = '-' } return string(buf[i:]) } func int32sEqual(a, b []int32) bool { if len(a) != len(b) { return false } for i := range a { if a[i] != b[i] { return false } } return true } func stringsEqual(a, b []string) bool { if len(a) != len(b) { return false } for i := range a { if a[i] != b[i] { return false } } return true } func int32SliceDistance(a, b []int32) int32 { var dist int32 minN := len(a) if len(b) < minN { minN = len(b) } for i := 0; i < minN; i++ { d := a[i] - b[i] if d < 0 { d = -d } dist += d } if len(a) > len(b) { dist += int32(len(a) - len(b)) } else { dist += int32(len(b) - len(a)) } return dist } func cmpLocalSig(a, b LocalSig) int { if a.DeclDepth != b.DeclDepth { if a.DeclDepth < b.DeclDepth { return -1 } return 1 } if len(a.RefDepths) != len(b.RefDepths) { return len(a.RefDepths) - len(b.RefDepths) } for i := range a.RefDepths { if a.RefDepths[i] != b.RefDepths[i] { if a.RefDepths[i] < b.RefDepths[i] { return -1 } return 1 } } return 0 } func cmpExternSig(a, b ExternSig) int { if a.RefCount != b.RefCount { if a.RefCount < b.RefCount { return -1 } return 1 } if len(a.Depths) != len(b.Depths) { return len(a.Depths) - len(b.Depths) } for i := range a.Depths { if a.Depths[i] != b.Depths[i] { if a.Depths[i] < b.Depths[i] { return -1 } return 1 } } return 0 }