2015-01-11 21:38:45 +01:00
|
|
|
package ast
|
|
|
|
|
2015-01-12 09:28:47 +01:00
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
)
|
|
|
|
|
2015-01-11 21:38:45 +01:00
|
|
|
// Node is the interface that all AST nodes must implement.
|
2015-01-12 00:26:54 +01:00
|
|
|
type Node interface {
|
2015-01-15 01:36:01 +01:00
|
|
|
// Accept is called to dispatch to the visitors. It must return the
|
|
|
|
// resulting Node (which might be different in an AST transform).
|
|
|
|
Accept(Visitor) Node
|
2015-01-12 09:28:47 +01:00
|
|
|
|
|
|
|
// Pos returns the position of this node in some source.
|
|
|
|
Pos() Pos
|
2015-01-15 05:13:35 +01:00
|
|
|
|
|
|
|
// Type returns the type of this node for the given context.
|
|
|
|
Type(Scope) (Type, error)
|
2015-01-12 09:28:47 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Pos is the starting position of an AST node
|
|
|
|
type Pos struct {
|
|
|
|
Column, Line int // Column/Line number, starting at 1
|
|
|
|
}
|
|
|
|
|
2015-01-12 18:57:16 +01:00
|
|
|
func (p Pos) String() string {
|
2015-01-12 09:28:47 +01:00
|
|
|
return fmt.Sprintf("%d:%d", p.Line, p.Column)
|
2015-01-12 00:26:54 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Visitors are just implementations of this function.
|
|
|
|
//
|
2015-01-15 01:36:01 +01:00
|
|
|
// The function must return the Node to replace this node with. "nil" is
|
|
|
|
// _not_ a valid return value. If there is no replacement, the original node
|
|
|
|
// should be returned. We build this replacement directly into the visitor
|
|
|
|
// pattern since AST transformations are a common and useful tool and
|
|
|
|
// building it into the AST itself makes it required for future Node
|
|
|
|
// implementations and very easy to do.
|
|
|
|
//
|
2015-01-12 00:26:54 +01:00
|
|
|
// Note that this isn't a true implementation of the visitor pattern, which
|
|
|
|
// generally requires proper type dispatch on the function. However,
|
|
|
|
// implementing this basic visitor pattern style is still very useful even
|
|
|
|
// if you have to type switch.
|
2015-01-15 01:36:01 +01:00
|
|
|
type Visitor func(Node) Node
|
2015-01-11 21:38:45 +01:00
|
|
|
|
2015-01-11 23:35:14 +01:00
|
|
|
//go:generate stringer -type=Type
|
|
|
|
|
2015-01-15 05:13:35 +01:00
|
|
|
// Type is the type of any value.
|
2015-01-13 21:40:47 +01:00
|
|
|
type Type uint32
|
2015-01-11 21:38:45 +01:00
|
|
|
|
|
|
|
const (
|
2015-01-12 00:26:54 +01:00
|
|
|
TypeInvalid Type = 0
|
2015-01-13 17:50:28 +01:00
|
|
|
TypeString Type = 1 << iota
|
2015-01-12 08:38:21 +01:00
|
|
|
TypeInt
|
2015-01-12 17:53:27 +01:00
|
|
|
TypeFloat
|
2015-01-11 21:38:45 +01:00
|
|
|
)
|