2016-01-25 02:04:15 +08:00
|
|
|
package parse
|
|
|
|
|
2021-01-27 09:28:38 +08:00
|
|
|
import "src.elv.sh/pkg/diag"
|
2018-09-29 03:55:00 +08:00
|
|
|
|
2016-02-08 06:23:16 +08:00
|
|
|
// Node represents a parse tree as well as an AST.
|
2016-01-25 02:04:15 +08:00
|
|
|
type Node interface {
|
2018-10-13 20:57:25 +08:00
|
|
|
diag.Ranger
|
2020-04-26 01:55:44 +08:00
|
|
|
parse(*parser)
|
|
|
|
n() *node
|
2016-01-25 02:04:15 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
type node struct {
|
2018-10-14 00:04:02 +08:00
|
|
|
diag.Ranging
|
2016-01-25 02:04:15 +08:00
|
|
|
sourceText string
|
2018-10-14 00:04:02 +08:00
|
|
|
parent Node
|
2016-01-25 02:04:15 +08:00
|
|
|
children []Node
|
|
|
|
}
|
|
|
|
|
2020-04-26 01:55:44 +08:00
|
|
|
func (n *node) n() *node { return n }
|
2018-10-14 00:08:15 +08:00
|
|
|
|
|
|
|
func (n *node) addChild(ch Node) { n.children = append(n.children, ch) }
|
2018-10-13 23:02:19 +08:00
|
|
|
|
2020-04-26 01:55:44 +08:00
|
|
|
// Range returns the range within the full source text that parses to the node.
|
|
|
|
func (n *node) Range() diag.Ranging { return n.Ranging }
|
2016-01-25 02:04:15 +08:00
|
|
|
|
2020-04-26 01:55:44 +08:00
|
|
|
// Parent returns the parent of a node. It returns nil if the node is the root
|
|
|
|
// of the parse tree.
|
|
|
|
func Parent(n Node) Node { return n.n().parent }
|
2018-10-13 20:57:25 +08:00
|
|
|
|
2018-10-13 21:03:58 +08:00
|
|
|
// SourceText returns the part of the source text that parses to the node.
|
2020-04-26 01:55:44 +08:00
|
|
|
func SourceText(n Node) string { return n.n().sourceText }
|
2016-01-25 02:04:15 +08:00
|
|
|
|
2018-10-13 21:03:58 +08:00
|
|
|
// Children returns all children of the node in the parse tree.
|
2020-04-26 01:55:44 +08:00
|
|
|
func Children(n Node) []Node { return n.n().children }
|