/
typhoon.go
executable file
·220 lines (187 loc) · 5.42 KB
/
typhoon.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
package typhoon
import (
"crypto/sha1"
"flag"
"fmt"
"go/ast"
"go/parser"
"go/token"
"io"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
)
// String format placeholder regex
// Adapted from https://stackoverflow.com/a/29403060
var formatPlaceholderRegex, _ = regexp.Compile("%(?:\\x25\\x25)|(\\x25(?:(?:[1-9]\\d*)\\$|\\((?:[^\\)]+)\\))?(?:\\+)?(?: )?(?:\\#)?(?:0|'[^$])?(?:-)?(?:\\d+)?(?:\\.(?:\\d+))?(?:[vT%bcdoqxXUeEfFgGsqp]))")
// Format placeholder threshold for composite string arguments (ie: "-%s-")
var formatPlaceholderThreshold = 5
func inspect(fileName string, tree *Tree, queries *[]string) {
// Create the AST by parsing src.
fset := token.NewFileSet() // Positions are relative to fset
f, err := parser.ParseFile(fset, fileName, nil, 0)
if err != nil {
panic(err)
}
// Import token tracking variables
importStartPos := token.NoPos
importEndPos := token.NoPos
// Inspect the AST identify all string literals.
ast.Inspect(f, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.GenDecl:
// Ignore import tokens
if x.Tok == token.IMPORT {
if len(x.Specs) > 1 {
// Capture token positions to filter literals in multiline imports
importStartPos = x.Pos()
importEndPos = x.End()
}
}
case *ast.BasicLit:
if x.Kind == token.STRING {
// Prevent duplicates
if !inSlice(x.Value, *queries) {
// Ignore empty strings and string format placeholder literals
if x.Value == "" || (formatPlaceholderRegex.FindString(x.Value) != "" && len(x.Value) <= formatPlaceholderThreshold) {
return true
}
// Filter literals contained by multiline imports
if importStartPos != token.NoPos && importEndPos != token.NoPos {
if importStartPos <= x.Pos() && importEndPos >= x.End() {
return true
}
}
*queries = append(*queries, x.Value)
position := fset.Position(n.Pos())
tree.Add(x.Value, &position)
//fmt.Printf("Adding %v\n", x.Value)
}
}
}
return true
})
}
func inSlice(a string, list []string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}
func GetApproximateMatches(tree Tree, queries []string, distance int) *map[string][]*ResultInfo {
results := map[string][]*Node{}
matchIndex := map[string]bool{}
for _, query := range queries {
matches := tree.Search(query, distance)
sort.Sort(ByNode(matches))
matchHash := sha1.New()
for _, match := range matches {
io.WriteString(matchHash, fmt.Sprintf("%#v", match))
}
if len(matches) == 0 {
continue
}
// Index queries with equal matches only once
matchDigest := fmt.Sprintf("% x", matchHash.Sum(nil))
if _, ok := matchIndex[matchDigest]; !ok {
results[query] = matches
matchIndex[matchDigest] = true
}
}
/*
Results are duplicated via their reciprocals:
- query "hello"
match in ".../example.go": "Hella"
- query "hella"
match in ".../example.go": "Hello"
A last processing step over the results is necessary in order to group these
*/
groupedResults := groupResults(results)
return groupedResults
}
type ResultInfo struct {
Node *Node
AssociatedQueries string
}
type ResultCandidate struct {
Query string
NodeWords string
Result []*Node
}
func groupResults(results map[string][]*Node) *map[string][]*ResultInfo {
candidates := &[]*ResultCandidate{}
for query, nodes := range results {
wordAcc := &[]string{}
for _, node := range nodes {
*wordAcc = append(*wordAcc, node.Word)
}
sort.Strings(*wordAcc)
*candidates = append(*candidates, &ResultCandidate{
Query: query,
Result: results[query],
NodeWords: strings.ToLower(strings.Join(*wordAcc, "")),
})
}
groupedResults := removeDuplicates(candidates)
return groupedResults
}
func removeDuplicates(elements *[]*ResultCandidate) *map[string][]*ResultInfo {
groupedResults := map[string][]*ResultInfo{}
encountered := map[string]bool{}
for _, v := range *elements {
keys := []string{strings.ToLower(v.Query), v.NodeWords}
sort.Strings(keys)
compositeKey := strings.Join(keys, "")
if encountered[compositeKey] == false {
encountered[compositeKey] = true
groupedResults[v.Query] = []*ResultInfo{}
for _, result := range v.Result {
groupedResults[v.Query] = append(groupedResults[v.Query], &ResultInfo{
Node: result,
AssociatedQueries: v.Query + " <-> " + result.Word,
})
}
}
}
return &groupedResults
}
func IndexSourcesFromPath(pathArgPtr *string) (Tree, []string) {
fileList := getSourceFiles(*pathArgPtr)
tree := Tree{}
queries := []string{}
for _, fileName := range fileList {
inspect(fileName, &tree, &queries)
}
return tree, queries
}
func getSourceFiles(path string) []string {
var files []string
filepath.Walk(path, func(path string, f os.FileInfo, _ error) error {
if f != nil && !f.IsDir() {
if filepath.Ext(path) == ".go" {
files = append(files, path)
}
}
return nil
})
return files
}
func ParseArgs() (*int, string) {
pathArgPtr := flag.String("dir", "", "Path containing the source to analyze. If none, will use os.Getwd()")
distanceArgPtr := flag.Int("dist", 2, "Levenshtein-Damerau distance threshold. Default is 2")
flag.Parse()
sourcePath := ""
if *pathArgPtr == "" {
sourcePath, _ = os.Getwd()
} else {
sourcePath = *pathArgPtr
}
if _, err := os.Stat(sourcePath); os.IsNotExist(err) {
println("Invalid argument. A valid directory path is required: " + err.Error())
}
return distanceArgPtr, sourcePath
}