ANTLR for Ruby
The latest release of ANTLR v3 adds support for Ruby as a target language, courtesy of yours truly. Let's look at an example to see what's possible.
The following grammar generates a parser that can evaluate simple arithmetic expressions involving integer numbers, +, -, *, /, ( and ).
grammar Calculator;
options {
language = Ruby;
}
@members {
@stack = []
def result
@stack[0]
end
}
parse: expression;
expression: mult (
'+' mult {
@stack.push(@stack.pop + @stack.pop)
}
| '-' mult {
a = @stack.pop
b = @stack.pop
@stack.push(b - a)
}
)* ;
mult: atom (
'*' atom {
@stack.push(@stack.pop * @stack.pop)
}
| '/' atom {
a = @stack.pop
b = @stack.pop
@stack.push(b / a.to_f)
}
)* ;
atom: n=NUMBER { @stack.push($n.text.to_i) }
| '(' expression ')';
NUMBER: ('0'..'9')+;
WS: (' ' | '\n' | '\t')+ { channel = 99 };
First, we need to process the grammar with ANTLR. You'll need to have Java installed in order to do this. ANTLR will generate two files: Calculator.rb and CalculatorLexer.rb.
You'll also need the ANTLR ruby runtime library (just a small .rb file) which you can get here. Just drop into the same directory as the two .rb files created above (in the future I may package it as a gem).
We got our parser, so let's try it out. Create another ruby file with the following:
require 'Calculator'
require 'CalculatorLexer'
lexer = CalculatorLexer.new(ANTLR::CharStream.new(STDIN))
parser = Calculator.new(ANTLR::TokenStream.new(lexer))
parser.parse
puts parser.result
Now, run the program, type an expression and press CTRL-D (or CTRL-Z if in Windows) to see the results, like so:
Simple... but cool, eh?
ANTLR v3 is still in pre-alpha stage, and the Ruby backend is a work in progress. So far, it can handle syntactic and semantic predicates, token labels, etc. and I'm planning to add support for scopes and token/rule parameters and return values next. AST creation will come after that.
The following grammar generates a parser that can evaluate simple arithmetic expressions involving integer numbers, +, -, *, /, ( and ).
grammar Calculator;
options {
language = Ruby;
}
@members {
@stack = []
def result
@stack[0]
end
}
parse: expression;
expression: mult (
'+' mult {
@stack.push(@stack.pop + @stack.pop)
}
| '-' mult {
a = @stack.pop
b = @stack.pop
@stack.push(b - a)
}
)* ;
mult: atom (
'*' atom {
@stack.push(@stack.pop * @stack.pop)
}
| '/' atom {
a = @stack.pop
b = @stack.pop
@stack.push(b / a.to_f)
}
)* ;
atom: n=NUMBER { @stack.push($n.text.to_i) }
| '(' expression ')';
NUMBER: ('0'..'9')+;
WS: (' ' | '\n' | '\t')+ { channel = 99 };
First, we need to process the grammar with ANTLR. You'll need to have Java installed in order to do this. ANTLR will generate two files: Calculator.rb and CalculatorLexer.rb.
You'll also need the ANTLR ruby runtime library (just a small .rb file) which you can get here. Just drop into the same directory as the two .rb files created above (in the future I may package it as a gem).
We got our parser, so let's try it out. Create another ruby file with the following:
require 'Calculator'
require 'CalculatorLexer'
lexer = CalculatorLexer.new(ANTLR::CharStream.new(STDIN))
parser = Calculator.new(ANTLR::TokenStream.new(lexer))
parser.parse
puts parser.result
Now, run the program, type an expression and press CTRL-D (or CTRL-Z if in Windows) to see the results, like so:
(5 + 4) * (10 - 2) / 3
^Z
24.0
Simple... but cool, eh?
ANTLR v3 is still in pre-alpha stage, and the Ruby backend is a work in progress. So far, it can handle syntactic and semantic predicates, token labels, etc. and I'm planning to add support for scopes and token/rule parameters and return values next. AST creation will come after that.
Labels: ruby
16 Comments:
thank you! :)
Hello,
I actually used ANTLR 3 for Ruby for RLisp parsing.
It's not that bad. However, would it be possible for {}-block to return values, and $foo to access those values (functional programming way) instead assigning everything to some variables ? Assignment relies rather heavily on order of operations, and it's not always clear with parsers in what order will the operations be executed. :-)
I'll add those features at some point. I was waiting for ANTLR to stabilize a bit before continuing development.
Eventually, I'd like to support all of ANTLR's features, including ASTs, tree grammars, etc.
By the way, do you plan to update Ruby support in ANTLR to 3.0b3 ? Versions since 3.0ea8 don't support Ruby any more. Apparently templates got some new attributes.
Shotgun approach to fixing this problem by just adding the attributes to argument lists made ANTLR compile Ruby grammars back, and the calculator even works, but RLisp doesn't. (the chance of that hack working was about zero anyway ;-) )
./antlr.rb:300:in `predict': undefined method `call' for nil:NilClass
(NoMethodError)
So it seems fixing it requires actually understanding what's going on :-) Should I send code of my attempts somewhere ?
Tomasz: I'm working on it. Essentially, changes in the way ANTLR deals with cyclic DFAs broke the Ruby implementation.
I hope to have it working again in a few days.
Terence: done! I'll keep adding stuff as I make progress.
Thanks for the good work on integrating antlr with Ruby. When using antlr version 3.0 (May 17. 2007) with the above grammar, however, I get the following error:
error(10): internal error: group Ruby does not satisfy interface ANTLRCore: missing templates [lexerRuleRefAndListLabel]
Is there anything I can do about it other than implementing the missing functions myself ?
Ben
Is this now abandoned?
Martin,
Is this project still maintained?
Ricky
It looks like Martin has abandoned the project.
Beltrachi (Not sure what the real name is) has done some work on a fork at GitHub:
http://github.com/beltrachi/antlr-3/tree/master
http://github.com/beltrachi/antlr-3/tree/master/README
It looks like beltrachi has abandoned it too....
buy wow gold,cheap wow gold,power wow power levelingworld of warcrft gold.
Do you know Archlord gold? I like it.
My brother often go to the internet bar to buy Archlord money and play it.
After school, He likes playing games using these archlord online Gold with his friend.
I do not like to play it. Because I think that it not only costs much money but also spend much time. One day, he give me many cheap Archlord gold and play the game with me.
I came to the bar following him and found buy Archlord gold was so cheap. After that, I also go to play game with him.
Do you know cabal online alz? I like it.
My brother often go to the internet bar to buy cabal alz and play it.
After school, He likes playing games using these cabal gold with his friend.
I do not like to play it. Because I think that it not only costs much money but also spend much time. One day, he give me many cabal money and play the game with me.
I came to the bar following him and found buy cabal alz was so cheap. After that, I also go to play game with him.
What do you know Rose zuly. And do you want to know? You can get rose zulie here. And welcome to our website, here you can play games, and you will get rose online zuly to play game. I know rose online zulie, and it is very interesting.Do you want a try, come and view our website, and you will learn how to Arua ROSE zuly. Come and join with us. We are waiting for your coming.
What do you know angels gold. And do you want to know? You can get angels online gold here. And welcome to our website, here you can play games, and you will buy angels gold to play game. And it is very interesting. Do you want a try, come and view our website, and you will learn much about cheap angels online gold. Come and join with us. We are waiting for your coming.
Have you heared about a game which you need use Tales Of Pirates gold to play, and you can also borrow Tales Of Pirates money from other players? But you can buy Tales Of Pirates Gold, or you will lose the choice if you do not have cheap Tales Of Pirates gold. If you get it, you can continue this game.
Have you heared about a game which you need use priston tale Gold to play, and you can also borrow priston tale Money from other players? But you can buy priston tale Gold, or you will lose the choice if you do not have cheap priston tale Gold. If you get it, you can continue this game.
Find and download what you need at Rapidshare Search Engine.
Top Site List Free Proxy Site Internet Marketing Tools Internet Marketing Auto Insurance Quotes Home Mortgage Loan Newest Gadgets Review Free Download mp3
ANTLR is not that great option, I prefer to use some Generic Viagra, that's all
Tool for Language Recognition, is a language tool that provides a framework for constructing recognizers, sportsbookinterpreters, compilers, http://www.enterbet.comand translators from grammatical descriptions containing actions in a
Post a Comment
<< Home