kach / nearley

📜🔜🌲 Simple, fast, powerful parser toolkit for JavaScript.
https://nearley.js.org
MIT License
3.59k stars 232 forks source link

Problem with Unary minus #524

Closed jskolovos closed 4 years ago

jskolovos commented 4 years ago

Hi, I have problems with a very simple grammar

# Filename: gram.ne

Expr   -> Sign Num
Sign   -> "+" | "-"
Num    -> Digit | Num Digit
Digit  -> [0-9]

I compiled it with

nearleyc ./gram.ne --out ./gram.js

and I tested it with nearley-test , I think the following output is incorrect

nearley-test ./gram.js --input '-1'

Table length: 1
Number of parses: 0
Parse Charts
Chart: 0
0: {Expr →  ● Sign Num}, from: 0
1: {Sign →  ● "+"}, from: 0
2: {Sign →  ● "-"}, from: 0

Parse results: 
[]

But with "+" sign instead of "-" it behaves as expected

nearley-test ./gram.js --input '+1'

Table length: 3
Number of parses: 1
Parse Charts
Chart: 0
0: {Expr →  ● Sign Num}, from: 0
1: {Sign →  ● "+"}, from: 0
2: {Sign →  ● "-"}, from: 0

Chart: 1
0: {Sign → "+" ● }, from: 0
1: {Expr → Sign ● Num}, from: 0
2: {Num →  ● Digit}, from: 1
3: {Num →  ● Num Digit}, from: 1
4: {Digit →  ● /[0-9]/}, from: 1

Chart: 2
0: {Digit → /[0-9]/ ● }, from: 1
1: {Num → Digit ● }, from: 1
2: {Num → Num ● Digit}, from: 1
3: {Expr → Sign Num ● }, from: 0
4: {Digit →  ● /[0-9]/}, from: 2

Parse results: 
[ [ [ '+' ], [ [ '1' ] ] ] ]

The nearley version I am using is:

nearleyc -v
2.19.4
nearley-test -v
2.19.4

I expected Parse results to be [ [ [ '-' ], [ [ '1' ] ] ] ] with the minus sign.

Is this a bug?? or am I missing something.

Thanks in advance.

jskolovos commented 4 years ago

Ok. After some tests, I have these findings.

It is a bug inside nearley-test.js, expecifically with commander.js

I put console.log('INP=', opts.input) before the instruction parser.feed(opts.input) in the sourcce code of nearley-test.js and when I test with nearley-test ./gg1.js --input '-1' it prints:

When I test with nearley-test ./gg1.js --input '+1' it prints:

I'm glad nearley.js is not misbehaving, but I think it should be important to fix this problem in order to avoid other people facing this problem.

kach commented 4 years ago

Huh, that is odd. It seems the option parser thinks -1 is a flag.

To solve your immediate problem, can you pipe the input you want into nearley-test's stdin instead?

jskolovos commented 4 years ago

@kach Thanks for your reply.

I was worried that the problem where in the parser, but being in the tester, I can avoid making tests beginning with minus (they are only tests).

And when I put the parser in a program, I know it works just fine.

I think it is important to at least mention it in the docs, In order to help the people new into nearley.js.

Thanks again for the parser, the docs and examples.

jskolovos commented 4 years ago

I reopened this issue wondering somebody have something to add. Sorry for closing it before

kach commented 4 years ago

That's alright, I think it can be closed.