corpus.go raw
1 package iskra
2
3 import (
4 "encoding/json"
5 "fmt"
6 "os"
7 "path/filepath"
8 "strings"
9
10 "git.smesh.lol/go-iskra/lattice"
11 )
12
13 // Segment is one row of a code corpus: a named piece of source at a kind.
14 type Segment struct {
15 ID string
16 Kind string
17 Name string
18 Source string // path to the segment's own source file
19 AST string // path to its AST dump
20 }
21
22 // Corpus is a directory produced by mxcorpus: per-file .segments directories,
23 // an ast/ directory of dumps, and a manifest.json describing both. The moxie
24 // loader reads a tab-separated manifest.csv instead; mxcorpus writes
25 // manifest.json, so the Go loader reads that.
26 type Corpus struct {
27 Dir string
28 Segments []Segment
29 }
30
31 // LoadCorpus lists the segments under a corpus directory.
32 func LoadCorpus(dir string) (*Corpus, error) {
33 manifest := filepath.Join(dir, "manifest.json")
34 data, err := os.ReadFile(manifest)
35 if err != nil {
36 return nil, fmt.Errorf("iskra: %s: %w", manifest, err)
37 }
38 var m struct {
39 Files []struct {
40 Path string `json:"path"`
41 Segments []struct {
42 ID string `json:"id"`
43 Kind string `json:"kind"`
44 Name string `json:"name"`
45 ASTFile string `json:"ast_file"`
46 } `json:"segments"`
47 } `json:"files"`
48 }
49 if err := json.Unmarshal(data, &m); err != nil {
50 return nil, fmt.Errorf("iskra: %s: %w", manifest, err)
51 }
52 c := &Corpus{Dir: dir}
53 for _, f := range m.Files {
54 segDir := filepath.Join(dir, f.Path+".segments")
55 for _, s := range f.Segments {
56 seg := Segment{ID: s.ID, Kind: s.Kind, Name: s.Name}
57 if p := filepath.Join(segDir, s.ID+".mx"); fileExists(p) {
58 seg.Source = p
59 }
60 if s.ASTFile != "" {
61 if p := filepath.Join(dir, "ast", s.ASTFile); fileExists(p) {
62 seg.AST = p
63 }
64 }
65 c.Segments = append(c.Segments, seg)
66 }
67 }
68 return c, nil
69 }
70
71 // SegmentName is the name a segment occupies in the lattice at a stage.
72 //
73 // The moxie corpus loader addresses a segment by its bare name, so the 21 pkg
74 // and 7 import segments of an iskra corpus - one per source file, all named
75 // "iskra" and "import" - share two keys and 26 of 250 segments overwrite each
76 // other. The segment id is unique per file and is what the lattice addresses
77 // here. stage needs no prefix because the stage byte is already in the key.
78 func SegmentName(seg *Segment) string { return seg.ID }
79
80 // InsertSegment stores one segment at a stage under NameKey(stage, name), with
81 // its content in the token pool and, for an AST, its signature hash.
82 func InsertSegment(t *Tree, stage uint8, kindName, name string, content []byte) (uint32, error) {
83 kind := ParseKind(kindName)
84 key := NameKey(stage, name)
85 branch := KindToBranch(kind)
86 recIdx, err := t.Insert(branch, key, name, kind, stage)
87 if err != nil {
88 return 0, err
89 }
90 t.SetContent(recIdx, content)
91 if stage == StageAST {
92 st := ExtractSymbols(string(content))
93 sig := SignatureWithTypes(st)
94 h := SignatureHash24(sig)
95 t.MetaAt(recIdx).SetSigHash(h)
96 t.SigIdxAdd(recIdx, stage, h)
97 }
98 return recIdx, nil
99 }
100
101 // LoadCorpusIntoF loads a corpus into a tree. stages is a bitmask over stage
102 // numbers: 1<<StageSRC etc.
103 func LoadCorpusIntoF(c *Corpus, t *Tree, stages uint8) (int, error) {
104 n := 0
105 for _, seg := range c.Segments {
106 name := SegmentName(&seg)
107 if stages&(1<<StageSRC) != 0 && seg.Source != "" {
108 data, err := os.ReadFile(seg.Source)
109 if err != nil {
110 return n, err
111 }
112 if _, err := InsertSegment(t, StageSRC, seg.Kind, name, data); err != nil {
113 return n, err
114 }
115 n++
116 }
117 if stages&(1<<StageAST) != 0 && seg.AST != "" {
118 data, err := os.ReadFile(seg.AST)
119 if err != nil {
120 return n, err
121 }
122 if _, err := InsertSegment(t, StageAST, seg.Kind, name, data); err != nil {
123 return n, err
124 }
125 n++
126 }
127 }
128 return n, nil
129 }
130
131 // FinalizeCorpus wires cross-branch links.
132 func FinalizeCorpus(t *Tree) error { return t.FinalizeLinks() }
133
134 // ParseKind maps a manifest kind string to a node kind.
135 func ParseKind(s string) lattice.NodeKind {
136 switch strings.ToLower(s) {
137 case "pkg":
138 return lattice.KindPkg
139 case "import":
140 return lattice.KindImport
141 case "const":
142 return lattice.KindConst
143 case "var":
144 return lattice.KindVar
145 case "type":
146 return lattice.KindType
147 case "func":
148 return lattice.KindFunc
149 case "method":
150 return lattice.KindMethod
151 case "field":
152 return lattice.KindField
153 case "stmt":
154 return lattice.KindStmt
155 case "expr":
156 return lattice.KindExpr
157 case "control":
158 return lattice.KindControl
159 case "literal":
160 return lattice.KindLiteral
161 default:
162 return lattice.KindUnknown
163 }
164 }
165
166 func fileExists(p string) bool {
167 st, err := os.Stat(p)
168 return err == nil && !st.IsDir()
169 }
170