SlideShare uma empresa Scribd logo
1 de 73
Ruby AST Tools
       The ParseTree Family




       Brian Landau
Wednesday, March 25, 2009
The Ruby AST

            Code                  Code
            Style 1               Style 2


                            AST

            Code                  Code
            Style 3               Style 4
Wednesday, March 25, 2009
The Ruby AST Nodes




Wednesday, March 25, 2009
The Ruby AST Nodes

                  def       (a,b)     def     (a,b)


                  c=        a.to_s    c=      a.to_s


               return        end     return    end



                  def       (a,b)     def     (a,b)


                  c=        a.to_s    c=      a.to_s
Wednesday, March 25, 2009
Parsing Ruby in Ruby



            ParseTree
            ruby_parser

Wednesday, March 25, 2009
ParseTree




Wednesday, March 25, 2009
ParseTree

            RubyInline based




Wednesday, March 25, 2009
ParseTree

            RubyInline based
            Input sources:
                 Class
                 Method
                 Proc
                 String
Wednesday, March 25, 2009
ruby_parser




Wednesday, March 25, 2009
ruby_parser

            Uses Racc




Wednesday, March 25, 2009
ruby_parser

            Uses Racc
            Retrives line numbers




Wednesday, March 25, 2009
ruby_parser

            Uses Racc
            Retrives line numbers
            Slower than ParseTree



Wednesday, March 25, 2009
ruby_parser

            Uses Racc
            Retrives line numbers
            Slower than ParseTree
            Sexp output is ParseTree
            compatible
Wednesday, March 25, 2009
Sexp Nodes




Wednesday, March 25, 2009
Sexp Nodes
       class Simple
        def say(*args)
          puts args * ' '
        end
       end




Wednesday, March 25, 2009
Sexp Nodes
       class Simple
        def say(*args)
          puts args * ' '
        end
       end




       s(:class,
        :Simple,
        nil,
        s(:scope,
         s(:defn,
          :say,
          s(:args, :quot;*argsquot;),
          s(:scope,
           s(:block,
            s(:call,
             nil,
             :puts,
             s(:arglist,
              s(:call, s(:lvar, :args), :*, s(:arglist, s(:str, quot; quot;))))))))))

Wednesday, March 25, 2009
Sexp Objects


                 Inherits from Array
                 `structure` method
                 `each_of_type` method
                 `sexp_type` method
                 `sexp_body` method

Wednesday, March 25, 2009
SexpProcessors
       Or How I Learned to Love ParseTree




Wednesday, March 25, 2009
Making a SexpProcessors




Wednesday, March 25, 2009
Making a SexpProcessors


            Subclass `SexpProcessor`




Wednesday, March 25, 2009
Making a SexpProcessors


            Subclass `SexpProcessor`
            Call `super` from initialize




Wednesday, March 25, 2009
Making a SexpProcessors


            Subclass `SexpProcessor`
            Call `super` from initialize
            Define `process_xxx` methods




Wednesday, March 25, 2009
Making a SexpProcessors


            Subclass `SexpProcessor`
            Call `super` from initialize
            Define `process_xxx` methods
            Shift off Sexp nodes



Wednesday, March 25, 2009
Making a SexpProcessors


            Subclass `SexpProcessor`
            Call `super` from initialize
            Define `process_xxx` methods
            Shift off Sexp nodes
            Default process method

Wednesday, March 25, 2009
Making a SexpProcessors


            Subclass `SexpProcessor`
            Call `super` from initialize
            Define `process_xxx` methods
            Shift off Sexp nodes
            Default process method
            `rewrite_xxx` methods
Wednesday, March 25, 2009
Making a SexpProcessors


                            Subclass SexpProcessor

       class MyProcessor < SexpProcessor

       end




Wednesday, March 25, 2009
Making a SexpProcessors


                            Call “super” in “initialize”

       class MyProcessor < SexpProcessor
        def initialize
          super
          self.warn_on_default = false
          self.strict = false
        end
       end




Wednesday, March 25, 2009
Making a SexpProcessors


       class MyProcessor < SexpProcessor
        # ...
                                     Process “call” node
         def process_call(exp)
          recv = process exp.shift
          name = exp.shift
          args = process exp.shift

          return s()
         end
       end



Wednesday, March 25, 2009
Making a SexpProcessors


       class MyProcessor < SexpProcessor
        # ...

         def process_call(exp)
          recv = process exp.shift
          name = exp.shift
          args = process exp.shift

          return s()
         end
                            Must shift o all Sexp Nodes
       end



Wednesday, March 25, 2009
Making a SexpProcessors


       class MyProcessor  SexpProcessor
        # ...

         def process_call(exp)
          recv = process exp.shift
          name = exp.shift
          args = process exp.shift

          return s()
         end
                                     Must return a Sexp
       end



Wednesday, March 25, 2009
Making a SexpProcessors


       class MyProcessor  SexpProcessor
        # ...

        def default_process(exp)
         until exp.size == 0
          exp.shift
         end
         return s()
                          A default   process method
        end
       end




Wednesday, March 25, 2009
UnifiedRuby


     pt = ParseTree.new
     parse_tree = pt.parse_tree(Simple)
     ast = pt.process(parse_tree)

     # OR

     ast = pt.process(File.read('simple.rb'))




Wednesday, March 25, 2009
UnifiedRuby


      class MyProcessor  SexpProcessor
       include UnifiedRuby

         # ...

      end




Wednesday, March 25, 2009
Ruby2Ruby



        Ruby2Ruby.translate(Simple, :say)
        # = quot;def say(*args)...quot;




Wednesday, March 25, 2009
ParseTree extensions

  require 'parse_tree'
  require 'ruby2ruby'
  require 'parse_tree_extensions'

  bomb = proc do
   quot;BOOM!quot;
  end

  puts bomb.to_ruby # = quot;proc { quot;BOOM!quot; }quot;



Wednesday, March 25, 2009
ParseTree Family

                            Flog           ambition

                                   Parse
                                    Tree



                                   roodi

Wednesday, March 25, 2009
ParseTree Family




            Code Analytics
            Custom DSL


Wednesday, March 25, 2009
Flog




            Takes a set of files as input
            Processes for “bad code”



Wednesday, March 25, 2009
Flog




            Decends from SexpProcessor
            Includes UnifiedRuby



Wednesday, March 25, 2009
Flog


            Assigns weighted scores to:
                 Node Types
                 Node Constructions
                 Method calls

Wednesday, March 25, 2009
Flog



            Reports scores by:
                 Class
                 Method


Wednesday, March 25, 2009
Flog
     flog lib
         377.6: flog total
         11.1: flog/method average

         150.2: ClassMethods#acts_as_markup
         24.7: HTML#array_to_html
         21.5: ClassMethods#get_markdown_class
         18.4: main#none
         17.9: ActsAsMarkup#none




Wednesday, March 25, 2009
Flog
     flog -g lib
         377.6: flog total
         11.1: flog/method average

         171.7: ClassMethods total
         150.2: ClassMethods#acts_as_markup
         21.5: ClassMethods#get_markdown_class

          24.7: HTML total
          24.7: HTML#array_to_html
          ...


Wednesday, March 25, 2009
Flog
     flog -d lib
         377.6: flog total
         11.1: flog/method average

         150.2: ClassMethods#acts_as_markup
         50.9: []
         42.6: branch
         24.0: send
         16.5: define_method
         11.9: to_s
         11.8: assignment
         ...

Wednesday, March 25, 2009
self-flagellation




            Choose your own weightings




Wednesday, March 25, 2009
roodi
       Ruby Object Oriented Design Inferometer




Wednesday, March 25, 2009
roodi
       Ruby Object Oriented Design Inferometer


            Cyclomatic complexity




Wednesday, March 25, 2009
roodi
       Ruby Object Oriented Design Inferometer


            Cyclomatic complexity
            Assignment in conditional




Wednesday, March 25, 2009
roodi
       Ruby Object Oriented Design Inferometer


            Cyclomatic complexity
            Assignment in conditional
            Class/Method line count




Wednesday, March 25, 2009
roodi
       Ruby Object Oriented Design Inferometer


            Cyclomatic complexity
            Assignment in conditional
            Class/Method line count
            Empty rescue body




Wednesday, March 25, 2009
roodi
       Ruby Object Oriented Design Inferometer


            Cyclomatic complexity
            Assignment in conditional
            Class/Method line count
            Empty rescue body
            No for loops


Wednesday, March 25, 2009
roodi
       Ruby Object Oriented Design Inferometer


            Cyclomatic complexity
            Assignment in conditional
            Class/Method line count
            Empty rescue body
            No for loops
            Number of parameters

Wednesday, March 25, 2009
roodi


     sudo gem install roodi
     roodi “lib/**/*.rb”




Wednesday, March 25, 2009
roodi:
       How it works




Wednesday, March 25, 2009
roodi:
       How it works

            Parse files




Wednesday, March 25, 2009
roodi:
       How it works

            Parse files
            Move node-by-node




Wednesday, March 25, 2009
roodi:
       How it works

            Parse files
            Move node-by-node
            Evaluate each “Check”



Wednesday, March 25, 2009
roodi:
       How it works

            Parse files
            Move node-by-node
            Evaluate each “Check”
            Do Recursively

Wednesday, March 25, 2009
Ambition




Wednesday, March 25, 2009
Ambition



            DSL for Querying as Ruby




Wednesday, March 25, 2009
Ambition



            DSL for Querying as Ruby
            Framework for API Adapters




Wednesday, March 25, 2009
Ambition



            DSL for Querying as Ruby
            Framework for API Adapters
            Generator for new Adapters


Wednesday, March 25, 2009
Ambition ActiveRecord Adapter




            Queries only run when needed
            to_s = SQL
            to_hash = find-compatible hash



Wednesday, March 25, 2009
Ambition:
       How it works


            Processors parameters:
                 Context/Owner
                 Block


Wednesday, March 25, 2009
Ambition:
       How it works

           Context/Owner


       User.select { |m| m.name == 'jon' }




             Processor             Block


Wednesday, March 25, 2009
Ambition:
       How it works


            Parse the block
            Process nodes recursively
            Translate “clauses” to query
            string


Wednesday, March 25, 2009
Ambition:
       How it works


            Adapters:
                 Translator for Processors
                 Make API calls with a Query
                 Class


Wednesday, March 25, 2009
The Future:
       Ruby 1.9


            YARV
                 A virtual machine based stack architecture
                 implementation

            Ripper
                 Offers similar functionality as ParseTree and
                 SexpProcessor



Wednesday, March 25, 2009
Ripper


            Effects YARV behavior
            Returns array of arrays  literals
            Line and column for each token
            Ripper::Filter

Wednesday, March 25, 2009
Ripper:
       Lexer
      require 'ripper'
      require 'pp'

      p Ripper.lex(quot;def m(a) nil endquot;)
       #= [[[1, 0], :on_kw,     quot;defquot;],
       # [[1, 3], :on_sp,    quot; quot; ],
       # [[1, 4], :on_ident, quot;mquot; ],
       # [[1, 5], :on_lparen, quot;(quot; ],
       # [[1, 6], :on_ident, quot;aquot; ],
       # [[1, 7], :on_rparen, quot;)quot; ],
       # [[1, 8], :on_sp,    quot; quot; ],
       # [[1, 9], :on_kw,     quot;nilquot;],
       # [[1, 12], :on_sp,    quot; quot; ],
       # [[1, 13], :on_kw,     quot;endquot;]]

Wednesday, March 25, 2009
Ripper:
       Sexp Tree

 require 'ripper'
 require 'pp'

 pp Ripper.sexp(quot;def m(a) nil endquot;)
  #= [:program,
  # [:stmts_add,
  #   [:stmts_new],
  #   [:def,
  #    [:@ident, quot;mquot;, [1, 4]],
  #    [:paren, [:params, [[:@ident, quot;aquot;, [1, 6]]], nil, nil, nil]],
  #    [:bodystmt,
  #     [:stmts_add, [:stmts_new], [:var_ref, [:@kw, quot;nilquot;, [1, 9]]]],
  #     nil,
  #     nil,
  #     nil]]]]




Wednesday, March 25, 2009
Ripper:
       Filter
       require 'ripper/filter'

       class CommentStripper  Ripper::Filter
        def self.strip(src)
          new(src).parse
        end

         def on_default(event, token, data)
          print token
         end

        def on_comment(token, data)
         puts
        end
       end

       CommentStripper.strip(ARGF)
Wednesday, March 25, 2009
QA
       Rate at:
       http://speakerrate.com/talks/594-ruby-ast-tools


       brian.landau@viget.com
       http://www.viget.com/extend
       http://www.websideattractions.com/
Wednesday, March 25, 2009

Mais conteúdo relacionado

Semelhante a Ruby AST Tools

Ruby para-programadores-php
Ruby para-programadores-phpRuby para-programadores-php
Ruby para-programadores-phpJuan Maiz
 
What to do when things go wrong
What to do when things go wrongWhat to do when things go wrong
What to do when things go wrongDorneles Treméa
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9sagaroceanic11
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9sagaroceanic11
 
Palestra no Grupo Sou Java
Palestra no Grupo Sou JavaPalestra no Grupo Sou Java
Palestra no Grupo Sou JavaFabio Akita
 
Symfony - Introduction
Symfony - IntroductionSymfony - Introduction
Symfony - IntroductionPiers Warmers
 
メタプログラミングPerl nagoya rubykaigi02
メタプログラミングPerl nagoya rubykaigi02メタプログラミングPerl nagoya rubykaigi02
メタプログラミングPerl nagoya rubykaigi02なんとか くら
 
Ruby for C# Developers
Ruby for C# DevelopersRuby for C# Developers
Ruby for C# DevelopersCory Foy
 
Ruby and rails - Advanced Training (Cybage)
Ruby and rails - Advanced Training (Cybage)Ruby and rails - Advanced Training (Cybage)
Ruby and rails - Advanced Training (Cybage)Gautam Rege
 
Ruby 2.0 / Rails 4.0, A selection of new features.
Ruby 2.0 / Rails 4.0, A selection of new features.Ruby 2.0 / Rails 4.0, A selection of new features.
Ruby 2.0 / Rails 4.0, A selection of new features.lrdesign
 
An introduction to Erlang and Elixir
An introduction to Erlang and ElixirAn introduction to Erlang and Elixir
An introduction to Erlang and Elixirericbmerritt
 
A Toda Maquina Con Ruby on Rails
A Toda Maquina Con Ruby on RailsA Toda Maquina Con Ruby on Rails
A Toda Maquina Con Ruby on RailsRafael García
 
P4 P Update January 2009
P4 P Update January 2009P4 P Update January 2009
P4 P Update January 2009vsainteluce
 
JavaOne 2013 - Clojure for Java Developers
JavaOne 2013 - Clojure for Java DevelopersJavaOne 2013 - Clojure for Java Developers
JavaOne 2013 - Clojure for Java DevelopersJan Kronquist
 
The details of CI/CD environment for Ruby
The details of CI/CD environment for RubyThe details of CI/CD environment for Ruby
The details of CI/CD environment for RubyHiroshi SHIBATA
 

Semelhante a Ruby AST Tools (20)

Ruby para-programadores-php
Ruby para-programadores-phpRuby para-programadores-php
Ruby para-programadores-php
 
What to do when things go wrong
What to do when things go wrongWhat to do when things go wrong
What to do when things go wrong
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9
 
Palestra no Grupo Sou Java
Palestra no Grupo Sou JavaPalestra no Grupo Sou Java
Palestra no Grupo Sou Java
 
Symfony - Introduction
Symfony - IntroductionSymfony - Introduction
Symfony - Introduction
 
メタプログラミングPerl nagoya rubykaigi02
メタプログラミングPerl nagoya rubykaigi02メタプログラミングPerl nagoya rubykaigi02
メタプログラミングPerl nagoya rubykaigi02
 
Ruby for C# Developers
Ruby for C# DevelopersRuby for C# Developers
Ruby for C# Developers
 
Ruby and rails - Advanced Training (Cybage)
Ruby and rails - Advanced Training (Cybage)Ruby and rails - Advanced Training (Cybage)
Ruby and rails - Advanced Training (Cybage)
 
Ruby 2.0 / Rails 4.0, A selection of new features.
Ruby 2.0 / Rails 4.0, A selection of new features.Ruby 2.0 / Rails 4.0, A selection of new features.
Ruby 2.0 / Rails 4.0, A selection of new features.
 
An introduction to Erlang and Elixir
An introduction to Erlang and ElixirAn introduction to Erlang and Elixir
An introduction to Erlang and Elixir
 
Django Testing
Django TestingDjango Testing
Django Testing
 
A Toda Maquina Con Ruby on Rails
A Toda Maquina Con Ruby on RailsA Toda Maquina Con Ruby on Rails
A Toda Maquina Con Ruby on Rails
 
JRubyConf 2009
JRubyConf 2009JRubyConf 2009
JRubyConf 2009
 
P4 P Update January 2009
P4 P Update January 2009P4 P Update January 2009
P4 P Update January 2009
 
Ebay News 2000 10 19 Earnings
Ebay News 2000 10 19 EarningsEbay News 2000 10 19 Earnings
Ebay News 2000 10 19 Earnings
 
Ebay News 2001 4 19 Earnings
Ebay News 2001 4 19 EarningsEbay News 2001 4 19 Earnings
Ebay News 2001 4 19 Earnings
 
Power Ruby
Power RubyPower Ruby
Power Ruby
 
JavaOne 2013 - Clojure for Java Developers
JavaOne 2013 - Clojure for Java DevelopersJavaOne 2013 - Clojure for Java Developers
JavaOne 2013 - Clojure for Java Developers
 
The details of CI/CD environment for Ruby
The details of CI/CD environment for RubyThe details of CI/CD environment for Ruby
The details of CI/CD environment for Ruby
 

Último

Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 

Último (20)

Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 

Ruby AST Tools

  • 1. Ruby AST Tools The ParseTree Family Brian Landau Wednesday, March 25, 2009
  • 2. The Ruby AST Code Code Style 1 Style 2 AST Code Code Style 3 Style 4 Wednesday, March 25, 2009
  • 3. The Ruby AST Nodes Wednesday, March 25, 2009
  • 4. The Ruby AST Nodes def (a,b) def (a,b) c= a.to_s c= a.to_s return end return end def (a,b) def (a,b) c= a.to_s c= a.to_s Wednesday, March 25, 2009
  • 5. Parsing Ruby in Ruby ParseTree ruby_parser Wednesday, March 25, 2009
  • 7. ParseTree RubyInline based Wednesday, March 25, 2009
  • 8. ParseTree RubyInline based Input sources: Class Method Proc String Wednesday, March 25, 2009
  • 10. ruby_parser Uses Racc Wednesday, March 25, 2009
  • 11. ruby_parser Uses Racc Retrives line numbers Wednesday, March 25, 2009
  • 12. ruby_parser Uses Racc Retrives line numbers Slower than ParseTree Wednesday, March 25, 2009
  • 13. ruby_parser Uses Racc Retrives line numbers Slower than ParseTree Sexp output is ParseTree compatible Wednesday, March 25, 2009
  • 15. Sexp Nodes class Simple def say(*args) puts args * ' ' end end Wednesday, March 25, 2009
  • 16. Sexp Nodes class Simple def say(*args) puts args * ' ' end end s(:class, :Simple, nil, s(:scope, s(:defn, :say, s(:args, :quot;*argsquot;), s(:scope, s(:block, s(:call, nil, :puts, s(:arglist, s(:call, s(:lvar, :args), :*, s(:arglist, s(:str, quot; quot;)))))))))) Wednesday, March 25, 2009
  • 17. Sexp Objects Inherits from Array `structure` method `each_of_type` method `sexp_type` method `sexp_body` method Wednesday, March 25, 2009
  • 18. SexpProcessors Or How I Learned to Love ParseTree Wednesday, March 25, 2009
  • 20. Making a SexpProcessors Subclass `SexpProcessor` Wednesday, March 25, 2009
  • 21. Making a SexpProcessors Subclass `SexpProcessor` Call `super` from initialize Wednesday, March 25, 2009
  • 22. Making a SexpProcessors Subclass `SexpProcessor` Call `super` from initialize Define `process_xxx` methods Wednesday, March 25, 2009
  • 23. Making a SexpProcessors Subclass `SexpProcessor` Call `super` from initialize Define `process_xxx` methods Shift off Sexp nodes Wednesday, March 25, 2009
  • 24. Making a SexpProcessors Subclass `SexpProcessor` Call `super` from initialize Define `process_xxx` methods Shift off Sexp nodes Default process method Wednesday, March 25, 2009
  • 25. Making a SexpProcessors Subclass `SexpProcessor` Call `super` from initialize Define `process_xxx` methods Shift off Sexp nodes Default process method `rewrite_xxx` methods Wednesday, March 25, 2009
  • 26. Making a SexpProcessors Subclass SexpProcessor class MyProcessor < SexpProcessor end Wednesday, March 25, 2009
  • 27. Making a SexpProcessors Call “super” in “initialize” class MyProcessor < SexpProcessor def initialize super self.warn_on_default = false self.strict = false end end Wednesday, March 25, 2009
  • 28. Making a SexpProcessors class MyProcessor < SexpProcessor # ... Process “call” node def process_call(exp) recv = process exp.shift name = exp.shift args = process exp.shift return s() end end Wednesday, March 25, 2009
  • 29. Making a SexpProcessors class MyProcessor < SexpProcessor # ... def process_call(exp) recv = process exp.shift name = exp.shift args = process exp.shift return s() end Must shift o all Sexp Nodes end Wednesday, March 25, 2009
  • 30. Making a SexpProcessors class MyProcessor SexpProcessor # ... def process_call(exp) recv = process exp.shift name = exp.shift args = process exp.shift return s() end Must return a Sexp end Wednesday, March 25, 2009
  • 31. Making a SexpProcessors class MyProcessor SexpProcessor # ... def default_process(exp) until exp.size == 0 exp.shift end return s() A default process method end end Wednesday, March 25, 2009
  • 32. UnifiedRuby pt = ParseTree.new parse_tree = pt.parse_tree(Simple) ast = pt.process(parse_tree) # OR ast = pt.process(File.read('simple.rb')) Wednesday, March 25, 2009
  • 33. UnifiedRuby class MyProcessor SexpProcessor include UnifiedRuby # ... end Wednesday, March 25, 2009
  • 34. Ruby2Ruby Ruby2Ruby.translate(Simple, :say) # = quot;def say(*args)...quot; Wednesday, March 25, 2009
  • 35. ParseTree extensions require 'parse_tree' require 'ruby2ruby' require 'parse_tree_extensions' bomb = proc do quot;BOOM!quot; end puts bomb.to_ruby # = quot;proc { quot;BOOM!quot; }quot; Wednesday, March 25, 2009
  • 36. ParseTree Family Flog ambition Parse Tree roodi Wednesday, March 25, 2009
  • 37. ParseTree Family Code Analytics Custom DSL Wednesday, March 25, 2009
  • 38. Flog Takes a set of files as input Processes for “bad code” Wednesday, March 25, 2009
  • 39. Flog Decends from SexpProcessor Includes UnifiedRuby Wednesday, March 25, 2009
  • 40. Flog Assigns weighted scores to: Node Types Node Constructions Method calls Wednesday, March 25, 2009
  • 41. Flog Reports scores by: Class Method Wednesday, March 25, 2009
  • 42. Flog flog lib 377.6: flog total 11.1: flog/method average 150.2: ClassMethods#acts_as_markup 24.7: HTML#array_to_html 21.5: ClassMethods#get_markdown_class 18.4: main#none 17.9: ActsAsMarkup#none Wednesday, March 25, 2009
  • 43. Flog flog -g lib 377.6: flog total 11.1: flog/method average 171.7: ClassMethods total 150.2: ClassMethods#acts_as_markup 21.5: ClassMethods#get_markdown_class 24.7: HTML total 24.7: HTML#array_to_html ... Wednesday, March 25, 2009
  • 44. Flog flog -d lib 377.6: flog total 11.1: flog/method average 150.2: ClassMethods#acts_as_markup 50.9: [] 42.6: branch 24.0: send 16.5: define_method 11.9: to_s 11.8: assignment ... Wednesday, March 25, 2009
  • 45. self-flagellation Choose your own weightings Wednesday, March 25, 2009
  • 46. roodi Ruby Object Oriented Design Inferometer Wednesday, March 25, 2009
  • 47. roodi Ruby Object Oriented Design Inferometer Cyclomatic complexity Wednesday, March 25, 2009
  • 48. roodi Ruby Object Oriented Design Inferometer Cyclomatic complexity Assignment in conditional Wednesday, March 25, 2009
  • 49. roodi Ruby Object Oriented Design Inferometer Cyclomatic complexity Assignment in conditional Class/Method line count Wednesday, March 25, 2009
  • 50. roodi Ruby Object Oriented Design Inferometer Cyclomatic complexity Assignment in conditional Class/Method line count Empty rescue body Wednesday, March 25, 2009
  • 51. roodi Ruby Object Oriented Design Inferometer Cyclomatic complexity Assignment in conditional Class/Method line count Empty rescue body No for loops Wednesday, March 25, 2009
  • 52. roodi Ruby Object Oriented Design Inferometer Cyclomatic complexity Assignment in conditional Class/Method line count Empty rescue body No for loops Number of parameters Wednesday, March 25, 2009
  • 53. roodi sudo gem install roodi roodi “lib/**/*.rb” Wednesday, March 25, 2009
  • 54. roodi: How it works Wednesday, March 25, 2009
  • 55. roodi: How it works Parse files Wednesday, March 25, 2009
  • 56. roodi: How it works Parse files Move node-by-node Wednesday, March 25, 2009
  • 57. roodi: How it works Parse files Move node-by-node Evaluate each “Check” Wednesday, March 25, 2009
  • 58. roodi: How it works Parse files Move node-by-node Evaluate each “Check” Do Recursively Wednesday, March 25, 2009
  • 60. Ambition DSL for Querying as Ruby Wednesday, March 25, 2009
  • 61. Ambition DSL for Querying as Ruby Framework for API Adapters Wednesday, March 25, 2009
  • 62. Ambition DSL for Querying as Ruby Framework for API Adapters Generator for new Adapters Wednesday, March 25, 2009
  • 63. Ambition ActiveRecord Adapter Queries only run when needed to_s = SQL to_hash = find-compatible hash Wednesday, March 25, 2009
  • 64. Ambition: How it works Processors parameters: Context/Owner Block Wednesday, March 25, 2009
  • 65. Ambition: How it works Context/Owner User.select { |m| m.name == 'jon' } Processor Block Wednesday, March 25, 2009
  • 66. Ambition: How it works Parse the block Process nodes recursively Translate “clauses” to query string Wednesday, March 25, 2009
  • 67. Ambition: How it works Adapters: Translator for Processors Make API calls with a Query Class Wednesday, March 25, 2009
  • 68. The Future: Ruby 1.9 YARV A virtual machine based stack architecture implementation Ripper Offers similar functionality as ParseTree and SexpProcessor Wednesday, March 25, 2009
  • 69. Ripper Effects YARV behavior Returns array of arrays literals Line and column for each token Ripper::Filter Wednesday, March 25, 2009
  • 70. Ripper: Lexer require 'ripper' require 'pp' p Ripper.lex(quot;def m(a) nil endquot;) #= [[[1, 0], :on_kw, quot;defquot;], # [[1, 3], :on_sp, quot; quot; ], # [[1, 4], :on_ident, quot;mquot; ], # [[1, 5], :on_lparen, quot;(quot; ], # [[1, 6], :on_ident, quot;aquot; ], # [[1, 7], :on_rparen, quot;)quot; ], # [[1, 8], :on_sp, quot; quot; ], # [[1, 9], :on_kw, quot;nilquot;], # [[1, 12], :on_sp, quot; quot; ], # [[1, 13], :on_kw, quot;endquot;]] Wednesday, March 25, 2009
  • 71. Ripper: Sexp Tree require 'ripper' require 'pp' pp Ripper.sexp(quot;def m(a) nil endquot;) #= [:program, # [:stmts_add, # [:stmts_new], # [:def, # [:@ident, quot;mquot;, [1, 4]], # [:paren, [:params, [[:@ident, quot;aquot;, [1, 6]]], nil, nil, nil]], # [:bodystmt, # [:stmts_add, [:stmts_new], [:var_ref, [:@kw, quot;nilquot;, [1, 9]]]], # nil, # nil, # nil]]]] Wednesday, March 25, 2009
  • 72. Ripper: Filter require 'ripper/filter' class CommentStripper Ripper::Filter def self.strip(src) new(src).parse end def on_default(event, token, data) print token end def on_comment(token, data) puts end end CommentStripper.strip(ARGF) Wednesday, March 25, 2009
  • 73. QA Rate at: http://speakerrate.com/talks/594-ruby-ast-tools brian.landau@viget.com http://www.viget.com/extend http://www.websideattractions.com/ Wednesday, March 25, 2009

Notas do Editor

  1. Ruby 1.8 uses a Bison Yacc-like parser Many different styles lead to the same Abstract Syntax tree or set of instructions.
  2. Best to thing of the AST not as a tree but a large container composed of inner nodes
  3. themselves composed of smaller nodes. until you get to an individual &#x201C;token&#x201D;
  4. Both by Ryan Davis
  5. Pure ruby implementation using racc. For those that don&#x2019;t know RACC is a ruby based YACC parser. Slowness not a huge issue in my experience.
  6. Pure ruby implementation using racc. For those that don&#x2019;t know RACC is a ruby based YACC parser. Slowness not a huge issue in my experience.
  7. Pure ruby implementation using racc. For those that don&#x2019;t know RACC is a ruby based YACC parser. Slowness not a huge issue in my experience.
  8. Pure ruby implementation using racc. For those that don&#x2019;t know RACC is a ruby based YACC parser. Slowness not a huge issue in my experience.
  9. Obtains the Parse tree and represents it as nested s-expresions.
  10. Obtains the Parse tree and represents it as nested s-expresions.
  11. composed of array&#x2019;s, symbol&#x2019;s and literals `structure` just returns the node type structure not the contents of the nodes. this is very handy for code structure analysis.
  12. Takes the sexp objects returned by ParseTree and processes returning output.
  13. Essentially turns the parse tree into an AST. It does this via a set of rewrite methods. By default ParseTree does this. To get the un-unified version you have to use RawParseTree. ParseTree does this by processing with a CompositeSexpProcessor called Unifier
  14. A Module that can be included in a SexpProcessor.
  15. Another good example of a SexpProcessor. Take a class or method and translates it into a string of valid Ruby code that would create that Class/method exactly. Useful for metaprogramming and dissecting dynamically created classes, methods, and procs
  16. Convert Methods, UnboundMethods and Procs to sexps and strings of ruby code. Helpful in debuging mysterious Procs.
  17. Often times I find libraries that use ParseTree but don't take advantage of SexpProcessor and often rebuild similar functionality. very sad.
  18. 2 Types of Libraries based on ParseTree
  19. Good at finding problem areas that may need refactoring
  20. Also adds to varying amounts to a score multiplier for specific types of nestings.
  21. with no options Ryan Davis has said to remember it's more about relative scores. Particularly bad scores I generally consider is those over 40 or if I'm being very rough those over 25.
  22. with group option, groups by class
  23. with detail version (old output) gives why each method earned it's score.
  24. Converted over by Ben Scofield Working on a site that will allow you to share and download those weightings.
  25. by Marty Andrews
  26. by Marty Andrews
  27. by Marty Andrews
  28. by Marty Andrews
  29. by Marty Andrews
  30. by Marty Andrews
  31. Once again, Very good at finding problem areas that need refactoring.
  32. by github&#x2019;s Chris Wanstrath Allows you to express queries in clear and concise ruby code. Think of it as a Framework for specific API adapters, e.g. ActiveRecord Includes a Rubigen based adapter generator for any data-source API you want
  33. by github&#x2019;s Chris Wanstrath Allows you to express queries in clear and concise ruby code. Think of it as a Framework for specific API adapters, e.g. ActiveRecord Includes a Rubigen based adapter generator for any data-source API you want
  34. by github&#x2019;s Chris Wanstrath Allows you to express queries in clear and concise ruby code. Think of it as a Framework for specific API adapters, e.g. ActiveRecord Includes a Rubigen based adapter generator for any data-source API you want
  35. Just gives us another syntax for doing finds, the syntax may be preferable to some. Still needs lots of work to do everything you can do with find or SQL.
  36. No composite SexpProcessor equivalent yet.
  37. line and column, node/event type, &#x201C;code&#x201D; that produced it.
  38. Very similar output to ParseTree, but does include line and column info for inner most nodes.
  39. Uses Lexer and goes thru each node.