package iskra import ( "encoding/json" "fmt" "os" "path/filepath" "strings" "git.smesh.lol/go-iskra/lattice" ) // Segment is one row of a code corpus: a named piece of source at a kind. type Segment struct { ID string Kind string Name string Source string // path to the segment's own source file AST string // path to its AST dump } // Corpus is a directory produced by mxcorpus: per-file .segments directories, // an ast/ directory of dumps, and a manifest.json describing both. The moxie // loader reads a tab-separated manifest.csv instead; mxcorpus writes // manifest.json, so the Go loader reads that. type Corpus struct { Dir string Segments []Segment } // LoadCorpus lists the segments under a corpus directory. func LoadCorpus(dir string) (*Corpus, error) { manifest := filepath.Join(dir, "manifest.json") data, err := os.ReadFile(manifest) if err != nil { return nil, fmt.Errorf("iskra: %s: %w", manifest, err) } var m struct { Files []struct { Path string `json:"path"` Segments []struct { ID string `json:"id"` Kind string `json:"kind"` Name string `json:"name"` ASTFile string `json:"ast_file"` } `json:"segments"` } `json:"files"` } if err := json.Unmarshal(data, &m); err != nil { return nil, fmt.Errorf("iskra: %s: %w", manifest, err) } c := &Corpus{Dir: dir} for _, f := range m.Files { segDir := filepath.Join(dir, f.Path+".segments") for _, s := range f.Segments { seg := Segment{ID: s.ID, Kind: s.Kind, Name: s.Name} if p := filepath.Join(segDir, s.ID+".mx"); fileExists(p) { seg.Source = p } if s.ASTFile != "" { if p := filepath.Join(dir, "ast", s.ASTFile); fileExists(p) { seg.AST = p } } c.Segments = append(c.Segments, seg) } } return c, nil } // SegmentName is the name a segment occupies in the lattice at a stage. // // The moxie corpus loader addresses a segment by its bare name, so the 21 pkg // and 7 import segments of an iskra corpus - one per source file, all named // "iskra" and "import" - share two keys and 26 of 250 segments overwrite each // other. The segment id is unique per file and is what the lattice addresses // here. stage needs no prefix because the stage byte is already in the key. func SegmentName(seg *Segment) string { return seg.ID } // InsertSegment stores one segment at a stage under NameKey(stage, name), with // its content in the token pool and, for an AST, its signature hash. func InsertSegment(t *Tree, stage uint8, kindName, name string, content []byte) (uint32, error) { kind := ParseKind(kindName) key := NameKey(stage, name) branch := KindToBranch(kind) recIdx, err := t.Insert(branch, key, name, kind, stage) if err != nil { return 0, err } t.SetContent(recIdx, content) if stage == StageAST { st := ExtractSymbols(string(content)) sig := SignatureWithTypes(st) h := SignatureHash24(sig) t.MetaAt(recIdx).SetSigHash(h) t.SigIdxAdd(recIdx, stage, h) } return recIdx, nil } // LoadCorpusIntoF loads a corpus into a tree. stages is a bitmask over stage // numbers: 1<