[grammarians] ambiguity with method call?
Mauricio Fernández
mfp at acm.org
Tue Nov 29 18:01:54 EST 2005
On Tue, Nov 29, 2005 at 09:23:08PM +0000, Sean O'Halpin wrote:
> On 11/29/05, Terence Parr <parrt at cs.usfca.edu> wrote:
> > Howdy,
> > What does foo [1] parse as?
> > foo could be a variable and then foo is a simple array var:
> > foo = [a,b]
> > foo[1]
> > If foo is a method, it could return an array and then you could
> > access the 1st element:
> > def foo
> > return [a,b]
> > end
> > foo[1]
> > It could also be a method with args:
> > def foo x
> > ...
> > end
> > foo [1] # same as foo([1])
[...]
> There is also the case where [] can be a synonym for Proc#call, e.g.
>
> foo = proc {|x| x*x }
>
> foo [2] #=> 4
That's just another instance of a call to #[].
Before assigning to foo:
* foo is considered a method call until the parser sees an assignment to the foo
variable (as said before, this does not depend on whether that assignment is
actually executed or not).
* somemethod[0] means sending the #[] message to the value returned by
somemethod, like (x = somemethod; x[0])
* somemethod [0] is a call to the somemethod method (argument [0])
After assigning to foo:
* both foo[0] and foo [0] send the #[] message to the object referred to by
foo (argument 0)
These are all reflected in the AST built in parse.y:
def foo(x = :default); [x,1] end
foo[0] # => :default
# [:call, [:vcall, :foo], :[], [:array, [:lit, 0]]]
foo [0] # => [[0], 1]
# [:fcall, :foo, [:array, [:array, [:lit, 0]]]]
foo=[1]
foo[0] # => 1
# [:call, [:lvar, :foo], :[], [:array, [:lit, 0]]]
foo [0] # => 1
# [:call, [:lvar, :foo], :[], [:array, [:lit, 0]]]
foo = lambda{|x| [x]}
foo[0] # => [0]
# [:call, [:lvar, :foo], :[], [:array, [:lit, 0]]]
foo [0] # => [0]
# [:call, [:lvar, :foo], :[], [:array, [:lit, 0]]]
--
Mauricio Fernandez
More information about the Rubygrammar-grammarians
mailing list