print.go 20.8 KB
Newer Older
Rob Pike's avatar
Rob Pike committed
1 2 3 4
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

Rob Pike's avatar
Rob Pike committed
5 6 7 8 9 10 11 12
/*
	Package fmt implements formatted I/O with functions analogous
	to C's printf.  The format 'verbs' are derived from C's but
	are simpler.

	The verbs:

	General:
Russ Cox's avatar
Russ Cox committed
13
		%v	the value in a default format.
Rob Pike's avatar
Rob Pike committed
14
			when printing structs, the plus flag (%+v) adds field names
Russ Cox's avatar
Russ Cox committed
15 16 17
		%#v	a Go-syntax representation of the value
		%T	a Go-syntax representation of the type of the value

Rob Pike's avatar
Rob Pike committed
18 19 20 21 22 23 24 25 26 27 28
	Boolean:
		%t	the word true or false
	Integer:
		%b	base 2
		%c	the character represented by the corresponding Unicode code point
		%d	base 10
		%o	base 8
		%x	base 16, with lower-case letters for a-f
		%X	base 16, with upper-case letters for A-F
	Floating-point:
		%e	scientific notation, e.g. -1234.456e+78
Russ Cox's avatar
Russ Cox committed
29
		%E	scientific notation, e.g. -1234.456E+78
Rob Pike's avatar
Rob Pike committed
30 31
		%f	decimal point but no exponent, e.g. 123.456
		%g	whichever of %e or %f produces more compact output
Russ Cox's avatar
Russ Cox committed
32
		%G	whichever of %E or %f produces more compact output
Rob Pike's avatar
Rob Pike committed
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
	String and slice of bytes:
		%s	the uninterpreted bytes of the string or slice
		%q	a double-quoted string safely escaped with Go syntax
		%x	base 16 notation with two characters per byte
	Pointer:
		%p	base 16 notation, with leading 0x

	There is no 'u' flag.  Integers are printed unsigned if they have unsigned type.
	Similarly, there is no need to specify the size of the operand (int8, int64).

	For numeric values, the width and precision flags control
	formatting; width sets the width of the field, precision the
	number of places after the decimal, if appropriate.  The
	format %6.2f prints 123.45.

	Other flags:
		+	always print a sign for numeric values
		-	pad with spaces on the right rather than the left (left-justify the field)
		#	alternate format: add leading 0 for octal (%#o), 0x for hex (%#x);
			suppress 0x for %p (%#p);
			print a raw (backquoted) string if possible for %q (%#q)
		' '	(space) leave a space for elided sign in numbers (% d);
			put spaces between bytes printing strings or slices in hex (% x)
		0	pad with leading zeros rather than spaces

	For each Printf-like function, there is also a Print function
	that takes no format and is equivalent to saying %v for every
	operand.  Another variant Println inserts blanks between
	operands and appends a newline.

63 64 65 66 67 68 69
	Regardless of the verb, if an operand is an interface value,
	the internal concrete value is used, not the interface itself.
	Thus:
		var i interface{} = 23;
		fmt.Printf("%v\n", i);
	will print 23.

Rob Pike's avatar
Rob Pike committed
70
	If an operand implements interface Formatter, that interface
Rob Pike's avatar
Rob Pike committed
71 72 73 74 75
	can be used for fine control of formatting.

	If an operand implements method String() string that method
	will be used for %v, %s, or Print etc.
*/
Rob Pike's avatar
Rob Pike committed
76 77
package fmt

Rob Pike's avatar
Rob Pike committed
78

Rob Pike's avatar
Rob Pike committed
79
import (
Rob Pike's avatar
Rob Pike committed
80
	"io";
Rob Pike's avatar
Rob Pike committed
81
	"os";
82
	"reflect";
Russ Cox's avatar
Russ Cox committed
83
	"utf8";
Rob Pike's avatar
Rob Pike committed
84 85
)

86
// State represents the printer state passed to custom formatters.
87
// It provides access to the io.Writer interface plus information about
Rob Pike's avatar
Rob Pike committed
88
// the flags and options for the operand's format specifier.
89
type State interface {
Rob Pike's avatar
Rob Pike committed
90
	// Write is the function to call to emit formatted output to be printed.
91
	Write(b []byte) (ret int, err os.Error);
Rob Pike's avatar
Rob Pike committed
92
	// Width returns the value of the width option and whether it has been set.
Rob Pike's avatar
Rob Pike committed
93
	Width()	(wid int, ok bool);
Rob Pike's avatar
Rob Pike committed
94
	// Precision returns the value of the precision option and whether it has been set.
Rob Pike's avatar
Rob Pike committed
95
	Precision()	(prec int, ok bool);
96

Rob Pike's avatar
Rob Pike committed
97
	// Flag returns whether the flag c, a character, has been set.
98
	Flag(int)	bool;
Rob Pike's avatar
Rob Pike committed
99 100
}

Russ Cox's avatar
Russ Cox committed
101
// Formatter is the interface implemented by values with a custom formatter.
Rob Pike's avatar
Rob Pike committed
102 103
// The implementation of Format may call Sprintf or Fprintf(f) etc.
// to generate its output.
104 105
type Formatter interface {
	Format(f State, c int);
106 107
}

Russ Cox's avatar
Russ Cox committed
108 109 110 111
// Stringer is implemented by any value that has a String method(),
// which defines the ``native'' format for that value.
// The String method is used to print values passed as an operand
// to a %s or %v format or to an unformatted printer such as Print.
112
type Stringer interface {
113
	String() string
Rob Pike's avatar
Rob Pike committed
114 115
}

Russ Cox's avatar
Russ Cox committed
116 117 118 119 120 121 122 123
// GoStringer is implemented by any value that has a GoString() method,
// which defines the Go syntax for that value.
// The GoString method is used to print values passed as an operand
// to a %#v format.
type GoStringer interface {
	GoString() string
}

Rob Pike's avatar
Rob Pike committed
124
const runeSelf = utf8.RuneSelf
Rob Pike's avatar
Rob Pike committed
125
const allocSize = 32
Rob Pike's avatar
Rob Pike committed
126

Rob Pike's avatar
Rob Pike committed
127
type pp struct {
Rob Pike's avatar
Rob Pike committed
128
	n	int;
Russ Cox's avatar
Russ Cox committed
129
	buf	[]byte;
Rob Pike's avatar
Rob Pike committed
130 131 132
	fmt	*Fmt;
}

Rob Pike's avatar
Rob Pike committed
133
func newPrinter() *pp {
Rob Pike's avatar
Rob Pike committed
134
	p := new(pp);
135
	p.fmt = New();
Rob Pike's avatar
Rob Pike committed
136 137 138
	return p;
}

Rob Pike's avatar
Rob Pike committed
139
func (p *pp) Width() (wid int, ok bool) {
140
	return p.fmt.wid, p.fmt.wid_present
Rob Pike's avatar
Rob Pike committed
141 142
}

Rob Pike's avatar
Rob Pike committed
143
func (p *pp) Precision() (prec int, ok bool) {
144 145 146
	return p.fmt.prec, p.fmt.prec_present
}

Rob Pike's avatar
Rob Pike committed
147
func (p *pp) Flag(b int) bool {
148 149 150 151 152 153 154 155 156 157 158 159 160
	switch b {
	case '-':
		return p.fmt.minus;
	case '+':
		return p.fmt.plus;
	case '#':
		return p.fmt.sharp;
	case ' ':
		return p.fmt.space;
	case '0':
		return p.fmt.zero;
	}
	return false
Rob Pike's avatar
Rob Pike committed
161 162
}

Rob Pike's avatar
Rob Pike committed
163
func (p *pp) ensure(n int) {
Russ Cox's avatar
Russ Cox committed
164
	if len(p.buf) < n {
Rob Pike's avatar
Rob Pike committed
165
		newn := allocSize + len(p.buf);
Rob Pike's avatar
Rob Pike committed
166
		if newn < n {
Rob Pike's avatar
Rob Pike committed
167
			newn = n + allocSize
Rob Pike's avatar
Rob Pike committed
168
		}
Russ Cox's avatar
Russ Cox committed
169
		b := make([]byte, newn);
Rob Pike's avatar
Rob Pike committed
170 171 172 173 174 175 176
		for i := 0; i < p.n; i++ {
			b[i] = p.buf[i];
		}
		p.buf = b;
	}
}

Rob Pike's avatar
Rob Pike committed
177
func (p *pp) addstr(s string) {
Rob Pike's avatar
Rob Pike committed
178 179 180 181 182 183 184 185
	n := len(s);
	p.ensure(p.n + n);
	for i := 0; i < n; i++ {
		p.buf[p.n] = s[i];
		p.n++;
	}
}

Rob Pike's avatar
Rob Pike committed
186
func (p *pp) addbytes(b []byte, start, end int) {
Rob Pike's avatar
Rob Pike committed
187 188 189 190 191 192 193
	p.ensure(p.n + end-start);
	for i := start; i < end; i++ {
		p.buf[p.n] = b[i];
		p.n++;
	}
}

Rob Pike's avatar
Rob Pike committed
194
func (p *pp) add(c int) {
Rob Pike's avatar
Rob Pike committed
195
	p.ensure(p.n + 1);
Rob Pike's avatar
Rob Pike committed
196
	if c < runeSelf {
Rob Pike's avatar
Rob Pike committed
197 198 199 200 201 202 203
		p.buf[p.n] = byte(c);
		p.n++;
	} else {
		p.addstr(string(c));
	}
}

Rob Pike's avatar
Rob Pike committed
204 205
// Implement Write so we can call fprintf on a P, for
// recursive use in custom verbs.
206
func (p *pp) Write(b []byte) (ret int, err os.Error) {
Rob Pike's avatar
Rob Pike committed
207 208
	p.addbytes(b, 0, len(b));
	return len(b), nil;
Rob Pike's avatar
Rob Pike committed
209 210 211 212
}

// These routines end in 'f' and take a format string.

Rob Pike's avatar
Rob Pike committed
213
// Fprintf formats according to a format specifier and writes to w.
214
func Fprintf(w io.Writer, format string, a ...) (n int, error os.Error) {
215
	v := reflect.NewValue(a).(*reflect.StructValue);
Rob Pike's avatar
Rob Pike committed
216
	p := newPrinter();
Rob Pike's avatar
Rob Pike committed
217 218 219 220 221
	p.doprintf(format, v);
	n, error = w.Write(p.buf[0:p.n]);
	return n, error;
}

Rob Pike's avatar
Rob Pike committed
222
// Printf formats according to a format specifier and writes to standard output.
223
func Printf(format string, v ...) (n int, errno os.Error) {
Rob Pike's avatar
Rob Pike committed
224
	n, errno = Fprintf(os.Stdout, format, v);
Rob Pike's avatar
Rob Pike committed
225 226 227
	return n, errno;
}

Rob Pike's avatar
Rob Pike committed
228
// Sprintf formats according to a format specifier and returns the resulting string.
Russ Cox's avatar
Russ Cox committed
229
func Sprintf(format string, a ...) string {
230
	v := reflect.NewValue(a).(*reflect.StructValue);
Rob Pike's avatar
Rob Pike committed
231
	p := newPrinter();
232
	p.doprintf(format, v);
Rob Pike's avatar
Rob Pike committed
233 234 235 236
	s := string(p.buf)[0 : p.n];
	return s;
}

Rob Pike's avatar
Rob Pike committed
237
// These routines do not take a format string
Rob Pike's avatar
Rob Pike committed
238

Rob Pike's avatar
Rob Pike committed
239 240
// Fprint formats using the default formats for its operands and writes to w.
// Spaces are added between operands when neither is a string.
241
func Fprint(w io.Writer, a ...) (n int, error os.Error) {
242
	v := reflect.NewValue(a).(*reflect.StructValue);
Rob Pike's avatar
Rob Pike committed
243
	p := newPrinter();
Rob Pike's avatar
Rob Pike committed
244
	p.doprint(v, false, false);
Rob Pike's avatar
Rob Pike committed
245 246 247 248
	n, error = w.Write(p.buf[0:p.n]);
	return n, error;
}

Rob Pike's avatar
Rob Pike committed
249 250
// Print formats using the default formats for its operands and writes to standard output.
// Spaces are added between operands when neither is a string.
251
func Print(v ...) (n int, errno os.Error) {
Rob Pike's avatar
Rob Pike committed
252
	n, errno = Fprint(os.Stdout, v);
Rob Pike's avatar
Rob Pike committed
253 254 255
	return n, errno;
}

Rob Pike's avatar
Rob Pike committed
256 257
// Sprint formats using the default formats for its operands and returns the resulting string.
// Spaces are added between operands when neither is a string.
Russ Cox's avatar
Russ Cox committed
258
func Sprint(a ...) string {
259
	v := reflect.NewValue(a).(*reflect.StructValue);
Rob Pike's avatar
Rob Pike committed
260
	p := newPrinter();
261
	p.doprint(v, false, false);
Rob Pike's avatar
Rob Pike committed
262 263 264 265 266 267 268 269
	s := string(p.buf)[0 : p.n];
	return s;
}

// These routines end in 'ln', do not take a format string,
// always add spaces between operands, and add a newline
// after the last operand.

Rob Pike's avatar
Rob Pike committed
270 271
// Fprintln formats using the default formats for its operands and writes to w.
// Spaces are always added between operands and a newline is appended.
272
func Fprintln(w io.Writer, a ...) (n int, error os.Error) {
273
	v := reflect.NewValue(a).(*reflect.StructValue);
Rob Pike's avatar
Rob Pike committed
274
	p := newPrinter();
Rob Pike's avatar
Rob Pike committed
275
	p.doprint(v, true, true);
Rob Pike's avatar
Rob Pike committed
276 277 278 279
	n, error = w.Write(p.buf[0:p.n]);
	return n, error;
}

Rob Pike's avatar
Rob Pike committed
280 281
// Println formats using the default formats for its operands and writes to standard output.
// Spaces are always added between operands and a newline is appended.
282
func Println(v ...) (n int, errno os.Error) {
Rob Pike's avatar
Rob Pike committed
283
	n, errno = Fprintln(os.Stdout, v);
Rob Pike's avatar
Rob Pike committed
284 285 286
	return n, errno;
}

Rob Pike's avatar
Rob Pike committed
287 288
// Sprintln formats using the default formats for its operands and returns the resulting string.
// Spaces are always added between operands and a newline is appended.
Russ Cox's avatar
Russ Cox committed
289
func Sprintln(a ...) string {
290
	v := reflect.NewValue(a).(*reflect.StructValue);
Rob Pike's avatar
Rob Pike committed
291
	p := newPrinter();
292
	p.doprint(v, true, true);
Rob Pike's avatar
Rob Pike committed
293 294 295 296
	s := string(p.buf)[0 : p.n];
	return s;
}

297 298 299 300

// Get the i'th arg of the struct value.
// If the arg itself is an interface, return a value for
// the thing inside the interface, not the interface itself.
301
func getField(v *reflect.StructValue, i int) reflect.Value {
302
	val := v.Field(i);
303 304 305 306
	if i, ok := val.(*reflect.InterfaceValue); ok {
		if inter := i.Interface(); inter != nil {
			return reflect.NewValue(inter);
		}
307 308 309 310
	}
	return val;
}

Rob Pike's avatar
Rob Pike committed
311 312
// Getters for the fields of the argument structure.

Rob Pike's avatar
Rob Pike committed
313
func getBool(v reflect.Value) (val bool, ok bool) {
314 315
	if b, ok := v.(*reflect.BoolValue); ok {
		return b.Get(), true;
Rob Pike's avatar
Rob Pike committed
316
	}
317
	return;
Rob Pike's avatar
Rob Pike committed
318 319
}

Rob Pike's avatar
Rob Pike committed
320
func getInt(v reflect.Value) (val int64, signed, ok bool) {
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
	switch v := v.(type) {
	case *reflect.IntValue:
		return int64(v.Get()), true, true;
	case *reflect.Int8Value:
		return int64(v.Get()), true, true;
	case *reflect.Int16Value:
		return int64(v.Get()), true, true;
	case *reflect.Int32Value:
		return int64(v.Get()), true, true;
	case *reflect.Int64Value:
		return int64(v.Get()), true, true;
	case *reflect.UintValue:
		return int64(v.Get()), false, true;
	case *reflect.Uint8Value:
		return int64(v.Get()), false, true;
	case *reflect.Uint16Value:
		return int64(v.Get()), false, true;
	case *reflect.Uint32Value:
		return int64(v.Get()), false, true;
	case *reflect.Uint64Value:
		return int64(v.Get()), false, true;
	case *reflect.UintptrValue:
		return int64(v.Get()), false, true;
Rob Pike's avatar
Rob Pike committed
344
	}
345
	return;
Rob Pike's avatar
Rob Pike committed
346 347 348
}

func getString(v reflect.Value) (val string, ok bool) {
349 350 351 352 353
	if v, ok := v.(*reflect.StringValue); ok {
		return v.Get(), true;
	}
	if bytes, ok := v.Interface().([]byte); ok {
		return string(bytes), true;
Rob Pike's avatar
Rob Pike committed
354
	}
355
	return;
Rob Pike's avatar
Rob Pike committed
356 357
}

358
func getFloat32(v reflect.Value) (val float32, ok bool) {
359 360 361 362
	switch v := v.(type) {
	case *reflect.Float32Value:
		return float32(v.Get()), true;
	case *reflect.FloatValue:
363
		if v.Type().Size()*8 == 32 {
364
			return float32(v.Get()), true;
365 366
		}
	}
367
	return;
368 369 370
}

func getFloat64(v reflect.Value) (val float64, ok bool) {
371 372
	switch v := v.(type) {
	case *reflect.FloatValue:
373
		if v.Type().Size()*8 == 64 {
374
			return float64(v.Get()), true;
375
		}
376 377
	case *reflect.Float64Value:
		return float64(v.Get()), true;
Rob Pike's avatar
Rob Pike committed
378
	}
379
	return;
Rob Pike's avatar
Rob Pike committed
380 381
}

382
func getPtr(v reflect.Value) (val uintptr, ok bool) {
383 384 385
	switch v := v.(type) {
	case *reflect.PtrValue:
		return uintptr(v.Get()), true;
386
	}
387
	return;
388 389
}

Rob Pike's avatar
Rob Pike committed
390
// Convert ASCII to integer.  n is 0 (and got is false) if no number present.
Rob Pike's avatar
Rob Pike committed
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405

func parsenum(s string, start, end int) (n int, got bool, newi int) {
	if start >= end {
		return 0, false, end
	}
	isnum := false;
	num := 0;
	for '0' <= s[start] && s[start] <= '9' {
		num = num*10 + int(s[start] - '0');
		start++;
		isnum = true;
	}
	return num, isnum, start;
}

Russ Cox's avatar
Russ Cox committed
406 407 408 409 410
type uintptrGetter interface {
	Get() uintptr;
}

func (p *pp) printField(field reflect.Value, plus, sharp bool, depth int) (was_string bool) {
411 412
	inter := field.Interface();
	if inter != nil {
Russ Cox's avatar
Russ Cox committed
413 414 415 416 417 418 419 420 421 422 423
		switch {
		default:
			if stringer, ok := inter.(Stringer); ok {
				p.addstr(stringer.String());
				return false;	// this value is not a string
			}
		case sharp:
			if stringer, ok := inter.(GoStringer); ok {
				p.addstr(stringer.GoString());
				return false;	// this value is not a string
			}
424
		}
425 426
	}
	s := "";
Russ Cox's avatar
Russ Cox committed
427
BigSwitch:
428 429 430 431 432 433 434 435
	switch f := field.(type) {
	case *reflect.BoolValue:
		s = p.fmt.Fmt_boolean(f.Get()).Str();
	case *reflect.Float32Value:
		s = p.fmt.Fmt_g32(f.Get()).Str();
	case *reflect.Float64Value:
		s = p.fmt.Fmt_g64(f.Get()).Str();
	case *reflect.FloatValue:
436
		if field.Type().Size()*8 == 32 {
437
			s = p.fmt.Fmt_g32(float32(f.Get())).Str();
438
		} else {
439
			s = p.fmt.Fmt_g64(float64(f.Get())).Str();
440
		}
441
	case *reflect.StringValue:
Russ Cox's avatar
Russ Cox committed
442 443 444 445 446
		if sharp {
			s = p.fmt.Fmt_q(f.Get()).Str();
		} else {
			s = p.fmt.Fmt_s(f.Get()).Str();
			was_string = true;
447
		}
Rob Pike's avatar
Rob Pike committed
448
	case *reflect.MapValue:
Russ Cox's avatar
Russ Cox committed
449 450 451 452 453 454
		if sharp {
			p.addstr(field.Type().String());
			p.addstr("{");
		} else {
			p.addstr("map[");
		}
Rob Pike's avatar
Rob Pike committed
455 456 457
		keys := f.Keys();
		for i, key := range keys {
			if i > 0 {
Russ Cox's avatar
Russ Cox committed
458 459 460 461 462
				if sharp {
					p.addstr(", ");
				} else {
					p.addstr(" ");
				}
Rob Pike's avatar
Rob Pike committed
463
			}
Russ Cox's avatar
Russ Cox committed
464
			p.printField(key, plus, sharp, depth+1);
Rob Pike's avatar
Rob Pike committed
465
			p.addstr(":");
Russ Cox's avatar
Russ Cox committed
466 467 468 469 470 471
			p.printField(f.Elem(key), plus, sharp, depth+1);
		}
		if sharp {
			p.addstr("}");
		} else {
			p.addstr("]");
Rob Pike's avatar
Rob Pike committed
472
		}
473
	case *reflect.StructValue:
Russ Cox's avatar
Russ Cox committed
474 475 476
		if sharp {
			p.addstr(field.Type().String());
		}
477
		p.add('{');
478 479
		v := f;
		t := v.Type().(*reflect.StructType);
480
		p.fmt.clearflags();	// clear flags for p.printField
481
		for i := 0; i < v.NumField();  i++ {
482
			if i > 0 {
Russ Cox's avatar
Russ Cox committed
483 484 485 486 487
				if sharp {
					p.addstr(", ");
				} else {
					p.addstr(" ");
				}
488
			}
Russ Cox's avatar
Russ Cox committed
489
			if plus || sharp {
490 491
				if f := t.Field(i); f.Name != "" {
					p.addstr(f.Name);
Rob Pike's avatar
Rob Pike committed
492
					p.add(':');
493 494
				}
			}
Russ Cox's avatar
Russ Cox committed
495
			p.printField(getField(v, i), plus, sharp, depth+1);
496
		}
Russ Cox's avatar
Russ Cox committed
497
		p.addstr("}");
498 499
	case *reflect.InterfaceValue:
		value := f.Elem();
500
		if value == nil {
Russ Cox's avatar
Russ Cox committed
501 502 503 504 505 506
			if sharp {
				p.addstr(field.Type().String());
				p.addstr("(nil)");
			} else {
				s = "<nil>"
			}
507
		} else {
Russ Cox's avatar
Russ Cox committed
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
			return p.printField(value, plus, sharp, depth+1);
		}
	case reflect.ArrayOrSliceValue:
		if sharp {
			p.addstr(field.Type().String());
			p.addstr("{");
		} else {
			p.addstr("[");
		}
		for i := 0; i < f.Len(); i++ {
			if i > 0 {
				if sharp {
					p.addstr(", ");
				} else {
					p.addstr(" ");
				}
			}
			p.printField(f.Elem(i), plus, sharp, depth+1);
		}
		if sharp {
			p.addstr("}");
		} else {
			p.addstr("]");
		}
	case *reflect.PtrValue:
		v := f.Get();
		// pointer to array or slice or struct?  ok at top level
		// but not embedded (avoid loops)
		if v != 0 && depth == 0 {
			switch a := f.Elem().(type) {
			case reflect.ArrayOrSliceValue:
				p.addstr("&");
				p.printField(a, plus, sharp, depth+1);
				break BigSwitch;
			case *reflect.StructValue:
				p.addstr("&");
				p.printField(a, plus, sharp, depth+1);
				break BigSwitch;
			}
		}
		if sharp {
			p.addstr("(");
			p.addstr(field.Type().String());
			p.addstr(")(");
			if v == 0 {
				p.addstr("nil");
			} else {
				p.fmt.sharp = true;
				p.addstr(p.fmt.Fmt_ux64(uint64(v)).Str());
			}
			p.addstr(")");
			break;
		}
		if v == 0 {
			s = "<nil>";
			break;
		}
		p.fmt.sharp = true;  // turn 0x on
		s = p.fmt.Fmt_ux64(uint64(v)).Str();
	case uintptrGetter:
		v := f.Get();
		if sharp {
			p.addstr("(");
			p.addstr(field.Type().String());
			p.addstr(")(");
			if v == 0 {
				p.addstr("nil");
			} else {
				p.fmt.sharp = true;
				p.addstr(p.fmt.Fmt_ux64(uint64(v)).Str());
			}
			p.addstr(")");
		} else {
			p.fmt.sharp = true;  // turn 0x on
			p.addstr(p.fmt.Fmt_ux64(uint64(f.Get())).Str());
583
		}
584
	default:
585 586 587 588 589
		v, signed, ok := getInt(field);
		if ok {
			if signed {
				s = p.fmt.Fmt_d64(v).Str();
			} else {
Russ Cox's avatar
Russ Cox committed
590 591 592 593 594 595
				if sharp {
					p.fmt.sharp = true;	// turn on 0x
					s = p.fmt.Fmt_ux64(uint64(v)).Str();
				} else {
					s = p.fmt.Fmt_ud64(uint64(v)).Str();
				}
596 597 598
			}
			break;
		}
599 600 601 602 603 604
		s = "?" + field.Type().String() + "?";
	}
	p.addstr(s);
	return was_string;
}

605
func (p *pp) doprintf(format string, v *reflect.StructValue) {
Rob Pike's avatar
Rob Pike committed
606 607 608 609
	p.ensure(len(format));	// a good starting size
	end := len(format) - 1;
	fieldnum := 0;	// we process one field per non-trivial format
	for i := 0; i <= end;  {
610
		c, w := utf8.DecodeRuneInString(format[i:len(format)]);
Rob Pike's avatar
Rob Pike committed
611 612 613 614 615
		if c != '%' || i == end {
			p.add(c);
			i += w;
			continue;
		}
616
		i++;
617 618
		// flags and widths
		p.fmt.clearflags();
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
		F: for ; i < end; i++ {
			switch format[i] {
			case '#':
				p.fmt.sharp = true;
			case '0':
				p.fmt.zero = true;
			case '+':
				p.fmt.plus = true;
			case '-':
				p.fmt.minus = true;
			case ' ':
				p.fmt.space = true;
			default:
				break F;
			}
		}
		// do we have 20 (width)?
636
		p.fmt.wid, p.fmt.wid_present, i = parsenum(format, i, end);
637
		// do we have .20 (precision)?
Rob Pike's avatar
Rob Pike committed
638
		if i < end && format[i] == '.' {
639
			p.fmt.prec, p.fmt.prec_present, i = parsenum(format, i+1, end);
Rob Pike's avatar
Rob Pike committed
640
		}
641
		c, w = utf8.DecodeRuneInString(format[i:len(format)]);
Rob Pike's avatar
Rob Pike committed
642 643 644 645 646 647
		i += w;
		// percent is special - absorbs no operand
		if c == '%' {
			p.add('%');	// TODO: should we bother with width & prec?
			continue;
		}
648
		if fieldnum >= v.NumField() {	// out of operands
Rob Pike's avatar
Rob Pike committed
649 650 651
			p.add('%');
			p.add(c);
			p.addstr("(missing)");
Rob Pike's avatar
Rob Pike committed
652 653
			continue;
		}
654
		field := getField(v, fieldnum);
Rob Pike's avatar
Rob Pike committed
655
		fieldnum++;
Russ Cox's avatar
Russ Cox committed
656 657 658

		// Try formatter except for %T,
		// which is special and handled internally.
659
		inter := field.Interface();
Russ Cox's avatar
Russ Cox committed
660
		if inter != nil && c != 'T' {
661
			if formatter, ok := inter.(Formatter); ok {
662 663 664
				formatter.Format(p, c);
				continue;
			}
Rob Pike's avatar
Rob Pike committed
665
		}
Russ Cox's avatar
Russ Cox committed
666

Rob Pike's avatar
Rob Pike committed
667 668
		s := "";
		switch c {
Russ Cox's avatar
Russ Cox committed
669 670 671 672 673
		// bool
		case 't':
			if v, ok := getBool(field); ok {
				if v {
					s = "true";
Rob Pike's avatar
Rob Pike committed
674
				} else {
Russ Cox's avatar
Russ Cox committed
675
					s = "false";
Rob Pike's avatar
Rob Pike committed
676
				}
Russ Cox's avatar
Russ Cox committed
677 678 679
			} else {
				goto badtype;
			}
Rob Pike's avatar
Rob Pike committed
680

Russ Cox's avatar
Russ Cox committed
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
		// int
		case 'b':
			if v, signed, ok := getInt(field); ok {
				s = p.fmt.Fmt_b64(uint64(v)).Str()	// always unsigned
			} else if v, ok := getFloat32(field); ok {
				s = p.fmt.Fmt_fb32(v).Str()
			} else if v, ok := getFloat64(field); ok {
				s = p.fmt.Fmt_fb64(v).Str()
			} else {
				goto badtype
			}
		case 'c':
			if v, signed, ok := getInt(field); ok {
				s = p.fmt.Fmt_c(int(v)).Str()
			} else {
				goto badtype
			}
		case 'd':
			if v, signed, ok := getInt(field); ok {
				if signed {
					s = p.fmt.Fmt_d64(v).Str()
Rob Pike's avatar
Rob Pike committed
702
				} else {
Russ Cox's avatar
Russ Cox committed
703
					s = p.fmt.Fmt_ud64(uint64(v)).Str()
Rob Pike's avatar
Rob Pike committed
704
				}
Russ Cox's avatar
Russ Cox committed
705 706 707 708 709 710 711
			} else {
				goto badtype
			}
		case 'o':
			if v, signed, ok := getInt(field); ok {
				if signed {
					s = p.fmt.Fmt_o64(v).Str()
Rob Pike's avatar
Rob Pike committed
712
				} else {
Russ Cox's avatar
Russ Cox committed
713
					s = p.fmt.Fmt_uo64(uint64(v)).Str()
Rob Pike's avatar
Rob Pike committed
714
				}
Russ Cox's avatar
Russ Cox committed
715 716 717 718 719 720 721
			} else {
				goto badtype
			}
		case 'x':
			if v, signed, ok := getInt(field); ok {
				if signed {
					s = p.fmt.Fmt_x64(v).Str()
722
				} else {
Russ Cox's avatar
Russ Cox committed
723
					s = p.fmt.Fmt_ux64(uint64(v)).Str()
724
				}
Russ Cox's avatar
Russ Cox committed
725 726 727 728 729 730 731 732 733
			} else if v, ok := getString(field); ok {
				s = p.fmt.Fmt_sx(v).Str();
			} else {
				goto badtype
			}
		case 'X':
			if v, signed, ok := getInt(field); ok {
				if signed {
					s = p.fmt.Fmt_X64(v).Str()
Rob Pike's avatar
Rob Pike committed
734
				} else {
Russ Cox's avatar
Russ Cox committed
735
					s = p.fmt.Fmt_uX64(uint64(v)).Str()
Rob Pike's avatar
Rob Pike committed
736
				}
Russ Cox's avatar
Russ Cox committed
737 738 739 740 741
			} else if v, ok := getString(field); ok {
				s = p.fmt.Fmt_sX(v).Str();
			} else {
				goto badtype
			}
Rob Pike's avatar
Rob Pike committed
742

Russ Cox's avatar
Russ Cox committed
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
		// float
		case 'e':
			if v, ok := getFloat32(field); ok {
				s = p.fmt.Fmt_e32(v).Str()
			} else if v, ok := getFloat64(field); ok {
				s = p.fmt.Fmt_e64(v).Str()
			} else {
				goto badtype
			}
		case 'E':
			if v, ok := getFloat32(field); ok {
				s = p.fmt.Fmt_E32(v).Str()
			} else if v, ok := getFloat64(field); ok {
				s = p.fmt.Fmt_E64(v).Str()
			} else {
				goto badtype
			}
		case 'f':
			if v, ok := getFloat32(field); ok {
				s = p.fmt.Fmt_f32(v).Str()
			} else if v, ok := getFloat64(field); ok {
				s = p.fmt.Fmt_f64(v).Str()
			} else {
				goto badtype
			}
		case 'g':
			if v, ok := getFloat32(field); ok {
				s = p.fmt.Fmt_g32(v).Str()
			} else if v, ok := getFloat64(field); ok {
				s = p.fmt.Fmt_g64(v).Str()
			} else {
				goto badtype
			}
		case 'G':
			if v, ok := getFloat32(field); ok {
				s = p.fmt.Fmt_G32(v).Str()
			} else if v, ok := getFloat64(field); ok {
				s = p.fmt.Fmt_G64(v).Str()
			} else {
				goto badtype
			}
Rob Pike's avatar
Rob Pike committed
784

Russ Cox's avatar
Russ Cox committed
785 786 787 788 789 790 791
		// string
		case 's':
			if inter != nil {
				// if object implements String, use the result.
				if stringer, ok := inter.(Stringer); ok {
					s = p.fmt.Fmt_s(stringer.String()).Str();
					break;
792
				}
Russ Cox's avatar
Russ Cox committed
793 794 795 796 797 798 799 800 801 802 803 804
			}
			if v, ok := getString(field); ok {
				s = p.fmt.Fmt_s(v).Str()
			} else {
				goto badtype
			}
		case 'q':
			if v, ok := getString(field); ok {
				s = p.fmt.Fmt_q(v).Str()
			} else {
				goto badtype
			}
Rob Pike's avatar
Rob Pike committed
805

Russ Cox's avatar
Russ Cox committed
806 807 808 809 810
		// pointer
		case 'p':
			if v, ok := getPtr(field); ok {
				if v == 0 {
					s = "<nil>"
Rob Pike's avatar
Rob Pike committed
811
				} else {
Russ Cox's avatar
Russ Cox committed
812
					s = "0x" + p.fmt.Fmt_uX64(uint64(v)).Str()
Rob Pike's avatar
Rob Pike committed
813
				}
Russ Cox's avatar
Russ Cox committed
814 815 816
			} else {
				goto badtype
			}
Rob Pike's avatar
Rob Pike committed
817

Russ Cox's avatar
Russ Cox committed
818 819 820 821 822 823
		// arbitrary value; do your best
		case 'v':
			plus, sharp := p.fmt.plus, p.fmt.sharp;
			p.fmt.plus = false;
			p.fmt.sharp = false;
			p.printField(field, plus, sharp, 0);
824

Russ Cox's avatar
Russ Cox committed
825 826 827
		// the value's type
		case 'T':
			s = field.Type().String();
828

Russ Cox's avatar
Russ Cox committed
829 830 831 832 833 834
		default:
		badtype:
			s = "%" + string(c) + "(" + field.Type().String() + "=";
			p.addstr(s);
			p.printField(field, false, false, 0);
			s = ")";
Rob Pike's avatar
Rob Pike committed
835 836 837
		}
		p.addstr(s);
	}
838
	if fieldnum < v.NumField() {
Rob Pike's avatar
Rob Pike committed
839
		p.addstr("?(extra ");
840
		for ; fieldnum < v.NumField(); fieldnum++ {
841 842 843
			field := getField(v, fieldnum);
			p.addstr(field.Type().String());
			p.addstr("=");
Russ Cox's avatar
Russ Cox committed
844
			p.printField(field, false, false, 0);
845
			if fieldnum + 1 < v.NumField() {
Rob Pike's avatar
Rob Pike committed
846 847 848 849 850
				p.addstr(", ");
			}
		}
		p.addstr(")");
	}
Rob Pike's avatar
Rob Pike committed
851 852
}

853
func (p *pp) doprint(v *reflect.StructValue, addspace, addnewline bool) {
Rob Pike's avatar
Rob Pike committed
854
	prev_string := false;
855
	for fieldnum := 0; fieldnum < v.NumField();  fieldnum++ {
Rob Pike's avatar
Rob Pike committed
856
		// always add spaces if we're doing println
857
		field := getField(v, fieldnum);
Rob Pike's avatar
Rob Pike committed
858
		if fieldnum > 0 {
859 860 861
			_, is_string := field.(*reflect.StringValue);
			if addspace || !is_string && !prev_string {
				p.add(' ');
Rob Pike's avatar
Rob Pike committed
862 863
			}
		}
Russ Cox's avatar
Russ Cox committed
864
		prev_string = p.printField(field, false, false, 0);
Rob Pike's avatar
Rob Pike committed
865
	}
Rob Pike's avatar
Rob Pike committed
866
	if addnewline {
Rob Pike's avatar
Rob Pike committed
867 868 869
		p.add('\n')
	}
}