decode.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. package toml
  2. import (
  3. "fmt"
  4. "io"
  5. "io/ioutil"
  6. "reflect"
  7. "strings"
  8. "time"
  9. )
  10. var e = fmt.Errorf
  11. // Primitive is a TOML value that hasn't been decoded into a Go value.
  12. // When using the various `Decode*` functions, the type `Primitive` may
  13. // be given to any value, and its decoding will be delayed.
  14. //
  15. // A `Primitive` value can be decoded using the `PrimitiveDecode` function.
  16. //
  17. // The underlying representation of a `Primitive` value is subject to change.
  18. // Do not rely on it.
  19. //
  20. // N.B. Primitive values are still parsed, so using them will only avoid
  21. // the overhead of reflection. They can be useful when you don't know the
  22. // exact type of TOML data until run time.
  23. type Primitive interface{}
  24. // PrimitiveDecode is just like the other `Decode*` functions, except it
  25. // decodes a TOML value that has already been parsed. Valid primitive values
  26. // can *only* be obtained from values filled by the decoder functions,
  27. // including `PrimitiveDecode`. (i.e., `v` may contain more `Primitive`
  28. // values.)
  29. //
  30. // Meta data for primitive values is included in the meta data returned by
  31. // the `Decode*` functions.
  32. func PrimitiveDecode(primValue Primitive, v interface{}) error {
  33. return unify(primValue, rvalue(v))
  34. }
  35. // Decode will decode the contents of `data` in TOML format into a pointer
  36. // `v`.
  37. //
  38. // TOML hashes correspond to Go structs or maps. (Dealer's choice. They can be
  39. // used interchangeably.)
  40. //
  41. // TOML datetimes correspond to Go `time.Time` values.
  42. //
  43. // All other TOML types (float, string, int, bool and array) correspond
  44. // to the obvious Go types.
  45. //
  46. // TOML keys can map to either keys in a Go map or field names in a Go
  47. // struct. The special `toml` struct tag may be used to map TOML keys to
  48. // struct fields that don't match the key name exactly. (See the example.)
  49. // A case insensitive match to struct names will be tried if an exact match
  50. // can't be found.
  51. //
  52. // The mapping between TOML values and Go values is loose. That is, there
  53. // may exist TOML values that cannot be placed into your representation, and
  54. // there may be parts of your representation that do not correspond to
  55. // TOML values.
  56. //
  57. // This decoder will not handle cyclic types. If a cyclic type is passed,
  58. // `Decode` will not terminate.
  59. func Decode(data string, v interface{}) (MetaData, error) {
  60. p, err := parse(data)
  61. if err != nil {
  62. return MetaData{}, err
  63. }
  64. return MetaData{p.mapping, p.types, p.ordered}, unify(p.mapping, rvalue(v))
  65. }
  66. // DecodeFile is just like Decode, except it will automatically read the
  67. // contents of the file at `fpath` and decode it for you.
  68. func DecodeFile(fpath string, v interface{}) (MetaData, error) {
  69. bs, err := ioutil.ReadFile(fpath)
  70. if err != nil {
  71. return MetaData{}, err
  72. }
  73. return Decode(string(bs), v)
  74. }
  75. // DecodeReader is just like Decode, except it will consume all bytes
  76. // from the reader and decode it for you.
  77. func DecodeReader(r io.Reader, v interface{}) (MetaData, error) {
  78. bs, err := ioutil.ReadAll(r)
  79. if err != nil {
  80. return MetaData{}, err
  81. }
  82. return Decode(string(bs), v)
  83. }
  84. // unify performs a sort of type unification based on the structure of `rv`,
  85. // which is the client representation.
  86. //
  87. // Any type mismatch produces an error. Finding a type that we don't know
  88. // how to handle produces an unsupported type error.
  89. func unify(data interface{}, rv reflect.Value) error {
  90. // Special case. Look for a `Primitive` value.
  91. if rv.Type() == reflect.TypeOf((*Primitive)(nil)).Elem() {
  92. return unifyAnything(data, rv)
  93. }
  94. // Special case. Go's `time.Time` is a struct, which we don't want
  95. // to confuse with a user struct.
  96. if rv.Type().AssignableTo(rvalue(time.Time{}).Type()) {
  97. return unifyDatetime(data, rv)
  98. }
  99. k := rv.Kind()
  100. // laziness
  101. if k >= reflect.Int && k <= reflect.Uint64 {
  102. return unifyInt(data, rv)
  103. }
  104. switch k {
  105. case reflect.Ptr:
  106. elem := reflect.New(rv.Type().Elem())
  107. err := unify(data, reflect.Indirect(elem))
  108. if err != nil {
  109. return err
  110. }
  111. rv.Set(elem)
  112. return nil
  113. case reflect.Struct:
  114. return unifyStruct(data, rv)
  115. case reflect.Map:
  116. return unifyMap(data, rv)
  117. case reflect.Slice:
  118. return unifySlice(data, rv)
  119. case reflect.String:
  120. return unifyString(data, rv)
  121. case reflect.Bool:
  122. return unifyBool(data, rv)
  123. case reflect.Interface:
  124. // we only support empty interfaces.
  125. if rv.NumMethod() > 0 {
  126. return e("Unsupported type '%s'.", rv.Kind())
  127. }
  128. return unifyAnything(data, rv)
  129. case reflect.Float32:
  130. fallthrough
  131. case reflect.Float64:
  132. return unifyFloat64(data, rv)
  133. }
  134. return e("Unsupported type '%s'.", rv.Kind())
  135. }
  136. func unifyStruct(mapping interface{}, rv reflect.Value) error {
  137. tmap, ok := mapping.(map[string]interface{})
  138. if !ok {
  139. return mismatch(rv, "map", mapping)
  140. }
  141. rt := rv.Type()
  142. for i := 0; i < rt.NumField(); i++ {
  143. // A little tricky. We want to use the special `toml` name in the
  144. // struct tag if it exists. In particular, we need to make sure that
  145. // this struct field is in the current map before trying to unify it.
  146. sft := rt.Field(i)
  147. kname := sft.Tag.Get("toml")
  148. if len(kname) == 0 {
  149. kname = sft.Name
  150. }
  151. if datum, ok := insensitiveGet(tmap, kname); ok {
  152. sf := indirect(rv.Field(i))
  153. // Don't try to mess with unexported types and other such things.
  154. if sf.CanSet() {
  155. if err := unify(datum, sf); err != nil {
  156. return e("Type mismatch for '%s.%s': %s",
  157. rt.String(), sft.Name, err)
  158. }
  159. } else if len(sft.Tag.Get("toml")) > 0 {
  160. // Bad user! No soup for you!
  161. return e("Field '%s.%s' is unexported, and therefore cannot "+
  162. "be loaded with reflection.", rt.String(), sft.Name)
  163. }
  164. }
  165. }
  166. return nil
  167. }
  168. func unifyMap(mapping interface{}, rv reflect.Value) error {
  169. tmap, ok := mapping.(map[string]interface{})
  170. if !ok {
  171. return badtype("map", mapping)
  172. }
  173. if rv.IsNil() {
  174. rv.Set(reflect.MakeMap(rv.Type()))
  175. }
  176. for k, v := range tmap {
  177. rvkey := indirect(reflect.New(rv.Type().Key()))
  178. rvval := reflect.Indirect(reflect.New(rv.Type().Elem()))
  179. if err := unify(v, rvval); err != nil {
  180. return err
  181. }
  182. rvkey.SetString(k)
  183. rv.SetMapIndex(rvkey, rvval)
  184. }
  185. return nil
  186. }
  187. func unifySlice(data interface{}, rv reflect.Value) error {
  188. datav := reflect.ValueOf(data)
  189. if datav.Kind() != reflect.Slice {
  190. return badtype("slice", data)
  191. }
  192. sliceLen := datav.Len()
  193. if rv.IsNil() {
  194. rv.Set(reflect.MakeSlice(rv.Type(), sliceLen, sliceLen))
  195. }
  196. for i := 0; i < sliceLen; i++ {
  197. v := datav.Index(i).Interface()
  198. sliceval := indirect(rv.Index(i))
  199. if err := unify(v, sliceval); err != nil {
  200. return err
  201. }
  202. }
  203. return nil
  204. }
  205. func unifyDatetime(data interface{}, rv reflect.Value) error {
  206. if _, ok := data.(time.Time); ok {
  207. rv.Set(reflect.ValueOf(data))
  208. return nil
  209. }
  210. return badtype("time.Time", data)
  211. }
  212. func unifyString(data interface{}, rv reflect.Value) error {
  213. if s, ok := data.(string); ok {
  214. rv.SetString(s)
  215. return nil
  216. }
  217. return badtype("string", data)
  218. }
  219. func unifyFloat64(data interface{}, rv reflect.Value) error {
  220. if num, ok := data.(float64); ok {
  221. switch rv.Kind() {
  222. case reflect.Float32:
  223. fallthrough
  224. case reflect.Float64:
  225. rv.SetFloat(num)
  226. default:
  227. panic("bug")
  228. }
  229. return nil
  230. }
  231. return badtype("float", data)
  232. }
  233. func unifyInt(data interface{}, rv reflect.Value) error {
  234. if num, ok := data.(int64); ok {
  235. switch rv.Kind() {
  236. case reflect.Int:
  237. fallthrough
  238. case reflect.Int8:
  239. fallthrough
  240. case reflect.Int16:
  241. fallthrough
  242. case reflect.Int32:
  243. fallthrough
  244. case reflect.Int64:
  245. rv.SetInt(int64(num))
  246. case reflect.Uint:
  247. fallthrough
  248. case reflect.Uint8:
  249. fallthrough
  250. case reflect.Uint16:
  251. fallthrough
  252. case reflect.Uint32:
  253. fallthrough
  254. case reflect.Uint64:
  255. rv.SetUint(uint64(num))
  256. default:
  257. panic("bug")
  258. }
  259. return nil
  260. }
  261. return badtype("integer", data)
  262. }
  263. func unifyBool(data interface{}, rv reflect.Value) error {
  264. if b, ok := data.(bool); ok {
  265. rv.SetBool(b)
  266. return nil
  267. }
  268. return badtype("integer", data)
  269. }
  270. func unifyAnything(data interface{}, rv reflect.Value) error {
  271. // too awesome to fail
  272. rv.Set(reflect.ValueOf(data))
  273. return nil
  274. }
  275. // rvalue returns a reflect.Value of `v`. All pointers are resolved.
  276. func rvalue(v interface{}) reflect.Value {
  277. return indirect(reflect.ValueOf(v))
  278. }
  279. // indirect returns the value pointed to by a pointer.
  280. // Pointers are followed until the value is not a pointer.
  281. // New values are allocated for each nil pointer.
  282. func indirect(v reflect.Value) reflect.Value {
  283. if v.Kind() != reflect.Ptr {
  284. return v
  285. }
  286. if v.IsNil() {
  287. v.Set(reflect.New(v.Type().Elem()))
  288. }
  289. return indirect(reflect.Indirect(v))
  290. }
  291. func tstring(rv reflect.Value) string {
  292. return rv.Type().String()
  293. }
  294. func badtype(expected string, data interface{}) error {
  295. return e("Expected %s but found '%T'.", expected, data)
  296. }
  297. func mismatch(user reflect.Value, expected string, data interface{}) error {
  298. return e("Type mismatch for %s. Expected %s but found '%T'.",
  299. tstring(user), expected, data)
  300. }
  301. func insensitiveGet(
  302. tmap map[string]interface{}, kname string) (interface{}, bool) {
  303. if datum, ok := tmap[kname]; ok {
  304. return datum, true
  305. }
  306. for k, v := range tmap {
  307. if strings.EqualFold(kname, k) {
  308. return v, true
  309. }
  310. }
  311. return nil, false
  312. }
  313. // MetaData allows access to meta information about TOML data that may not
  314. // be inferrable via reflection. In particular, whether a key has been defined
  315. // and the TOML type of a key.
  316. //
  317. // (XXX: If TOML gets NULL values, that information will be added here too.)
  318. type MetaData struct {
  319. mapping map[string]interface{}
  320. types map[string]tomlType
  321. keys []Key
  322. }
  323. // IsDefined returns true if the key given exists in the TOML data. The key
  324. // should be specified hierarchially. e.g.,
  325. //
  326. // // access the TOML key 'a.b.c'
  327. // IsDefined("a", "b", "c")
  328. //
  329. // IsDefined will return false if an empty key given. Keys are case sensitive.
  330. func (md MetaData) IsDefined(key ...string) bool {
  331. var hashOrVal interface{}
  332. var hash map[string]interface{}
  333. var ok bool
  334. if len(key) == 0 {
  335. return false
  336. }
  337. hashOrVal = md.mapping
  338. for _, k := range key {
  339. if hash, ok = hashOrVal.(map[string]interface{}); !ok {
  340. return false
  341. }
  342. if hashOrVal, ok = hash[k]; !ok {
  343. return false
  344. }
  345. }
  346. return true
  347. }
  348. // Type returns a string representation of the type of the key specified.
  349. //
  350. // Type will return the empty string if given an empty key or a key that
  351. // does not exist. Keys are case sensitive.
  352. func (md MetaData) Type(key ...string) string {
  353. fullkey := strings.Join(key, ".")
  354. if typ, ok := md.types[fullkey]; ok {
  355. return typ.typeString()
  356. }
  357. return ""
  358. }
  359. // Key is the type of any TOML key, including key groups. Use (MetaData).Keys
  360. // to get values of this type.
  361. type Key []string
  362. func (k Key) String() string {
  363. return strings.Join(k, ".")
  364. }
  365. func (k Key) add(piece string) Key {
  366. newKey := make(Key, len(k))
  367. copy(newKey, k)
  368. return append(newKey, piece)
  369. }
  370. // Keys returns a slice of every key in the TOML data, including key groups.
  371. // Each key is itself a slice, where the first element is the top of the
  372. // hierarchy and the last is the most specific.
  373. //
  374. // The list will have the same order as the keys appeared in the TOML data.
  375. //
  376. // All keys returned are non-empty.
  377. func (md MetaData) Keys() []Key {
  378. return md.keys
  379. }
  380. func allKeys(m map[string]interface{}, context Key) []Key {
  381. keys := make([]Key, 0, len(m))
  382. for k, v := range m {
  383. keys = append(keys, context.add(k))
  384. if t, ok := v.(map[string]interface{}); ok {
  385. keys = append(keys, allKeys(t, context.add(k))...)
  386. }
  387. }
  388. return keys
  389. }