Skip to content
xraid edited this page Sep 13, 2010 · 17 revisions

code.duby => TheParser => TheTransformer => TheTyper => TheCompiler


The parsers role is to generate a AST (Abstract Syntax Tree) to do further transformations on.

Todays Duby uses the JRubyParser internally http://kenai.com/projects/jruby-parser/sources/mercurial/show it is included in “duby_source_dir/javalib/JRubyParse.jar”, JRubyParser is written in Java and could be used in JRuby .rb files as :


import org.jrubyparser.parser

Parser = org.jrubyparser.Parser

def parse_ruby(src, filename='-')
  parser = Parser.new
  config = ParserConfiguration.new(0, CompatVersion::RUBY1_9, true)
  ast = parser.parse(filename, StringReader.new(src), config)
end

In Duby code it could be called as:

ast = Duby::AST.parse_ruby(src, filename)

Lets look at an example parse to AST


def fib(a:int)
  if a < 2
    a
  else
    fib(a - 1) + fib(a - 2)
  end
end

Parses to Duby::AST as :


(RootNode, (NewlineNode, (DefnNode:fib, (ArgumentNode:fib), (ArgsNode, (BlockNode, (TypedArgumentNode:a, (VCallNode:int)))), (NewlineNode, (IfNode, (CallNode:<, (LocalVarNode:a), (ArrayNode, (FixnumNode))), (NewlineNode, (LocalVarNode:a)), (NewlineNode, (CallNode:+, (FCallNode:fib, (ArrayNode, (CallNode:-, (LocalVarNode:a), (ArrayNode, (FixnumNode))))), (ArrayNode, (FCallNode:fib, (ArrayNode, (CallNode:-, (LocalVarNode:a), (ArrayNode, (FixnumNode)))))))))))))

With JRuby installed and defined in PATH one can use the command ast => JRuby/bin/ast

$ ast -e "def method;puts "hey";end"

AST:
RootNode 0
  NewlineNode 0
    DefnNode:method 0
      ArgumentNode:method 0
      ArgsNoArgNode 0
      NewlineNode 0
        FCallOneArgNode:puts 0
          ArrayNode 0
            VCallNode:hey 0

where the -e is a flag for evaluate,

Next up in the duby flow is TheTransformer

Clone this wiki locally