shotness.go 13 KB

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