internal/symbols/extract.go

545ba0bcdea3b534903bd78c918c0c025a97eda7
gitbay/internal/symbols/extract.go

358 lines · 10744 bytes

21 symbols in this file
  1// Package symbols finds definitions in source files and keeps one index of
  2// them per repository, for `repo symbols` and the blob view's links from a
  3// name to where it is defined.
  4//
  5// The indexer is pure Go, with no external tagger. Go is parsed with
  6// go/parser; the other languages are matched a line at a time against a
  7// small table of anchored patterns, which finds the common definition
  8// shapes and misses the unusual ones.
  9//
 10//	Go                  function, method (named Type.Method), type, const, var
 11//	Swift               function, class, struct, enum, interface (protocol), type (typealias)
 12//	Rust                function, struct, enum, interface (trait), type, module, const, macro
 13//	Python              function, method (an indented def), class
 14//	JavaScript, TS      function, class, interface, type, enum, const
 15//	C and C++ headers   function (prototype), struct, enum, class, type (typedef), macro (#define)
 16//	Shell               function
 17//	Org, Markdown       section (a heading)
 18//
 19// The index covers the tree of the default branch's head and is keyed by
 20// that tree's id, so a push that leaves the tree as it was is not indexed
 21// again. Worker builds it in the background after a push to the default
 22// branch.
 23package symbols
 24
 25import (
 26	"bytes"
 27	"go/ast"
 28	"go/parser"
 29	"go/token"
 30	"path"
 31	"regexp"
 32	"strings"
 33)
 34
 35// Kinds are the symbol kinds the indexer records, in the order they are
 36// listed.
 37var Kinds = []string{
 38	"function", "method", "class", "struct", "enum", "interface",
 39	"type", "const", "var", "module", "macro", "section",
 40}
 41
 42// ValidKind reports whether k is one of Kinds.
 43func ValidKind(k string) bool {
 44	for _, v := range Kinds {
 45		if v == k {
 46			return true
 47		}
 48	}
 49	return false
 50}
 51
 52// Symbol is one definition in one file. Name is what is listed; Key is the
 53// name as it is written where the symbol is used, which differs from Name
 54// only for Go methods (Name "Server.Handle", Key "Handle").
 55type Symbol struct {
 56	Name string
 57	Key  string
 58	Kind string
 59	Line int
 60}
 61
 62// MaxFileBytes is the largest file the indexer reads.
 63const MaxFileBytes = 1 << 20
 64
 65// Skip reports whether a file is left out of the index before it is read:
 66// too large, vendored, generated by its name, or in a language the indexer
 67// does not know.
 68func Skip(p string, size int64) bool {
 69	if size > MaxFileBytes || Language(p) == "" {
 70		return true
 71	}
 72	for _, seg := range strings.Split(path.Dir(p), "/") {
 73		if seg == "vendor" || seg == "node_modules" {
 74			return true
 75		}
 76	}
 77	base := path.Base(p)
 78	return strings.HasSuffix(base, "_gen.go") || strings.HasSuffix(base, ".pb.go") ||
 79		strings.HasSuffix(base, ".min.js")
 80}
 81
 82var languages = map[string]string{
 83	".go":       "go",
 84	".swift":    "swift",
 85	".rs":       "rust",
 86	".py":       "python",
 87	".js":       "js",
 88	".mjs":      "js",
 89	".cjs":      "js",
 90	".jsx":      "js",
 91	".ts":       "js",
 92	".tsx":      "js",
 93	".mts":      "js",
 94	".h":        "c",
 95	".hh":       "c",
 96	".hpp":      "c",
 97	".hxx":      "c",
 98	".sh":       "shell",
 99	".bash":     "shell",
100	".zsh":      "shell",
101	".org":      "org",
102	".md":       "markdown",
103	".markdown": "markdown",
104}
105
106// Language names the indexer's language for a path, or "" when it has
107// none.
108func Language(p string) string {
109	return languages[strings.ToLower(path.Ext(p))]
110}
111
112// generatedGo is the marker `go generate` tools write, per the Go
113// convention for generated files.
114var generatedGo = regexp.MustCompile(`(?m)^// Code generated .* DO NOT EDIT\.$`)
115
116// MaxNameBytes is the longest name the index keeps. A longer one is
117// dropped: no real definition is named that way, and a file of them is a
118// way to fill the index.
119const MaxNameBytes = 256
120
121// Extract returns the definitions in one file, in line order.
122func Extract(p string, data []byte) []Symbol {
123	var syms []Symbol
124	switch lang := Language(p); lang {
125	case "":
126		return nil
127	case "go":
128		syms = extractGo(data)
129	case "org", "markdown":
130		syms = extractHeadings(lang, data)
131	default:
132		syms = extractLines(rules[lang], data)
133	}
134	kept := syms[:0]
135	for _, s := range syms {
136		if len(s.Name) <= MaxNameBytes && len(s.Key) <= MaxNameBytes {
137			kept = append(kept, s)
138		}
139	}
140	return kept
141}
142
143func extractGo(data []byte) []Symbol {
144	head := data
145	if len(head) > 4096 {
146		head = head[:4096]
147	}
148	if generatedGo.Match(head) {
149		return nil
150	}
151	fset := token.NewFileSet()
152	// A file that does not parse still yields the declarations before the
153	// error.
154	f, _ := parser.ParseFile(fset, "", data, parser.SkipObjectResolution)
155	if f == nil {
156		return nil
157	}
158	var out []Symbol
159	add := func(id *ast.Ident, name, kind string) {
160		if id == nil || id.Name == "_" {
161			return
162		}
163		out = append(out, Symbol{Name: name, Key: id.Name, Kind: kind, Line: fset.Position(id.Pos()).Line})
164	}
165	addNames := func(ids []*ast.Ident, kind string) {
166		for _, id := range ids {
167			add(id, id.Name, kind)
168		}
169	}
170	for _, d := range f.Decls {
171		switch d := d.(type) {
172		case *ast.FuncDecl:
173			if d.Recv == nil || len(d.Recv.List) == 0 {
174				add(d.Name, d.Name.Name, "function")
175				continue
176			}
177			recv := receiverName(d.Recv.List[0].Type)
178			if recv == "" {
179				add(d.Name, d.Name.Name, "method")
180				continue
181			}
182			add(d.Name, recv+"."+d.Name.Name, "method")
183		case *ast.GenDecl:
184			kind := "var"
185			if d.Tok == token.CONST {
186				kind = "const"
187			}
188			for _, spec := range d.Specs {
189				switch s := spec.(type) {
190				case *ast.TypeSpec:
191					add(s.Name, s.Name.Name, "type")
192				case *ast.ValueSpec:
193					addNames(s.Names, kind)
194				}
195			}
196		}
197	}
198	return out
199}
200
201// receiverName is the type a method is declared on, without a pointer or
202// type parameters.
203func receiverName(e ast.Expr) string {
204	for {
205		switch t := e.(type) {
206		case *ast.StarExpr:
207			e = t.X
208		case *ast.ParenExpr:
209			e = t.X
210		case *ast.IndexExpr:
211			e = t.X
212		case *ast.IndexListExpr:
213			e = t.X
214		case *ast.Ident:
215			return t.Name
216		default:
217			return ""
218		}
219	}
220}
221
222// rule is one line pattern: the first submatch is the name.
223type rule struct {
224	re   *regexp.Regexp
225	kind string
226}
227
228func r(kind, pattern string) rule { return rule{regexp.MustCompile(pattern), kind} }
229
230// ident is a name in the languages the line rules cover.
231const ident = `([A-Za-z_$][A-Za-z0-9_$]*)`
232
233var rules = map[string][]rule{
234	"swift": {
235		r("function", `^\s*(?:@\w+\s+)*(?:(?:public|private|fileprivate|internal|open|static|class|final|override|mutating|nonisolated|async|convenience|required)\s+)*func\s+`+ident),
236		r("class", `^\s*(?:@\w+\s+)*(?:(?:public|private|fileprivate|internal|open|final)\s+)*(?:class|actor)\s+`+ident),
237		r("struct", `^\s*(?:@\w+\s+)*(?:(?:public|private|fileprivate|internal)\s+)*struct\s+`+ident),
238		r("enum", `^\s*(?:@\w+\s+)*(?:(?:public|private|fileprivate|internal|indirect)\s+)*enum\s+`+ident),
239		r("interface", `^\s*(?:@\w+\s+)*(?:(?:public|private|fileprivate|internal)\s+)*protocol\s+`+ident),
240		r("type", `^\s*(?:(?:public|private|fileprivate|internal)\s+)*typealias\s+`+ident),
241	},
242	"rust": {
243		r("function", `^\s*(?:pub(?:\([^)]*\))?\s+)?(?:(?:const|async|unsafe|extern(?:\s+"[^"]*")?)\s+)*fn\s+`+ident),
244		r("struct", `^\s*(?:pub(?:\([^)]*\))?\s+)?struct\s+`+ident),
245		r("enum", `^\s*(?:pub(?:\([^)]*\))?\s+)?enum\s+`+ident),
246		r("interface", `^\s*(?:pub(?:\([^)]*\))?\s+)?(?:unsafe\s+)?trait\s+`+ident),
247		r("type", `^\s*(?:pub(?:\([^)]*\))?\s+)?type\s+`+ident),
248		r("module", `^\s*(?:pub(?:\([^)]*\))?\s+)?mod\s+`+ident),
249		r("const", `^\s*(?:pub(?:\([^)]*\))?\s+)?(?:const|static(?:\s+mut)?)\s+`+ident+`\s*:`),
250		r("macro", `^\s*macro_rules!\s+`+ident),
251	},
252	"python": {
253		r("function", `^(?:async\s+)?def\s+`+ident),
254		r("method", `^\s+(?:async\s+)?def\s+`+ident),
255		r("class", `^\s*class\s+`+ident),
256	},
257	"js": {
258		r("function", `^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s*`+ident),
259		r("class", `^\s*(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+`+ident),
260		r("interface", `^\s*(?:export\s+)?(?:declare\s+)?interface\s+`+ident),
261		r("type", `^\s*(?:export\s+)?(?:declare\s+)?type\s+`+ident+`\s*(?:<[^=]*>)?\s*=`),
262		r("enum", `^\s*(?:export\s+)?(?:declare\s+)?(?:const\s+)?enum\s+`+ident),
263		r("const", `^(?:export\s+)?const\s+`+ident+`\s*(?::[^=]*)?=`),
264	},
265	"c": {
266		r("macro", `^\s*#\s*define\s+`+ident),
267		r("struct", `^\s*(?:typedef\s+)?struct\s+`+ident+`\s*\{`),
268		r("enum", `^\s*(?:typedef\s+)?enum\s+(?:class\s+)?`+ident+`\s*(?::[^{]*)?\{`),
269		r("class", `^\s*class\s+`+ident+`\s*(?::[^{;]*)?\{`),
270		r("type", `^\s*typedef\s+[^;(]*?\b`+ident+`\s*;`),
271		r("type", `^\s*}\s*`+ident+`\s*;`),
272		r("function", `^[A-Za-z_][\w\s\*&:<>,]*?[\s\*&]`+ident+`\s*\([^;{]*\)\s*(?:const\s*)?;`),
273	},
274	"shell": {
275		r("function", `^\s*function\s+([A-Za-z_][A-Za-z0-9_:.-]*)`),
276		r("function", `^\s*([A-Za-z_][A-Za-z0-9_:.-]*)\s*\(\)\s*(?:\{|$)`),
277	},
278}
279
280// keywords are never names, though a rule can capture one: Swift's
281// `class var x` reads as a class named var, C's `if (x);` as a prototype.
282var keywords = map[string]bool{
283	"return": true, "if": true, "while": true, "for": true, "switch": true,
284	"sizeof": true, "else": true, "case": true, "do": true, "goto": true,
285	"var": true, "let": true, "func": true, "static": true,
286}
287
288func extractLines(rs []rule, data []byte) []Symbol {
289	var out []Symbol
290	line := 0
291	for len(data) > 0 {
292		line++
293		var text []byte
294		if i := bytes.IndexByte(data, '\n'); i >= 0 {
295			text, data = data[:i], data[i+1:]
296		} else {
297			text, data = data, nil
298		}
299		if len(text) > 1000 {
300			continue
301		}
302		for _, ru := range rs {
303			m := ru.re.FindSubmatch(text)
304			if m == nil {
305				continue
306			}
307			name := string(m[1])
308			if keywords[name] {
309				continue
310			}
311			out = append(out, Symbol{Name: name, Key: name, Kind: ru.kind, Line: line})
312			break
313		}
314	}
315	return out
316}
317
318var (
319	mdHeading  = regexp.MustCompile(`^#{1,6}\s+(.+?)\s*#*\s*$`)
320	orgHeading = regexp.MustCompile(`^\*+\s+(.+?)\s*$`)
321)
322
323// extractHeadings lists headings as sections, skipping what sits inside a
324// code block, where a line starting with # or * is code.
325func extractHeadings(lang string, data []byte) []Symbol {
326	var out []Symbol
327	inBlock := false
328	for i, text := range strings.Split(string(data), "\n") {
329		trimmed := strings.TrimSpace(text)
330		if lang == "markdown" {
331			if strings.HasPrefix(trimmed, "```") || strings.HasPrefix(trimmed, "~~~") {
332				inBlock = !inBlock
333				continue
334			}
335		} else {
336			lower := strings.ToLower(trimmed)
337			if strings.HasPrefix(lower, "#+begin_") {
338				inBlock = true
339				continue
340			}
341			if strings.HasPrefix(lower, "#+end_") {
342				inBlock = false
343				continue
344			}
345		}
346		if inBlock || len(text) > 1000 {
347			continue
348		}
349		re := mdHeading
350		if lang == "org" {
351			re = orgHeading
352		}
353		if m := re.FindStringSubmatch(text); m != nil {
354			out = append(out, Symbol{Name: m[1], Key: m[1], Kind: "section", Line: i + 1})
355		}
356	}
357	return out
358}