typos.go 9.8 KB

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