shotness.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. package leaves
  2. import (
  3. "fmt"
  4. "io"
  5. "log"
  6. "sort"
  7. "unicode/utf8"
  8. "github.com/gogo/protobuf/proto"
  9. "github.com/sergi/go-diff/diffmatchpatch"
  10. "gopkg.in/bblfsh/client-go.v3/tools"
  11. "gopkg.in/bblfsh/sdk.v2/uast"
  12. uast_nodes "gopkg.in/bblfsh/sdk.v2/uast/nodes"
  13. "gopkg.in/bblfsh/sdk.v2/uast/query"
  14. "gopkg.in/src-d/go-git.v4"
  15. "gopkg.in/src-d/go-git.v4/plumbing/object"
  16. "gopkg.in/src-d/hercules.v9/internal/core"
  17. "gopkg.in/src-d/hercules.v9/internal/pb"
  18. items "gopkg.in/src-d/hercules.v9/internal/plumbing"
  19. uast_items "gopkg.in/src-d/hercules.v9/internal/plumbing/uast"
  20. )
  21. // ShotnessAnalysis contains the intermediate state which is mutated by Consume(). It should implement
  22. // LeafPipelineItem.
  23. type ShotnessAnalysis struct {
  24. core.NoopMerger
  25. core.OneShotMergeProcessor
  26. XpathStruct string
  27. XpathName string
  28. nodes map[string]*nodeShotness
  29. files map[string]map[string]*nodeShotness
  30. }
  31. const (
  32. // ConfigShotnessXpathStruct is the name of the configuration option (ShotnessAnalysis.Configure())
  33. // which sets the UAST XPath to choose the analysed nodes.
  34. // The format is Semantic UASTv2, see https://docs.sourced.tech/babelfish/using-babelfish/uast-querying
  35. ConfigShotnessXpathStruct = "Shotness.XpathStruct"
  36. // ConfigShotnessXpathName is the name of the configuration option (ShotnessAnalysis.Configure())
  37. // which sets the UAST XPath to find the name of the nodes chosen by ConfigShotnessXpathStruct.
  38. // The format is Semantic UASTv2, see https://docs.sourced.tech/babelfish/using-babelfish/uast-querying
  39. ConfigShotnessXpathName = "Shotness.XpathName"
  40. // DefaultShotnessXpathStruct is the default UAST XPath to choose the analysed nodes.
  41. // It extracts functions.
  42. DefaultShotnessXpathStruct = "//uast:FunctionGroup"
  43. // DefaultShotnessXpathName is the default UAST XPath to choose the names of the analysed nodes.
  44. // It looks at the current tree level and at the immediate children.
  45. DefaultShotnessXpathName = "/Nodes/uast:Alias/Name"
  46. )
  47. type nodeShotness struct {
  48. Count int
  49. Summary NodeSummary
  50. Couples map[string]int
  51. }
  52. // NodeSummary carries the node attributes which annotate the "shotness" analysis' counters.
  53. // These attributes are supposed to uniquely identify each node.
  54. type NodeSummary struct {
  55. Type string
  56. Name string
  57. File string
  58. }
  59. // ShotnessResult is returned by ShotnessAnalysis.Finalize() and represents the analysis result.
  60. type ShotnessResult struct {
  61. Nodes []NodeSummary
  62. Counters []map[int]int
  63. }
  64. func (node NodeSummary) String() string {
  65. return node.Type + "_" + node.Name + "_" + node.File
  66. }
  67. // Name of this PipelineItem. Uniquely identifies the type, used for mapping keys, etc.
  68. func (shotness *ShotnessAnalysis) Name() string {
  69. return "Shotness"
  70. }
  71. // Provides returns the list of names of entities which are produced by this PipelineItem.
  72. // Each produced entity will be inserted into `deps` of dependent Consume()-s according
  73. // to this list. Also used by core.Registry to build the global map of providers.
  74. func (shotness *ShotnessAnalysis) Provides() []string {
  75. return []string{}
  76. }
  77. // Requires returns the list of names of entities which are needed by this PipelineItem.
  78. // Each requested entity will be inserted into `deps` of Consume(). In turn, those
  79. // entities are Provides() upstream.
  80. func (shotness *ShotnessAnalysis) Requires() []string {
  81. arr := [...]string{items.DependencyFileDiff, uast_items.DependencyUastChanges}
  82. return arr[:]
  83. }
  84. // Features which must be enabled for this PipelineItem to be automatically inserted into the DAG.
  85. func (shotness *ShotnessAnalysis) Features() []string {
  86. arr := [...]string{uast_items.FeatureUast}
  87. return arr[:]
  88. }
  89. // ListConfigurationOptions returns the list of changeable public properties of this PipelineItem.
  90. func (shotness *ShotnessAnalysis) ListConfigurationOptions() []core.ConfigurationOption {
  91. opts := [...]core.ConfigurationOption{{
  92. Name: ConfigShotnessXpathStruct,
  93. Description: "Semantic UAST XPath query to use for filtering the nodes. " +
  94. "Refer to https://docs.sourced.tech/babelfish/using-babelfish/uast-querying",
  95. Flag: "shotness-xpath-struct",
  96. Type: core.StringConfigurationOption,
  97. Default: DefaultShotnessXpathStruct}, {
  98. Name: ConfigShotnessXpathName,
  99. Description: "Semantic UAST XPath query to determine the names of the filtered nodes. " +
  100. "Refer to https://docs.sourced.tech/babelfish/using-babelfish/uast-querying",
  101. Flag: "shotness-xpath-name",
  102. Type: core.StringConfigurationOption,
  103. Default: DefaultShotnessXpathName},
  104. }
  105. return opts[:]
  106. }
  107. // Flag returns the command line switch which activates the analysis.
  108. func (shotness *ShotnessAnalysis) Flag() string {
  109. return "shotness"
  110. }
  111. // Description returns the text which explains what the analysis is doing.
  112. func (shotness *ShotnessAnalysis) Description() string {
  113. return "Structural hotness - a fine-grained alternative to --couples. " +
  114. "Given an XPath over UASTs - selecting functions by default - we build the square " +
  115. "co-occurrence matrix. The value in each cell equals to the number of times the pair " +
  116. "of selected UAST units appeared in the same commit."
  117. }
  118. // Configure sets the properties previously published by ListConfigurationOptions().
  119. func (shotness *ShotnessAnalysis) Configure(facts map[string]interface{}) error {
  120. if val, exists := facts[ConfigShotnessXpathStruct]; exists {
  121. shotness.XpathStruct = val.(string)
  122. } else {
  123. shotness.XpathStruct = DefaultShotnessXpathStruct
  124. }
  125. if val, exists := facts[ConfigShotnessXpathName]; exists {
  126. shotness.XpathName = val.(string)
  127. } else {
  128. shotness.XpathName = DefaultShotnessXpathName
  129. }
  130. return nil
  131. }
  132. // Initialize resets the temporary caches and prepares this PipelineItem for a series of Consume()
  133. // calls. The repository which is going to be analysed is supplied as an argument.
  134. func (shotness *ShotnessAnalysis) Initialize(repository *git.Repository) error {
  135. shotness.nodes = map[string]*nodeShotness{}
  136. shotness.files = map[string]map[string]*nodeShotness{}
  137. shotness.OneShotMergeProcessor.Initialize()
  138. return nil
  139. }
  140. // Consume runs this PipelineItem on the next commit data.
  141. // `deps` contain all the results from upstream PipelineItem-s as requested by Requires().
  142. // Additionally, DependencyCommit is always present there and represents the analysed *object.Commit.
  143. // This function returns the mapping with analysis results. The keys must be the same as
  144. // in Provides(). If there was an error, nil is returned.
  145. func (shotness *ShotnessAnalysis) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  146. if !shotness.ShouldConsumeCommit(deps) {
  147. return nil, nil
  148. }
  149. commit := deps[core.DependencyCommit].(*object.Commit)
  150. changesList := deps[uast_items.DependencyUastChanges].([]uast_items.Change)
  151. diffs := deps[items.DependencyFileDiff].(map[string]items.FileDiffData)
  152. allNodes := map[string]bool{}
  153. addNode := func(name string, node uast_nodes.Node, fileName string) {
  154. nodeSummary := NodeSummary{
  155. Type: uast.TypeOf(node),
  156. Name: name,
  157. File: fileName,
  158. }
  159. key := nodeSummary.String()
  160. exists := allNodes[key]
  161. allNodes[key] = true
  162. var count int
  163. if ns := shotness.nodes[key]; ns != nil {
  164. count = ns.Count
  165. }
  166. if count == 0 {
  167. shotness.nodes[key] = &nodeShotness{
  168. Summary: nodeSummary, Count: 1, Couples: map[string]int{}}
  169. fmap := shotness.files[nodeSummary.File]
  170. if fmap == nil {
  171. fmap = map[string]*nodeShotness{}
  172. }
  173. fmap[key] = shotness.nodes[key]
  174. shotness.files[nodeSummary.File] = fmap
  175. } else if !exists { // in case there are removals and additions in the same node
  176. shotness.nodes[key].Count = count + 1
  177. }
  178. }
  179. for _, change := range changesList {
  180. if change.After == nil {
  181. for key, summary := range shotness.files[change.Change.From.Name] {
  182. for subkey := range summary.Couples {
  183. delete(shotness.nodes[subkey].Couples, key)
  184. }
  185. }
  186. for key := range shotness.files[change.Change.From.Name] {
  187. delete(shotness.nodes, key)
  188. }
  189. delete(shotness.files, change.Change.From.Name)
  190. continue
  191. }
  192. toName := change.Change.To.Name
  193. if change.Before == nil {
  194. nodes, err := shotness.extractNodes(change.After)
  195. if err != nil {
  196. log.Printf("Shotness: commit %s file %s failed to filter UAST: %s\n",
  197. commit.Hash.String(), toName, err.Error())
  198. continue
  199. }
  200. for name, node := range nodes {
  201. addNode(name, node, toName)
  202. }
  203. continue
  204. }
  205. // Before -> After
  206. if change.Change.From.Name != toName {
  207. // renamed
  208. oldFile := shotness.files[change.Change.From.Name]
  209. newFile := map[string]*nodeShotness{}
  210. shotness.files[toName] = newFile
  211. for oldKey, ns := range oldFile {
  212. ns.Summary.File = toName
  213. newKey := ns.Summary.String()
  214. newFile[newKey] = ns
  215. shotness.nodes[newKey] = ns
  216. for coupleKey, count := range ns.Couples {
  217. coupleCouples := shotness.nodes[coupleKey].Couples
  218. delete(coupleCouples, oldKey)
  219. coupleCouples[newKey] = count
  220. }
  221. }
  222. // deferred cleanup is needed
  223. for key := range oldFile {
  224. delete(shotness.nodes, key)
  225. }
  226. delete(shotness.files, change.Change.From.Name)
  227. }
  228. // pass through old UAST
  229. // pass through new UAST
  230. nodesBefore, err := shotness.extractNodes(change.Before)
  231. if err != nil {
  232. log.Printf("Shotness: commit ^%s file %s failed to filter UAST: %s\n",
  233. commit.Hash.String(), change.Change.From.Name, err.Error())
  234. continue
  235. }
  236. reversedNodesBefore := reverseNodeMap(nodesBefore)
  237. nodesAfter, err := shotness.extractNodes(change.After)
  238. if err != nil {
  239. log.Printf("Shotness: commit %s file %s failed to filter UAST: %s\n",
  240. commit.Hash.String(), toName, err.Error())
  241. continue
  242. }
  243. reversedNodesAfter := reverseNodeMap(nodesAfter)
  244. genLine2Node := func(nodes map[string]uast_nodes.Node, linesNum int) [][]uast_nodes.Node {
  245. res := make([][]uast_nodes.Node, linesNum)
  246. for _, node := range nodes {
  247. pos := uast.PositionsOf(node.(uast_nodes.Object))
  248. if pos.Start() == nil {
  249. continue
  250. }
  251. startLine := pos.Start().Line
  252. endLine := pos.Start().Line
  253. if pos.End() != nil && pos.End().Line > pos.Start().Line {
  254. endLine = pos.End().Line
  255. } else {
  256. // we need to determine pos.End().Line
  257. uast_items.VisitEachNode(node, func(child uast_nodes.Node) {
  258. childPos := uast.PositionsOf(child.(uast_nodes.Object))
  259. if childPos.Start() != nil {
  260. candidate := childPos.Start().Line
  261. if childPos.End() != nil {
  262. candidate = childPos.End().Line
  263. }
  264. if candidate > endLine {
  265. endLine = candidate
  266. }
  267. }
  268. })
  269. }
  270. for l := startLine; l <= endLine; l++ {
  271. lineNodes := res[l-1]
  272. if lineNodes == nil {
  273. lineNodes = []uast_nodes.Node{}
  274. }
  275. lineNodes = append(lineNodes, node)
  276. res[l-1] = lineNodes
  277. }
  278. }
  279. return res
  280. }
  281. diff := diffs[toName]
  282. line2nodeBefore := genLine2Node(nodesBefore, diff.OldLinesOfCode)
  283. line2nodeAfter := genLine2Node(nodesAfter, diff.NewLinesOfCode)
  284. // Scan through all the edits. Given the line numbers, get the list of active nodes
  285. // and add them.
  286. var lineNumBefore, lineNumAfter int
  287. for _, edit := range diff.Diffs {
  288. size := utf8.RuneCountInString(edit.Text)
  289. switch edit.Type {
  290. case diffmatchpatch.DiffDelete:
  291. for l := lineNumBefore; l < lineNumBefore+size; l++ {
  292. nodes := line2nodeBefore[l]
  293. for _, node := range nodes {
  294. // toName because we handled a possible rename before
  295. addNode(reversedNodesBefore[uast_nodes.UniqueKey(node)], node, toName)
  296. }
  297. }
  298. lineNumBefore += size
  299. case diffmatchpatch.DiffInsert:
  300. for l := lineNumAfter; l < lineNumAfter+size; l++ {
  301. nodes := line2nodeAfter[l]
  302. for _, node := range nodes {
  303. addNode(reversedNodesAfter[uast_nodes.UniqueKey(node)], node, toName)
  304. }
  305. }
  306. lineNumAfter += size
  307. case diffmatchpatch.DiffEqual:
  308. lineNumBefore += size
  309. lineNumAfter += size
  310. }
  311. }
  312. }
  313. for keyi := range allNodes {
  314. for keyj := range allNodes {
  315. if keyi == keyj {
  316. continue
  317. }
  318. shotness.nodes[keyi].Couples[keyj]++
  319. }
  320. }
  321. return nil, nil
  322. }
  323. // Fork clones this PipelineItem.
  324. func (shotness *ShotnessAnalysis) Fork(n int) []core.PipelineItem {
  325. return core.ForkSamePipelineItem(shotness, n)
  326. }
  327. // Finalize returns the result of the analysis. Further Consume() calls are not expected.
  328. func (shotness *ShotnessAnalysis) Finalize() interface{} {
  329. result := ShotnessResult{
  330. Nodes: make([]NodeSummary, len(shotness.nodes)),
  331. Counters: make([]map[int]int, len(shotness.nodes)),
  332. }
  333. keys := make([]string, len(shotness.nodes))
  334. i := 0
  335. for key := range shotness.nodes {
  336. keys[i] = key
  337. i++
  338. }
  339. sort.Strings(keys)
  340. reverseKeys := map[string]int{}
  341. for i, key := range keys {
  342. reverseKeys[key] = i
  343. }
  344. for i, key := range keys {
  345. node := shotness.nodes[key]
  346. result.Nodes[i] = node.Summary
  347. counter := map[int]int{}
  348. result.Counters[i] = counter
  349. counter[i] = node.Count
  350. for ck, val := range node.Couples {
  351. counter[reverseKeys[ck]] = val
  352. }
  353. }
  354. return result
  355. }
  356. // Serialize converts the analysis result as returned by Finalize() to text or bytes.
  357. // The text format is YAML and the bytes format is Protocol Buffers.
  358. func (shotness *ShotnessAnalysis) Serialize(result interface{}, binary bool, writer io.Writer) error {
  359. shotnessResult := result.(ShotnessResult)
  360. if binary {
  361. return shotness.serializeBinary(&shotnessResult, writer)
  362. }
  363. shotness.serializeText(&shotnessResult, writer)
  364. return nil
  365. }
  366. func (shotness *ShotnessAnalysis) serializeText(result *ShotnessResult, writer io.Writer) {
  367. for i, summary := range result.Nodes {
  368. fmt.Fprintf(writer, " - name: %s\n file: %s\n internal_role: %s\n counters: {",
  369. summary.Name, summary.File, summary.Type)
  370. keys := make([]int, len(result.Counters[i]))
  371. j := 0
  372. for key := range result.Counters[i] {
  373. keys[j] = key
  374. j++
  375. }
  376. sort.Ints(keys)
  377. j = 0
  378. for _, key := range keys {
  379. val := result.Counters[i][key]
  380. if j < len(result.Counters[i])-1 {
  381. fmt.Fprintf(writer, "\"%d\":%d,", key, val)
  382. } else {
  383. fmt.Fprintf(writer, "\"%d\":%d}\n", key, val)
  384. }
  385. j++
  386. }
  387. }
  388. }
  389. func (shotness *ShotnessAnalysis) serializeBinary(result *ShotnessResult, writer io.Writer) error {
  390. message := pb.ShotnessAnalysisResults{
  391. Records: make([]*pb.ShotnessRecord, len(result.Nodes)),
  392. }
  393. for i, summary := range result.Nodes {
  394. record := &pb.ShotnessRecord{
  395. Name: summary.Name,
  396. File: summary.File,
  397. Type: summary.Type,
  398. Counters: map[int32]int32{},
  399. }
  400. for key, val := range result.Counters[i] {
  401. record.Counters[int32(key)] = int32(val)
  402. }
  403. message.Records[i] = record
  404. }
  405. serialized, err := proto.Marshal(&message)
  406. if err != nil {
  407. return err
  408. }
  409. _, err = writer.Write(serialized)
  410. return err
  411. }
  412. func (shotness *ShotnessAnalysis) extractNodes(root uast_nodes.Node) (map[string]uast_nodes.Node, error) {
  413. it, err := tools.Filter(root, shotness.XpathStruct)
  414. if err != nil {
  415. return nil, err
  416. }
  417. structs := query.AllNodes(it)
  418. // some structs may be inside other structs; we pick the outermost
  419. // otherwise due to UAST quirks there may be false positives
  420. internal := map[uast_nodes.Comparable]bool{}
  421. for _, ext := range structs {
  422. mainNode := ext.(uast_nodes.Node)
  423. if internal[uast_nodes.UniqueKey(mainNode)] {
  424. continue
  425. }
  426. subs, err := tools.Filter(mainNode, shotness.XpathStruct)
  427. if err != nil {
  428. return nil, err
  429. }
  430. for subs.Next() {
  431. sub := subs.Node().(uast_nodes.Node)
  432. if uast_nodes.UniqueKey(sub) != uast_nodes.UniqueKey(mainNode) {
  433. internal[uast_nodes.UniqueKey(sub)] = true
  434. }
  435. }
  436. }
  437. res := map[string]uast_nodes.Node{}
  438. for _, ext := range structs {
  439. node := ext.(uast_nodes.Node)
  440. if internal[uast_nodes.UniqueKey(node)] {
  441. continue
  442. }
  443. nodeName, err := tools.FilterNode(node, "/*"+shotness.XpathName)
  444. if err != nil {
  445. return nil, err
  446. }
  447. res[string(nodeName.(uast_nodes.Object)["Name"].(uast_nodes.String))] = node
  448. }
  449. return res, nil
  450. }
  451. func reverseNodeMap(nodes map[string]uast_nodes.Node) map[uast_nodes.Comparable]string {
  452. res := map[uast_nodes.Comparable]string{}
  453. for key, node := range nodes {
  454. res[uast_nodes.UniqueKey(node)] = key
  455. }
  456. return res
  457. }
  458. func init() {
  459. core.Registry.Register(&ShotnessAnalysis{})
  460. }