// E'1 -> Number func ep1(buf *token.Buffer, tree ast.Node) (newTree ast.Node, err error) { origPos := buf.Pos() defer func() { if err != nil { buf.MustSeek(origPos) } }() node, err := termNumber(buf) if err != nil { return nil, err } newTree = tree.Copy() newTree.AddChild(node) return newTree, nil }
// E' -> Number | "(" E ")" func ep(buf *token.Buffer, tree ast.Node) (newTree ast.Node, err error) { origPos := buf.Pos() defer func() { if err != nil { buf.MustSeek(origPos) } }() if newTree, err := ep1(buf, tree); err == nil { return newTree, nil } else if newTree, err := ep2(buf, tree); err == nil { return newTree, nil } buf.MustSeek(origPos) return nil, newUnexpectedTokenErrorNext(buf) }
func termNumber(buf *token.Buffer) (node ast.Node, err error) { origPos := buf.Pos() defer func() { if err != nil { buf.MustSeek(origPos) } }() if t, err := buf.Read(); err != nil { return nil, err } else if t.Class == token.Number { return &ast.Number{ Value: t.Value, }, nil } else { return nil, newUnexpectedTokenError(t) } }
// E'2 -> "(" E ")" func ep2(buf *token.Buffer, tree ast.Node) (newTree ast.Node, err error) { origPos := buf.Pos() defer func() { if err != nil { buf.MustSeek(origPos) } }() newTree = tree.Copy() expr := ast.New() newTree.AddChild(expr) if err := termOpenParen(buf); err != nil { return nil, err } if buf.Pos() >= buf.Len() { return nil, io.EOF } eTree, err := e(buf, tree.Copy()) if err != nil { return nil, err } expr.AddChildren(eTree.Children()) if buf.Pos() >= buf.Len() { return nil, io.EOF } if err := termCloseParen(buf); err != nil { return nil, err } return newTree, nil }
// E1 -> E' Op E func e1(buf *token.Buffer, tree ast.Node) (newTree ast.Node, err error) { origPos := buf.Pos() defer func() { if err != nil { buf.MustSeek(origPos) } }() newTree = tree.Copy() epTree, err := ep(buf, tree.Copy()) if err != nil { return nil, err } newTree.AddChildren(epTree.Children()) if buf.Pos() >= buf.Len() { return nil, io.EOF } opNode, err := termOp(buf) if err != nil { return nil, err } newTree.AddChild(opNode) if buf.Pos() >= buf.Len() { return nil, io.EOF } eTree, err := e(buf, tree.Copy()) if err != nil { return nil, err } newTree.AddChildren(eTree.Children()) return newTree, nil }
func termOp(buf *token.Buffer) (node ast.Node, err error) { origPos := buf.Pos() defer func() { if err != nil { buf.MustSeek(origPos) } }() t, err := buf.Read() if err != nil { return nil, err } switch t.Class { case token.Add: return &ast.Operator{ Class: ast.OpAdd, }, nil case token.Subtract: return &ast.Operator{ Class: ast.OpSubtract, }, nil } return nil, newUnexpectedTokenError(t) }