typos.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. package research
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "log"
  7. "unicode/utf8"
  8. "github.com/gogo/protobuf/proto"
  9. "github.com/sergi/go-diff/diffmatchpatch"
  10. "gopkg.in/bblfsh/sdk.v2/uast"
  11. "gopkg.in/bblfsh/sdk.v2/uast/nodes"
  12. "gopkg.in/src-d/go-git.v4"
  13. "gopkg.in/src-d/go-git.v4/plumbing"
  14. "gopkg.in/src-d/go-git.v4/plumbing/object"
  15. "gopkg.in/src-d/hercules.v10/internal/core"
  16. "gopkg.in/src-d/hercules.v10/internal/levenshtein"
  17. "gopkg.in/src-d/hercules.v10/internal/pb"
  18. items "gopkg.in/src-d/hercules.v10/internal/plumbing"
  19. uast_items "gopkg.in/src-d/hercules.v10/internal/plumbing/uast"
  20. )
  21. // TyposDatasetBuilder collects pairs of typo-fix in source code identifiers.
  22. type TyposDatasetBuilder struct {
  23. core.NoopMerger
  24. // MaximumAllowedDistance is the maximum Levenshtein distance between two identifiers
  25. // to consider them a typo-fix pair.
  26. MaximumAllowedDistance int
  27. // typos stores the found typo-fix pairs.
  28. typos []Typo
  29. // lcontext is the Context for measuring Levenshtein distance between lines.
  30. lcontext *levenshtein.Context
  31. // xpather filters identifiers.
  32. xpather uast_items.ChangesXPather
  33. // remote carries the repository remote URL (for debugging)
  34. remote string
  35. }
  36. // TyposResult is returned by TyposDatasetBuilder.Finalize() and carries the found typo-fix
  37. // pairs of identifiers.
  38. type TyposResult struct {
  39. Typos []Typo
  40. }
  41. // Typo carries the information about a typo-fix pair.
  42. type Typo struct {
  43. Wrong string
  44. Correct string
  45. Commit plumbing.Hash
  46. File string
  47. Line int
  48. }
  49. const (
  50. // DefaultMaximumAllowedTypoDistance is the default value of the maximum Levenshtein distance
  51. // between two identifiers to consider them a typo-fix pair.
  52. DefaultMaximumAllowedTypoDistance = 4
  53. // ConfigTyposDatasetMaximumAllowedDistance is the name of the configuration option
  54. // (`TyposDatasetBuilder.Configure()`) which sets the maximum Levenshtein distance between
  55. // two identifiers to consider them a typo-fix pair.
  56. ConfigTyposDatasetMaximumAllowedDistance = "TyposDatasetBuilder.MaximumAllowedDistance"
  57. )
  58. // Name of this PipelineItem. Uniquely identifies the type, used for mapping keys, etc.
  59. func (tdb *TyposDatasetBuilder) Name() string {
  60. return "TyposDataset"
  61. }
  62. // Provides returns the list of names of entities which are produced by this PipelineItem.
  63. // Each produced entity will be inserted into `deps` of dependent Consume()-s according
  64. // to this list. Also used by core.Registry to build the global map of providers.
  65. func (tdb *TyposDatasetBuilder) Provides() []string {
  66. return []string{}
  67. }
  68. // Requires returns the list of names of entities which are needed by this PipelineItem.
  69. // Each requested entity will be inserted into `deps` of Consume(). In turn, those
  70. // entities are Provides() upstream.
  71. func (tdb *TyposDatasetBuilder) Requires() []string {
  72. arr := [...]string{
  73. uast_items.DependencyUastChanges, items.DependencyFileDiff, items.DependencyBlobCache}
  74. return arr[:]
  75. }
  76. // ListConfigurationOptions returns the list of changeable public properties of this PipelineItem.
  77. func (tdb *TyposDatasetBuilder) ListConfigurationOptions() []core.ConfigurationOption {
  78. options := [...]core.ConfigurationOption{{
  79. Name: ConfigTyposDatasetMaximumAllowedDistance,
  80. Description: "Maximum Levenshtein distance between two identifiers to consider them " +
  81. "a typo-fix pair.",
  82. Flag: "typos-max-distance",
  83. Type: core.IntConfigurationOption,
  84. Default: DefaultMaximumAllowedTypoDistance},
  85. }
  86. return options[:]
  87. }
  88. // Configure sets the properties previously published by ListConfigurationOptions().
  89. func (tdb *TyposDatasetBuilder) Configure(facts map[string]interface{}) error {
  90. if val, exists := facts[ConfigTyposDatasetMaximumAllowedDistance].(int); exists {
  91. tdb.MaximumAllowedDistance = val
  92. }
  93. return nil
  94. }
  95. // Flag for the command line switch which enables this analysis.
  96. func (tdb *TyposDatasetBuilder) Flag() string {
  97. return "typos-dataset"
  98. }
  99. // Description returns the text which explains what the analysis is doing.
  100. func (tdb *TyposDatasetBuilder) Description() string {
  101. return "Extracts typo-fix identifier pairs from source code in commit diffs."
  102. }
  103. // Initialize resets the temporary caches and prepares this PipelineItem for a series of Consume()
  104. // calls. The repository which is going to be analysed is supplied as an argument.
  105. func (tdb *TyposDatasetBuilder) Initialize(repository *git.Repository) error {
  106. if tdb.MaximumAllowedDistance <= 0 {
  107. tdb.MaximumAllowedDistance = DefaultMaximumAllowedTypoDistance
  108. }
  109. tdb.lcontext = &levenshtein.Context{}
  110. tdb.xpather.XPath = "//uast:Identifier"
  111. tdb.remote = core.GetSensibleRemote(repository)
  112. return nil
  113. }
  114. type candidate struct {
  115. Before int
  116. After int
  117. }
  118. // Consume runs this PipelineItem on the next commit data.
  119. // `deps` contain all the results from upstream PipelineItem-s as requested by Requires().
  120. // Additionally, DependencyCommit is always present there and represents the analysed *object.Commit.
  121. // This function returns the mapping with analysis results. The keys must be the same as
  122. // in Provides(). If there was an error, nil is returned.
  123. func (tdb *TyposDatasetBuilder) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  124. if deps[core.DependencyIsMerge].(bool) {
  125. return nil, nil
  126. }
  127. commit := deps[core.DependencyCommit].(*object.Commit).Hash
  128. cache := deps[items.DependencyBlobCache].(map[plumbing.Hash]*items.CachedBlob)
  129. diffs := deps[items.DependencyFileDiff].(map[string]items.FileDiffData)
  130. changes := deps[uast_items.DependencyUastChanges].([]uast_items.Change)
  131. for _, change := range changes {
  132. if change.Before == nil || change.After == nil {
  133. continue
  134. }
  135. linesBefore := bytes.Split(cache[change.Change.From.TreeEntry.Hash].Data, []byte{'\n'})
  136. linesAfter := bytes.Split(cache[change.Change.To.TreeEntry.Hash].Data, []byte{'\n'})
  137. diff := diffs[change.Change.To.Name]
  138. var lineNumBefore, lineNumAfter int
  139. var candidates []candidate
  140. focusedLinesBefore := map[int]bool{}
  141. focusedLinesAfter := map[int]bool{}
  142. removedSize := 0
  143. for _, edit := range diff.Diffs {
  144. size := utf8.RuneCountInString(edit.Text)
  145. switch edit.Type {
  146. case diffmatchpatch.DiffDelete:
  147. lineNumBefore += size
  148. removedSize = size
  149. case diffmatchpatch.DiffInsert:
  150. if size == removedSize {
  151. for i := 0; i < size; i++ {
  152. lb := lineNumBefore - size + i
  153. la := lineNumAfter + i
  154. dist := tdb.lcontext.Distance(string(linesBefore[lb]), string(linesAfter[la]))
  155. if dist <= tdb.MaximumAllowedDistance {
  156. candidates = append(candidates, candidate{lb, la})
  157. focusedLinesBefore[lb] = true
  158. focusedLinesAfter[la] = true
  159. }
  160. }
  161. }
  162. lineNumAfter += size
  163. removedSize = 0
  164. case diffmatchpatch.DiffEqual:
  165. lineNumBefore += size
  166. lineNumAfter += size
  167. removedSize = 0
  168. }
  169. }
  170. if len(candidates) == 0 {
  171. continue
  172. }
  173. // at this point we have pairs of very similar lines
  174. // we need to build the line mappings of the identifiers before/after the change
  175. // we should keep only those which are present on those focused lines
  176. nodesAdded, nodesRemoved := tdb.xpather.Extract([]uast_items.Change{change})
  177. addedIdentifiers := map[int][]nodes.Node{}
  178. removedIdentifiers := map[int][]nodes.Node{}
  179. for _, n := range nodesAdded {
  180. pos := uast.PositionsOf(n.(nodes.Object))
  181. if pos.Start() == nil {
  182. log.Printf("repo %s commit %s file %s adds identifier %s with no position",
  183. tdb.remote, commit.String(), change.Change.To.Name,
  184. n.(nodes.Object)["Name"].(nodes.String))
  185. continue
  186. }
  187. line := int(pos.Start().Line) - 1
  188. if focusedLinesAfter[line] {
  189. addedIdentifiers[line] = append(addedIdentifiers[line], n)
  190. }
  191. }
  192. for _, n := range nodesRemoved {
  193. pos := uast.PositionsOf(n.(nodes.Object))
  194. if pos.Start() == nil {
  195. log.Printf("repo %s commit %s file %s removes identifier %s with no position",
  196. tdb.remote, commit.String(), change.Change.To.Name,
  197. n.(nodes.Object)["Name"].(nodes.String))
  198. continue
  199. }
  200. line := int(pos.Start().Line) - 1
  201. if focusedLinesBefore[line] {
  202. removedIdentifiers[line] = append(removedIdentifiers[line], n)
  203. }
  204. }
  205. for _, c := range candidates {
  206. nodesBefore := removedIdentifiers[c.Before]
  207. nodesAfter := addedIdentifiers[c.After]
  208. if len(nodesBefore) == 1 && len(nodesAfter) == 1 {
  209. idBefore := string(nodesBefore[0].(nodes.Object)["Name"].(nodes.String))
  210. idAfter := string(nodesAfter[0].(nodes.Object)["Name"].(nodes.String))
  211. tdb.typos = append(tdb.typos, Typo{
  212. Wrong: idBefore,
  213. Correct: idAfter,
  214. Commit: commit,
  215. File: change.Change.To.Name,
  216. Line: c.After,
  217. })
  218. }
  219. }
  220. }
  221. return nil, nil
  222. }
  223. // Finalize returns the result of the analysis. Further Consume() calls are not expected.
  224. func (tdb *TyposDatasetBuilder) Finalize() interface{} {
  225. // deduplicate
  226. typos := make([]Typo, 0, len(tdb.typos))
  227. pairs := map[string]bool{}
  228. for _, t := range tdb.typos {
  229. id := t.Wrong + "|" + t.Correct
  230. if _, exists := pairs[id]; !exists {
  231. pairs[id] = true
  232. typos = append(typos, t)
  233. }
  234. }
  235. return TyposResult{Typos: typos}
  236. }
  237. // Fork clones this pipeline item.
  238. func (tdb *TyposDatasetBuilder) Fork(n int) []core.PipelineItem {
  239. return core.ForkSamePipelineItem(tdb, n)
  240. }
  241. // Serialize converts the analysis result as returned by Finalize() to text or bytes.
  242. // The text format is YAML and the bytes format is Protocol Buffers.
  243. func (tdb *TyposDatasetBuilder) Serialize(result interface{}, binary bool, writer io.Writer) error {
  244. commitsResult := result.(TyposResult)
  245. if binary {
  246. return tdb.serializeBinary(&commitsResult, writer)
  247. }
  248. tdb.serializeText(&commitsResult, writer)
  249. return nil
  250. }
  251. func (tdb *TyposDatasetBuilder) serializeText(result *TyposResult, writer io.Writer) {
  252. for _, t := range result.Typos {
  253. fmt.Fprintf(writer, " - wrong: %s\n", t.Wrong)
  254. fmt.Fprintf(writer, " correct: %s\n", t.Correct)
  255. fmt.Fprintf(writer, " commit: %s\n", t.Commit.String())
  256. fmt.Fprintf(writer, " file: %s\n", t.File)
  257. fmt.Fprintf(writer, " line: %d\n", t.Line)
  258. }
  259. }
  260. func (tdb *TyposDatasetBuilder) serializeBinary(result *TyposResult, writer io.Writer) error {
  261. message := pb.TyposDataset{}
  262. message.Typos = make([]*pb.Typo, len(result.Typos))
  263. for i, t := range result.Typos {
  264. message.Typos[i] = &pb.Typo{
  265. Wrong: t.Wrong,
  266. Correct: t.Correct,
  267. Commit: t.Commit.String(),
  268. File: t.File,
  269. Line: int32(t.Line),
  270. }
  271. }
  272. serialized, err := proto.Marshal(&message)
  273. if err != nil {
  274. return err
  275. }
  276. _, err = writer.Write(serialized)
  277. return err
  278. }
  279. func init() {
  280. core.Registry.Register(&TyposDatasetBuilder{})
  281. }