9 ms·
How to Parse Ruby
- skurmedel 14y agohttp://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=59579 http://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_... ?
- steveklabnik 14y agoThe ISO standard is based on Ruby 1.8.7, by the way. That said, 1.8.7 still has these issues. You absolutely _can_ parse Ruby, that doesn't mean it's not incredibly difficult.
- michaelfeathers 14y agoUse Ripper in 1.9.3. It's part of the distribution and it works well. http://www.rubyinside.com/using-ripper-to-see-how-ruby-is-parsing-your-code-5270.html http://www.rubyinside.com/using-ripper-to-see-how-ruby-is-pa... https://gist.github.com/michaelfeathers/4704833 https://gist.github.com/michaelfeathers/4704833
- markov_twain 14y agofwiw, I find the syntax definition in the ruby_parser gem at https://github.com/seattlerb/ruby_parser/blob/master/lib/ruby19_parser.y https://github.com/seattlerb/ruby_parser/blob/master/lib/rub... to be much easier reading, as it's written for racc (the ruby equivalent of yacc), although as the readme warns, it's not perfect.
- endlessvoid94 14y agoI found the Rubinius source code to be quite readable. For example, here are the AST node definitions: https://github.com/rubinius/rubinius/tree/master/lib/compiler/ast https://github.com/rubinius/rubinius/tree/master/lib/compile...
- akkartik 14y agoDoes it come with decent tests?
- mcphage 14y agohttp://rubyspec.org http://rubyspec.org
- koenigdavidmj 14y agoWell, even C has this requirement. Code like foo * bar; Could either mean "multiply foo by bar and drop it on the floor", or "declare bar as a pointer to a foo". C++ makes it worse, of course. Either way, you need to be aware of what symbols are in scope at any given point.
- masklinn 14y agoAn other fun one: (a) - (b) which in statically typed C-like languages can mean either "cast the value -(b) to type a" or "subtract the value (b) from the value (a)"
- epidemian 14y agoThese two are great examples of why i think "overloading" syntax symbols sucks. Problem is, nearly every language does that, and in many cases it makes some expressions ambiguous (not to the parsers, as they have those corner-cases defined, but ambiguous to the programmers): - in JavaScript braces are used both as block delimiters and object literal delimiters - in CoffeeScript, which prevents that particular grammar ambiguity from JS, whitespace is used for many different things: scope/block delimiting, object literals, even function calls (optional parentheses) - Python uses parentheses both for expression grouping (precedence), function calls AND tuples - square brackets are used in many languages to both denote literal lists/arrays and element access ([] operator) - etc, etc, etc There are very few languages that i know about don't do this kind of lexical-token overloading. Smalltalk is an example: square brackets are always blocks, parentheses are only used to group expressions, dots are always statement terminators, etc. I think Haskell is another example of a straightforward syntax, but don't quote me on that. Is there any formal name for these kinds of non-overloaded/simple syntaxes? If there is a formalism for those, why is it that "overloaded" syntaxes are preferred most of the time, or why are they so prevalent?
- Wilduck 14y ago> Is there any formal name for these kinds of non-overloaded/simple syntaxes? If there is a formalism for those, why is it that "overloaded" syntaxes are preferred most of the time, or why are they so prevalent? Someone might be able to say with more certainty, but I believe this is covered by the formalism of "Context Free Grammars" versus "Context Sensitive Grammars"[1]. That is, a language is context free if you don't need information from elsewhere in the code to determine the meaning of a symbol. There's a good discussion of what makes C context sensitive on Eli Bendersky's blog[2]. Edit: Thinking about this some more, I'm realizing that this has little to do with the overloading of symbols like block delimiters, since these can be tokenized and parsed by a context free grammar fairly easily in an "overloaded" fashion. Maybe what you're describing is related to the concept of "purely functional," or even some more vague notion of purity generally... [1] http://en.wikipedia.org/wiki/Context-free_grammar http://en.wikipedia.org/wiki/Context-free_grammar [2] http://eli.thegreenplace.net/2007/11/24/the-context-sensitivity-of-cs-grammar/#fn1 http://eli.thegreenplace.net/2007/11/24/the-context-sensitiv...
- cllns 14y agoI'm interested in how this compares to other languages with reference implementations. Is ruby the odd one out here, not providing a formal grammar, or is that the norm? Ruby has a stated design goal of making developers happy. As far as I'm aware, it hasn't been designed to be easily parsed. I, as an end user (i.e. programmer), prefer it this way. If ease of parsing is important for you, maybe you should use something like LISP.
- masklinn 14y ago> Ruby has a stated design goal of making developers happy. As far as I'm aware, it hasn't been designed to be easily parsed. That does not mean they're opposite goals. Having parsing ambiguities means insufficient thought has been given to parsing, or the language has been defined as "as implemented" with an ad-hoc and organically grown parser (other examples of such case: Perl, PHP) > I, as an end user (i.e. programmer), prefer it this way. You prefer that languages have broken, inane or completely missing grammars? So you like PHP even more than Ruby?
- cllns 14y ago> That does not mean they're opposite goals. Having parsing ambiguities means insufficient thought has been given to parsing, or the language has been defined as "as implemented" with an ad-hoc and organically grown parser (other examples of such case: Perl, PHP) Of course they're not opposite, but you have to choose what to focus on. > You prefer that languages have broken, inane or completely missing grammars? So you like PHP even more than Ruby? Sorry if it wasn't clear, I was comparing easy parsing to developer happiness. That is, I prefer a language tries to make me happy rather than be easy to parse. (this goes back to your point above)
- nine_k 14y agoA language which is hard to parse for a computer is often hard to parse for a human. For instance, computers have fewer problems with the amount of short-term context memory. 'Magic' is often considered bad because it's inexplicable, while clarity is a principal virtue of a programming language in the eyes of many. This is the key problem with DWIM interfaces in general. When it does what you mean, it's so nice. But sometimes you're stuck with ambiguity and lack of a precise means of expression; then you have to jump through hoops to push the 'intuitive' thing out of your way. (Curiously, both MS Word and Perl, of all things, manifest this problem.)
- stib 14y agoA different approach, which has served me well, is to study and understand Perl's parser/lexer, which are more intertwined than your grandmother's Friday night challah. Once you get that, understanding the MRI parser is a snap.
- rictic 14y agoPerl cannot be parsed in the traditional sense of the word. The parse tree is unknowable until you're actually running. http://www.perlmonks.org/?node_id=663393 http://www.perlmonks.org/?node_id=663393
- tantalor 14y agoThis one is also a good read, http://www.perlmonks.org/index.pl?node_id=44722 http://www.perlmonks.org/index.pl?node_id=44722
- joeroot 14y agoI came across this issue when looking to build a stripped down Ruby interpreter in JS last summer. A few attempts have been made at defining its grammar, though with each new version the task becomes more and more challenging. If anyone's interested, this definition of Ruby 1.4 is pretty good: http://www.cse.buffalo.edu/~regan/cse305/RubyBNF.pdf http://www.cse.buffalo.edu/~regan/cse305/RubyBNF.pdf
- masklinn 14y ago> If anyone's interested, this definition of Ruby 1.4 is pretty good The question is whether what it defines corresponds to Ruby. It's easy enough to define an unambiguous subset of the language and declare you're done, but it's irrelevant if the grammar does not match what the language actually is.
- joeroot 14y agoYou'll never reduce Ruby to a pure grammar, there are too many ambiguous cases - my point was simply that it covers a subset which incorporates almost all common idioms. As far as I am aware it is one of the few openly available, non-trivial attempts to do so and thought it might be of interest.
- jayferd 14y agoEven lexing ruby for highlighting is really hard. I had to use so many lookahead hacks to get the lexer in rouge working: https://github.com/jayferd/rouge/blob/master/lib/rouge/lexers/ruby.rb https://github.com/jayferd/rouge/blob/master/lib/rouge/lexer... I learned a ton about ruby when implementing that. Did you know that this totally works: my_method <<-ONE, <<-TWO, <<-THREE text of one ONE text of two TWO text of three THREE And all the % delimited strings are super hard. (also note that pygments chokes on my perfectly valid ruby file, at `%r(\\\\)`)
- Udo 14y agoFor non-rubyists, what does this example do? Are those labels?
- venus 14y agoThat's ruby's heredoc syntax: http://en.wikipedia.org/wiki/Here_document http://en.wikipedia.org/wiki/Here_document I had no idea it could be nested like that and I've been using ruby for 8 years. Crazy!
- mitchty 14y agoHoly cow, 10 years for me and I've never even thought of nesting heredocs. Some days I wish Matz would formalize the grammar so it is sane.
- ahlatimer 14y agoIt's a way of writing strings without having to escape things or having line breaks mess things up (a heredoc, if you're familiar with that terminology). For instance, <<-END this is some text END will give you a string containing " this is some text\n". END can be anything. It's particularly useful in metaprogramming, since you can maintain formatting, and you don't have to escape " or ' if they happen to show up in your code. What's interesting in the OP's example is that you end up passing three strings " text of one\n", " text of two\n", " text of three\n". I had no idea that would happen, though I have seen things like define_method <<-RUBY, __FILE__, __LINE__ + 1 some_code RUBY so it makes sense. Ruby treats anything on the same line after the comma as separate arguments, so even though __FILE__ comes after <<-RUBY and before RUBY, it really appears after the final RUBY to the interpreter.
- softbuilder 14y agoYou can also gaze at http://rubyspec.org/ http://rubyspec.org/
- deleted 14y ago[deleted]
- c3d 14y agoHow to parse XL: http://xlr.git.sourceforge.net/git/gitweb.cgi?p=xlr/xlr;a=blob;f=xlr/scanner.cpp http://xlr.git.sourceforge.net/git/gitweb.cgi?p=xlr/xlr;a=bl... and http://xlr.git.sourceforge.net/git/gitweb.cgi?p=xlr/xlr;a=blob;f=xlr/parser.cpp http://xlr.git.sourceforge.net/git/gitweb.cgi?p=xlr/xlr;a=bl.... 676 + 747 lines of non-hacky C++ code.
- TallboyOne 14y agoI wrote something similar here: http://pineapple.io/discussion/just-learned-about-ripper-in-ruby http://pineapple.io/discussion/just-learned-about-ripper-in-...
- mbillie1 14y ago"By luck and various cabal like connections" - wasn't the Topaz link on hackernews or lobsters like 2 days ago?
- sanxiyn 14y agoHere I note that while JRuby and IronRuby ported parse.y, CPython, Jython, and IronPython use totally different parsing (CPython rolls its own parser generator, Jython uses ANTLR, IronPython does handwritten recursive descent parsing) but are still comatible with each other.
- quadhome 14y ago"Nobody really knows what the Bourne shell’s grammar is. Even examination of the source code is little help." -- Tom Duff, "Rc — A Shell for Plan 9 and UNIX Systems"[1] [1] http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.41.3287&rep=rep1&type=pdf http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.41....
- ww520 14y agoRemember that a yacc file builds an AST tree and paying attention to the AST tree goes a long way in understanding yacc file. Language ambiguity due to context is pretty common. The way to deal with them is with nested scope symbol tables. And determine the semantic of a symbol usage based on previous declaration of the symbol, tracked in the symbol tables. In the article's example, x + 3, it confuses the stages of the lexer and the parser. The lexer only knows x as a symbol. Its output is symbol('x') op('+') num(3). It doesn't know it's a function call or a variable reference. It is the parser's job to figure out the semantic of x based on context and to build the AST. In this case if x has been declared as a variable before, its symbol and type info are recorded in the symbol table. When x + 3 is encountered, it's a simple lookup on the symbol table to see if it's a declared variable and generate the AST node with op('+', var('x'), num(3)). If x has been declared as function in the symbol table, the lookup will generate the funcall AST node. For special declaration rule like usage before declaration (as in Ruby), the lack of definition in the symbol table can be defaulted to a funcall.