decode.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  1. //
  2. // Copyright (c) 2011-2019 Canonical Ltd
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. package yaml
  16. import (
  17. "encoding"
  18. "encoding/base64"
  19. "fmt"
  20. "io"
  21. "math"
  22. "reflect"
  23. "strconv"
  24. "time"
  25. "google.golang.org/protobuf/types/known/durationpb"
  26. )
  27. // ----------------------------------------------------------------------------
  28. // Parser, produces a node tree out of a libyaml event stream.
  29. type parser struct {
  30. parser yaml_parser_t
  31. event yaml_event_t
  32. doc *Node
  33. anchors map[string]*Node
  34. doneInit bool
  35. textless bool
  36. }
  37. func newParser(b []byte) *parser {
  38. p := parser{}
  39. if !yaml_parser_initialize(&p.parser) {
  40. panic("failed to initialize YAML emitter")
  41. }
  42. if len(b) == 0 {
  43. b = []byte{'\n'}
  44. }
  45. yaml_parser_set_input_string(&p.parser, b)
  46. return &p
  47. }
  48. func newParserFromReader(r io.Reader) *parser {
  49. p := parser{}
  50. if !yaml_parser_initialize(&p.parser) {
  51. panic("failed to initialize YAML emitter")
  52. }
  53. yaml_parser_set_input_reader(&p.parser, r)
  54. return &p
  55. }
  56. func (p *parser) init() {
  57. if p.doneInit {
  58. return
  59. }
  60. p.anchors = make(map[string]*Node)
  61. p.expect(yaml_STREAM_START_EVENT)
  62. p.doneInit = true
  63. }
  64. func (p *parser) destroy() {
  65. if p.event.typ != yaml_NO_EVENT {
  66. yaml_event_delete(&p.event)
  67. }
  68. yaml_parser_delete(&p.parser)
  69. }
  70. // expect consumes an event from the event stream and
  71. // checks that it's of the expected type.
  72. func (p *parser) expect(e yaml_event_type_t) {
  73. if p.event.typ == yaml_NO_EVENT {
  74. if !yaml_parser_parse(&p.parser, &p.event) {
  75. p.fail()
  76. }
  77. }
  78. if p.event.typ == yaml_STREAM_END_EVENT {
  79. failf("attempted to go past the end of stream; corrupted value?")
  80. }
  81. if p.event.typ != e {
  82. p.parser.problem = fmt.Sprintf("expected %s event but got %s", e, p.event.typ)
  83. p.fail()
  84. }
  85. yaml_event_delete(&p.event)
  86. p.event.typ = yaml_NO_EVENT
  87. }
  88. // peek peeks at the next event in the event stream,
  89. // puts the results into p.event and returns the event type.
  90. func (p *parser) peek() yaml_event_type_t {
  91. if p.event.typ != yaml_NO_EVENT {
  92. return p.event.typ
  93. }
  94. if !yaml_parser_parse(&p.parser, &p.event) {
  95. p.fail()
  96. }
  97. return p.event.typ
  98. }
  99. func (p *parser) fail() {
  100. var where string
  101. var line int
  102. if p.parser.context_mark.line != 0 {
  103. line = p.parser.context_mark.line
  104. // Scanner errors don't iterate line before returning error
  105. if p.parser.error == yaml_SCANNER_ERROR {
  106. line++
  107. }
  108. } else if p.parser.problem_mark.line != 0 {
  109. line = p.parser.problem_mark.line
  110. // Scanner errors don't iterate line before returning error
  111. if p.parser.error == yaml_SCANNER_ERROR {
  112. line++
  113. }
  114. }
  115. if line != 0 {
  116. where = "line " + strconv.Itoa(line) + ": "
  117. }
  118. var msg string
  119. if len(p.parser.problem) > 0 {
  120. msg = p.parser.problem
  121. } else {
  122. msg = "unknown problem parsing YAML content"
  123. }
  124. failf("%s%s", where, msg)
  125. }
  126. func (p *parser) anchor(n *Node, anchor []byte) {
  127. if anchor != nil {
  128. n.Anchor = string(anchor)
  129. p.anchors[n.Anchor] = n
  130. }
  131. }
  132. func (p *parser) parse() *Node {
  133. p.init()
  134. switch p.peek() {
  135. case yaml_SCALAR_EVENT:
  136. return p.scalar()
  137. case yaml_ALIAS_EVENT:
  138. return p.alias()
  139. case yaml_MAPPING_START_EVENT:
  140. return p.mapping()
  141. case yaml_SEQUENCE_START_EVENT:
  142. return p.sequence()
  143. case yaml_DOCUMENT_START_EVENT:
  144. return p.document()
  145. case yaml_STREAM_END_EVENT:
  146. // Happens when attempting to decode an empty buffer.
  147. return nil
  148. case yaml_TAIL_COMMENT_EVENT:
  149. panic("internal error: unexpected tail comment event (please report)")
  150. default:
  151. panic("internal error: attempted to parse unknown event (please report): " + p.event.typ.String())
  152. }
  153. }
  154. func (p *parser) node(kind Kind, defaultTag, tag, value string) *Node {
  155. var style Style
  156. if tag != "" && tag != "!" {
  157. tag = shortTag(tag)
  158. style = TaggedStyle
  159. } else if defaultTag != "" {
  160. tag = defaultTag
  161. } else if kind == ScalarNode {
  162. tag, _ = resolve("", value)
  163. }
  164. n := &Node{
  165. Kind: kind,
  166. Tag: tag,
  167. Value: value,
  168. Style: style,
  169. }
  170. if !p.textless {
  171. n.Line = p.event.start_mark.line + 1
  172. n.Column = p.event.start_mark.column + 1
  173. n.HeadComment = string(p.event.head_comment)
  174. n.LineComment = string(p.event.line_comment)
  175. n.FootComment = string(p.event.foot_comment)
  176. }
  177. return n
  178. }
  179. func (p *parser) parseChild(parent *Node) *Node {
  180. child := p.parse()
  181. parent.Content = append(parent.Content, child)
  182. return child
  183. }
  184. func (p *parser) document() *Node {
  185. n := p.node(DocumentNode, "", "", "")
  186. p.doc = n
  187. p.expect(yaml_DOCUMENT_START_EVENT)
  188. p.parseChild(n)
  189. if p.peek() == yaml_DOCUMENT_END_EVENT {
  190. n.FootComment = string(p.event.foot_comment)
  191. }
  192. p.expect(yaml_DOCUMENT_END_EVENT)
  193. return n
  194. }
  195. func (p *parser) alias() *Node {
  196. n := p.node(AliasNode, "", "", string(p.event.anchor))
  197. n.Alias = p.anchors[n.Value]
  198. if n.Alias == nil {
  199. failf("unknown anchor '%s' referenced", n.Value)
  200. }
  201. p.expect(yaml_ALIAS_EVENT)
  202. return n
  203. }
  204. func (p *parser) scalar() *Node {
  205. var parsedStyle = p.event.scalar_style()
  206. var nodeStyle Style
  207. switch {
  208. case parsedStyle&yaml_DOUBLE_QUOTED_SCALAR_STYLE != 0:
  209. nodeStyle = DoubleQuotedStyle
  210. case parsedStyle&yaml_SINGLE_QUOTED_SCALAR_STYLE != 0:
  211. nodeStyle = SingleQuotedStyle
  212. case parsedStyle&yaml_LITERAL_SCALAR_STYLE != 0:
  213. nodeStyle = LiteralStyle
  214. case parsedStyle&yaml_FOLDED_SCALAR_STYLE != 0:
  215. nodeStyle = FoldedStyle
  216. }
  217. var nodeValue = string(p.event.value)
  218. var nodeTag = string(p.event.tag)
  219. var defaultTag string
  220. if nodeStyle == 0 {
  221. if nodeValue == "<<" {
  222. defaultTag = mergeTag
  223. }
  224. } else {
  225. defaultTag = strTag
  226. }
  227. n := p.node(ScalarNode, defaultTag, nodeTag, nodeValue)
  228. n.Style |= nodeStyle
  229. p.anchor(n, p.event.anchor)
  230. p.expect(yaml_SCALAR_EVENT)
  231. return n
  232. }
  233. func (p *parser) sequence() *Node {
  234. n := p.node(SequenceNode, seqTag, string(p.event.tag), "")
  235. if p.event.sequence_style()&yaml_FLOW_SEQUENCE_STYLE != 0 {
  236. n.Style |= FlowStyle
  237. }
  238. p.anchor(n, p.event.anchor)
  239. p.expect(yaml_SEQUENCE_START_EVENT)
  240. for p.peek() != yaml_SEQUENCE_END_EVENT {
  241. p.parseChild(n)
  242. }
  243. n.LineComment = string(p.event.line_comment)
  244. n.FootComment = string(p.event.foot_comment)
  245. p.expect(yaml_SEQUENCE_END_EVENT)
  246. return n
  247. }
  248. func (p *parser) mapping() *Node {
  249. n := p.node(MappingNode, mapTag, string(p.event.tag), "")
  250. block := true
  251. if p.event.mapping_style()&yaml_FLOW_MAPPING_STYLE != 0 {
  252. block = false
  253. n.Style |= FlowStyle
  254. }
  255. p.anchor(n, p.event.anchor)
  256. p.expect(yaml_MAPPING_START_EVENT)
  257. for p.peek() != yaml_MAPPING_END_EVENT {
  258. k := p.parseChild(n)
  259. if block && k.FootComment != "" {
  260. // Must be a foot comment for the prior value when being dedented.
  261. if len(n.Content) > 2 {
  262. n.Content[len(n.Content)-3].FootComment = k.FootComment
  263. k.FootComment = ""
  264. }
  265. }
  266. v := p.parseChild(n)
  267. if k.FootComment == "" && v.FootComment != "" {
  268. k.FootComment = v.FootComment
  269. v.FootComment = ""
  270. }
  271. if p.peek() == yaml_TAIL_COMMENT_EVENT {
  272. if k.FootComment == "" {
  273. k.FootComment = string(p.event.foot_comment)
  274. }
  275. p.expect(yaml_TAIL_COMMENT_EVENT)
  276. }
  277. }
  278. n.LineComment = string(p.event.line_comment)
  279. n.FootComment = string(p.event.foot_comment)
  280. if n.Style&FlowStyle == 0 && n.FootComment != "" && len(n.Content) > 1 {
  281. n.Content[len(n.Content)-2].FootComment = n.FootComment
  282. n.FootComment = ""
  283. }
  284. p.expect(yaml_MAPPING_END_EVENT)
  285. return n
  286. }
  287. // ----------------------------------------------------------------------------
  288. // Decoder, unmarshals a node into a provided value.
  289. type decoder struct {
  290. doc *Node
  291. aliases map[*Node]bool
  292. terrors []string
  293. stringMapType reflect.Type
  294. generalMapType reflect.Type
  295. knownFields bool
  296. uniqueKeys bool
  297. decodeCount int
  298. aliasCount int
  299. aliasDepth int
  300. }
  301. var (
  302. nodeType = reflect.TypeOf(Node{})
  303. durationType = reflect.TypeOf(time.Duration(0))
  304. protoDurationType = reflect.TypeOf(durationpb.Duration{})
  305. stringMapType = reflect.TypeOf(map[string]interface{}{})
  306. generalMapType = reflect.TypeOf(map[interface{}]interface{}{})
  307. ifaceType = generalMapType.Elem()
  308. timeType = reflect.TypeOf(time.Time{})
  309. ptrTimeType = reflect.TypeOf(&time.Time{})
  310. )
  311. func newDecoder() *decoder {
  312. d := &decoder{
  313. stringMapType: stringMapType,
  314. generalMapType: generalMapType,
  315. uniqueKeys: true,
  316. }
  317. d.aliases = make(map[*Node]bool)
  318. return d
  319. }
  320. func (d *decoder) terror(n *Node, tag string, out reflect.Value) {
  321. if n.Tag != "" {
  322. tag = n.Tag
  323. }
  324. value := n.Value
  325. if tag != seqTag && tag != mapTag {
  326. if len(value) > 10 {
  327. value = " `" + value[:7] + "...`"
  328. } else {
  329. value = " `" + value + "`"
  330. }
  331. }
  332. d.terrors = append(d.terrors, fmt.Sprintf("line %d: cannot unmarshal %s%s into %s", n.Line, shortTag(tag), value, out.Type()))
  333. }
  334. func (d *decoder) callUnmarshaler(n *Node, u Unmarshaler) (good bool) {
  335. err := u.UnmarshalYAML(n)
  336. if e, ok := err.(*TypeError); ok {
  337. d.terrors = append(d.terrors, e.Errors...)
  338. return false
  339. }
  340. if err != nil {
  341. fail(err)
  342. }
  343. return true
  344. }
  345. func (d *decoder) callObsoleteUnmarshaler(n *Node, u obsoleteUnmarshaler) (good bool) {
  346. terrlen := len(d.terrors)
  347. err := u.UnmarshalYAML(func(v interface{}) (err error) {
  348. defer handleErr(&err)
  349. d.unmarshal(n, reflect.ValueOf(v))
  350. if len(d.terrors) > terrlen {
  351. issues := d.terrors[terrlen:]
  352. d.terrors = d.terrors[:terrlen]
  353. return &TypeError{issues}
  354. }
  355. return nil
  356. })
  357. if e, ok := err.(*TypeError); ok {
  358. d.terrors = append(d.terrors, e.Errors...)
  359. return false
  360. }
  361. if err != nil {
  362. fail(err)
  363. }
  364. return true
  365. }
  366. // d.prepare initializes and dereferences pointers and calls UnmarshalYAML
  367. // if a value is found to implement it.
  368. // It returns the initialized and dereferenced out value, whether
  369. // unmarshalling was already done by UnmarshalYAML, and if so whether
  370. // its types unmarshalled appropriately.
  371. //
  372. // If n holds a null value, prepare returns before doing anything.
  373. func (d *decoder) prepare(n *Node, out reflect.Value) (newout reflect.Value, unmarshaled, good bool) {
  374. if n.ShortTag() == nullTag {
  375. return out, false, false
  376. }
  377. again := true
  378. for again {
  379. again = false
  380. if out.Kind() == reflect.Ptr {
  381. if out.IsNil() {
  382. out.Set(reflect.New(out.Type().Elem()))
  383. }
  384. out = out.Elem()
  385. again = true
  386. }
  387. if out.CanAddr() {
  388. outi := out.Addr().Interface()
  389. if u, ok := outi.(Unmarshaler); ok {
  390. good = d.callUnmarshaler(n, u)
  391. return out, true, good
  392. }
  393. if u, ok := outi.(obsoleteUnmarshaler); ok {
  394. good = d.callObsoleteUnmarshaler(n, u)
  395. return out, true, good
  396. }
  397. }
  398. }
  399. return out, false, false
  400. }
  401. func (d *decoder) fieldByIndex(n *Node, v reflect.Value, index []int) (field reflect.Value) {
  402. if n.ShortTag() == nullTag {
  403. return reflect.Value{}
  404. }
  405. for _, num := range index {
  406. for {
  407. if v.Kind() == reflect.Ptr {
  408. if v.IsNil() {
  409. v.Set(reflect.New(v.Type().Elem()))
  410. }
  411. v = v.Elem()
  412. continue
  413. }
  414. break
  415. }
  416. v = v.Field(num)
  417. }
  418. return v
  419. }
  420. const (
  421. // 400,000 decode operations is ~500kb of dense object declarations, or
  422. // ~5kb of dense object declarations with 10000% alias expansion
  423. alias_ratio_range_low = 400000
  424. // 4,000,000 decode operations is ~5MB of dense object declarations, or
  425. // ~4.5MB of dense object declarations with 10% alias expansion
  426. alias_ratio_range_high = 4000000
  427. // alias_ratio_range is the range over which we scale allowed alias ratios
  428. alias_ratio_range = float64(alias_ratio_range_high - alias_ratio_range_low)
  429. )
  430. func allowedAliasRatio(decodeCount int) float64 {
  431. switch {
  432. case decodeCount <= alias_ratio_range_low:
  433. // allow 99% to come from alias expansion for small-to-medium documents
  434. return 0.99
  435. case decodeCount >= alias_ratio_range_high:
  436. // allow 10% to come from alias expansion for very large documents
  437. return 0.10
  438. default:
  439. // scale smoothly from 99% down to 10% over the range.
  440. // this maps to 396,000 - 400,000 allowed alias-driven decodes over the range.
  441. // 400,000 decode operations is ~100MB of allocations in worst-case scenarios (single-item maps).
  442. return 0.99 - 0.89*(float64(decodeCount-alias_ratio_range_low)/alias_ratio_range)
  443. }
  444. }
  445. func (d *decoder) unmarshal(n *Node, out reflect.Value) (good bool) {
  446. d.decodeCount++
  447. if d.aliasDepth > 0 {
  448. d.aliasCount++
  449. }
  450. if d.aliasCount > 100 && d.decodeCount > 1000 && float64(d.aliasCount)/float64(d.decodeCount) > allowedAliasRatio(d.decodeCount) {
  451. failf("document contains excessive aliasing")
  452. }
  453. if out.Type() == nodeType {
  454. out.Set(reflect.ValueOf(n).Elem())
  455. return true
  456. }
  457. switch n.Kind {
  458. case DocumentNode:
  459. return d.document(n, out)
  460. case AliasNode:
  461. return d.alias(n, out)
  462. }
  463. out, unmarshaled, good := d.prepare(n, out)
  464. if unmarshaled {
  465. return good
  466. }
  467. switch n.Kind {
  468. case ScalarNode:
  469. good = d.scalar(n, out)
  470. case MappingNode:
  471. good = d.mapping(n, out)
  472. case SequenceNode:
  473. good = d.sequence(n, out)
  474. case 0:
  475. if n.IsZero() {
  476. return d.null(out)
  477. }
  478. fallthrough
  479. default:
  480. failf("cannot decode node with unknown kind %d", n.Kind)
  481. }
  482. return good
  483. }
  484. func (d *decoder) document(n *Node, out reflect.Value) (good bool) {
  485. if len(n.Content) == 1 {
  486. d.doc = n
  487. d.unmarshal(n.Content[0], out)
  488. return true
  489. }
  490. return false
  491. }
  492. func (d *decoder) alias(n *Node, out reflect.Value) (good bool) {
  493. if d.aliases[n] {
  494. // TODO this could actually be allowed in some circumstances.
  495. failf("anchor '%s' value contains itself", n.Value)
  496. }
  497. d.aliases[n] = true
  498. d.aliasDepth++
  499. good = d.unmarshal(n.Alias, out)
  500. d.aliasDepth--
  501. delete(d.aliases, n)
  502. return good
  503. }
  504. var zeroValue reflect.Value
  505. func resetMap(out reflect.Value) {
  506. for _, k := range out.MapKeys() {
  507. out.SetMapIndex(k, zeroValue)
  508. }
  509. }
  510. func (d *decoder) null(out reflect.Value) bool {
  511. if out.CanAddr() {
  512. switch out.Kind() {
  513. case reflect.Interface, reflect.Ptr, reflect.Map, reflect.Slice:
  514. out.Set(reflect.Zero(out.Type()))
  515. return true
  516. }
  517. }
  518. return false
  519. }
  520. func (d *decoder) scalar(n *Node, out reflect.Value) bool {
  521. var tag string
  522. var resolved interface{}
  523. if n.indicatedString() {
  524. tag = strTag
  525. resolved = n.Value
  526. } else {
  527. tag, resolved = resolve(n.Tag, n.Value)
  528. if tag == binaryTag {
  529. data, err := base64.StdEncoding.DecodeString(resolved.(string))
  530. if err != nil {
  531. failf("!!binary value contains invalid base64 data")
  532. }
  533. resolved = string(data)
  534. }
  535. }
  536. if resolved == nil {
  537. return d.null(out)
  538. }
  539. if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() {
  540. // We've resolved to exactly the type we want, so use that.
  541. out.Set(resolvedv)
  542. return true
  543. }
  544. // Perhaps we can use the value as a TextUnmarshaler to
  545. // set its value.
  546. if out.CanAddr() {
  547. u, ok := out.Addr().Interface().(encoding.TextUnmarshaler)
  548. if ok {
  549. var text []byte
  550. if tag == binaryTag {
  551. text = []byte(resolved.(string))
  552. } else {
  553. // We let any value be unmarshaled into TextUnmarshaler.
  554. // That might be more lax than we'd like, but the
  555. // TextUnmarshaler itself should bowl out any dubious values.
  556. text = []byte(n.Value)
  557. }
  558. err := u.UnmarshalText(text)
  559. if err != nil {
  560. fail(err)
  561. }
  562. return true
  563. }
  564. }
  565. switch out.Kind() {
  566. case reflect.String:
  567. if tag == binaryTag {
  568. out.SetString(resolved.(string))
  569. return true
  570. }
  571. out.SetString(n.Value)
  572. return true
  573. case reflect.Interface:
  574. out.Set(reflect.ValueOf(resolved))
  575. return true
  576. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  577. // This used to work in v2, but it's very unfriendly.
  578. isDuration := out.Type() == durationType
  579. switch resolved := resolved.(type) {
  580. case int:
  581. if !isDuration && !out.OverflowInt(int64(resolved)) {
  582. out.SetInt(int64(resolved))
  583. return true
  584. }
  585. case int64:
  586. if !isDuration && !out.OverflowInt(resolved) {
  587. out.SetInt(resolved)
  588. return true
  589. }
  590. case uint64:
  591. if !isDuration && resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) {
  592. out.SetInt(int64(resolved))
  593. return true
  594. }
  595. case float64:
  596. if !isDuration && resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) {
  597. out.SetInt(int64(resolved))
  598. return true
  599. }
  600. case string:
  601. if out.Type() == durationType {
  602. d, err := time.ParseDuration(resolved)
  603. if err == nil {
  604. out.SetInt(int64(d))
  605. return true
  606. }
  607. } else if out.Type() == protoDurationType {
  608. d, err := time.ParseDuration(resolved)
  609. if err == nil {
  610. out.SetInt(int64(d))
  611. return true
  612. }
  613. }
  614. }
  615. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  616. switch resolved := resolved.(type) {
  617. case int:
  618. if resolved >= 0 && !out.OverflowUint(uint64(resolved)) {
  619. out.SetUint(uint64(resolved))
  620. return true
  621. }
  622. case int64:
  623. if resolved >= 0 && !out.OverflowUint(uint64(resolved)) {
  624. out.SetUint(uint64(resolved))
  625. return true
  626. }
  627. case uint64:
  628. if !out.OverflowUint(resolved) {
  629. out.SetUint(resolved)
  630. return true
  631. }
  632. case float64:
  633. if resolved <= math.MaxUint64 && !out.OverflowUint(uint64(resolved)) {
  634. out.SetUint(uint64(resolved))
  635. return true
  636. }
  637. }
  638. case reflect.Bool:
  639. switch resolved := resolved.(type) {
  640. case bool:
  641. out.SetBool(resolved)
  642. return true
  643. case string:
  644. // This offers some compatibility with the 1.1 spec (https://yaml.org/type/bool.html).
  645. // It only works if explicitly attempting to unmarshal into a typed bool value.
  646. switch resolved {
  647. case "y", "Y", "yes", "Yes", "YES", "on", "On", "ON":
  648. out.SetBool(true)
  649. return true
  650. case "n", "N", "no", "No", "NO", "off", "Off", "OFF":
  651. out.SetBool(false)
  652. return true
  653. }
  654. }
  655. case reflect.Float32, reflect.Float64:
  656. switch resolved := resolved.(type) {
  657. case int:
  658. out.SetFloat(float64(resolved))
  659. return true
  660. case int64:
  661. out.SetFloat(float64(resolved))
  662. return true
  663. case uint64:
  664. out.SetFloat(float64(resolved))
  665. return true
  666. case float64:
  667. out.SetFloat(resolved)
  668. return true
  669. }
  670. case reflect.Struct:
  671. if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() {
  672. out.Set(resolvedv)
  673. return true
  674. }
  675. if out.Type() == protoDurationType {
  676. switch resolved := resolved.(type) {
  677. case int:
  678. if !out.OverflowInt(int64(resolved)) {
  679. out.Set(reflect.ValueOf(*durationpb.New(time.Duration(int64(resolved)))))
  680. return true
  681. }
  682. case int64:
  683. if !out.OverflowInt(resolved) {
  684. out.Set(reflect.ValueOf(*durationpb.New(time.Duration(resolved))))
  685. return true
  686. }
  687. case uint64:
  688. if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) {
  689. out.Set(reflect.ValueOf(*durationpb.New(time.Duration(int64(resolved)))))
  690. return true
  691. }
  692. case float64:
  693. if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) {
  694. out.Set(reflect.ValueOf(*durationpb.New(time.Duration(int64(resolved)))))
  695. return true
  696. }
  697. case string:
  698. d, err := time.ParseDuration(resolved)
  699. if err == nil {
  700. out.Set(reflect.ValueOf(*durationpb.New(d)))
  701. return true
  702. }
  703. }
  704. }
  705. case reflect.Ptr:
  706. panic("yaml internal error: please report the issue")
  707. }
  708. d.terror(n, tag, out)
  709. return false
  710. }
  711. func settableValueOf(i interface{}) reflect.Value {
  712. v := reflect.ValueOf(i)
  713. sv := reflect.New(v.Type()).Elem()
  714. sv.Set(v)
  715. return sv
  716. }
  717. func (d *decoder) sequence(n *Node, out reflect.Value) (good bool) {
  718. l := len(n.Content)
  719. var iface reflect.Value
  720. switch out.Kind() {
  721. case reflect.Slice:
  722. out.Set(reflect.MakeSlice(out.Type(), l, l))
  723. case reflect.Array:
  724. if l != out.Len() {
  725. failf("invalid array: want %d elements but got %d", out.Len(), l)
  726. }
  727. case reflect.Interface:
  728. // No type hints. Will have to use a generic sequence.
  729. iface = out
  730. out = settableValueOf(make([]interface{}, l))
  731. default:
  732. d.terror(n, seqTag, out)
  733. return false
  734. }
  735. et := out.Type().Elem()
  736. j := 0
  737. for i := 0; i < l; i++ {
  738. e := reflect.New(et).Elem()
  739. if ok := d.unmarshal(n.Content[i], e); ok {
  740. out.Index(j).Set(e)
  741. j++
  742. }
  743. }
  744. if out.Kind() != reflect.Array {
  745. out.Set(out.Slice(0, j))
  746. }
  747. if iface.IsValid() {
  748. iface.Set(out)
  749. }
  750. return true
  751. }
  752. func (d *decoder) mapping(n *Node, out reflect.Value) (good bool) {
  753. l := len(n.Content)
  754. if d.uniqueKeys {
  755. nerrs := len(d.terrors)
  756. for i := 0; i < l; i += 2 {
  757. ni := n.Content[i]
  758. for j := i + 2; j < l; j += 2 {
  759. nj := n.Content[j]
  760. if ni.Kind == nj.Kind && ni.Value == nj.Value {
  761. d.terrors = append(d.terrors, fmt.Sprintf("line %d: mapping key %#v already defined at line %d", nj.Line, nj.Value, ni.Line))
  762. }
  763. }
  764. }
  765. if len(d.terrors) > nerrs {
  766. return false
  767. }
  768. }
  769. switch out.Kind() {
  770. case reflect.Struct:
  771. return d.mappingStruct(n, out)
  772. case reflect.Map:
  773. // okay
  774. case reflect.Interface:
  775. iface := out
  776. if isStringMap(n) {
  777. out = reflect.MakeMap(d.stringMapType)
  778. } else {
  779. out = reflect.MakeMap(d.generalMapType)
  780. }
  781. iface.Set(out)
  782. default:
  783. d.terror(n, mapTag, out)
  784. return false
  785. }
  786. outt := out.Type()
  787. kt := outt.Key()
  788. et := outt.Elem()
  789. stringMapType := d.stringMapType
  790. generalMapType := d.generalMapType
  791. if outt.Elem() == ifaceType {
  792. if outt.Key().Kind() == reflect.String {
  793. d.stringMapType = outt
  794. } else if outt.Key() == ifaceType {
  795. d.generalMapType = outt
  796. }
  797. }
  798. mapIsNew := false
  799. if out.IsNil() {
  800. out.Set(reflect.MakeMap(outt))
  801. mapIsNew = true
  802. }
  803. for i := 0; i < l; i += 2 {
  804. if isMerge(n.Content[i]) {
  805. d.merge(n.Content[i+1], out)
  806. continue
  807. }
  808. k := reflect.New(kt).Elem()
  809. if d.unmarshal(n.Content[i], k) {
  810. kkind := k.Kind()
  811. if kkind == reflect.Interface {
  812. kkind = k.Elem().Kind()
  813. }
  814. if kkind == reflect.Map || kkind == reflect.Slice {
  815. failf("invalid map key: %#v", k.Interface())
  816. }
  817. e := reflect.New(et).Elem()
  818. if d.unmarshal(n.Content[i+1], e) || n.Content[i+1].ShortTag() == nullTag && (mapIsNew || !out.MapIndex(k).IsValid()) {
  819. out.SetMapIndex(k, e)
  820. }
  821. }
  822. }
  823. d.stringMapType = stringMapType
  824. d.generalMapType = generalMapType
  825. return true
  826. }
  827. func isStringMap(n *Node) bool {
  828. if n.Kind != MappingNode {
  829. return false
  830. }
  831. l := len(n.Content)
  832. for i := 0; i < l; i += 2 {
  833. if n.Content[i].ShortTag() != strTag {
  834. return false
  835. }
  836. }
  837. return true
  838. }
  839. func (d *decoder) mappingStruct(n *Node, out reflect.Value) (good bool) {
  840. sinfo, err := getStructInfo(out.Type())
  841. if err != nil {
  842. panic(err)
  843. }
  844. var inlineMap reflect.Value
  845. var elemType reflect.Type
  846. if sinfo.InlineMap != -1 {
  847. inlineMap = out.Field(sinfo.InlineMap)
  848. inlineMap.Set(reflect.New(inlineMap.Type()).Elem())
  849. elemType = inlineMap.Type().Elem()
  850. }
  851. for _, index := range sinfo.InlineUnmarshalers {
  852. field := d.fieldByIndex(n, out, index)
  853. d.prepare(n, field)
  854. }
  855. var doneFields []bool
  856. if d.uniqueKeys {
  857. doneFields = make([]bool, len(sinfo.FieldsList))
  858. }
  859. name := settableValueOf("")
  860. l := len(n.Content)
  861. for i := 0; i < l; i += 2 {
  862. ni := n.Content[i]
  863. if isMerge(ni) {
  864. d.merge(n.Content[i+1], out)
  865. continue
  866. }
  867. if !d.unmarshal(ni, name) {
  868. continue
  869. }
  870. if info, ok := sinfo.FieldsMap[name.String()]; ok {
  871. if d.uniqueKeys {
  872. if doneFields[info.Id] {
  873. d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s already set in type %s", ni.Line, name.String(), out.Type()))
  874. continue
  875. }
  876. doneFields[info.Id] = true
  877. }
  878. var field reflect.Value
  879. if info.Inline == nil {
  880. field = out.Field(info.Num)
  881. } else {
  882. field = d.fieldByIndex(n, out, info.Inline)
  883. }
  884. d.unmarshal(n.Content[i+1], field)
  885. } else if sinfo.InlineMap != -1 {
  886. if inlineMap.IsNil() {
  887. inlineMap.Set(reflect.MakeMap(inlineMap.Type()))
  888. }
  889. value := reflect.New(elemType).Elem()
  890. d.unmarshal(n.Content[i+1], value)
  891. inlineMap.SetMapIndex(name, value)
  892. } else if d.knownFields {
  893. d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s not found in type %s", ni.Line, name.String(), out.Type()))
  894. }
  895. }
  896. return true
  897. }
  898. func failWantMap() {
  899. failf("map merge requires map or sequence of maps as the value")
  900. }
  901. func (d *decoder) merge(n *Node, out reflect.Value) {
  902. switch n.Kind {
  903. case MappingNode:
  904. d.unmarshal(n, out)
  905. case AliasNode:
  906. if n.Alias != nil && n.Alias.Kind != MappingNode {
  907. failWantMap()
  908. }
  909. d.unmarshal(n, out)
  910. case SequenceNode:
  911. // Step backwards as earlier nodes take precedence.
  912. for i := len(n.Content) - 1; i >= 0; i-- {
  913. ni := n.Content[i]
  914. if ni.Kind == AliasNode {
  915. if ni.Alias != nil && ni.Alias.Kind != MappingNode {
  916. failWantMap()
  917. }
  918. } else if ni.Kind != MappingNode {
  919. failWantMap()
  920. }
  921. d.unmarshal(ni, out)
  922. }
  923. default:
  924. failWantMap()
  925. }
  926. }
  927. func isMerge(n *Node) bool {
  928. return n.Kind == ScalarNode && n.Value == "<<" && (n.Tag == "" || n.Tag == "!" || shortTag(n.Tag) == mergeTag)
  929. }