shotness.go 15 KB

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