xml.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. // +build ignore
  2. package codec
  3. import "reflect"
  4. /*
  5. A strict Non-validating namespace-aware XML 1.0 parser and (en|de)coder.
  6. We are attempting this due to perceived issues with encoding/xml:
  7. - Complicated. It tried to do too much, and is not as simple to use as json.
  8. - Due to over-engineering, reflection is over-used AND performance suffers:
  9. java is 6X faster:http://fabsk.eu/blog/category/informatique/dev/golang/
  10. even PYTHON performs better: http://outgoing.typepad.com/outgoing/2014/07/exploring-golang.html
  11. codec framework will offer the following benefits
  12. - VASTLY improved performance (when using reflection-mode or codecgen)
  13. - simplicity and consistency: with the rest of the supported formats
  14. - all other benefits of codec framework (streaming, codegeneration, etc)
  15. codec is not a drop-in replacement for encoding/xml.
  16. It is a replacement, based on the simplicity and performance of codec.
  17. Look at it like JAXB for Go.
  18. Challenges:
  19. - Need to output XML preamble, with all namespaces at the right location in the output.
  20. - Each "end" block is dynamic, so we need to maintain a context-aware stack
  21. - How to decide when to use an attribute VS an element
  22. - How to handle chardata, attr, comment EXPLICITLY.
  23. - Should it output fragments?
  24. e.g. encoding a bool should just output true OR false, which is not well-formed XML.
  25. Extend the struct tag. See representative example:
  26. type X struct {
  27. ID uint8 `codec:"http://ugorji.net/x-namespace xid id,omitempty,toarray,attr,cdata"`
  28. // format: [namespace-uri ][namespace-prefix ]local-name, ...
  29. }
  30. Based on this, we encode
  31. - fields as elements, BUT
  32. encode as attributes if struct tag contains ",attr" and is a scalar (bool, number or string)
  33. - text as entity-escaped text, BUT encode as CDATA if struct tag contains ",cdata".
  34. To handle namespaces:
  35. - XMLHandle is denoted as being namespace-aware.
  36. Consequently, we WILL use the ns:name pair to encode and decode if defined, else use the plain name.
  37. - *Encoder and *Decoder know whether the Handle "prefers" namespaces.
  38. - add *Encoder.getEncName(*structFieldInfo).
  39. No one calls *structFieldInfo.indexForEncName directly anymore
  40. - OR better yet: indexForEncName is namespace-aware, and helper.go is all namespace-aware
  41. indexForEncName takes a parameter of the form namespace:local-name OR local-name
  42. - add *Decoder.getStructFieldInfo(encName string) // encName here is either like abc, or h1:nsabc
  43. by being a method on *Decoder, or maybe a method on the Handle itself.
  44. No one accesses .encName anymore
  45. - let encode.go and decode.go use these (for consistency)
  46. - only problem exists for gen.go, where we create a big switch on encName.
  47. Now, we also have to add a switch on strings.endsWith(kName, encNsName)
  48. - gen.go will need to have many more methods, and then double-on the 2 switch loops like:
  49. switch k {
  50. case "abc" : x.abc()
  51. case "def" : x.def()
  52. default {
  53. switch {
  54. case !nsAware: panic(...)
  55. case strings.endsWith(":abc"): x.abc()
  56. case strings.endsWith(":def"): x.def()
  57. default: panic(...)
  58. }
  59. }
  60. }
  61. The structure below accommodates this:
  62. type typeInfo struct {
  63. sfi []*structFieldInfo // sorted by encName
  64. sfins // sorted by namespace
  65. sfia // sorted, to have those with attributes at the top. Needed to write XML appropriately.
  66. sfip // unsorted
  67. }
  68. type structFieldInfo struct {
  69. encName
  70. nsEncName
  71. ns string
  72. attr bool
  73. cdata bool
  74. }
  75. indexForEncName is now an internal helper function that takes a sorted array
  76. (one of ti.sfins or ti.sfi). It is only used by *Encoder.getStructFieldInfo(...)
  77. There will be a separate parser from the builder.
  78. The parser will have a method: next() xmlToken method. It has lookahead support,
  79. so you can pop multiple tokens, make a determination, and push them back in the order popped.
  80. This will be needed to determine whether we are "nakedly" decoding a container or not.
  81. The stack will be implemented using a slice and push/pop happens at the [0] element.
  82. xmlToken has fields:
  83. - type uint8: 0 | ElementStart | ElementEnd | AttrKey | AttrVal | Text
  84. - value string
  85. - ns string
  86. SEE: http://www.xml.com/pub/a/98/10/guide0.html?page=3#ENTDECL
  87. The following are skipped when parsing:
  88. - External Entities (from external file)
  89. - Notation Declaration e.g. <!NOTATION GIF87A SYSTEM "GIF">
  90. - Entity Declarations & References
  91. - XML Declaration (assume UTF-8)
  92. - XML Directive i.e. <! ... >
  93. - Other Declarations: Notation, etc.
  94. - Comment
  95. - Processing Instruction
  96. - schema / DTD for validation:
  97. We are not a VALIDATING parser. Validation is done elsewhere.
  98. However, some parts of the DTD internal subset are used (SEE BELOW).
  99. For Attribute List Declarations e.g.
  100. <!ATTLIST foo:oldjoke name ID #REQUIRED label CDATA #IMPLIED status ( funny | notfunny ) 'funny' >
  101. We considered using the ATTLIST to get "default" value, but not to validate the contents. (VETOED)
  102. The following XML features are supported
  103. - Namespace
  104. - Element
  105. - Attribute
  106. - cdata
  107. - Unicode escape
  108. The following DTD (when as an internal sub-set) features are supported:
  109. - Internal Entities e.g.
  110. <!ELEMENT burns "ugorji is cool" > AND entities for the set: [<>&"']
  111. - Parameter entities e.g.
  112. <!ENTITY % personcontent "ugorji is cool"> <!ELEMENT burns (%personcontent;)*>
  113. At decode time, a structure containing the following is kept
  114. - namespace mapping
  115. - default attribute values
  116. - all internal entities (<>&"' and others written in the document)
  117. When decode starts, it parses XML namespace declarations and creates a map in the
  118. xmlDecDriver. While parsing, that map continuously gets updated.
  119. The only problem happens when a namespace declaration happens on the node that it defines.
  120. e.g. <hn:name xmlns:hn="http://www.ugorji.net" >
  121. To handle this, each Element must be fully parsed at a time,
  122. even if it amounts to multiple tokens which are returned one at a time on request.
  123. xmlns is a special attribute name.
  124. - It is used to define namespaces, including the default
  125. - It is never returned as an AttrKey or AttrVal.
  126. *We may decide later to allow user to use it e.g. you want to parse the xmlns mappings into a field.*
  127. Number, bool, null, mapKey, etc can all be decoded from any xmlToken.
  128. This accommodates map[int]string for example.
  129. It should be possible to create a schema from the types,
  130. or vice versa (generate types from schema with appropriate tags).
  131. This is however out-of-scope from this parsing project.
  132. We should write all namespace information at the first point that it is referenced in the tree,
  133. and use the mapping for all child nodes and attributes. This means that state is maintained
  134. at a point in the tree. This also means that calls to Decode or MustDecode will reset some state.
  135. When decoding, it is important to keep track of entity references and default attribute values.
  136. It seems these can only be stored in the DTD components. We should honor them when decoding.
  137. Configuration for XMLHandle will look like this:
  138. XMLHandle
  139. DefaultNS string
  140. // Encoding:
  141. NS map[string]string // ns URI to key, used for encoding
  142. // Decoding: in case ENTITY declared in external schema or dtd, store info needed here
  143. Entities map[string]string // map of entity rep to character
  144. During encode, if a namespace mapping is not defined for a namespace found on a struct,
  145. then we create a mapping for it using nsN (where N is 1..1000000, and doesn't conflict
  146. with any other namespace mapping).
  147. Note that different fields in a struct can have different namespaces.
  148. However, all fields will default to the namespace on the _struct field (if defined).
  149. An XML document is a name, a map of attributes and a list of children.
  150. Consequently, we cannot "DecodeNaked" into a map[string]interface{} (for example).
  151. We have to "DecodeNaked" into something that resembles XML data.
  152. To support DecodeNaked (decode into nil interface{}), we have to define some "supporting" types:
  153. type Name struct { // Preferred. Less allocations due to conversions.
  154. Local string
  155. Space string
  156. }
  157. type Element struct {
  158. Name Name
  159. Attrs map[Name]string
  160. Children []interface{} // each child is either *Element or string
  161. }
  162. Only two "supporting" types are exposed for XML: Name and Element.
  163. // ------------------
  164. We considered 'type Name string' where Name is like "Space Local" (space-separated).
  165. We decided against it, because each creation of a name would lead to
  166. double allocation (first convert []byte to string, then concatenate them into a string).
  167. The benefit is that it is faster to read Attrs from a map. But given that Element is a value
  168. object, we want to eschew methods and have public exposed variables.
  169. We also considered the following, where xml types were not value objects, and we used
  170. intelligent accessor methods to extract information and for performance.
  171. *** WE DECIDED AGAINST THIS. ***
  172. type Attr struct {
  173. Name Name
  174. Value string
  175. }
  176. // Element is a ValueObject: There are no accessor methods.
  177. // Make element self-contained.
  178. type Element struct {
  179. Name Name
  180. attrsMap map[string]string // where key is "Space Local"
  181. attrs []Attr
  182. childrenT []string
  183. childrenE []Element
  184. childrenI []int // each child is a index into T or E.
  185. }
  186. func (x *Element) child(i) interface{} // returns string or *Element
  187. // ------------------
  188. Per XML spec and our default handling, white space is always treated as
  189. insignificant between elements, except in a text node. The xml:space='preserve'
  190. attribute is ignored.
  191. **Note: there is no xml: namespace. The xml: attributes were defined before namespaces.**
  192. **So treat them as just "directives" that should be interpreted to mean something**.
  193. On encoding, we support indenting aka prettifying markup in the same way we support it for json.
  194. A document or element can only be encoded/decoded from/to a struct. In this mode:
  195. - struct name maps to element name (or tag-info from _struct field)
  196. - fields are mapped to child elements or attributes
  197. A map is either encoded as attributes on current element, or as a set of child elements.
  198. Maps are encoded as attributes iff their keys and values are primitives (number, bool, string).
  199. A list is encoded as a set of child elements.
  200. Primitives (number, bool, string) are encoded as an element, attribute or text
  201. depending on the context.
  202. Extensions must encode themselves as a text string.
  203. Encoding is tough, specifically when encoding mappings, because we need to encode
  204. as either attribute or element. To do this, we need to default to encoding as attributes,
  205. and then let Encoder inform the Handle when to start encoding as nodes.
  206. i.e. Encoder does something like:
  207. h.EncodeMapStart()
  208. h.Encode(), h.Encode(), ...
  209. h.EncodeMapNotAttrSignal() // this is not a bool, because it's a signal
  210. h.Encode(), h.Encode(), ...
  211. h.EncodeEnd()
  212. Only XMLHandle understands this, and will set itself to start encoding as elements.
  213. This support extends to maps. For example, if a struct field is a map, and it has
  214. the struct tag signifying it should be attr, then all its fields are encoded as attributes.
  215. e.g.
  216. type X struct {
  217. M map[string]int `codec:"m,attr"` // encode keys as attributes named
  218. }
  219. Question:
  220. - if encoding a map, what if map keys have spaces in them???
  221. Then they cannot be attributes or child elements. Error.
  222. Options to consider adding later:
  223. - For attribute values, normalize by trimming beginning and ending white space,
  224. and converting every white space sequence to a single space.
  225. - ATTLIST restrictions are enforced.
  226. e.g. default value of xml:space, skipping xml:XYZ style attributes, etc.
  227. - Consider supporting NON-STRICT mode (e.g. to handle HTML parsing).
  228. Some elements e.g. br, hr, etc need not close and should be auto-closed
  229. ... (see http://www.w3.org/TR/html4/loose.dtd)
  230. An expansive set of entities are pre-defined.
  231. - Have easy way to create a HTML parser:
  232. add a HTML() method to XMLHandle, that will set Strict=false, specify AutoClose,
  233. and add HTML Entities to the list.
  234. - Support validating element/attribute XMLName before writing it.
  235. Keep this behind a flag, which is set to false by default (for performance).
  236. type XMLHandle struct {
  237. CheckName bool
  238. }
  239. Misc:
  240. ROADMAP (1 weeks):
  241. - build encoder (1 day)
  242. - build decoder (based off xmlParser) (1 day)
  243. - implement xmlParser (2 days).
  244. Look at encoding/xml for inspiration.
  245. - integrate and TEST (1 days)
  246. - write article and post it (1 day)
  247. // ---------- MORE NOTES FROM 2017-11-30 ------------
  248. when parsing
  249. - parse the attributes first
  250. - then parse the nodes
  251. basically:
  252. - if encoding a field: we use the field name for the wrapper
  253. - if encoding a non-field, then just use the element type name
  254. map[string]string ==> <map><key>abc</key><value>val</value></map>... or
  255. <map key="abc">val</map>... OR
  256. <key1>val1</key1><key2>val2</key2>... <- PREFERED
  257. []string ==> <string>v1</string><string>v2</string>...
  258. string v1 ==> <string>v1</string>
  259. bool true ==> <bool>true</bool>
  260. float 1.0 ==> <float>1.0</float>
  261. ...
  262. F1 map[string]string ==> <F1><key>abc</key><value>val</value></F1>... OR
  263. <F1 key="abc">val</F1>... OR
  264. <F1><abc>val</abc>...</F1> <- PREFERED
  265. F2 []string ==> <F2>v1</F2><F2>v2</F2>...
  266. F3 bool ==> <F3>true</F3>
  267. ...
  268. - a scalar is encoded as:
  269. (value) of type T ==> <T><value/></T>
  270. (value) of field F ==> <F><value/></F>
  271. - A kv-pair is encoded as:
  272. (key,value) ==> <map><key><value/></key></map> OR <map key="value">
  273. (key,value) of field F ==> <F><key><value/></key></F> OR <F key="value">
  274. - A map or struct is just a list of kv-pairs
  275. - A list is encoded as sequences of same node e.g.
  276. <F1 key1="value11">
  277. <F1 key2="value12">
  278. <F2>value21</F2>
  279. <F2>value22</F2>
  280. - we may have to singularize the field name, when entering into xml,
  281. and pluralize them when encoding.
  282. - bi-directional encode->decode->encode is not a MUST.
  283. even encoding/xml cannot decode correctly what was encoded:
  284. see https://play.golang.org/p/224V_nyhMS
  285. func main() {
  286. fmt.Println("Hello, playground")
  287. v := []interface{}{"hello", 1, true, nil, time.Now()}
  288. s, err := xml.Marshal(v)
  289. fmt.Printf("err: %v, \ns: %s\n", err, s)
  290. var v2 []interface{}
  291. err = xml.Unmarshal(s, &v2)
  292. fmt.Printf("err: %v, \nv2: %v\n", err, v2)
  293. type T struct {
  294. V []interface{}
  295. }
  296. v3 := T{V: v}
  297. s, err = xml.Marshal(v3)
  298. fmt.Printf("err: %v, \ns: %s\n", err, s)
  299. var v4 T
  300. err = xml.Unmarshal(s, &v4)
  301. fmt.Printf("err: %v, \nv4: %v\n", err, v4)
  302. }
  303. Output:
  304. err: <nil>,
  305. s: <string>hello</string><int>1</int><bool>true</bool><Time>2009-11-10T23:00:00Z</Time>
  306. err: <nil>,
  307. v2: [<nil>]
  308. err: <nil>,
  309. s: <T><V>hello</V><V>1</V><V>true</V><V>2009-11-10T23:00:00Z</V></T>
  310. err: <nil>,
  311. v4: {[<nil> <nil> <nil> <nil>]}
  312. -
  313. */
  314. // ----------- PARSER -------------------
  315. type xmlTokenType uint8
  316. const (
  317. _ xmlTokenType = iota << 1
  318. xmlTokenElemStart
  319. xmlTokenElemEnd
  320. xmlTokenAttrKey
  321. xmlTokenAttrVal
  322. xmlTokenText
  323. )
  324. type xmlToken struct {
  325. Type xmlTokenType
  326. Value string
  327. Namespace string // blank for AttrVal and Text
  328. }
  329. type xmlParser struct {
  330. r decReader
  331. toks []xmlToken // list of tokens.
  332. ptr int // ptr into the toks slice
  333. done bool // nothing else to parse. r now returns EOF.
  334. }
  335. func (x *xmlParser) next() (t *xmlToken) {
  336. // once x.done, or x.ptr == len(x.toks) == 0, then return nil (to signify finish)
  337. if !x.done && len(x.toks) == 0 {
  338. x.nextTag()
  339. }
  340. // parses one element at a time (into possible many tokens)
  341. if x.ptr < len(x.toks) {
  342. t = &(x.toks[x.ptr])
  343. x.ptr++
  344. if x.ptr == len(x.toks) {
  345. x.ptr = 0
  346. x.toks = x.toks[:0]
  347. }
  348. }
  349. return
  350. }
  351. // nextTag will parses the next element and fill up toks.
  352. // It set done flag if/once EOF is reached.
  353. func (x *xmlParser) nextTag() {
  354. // TODO: implement.
  355. }
  356. // ----------- ENCODER -------------------
  357. type xmlEncDriver struct {
  358. e *Encoder
  359. w encWriter
  360. h *XMLHandle
  361. b [64]byte // scratch
  362. bs []byte // scratch
  363. // s jsonStack
  364. noBuiltInTypes
  365. }
  366. // ----------- DECODER -------------------
  367. type xmlDecDriver struct {
  368. d *Decoder
  369. h *XMLHandle
  370. r decReader // *bytesDecReader decReader
  371. ct valueType // container type. one of unset, array or map.
  372. bstr [8]byte // scratch used for string \UXXX parsing
  373. b [64]byte // scratch
  374. // wsSkipped bool // whitespace skipped
  375. // s jsonStack
  376. noBuiltInTypes
  377. }
  378. // DecodeNaked will decode into an XMLNode
  379. // XMLName is a value object representing a namespace-aware NAME
  380. type XMLName struct {
  381. Local string
  382. Space string
  383. }
  384. // XMLNode represents a "union" of the different types of XML Nodes.
  385. // Only one of fields (Text or *Element) is set.
  386. type XMLNode struct {
  387. Element *Element
  388. Text string
  389. }
  390. // XMLElement is a value object representing an fully-parsed XML element.
  391. type XMLElement struct {
  392. Name Name
  393. Attrs map[XMLName]string
  394. // Children is a list of child nodes, each being a *XMLElement or string
  395. Children []XMLNode
  396. }
  397. // ----------- HANDLE -------------------
  398. type XMLHandle struct {
  399. BasicHandle
  400. textEncodingType
  401. DefaultNS string
  402. NS map[string]string // ns URI to key, for encoding
  403. Entities map[string]string // entity representation to string, for encoding.
  404. }
  405. func (h *XMLHandle) newEncDriver(e *Encoder) encDriver {
  406. return &xmlEncDriver{e: e, w: e.w, h: h}
  407. }
  408. func (h *XMLHandle) newDecDriver(d *Decoder) decDriver {
  409. // d := xmlDecDriver{r: r.(*bytesDecReader), h: h}
  410. hd := xmlDecDriver{d: d, r: d.r, h: h}
  411. hd.n.bytes = d.b[:]
  412. return &hd
  413. }
  414. func (h *XMLHandle) SetInterfaceExt(rt reflect.Type, tag uint64, ext InterfaceExt) (err error) {
  415. return h.SetExt(rt, tag, &setExtWrapper{i: ext})
  416. }
  417. var _ decDriver = (*xmlDecDriver)(nil)
  418. var _ encDriver = (*xmlEncDriver)(nil)