現場の RubyVM::AbstractSyntaxTree

6a23b69942e4b4f7edc9e6abad702c7a?s=47 hkdnet
June 29, 2019

現場の RubyVM::AbstractSyntaxTree

TokyuRubyKaigi 13 のLTスライドです。
http://regional.rubykaigi.org/tokyu13/

---

RubyVM::AbstractSyntaxTree (AST) is a very useful tool. It is not only used for black magic. It is helpful for your Ruby projects.

6a23b69942e4b4f7edc9e6abad702c7a?s=128

hkdnet

June 29, 2019
Tweet

Transcript

  1. ݱ৔ͷ RubyVM::AbstractSyntaxTree @hkdnet / ͸͘Ͳʔ

  2. ͩΕʁ • hkdnet / ͸͘Ͳʔ • Ruby ͱ RoR Ͱ͓࢓ࣄ͍ͯ͠·͢

  3. ઌʹ·ͱΊ

  4. AST ͸ࠇຐज़͚ͩͷ΋ͷͰ͸ͳ͍ • ݱ৔Ͱ࢖͑Δ = ݱੈརӹ͕͋Δ • ੩తղੳͷҰखͱͯ͠࢖͑Δ

  5. ͓͜ͱΘΓ • ASTͷઆ໌͸͜ΕҎ߱Ͱ͸͠·ͤΜ • AST = Abstract Syntax Tree •

    ந৅ߏจ໦ͱݴΘΕΔ΍ͭͰύʔεͨ݁͠ՌͰ͋Γɺϓϩάϥ ϜͷҙຯΛࣔͨ͠໦ߏ଄ͩͱࢥ͍ͬͯͩ͘͞
  6. ࣄྫ

  7. deprecated ͳϝιουΛۦஞ͍ͨ͠

  8. deprecated ͳϝιουΛۦஞ͍ͨ͠ • ΞϓϦέʔγϣϯ͕ҭͭͱඇਪ঑ͳϝιου͕ग़ͯ͘Δ • -> ౰વ͖Ε͍ʹ͍ͨ͠

  9. deprecated ͳϝιουΛۦஞ͍ͨ͠ • ΞϓϦέʔγϣϯ͕ҭͭͱඇਪ঑ͳϝιου͕ग़ͯ͘Δ • -> ౰વ͖Ε͍ʹ͍ͨ͠ • deprecated ͳϩά͕େྔʹग़ͯͯӡ༻্अຐͩͬͨ

    • -> ࣮༻తʹ໰୊͋Γ
  10. ର৅ • ͋ΔΦϒδΣΫτͷଐੑΛऔಘ͢ΔͨΊͷ obj.foo_attr Έ͍ͨ ͳϝιου • ֓೦తʹ foo_attr ͱ͍͏ͷ͕ద੾Ͱͳ͘ͳͬͨͷͰ

    obj.bar_attr ʹ৐Γ׵͍͑ͨ
  11. ࣮ફฤ

  12. grep

  13. grep • ݴΘͣͱ͠Εͨߦݕࡧπʔϧ • ͍͚ͦͦ͜͜Δ

  14. grep • ݴΘͣͱ͠Εͨߦݕࡧπʔϧ • ʮͦͦ͜͜ʯ͍͚Δ

  15. grepͷݶք # OK foo_attr = obj.foo_attr # NG: false positive

    { foo_attr: foo_attr }.to_json
  16. grep ͷݶք • Ruby εΫϦϓτʹ͓͍ͯɺจࣈྻ͚ͩͰ͸ҙຯΛ൑அͰ͖ͳ ͍ x = 1 #

    ͋Δ͍͸͜ͷߦͳ͠ x # ϩʔΧϧม਺ݺͼग़͠ or Ϩγʔόͳ͠ϝιουݺͼग़͠
  17. AST ͷग़൪ʂʂʂ

  18. RubyVM::AbstractSyntaxTree • AST ͸ϓϩάϥϜͷҙຯ(syntax)Λද͍ͯ͠Δ • ౰વϩʔΧϧม਺ࢀর(NODE_DVAR)ͱҾ਺ͳ͠ϝιουݺͼ ग़͠(NODE_VCALL)͕۠ผͰ͖Δ

  19. RubyVM::AbstractSyntaxTree • ࠓճ͸ɺ͋ΔAST܈͔ΒಛఆͷϝιουίʔϧΛ୳͍ͨ͠ • -> call_searcher gem • https://github.com/hkdnet/call_searcher

  20. RubyVM::AbstractSyntaxTree require 'call_searcher' s = CallSearcher::Searcher.new { |e| e.mid ==

    :search } root_dir = File.expand_path('../', __dir__) result = s.search_dir(root_dir: root_dir, path: '{app,lib,spec}', github: 'hkdnet/call_searcher') result.each { |e| puts e.github_url } # => https://github.com/hkdnet/call_searcher/blob/master/ lib/call_searcher/searcher.rb#L14
  21. RubyVM::AbstractSyntaxTree • Ұ݅མண

  22. RubyVM::AbstractSyntaxTree • Ұ݅མணͯ͠ͳ͍ • ʮ͋ΔAST܈͔ΒಛఆͷϝιουίʔϧΛ୳͍ͨ͠ʯ • ϓϩδΣΫτʹ͓͚Δ AST ܈Λ͢΂ͯൈ͘ඞཁ͕͋Δ •

    ͋Μ·Γࣗ໌Ͱ͸ͳ͍
  23. RubyVM::AbstractSyntaxTree • Rails ϓϩδΣΫτʹ͓͍ͯ Ruby εΫϦϓτ͸͋·Ͷ͘ଘࡏ͠ ͍ͯΔ • .rb ϑΝΠϧ

    • .yaml ϑΝΠϧ(erbه๏) • .haml / .slim / .jbuilder ϑΝΠϧ
  24. RubyVM::AbstractSyntaxTree • ઈࢍ࡞ۀத • https://github.com/hkdnet/asts • call_searcher ଆͰͲ͏ݕࡧ͢Δ͔ͱ͔Λؾʹ͠ͳͯ͘Α͘ͳΔ ͸ͣ……ɻ

  25. ҎԼ͓·͚

  26. slim ରԠ

  27. slim ରԠ • ύʔεͨ͠Β SࣜΛฦ͖ͯͯ͠ΊΜͲ͘͘͞ͳͬͨ parser = Slim::Parser.new parser.call(s) [:multi,

    [:html, :tag, "h1", [:html, :attrs], [:slim, :output, true, "@foo", [:multi, [:newline]]]]]
  28. haml ରԠ • ๻ʮHaml::Parser ͕ AST Λฦ͢ͷͰ͔ͦ͜Β Ruby ͱͯ͠ධՁ ͞ΕΔ΋ͷΛൈ͍ͯ͘Ε͹ྑ͍Μ͡ΌͶʔͷʯ

  29. haml • Haml::Parser ͕ AST Λฦ͢ͷͰ͔ͦ͜Β Ruby ͱͯ͠ධՁ͞Ε Δ΋ͷΛൈ͍ͯ͘Ε͹ྑ͍ <-

    ΢ι • લड़ͷΑ͏ʹ a ͱ͍͏εΫϦϓτ͸ a ͕ԿͰ͋Δ͔ʹΑܾͬͯ ·Δ • ݁ہίϯςΩετґଘ͕ൈ͚ͳ͍
  30. haml • ࠷ऴతʹ view Λు͘1ͭͷ Ruby εΫϦϓτʹͳΔ͸͔ͣͩΒ ͔ͦ͜Βൈ͍ͯ͘Ε͹ྑ͍ʁ • ͦΕͬͯ

    helper ͱ͔ਖ਼͘͠ೝࣝͰ͖ΔΜͩΖ͏͔ • ͳΜ͔ແཧͳؾ͕͠ͳ͘΋ͳ͍ͳʔ <- ΠϚίί