parse.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. package toml
  2. import (
  3. "errors"
  4. "fmt"
  5. "strconv"
  6. "strings"
  7. "github.com/naoina/toml/ast"
  8. )
  9. // The parser is generated by github.com/pointlander/peg. To regenerate it, do:
  10. //
  11. // go get -u github.com/pointlander/peg
  12. // go generate .
  13. //go:generate peg -switch -inline parse.peg
  14. var errParse = errors.New("invalid TOML syntax")
  15. // Parse returns an AST representation of TOML.
  16. // The toplevel is represented by a table.
  17. func Parse(data []byte) (*ast.Table, error) {
  18. d := &parseState{p: &tomlParser{Buffer: string(data)}}
  19. d.init()
  20. if err := d.parse(); err != nil {
  21. return nil, err
  22. }
  23. return d.p.toml.table, nil
  24. }
  25. type parseState struct {
  26. p *tomlParser
  27. }
  28. func (d *parseState) init() {
  29. d.p.Init()
  30. d.p.toml.init(d.p.buffer)
  31. }
  32. func (d *parseState) parse() error {
  33. if err := d.p.Parse(); err != nil {
  34. if err, ok := err.(*parseError); ok {
  35. return lineError(err.Line(), errParse)
  36. }
  37. return err
  38. }
  39. return d.execute()
  40. }
  41. func (d *parseState) execute() (err error) {
  42. defer func() {
  43. if e := recover(); e != nil {
  44. lerr, ok := e.(*LineError)
  45. if !ok {
  46. panic(e)
  47. }
  48. err = lerr
  49. }
  50. }()
  51. d.p.Execute()
  52. return nil
  53. }
  54. func (e *parseError) Line() int {
  55. tokens := []token32{e.max}
  56. positions, p := make([]int, 2*len(tokens)), 0
  57. for _, token := range tokens {
  58. positions[p], p = int(token.begin), p+1
  59. positions[p], p = int(token.end), p+1
  60. }
  61. for _, t := range translatePositions(e.p.buffer, positions) {
  62. if e.p.line < t.line {
  63. e.p.line = t.line
  64. }
  65. }
  66. return e.p.line
  67. }
  68. type stack struct {
  69. key string
  70. table *ast.Table
  71. }
  72. type array struct {
  73. parent *array
  74. child *array
  75. current *ast.Array
  76. line int
  77. }
  78. type toml struct {
  79. table *ast.Table
  80. line int
  81. currentTable *ast.Table
  82. s string
  83. key string
  84. tableKeys []string
  85. val ast.Value
  86. arr *array
  87. stack []*stack
  88. skip bool
  89. }
  90. func (p *toml) init(data []rune) {
  91. p.line = 1
  92. p.table = p.newTable(ast.TableTypeNormal, "")
  93. p.table.Position.End = len(data) - 1
  94. p.table.Data = data[:len(data)-1] // truncate the end_symbol added by PEG parse generator.
  95. p.currentTable = p.table
  96. }
  97. func (p *toml) Error(err error) {
  98. panic(lineError(p.line, err))
  99. }
  100. func (p *tomlParser) SetTime(begin, end int) {
  101. p.val = &ast.Datetime{
  102. Position: ast.Position{Begin: begin, End: end},
  103. Data: p.buffer[begin:end],
  104. Value: string(p.buffer[begin:end]),
  105. }
  106. }
  107. func (p *tomlParser) SetFloat64(begin, end int) {
  108. p.val = &ast.Float{
  109. Position: ast.Position{Begin: begin, End: end},
  110. Data: p.buffer[begin:end],
  111. Value: underscoreReplacer.Replace(string(p.buffer[begin:end])),
  112. }
  113. }
  114. func (p *tomlParser) SetInt64(begin, end int) {
  115. p.val = &ast.Integer{
  116. Position: ast.Position{Begin: begin, End: end},
  117. Data: p.buffer[begin:end],
  118. Value: underscoreReplacer.Replace(string(p.buffer[begin:end])),
  119. }
  120. }
  121. func (p *tomlParser) SetString(begin, end int) {
  122. p.val = &ast.String{
  123. Position: ast.Position{Begin: begin, End: end},
  124. Data: p.buffer[begin:end],
  125. Value: p.s,
  126. }
  127. p.s = ""
  128. }
  129. func (p *tomlParser) SetBool(begin, end int) {
  130. p.val = &ast.Boolean{
  131. Position: ast.Position{Begin: begin, End: end},
  132. Data: p.buffer[begin:end],
  133. Value: string(p.buffer[begin:end]),
  134. }
  135. }
  136. func (p *tomlParser) StartArray() {
  137. if p.arr == nil {
  138. p.arr = &array{line: p.line, current: &ast.Array{}}
  139. return
  140. }
  141. p.arr.child = &array{parent: p.arr, line: p.line, current: &ast.Array{}}
  142. p.arr = p.arr.child
  143. }
  144. func (p *tomlParser) AddArrayVal() {
  145. if p.arr.current == nil {
  146. p.arr.current = &ast.Array{}
  147. }
  148. p.arr.current.Value = append(p.arr.current.Value, p.val)
  149. }
  150. func (p *tomlParser) SetArray(begin, end int) {
  151. p.arr.current.Position = ast.Position{Begin: begin, End: end}
  152. p.arr.current.Data = p.buffer[begin:end]
  153. p.val = p.arr.current
  154. p.arr = p.arr.parent
  155. }
  156. func (p *toml) SetTable(buf []rune, begin, end int) {
  157. rawName := string(buf[begin:end])
  158. p.setTable(p.table, rawName, p.tableKeys)
  159. p.tableKeys = nil
  160. }
  161. func (p *toml) setTable(parent *ast.Table, name string, names []string) {
  162. parent, err := p.lookupTable(parent, names[:len(names)-1])
  163. if err != nil {
  164. p.Error(err)
  165. }
  166. last := names[len(names)-1]
  167. tbl := p.newTable(ast.TableTypeNormal, last)
  168. switch v := parent.Fields[last].(type) {
  169. case nil:
  170. parent.Fields[last] = tbl
  171. case []*ast.Table:
  172. p.Error(fmt.Errorf("table `%s' is in conflict with array table in line %d", name, v[0].Line))
  173. case *ast.Table:
  174. if (v.Position == ast.Position{}) {
  175. // This table was created as an implicit parent.
  176. // Replace it with the real defined table.
  177. tbl.Fields = v.Fields
  178. parent.Fields[last] = tbl
  179. } else {
  180. p.Error(fmt.Errorf("table `%s' is in conflict with table in line %d", name, v.Line))
  181. }
  182. case *ast.KeyValue:
  183. p.Error(fmt.Errorf("table `%s' is in conflict with line %d", name, v.Line))
  184. default:
  185. p.Error(fmt.Errorf("BUG: table `%s' is in conflict but it's unknown type `%T'", last, v))
  186. }
  187. p.currentTable = tbl
  188. }
  189. func (p *toml) newTable(typ ast.TableType, name string) *ast.Table {
  190. return &ast.Table{
  191. Line: p.line,
  192. Name: name,
  193. Type: typ,
  194. Fields: make(map[string]interface{}),
  195. }
  196. }
  197. func (p *tomlParser) SetTableString(begin, end int) {
  198. p.currentTable.Data = p.buffer[begin:end]
  199. p.currentTable.Position.Begin = begin
  200. p.currentTable.Position.End = end
  201. }
  202. func (p *toml) SetArrayTable(buf []rune, begin, end int) {
  203. rawName := string(buf[begin:end])
  204. p.setArrayTable(p.table, rawName, p.tableKeys)
  205. p.tableKeys = nil
  206. }
  207. func (p *toml) setArrayTable(parent *ast.Table, name string, names []string) {
  208. parent, err := p.lookupTable(parent, names[:len(names)-1])
  209. if err != nil {
  210. p.Error(err)
  211. }
  212. last := names[len(names)-1]
  213. tbl := p.newTable(ast.TableTypeArray, last)
  214. switch v := parent.Fields[last].(type) {
  215. case nil:
  216. parent.Fields[last] = []*ast.Table{tbl}
  217. case []*ast.Table:
  218. parent.Fields[last] = append(v, tbl)
  219. case *ast.Table:
  220. p.Error(fmt.Errorf("array table `%s' is in conflict with table in line %d", name, v.Line))
  221. case *ast.KeyValue:
  222. p.Error(fmt.Errorf("array table `%s' is in conflict with line %d", name, v.Line))
  223. default:
  224. p.Error(fmt.Errorf("BUG: array table `%s' is in conflict but it's unknown type `%T'", name, v))
  225. }
  226. p.currentTable = tbl
  227. }
  228. func (p *toml) StartInlineTable() {
  229. p.skip = false
  230. p.stack = append(p.stack, &stack{p.key, p.currentTable})
  231. names := []string{p.key}
  232. if p.arr == nil {
  233. p.setTable(p.currentTable, names[0], names)
  234. } else {
  235. p.setArrayTable(p.currentTable, names[0], names)
  236. }
  237. }
  238. func (p *toml) EndInlineTable() {
  239. st := p.stack[len(p.stack)-1]
  240. p.key, p.currentTable = st.key, st.table
  241. p.stack[len(p.stack)-1] = nil
  242. p.stack = p.stack[:len(p.stack)-1]
  243. p.skip = true
  244. }
  245. func (p *toml) AddLineCount(i int) {
  246. p.line += i
  247. }
  248. func (p *toml) SetKey(buf []rune, begin, end int) {
  249. p.key = string(buf[begin:end])
  250. if len(p.key) > 0 && p.key[0] == '"' {
  251. p.key = p.unquote(p.key)
  252. }
  253. }
  254. func (p *toml) AddTableKey() {
  255. p.tableKeys = append(p.tableKeys, p.key)
  256. }
  257. func (p *toml) AddKeyValue() {
  258. if p.skip {
  259. p.skip = false
  260. return
  261. }
  262. if val, exists := p.currentTable.Fields[p.key]; exists {
  263. switch v := val.(type) {
  264. case *ast.Table:
  265. p.Error(fmt.Errorf("key `%s' is in conflict with table in line %d", p.key, v.Line))
  266. case *ast.KeyValue:
  267. p.Error(fmt.Errorf("key `%s' is in conflict with line %xd", p.key, v.Line))
  268. default:
  269. p.Error(fmt.Errorf("BUG: key `%s' is in conflict but it's unknown type `%T'", p.key, v))
  270. }
  271. }
  272. p.currentTable.Fields[p.key] = &ast.KeyValue{Key: p.key, Value: p.val, Line: p.line}
  273. }
  274. func (p *toml) SetBasicString(buf []rune, begin, end int) {
  275. p.s = p.unquote(string(buf[begin:end]))
  276. }
  277. func (p *toml) SetMultilineString() {
  278. p.s = p.unquote(`"` + escapeReplacer.Replace(strings.TrimLeft(p.s, "\r\n")) + `"`)
  279. }
  280. func (p *toml) AddMultilineBasicBody(buf []rune, begin, end int) {
  281. p.s += string(buf[begin:end])
  282. }
  283. func (p *toml) SetLiteralString(buf []rune, begin, end int) {
  284. p.s = string(buf[begin:end])
  285. }
  286. func (p *toml) SetMultilineLiteralString(buf []rune, begin, end int) {
  287. p.s = strings.TrimLeft(string(buf[begin:end]), "\r\n")
  288. }
  289. func (p *toml) unquote(s string) string {
  290. s, err := strconv.Unquote(s)
  291. if err != nil {
  292. p.Error(err)
  293. }
  294. return s
  295. }
  296. func (p *toml) lookupTable(t *ast.Table, keys []string) (*ast.Table, error) {
  297. for _, s := range keys {
  298. val, exists := t.Fields[s]
  299. if !exists {
  300. tbl := p.newTable(ast.TableTypeNormal, s)
  301. t.Fields[s] = tbl
  302. t = tbl
  303. continue
  304. }
  305. switch v := val.(type) {
  306. case *ast.Table:
  307. t = v
  308. case []*ast.Table:
  309. t = v[len(v)-1]
  310. case *ast.KeyValue:
  311. return nil, fmt.Errorf("key `%s' is in conflict with line %d", s, v.Line)
  312. default:
  313. return nil, fmt.Errorf("BUG: key `%s' is in conflict but it's unknown type `%T'", s, v)
  314. }
  315. }
  316. return t, nil
  317. }