government / src / sexpr / notes.go

@ efc0e8ad4d88be48a5cdedd9b62e88420b8b6e5e | history


package sexpr

import "strings"

// ReadProgram reads every top-level form of src and attaches each comment
// to the datum it describes, as that datum's Note.
//
// A comment that follows code on the same line describes that code: the
// last datum to end before it, taking the outermost when several end at
// the same place, as a list and its last element do. Any other comment
// describes the next datum to start after it. Several comments on the same
// datum are joined with newlines, in order. Every comment is a note: the
// test runner's ";=>" and ";=!" annotations mean nothing to the language.
func ReadProgram(src string) ([]*Datum, error) {
	r := NewReader(src)
	var forms []*Datum
	for {
		d, err := r.ReadDatum()
		if err != nil {
			return nil, err
		}
		if d == nil {
			break
		}
		forms = append(forms, d)
	}

	// Every datum that is part of the program, in reading order. Only these
	// can take a note, so a "." or parentheses that a dotted tail merged
	// away never take one by mistake.
	var all []*Datum
	for _, f := range forms {
		f.walk(func(d *Datum) { all = append(all, d) })
	}
	for _, c := range r.comments {
		d := trailed(all, c.Pos)
		if d == nil {
			d = following(all, c.Pos)
		}
		if d == nil {
			continue
		}
		text := noteText(c.Text)
		if d.Note != "" {
			text = d.Note + "\n" + text
		}
		d.Note = text
	}
	return forms, nil
}

// noteText drops the comment markers and the one space after them, so
// ";; total" and "; total" are both the note "total".
func noteText(text string) string {
	text = strings.TrimLeft(text, ";")
	text = strings.TrimPrefix(text, " ")
	return strings.TrimRight(text, " \t\r")
}

// trailed is the datum a comment at pos follows on the same line, or nil.
// all is in reading order, so the first datum to reach the latest end is
// the outermost one ending there.
func trailed(all []*Datum, pos Pos) *Datum {
	var best *Datum
	for _, d := range all {
		if d.End.Line != pos.Line || d.End.Col > pos.Col {
			continue
		}
		if best == nil || d.End.Col > best.End.Col {
			best = d
		}
	}
	return best
}

// following is the first datum that starts after pos, or nil: the
// outermost datum starting there, since a list comes before its elements.
func following(all []*Datum, pos Pos) *Datum {
	for _, d := range all {
		if d.Start.Line > pos.Line || (d.Start.Line == pos.Line && d.Start.Col > pos.Col) {
			return d
		}
	}
	return nil
}