示例#1
0
func (p *Printer) printInit(typ *cc.Type, x *cc.Init) {
	p.Print(x.Comments.Before)
	defer p.Print(x.Comments.Suffix, x.Comments.After)

	if len(x.Prefix) > 0 {
		for _, pre := range x.Prefix {
			p.Print(pre)
		}
	}
	if x.Expr != nil {
		if x.Expr.Op == cc.Number && (typ.Is(cc.Ptr) || typ.Is(Slice)) {
			p.Print("nil")
			return
		}
		p.printExpr(x.Expr, precComma)
		return
	}

	nl := len(x.Braced) > 0 && x.Braced[0].Span.Start.Line != x.Braced[len(x.Braced)-1].Span.End.Line
	if typ != nil {
		p.printType(typ)
	}
	p.Print("{")
	if nl {
		p.Print(Indent)
	}
	warned := false
	for i, y := range x.Braced {
		if nl {
			p.Print(Newline)
		} else if i > 0 {
			p.Print(" ")
		}
		var subtyp *cc.Type
		if typ != nil {
			if typ.Is(cc.Struct) && i < len(typ.Def().Decls) && len(y.Prefix) == 0 {
				subtyp = typ.Def().Decls[i].Type
			} else if typ.Is(cc.Struct) && len(y.Prefix) == 1 && y.Prefix[0].XDecl != nil {
				subtyp = y.Prefix[0].XDecl.Type
			} else if typ.Is(cc.Array) || typ.Is(Slice) {
				subtyp = typ.Def().Base
			} else if !warned {
				warned = true
				fprintf(x.Span, "too many fields in braced initializer of %s", GoString(typ))
			}
		}
		p.printInit(subtyp, y)
		p.Print(",")
	}
	if typ != nil && typ.Is(cc.Struct) && len(x.Braced) > 0 && len(x.Braced[0].Prefix) == 0 && len(x.Braced) < len(typ.Def().Decls) {
		for i := len(x.Braced); i < len(typ.Def().Decls); i++ {
			subtyp := typ.Def().Decls[i].Type
			if subtyp.Is(cc.Ptr) || subtyp.Is(Slice) {
				p.Print(" nil,")
			} else if subtyp.Is(cc.Array) {
				p.Print(" ", subtyp, "{},")
			} else {
				p.Print(" 0,")
			}
		}
	}
	if nl {
		p.Print(Unindent, Newline)
	}
	p.Print("}")
}