Cima di albero ruby ??parser - Impossibile analizzare ordinato Scelta
Domanda
Ho definito semplice grammatica per il parsing della stringa e il numero utilizzando Cima di albero, come di seguito.
grammar Simple
rule value
number / string
end
rule string
word space string
/
word
end
rule word
[0-9a-zA-Z]+
end
rule number
[1-9] [0-9]*
end
rule space
' '+
end
end
Rubino:
parser = SimpleParser.new
parser.parse('123abc wer') # => nil
mi aspetto il parser per tornare stringa nodo , ma aspetto come il parser non riusciva a capire l'ingresso. Qualsiasi idea sarebbe apprezzato.
Soluzione
In Cima (e picchetti in generale, in realtà) l'operatore scelta è ordinato , a differenza di molti altri formalismi di analisi.
Quindi, in
rule value
number / string
end
si sta dicendo Cima di albero che si preferite number
sopra string
.
I tuoi inizia input con 1
, che corrisponde a sia e number
string
(attraverso word
), ma vi ha detto Treetop a preferire l'interpretazione number
, in modo che analizza come number
. Quando si tratta di l'a
nell'input, non ha più regole da applicare, e quindi restituisce nulla (nil
), perché in Cima di albero è un errore di non consumare l'intero flusso di input.
Se semplicemente invertire l'ordine della scelta, l'intero ingresso sarà interpretato come una string
invece di un number
:
SyntaxNode+String0 offset=0, "123abc wer" (word,space,string):
SyntaxNode offset=0, "123abc":
SyntaxNode offset=0, "1"
SyntaxNode offset=1, "2"
SyntaxNode offset=2, "3"
SyntaxNode offset=3, "a"
SyntaxNode offset=4, "b"
SyntaxNode offset=5, "c"
SyntaxNode offset=6, " ":
SyntaxNode offset=6, " "
SyntaxNode offset=7, "wer":
SyntaxNode offset=7, "w"
SyntaxNode offset=8, "e"
SyntaxNode offset=9, "r"
In alternativa, si potrebbe mantenere l'ordine così com'è, ma permettono la regola value
da abbinare più volte. O Inserire una nuova regola di livello superiore in questo modo:
rule values
value+
end
o modificare la regola di value
in questo modo:
rule value
(number / string)+
end
che vi darà un AST o meno in questo modo:
SyntaxNode offset=0, "123abc wer":
SyntaxNode+Number0 offset=0, "123":
SyntaxNode offset=0, "1"
SyntaxNode offset=1, "23":
SyntaxNode offset=1, "2"
SyntaxNode offset=2, "3"
SyntaxNode+String0 offset=3, "abc wer" (word,space,string):
SyntaxNode offset=3, "abc":
SyntaxNode offset=3, "a"
SyntaxNode offset=4, "b"
SyntaxNode offset=5, "c"
SyntaxNode offset=6, " ":
SyntaxNode offset=6, " "
SyntaxNode offset=7, "wer":
SyntaxNode offset=7, "w"
SyntaxNode offset=8, "e"
SyntaxNode offset=9, "r"