shotness.go 13 KB

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