45

I'm looking for Ruby grammar in BNF form. Is there an official version?

user68109
  • 2,446
  • 6
  • 21
  • 20

3 Answers3

38

The YACC syntax is in the Ruby source. Download it and run the bundled utiliy to get the readable syntax.

wget ftp://ftp.ruby-lang.org/pub/ruby/2.0/ruby-2.0.0-p195.tar.gz
tar xvzf ruby-2.0.0-p195.tar.gz
cd ruby-2.0.0-p195
ruby sample/exyacc.rb < parse.y

Output sample (total 918 lines for the v2.0.0-p195)

program         : top_compstmt
                ;

top_compstmt    : top_stmts opt_terms
                ;

top_stmts       : none
                | top_stmt
                | top_stmts terms top_stmt
                | error top_stmt
                ;

top_stmt        : stmt
                | keyword_BEGIN
                  '{' top_compstmt '}'
                ;

bodystmt        : compstmt
                  opt_rescue
                  opt_else
                  opt_ensure
                ;

compstmt        : stmts opt_terms
                ;
Kenji Noguchi
  • 1,752
  • 2
  • 17
  • 26
  • 12
    now just `git clone https://github.com/ruby/ruby ; cd ruby ; ruby sample/exyacc.rb < parse.y` – Lance Jun 08 '14 at 07:09
15

Yes, there is one Ruby BNF syntax by the University of buffalo.

Edit: I've also found this alternate Ruby BNF syntax.

Kevin Chen
  • 994
  • 8
  • 24
Adrian Grigore
  • 33,034
  • 36
  • 130
  • 210
  • 5
    But I don't think the first link is to an "official" grammar. I hear that the closest thing to an official grammar for Ruby is the parse.y file. – Eric Walker Jan 01 '11 at 00:10
  • 6
    Unfortunately, the similar UoB and the njit grammars are completely wrong. There is no do in a for loop, extend and include statements are missing and exception variables are missing. –  Feb 07 '13 at 03:46
5

also an official version: Ruby Draft Specification. you can find the grammar there.

Ruby Draft Specification: http://ruby-std.netlab.jp. the server is down, but you can download it from http://www.ipa.go.jp/osc/english/ruby

GutenYe
  • 3,227
  • 2
  • 25
  • 21