-
Notifications
You must be signed in to change notification settings - Fork 0
/
errgoengine.go
273 lines (222 loc) · 6.67 KB
/
errgoengine.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
package errgoengine
import (
"bytes"
"fmt"
"io/fs"
sitter "github.com/smacker/go-tree-sitter"
)
type ErrgoEngine struct {
SharedStore *Store
ErrorTemplates ErrorTemplates
FS *MultiReadFileFS
OutputGen *OutputGenerator
IsTesting bool
}
func New() *ErrgoEngine {
return &ErrgoEngine{
SharedStore: NewEmptyStore(),
ErrorTemplates: ErrorTemplates{},
FS: &MultiReadFileFS{
FSs: []fs.ReadFileFS{
&RawFS{},
},
},
OutputGen: &OutputGenerator{},
}
}
func (e *ErrgoEngine) AttachMainFS(instance fs.ReadFileFS) {
// remove existing documents
fs.WalkDir(e.FS.FSs[0], ".", func(path string, d fs.DirEntry, err error) error {
if d.IsDir() {
return nil
} else if _, ok := e.SharedStore.Documents[path]; !ok {
return nil
}
// delete document
delete(e.SharedStore.Documents, path)
return nil
})
// attach new fs
e.FS.Attach(instance, 0)
}
func (e *ErrgoEngine) Analyze(workingPath, msg string) (*CompiledErrorTemplate, *ContextData, error) {
template := e.ErrorTemplates.Match(msg)
// initial context data extraction
contextData := NewContextData(e.SharedStore, workingPath)
contextData.AddVariable("message", msg)
contextData.FS = e.FS
// return context data if template is not found
if template == nil {
return nil, contextData, fmt.Errorf("template not found. \nMessage: %s", msg)
}
contextData.Analyzer = template.Language.AnalyzerFactory(contextData)
// extract variables from the error message
contextData.AddVariables(template.ExtractVariables(msg))
// extract stack trace
contextData.TraceStack = template.ExtractStackTrace(contextData)
// open contents of the extracted stack file locations
if err := ParseFromStackTrace(contextData, template.Language, e.FS); err != nil {
// return error template for bugbuddy to handle
// incomplete error messages
return template, nil, err
}
// locate main error
mainTraceNode := contextData.TraceStack.NearestTo(contextData.WorkingPath)
// get nearest node
if doc, ok := contextData.Documents[mainTraceNode.DocumentPath]; ok {
nearest := doc.Tree.RootNode().NamedDescendantForPointRange(
sitter.Point{Row: uint32(mainTraceNode.StartPos.Line)},
sitter.Point{Row: uint32(mainTraceNode.EndPos.Line)},
)
if nearest.StartPoint().Row != uint32(mainTraceNode.StartPos.Line) {
cursor := sitter.NewTreeCursor(nearest)
nearest = nearestNodeFromPos(cursor, mainTraceNode.StartPos)
}
// further analyze main error
contextData.MainError = &MainError{
ErrorNode: &mainTraceNode,
Document: doc,
Nearest: WrapNode(doc, nearest),
}
} else if template == FallbackErrorTemplate {
contextData.MainError = &MainError{
ErrorNode: nil,
Document: nil,
Nearest: SyntaxNode{},
}
} else {
// return error template for bugbuddy to handle
// incomplete error messages
return template, nil, fmt.Errorf("main trace node document not found")
}
if contextData.MainError != nil && template.OnAnalyzeErrorFn != nil {
template.OnAnalyzeErrorFn(contextData, contextData.MainError)
}
return template, contextData, nil
}
func (e *ErrgoEngine) Translate(template *CompiledErrorTemplate, contextData *ContextData) (mainExp string, fullExp string) {
expGen := &ExplainGenerator{ErrorName: template.Name}
fixGen := &BugFixGenerator{}
if contextData.MainError != nil {
fixGen.Document = contextData.MainError.Document
}
// execute error generator function
template.OnGenExplainFn(contextData, expGen)
// execute bug fix generator function
if template.OnGenBugFixFn != nil {
template.OnGenBugFixFn(contextData, fixGen)
}
if e.IsTesting {
// add a code snippet that points to the error
e.OutputGen.GenAfterExplain = func(gen *OutputGenerator) {
err := contextData.MainError
if err == nil {
return
}
doc := err.Document
if doc == nil || err.Nearest.IsNull() {
return
}
startLineNr := err.Nearest.StartPosition().Line
startLines := doc.LinesAt(max(startLineNr-1, 0), startLineNr)
endLines := doc.LinesAt(min(startLineNr+1, doc.TotalLines()), min(startLineNr+2, doc.TotalLines()))
arrowLength := int(err.Nearest.EndByte() - err.Nearest.StartByte())
if arrowLength == 0 {
arrowLength = 1
}
startArrowPos := err.Nearest.StartPosition().Column
gen.Writeln("```")
gen.WriteLines(startLines...)
for i := 0; i < startArrowPos; i++ {
if startLines[len(startLines)-1][i] == '\t' {
gen.Builder.WriteString(" ")
} else {
gen.Builder.WriteByte(' ')
}
}
for i := 0; i < arrowLength; i++ {
gen.Builder.WriteByte('^')
}
gen.Break()
gen.WriteLines(endLines...)
gen.Writeln("```")
}
}
output := e.OutputGen.Generate(expGen, fixGen)
defer e.OutputGen.Reset()
return expGen.Builder.String(), output
}
func ParseFiles(contextData *ContextData, defaultLanguage *Language, files fs.ReadFileFS, fileNames []string) error {
if files == nil {
return fmt.Errorf("files is nil")
}
parser := sitter.NewParser()
analyzer := &SymbolAnalyzer{ContextData: contextData}
for _, path := range fileNames {
contents, err := files.ReadFile(path)
if err != nil {
// return err
// Do not return error if file not found
continue
}
// Skip stub files
if len(contents) == 0 {
continue
}
// check if document already exists
existingDoc, docExists := contextData.Documents[path]
if docExists && existingDoc.BytesContentEquals(contents) {
// do not parse if content is the same
continue
}
// check matched languages
selectedLanguage := defaultLanguage
if docExists {
selectedLanguage = existingDoc.Language
} else {
if !selectedLanguage.MatchPath(path) {
return fmt.Errorf("no language found for %s", path)
}
// compile language first (if not yet)
selectedLanguage.Compile()
}
// do semantic analysis
contentReader := bytes.NewReader(contents)
doc, err := ParseDocument(path, contentReader, parser, selectedLanguage, existingDoc)
if err != nil {
return err
}
// add doc if it does not already exist
if doc != existingDoc {
doc = contextData.AddDocument(doc)
}
analyzer.Analyze(doc)
}
return nil
}
func ParseFromStackTrace(contextData *ContextData, defaultLanguage *Language, files fs.ReadFileFS) error {
filesToParse := []string{}
for _, node := range contextData.TraceStack {
path := node.DocumentPath
if path == "" {
continue
}
// check if file is already parsed
if _, ok := contextData.Documents[path]; ok {
continue
}
// check if file is already in the list
found := false
for _, f := range filesToParse {
if f == path {
found = true
break
}
}
if found {
continue
}
filesToParse = append(filesToParse, path)
}
return ParseFiles(contextData, defaultLanguage, files, filesToParse)
}