print.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package fmt
  5. import (
  6. "errors"
  7. "io"
  8. "os"
  9. "reflect"
  10. "sync"
  11. "unicode/utf8"
  12. )
  13. // Some constants in the form of bytes, to avoid string overhead.
  14. // Needlessly fastidious, I suppose.
  15. var (
  16. commaSpaceBytes = []byte(", ")
  17. nilAngleBytes = []byte("<nil>")
  18. nilParenBytes = []byte("(nil)")
  19. nilBytes = []byte("nil")
  20. mapBytes = []byte("map[")
  21. percentBangBytes = []byte("%!")
  22. missingBytes = []byte("(MISSING)")
  23. badIndexBytes = []byte("(BADINDEX)")
  24. panicBytes = []byte("(PANIC=")
  25. extraBytes = []byte("%!(EXTRA ")
  26. irparenBytes = []byte("i)")
  27. bytesBytes = []byte("[]byte{")
  28. badWidthBytes = []byte("%!(BADWIDTH)")
  29. badPrecBytes = []byte("%!(BADPREC)")
  30. noVerbBytes = []byte("%!(NOVERB)")
  31. )
  32. // State represents the printer state passed to custom formatters.
  33. // It provides access to the io.Writer interface plus information about
  34. // the flags and options for the operand's format specifier.
  35. type State interface {
  36. // Write is the function to call to emit formatted output to be printed.
  37. Write(b []byte) (ret int, err error)
  38. // Width returns the value of the width option and whether it has been set.
  39. Width() (wid int, ok bool)
  40. // Precision returns the value of the precision option and whether it has been set.
  41. Precision() (prec int, ok bool)
  42. // Flag reports whether the flag c, a character, has been set.
  43. Flag(c int) bool
  44. }
  45. // Formatter is the interface implemented by values with a custom formatter.
  46. // The implementation of Format may call Sprint(f) or Fprint(f) etc.
  47. // to generate its output.
  48. type Formatter interface {
  49. Format(f State, c rune)
  50. }
  51. // Stringer is implemented by any value that has a String method,
  52. // which defines the ``native'' format for that value.
  53. // The String method is used to print values passed as an operand
  54. // to any format that accepts a string or to an unformatted printer
  55. // such as Print.
  56. type Stringer interface {
  57. String() string
  58. }
  59. // GoStringer is implemented by any value that has a GoString method,
  60. // which defines the Go syntax for that value.
  61. // The GoString method is used to print values passed as an operand
  62. // to a %#v format.
  63. type GoStringer interface {
  64. GoString() string
  65. }
  66. // Use simple []byte instead of bytes.Buffer to avoid large dependency.
  67. type buffer []byte
  68. func (b *buffer) Write(p []byte) (n int, err error) {
  69. *b = append(*b, p...)
  70. return len(p), nil
  71. }
  72. func (b *buffer) WriteString(s string) (n int, err error) {
  73. *b = append(*b, s...)
  74. return len(s), nil
  75. }
  76. func (b *buffer) WriteByte(c byte) error {
  77. *b = append(*b, c)
  78. return nil
  79. }
  80. func (bp *buffer) WriteRune(r rune) error {
  81. if r < utf8.RuneSelf {
  82. *bp = append(*bp, byte(r))
  83. return nil
  84. }
  85. b := *bp
  86. n := len(b)
  87. for n+utf8.UTFMax > cap(b) {
  88. b = append(b, 0)
  89. }
  90. w := utf8.EncodeRune(b[n:n+utf8.UTFMax], r)
  91. *bp = b[:n+w]
  92. return nil
  93. }
  94. type pp struct {
  95. n int
  96. panicking bool
  97. erroring bool // printing an error condition
  98. buf buffer
  99. // arg holds the current item, as an interface{}.
  100. arg interface{}
  101. // value holds the current item, as a reflect.Value, and will be
  102. // the zero Value if the item has not been reflected.
  103. value reflect.Value
  104. // reordered records whether the format string used argument reordering.
  105. reordered bool
  106. // goodArgNum records whether the most recent reordering directive was valid.
  107. goodArgNum bool
  108. runeBuf [utf8.UTFMax]byte
  109. fmt fmt
  110. }
  111. var ppFree = sync.Pool{
  112. New: func() interface{} { return new(pp) },
  113. }
  114. // newPrinter allocates a new pp struct or grabs a cached one.
  115. func newPrinter() *pp {
  116. p := ppFree.Get().(*pp)
  117. p.panicking = false
  118. p.erroring = false
  119. p.fmt.init(&p.buf)
  120. return p
  121. }
  122. // free saves used pp structs in ppFree; avoids an allocation per invocation.
  123. func (p *pp) free() {
  124. // Don't hold on to pp structs with large buffers.
  125. if cap(p.buf) > 1024 {
  126. return
  127. }
  128. p.buf = p.buf[:0]
  129. p.arg = nil
  130. p.value = reflect.Value{}
  131. ppFree.Put(p)
  132. }
  133. func (p *pp) Width() (wid int, ok bool) { return p.fmt.wid, p.fmt.widPresent }
  134. func (p *pp) Precision() (prec int, ok bool) { return p.fmt.prec, p.fmt.precPresent }
  135. func (p *pp) Flag(b int) bool {
  136. switch b {
  137. case '-':
  138. return p.fmt.minus
  139. case '+':
  140. return p.fmt.plus
  141. case '#':
  142. return p.fmt.sharp
  143. case ' ':
  144. return p.fmt.space
  145. case '0':
  146. return p.fmt.zero
  147. }
  148. return false
  149. }
  150. func (p *pp) add(c rune) {
  151. p.buf.WriteRune(c)
  152. }
  153. // Implement Write so we can call Fprintf on a pp (through State), for
  154. // recursive use in custom verbs.
  155. func (p *pp) Write(b []byte) (ret int, err error) {
  156. return p.buf.Write(b)
  157. }
  158. // These routines end in 'f' and take a format string.
  159. // Fprintf formats according to a format specifier and writes to w.
  160. // It returns the number of bytes written and any write error encountered.
  161. func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
  162. p := newPrinter()
  163. p.doPrintf(format, a)
  164. n, err = w.Write(p.buf)
  165. p.free()
  166. return
  167. }
  168. // Printf formats according to a format specifier and writes to standard output.
  169. // It returns the number of bytes written and any write error encountered.
  170. func Printf(format string, a ...interface{}) (n int, err error) {
  171. return Fprintf(os.Stdout, format, a...)
  172. }
  173. // Sprintf formats according to a format specifier and returns the resulting string.
  174. func Sprintf(format string, a ...interface{}) string {
  175. p := newPrinter()
  176. p.doPrintf(format, a)
  177. s := string(p.buf)
  178. p.free()
  179. return s
  180. }
  181. // Errorf formats according to a format specifier and returns the string
  182. // as a value that satisfies error.
  183. func Errorf(format string, a ...interface{}) error {
  184. return errors.New(Sprintf(format, a...))
  185. }
  186. // These routines do not take a format string
  187. // Fprint formats using the default formats for its operands and writes to w.
  188. // Spaces are added between operands when neither is a string.
  189. // It returns the number of bytes written and any write error encountered.
  190. func Fprint(w io.Writer, a ...interface{}) (n int, err error) {
  191. p := newPrinter()
  192. p.doPrint(a, false, false)
  193. n, err = w.Write(p.buf)
  194. p.free()
  195. return
  196. }
  197. // Print formats using the default formats for its operands and writes to standard output.
  198. // Spaces are added between operands when neither is a string.
  199. // It returns the number of bytes written and any write error encountered.
  200. func Print(a ...interface{}) (n int, err error) {
  201. return Fprint(os.Stdout, a...)
  202. }
  203. // Sprint formats using the default formats for its operands and returns the resulting string.
  204. // Spaces are added between operands when neither is a string.
  205. func Sprint(a ...interface{}) string {
  206. p := newPrinter()
  207. p.doPrint(a, false, false)
  208. s := string(p.buf)
  209. p.free()
  210. return s
  211. }
  212. // These routines end in 'ln', do not take a format string,
  213. // always add spaces between operands, and add a newline
  214. // after the last operand.
  215. // Fprintln formats using the default formats for its operands and writes to w.
  216. // Spaces are always added between operands and a newline is appended.
  217. // It returns the number of bytes written and any write error encountered.
  218. func Fprintln(w io.Writer, a ...interface{}) (n int, err error) {
  219. p := newPrinter()
  220. p.doPrint(a, true, true)
  221. n, err = w.Write(p.buf)
  222. p.free()
  223. return
  224. }
  225. // Println formats using the default formats for its operands and writes to standard output.
  226. // Spaces are always added between operands and a newline is appended.
  227. // It returns the number of bytes written and any write error encountered.
  228. func Println(a ...interface{}) (n int, err error) {
  229. return Fprintln(os.Stdout, a...)
  230. }
  231. // Sprintln formats using the default formats for its operands and returns the resulting string.
  232. // Spaces are always added between operands and a newline is appended.
  233. func Sprintln(a ...interface{}) string {
  234. p := newPrinter()
  235. p.doPrint(a, true, true)
  236. s := string(p.buf)
  237. p.free()
  238. return s
  239. }
  240. // getField gets the i'th field of the struct value.
  241. // If the field is itself is an interface, return a value for
  242. // the thing inside the interface, not the interface itself.
  243. func getField(v reflect.Value, i int) reflect.Value {
  244. val := v.Field(i)
  245. if val.Kind() == reflect.Interface && !val.IsNil() {
  246. val = val.Elem()
  247. }
  248. return val
  249. }
  250. // parsenum converts ASCII to integer. num is 0 (and isnum is false) if no number present.
  251. func parsenum(s string, start, end int) (num int, isnum bool, newi int) {
  252. if start >= end {
  253. return 0, false, end
  254. }
  255. for newi = start; newi < end && '0' <= s[newi] && s[newi] <= '9'; newi++ {
  256. num = num*10 + int(s[newi]-'0')
  257. isnum = true
  258. }
  259. return
  260. }
  261. func (p *pp) unknownType(v reflect.Value) {
  262. if !v.IsValid() {
  263. p.buf.Write(nilAngleBytes)
  264. return
  265. }
  266. p.buf.WriteByte('?')
  267. p.buf.WriteString(v.Type().String())
  268. p.buf.WriteByte('?')
  269. }
  270. func (p *pp) badVerb(verb rune) {
  271. p.erroring = true
  272. p.add('%')
  273. p.add('!')
  274. p.add(verb)
  275. p.add('(')
  276. switch {
  277. case p.arg != nil:
  278. p.buf.WriteString(reflect.TypeOf(p.arg).String())
  279. p.add('=')
  280. p.printArg(p.arg, 'v', 0)
  281. case p.value.IsValid():
  282. p.buf.WriteString(p.value.Type().String())
  283. p.add('=')
  284. p.printValue(p.value, 'v', 0)
  285. default:
  286. p.buf.Write(nilAngleBytes)
  287. }
  288. p.add(')')
  289. p.erroring = false
  290. }
  291. func (p *pp) fmtBool(v bool, verb rune) {
  292. switch verb {
  293. case 't', 'v':
  294. p.fmt.fmt_boolean(v)
  295. default:
  296. p.badVerb(verb)
  297. }
  298. }
  299. // fmtC formats a rune for the 'c' format.
  300. func (p *pp) fmtC(c int64) {
  301. r := rune(c) // Check for overflow.
  302. if int64(r) != c {
  303. r = utf8.RuneError
  304. }
  305. w := utf8.EncodeRune(p.runeBuf[0:utf8.UTFMax], r)
  306. p.fmt.pad(p.runeBuf[0:w])
  307. }
  308. func (p *pp) fmtInt64(v int64, verb rune) {
  309. switch verb {
  310. case 'b':
  311. p.fmt.integer(v, 2, signed, ldigits)
  312. case 'c':
  313. p.fmtC(v)
  314. case 'd', 'v':
  315. p.fmt.integer(v, 10, signed, ldigits)
  316. case 'o':
  317. p.fmt.integer(v, 8, signed, ldigits)
  318. case 'q':
  319. if 0 <= v && v <= utf8.MaxRune {
  320. p.fmt.fmt_qc(v)
  321. } else {
  322. p.badVerb(verb)
  323. }
  324. case 'x':
  325. p.fmt.integer(v, 16, signed, ldigits)
  326. case 'U':
  327. p.fmtUnicode(v)
  328. case 'X':
  329. p.fmt.integer(v, 16, signed, udigits)
  330. default:
  331. p.badVerb(verb)
  332. }
  333. }
  334. // fmt0x64 formats a uint64 in hexadecimal and prefixes it with 0x or
  335. // not, as requested, by temporarily setting the sharp flag.
  336. func (p *pp) fmt0x64(v uint64, leading0x bool) {
  337. sharp := p.fmt.sharp
  338. p.fmt.sharp = leading0x
  339. p.fmt.integer(int64(v), 16, unsigned, ldigits)
  340. p.fmt.sharp = sharp
  341. }
  342. // fmtUnicode formats a uint64 in U+1234 form by
  343. // temporarily turning on the unicode flag and tweaking the precision.
  344. func (p *pp) fmtUnicode(v int64) {
  345. precPresent := p.fmt.precPresent
  346. sharp := p.fmt.sharp
  347. p.fmt.sharp = false
  348. prec := p.fmt.prec
  349. if !precPresent {
  350. // If prec is already set, leave it alone; otherwise 4 is minimum.
  351. p.fmt.prec = 4
  352. p.fmt.precPresent = true
  353. }
  354. p.fmt.unicode = true // turn on U+
  355. p.fmt.uniQuote = sharp
  356. p.fmt.integer(int64(v), 16, unsigned, udigits)
  357. p.fmt.unicode = false
  358. p.fmt.uniQuote = false
  359. p.fmt.prec = prec
  360. p.fmt.precPresent = precPresent
  361. p.fmt.sharp = sharp
  362. }
  363. func (p *pp) fmtUint64(v uint64, verb rune) {
  364. switch verb {
  365. case 'b':
  366. p.fmt.integer(int64(v), 2, unsigned, ldigits)
  367. case 'c':
  368. p.fmtC(int64(v))
  369. case 'd':
  370. p.fmt.integer(int64(v), 10, unsigned, ldigits)
  371. case 'v':
  372. if p.fmt.sharpV {
  373. p.fmt0x64(v, true)
  374. } else {
  375. p.fmt.integer(int64(v), 10, unsigned, ldigits)
  376. }
  377. case 'o':
  378. p.fmt.integer(int64(v), 8, unsigned, ldigits)
  379. case 'q':
  380. if 0 <= v && v <= utf8.MaxRune {
  381. p.fmt.fmt_qc(int64(v))
  382. } else {
  383. p.badVerb(verb)
  384. }
  385. case 'x':
  386. p.fmt.integer(int64(v), 16, unsigned, ldigits)
  387. case 'X':
  388. p.fmt.integer(int64(v), 16, unsigned, udigits)
  389. case 'U':
  390. p.fmtUnicode(int64(v))
  391. default:
  392. p.badVerb(verb)
  393. }
  394. }
  395. func (p *pp) fmtFloat32(v float32, verb rune) {
  396. switch verb {
  397. case 'b':
  398. p.fmt.fmt_fb32(v)
  399. case 'e':
  400. p.fmt.fmt_e32(v)
  401. case 'E':
  402. p.fmt.fmt_E32(v)
  403. case 'f', 'F':
  404. p.fmt.fmt_f32(v)
  405. case 'g', 'v':
  406. p.fmt.fmt_g32(v)
  407. case 'G':
  408. p.fmt.fmt_G32(v)
  409. default:
  410. p.badVerb(verb)
  411. }
  412. }
  413. func (p *pp) fmtFloat64(v float64, verb rune) {
  414. switch verb {
  415. case 'b':
  416. p.fmt.fmt_fb64(v)
  417. case 'e':
  418. p.fmt.fmt_e64(v)
  419. case 'E':
  420. p.fmt.fmt_E64(v)
  421. case 'f', 'F':
  422. p.fmt.fmt_f64(v)
  423. case 'g', 'v':
  424. p.fmt.fmt_g64(v)
  425. case 'G':
  426. p.fmt.fmt_G64(v)
  427. default:
  428. p.badVerb(verb)
  429. }
  430. }
  431. func (p *pp) fmtComplex64(v complex64, verb rune) {
  432. switch verb {
  433. case 'b', 'e', 'E', 'f', 'F', 'g', 'G':
  434. p.fmt.fmt_c64(v, verb)
  435. case 'v':
  436. p.fmt.fmt_c64(v, 'g')
  437. default:
  438. p.badVerb(verb)
  439. }
  440. }
  441. func (p *pp) fmtComplex128(v complex128, verb rune) {
  442. switch verb {
  443. case 'b', 'e', 'E', 'f', 'F', 'g', 'G':
  444. p.fmt.fmt_c128(v, verb)
  445. case 'v':
  446. p.fmt.fmt_c128(v, 'g')
  447. default:
  448. p.badVerb(verb)
  449. }
  450. }
  451. func (p *pp) fmtString(v string, verb rune) {
  452. switch verb {
  453. case 'v':
  454. if p.fmt.sharpV {
  455. p.fmt.fmt_q(v)
  456. } else {
  457. p.fmt.fmt_s(v)
  458. }
  459. case 's':
  460. p.fmt.fmt_s(v)
  461. case 'x':
  462. p.fmt.fmt_sx(v, ldigits)
  463. case 'X':
  464. p.fmt.fmt_sx(v, udigits)
  465. case 'q':
  466. p.fmt.fmt_q(v)
  467. default:
  468. p.badVerb(verb)
  469. }
  470. }
  471. func (p *pp) fmtBytes(v []byte, verb rune, typ reflect.Type, depth int) {
  472. if verb == 'v' || verb == 'd' {
  473. if p.fmt.sharpV {
  474. if v == nil {
  475. if typ == nil {
  476. p.buf.WriteString("[]byte(nil)")
  477. } else {
  478. p.buf.WriteString(typ.String())
  479. p.buf.Write(nilParenBytes)
  480. }
  481. return
  482. }
  483. if typ == nil {
  484. p.buf.Write(bytesBytes)
  485. } else {
  486. p.buf.WriteString(typ.String())
  487. p.buf.WriteByte('{')
  488. }
  489. } else {
  490. p.buf.WriteByte('[')
  491. }
  492. for i, c := range v {
  493. if i > 0 {
  494. if p.fmt.sharpV {
  495. p.buf.Write(commaSpaceBytes)
  496. } else {
  497. p.buf.WriteByte(' ')
  498. }
  499. }
  500. p.printArg(c, 'v', depth+1)
  501. }
  502. if p.fmt.sharpV {
  503. p.buf.WriteByte('}')
  504. } else {
  505. p.buf.WriteByte(']')
  506. }
  507. return
  508. }
  509. switch verb {
  510. case 's':
  511. p.fmt.fmt_s(string(v))
  512. case 'x':
  513. p.fmt.fmt_bx(v, ldigits)
  514. case 'X':
  515. p.fmt.fmt_bx(v, udigits)
  516. case 'q':
  517. p.fmt.fmt_q(string(v))
  518. default:
  519. p.badVerb(verb)
  520. }
  521. }
  522. func (p *pp) fmtPointer(value reflect.Value, verb rune) {
  523. use0x64 := true
  524. switch verb {
  525. case 'p', 'v':
  526. // ok
  527. case 'b', 'd', 'o', 'x', 'X':
  528. use0x64 = false
  529. // ok
  530. default:
  531. p.badVerb(verb)
  532. return
  533. }
  534. var u uintptr
  535. switch value.Kind() {
  536. case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer:
  537. u = value.Pointer()
  538. default:
  539. p.badVerb(verb)
  540. return
  541. }
  542. if p.fmt.sharpV {
  543. p.add('(')
  544. p.buf.WriteString(value.Type().String())
  545. p.add(')')
  546. p.add('(')
  547. if u == 0 {
  548. p.buf.Write(nilBytes)
  549. } else {
  550. p.fmt0x64(uint64(u), true)
  551. }
  552. p.add(')')
  553. } else if verb == 'v' && u == 0 {
  554. p.buf.Write(nilAngleBytes)
  555. } else {
  556. if use0x64 {
  557. p.fmt0x64(uint64(u), !p.fmt.sharp)
  558. } else {
  559. p.fmtUint64(uint64(u), verb)
  560. }
  561. }
  562. }
  563. var (
  564. intBits = reflect.TypeOf(0).Bits()
  565. uintptrBits = reflect.TypeOf(uintptr(0)).Bits()
  566. )
  567. func (p *pp) catchPanic(arg interface{}, verb rune) {
  568. if err := recover(); err != nil {
  569. // If it's a nil pointer, just say "<nil>". The likeliest causes are a
  570. // Stringer that fails to guard against nil or a nil pointer for a
  571. // value receiver, and in either case, "<nil>" is a nice result.
  572. if v := reflect.ValueOf(arg); v.Kind() == reflect.Ptr && v.IsNil() {
  573. p.buf.Write(nilAngleBytes)
  574. return
  575. }
  576. // Otherwise print a concise panic message. Most of the time the panic
  577. // value will print itself nicely.
  578. if p.panicking {
  579. // Nested panics; the recursion in printArg cannot succeed.
  580. panic(err)
  581. }
  582. p.fmt.clearflags() // We are done, and for this output we want default behavior.
  583. p.buf.Write(percentBangBytes)
  584. p.add(verb)
  585. p.buf.Write(panicBytes)
  586. p.panicking = true
  587. p.printArg(err, 'v', 0)
  588. p.panicking = false
  589. p.buf.WriteByte(')')
  590. }
  591. }
  592. // clearSpecialFlags pushes %#v back into the regular flags and returns their old state.
  593. func (p *pp) clearSpecialFlags() (plusV, sharpV bool) {
  594. plusV = p.fmt.plusV
  595. if plusV {
  596. p.fmt.plus = true
  597. p.fmt.plusV = false
  598. }
  599. sharpV = p.fmt.sharpV
  600. if sharpV {
  601. p.fmt.sharp = true
  602. p.fmt.sharpV = false
  603. }
  604. return
  605. }
  606. // restoreSpecialFlags, whose argument should be a call to clearSpecialFlags,
  607. // restores the setting of the plusV and sharpV flags.
  608. func (p *pp) restoreSpecialFlags(plusV, sharpV bool) {
  609. if plusV {
  610. p.fmt.plus = false
  611. p.fmt.plusV = true
  612. }
  613. if sharpV {
  614. p.fmt.sharp = false
  615. p.fmt.sharpV = true
  616. }
  617. }
  618. func (p *pp) handleMethods(verb rune, depth int) (handled bool) {
  619. if p.erroring {
  620. return
  621. }
  622. // Is it a Formatter?
  623. if formatter, ok := p.arg.(Formatter); ok {
  624. handled = true
  625. defer p.restoreSpecialFlags(p.clearSpecialFlags())
  626. defer p.catchPanic(p.arg, verb)
  627. formatter.Format(p, verb)
  628. return
  629. }
  630. // If we're doing Go syntax and the argument knows how to supply it, take care of it now.
  631. if p.fmt.sharpV {
  632. if stringer, ok := p.arg.(GoStringer); ok {
  633. handled = true
  634. defer p.catchPanic(p.arg, verb)
  635. // Print the result of GoString unadorned.
  636. p.fmt.fmt_s(stringer.GoString())
  637. return
  638. }
  639. } else {
  640. // If a string is acceptable according to the format, see if
  641. // the value satisfies one of the string-valued interfaces.
  642. // Println etc. set verb to %v, which is "stringable".
  643. switch verb {
  644. case 'v', 's', 'x', 'X', 'q':
  645. // Is it an error or Stringer?
  646. // The duplication in the bodies is necessary:
  647. // setting handled and deferring catchPanic
  648. // must happen before calling the method.
  649. switch v := p.arg.(type) {
  650. case error:
  651. handled = true
  652. defer p.catchPanic(p.arg, verb)
  653. p.printArg(v.Error(), verb, depth)
  654. return
  655. case Stringer:
  656. handled = true
  657. defer p.catchPanic(p.arg, verb)
  658. p.printArg(v.String(), verb, depth)
  659. return
  660. }
  661. }
  662. }
  663. return false
  664. }
  665. func (p *pp) printArg(arg interface{}, verb rune, depth int) (wasString bool) {
  666. p.arg = arg
  667. p.value = reflect.Value{}
  668. if arg == nil {
  669. if verb == 'T' || verb == 'v' {
  670. p.fmt.pad(nilAngleBytes)
  671. } else {
  672. p.badVerb(verb)
  673. }
  674. return false
  675. }
  676. // Special processing considerations.
  677. // %T (the value's type) and %p (its address) are special; we always do them first.
  678. switch verb {
  679. case 'T':
  680. p.printArg(reflect.TypeOf(arg).String(), 's', 0)
  681. return false
  682. case 'p':
  683. p.fmtPointer(reflect.ValueOf(arg), verb)
  684. return false
  685. }
  686. // Some types can be done without reflection.
  687. switch f := arg.(type) {
  688. case bool:
  689. p.fmtBool(f, verb)
  690. case float32:
  691. p.fmtFloat32(f, verb)
  692. case float64:
  693. p.fmtFloat64(f, verb)
  694. case complex64:
  695. p.fmtComplex64(f, verb)
  696. case complex128:
  697. p.fmtComplex128(f, verb)
  698. case int:
  699. p.fmtInt64(int64(f), verb)
  700. case int8:
  701. p.fmtInt64(int64(f), verb)
  702. case int16:
  703. p.fmtInt64(int64(f), verb)
  704. case int32:
  705. p.fmtInt64(int64(f), verb)
  706. case int64:
  707. p.fmtInt64(f, verb)
  708. case uint:
  709. p.fmtUint64(uint64(f), verb)
  710. case uint8:
  711. p.fmtUint64(uint64(f), verb)
  712. case uint16:
  713. p.fmtUint64(uint64(f), verb)
  714. case uint32:
  715. p.fmtUint64(uint64(f), verb)
  716. case uint64:
  717. p.fmtUint64(f, verb)
  718. case uintptr:
  719. p.fmtUint64(uint64(f), verb)
  720. case string:
  721. p.fmtString(f, verb)
  722. wasString = verb == 's' || verb == 'v'
  723. case []byte:
  724. p.fmtBytes(f, verb, nil, depth)
  725. wasString = verb == 's'
  726. default:
  727. // If the type is not simple, it might have methods.
  728. if handled := p.handleMethods(verb, depth); handled {
  729. return false
  730. }
  731. // Need to use reflection
  732. return p.printReflectValue(reflect.ValueOf(arg), verb, depth)
  733. }
  734. p.arg = nil
  735. return
  736. }
  737. // printValue is like printArg but starts with a reflect value, not an interface{} value.
  738. func (p *pp) printValue(value reflect.Value, verb rune, depth int) (wasString bool) {
  739. if !value.IsValid() {
  740. if verb == 'T' || verb == 'v' {
  741. p.buf.Write(nilAngleBytes)
  742. } else {
  743. p.badVerb(verb)
  744. }
  745. return false
  746. }
  747. // Special processing considerations.
  748. // %T (the value's type) and %p (its address) are special; we always do them first.
  749. switch verb {
  750. case 'T':
  751. p.printArg(value.Type().String(), 's', 0)
  752. return false
  753. case 'p':
  754. p.fmtPointer(value, verb)
  755. return false
  756. }
  757. // Handle values with special methods.
  758. // Call always, even when arg == nil, because handleMethods clears p.fmt.plus for us.
  759. p.arg = nil // Make sure it's cleared, for safety.
  760. if value.CanInterface() {
  761. p.arg = value.Interface()
  762. }
  763. if handled := p.handleMethods(verb, depth); handled {
  764. return false
  765. }
  766. return p.printReflectValue(value, verb, depth)
  767. }
  768. var byteType = reflect.TypeOf(byte(0))
  769. // printReflectValue is the fallback for both printArg and printValue.
  770. // It uses reflect to print the value.
  771. func (p *pp) printReflectValue(value reflect.Value, verb rune, depth int) (wasString bool) {
  772. oldValue := p.value
  773. p.value = value
  774. BigSwitch:
  775. switch f := value; f.Kind() {
  776. case reflect.Bool:
  777. p.fmtBool(f.Bool(), verb)
  778. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  779. p.fmtInt64(f.Int(), verb)
  780. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  781. p.fmtUint64(f.Uint(), verb)
  782. case reflect.Float32, reflect.Float64:
  783. if f.Type().Size() == 4 {
  784. p.fmtFloat32(float32(f.Float()), verb)
  785. } else {
  786. p.fmtFloat64(f.Float(), verb)
  787. }
  788. case reflect.Complex64, reflect.Complex128:
  789. if f.Type().Size() == 8 {
  790. p.fmtComplex64(complex64(f.Complex()), verb)
  791. } else {
  792. p.fmtComplex128(f.Complex(), verb)
  793. }
  794. case reflect.String:
  795. p.fmtString(f.String(), verb)
  796. case reflect.Map:
  797. if p.fmt.sharpV {
  798. p.buf.WriteString(f.Type().String())
  799. if f.IsNil() {
  800. p.buf.WriteString("(nil)")
  801. break
  802. }
  803. p.buf.WriteByte('{')
  804. } else {
  805. p.buf.Write(mapBytes)
  806. }
  807. keys := f.MapKeys()
  808. for i, key := range keys {
  809. if i > 0 {
  810. if p.fmt.sharpV {
  811. p.buf.Write(commaSpaceBytes)
  812. } else {
  813. p.buf.WriteByte(' ')
  814. }
  815. }
  816. p.printValue(key, verb, depth+1)
  817. p.buf.WriteByte(':')
  818. p.printValue(f.MapIndex(key), verb, depth+1)
  819. }
  820. if p.fmt.sharpV {
  821. p.buf.WriteByte('}')
  822. } else {
  823. p.buf.WriteByte(']')
  824. }
  825. case reflect.Struct:
  826. if p.fmt.sharpV {
  827. p.buf.WriteString(value.Type().String())
  828. }
  829. p.add('{')
  830. v := f
  831. t := v.Type()
  832. for i := 0; i < v.NumField(); i++ {
  833. if i > 0 {
  834. if p.fmt.sharpV {
  835. p.buf.Write(commaSpaceBytes)
  836. } else {
  837. p.buf.WriteByte(' ')
  838. }
  839. }
  840. if p.fmt.plusV || p.fmt.sharpV {
  841. if f := t.Field(i); f.Name != "" {
  842. p.buf.WriteString(f.Name)
  843. p.buf.WriteByte(':')
  844. }
  845. }
  846. p.printValue(getField(v, i), verb, depth+1)
  847. }
  848. p.buf.WriteByte('}')
  849. case reflect.Interface:
  850. value := f.Elem()
  851. if !value.IsValid() {
  852. if p.fmt.sharpV {
  853. p.buf.WriteString(f.Type().String())
  854. p.buf.Write(nilParenBytes)
  855. } else {
  856. p.buf.Write(nilAngleBytes)
  857. }
  858. } else {
  859. wasString = p.printValue(value, verb, depth+1)
  860. }
  861. case reflect.Array, reflect.Slice:
  862. // Byte slices are special:
  863. // - Handle []byte (== []uint8) with fmtBytes.
  864. // - Handle []T, where T is a named byte type, with fmtBytes only
  865. // for the s, q, an x verbs. For other verbs, T might be a
  866. // Stringer, so we use printValue to print each element.
  867. if typ := f.Type(); typ.Elem().Kind() == reflect.Uint8 && (typ.Elem() == byteType || verb == 's' || verb == 'q' || verb == 'x') {
  868. var bytes []byte
  869. if f.Kind() == reflect.Slice {
  870. bytes = f.Bytes()
  871. } else if f.CanAddr() {
  872. bytes = f.Slice(0, f.Len()).Bytes()
  873. } else {
  874. // We have an array, but we cannot Slice() a non-addressable array,
  875. // so we build a slice by hand. This is a rare case but it would be nice
  876. // if reflection could help a little more.
  877. bytes = make([]byte, f.Len())
  878. for i := range bytes {
  879. bytes[i] = byte(f.Index(i).Uint())
  880. }
  881. }
  882. p.fmtBytes(bytes, verb, typ, depth)
  883. wasString = verb == 's'
  884. break
  885. }
  886. if p.fmt.sharpV {
  887. p.buf.WriteString(value.Type().String())
  888. if f.Kind() == reflect.Slice && f.IsNil() {
  889. p.buf.WriteString("(nil)")
  890. break
  891. }
  892. p.buf.WriteByte('{')
  893. } else {
  894. p.buf.WriteByte('[')
  895. }
  896. for i := 0; i < f.Len(); i++ {
  897. if i > 0 {
  898. if p.fmt.sharpV {
  899. p.buf.Write(commaSpaceBytes)
  900. } else {
  901. p.buf.WriteByte(' ')
  902. }
  903. }
  904. p.printValue(f.Index(i), verb, depth+1)
  905. }
  906. if p.fmt.sharpV {
  907. p.buf.WriteByte('}')
  908. } else {
  909. p.buf.WriteByte(']')
  910. }
  911. case reflect.Ptr:
  912. v := f.Pointer()
  913. // pointer to array or slice or struct? ok at top level
  914. // but not embedded (avoid loops)
  915. if v != 0 && depth == 0 {
  916. switch a := f.Elem(); a.Kind() {
  917. case reflect.Array, reflect.Slice:
  918. p.buf.WriteByte('&')
  919. p.printValue(a, verb, depth+1)
  920. break BigSwitch
  921. case reflect.Struct:
  922. p.buf.WriteByte('&')
  923. p.printValue(a, verb, depth+1)
  924. break BigSwitch
  925. case reflect.Map:
  926. p.buf.WriteByte('&')
  927. p.printValue(a, verb, depth+1)
  928. break BigSwitch
  929. }
  930. }
  931. fallthrough
  932. case reflect.Chan, reflect.Func, reflect.UnsafePointer:
  933. p.fmtPointer(value, verb)
  934. default:
  935. p.unknownType(f)
  936. }
  937. p.value = oldValue
  938. return wasString
  939. }
  940. // intFromArg gets the argNumth element of a. On return, isInt reports whether the argument has type int.
  941. func intFromArg(a []interface{}, argNum int) (num int, isInt bool, newArgNum int) {
  942. newArgNum = argNum
  943. if argNum < len(a) {
  944. num, isInt = a[argNum].(int)
  945. newArgNum = argNum + 1
  946. }
  947. return
  948. }
  949. // parseArgNumber returns the value of the bracketed number, minus 1
  950. // (explicit argument numbers are one-indexed but we want zero-indexed).
  951. // The opening bracket is known to be present at format[0].
  952. // The returned values are the index, the number of bytes to consume
  953. // up to the closing paren, if present, and whether the number parsed
  954. // ok. The bytes to consume will be 1 if no closing paren is present.
  955. func parseArgNumber(format string) (index int, wid int, ok bool) {
  956. // Find closing bracket.
  957. for i := 1; i < len(format); i++ {
  958. if format[i] == ']' {
  959. width, ok, newi := parsenum(format, 1, i)
  960. if !ok || newi != i {
  961. return 0, i + 1, false
  962. }
  963. return width - 1, i + 1, true // arg numbers are one-indexed and skip paren.
  964. }
  965. }
  966. return 0, 1, false
  967. }
  968. // argNumber returns the next argument to evaluate, which is either the value of the passed-in
  969. // argNum or the value of the bracketed integer that begins format[i:]. It also returns
  970. // the new value of i, that is, the index of the next byte of the format to process.
  971. func (p *pp) argNumber(argNum int, format string, i int, numArgs int) (newArgNum, newi int, found bool) {
  972. if len(format) <= i || format[i] != '[' {
  973. return argNum, i, false
  974. }
  975. p.reordered = true
  976. index, wid, ok := parseArgNumber(format[i:])
  977. if ok && 0 <= index && index < numArgs {
  978. return index, i + wid, true
  979. }
  980. p.goodArgNum = false
  981. return argNum, i + wid, true
  982. }
  983. func (p *pp) doPrintf(format string, a []interface{}) {
  984. end := len(format)
  985. argNum := 0 // we process one argument per non-trivial format
  986. afterIndex := false // previous item in format was an index like [3].
  987. p.reordered = false
  988. for i := 0; i < end; {
  989. p.goodArgNum = true
  990. lasti := i
  991. for i < end && format[i] != '%' {
  992. i++
  993. }
  994. if i > lasti {
  995. p.buf.WriteString(format[lasti:i])
  996. }
  997. if i >= end {
  998. // done processing format string
  999. break
  1000. }
  1001. // Process one verb
  1002. i++
  1003. // Do we have flags?
  1004. p.fmt.clearflags()
  1005. F:
  1006. for ; i < end; i++ {
  1007. switch format[i] {
  1008. case '#':
  1009. p.fmt.sharp = true
  1010. case '0':
  1011. p.fmt.zero = true
  1012. case '+':
  1013. p.fmt.plus = true
  1014. case '-':
  1015. p.fmt.minus = true
  1016. case ' ':
  1017. p.fmt.space = true
  1018. default:
  1019. break F
  1020. }
  1021. }
  1022. // Do we have an explicit argument index?
  1023. argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a))
  1024. // Do we have width?
  1025. if i < end && format[i] == '*' {
  1026. i++
  1027. p.fmt.wid, p.fmt.widPresent, argNum = intFromArg(a, argNum)
  1028. if !p.fmt.widPresent {
  1029. p.buf.Write(badWidthBytes)
  1030. }
  1031. afterIndex = false
  1032. } else {
  1033. p.fmt.wid, p.fmt.widPresent, i = parsenum(format, i, end)
  1034. if afterIndex && p.fmt.widPresent { // "%[3]2d"
  1035. p.goodArgNum = false
  1036. }
  1037. }
  1038. // Do we have precision?
  1039. if i+1 < end && format[i] == '.' {
  1040. i++
  1041. if afterIndex { // "%[3].2d"
  1042. p.goodArgNum = false
  1043. }
  1044. argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a))
  1045. if format[i] == '*' {
  1046. i++
  1047. p.fmt.prec, p.fmt.precPresent, argNum = intFromArg(a, argNum)
  1048. if !p.fmt.precPresent {
  1049. p.buf.Write(badPrecBytes)
  1050. }
  1051. afterIndex = false
  1052. } else {
  1053. p.fmt.prec, p.fmt.precPresent, i = parsenum(format, i, end)
  1054. if !p.fmt.precPresent {
  1055. p.fmt.prec = 0
  1056. p.fmt.precPresent = true
  1057. }
  1058. }
  1059. }
  1060. if !afterIndex {
  1061. argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a))
  1062. }
  1063. if i >= end {
  1064. p.buf.Write(noVerbBytes)
  1065. continue
  1066. }
  1067. c, w := utf8.DecodeRuneInString(format[i:])
  1068. i += w
  1069. // percent is special - absorbs no operand
  1070. if c == '%' {
  1071. p.buf.WriteByte('%') // We ignore width and prec.
  1072. continue
  1073. }
  1074. if !p.goodArgNum {
  1075. p.buf.Write(percentBangBytes)
  1076. p.add(c)
  1077. p.buf.Write(badIndexBytes)
  1078. continue
  1079. } else if argNum >= len(a) { // out of operands
  1080. p.buf.Write(percentBangBytes)
  1081. p.add(c)
  1082. p.buf.Write(missingBytes)
  1083. continue
  1084. }
  1085. arg := a[argNum]
  1086. argNum++
  1087. if c == 'v' {
  1088. if p.fmt.sharp {
  1089. // Go syntax. Set the flag in the fmt and clear the sharp flag.
  1090. p.fmt.sharp = false
  1091. p.fmt.sharpV = true
  1092. }
  1093. if p.fmt.plus {
  1094. // Struct-field syntax. Set the flag in the fmt and clear the plus flag.
  1095. p.fmt.plus = false
  1096. p.fmt.plusV = true
  1097. }
  1098. }
  1099. p.printArg(arg, c, 0)
  1100. }
  1101. // Check for extra arguments unless the call accessed the arguments
  1102. // out of order, in which case it's too expensive to detect if they've all
  1103. // been used and arguably OK if they're not.
  1104. if !p.reordered && argNum < len(a) {
  1105. p.buf.Write(extraBytes)
  1106. for ; argNum < len(a); argNum++ {
  1107. arg := a[argNum]
  1108. if arg != nil {
  1109. p.buf.WriteString(reflect.TypeOf(arg).String())
  1110. p.buf.WriteByte('=')
  1111. }
  1112. p.printArg(arg, 'v', 0)
  1113. if argNum+1 < len(a) {
  1114. p.buf.Write(commaSpaceBytes)
  1115. }
  1116. }
  1117. p.buf.WriteByte(')')
  1118. }
  1119. }
  1120. func (p *pp) doPrint(a []interface{}, addspace, addnewline bool) {
  1121. prevString := false
  1122. for argNum := 0; argNum < len(a); argNum++ {
  1123. p.fmt.clearflags()
  1124. // always add spaces if we're doing Println
  1125. arg := a[argNum]
  1126. if argNum > 0 {
  1127. isString := arg != nil && reflect.TypeOf(arg).Kind() == reflect.String
  1128. if addspace || !isString && !prevString {
  1129. p.buf.WriteByte(' ')
  1130. }
  1131. }
  1132. prevString = p.printArg(arg, 'v', 0)
  1133. }
  1134. if addnewline {
  1135. p.buf.WriteByte('\n')
  1136. }
  1137. }