uast.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. package hercules
  2. import (
  3. "bytes"
  4. "context"
  5. "errors"
  6. "fmt"
  7. "io"
  8. goioutil "io/ioutil"
  9. "os"
  10. "runtime"
  11. "strings"
  12. "sync"
  13. "time"
  14. "github.com/gogo/protobuf/proto"
  15. "github.com/jeffail/tunny"
  16. "gopkg.in/bblfsh/client-go.v2"
  17. "gopkg.in/bblfsh/sdk.v1/protocol"
  18. "gopkg.in/bblfsh/sdk.v1/uast"
  19. "gopkg.in/src-d/enry.v1"
  20. "gopkg.in/src-d/go-git.v4"
  21. "gopkg.in/src-d/go-git.v4/plumbing"
  22. "gopkg.in/src-d/go-git.v4/plumbing/object"
  23. "gopkg.in/src-d/go-git.v4/utils/ioutil"
  24. "gopkg.in/src-d/go-git.v4/utils/merkletrie"
  25. "gopkg.in/src-d/hercules.v3/pb"
  26. )
  27. type UASTExtractor struct {
  28. Endpoint string
  29. Context func() context.Context
  30. PoolSize int
  31. Languages map[string]bool
  32. FailOnErrors bool
  33. ProcessedFiles map[string]int
  34. clients []*bblfsh.Client
  35. pool *tunny.WorkPool
  36. }
  37. const (
  38. UAST_EXTRACTION_SKIPPED = -(1 << 31)
  39. ConfigUASTEndpoint = "ConfigUASTEndpoint"
  40. ConfigUASTTimeout = "ConfigUASTTimeout"
  41. ConfigUASTPoolSize = "ConfigUASTPoolSize"
  42. ConfigUASTFailOnErrors = "ConfigUASTFailOnErrors"
  43. ConfigUASTLanguages = "ConfigUASTLanguages"
  44. )
  45. type uastTask struct {
  46. Client *bblfsh.Client
  47. Lock *sync.RWMutex
  48. Dest map[plumbing.Hash]*uast.Node
  49. File *object.File
  50. Errors *[]error
  51. Status chan int
  52. }
  53. type worker struct {
  54. Client *bblfsh.Client
  55. Job func(interface{}) interface{}
  56. }
  57. func (w worker) TunnyReady() bool {
  58. return true
  59. }
  60. func (w worker) TunnyJob(data interface{}) interface{} {
  61. task := data.(uastTask)
  62. task.Client = w.Client
  63. return w.Job(task)
  64. }
  65. func (exr *UASTExtractor) Name() string {
  66. return "UAST"
  67. }
  68. func (exr *UASTExtractor) Provides() []string {
  69. arr := [...]string{"uasts"}
  70. return arr[:]
  71. }
  72. func (exr *UASTExtractor) Requires() []string {
  73. arr := [...]string{"changes", "blob_cache"}
  74. return arr[:]
  75. }
  76. func (exr *UASTExtractor) Features() []string {
  77. arr := [...]string{"uast"}
  78. return arr[:]
  79. }
  80. func (exr *UASTExtractor) ListConfigurationOptions() []ConfigurationOption {
  81. options := [...]ConfigurationOption{{
  82. Name: ConfigUASTEndpoint,
  83. Description: "How many days there are in a single band.",
  84. Flag: "bblfsh",
  85. Type: StringConfigurationOption,
  86. Default: "0.0.0.0:9432"}, {
  87. Name: ConfigUASTTimeout,
  88. Description: "Babelfish's server timeout in seconds.",
  89. Flag: "bblfsh-timeout",
  90. Type: IntConfigurationOption,
  91. Default: 20}, {
  92. Name: ConfigUASTPoolSize,
  93. Description: "Number of goroutines to extract UASTs.",
  94. Flag: "bblfsh-pool-size",
  95. Type: IntConfigurationOption,
  96. Default: runtime.NumCPU()}, {
  97. Name: ConfigUASTFailOnErrors,
  98. Description: "Panic if there is a UAST extraction error.",
  99. Flag: "bblfsh-fail-on-error",
  100. Type: BoolConfigurationOption,
  101. Default: false}, {
  102. Name: ConfigUASTLanguages,
  103. Description: "Programming languages from which to extract UASTs. Separated by comma \",\".",
  104. Flag: "languages",
  105. Type: StringConfigurationOption,
  106. Default: "Python,Java"},
  107. }
  108. return options[:]
  109. }
  110. func (exr *UASTExtractor) Configure(facts map[string]interface{}) {
  111. if val, exists := facts[ConfigUASTEndpoint].(string); exists {
  112. exr.Endpoint = val
  113. }
  114. if val, exists := facts[ConfigUASTTimeout].(int); exists {
  115. exr.Context = func() context.Context {
  116. ctx, _ := context.WithTimeout(context.Background(),
  117. time.Duration(val)*time.Second)
  118. return ctx
  119. }
  120. }
  121. if val, exists := facts[ConfigUASTPoolSize].(int); exists {
  122. exr.PoolSize = val
  123. }
  124. if val, exists := facts[ConfigUASTLanguages].(string); exists {
  125. exr.Languages = map[string]bool{}
  126. for _, lang := range strings.Split(val, ",") {
  127. exr.Languages[strings.TrimSpace(lang)] = true
  128. }
  129. }
  130. if val, exists := facts[ConfigUASTFailOnErrors].(bool); exists {
  131. exr.FailOnErrors = val
  132. }
  133. }
  134. func (exr *UASTExtractor) Initialize(repository *git.Repository) {
  135. if exr.Context == nil {
  136. exr.Context = func() context.Context { return context.Background() }
  137. }
  138. poolSize := exr.PoolSize
  139. if poolSize == 0 {
  140. poolSize = runtime.NumCPU()
  141. }
  142. var err error
  143. exr.clients = make([]*bblfsh.Client, poolSize)
  144. for i := 0; i < poolSize; i++ {
  145. client, err := bblfsh.NewClient(exr.Endpoint)
  146. if err != nil {
  147. panic(err)
  148. }
  149. exr.clients[i] = client
  150. }
  151. if exr.pool != nil {
  152. exr.pool.Close()
  153. }
  154. workers := make([]tunny.TunnyWorker, poolSize)
  155. for i := 0; i < poolSize; i++ {
  156. workers[i] = worker{Client: exr.clients[i], Job: exr.extractTask}
  157. }
  158. exr.pool, err = tunny.CreateCustomPool(workers).Open()
  159. if err != nil {
  160. panic(err)
  161. }
  162. exr.ProcessedFiles = map[string]int{}
  163. if exr.Languages == nil {
  164. exr.Languages = map[string]bool{}
  165. }
  166. }
  167. func (exr *UASTExtractor) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  168. cache := deps["blob_cache"].(map[plumbing.Hash]*object.Blob)
  169. treeDiffs := deps["changes"].(object.Changes)
  170. uasts := map[plumbing.Hash]*uast.Node{}
  171. lock := sync.RWMutex{}
  172. errs := make([]error, 0)
  173. status := make(chan int)
  174. pending := 0
  175. submit := func(change *object.Change) {
  176. {
  177. reader, err := cache[change.To.TreeEntry.Hash].Reader()
  178. if err != nil {
  179. errs = append(errs, err)
  180. return
  181. }
  182. defer ioutil.CheckClose(reader, &err)
  183. buf := new(bytes.Buffer)
  184. if _, err := buf.ReadFrom(reader); err != nil {
  185. errs = append(errs, err)
  186. return
  187. }
  188. lang := enry.GetLanguage(change.To.Name, buf.Bytes())
  189. if _, exists := exr.Languages[lang]; !exists {
  190. exr.ProcessedFiles[change.To.Name] = UAST_EXTRACTION_SKIPPED
  191. return
  192. }
  193. exr.ProcessedFiles[change.To.Name]++
  194. }
  195. pending++
  196. exr.pool.SendWorkAsync(uastTask{
  197. Lock: &lock,
  198. Dest: uasts,
  199. File: &object.File{Name: change.To.Name, Blob: *cache[change.To.TreeEntry.Hash]},
  200. Errors: &errs, Status: status}, nil)
  201. }
  202. for _, change := range treeDiffs {
  203. action, err := change.Action()
  204. if err != nil {
  205. return nil, err
  206. }
  207. switch action {
  208. case merkletrie.Insert:
  209. submit(change)
  210. case merkletrie.Delete:
  211. continue
  212. case merkletrie.Modify:
  213. submit(change)
  214. }
  215. }
  216. for i := 0; i < pending; i++ {
  217. _ = <-status
  218. }
  219. if len(errs) > 0 {
  220. msgs := make([]string, len(errs))
  221. for i, err := range errs {
  222. msgs[i] = err.Error()
  223. }
  224. joined := strings.Join(msgs, "\n")
  225. if exr.FailOnErrors {
  226. return nil, errors.New(joined)
  227. } else {
  228. fmt.Fprintln(os.Stderr, joined)
  229. }
  230. }
  231. return map[string]interface{}{"uasts": uasts}, nil
  232. }
  233. func (exr *UASTExtractor) extractUAST(
  234. client *bblfsh.Client, file *object.File) (*uast.Node, error) {
  235. request := client.NewParseRequest()
  236. contents, err := file.Contents()
  237. if err != nil {
  238. return nil, err
  239. }
  240. request.Content(contents)
  241. request.Filename(file.Name)
  242. response, err := request.DoWithContext(exr.Context())
  243. if err != nil {
  244. if strings.Contains("missing driver", err.Error()) {
  245. return nil, nil
  246. }
  247. return nil, err
  248. }
  249. if response.Status != protocol.Ok {
  250. return nil, errors.New(strings.Join(response.Errors, "\n"))
  251. }
  252. if err != nil {
  253. return nil, err
  254. }
  255. return response.UAST, nil
  256. }
  257. func (exr *UASTExtractor) extractTask(data interface{}) interface{} {
  258. task := data.(uastTask)
  259. defer func() { task.Status <- 0 }()
  260. node, err := exr.extractUAST(task.Client, task.File)
  261. task.Lock.Lock()
  262. defer task.Lock.Unlock()
  263. if err != nil {
  264. *task.Errors = append(*task.Errors, errors.New(task.File.Name+": "+err.Error()))
  265. return nil
  266. }
  267. if node != nil {
  268. task.Dest[task.File.Hash] = node
  269. }
  270. return nil
  271. }
  272. type UASTChange struct {
  273. Before *uast.Node
  274. After *uast.Node
  275. Change *object.Change
  276. }
  277. type UASTChanges struct {
  278. cache map[plumbing.Hash]*uast.Node
  279. }
  280. func (uc *UASTChanges) Name() string {
  281. return "UASTChanges"
  282. }
  283. func (uc *UASTChanges) Provides() []string {
  284. arr := [...]string{"changed_uasts"}
  285. return arr[:]
  286. }
  287. func (uc *UASTChanges) Requires() []string {
  288. arr := [...]string{"uasts", "changes"}
  289. return arr[:]
  290. }
  291. func (uc *UASTChanges) Features() []string {
  292. arr := [...]string{"uast"}
  293. return arr[:]
  294. }
  295. func (uc *UASTChanges) ListConfigurationOptions() []ConfigurationOption {
  296. return []ConfigurationOption{}
  297. }
  298. func (uc *UASTChanges) Configure(facts map[string]interface{}) {}
  299. func (uc *UASTChanges) Initialize(repository *git.Repository) {
  300. uc.cache = map[plumbing.Hash]*uast.Node{}
  301. }
  302. func (uc *UASTChanges) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  303. uasts := deps["uasts"].(map[plumbing.Hash]*uast.Node)
  304. treeDiffs := deps["changes"].(object.Changes)
  305. commit := make([]UASTChange, 0, len(treeDiffs))
  306. for _, change := range treeDiffs {
  307. action, err := change.Action()
  308. if err != nil {
  309. return nil, err
  310. }
  311. switch action {
  312. case merkletrie.Insert:
  313. hashTo := change.To.TreeEntry.Hash
  314. uastTo := uasts[hashTo]
  315. commit = append(commit, UASTChange{Before: nil, After: uastTo, Change: change})
  316. uc.cache[hashTo] = uastTo
  317. case merkletrie.Delete:
  318. hashFrom := change.From.TreeEntry.Hash
  319. commit = append(commit, UASTChange{Before: uc.cache[hashFrom], After: nil, Change: change})
  320. delete(uc.cache, hashFrom)
  321. case merkletrie.Modify:
  322. hashFrom := change.From.TreeEntry.Hash
  323. hashTo := change.To.TreeEntry.Hash
  324. uastTo := uasts[hashTo]
  325. commit = append(commit, UASTChange{Before: uc.cache[hashFrom], After: uastTo, Change: change})
  326. delete(uc.cache, hashFrom)
  327. uc.cache[hashTo] = uastTo
  328. }
  329. }
  330. return map[string]interface{}{"changed_uasts": commit}, nil
  331. }
  332. type UASTChangesSaver struct {
  333. // OutputPath points to the target directory with UASTs
  334. OutputPath string
  335. repository *git.Repository
  336. result [][]UASTChange
  337. }
  338. const (
  339. ConfigUASTChangesSaverOutputPath = "UASTChangesSaver.OutputPath"
  340. )
  341. func (saver *UASTChangesSaver) Name() string {
  342. return "UASTChangesSaver"
  343. }
  344. func (saver *UASTChangesSaver) Provides() []string {
  345. return []string{}
  346. }
  347. func (saver *UASTChangesSaver) Requires() []string {
  348. arr := [...]string{"changed_uasts"}
  349. return arr[:]
  350. }
  351. func (saver *UASTChangesSaver) Features() []string {
  352. arr := [...]string{"uast"}
  353. return arr[:]
  354. }
  355. func (saver *UASTChangesSaver) ListConfigurationOptions() []ConfigurationOption {
  356. options := [...]ConfigurationOption{{
  357. Name: ConfigUASTChangesSaverOutputPath,
  358. Description: "The target directory where to store the changed UAST files.",
  359. Flag: "changed-uast-dir",
  360. Type: StringConfigurationOption,
  361. Default: "."},
  362. }
  363. return options[:]
  364. }
  365. func (saver *UASTChangesSaver) Flag() string {
  366. return "dump-uast-changes"
  367. }
  368. func (saver *UASTChangesSaver) Configure(facts map[string]interface{}) {
  369. if val, exists := facts[ConfigUASTChangesSaverOutputPath]; exists {
  370. saver.OutputPath = val.(string)
  371. }
  372. }
  373. func (saver *UASTChangesSaver) Initialize(repository *git.Repository) {
  374. saver.repository = repository
  375. saver.result = [][]UASTChange{}
  376. }
  377. func (saver *UASTChangesSaver) Consume(deps map[string]interface{}) (map[string]interface{}, error) {
  378. changes := deps["changed_uasts"].([]UASTChange)
  379. saver.result = append(saver.result, changes)
  380. return nil, nil
  381. }
  382. func (saver *UASTChangesSaver) Finalize() interface{} {
  383. return saver.result
  384. }
  385. func (saver *UASTChangesSaver) Serialize(result interface{}, binary bool, writer io.Writer) error {
  386. saverResult := result.([][]UASTChange)
  387. fileNames := saver.dumpFiles(saverResult)
  388. if binary {
  389. return saver.serializeBinary(fileNames, writer)
  390. }
  391. saver.serializeText(fileNames, writer)
  392. return nil
  393. }
  394. func (saver *UASTChangesSaver) dumpFiles(result [][]UASTChange) []*pb.UASTChange {
  395. fileNames := []*pb.UASTChange{}
  396. for i, changes := range result {
  397. for j, change := range changes {
  398. if change.Before == nil || change.After == nil {
  399. continue
  400. }
  401. record := &pb.UASTChange{FileName: change.Change.To.Name}
  402. bs, _ := change.Before.Marshal()
  403. record.UastBefore = fmt.Sprintf(
  404. "%d_%d_before_%s.pb", i, j, change.Change.From.TreeEntry.Hash.String())
  405. goioutil.WriteFile(record.UastBefore, bs, 0666)
  406. blob, _ := saver.repository.BlobObject(change.Change.From.TreeEntry.Hash)
  407. s, _ := (&object.File{Blob: *blob}).Contents()
  408. record.SrcBefore = fmt.Sprintf(
  409. "%d_%d_before_%s.src", i, j, change.Change.From.TreeEntry.Hash.String())
  410. goioutil.WriteFile(record.SrcBefore, []byte(s), 0666)
  411. bs, _ = change.After.Marshal()
  412. record.UastAfter = fmt.Sprintf(
  413. "%d_%d_after_%s.pb", i, j, change.Change.To.TreeEntry.Hash.String())
  414. goioutil.WriteFile(record.UastAfter, bs, 0666)
  415. blob, _ = saver.repository.BlobObject(change.Change.To.TreeEntry.Hash)
  416. s, _ = (&object.File{Blob: *blob}).Contents()
  417. record.SrcAfter = fmt.Sprintf(
  418. "%d_%d_after_%s.src", i, j, change.Change.To.TreeEntry.Hash.String())
  419. goioutil.WriteFile(record.SrcAfter, []byte(s), 0666)
  420. fileNames = append(fileNames, record)
  421. }
  422. }
  423. return fileNames
  424. }
  425. func (saver *UASTChangesSaver) serializeText(result []*pb.UASTChange, writer io.Writer) {
  426. for _, sc := range result {
  427. kv := [...]string{
  428. "file: " + sc.FileName,
  429. "src0: " + sc.SrcBefore, "src1: " + sc.SrcAfter,
  430. "uast0: " + sc.UastBefore, "uast1: " + sc.UastAfter,
  431. }
  432. fmt.Fprintf(writer, " - {%s}\n", strings.Join(kv[:], ", "))
  433. }
  434. }
  435. func (saver *UASTChangesSaver) serializeBinary(result []*pb.UASTChange, writer io.Writer) error {
  436. message := pb.UASTChangesSaverResults{Changes: result}
  437. serialized, err := proto.Marshal(&message)
  438. if err != nil {
  439. return err
  440. }
  441. writer.Write(serialized)
  442. return nil
  443. }
  444. func init() {
  445. Registry.Register(&UASTExtractor{})
  446. Registry.Register(&UASTChanges{})
  447. Registry.Register(&UASTChangesSaver{})
  448. }