Unless Expression Parsing

G

Gary Wright

I just came across an unexpected parsing problem:

x = 3 unless true # parses just fine, x = nil

p(3 unless true) # parser chokes on unless

p((3 unless true)) # OK, 'nil' is printed


This seems like a bug in the parser rather than a real
syntax problem, but maybe I'm missing something?


Gary Wright
 
B

bbiker

I just came across an unexpected parsing problem:

x = 3 unless true # parses just fine, x = nil

p(3 unless true) # parser chokes on unless

p((3 unless true)) # OK, 'nil' is printed

This seems like a bug in the parser rather than a real
syntax problem, but maybe I'm missing something?

Gary Wright

in irb:

x = 3 unless true => nil

x => nil # x declared as a nil
object since it was never assigned an object
p 3 unless true => nil

p (( 3 unless true)) => nil # you're asking for the result
of '3 unless true', )



p nil => # no result since p did
nothing

3 unless true => # the result is nil but not
captured
so
p (3 unless true) => # no result since you are asking
p to print nothing

Note:

the above is equivalent to
unless true so 'p 3' never gets
interpreted and nothing happens
p 3
end
 
G

Gary Wright

p (( 3 unless true)) => nil # you're asking for the result
of '3 unless true', )


if 'x unless y' is a valid expression then why is the *extra* set
of parenthesis needed when that expression is used as a method argument?

foo(x unless y) # syntax error
foo((x unless y)) # not a syntax error

This seems to be a problem with any of the statement modifier forms:
if, rescue, while, until.

Looking at parse.y it seems that the grammar differentiates between
arguments and statements. Adding the parens forces the statement to
become an expression.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,240
Messages
2,571,211
Members
47,845
Latest member
vojosay

Latest Threads

Top