goby icon indicating copy to clipboard operation
goby copied to clipboard

`a=1; -a` returns an invalid value

Open hachi8833 opened this issue 7 years ago • 7 comments

Found the issue in #560, on REPL. Unary operator + or - just after semicolon ; returns invalid values like:

» a=1;a
#» 1    # correct
» a=1; -a
#» 0    # invalid: should be -1
» a=1;+a
#» 2    # invalid: should be 1
» a
#» 1    # correct
» -a
#» -1  # correct

hachi8833 avatar Jan 07 '18 07:01 hachi8833

I have an idea to fix the issue: how about changing skipWhitespace() to treat ; as \n like the following? This would make the lexer simplified.

func (l *Lexer) skipWhitespace() {
	for l.ch == ' ' || l.ch == '\t' || l.ch == '\r' || l.ch == '\n' || l.ch == ';' {
		if l.ch == '\n' || l.ch == ';' {
			l.line++
		}
		l.readChar()
	}
}

hachi8833 avatar Jan 08 '18 01:01 hachi8833

I think this is just a workaround, not the best solution

st0012 avatar Jan 08 '18 01:01 st0012

It looks like when the unary operator is present, these are being treated as InfixExpression 🤔

» a="1";.to_i
#» 1

SD10 avatar Jan 17 '18 06:01 SD10

Can you help me confirm this as well?

st0012 avatar Jul 27 '19 03:07 st0012

Got it!

hachi8833 avatar Jul 27 '19 23:07 hachi8833

I know the test below is incorrect, but the result below should be clear on how it was parsed:

// parser_test.go
func TestMultipleExpressionOnSameLineParsing(t *testing.T) {
	tests := []struct {
		input    string
		expected string
	}{
		{
			"a = 1; +a",
			"a = 1; +a",
		},
		{
			"a = 1; .to_i",
			"a = 1; .to_i",
		},
	}
        // ... omit

The result:

// ...omit above
ok      github.com/goby-lang/goby/compiler/lexer        (cached)
--- FAIL: TestMultipleExpressionOnSameLineParsing (0.00s)
    parser_test.go:198: expcted="a = 1; +a", got="(a = 1 + a)"
    parser_test.go:198: expcted="a = 1; .to_i", got="a = 1.to_i()"
FAIL
// ...omit below

(However, I'm still thinking about how should the problem be solved. 🤔 )

Alexius-Huang avatar Oct 20 '19 13:10 Alexius-Huang

@Maxwell-Alexius great observation! According to the failure message, I think the parser just ignored the semicolon accidentally.

st0012 avatar Oct 27 '19 06:10 st0012