main.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package dirty
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. "reflect"
  7. )
  8. const DEBUG bool = true // build -X
  9. func debugf(format string, a ...interface{}) {
  10. if DEBUG {
  11. fmt.Printf(format, a...)
  12. }
  13. }
  14. func debugln(a ...interface{}) {
  15. if DEBUG {
  16. fmt.Println(a...)
  17. }
  18. }
  19. // todo func LoadArray()
  20. func Load(r io.Reader) (Array, error) {
  21. scanner := bufio.NewReader(r)
  22. array := []Element{}
  23. comment := token{ttype: COMMENT}
  24. lbrack := token{ttype: LBRACKET}
  25. eof := token{ttype: EOF}
  26. expected := lbrack
  27. for {
  28. t, err := nextToken(scanner)
  29. //debugf("in Load got %+v\n", t)
  30. if err != nil {
  31. return []Element{}, err
  32. }
  33. if t == comment {
  34. continue
  35. } else if t == lbrack {
  36. if expected != lbrack {
  37. //debugln("expected lbrac")
  38. return []Element{}, NewSyntaxError(t, []token{expected})
  39. }
  40. //debugf("in Load loading array\n")
  41. array, err = loadArray(scanner)
  42. if err != nil {
  43. return Array{}, err
  44. }
  45. expected = eof
  46. } else if t == eof {
  47. if expected != eof {
  48. //debugln("expected eof")
  49. return []Element{}, NewSyntaxError(t, []token{expected})
  50. }
  51. //debugf("in Load eofing\n")
  52. return array, nil
  53. } else {
  54. //debugln("garbage")
  55. return []Element{}, NewSyntaxError(t, []token{expected})
  56. }
  57. }
  58. }
  59. // todo func Load()
  60. func LoadStruct(r io.Reader, s interface{}) error {
  61. array, err := Load(r)
  62. if err != nil {
  63. return err
  64. }
  65. v := reflect.ValueOf(s).Elem()
  66. return convertStruct(array, v)
  67. }