government / sexpr / datum.go

@ 202aec8d6f143ace005fbbe41cc33c7a6344995e | history


package sexpr

// Datum is one piece of source as the reader saw it: the value it reads
// as, where it is, and the comment that describes it. The datums of a
// program form a tree with one datum per node of the program tree, so a
// comment attached to a datum lands on exactly that node, with nothing to
// count or keep in step.
type Datum struct {
	Value      Value
	Start, End Pos
	// Elems are a non-empty list's elements, in order. If the list ends in
	// a dotted pair, the last two are the "." (a datum with Dot set) and
	// the tail. A tail that is itself a list is not dotted at all: the
	// reader reads (a . (b c)) as (a b c), so its elements join this list.
	Elems []*Datum
	Dot   bool
	Note  string
}

// IsList reports whether the datum is a non-empty list, the kind with
// elements. () is an atom.
func (d *Datum) IsList() bool {
	_, ok := d.Value.(*Pair)
	return ok && !d.Dot
}

// DatumOf builds the datum tree for a value that did not come from source,
// with no positions or notes. A list is split exactly as the reader splits
// it, so the reader's datums for some text and DatumOf of the value it
// reads as have the same shape.
func DatumOf(v Value) *Datum {
	d := &Datum{Value: v}
	p, ok := v.(*Pair)
	if !ok {
		return d
	}
	var rest Value = p
	for {
		pair, ok := rest.(*Pair)
		if !ok {
			break
		}
		d.Elems = append(d.Elems, DatumOf(pair.Car))
		rest = pair.Cdr
	}
	if _, ok := rest.(Empty); !ok {
		d.Elems = append(d.Elems, &Datum{Value: Symbol("."), Dot: true}, DatumOf(rest))
	}
	return d
}

// DatumsOf is DatumOf for every form of a program.
func DatumsOf(program []Value) []*Datum {
	ds := make([]*Datum, len(program))
	for i, v := range program {
		ds[i] = DatumOf(v)
	}
	return ds
}

// walk visits d and every datum inside it, a list before its elements.
func (d *Datum) walk(visit func(*Datum)) {
	visit(d)
	for _, e := range d.Elems {
		e.walk(visit)
	}
}