print.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  1. // Copyright 2017 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 message
  5. import (
  6. "bytes"
  7. "fmt" // TODO: consider copying interfaces from package fmt to avoid dependency.
  8. "math"
  9. "reflect"
  10. "sync"
  11. "unicode/utf8"
  12. "golang.org/x/text/internal/format"
  13. "golang.org/x/text/internal/number"
  14. "golang.org/x/text/language"
  15. "golang.org/x/text/message/catalog"
  16. )
  17. // Strings for use with buffer.WriteString.
  18. // This is less overhead than using buffer.Write with byte arrays.
  19. const (
  20. commaSpaceString = ", "
  21. nilAngleString = "<nil>"
  22. nilParenString = "(nil)"
  23. nilString = "nil"
  24. mapString = "map["
  25. percentBangString = "%!"
  26. missingString = "(MISSING)"
  27. badIndexString = "(BADINDEX)"
  28. panicString = "(PANIC="
  29. extraString = "%!(EXTRA "
  30. badWidthString = "%!(BADWIDTH)"
  31. badPrecString = "%!(BADPREC)"
  32. noVerbString = "%!(NOVERB)"
  33. invReflectString = "<invalid reflect.Value>"
  34. )
  35. var printerPool = sync.Pool{
  36. New: func() interface{} { return new(printer) },
  37. }
  38. // newPrinter allocates a new printer struct or grabs a cached one.
  39. func newPrinter(pp *Printer) *printer {
  40. p := printerPool.Get().(*printer)
  41. p.Printer = *pp
  42. // TODO: cache most of the following call.
  43. p.catContext = pp.cat.Context(pp.tag, p)
  44. p.panicking = false
  45. p.erroring = false
  46. p.fmt.init(&p.Buffer)
  47. return p
  48. }
  49. // free saves used printer structs in printerFree; avoids an allocation per invocation.
  50. func (p *printer) free() {
  51. p.Buffer.Reset()
  52. p.arg = nil
  53. p.value = reflect.Value{}
  54. printerPool.Put(p)
  55. }
  56. // printer is used to store a printer's state.
  57. // It implements "golang.org/x/text/internal/format".State.
  58. type printer struct {
  59. Printer
  60. // the context for looking up message translations
  61. catContext *catalog.Context
  62. // buffer for accumulating output.
  63. bytes.Buffer
  64. // arg holds the current item, as an interface{}.
  65. arg interface{}
  66. // value is used instead of arg for reflect values.
  67. value reflect.Value
  68. // fmt is used to format basic items such as integers or strings.
  69. fmt formatInfo
  70. // panicking is set by catchPanic to avoid infinite panic, recover, panic, ... recursion.
  71. panicking bool
  72. // erroring is set when printing an error string to guard against calling handleMethods.
  73. erroring bool
  74. }
  75. // Language implements "golang.org/x/text/internal/format".State.
  76. func (p *printer) Language() language.Tag { return p.tag }
  77. func (p *printer) Width() (wid int, ok bool) { return p.fmt.Width, p.fmt.WidthPresent }
  78. func (p *printer) Precision() (prec int, ok bool) { return p.fmt.Prec, p.fmt.PrecPresent }
  79. func (p *printer) Flag(b int) bool {
  80. switch b {
  81. case '-':
  82. return p.fmt.Minus
  83. case '+':
  84. return p.fmt.Plus || p.fmt.PlusV
  85. case '#':
  86. return p.fmt.Sharp || p.fmt.SharpV
  87. case ' ':
  88. return p.fmt.Space
  89. case '0':
  90. return p.fmt.Zero
  91. }
  92. return false
  93. }
  94. // getField gets the i'th field of the struct value.
  95. // If the field is itself is an interface, return a value for
  96. // the thing inside the interface, not the interface itself.
  97. func getField(v reflect.Value, i int) reflect.Value {
  98. val := v.Field(i)
  99. if val.Kind() == reflect.Interface && !val.IsNil() {
  100. val = val.Elem()
  101. }
  102. return val
  103. }
  104. func (p *printer) unknownType(v reflect.Value) {
  105. if !v.IsValid() {
  106. p.WriteString(nilAngleString)
  107. return
  108. }
  109. p.WriteByte('?')
  110. p.WriteString(v.Type().String())
  111. p.WriteByte('?')
  112. }
  113. func (p *printer) badVerb(verb rune) {
  114. p.erroring = true
  115. p.WriteString(percentBangString)
  116. p.WriteRune(verb)
  117. p.WriteByte('(')
  118. switch {
  119. case p.arg != nil:
  120. p.WriteString(reflect.TypeOf(p.arg).String())
  121. p.WriteByte('=')
  122. p.printArg(p.arg, 'v')
  123. case p.value.IsValid():
  124. p.WriteString(p.value.Type().String())
  125. p.WriteByte('=')
  126. p.printValue(p.value, 'v', 0)
  127. default:
  128. p.WriteString(nilAngleString)
  129. }
  130. p.WriteByte(')')
  131. p.erroring = false
  132. }
  133. func (p *printer) fmtBool(v bool, verb rune) {
  134. switch verb {
  135. case 't', 'v':
  136. p.fmt.fmt_boolean(v)
  137. default:
  138. p.badVerb(verb)
  139. }
  140. }
  141. // fmt0x64 formats a uint64 in hexadecimal and prefixes it with 0x or
  142. // not, as requested, by temporarily setting the sharp flag.
  143. func (p *printer) fmt0x64(v uint64, leading0x bool) {
  144. sharp := p.fmt.Sharp
  145. p.fmt.Sharp = leading0x
  146. p.fmt.fmt_integer(v, 16, unsigned, ldigits)
  147. p.fmt.Sharp = sharp
  148. }
  149. // fmtInteger formats a signed or unsigned integer.
  150. func (p *printer) fmtInteger(v uint64, isSigned bool, verb rune) {
  151. switch verb {
  152. case 'v':
  153. if p.fmt.SharpV && !isSigned {
  154. p.fmt0x64(v, true)
  155. return
  156. }
  157. fallthrough
  158. case 'd':
  159. if p.fmt.Sharp || p.fmt.SharpV {
  160. p.fmt.fmt_integer(v, 10, isSigned, ldigits)
  161. } else {
  162. p.fmtDecimalInt(v, isSigned)
  163. }
  164. case 'b':
  165. p.fmt.fmt_integer(v, 2, isSigned, ldigits)
  166. case 'o':
  167. p.fmt.fmt_integer(v, 8, isSigned, ldigits)
  168. case 'x':
  169. p.fmt.fmt_integer(v, 16, isSigned, ldigits)
  170. case 'X':
  171. p.fmt.fmt_integer(v, 16, isSigned, udigits)
  172. case 'c':
  173. p.fmt.fmt_c(v)
  174. case 'q':
  175. if v <= utf8.MaxRune {
  176. p.fmt.fmt_qc(v)
  177. } else {
  178. p.badVerb(verb)
  179. }
  180. case 'U':
  181. p.fmt.fmt_unicode(v)
  182. default:
  183. p.badVerb(verb)
  184. }
  185. }
  186. // fmtFloat formats a float. The default precision for each verb
  187. // is specified as last argument in the call to fmt_float.
  188. func (p *printer) fmtFloat(v float64, size int, verb rune) {
  189. switch verb {
  190. case 'b':
  191. p.fmt.fmt_float(v, size, verb, -1)
  192. case 'v':
  193. verb = 'g'
  194. fallthrough
  195. case 'g', 'G':
  196. if p.fmt.Sharp || p.fmt.SharpV {
  197. p.fmt.fmt_float(v, size, verb, -1)
  198. } else {
  199. p.fmtVariableFloat(v, size)
  200. }
  201. case 'e', 'E':
  202. if p.fmt.Sharp || p.fmt.SharpV {
  203. p.fmt.fmt_float(v, size, verb, 6)
  204. } else {
  205. p.fmtScientific(v, size, 6)
  206. }
  207. case 'f', 'F':
  208. if p.fmt.Sharp || p.fmt.SharpV {
  209. p.fmt.fmt_float(v, size, verb, 6)
  210. } else {
  211. p.fmtDecimalFloat(v, size, 6)
  212. }
  213. default:
  214. p.badVerb(verb)
  215. }
  216. }
  217. func (p *printer) setFlags(f *number.Formatter) {
  218. f.Flags &^= number.ElideSign
  219. if p.fmt.Plus || p.fmt.Space {
  220. f.Flags |= number.AlwaysSign
  221. if !p.fmt.Plus {
  222. f.Flags |= number.ElideSign
  223. }
  224. } else {
  225. f.Flags &^= number.AlwaysSign
  226. }
  227. }
  228. func (p *printer) updatePadding(f *number.Formatter) {
  229. f.Flags &^= number.PadMask
  230. if p.fmt.Minus {
  231. f.Flags |= number.PadAfterSuffix
  232. } else {
  233. f.Flags |= number.PadBeforePrefix
  234. }
  235. f.PadRune = ' '
  236. f.FormatWidth = uint16(p.fmt.Width)
  237. }
  238. func (p *printer) initDecimal(minFrac, maxFrac int) {
  239. f := &p.toDecimal
  240. f.MinIntegerDigits = 1
  241. f.MaxIntegerDigits = 0
  242. f.MinFractionDigits = uint8(minFrac)
  243. f.MaxFractionDigits = int16(maxFrac)
  244. p.setFlags(f)
  245. f.PadRune = 0
  246. if p.fmt.WidthPresent {
  247. if p.fmt.Zero {
  248. wid := p.fmt.Width
  249. // Use significant integers for this.
  250. // TODO: this is not the same as width, but so be it.
  251. if f.MinFractionDigits > 0 {
  252. wid -= 1 + int(f.MinFractionDigits)
  253. }
  254. if p.fmt.Plus || p.fmt.Space {
  255. wid--
  256. }
  257. if wid > 0 && wid > int(f.MinIntegerDigits) {
  258. f.MinIntegerDigits = uint8(wid)
  259. }
  260. }
  261. p.updatePadding(f)
  262. }
  263. }
  264. func (p *printer) initScientific(minFrac, maxFrac int) {
  265. f := &p.toScientific
  266. if maxFrac < 0 {
  267. f.SetPrecision(maxFrac)
  268. } else {
  269. f.SetPrecision(maxFrac + 1)
  270. f.MinFractionDigits = uint8(minFrac)
  271. f.MaxFractionDigits = int16(maxFrac)
  272. }
  273. f.MinExponentDigits = 2
  274. p.setFlags(f)
  275. f.PadRune = 0
  276. if p.fmt.WidthPresent {
  277. f.Flags &^= number.PadMask
  278. if p.fmt.Zero {
  279. f.PadRune = f.Digit(0)
  280. f.Flags |= number.PadAfterPrefix
  281. } else {
  282. f.PadRune = ' '
  283. f.Flags |= number.PadBeforePrefix
  284. }
  285. p.updatePadding(f)
  286. }
  287. }
  288. func (p *printer) fmtDecimalInt(v uint64, isSigned bool) {
  289. var d number.Decimal
  290. f := &p.toDecimal
  291. if p.fmt.PrecPresent {
  292. p.setFlags(f)
  293. f.MinIntegerDigits = uint8(p.fmt.Prec)
  294. f.MaxIntegerDigits = 0
  295. f.MinFractionDigits = 0
  296. f.MaxFractionDigits = 0
  297. if p.fmt.WidthPresent {
  298. p.updatePadding(f)
  299. }
  300. } else {
  301. p.initDecimal(0, 0)
  302. }
  303. d.ConvertInt(p.toDecimal.RoundingContext, isSigned, v)
  304. out := p.toDecimal.Format([]byte(nil), &d)
  305. p.Buffer.Write(out)
  306. }
  307. func (p *printer) fmtDecimalFloat(v float64, size, prec int) {
  308. var d number.Decimal
  309. if p.fmt.PrecPresent {
  310. prec = p.fmt.Prec
  311. }
  312. p.initDecimal(prec, prec)
  313. d.ConvertFloat(p.toDecimal.RoundingContext, v, size)
  314. out := p.toDecimal.Format([]byte(nil), &d)
  315. p.Buffer.Write(out)
  316. }
  317. func (p *printer) fmtVariableFloat(v float64, size int) {
  318. prec := -1
  319. if p.fmt.PrecPresent {
  320. prec = p.fmt.Prec
  321. }
  322. var d number.Decimal
  323. p.initScientific(0, prec)
  324. d.ConvertFloat(p.toScientific.RoundingContext, v, size)
  325. // Copy logic of 'g' formatting from strconv. It is simplified a bit as
  326. // we don't have to mind having prec > len(d.Digits).
  327. shortest := prec < 0
  328. ePrec := prec
  329. if shortest {
  330. prec = len(d.Digits)
  331. ePrec = 6
  332. } else if prec == 0 {
  333. prec = 1
  334. ePrec = 1
  335. }
  336. exp := int(d.Exp) - 1
  337. if exp < -4 || exp >= ePrec {
  338. p.initScientific(0, prec)
  339. out := p.toScientific.Format([]byte(nil), &d)
  340. p.Buffer.Write(out)
  341. } else {
  342. if prec > int(d.Exp) {
  343. prec = len(d.Digits)
  344. }
  345. if prec -= int(d.Exp); prec < 0 {
  346. prec = 0
  347. }
  348. p.initDecimal(0, prec)
  349. out := p.toDecimal.Format([]byte(nil), &d)
  350. p.Buffer.Write(out)
  351. }
  352. }
  353. func (p *printer) fmtScientific(v float64, size, prec int) {
  354. var d number.Decimal
  355. if p.fmt.PrecPresent {
  356. prec = p.fmt.Prec
  357. }
  358. p.initScientific(prec, prec)
  359. rc := p.toScientific.RoundingContext
  360. d.ConvertFloat(rc, v, size)
  361. out := p.toScientific.Format([]byte(nil), &d)
  362. p.Buffer.Write(out)
  363. }
  364. // fmtComplex formats a complex number v with
  365. // r = real(v) and j = imag(v) as (r+ji) using
  366. // fmtFloat for r and j formatting.
  367. func (p *printer) fmtComplex(v complex128, size int, verb rune) {
  368. // Make sure any unsupported verbs are found before the
  369. // calls to fmtFloat to not generate an incorrect error string.
  370. switch verb {
  371. case 'v', 'b', 'g', 'G', 'f', 'F', 'e', 'E':
  372. p.WriteByte('(')
  373. p.fmtFloat(real(v), size/2, verb)
  374. // Imaginary part always has a sign.
  375. if math.IsNaN(imag(v)) {
  376. // By CLDR's rules, NaNs do not use patterns or signs. As this code
  377. // relies on AlwaysSign working for imaginary parts, we need to
  378. // manually handle NaNs.
  379. f := &p.toScientific
  380. p.setFlags(f)
  381. p.updatePadding(f)
  382. p.setFlags(f)
  383. nan := f.Symbol(number.SymNan)
  384. extra := 0
  385. if w, ok := p.Width(); ok {
  386. extra = w - utf8.RuneCountInString(nan) - 1
  387. }
  388. if f.Flags&number.PadAfterNumber == 0 {
  389. for ; extra > 0; extra-- {
  390. p.WriteRune(f.PadRune)
  391. }
  392. }
  393. p.WriteString(f.Symbol(number.SymPlusSign))
  394. p.WriteString(nan)
  395. for ; extra > 0; extra-- {
  396. p.WriteRune(f.PadRune)
  397. }
  398. p.WriteString("i)")
  399. return
  400. }
  401. oldPlus := p.fmt.Plus
  402. p.fmt.Plus = true
  403. p.fmtFloat(imag(v), size/2, verb)
  404. p.WriteString("i)") // TODO: use symbol?
  405. p.fmt.Plus = oldPlus
  406. default:
  407. p.badVerb(verb)
  408. }
  409. }
  410. func (p *printer) fmtString(v string, verb rune) {
  411. switch verb {
  412. case 'v':
  413. if p.fmt.SharpV {
  414. p.fmt.fmt_q(v)
  415. } else {
  416. p.fmt.fmt_s(v)
  417. }
  418. case 's':
  419. p.fmt.fmt_s(v)
  420. case 'x':
  421. p.fmt.fmt_sx(v, ldigits)
  422. case 'X':
  423. p.fmt.fmt_sx(v, udigits)
  424. case 'q':
  425. p.fmt.fmt_q(v)
  426. case 'm':
  427. ctx := p.cat.Context(p.tag, rawPrinter{p})
  428. if ctx.Execute(v) == catalog.ErrNotFound {
  429. p.WriteString(v)
  430. }
  431. default:
  432. p.badVerb(verb)
  433. }
  434. }
  435. func (p *printer) fmtBytes(v []byte, verb rune, typeString string) {
  436. switch verb {
  437. case 'v', 'd':
  438. if p.fmt.SharpV {
  439. p.WriteString(typeString)
  440. if v == nil {
  441. p.WriteString(nilParenString)
  442. return
  443. }
  444. p.WriteByte('{')
  445. for i, c := range v {
  446. if i > 0 {
  447. p.WriteString(commaSpaceString)
  448. }
  449. p.fmt0x64(uint64(c), true)
  450. }
  451. p.WriteByte('}')
  452. } else {
  453. p.WriteByte('[')
  454. for i, c := range v {
  455. if i > 0 {
  456. p.WriteByte(' ')
  457. }
  458. p.fmt.fmt_integer(uint64(c), 10, unsigned, ldigits)
  459. }
  460. p.WriteByte(']')
  461. }
  462. case 's':
  463. p.fmt.fmt_s(string(v))
  464. case 'x':
  465. p.fmt.fmt_bx(v, ldigits)
  466. case 'X':
  467. p.fmt.fmt_bx(v, udigits)
  468. case 'q':
  469. p.fmt.fmt_q(string(v))
  470. default:
  471. p.printValue(reflect.ValueOf(v), verb, 0)
  472. }
  473. }
  474. func (p *printer) fmtPointer(value reflect.Value, verb rune) {
  475. var u uintptr
  476. switch value.Kind() {
  477. case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer:
  478. u = value.Pointer()
  479. default:
  480. p.badVerb(verb)
  481. return
  482. }
  483. switch verb {
  484. case 'v':
  485. if p.fmt.SharpV {
  486. p.WriteByte('(')
  487. p.WriteString(value.Type().String())
  488. p.WriteString(")(")
  489. if u == 0 {
  490. p.WriteString(nilString)
  491. } else {
  492. p.fmt0x64(uint64(u), true)
  493. }
  494. p.WriteByte(')')
  495. } else {
  496. if u == 0 {
  497. p.fmt.padString(nilAngleString)
  498. } else {
  499. p.fmt0x64(uint64(u), !p.fmt.Sharp)
  500. }
  501. }
  502. case 'p':
  503. p.fmt0x64(uint64(u), !p.fmt.Sharp)
  504. case 'b', 'o', 'd', 'x', 'X':
  505. if verb == 'd' {
  506. p.fmt.Sharp = true // Print as standard go. TODO: does this make sense?
  507. }
  508. p.fmtInteger(uint64(u), unsigned, verb)
  509. default:
  510. p.badVerb(verb)
  511. }
  512. }
  513. func (p *printer) catchPanic(arg interface{}, verb rune) {
  514. if err := recover(); err != nil {
  515. // If it's a nil pointer, just say "<nil>". The likeliest causes are a
  516. // Stringer that fails to guard against nil or a nil pointer for a
  517. // value receiver, and in either case, "<nil>" is a nice result.
  518. if v := reflect.ValueOf(arg); v.Kind() == reflect.Ptr && v.IsNil() {
  519. p.WriteString(nilAngleString)
  520. return
  521. }
  522. // Otherwise print a concise panic message. Most of the time the panic
  523. // value will print itself nicely.
  524. if p.panicking {
  525. // Nested panics; the recursion in printArg cannot succeed.
  526. panic(err)
  527. }
  528. oldFlags := p.fmt.Parser
  529. // For this output we want default behavior.
  530. p.fmt.ClearFlags()
  531. p.WriteString(percentBangString)
  532. p.WriteRune(verb)
  533. p.WriteString(panicString)
  534. p.panicking = true
  535. p.printArg(err, 'v')
  536. p.panicking = false
  537. p.WriteByte(')')
  538. p.fmt.Parser = oldFlags
  539. }
  540. }
  541. func (p *printer) handleMethods(verb rune) (handled bool) {
  542. if p.erroring {
  543. return
  544. }
  545. // Is it a Formatter?
  546. if formatter, ok := p.arg.(format.Formatter); ok {
  547. handled = true
  548. defer p.catchPanic(p.arg, verb)
  549. formatter.Format(p, verb)
  550. return
  551. }
  552. if formatter, ok := p.arg.(fmt.Formatter); ok {
  553. handled = true
  554. defer p.catchPanic(p.arg, verb)
  555. formatter.Format(p, verb)
  556. return
  557. }
  558. // If we're doing Go syntax and the argument knows how to supply it, take care of it now.
  559. if p.fmt.SharpV {
  560. if stringer, ok := p.arg.(fmt.GoStringer); ok {
  561. handled = true
  562. defer p.catchPanic(p.arg, verb)
  563. // Print the result of GoString unadorned.
  564. p.fmt.fmt_s(stringer.GoString())
  565. return
  566. }
  567. } else {
  568. // If a string is acceptable according to the format, see if
  569. // the value satisfies one of the string-valued interfaces.
  570. // Println etc. set verb to %v, which is "stringable".
  571. switch verb {
  572. case 'v', 's', 'x', 'X', 'q':
  573. // Is it an error or Stringer?
  574. // The duplication in the bodies is necessary:
  575. // setting handled and deferring catchPanic
  576. // must happen before calling the method.
  577. switch v := p.arg.(type) {
  578. case error:
  579. handled = true
  580. defer p.catchPanic(p.arg, verb)
  581. p.fmtString(v.Error(), verb)
  582. return
  583. case fmt.Stringer:
  584. handled = true
  585. defer p.catchPanic(p.arg, verb)
  586. p.fmtString(v.String(), verb)
  587. return
  588. }
  589. }
  590. }
  591. return false
  592. }
  593. func (p *printer) printArg(arg interface{}, verb rune) {
  594. p.arg = arg
  595. p.value = reflect.Value{}
  596. if arg == nil {
  597. switch verb {
  598. case 'T', 'v':
  599. p.fmt.padString(nilAngleString)
  600. default:
  601. p.badVerb(verb)
  602. }
  603. return
  604. }
  605. // Special processing considerations.
  606. // %T (the value's type) and %p (its address) are special; we always do them first.
  607. switch verb {
  608. case 'T':
  609. p.fmt.fmt_s(reflect.TypeOf(arg).String())
  610. return
  611. case 'p':
  612. p.fmtPointer(reflect.ValueOf(arg), 'p')
  613. return
  614. }
  615. // Some types can be done without reflection.
  616. switch f := arg.(type) {
  617. case bool:
  618. p.fmtBool(f, verb)
  619. case float32:
  620. p.fmtFloat(float64(f), 32, verb)
  621. case float64:
  622. p.fmtFloat(f, 64, verb)
  623. case complex64:
  624. p.fmtComplex(complex128(f), 64, verb)
  625. case complex128:
  626. p.fmtComplex(f, 128, verb)
  627. case int:
  628. p.fmtInteger(uint64(f), signed, verb)
  629. case int8:
  630. p.fmtInteger(uint64(f), signed, verb)
  631. case int16:
  632. p.fmtInteger(uint64(f), signed, verb)
  633. case int32:
  634. p.fmtInteger(uint64(f), signed, verb)
  635. case int64:
  636. p.fmtInteger(uint64(f), signed, verb)
  637. case uint:
  638. p.fmtInteger(uint64(f), unsigned, verb)
  639. case uint8:
  640. p.fmtInteger(uint64(f), unsigned, verb)
  641. case uint16:
  642. p.fmtInteger(uint64(f), unsigned, verb)
  643. case uint32:
  644. p.fmtInteger(uint64(f), unsigned, verb)
  645. case uint64:
  646. p.fmtInteger(f, unsigned, verb)
  647. case uintptr:
  648. p.fmtInteger(uint64(f), unsigned, verb)
  649. case string:
  650. p.fmtString(f, verb)
  651. case []byte:
  652. p.fmtBytes(f, verb, "[]byte")
  653. case reflect.Value:
  654. // Handle extractable values with special methods
  655. // since printValue does not handle them at depth 0.
  656. if f.IsValid() && f.CanInterface() {
  657. p.arg = f.Interface()
  658. if p.handleMethods(verb) {
  659. return
  660. }
  661. }
  662. p.printValue(f, verb, 0)
  663. default:
  664. // If the type is not simple, it might have methods.
  665. if !p.handleMethods(verb) {
  666. // Need to use reflection, since the type had no
  667. // interface methods that could be used for formatting.
  668. p.printValue(reflect.ValueOf(f), verb, 0)
  669. }
  670. }
  671. }
  672. // printValue is similar to printArg but starts with a reflect value, not an interface{} value.
  673. // It does not handle 'p' and 'T' verbs because these should have been already handled by printArg.
  674. func (p *printer) printValue(value reflect.Value, verb rune, depth int) {
  675. // Handle values with special methods if not already handled by printArg (depth == 0).
  676. if depth > 0 && value.IsValid() && value.CanInterface() {
  677. p.arg = value.Interface()
  678. if p.handleMethods(verb) {
  679. return
  680. }
  681. }
  682. p.arg = nil
  683. p.value = value
  684. switch f := value; value.Kind() {
  685. case reflect.Invalid:
  686. if depth == 0 {
  687. p.WriteString(invReflectString)
  688. } else {
  689. switch verb {
  690. case 'v':
  691. p.WriteString(nilAngleString)
  692. default:
  693. p.badVerb(verb)
  694. }
  695. }
  696. case reflect.Bool:
  697. p.fmtBool(f.Bool(), verb)
  698. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  699. p.fmtInteger(uint64(f.Int()), signed, verb)
  700. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  701. p.fmtInteger(f.Uint(), unsigned, verb)
  702. case reflect.Float32:
  703. p.fmtFloat(f.Float(), 32, verb)
  704. case reflect.Float64:
  705. p.fmtFloat(f.Float(), 64, verb)
  706. case reflect.Complex64:
  707. p.fmtComplex(f.Complex(), 64, verb)
  708. case reflect.Complex128:
  709. p.fmtComplex(f.Complex(), 128, verb)
  710. case reflect.String:
  711. p.fmtString(f.String(), verb)
  712. case reflect.Map:
  713. if p.fmt.SharpV {
  714. p.WriteString(f.Type().String())
  715. if f.IsNil() {
  716. p.WriteString(nilParenString)
  717. return
  718. }
  719. p.WriteByte('{')
  720. } else {
  721. p.WriteString(mapString)
  722. }
  723. keys := f.MapKeys()
  724. for i, key := range keys {
  725. if i > 0 {
  726. if p.fmt.SharpV {
  727. p.WriteString(commaSpaceString)
  728. } else {
  729. p.WriteByte(' ')
  730. }
  731. }
  732. p.printValue(key, verb, depth+1)
  733. p.WriteByte(':')
  734. p.printValue(f.MapIndex(key), verb, depth+1)
  735. }
  736. if p.fmt.SharpV {
  737. p.WriteByte('}')
  738. } else {
  739. p.WriteByte(']')
  740. }
  741. case reflect.Struct:
  742. if p.fmt.SharpV {
  743. p.WriteString(f.Type().String())
  744. }
  745. p.WriteByte('{')
  746. for i := 0; i < f.NumField(); i++ {
  747. if i > 0 {
  748. if p.fmt.SharpV {
  749. p.WriteString(commaSpaceString)
  750. } else {
  751. p.WriteByte(' ')
  752. }
  753. }
  754. if p.fmt.PlusV || p.fmt.SharpV {
  755. if name := f.Type().Field(i).Name; name != "" {
  756. p.WriteString(name)
  757. p.WriteByte(':')
  758. }
  759. }
  760. p.printValue(getField(f, i), verb, depth+1)
  761. }
  762. p.WriteByte('}')
  763. case reflect.Interface:
  764. value := f.Elem()
  765. if !value.IsValid() {
  766. if p.fmt.SharpV {
  767. p.WriteString(f.Type().String())
  768. p.WriteString(nilParenString)
  769. } else {
  770. p.WriteString(nilAngleString)
  771. }
  772. } else {
  773. p.printValue(value, verb, depth+1)
  774. }
  775. case reflect.Array, reflect.Slice:
  776. switch verb {
  777. case 's', 'q', 'x', 'X':
  778. // Handle byte and uint8 slices and arrays special for the above verbs.
  779. t := f.Type()
  780. if t.Elem().Kind() == reflect.Uint8 {
  781. var bytes []byte
  782. if f.Kind() == reflect.Slice {
  783. bytes = f.Bytes()
  784. } else if f.CanAddr() {
  785. bytes = f.Slice(0, f.Len()).Bytes()
  786. } else {
  787. // We have an array, but we cannot Slice() a non-addressable array,
  788. // so we build a slice by hand. This is a rare case but it would be nice
  789. // if reflection could help a little more.
  790. bytes = make([]byte, f.Len())
  791. for i := range bytes {
  792. bytes[i] = byte(f.Index(i).Uint())
  793. }
  794. }
  795. p.fmtBytes(bytes, verb, t.String())
  796. return
  797. }
  798. }
  799. if p.fmt.SharpV {
  800. p.WriteString(f.Type().String())
  801. if f.Kind() == reflect.Slice && f.IsNil() {
  802. p.WriteString(nilParenString)
  803. return
  804. }
  805. p.WriteByte('{')
  806. for i := 0; i < f.Len(); i++ {
  807. if i > 0 {
  808. p.WriteString(commaSpaceString)
  809. }
  810. p.printValue(f.Index(i), verb, depth+1)
  811. }
  812. p.WriteByte('}')
  813. } else {
  814. p.WriteByte('[')
  815. for i := 0; i < f.Len(); i++ {
  816. if i > 0 {
  817. p.WriteByte(' ')
  818. }
  819. p.printValue(f.Index(i), verb, depth+1)
  820. }
  821. p.WriteByte(']')
  822. }
  823. case reflect.Ptr:
  824. // pointer to array or slice or struct? ok at top level
  825. // but not embedded (avoid loops)
  826. if depth == 0 && f.Pointer() != 0 {
  827. switch a := f.Elem(); a.Kind() {
  828. case reflect.Array, reflect.Slice, reflect.Struct, reflect.Map:
  829. p.WriteByte('&')
  830. p.printValue(a, verb, depth+1)
  831. return
  832. }
  833. }
  834. fallthrough
  835. case reflect.Chan, reflect.Func, reflect.UnsafePointer:
  836. p.fmtPointer(f, verb)
  837. default:
  838. p.unknownType(f)
  839. }
  840. }
  841. func (p *printer) badArgNum(verb rune) {
  842. p.WriteString(percentBangString)
  843. p.WriteRune(verb)
  844. p.WriteString(badIndexString)
  845. }
  846. func (p *printer) missingArg(verb rune) {
  847. p.WriteString(percentBangString)
  848. p.WriteRune(verb)
  849. p.WriteString(missingString)
  850. }
  851. func (p *printer) doPrintf(fmt string) {
  852. for p.fmt.Parser.SetFormat(fmt); p.fmt.Scan(); {
  853. switch p.fmt.Status {
  854. case format.StatusText:
  855. p.WriteString(p.fmt.Text())
  856. case format.StatusSubstitution:
  857. p.printArg(p.Arg(p.fmt.ArgNum), p.fmt.Verb)
  858. case format.StatusBadWidthSubstitution:
  859. p.WriteString(badWidthString)
  860. p.printArg(p.Arg(p.fmt.ArgNum), p.fmt.Verb)
  861. case format.StatusBadPrecSubstitution:
  862. p.WriteString(badPrecString)
  863. p.printArg(p.Arg(p.fmt.ArgNum), p.fmt.Verb)
  864. case format.StatusNoVerb:
  865. p.WriteString(noVerbString)
  866. case format.StatusBadArgNum:
  867. p.badArgNum(p.fmt.Verb)
  868. case format.StatusMissingArg:
  869. p.missingArg(p.fmt.Verb)
  870. default:
  871. panic("unreachable")
  872. }
  873. }
  874. // Check for extra arguments, but only if there was at least one ordered
  875. // argument. Note that this behavior is necessarily different from fmt:
  876. // different variants of messages may opt to drop some or all of the
  877. // arguments.
  878. if !p.fmt.Reordered && p.fmt.ArgNum < len(p.fmt.Args) && p.fmt.ArgNum != 0 {
  879. p.fmt.ClearFlags()
  880. p.WriteString(extraString)
  881. for i, arg := range p.fmt.Args[p.fmt.ArgNum:] {
  882. if i > 0 {
  883. p.WriteString(commaSpaceString)
  884. }
  885. if arg == nil {
  886. p.WriteString(nilAngleString)
  887. } else {
  888. p.WriteString(reflect.TypeOf(arg).String())
  889. p.WriteString("=")
  890. p.printArg(arg, 'v')
  891. }
  892. }
  893. p.WriteByte(')')
  894. }
  895. }
  896. func (p *printer) doPrint(a []interface{}) {
  897. prevString := false
  898. for argNum, arg := range a {
  899. isString := arg != nil && reflect.TypeOf(arg).Kind() == reflect.String
  900. // Add a space between two non-string arguments.
  901. if argNum > 0 && !isString && !prevString {
  902. p.WriteByte(' ')
  903. }
  904. p.printArg(arg, 'v')
  905. prevString = isString
  906. }
  907. }
  908. // doPrintln is like doPrint but always adds a space between arguments
  909. // and a newline after the last argument.
  910. func (p *printer) doPrintln(a []interface{}) {
  911. for argNum, arg := range a {
  912. if argNum > 0 {
  913. p.WriteByte(' ')
  914. }
  915. p.printArg(arg, 'v')
  916. }
  917. p.WriteByte('\n')
  918. }