godoc.org-compatible ast package

Change the dump code so that it hides the values of variable
definitions if they're large. This means that godoc.org should
be able to deal with the output, and the godoc output is
readable without needing to read through a huge struct literal definition.

Other approaches might be to always generate an extra variable
(seems unnecessary) or to pass to writer explicitly to the dump
methods rather than swapping s.w out temporarily. The former
seems unnecessarily intrusive to the usual output; the latter
seemed unnecessarily intrusive to the source itself.
YMMV.
This commit is contained in:
Roger Peppe 2018-04-12 12:43:24 +01:00 committed by Dave Cunningham
parent dfddf2b4e3
commit fde815f6a1
3 changed files with 39 additions and 1 deletions

View File

@ -4677,7 +4677,8 @@ var p1 = &Source{
}
// StdAst is the AST for the standard library.
var StdAst = &DesugaredObject{
var StdAst = _StdAst
var _StdAst = &DesugaredObject{
NodeBase: NodeBase{
loc: LocationRange{
FileName: "<std>",

View File

@ -184,7 +184,21 @@ func (s *dumpState) dump(value interface{}) {
if v.Kind() == reflect.Ptr && v.IsNil() {
printNil(s.w)
} else {
// Replace the writer with a temporary buffer so that
// we can see how big the output is. If it's too big,
// we use an intermediate value so that godoc output
// isn't swamped by the literal.
oldWriter := s.w
buf := new(bytes.Buffer)
s.w = buf
s.dumpVal(v)
s.w = oldWriter
if buf.Len() > 100 {
s.w.Write([]byte("_" + s.config.VariableName))
s.newline()
s.w.Write([]byte("var _" + s.config.VariableName + " = "))
}
s.w.Write(buf.Bytes())
}
s.newline()
}

View File

@ -454,3 +454,26 @@ var Obj = &struct { Foo *Zeo; Bar *Zeo }{
}
}
}
func TestSdumpLargeDefinition(t *testing.T) {
type largeStruct struct {
ABCDEFGHIJKLMNOBQRSTUVWXYZ0 int
ABCDEFGHIJKLMNOBQRSTUVWXYZ1 int
ABCDEFGHIJKLMNOBQRSTUVWXYZ2 int
ABCDEFGHIJKLMNOBQRSTUVWXYZ3 int
ABCDEFGHIJKLMNOBQRSTUVWXYZ4 int
}
got := Sdump(&largeStruct{1, 2, 3, 4, 5})
want := `var Obj = _Obj
var _Obj = &largeStruct{
ABCDEFGHIJKLMNOBQRSTUVWXYZ0: int(1),
ABCDEFGHIJKLMNOBQRSTUVWXYZ1: int(2),
ABCDEFGHIJKLMNOBQRSTUVWXYZ2: int(3),
ABCDEFGHIJKLMNOBQRSTUVWXYZ3: int(4),
ABCDEFGHIJKLMNOBQRSTUVWXYZ4: int(5),
}
`
if got != want {
t.Errorf("got : \n%#v\n, want : \n%#v", got, want)
}
}