PageRenderTime 43ms CodeModel.GetById 4ms RepoModel.GetById 0ms app.codeStats 0ms

/node.go

https://github.com/xiam/sexp
Go | 424 lines | 327 code | 44 blank | 53 comment | 102 complexity | 020a00c4988f72b30130850cfe570842 MD5 | raw file
  1. package sexp
  2. import (
  3. "fmt"
  4. "reflect"
  5. "strconv"
  6. "io"
  7. )
  8. // The main and only AST structure. All fields are self explanatory, however
  9. // the way they are being formed needs explanation.
  10. //
  11. // A list node has empty value and non-nil children pointer, which is a
  12. // nil-terminated list of children nodes.
  13. //
  14. // A scalar node has nil children pointer.
  15. //
  16. // Take a look at this example:
  17. //
  18. // ((1 2) 3 4)
  19. //
  20. // will yield:
  21. //
  22. // Node{Children:
  23. // Node{Children:
  24. // Node{Value: "1", Next:
  25. // Node{Value: "2"}}, Next:
  26. // Node{Value: "3", Next:
  27. // Node{Value: "4"}}}}
  28. type Node struct {
  29. Location SourceLoc
  30. Value string
  31. Children *Node
  32. Next *Node
  33. }
  34. // Returns true if the node is a list (has children).
  35. func (n *Node) IsList() bool {
  36. return n.Children != nil
  37. }
  38. // Dumps a Node to a io.Writer and keeps a record of the deepness.
  39. //
  40. // The `level` variable means deepness and may help to add pretty
  41. // indentation at a later time.
  42. func (n *Node) dump(fp io.Writer, level uint64) {
  43. if n.IsList() == true {
  44. if level > 0 {
  45. fp.Write([]byte(`(`))
  46. }
  47. if n.Children != nil {
  48. n.Children.dump(fp, level + 1)
  49. }
  50. if level > 0 {
  51. fp.Write([]byte(`)`))
  52. }
  53. } else {
  54. fp.Write([]byte(fmt.Sprintf("%q", n.Value)))
  55. }
  56. if n.Next != nil {
  57. fp.Write([]byte(` `))
  58. n.Next.dump(fp, level)
  59. }
  60. }
  61. // Dumps a *Node to an io.Writer
  62. func (n *Node) Dump(fp io.Writer) {
  63. n.dump(fp, 0)
  64. }
  65. // Return true if the node is a scalar (has no children).
  66. func (n *Node) IsScalar() bool {
  67. return n.Children == nil
  68. }
  69. func (n *Node) String() string {
  70. return n.Value
  71. }
  72. // Returns the number of children nodes. Has O(N) complexity.
  73. func (n *Node) NumChildren() int {
  74. i := 0
  75. c := n.Children
  76. for c != nil {
  77. i++
  78. c = c.Next
  79. }
  80. return i
  81. }
  82. // Returns Nth child node. If node is not a list, it will return an error.
  83. func (n *Node) Nth(num int) (*Node, error) {
  84. if !n.IsList() {
  85. return nil, new_error(n.Location, "node is not a list")
  86. }
  87. i := 0
  88. for c := n.Children; c != nil; c = c.Next {
  89. if i == num {
  90. return c, nil
  91. }
  92. i++
  93. }
  94. num++
  95. return nil, new_error(n.Location,
  96. "cannot retrieve %d%s child node, %s",
  97. num, number_suffix(num),
  98. the_list_has_n_children(n.NumChildren()))
  99. }
  100. // Walk over children nodes, assuming they are key/value pairs. It returns error
  101. // if the iterable node is not a list or if any of its children is not a
  102. // key/value pair.
  103. func (n *Node) IterKeyValues(f func(k, v *Node)) error {
  104. for c := n.Children; c != nil; c = c.Next {
  105. if !c.IsList() {
  106. return new_error(c.Location,
  107. "node is not a list, expected key/value pair")
  108. }
  109. // don't check for error here, because it's obvious that if the
  110. // node is a list (and the definition of the list is `Children
  111. // != nil`), it has at least one child
  112. k, _ := c.Nth(0)
  113. v, err := c.Nth(1)
  114. if err != nil {
  115. return err
  116. }
  117. f(k, v)
  118. }
  119. return nil
  120. }
  121. type Unmarshaler interface {
  122. UnmarshalSexp(n *Node) error
  123. }
  124. // Unmarshal all children nodes to pointer values. TODO: more details here.
  125. func (n *Node) UnmarshalChildren(vals ...interface{}) (err error) {
  126. if len(vals) == 0 {
  127. return nil
  128. }
  129. // unmarshal all children of the node
  130. i := 0
  131. for c := n.Children; c != nil; c = c.Next {
  132. if i >= len(vals) {
  133. break
  134. }
  135. if err := c.unmarshal(vals[i]); err != nil {
  136. return err
  137. }
  138. i++
  139. }
  140. // did we fullfil all the arguments?
  141. if i < len(vals) {
  142. return NewUnmarshalError(n, nil,
  143. "node has only %d children, %d was requested",
  144. i, len(vals))
  145. }
  146. return nil
  147. }
  148. // Unmarshal node and its siblings to pointer values. TODO: more details here.
  149. func (n *Node) Unmarshal(vals ...interface{}) (err error) {
  150. if len(vals) == 0 {
  151. return nil
  152. }
  153. // unmarshal the node itself
  154. if err := n.unmarshal(vals[0]); err != nil {
  155. return err
  156. }
  157. // unmarshal node's siblings
  158. i := 1
  159. for s := n.Next; s != nil; s = s.Next {
  160. if i >= len(vals) {
  161. break
  162. }
  163. if err := s.unmarshal(vals[i]); err != nil {
  164. return err
  165. }
  166. i++
  167. }
  168. // did we fullfil all the arguments?
  169. if i < len(vals) {
  170. return NewUnmarshalError(n, nil,
  171. "node has only %d siblings, %d was requested",
  172. i-1, len(vals)-1)
  173. }
  174. return nil
  175. }
  176. type UnmarshalError struct {
  177. Type reflect.Type
  178. Node *Node
  179. message string
  180. }
  181. func NewUnmarshalError(n *Node, t reflect.Type, format string, args ...interface{}) *UnmarshalError {
  182. return &UnmarshalError{
  183. Type: t,
  184. Node: n,
  185. message: fmt.Sprintf(format, args...),
  186. }
  187. }
  188. func (e *UnmarshalError) Error() string {
  189. args := []interface{}{e.message}
  190. format := "%s"
  191. if e.Node != nil {
  192. if e.Node.IsList() {
  193. format += " (list value)"
  194. } else {
  195. format += " (value: %q)"
  196. args = append(args, e.Node.Value)
  197. }
  198. }
  199. if e.Type != nil {
  200. format += " (type: %s)"
  201. args = append(args, e.Type)
  202. }
  203. return fmt.Sprintf(format, args...)
  204. }
  205. func (n *Node) unmarshal_error(t reflect.Type, format string, args ...interface{}) {
  206. panic(NewUnmarshalError(n, t, fmt.Sprintf(format, args...)))
  207. }
  208. func (n *Node) unmarshal_unmarshaler(v reflect.Value) bool {
  209. u, ok := v.Interface().(Unmarshaler)
  210. if !ok {
  211. // T doesn't work, try *T as well
  212. if v.Kind() != reflect.Ptr && v.CanAddr() {
  213. u, ok = v.Addr().Interface().(Unmarshaler)
  214. if ok {
  215. v = v.Addr()
  216. }
  217. }
  218. }
  219. if ok && (v.Kind() != reflect.Ptr || !v.IsNil()) {
  220. err := u.UnmarshalSexp(n)
  221. if err != nil {
  222. if ue, ok := err.(*UnmarshalError); ok {
  223. panic(ue)
  224. }
  225. n.unmarshal_error(v.Type(), err.Error())
  226. }
  227. return true
  228. }
  229. return false
  230. }
  231. func (n *Node) ensure_scalar(t reflect.Type) {
  232. if n.IsScalar() {
  233. return
  234. }
  235. n.unmarshal_error(t, "scalar value required")
  236. }
  237. func (n *Node) ensure_list(t reflect.Type) {
  238. if n.IsList() {
  239. return
  240. }
  241. n.unmarshal_error(t, "list value required")
  242. }
  243. func (n *Node) unmarshal_value(v reflect.Value) {
  244. t := v.Type()
  245. // we support one level of indirection at the moment
  246. if v.Kind() == reflect.Ptr {
  247. // if the pointer is nil, allocate a new element of the type it
  248. // points to
  249. if v.IsNil() {
  250. v.Set(reflect.New(t.Elem()))
  251. }
  252. v = v.Elem()
  253. }
  254. // try Unmarshaler interface
  255. if n.unmarshal_unmarshaler(v) {
  256. return
  257. }
  258. // fallback to default unmarshaling scheme
  259. switch v.Kind() {
  260. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  261. // TODO: more string -> int conversion options (hex, binary, octal, etc.)
  262. n.ensure_scalar(t)
  263. num, err := strconv.ParseInt(n.Value, 10, 64)
  264. if err != nil {
  265. n.unmarshal_error(t, err.Error())
  266. }
  267. if v.OverflowInt(num) {
  268. n.unmarshal_error(t, "integer overflow")
  269. }
  270. v.SetInt(num)
  271. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  272. // TODO: more string -> int conversion options (hex, binary, octal, etc.)
  273. n.ensure_scalar(t)
  274. num, err := strconv.ParseUint(n.Value, 10, 64)
  275. if err != nil {
  276. n.unmarshal_error(t, err.Error())
  277. }
  278. if v.OverflowUint(num) {
  279. n.unmarshal_error(t, "integer overflow")
  280. }
  281. v.SetUint(num)
  282. case reflect.Float32, reflect.Float64:
  283. n.ensure_scalar(t)
  284. num, err := strconv.ParseFloat(n.Value, 64)
  285. if err != nil {
  286. n.unmarshal_error(t, err.Error())
  287. }
  288. v.SetFloat(num)
  289. case reflect.Bool:
  290. n.ensure_scalar(t)
  291. switch n.Value {
  292. case "true":
  293. v.SetBool(true)
  294. case "false":
  295. v.SetBool(false)
  296. default:
  297. n.unmarshal_error(t, "undefined boolean value, use true|false")
  298. }
  299. case reflect.String:
  300. n.ensure_scalar(t)
  301. v.SetString(n.Value)
  302. case reflect.Array, reflect.Slice:
  303. n.ensure_list(t)
  304. i := 0
  305. for c := n.Children; c != nil; c = c.Next {
  306. if i >= v.Len() {
  307. if v.Kind() == reflect.Array {
  308. break
  309. } else {
  310. v.Set(reflect.Append(v, reflect.Zero(t.Elem())))
  311. }
  312. }
  313. c.unmarshal_value(v.Index(i))
  314. i++
  315. }
  316. if i < v.Len() {
  317. if v.Kind() == reflect.Array {
  318. z := reflect.Zero(t.Elem())
  319. for n := v.Len(); i < n; i++ {
  320. v.Index(i).Set(z)
  321. }
  322. } else {
  323. v.SetLen(i)
  324. }
  325. }
  326. case reflect.Interface:
  327. if v.NumMethod() != 0 {
  328. n.unmarshal_error(t, "unsupported type")
  329. }
  330. v.Set(reflect.ValueOf(n.unmarshal_as_interface()))
  331. case reflect.Map:
  332. n.ensure_list(t)
  333. if v.IsNil() {
  334. v.Set(reflect.MakeMap(t))
  335. }
  336. keyv := reflect.New(t.Key()).Elem()
  337. valv := reflect.New(t.Elem()).Elem()
  338. err := n.IterKeyValues(func(key, val *Node) {
  339. key.unmarshal_value(keyv)
  340. val.unmarshal_value(valv)
  341. v.SetMapIndex(keyv, valv)
  342. })
  343. if err != nil {
  344. n.unmarshal_error(t, "%s", err)
  345. }
  346. case reflect.Struct:
  347. // TODO
  348. default:
  349. n.unmarshal_error(t, "unsupported type")
  350. }
  351. }
  352. func (n *Node) unmarshal_as_interface() interface{} {
  353. // interface parsing for sexp isn't really useful, the outcome is
  354. // []interface{} or string
  355. if n.IsList() {
  356. var s []interface{}
  357. for c := n.Children; c != nil; c = c.Next {
  358. s = append(s, c.unmarshal_as_interface())
  359. }
  360. return s
  361. }
  362. return n.Value
  363. }
  364. func (n *Node) unmarshal(v interface{}) (err error) {
  365. defer func() {
  366. if e := recover(); e != nil {
  367. if _, ok := e.(*UnmarshalError); ok {
  368. err = e.(error)
  369. } else {
  370. panic(e)
  371. }
  372. }
  373. }()
  374. pv := reflect.ValueOf(v)
  375. if pv.Kind() != reflect.Ptr || pv.IsNil() {
  376. panic("Node.Unmarshal expects a non-nil pointer argument")
  377. }
  378. n.unmarshal_value(pv.Elem())
  379. return nil
  380. }