shotness.go 16 KB

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