Probably the first article Ive ever read about lexical parsing with code that i have actually understood - and I dont even program in golang. Great job.
yes
> that makes the code that much hairier
true, but it does save you the rigamarole of the lexer.
func parseDeclaration(s string, i0 Pos) (n Node, i Pos, err error) {
i = i0
i = skipSpace(s, i)
if word(s, i, "var") {
v := &ast.VarDecl{VarPos: i}
i += 3
i = skipSpace(s, i)
if v.Ident, i, err = parseIdent(s, i); err != nil {
return
}
i = skipSpace(s, i)
if is(s, i, "=") {
i += 1
i = skipSpace(s, i)
if v.Value, i, err = parseExpr(s, i); err != nil {
return
}
}
if !is(s, i, ";") {
return nil, i, fmt.Errorf(`unexpected input or EOF (expected ";")`)
}
⋮I like parser combinators but a word of warning.
A lot of parser combinators (not all) have problems with recursive grammar such as Json and SQL [1].
For instance, a JSON map can contain a JSON map and this can lead to stack overflows when defining the grammar.
[1] https://fsharpforfunandprofit.com/posts/understanding-parser...
Here is a great set of videos from "Low Level Javascript" channel explaining how to write parser combinators from scratch. - https://www.youtube.com/watch?v=6oQLRhw5Ah0&list=PLP29wDx6Qm...