xml.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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:"xid|http://ugorji.net/x-namespace id,omitempty,toarray,attr,cdata"
  28. }
  29. Based on this, we encode
  30. - fields as elements, BUT
  31. encode as attributes if struct tag contains ",attr" and is a scalar (bool, number or string)
  32. - text as entity-escaped text, BUT encode as CDATA if struct tag contains ",cdata".
  33. In this mode, we only encode as attribute if ",attr" is found, and only encode as CDATA
  34. if ",cdata" is found in the struct tag.
  35. To handle namespaces:
  36. - XMLHandle is denoted as being namespace-aware.
  37. Consequently, we WILL use the ns:name pair to encode and decode if defined, else use the plain name.
  38. - *Encoder and *Decoder know whether the Handle "prefers" namespaces.
  39. - add *Encoder.getEncName(*structFieldInfo).
  40. No one calls *structFieldInfo.indexForEncName directly anymore
  41. - add *Decoder.getStructFieldInfo(encName string) // encName here is either like abc, or h1:nsabc
  42. No one accesses .encName anymore except in
  43. - let encode.go and decode.go use these (for consistency)
  44. - only problem exists for gen.go, where we create a big switch on encName.
  45. Now, we also have to add a switch on strings.endsWith(kName, encNsName)
  46. - gen.go will need to have many more methods, and then double-on the 2 switch loops like:
  47. switch k {
  48. case "abc" : x.abc()
  49. case "def" : x.def()
  50. default {
  51. switch {
  52. case !nsAware: panic(...)
  53. case strings.endsWith("nsabc"): x.abc()
  54. case strings.endsWith("nsdef"): x.def()
  55. default: panic(...)
  56. }
  57. }
  58. }
  59. The structure below accomodates this:
  60. type typeInfo struct {
  61. sfi []*structFieldInfo // sorted by encName
  62. sfins // sorted by namespace
  63. sfia // sorted, to have those with attributes at the top. Needed to write XML appropriately.
  64. sfip // unsorted
  65. }
  66. type structFieldInfo struct {
  67. encName
  68. nsEncName
  69. ns string
  70. attr bool
  71. cdata bool
  72. }
  73. indexForEncName is now an internal helper function that takes a sorted array
  74. (one of ti.sfins or ti.sfi). It is only used by *Encoder.getStructFieldInfo(...)
  75. There will be a separate parser from the builder.
  76. The parser will have a method: next() xmlToken method.
  77. xmlToken has fields:
  78. - type uint8: 0 | ElementStart | ElementEnd | AttrKey | AttrVal | Text
  79. - value string
  80. - ns string
  81. SEE: http://www.xml.com/pub/a/98/10/guide0.html?page=3#ENTDECL
  82. The following are skipped when parsing:
  83. - External Entities (from external file)
  84. - Notation Declaration e.g. <!NOTATION GIF87A SYSTEM "GIF">
  85. - Entity Declarations & References
  86. - XML Declaration (assume UTF-8)
  87. - XML Directive i.e. <! ... >
  88. - Other Declarations: Notation, etc.
  89. - Comment
  90. - Processing Instruction
  91. - schema / DTD for validation:
  92. We are not a VALIDATING parser. Validation is done elsewhere.
  93. However, some parts of the DTD internal subset are used (SEE BELOW).
  94. For Attribute List Declarations e.g.
  95. <!ATTLIST foo:oldjoke name ID #REQUIRED label CDATA #IMPLIED status ( funny | notfunny ) 'funny' >
  96. We considered using the ATTLIST to get "default" value, but not to validate the contents. (VETOED)
  97. The following XML features are supported
  98. - Namespace
  99. - Element
  100. - Attribute
  101. - cdata
  102. - Unicode escape
  103. The following DTD (when as an internal sub-set) features are supported:
  104. - Internal Entities e.g.
  105. <!ELEMENT burns "ugorji is cool" > AND entities for the set: [<>&"']
  106. - Parameter entities e.g.
  107. <!ENTITY % personcontent "ugorji is cool"> <!ELEMENT burns (%personcontent;)*>
  108. At decode time, a structure containing the following is kept
  109. - namespace mapping
  110. - default attribute values
  111. - all internal entities (<>&"' and others written in the document)
  112. When decode starts, it parses XML namespace declarations and creates a map in the
  113. xmlDecDriver. While parsing, that map continously gets updated.
  114. The only problem happens when a namespace declaration happens on the node that it defines.
  115. e.g. <hn:name xmlns:hn="http://www.ugorji.net" >
  116. To handle this, each Element must be fully parsed at a time,
  117. even if it amounts to multiple tokens which are returned one at a time on request.
  118. xmlns is a special attribute name.
  119. - It is used to define namespaces, including the default
  120. - It is never returned as an AttrKey or AttrVal.
  121. *We may decide later to allow user to use it e.g. you want to parse the xmlns mappings into a field.*
  122. Number, bool, null, mapKey, etc can all be decoded from any xmlToken.
  123. This accomodates map[int]string for example.
  124. It should be possible to create a schema from the types,
  125. or vice versa (generate types from schema with appropriate tags).
  126. This is however out-of-scope from this parsing project.
  127. We should write all namespace information at the first point that it is referenced in the tree,
  128. and use the mapping for all child nodes and attributes. This means that state is maintained
  129. at a point in the tree. This also means that calls to Decode or MustDecode will reset some state.
  130. When decoding, it is important to keep track of entity references and default attribute values.
  131. It seems these can only be stored in the DTD components. We should honor them when decoding.
  132. Configuration for XMLHandle will look like this:
  133. XMLHandle
  134. DefaultNS string
  135. // Encoding:
  136. NS map[string]string // ns URI to key, used for encoding
  137. // Decoding: in case ENTITY declared in external schema or dtd, store info needed here
  138. Entities map[string]string // map of entity rep to character
  139. During encode, if a namespace mapping is not defined for a namespace found on a struct,
  140. then we create a mapping for it using nsN (where N is 1..1000000, and doesn't conflict
  141. with any other namespace mapping).
  142. Note that different fields in a struct can have different namespaces.
  143. However, all fields will default to the namespace on the _struct field (if defined).
  144. An XML document is a name, a map of attributes and a list of children.
  145. Consequently, we cannot "DecodeNaked" into a map[string]interface{} (for example).
  146. We have to "DecodeNaked" into something that resembles XML data.
  147. To support DecodeNaked (decode into nil interface{}), we have to define some "supporting" types:
  148. type Name struct { // Prefered. Less allocations due to conversions.
  149. Local string
  150. Space string
  151. }
  152. type Element struct {
  153. Name Name
  154. Attrs map[Name]string
  155. Children []interface{} // each child is either *Element or string
  156. }
  157. Only two "supporting" types are exposed for XML: Name and Element.
  158. // ------------------
  159. We considered 'type Name string' where Name is like "Space Local" (space-separated).
  160. We decided against it, because each creation of a name would lead to
  161. double allocation (first convert []byte to string, then concatenate them into a string).
  162. The benefit is that it is faster to read Attrs from a map. But given that Element is a value
  163. object, we want to eschew methods and have public exposed variables.
  164. We also considered the following, where xml types were not value objects, and we used
  165. intelligent accessor methods to extract information and for performance.
  166. *** WE DECIDED AGAINST THIS. ***
  167. type Attr struct {
  168. Name Name
  169. Value string
  170. }
  171. // Element is a ValueObject: There are no accessor methods.
  172. // Make element self-contained.
  173. type Element struct {
  174. Name Name
  175. attrsMap map[string]string // where key is "Space Local"
  176. attrs []Attr
  177. childrenT []string
  178. childrenE []Element
  179. childrenI []int // each child is a index into T or E.
  180. }
  181. func (x *Element) child(i) interface{} // returns string or *Element
  182. // ------------------
  183. Per XML spec and our default handling, white space is insignificant between elements,
  184. specifically between parent-child or siblings. White space occuring alone between start
  185. and end element IS significant. However, if xml:space='preserve', then we 'preserve'
  186. all whitespace. This is more critical when doing a DecodeNaked, but MAY not be as critical
  187. when decoding into a typed value.
  188. **Note: there is no xml: namespace. The xml: attributes were defined before namespaces.**
  189. **So treat them as just "directives" that should be interpreted to mean something**.
  190. On encoding, we don't add any prettifying markup (indenting, etc).
  191. A document or element can only be encoded/decoded from/to a struct. In this mode:
  192. - struct name maps to element name (or tag-info from _struct field)
  193. - fields are mapped to child elements or attributes
  194. A map is either encoded as attributes on current element, or as a set of child elements.
  195. Maps are encoded as attributes iff their keys and values are primitives (number, bool, string).
  196. A list is encoded as a set of child elements.
  197. Primitives (number, bool, string) are encoded as an element, attribute or text
  198. depending on the context.
  199. Extensions must encode themselves as a text string.
  200. Encoding is tough, specifically when encoding mappings, because we need to encode
  201. as either attribute or element. To do this, we need to default to encoding as attributes,
  202. and then let Encoder inform the Handle when to start encoding as nodes.
  203. i.e. Encoder does something like:
  204. h.EncodeMapStart()
  205. h.Encode(), h.Encode(), ...
  206. h.EncodeMapNotAttrSignal() // this is not a bool, because it's a signal
  207. h.Encode(), h.Encode(), ...
  208. h.EncodeEnd()
  209. Only XMLHandle understands this, and will set itself to start encoding as elements.
  210. This support extends to maps. For example, if a struct field is a map, and it has
  211. the struct tag signifying it should be attr, then all its fields are encoded as attributes.
  212. e.g.
  213. type X struct {
  214. M map[string]int `codec:"m,attr"` // encode as attributes
  215. }
  216. Question:
  217. - if encoding a map, what if map keys have spaces in them???
  218. Then they cannot be attributes or child elements. Error.
  219. Misc:
  220. - For attribute values, normalize by trimming beginning and ending white space,
  221. and converting every white space sequence to a single space.
  222. - ATTLIST restrictions are enforced.
  223. e.g. default value of xml:space, skipping xml:XYZ style attributes, etc.
  224. - Consider supporting NON-STRICT mode (e.g. to handle HTML parsing).
  225. Some elements e.g. br, hr, etc need not close and should be auto-closed
  226. ... (see http://www.w3.org/TR/html4/loose.dtd)
  227. An expansive set of entities are pre-defined.
  228. - Have easy way to create a HTML parser:
  229. add a HTML() method to XMLHandle, that will set Strict=false, specify AutoClose,
  230. and add HTML Entities to the list.
  231. - Support validating element/attribute XMLName before writing it.
  232. Keep this behind a flag, which is set to false by default (for performance).
  233. type XMLHandle struct {
  234. CheckName bool
  235. }
  236. ROADMAP (1 weeks):
  237. - build encoder (1 day)
  238. - build decoder (based off xmlParser) (1 day)
  239. - implement xmlParser (2 days).
  240. Look at encoding/xml for inspiration.
  241. - integrate and TEST (1 days)
  242. - write article and post it (1 day)
  243. */
  244. // ----------- PARSER -------------------
  245. type xmlTokenType uint8
  246. const (
  247. _ xmlTokenType = iota << 1
  248. xmlTokenElemStart
  249. xmlTokenElemEnd
  250. xmlTokenAttrKey
  251. xmlTokenAttrVal
  252. xmlTokenText
  253. )
  254. type xmlToken struct {
  255. Type xmlTokenType
  256. Value string
  257. Namespace string // blank for AttrVal and Text
  258. }
  259. type xmlParser struct {
  260. r decReader
  261. toks []xmlToken // list of tokens.
  262. ptr int // ptr into the toks slice
  263. done bool // nothing else to parse. r now returns EOF.
  264. }
  265. func (x *xmlParser) next() (t *xmlToken) {
  266. // once x.done, or x.ptr == len(x.toks) == 0, then return nil (to signify finish)
  267. if !x.done && len(x.toks) == 0 {
  268. x.nextTag()
  269. }
  270. // parses one element at a time (into possible many tokens)
  271. if x.ptr < len(x.toks) {
  272. t = &(x.toks[x.ptr])
  273. x.ptr++
  274. if x.ptr == len(x.toks) {
  275. x.ptr = 0
  276. x.toks = x.toks[:0]
  277. }
  278. }
  279. return
  280. }
  281. // nextTag will parses the next element and fill up toks.
  282. // It set done flag if/once EOF is reached.
  283. func (x *xmlParser) nextTag() {
  284. // TODO: implement.
  285. }
  286. // ----------- ENCODER -------------------
  287. type xmlEncDriver struct {
  288. e *Encoder
  289. w encWriter
  290. h *XMLHandle
  291. b [64]byte // scratch
  292. bs []byte // scratch
  293. // s jsonStack
  294. noBuiltInTypes
  295. }
  296. // ----------- DECODER -------------------
  297. type xmlDecDriver struct {
  298. d *Decoder
  299. h *XMLHandle
  300. r decReader // *bytesDecReader decReader
  301. ct valueType // container type. one of unset, array or map.
  302. bstr [8]byte // scratch used for string \UXXX parsing
  303. b [64]byte // scratch
  304. // wsSkipped bool // whitespace skipped
  305. // s jsonStack
  306. noBuiltInTypes
  307. }
  308. // DecodeNaked will decode into an XMLNode
  309. // XMLName is a value object representing a namespace-aware NAME
  310. type XMLName struct {
  311. Local string
  312. Space string
  313. }
  314. // XMLNode represents a "union" of the different types of XML Nodes.
  315. // Only one of fields (Text or *Element) is set.
  316. type XMLNode struct {
  317. Element *Element
  318. Text string
  319. }
  320. // XMLElement is a value object representing an fully-parsed XML element.
  321. type XMLElement struct {
  322. Name Name
  323. Attrs map[XMLName]string
  324. // Children is a list of child nodes, each being a *XMLElement or string
  325. Children []XMLNode
  326. }
  327. // ----------- HANDLE -------------------
  328. type XMLHandle struct {
  329. BasicHandle
  330. textEncodingType
  331. DefaultNS string
  332. NS map[string]string // ns URI to key, for encoding
  333. Entities map[string]string // entity representation to string, for encoding.
  334. }
  335. func (h *XMLHandle) newEncDriver(e *Encoder) encDriver {
  336. return &xmlEncDriver{e: e, w: e.w, h: h}
  337. }
  338. func (h *XMLHandle) newDecDriver(d *Decoder) decDriver {
  339. // d := xmlDecDriver{r: r.(*bytesDecReader), h: h}
  340. hd := xmlDecDriver{d: d, r: d.r, h: h}
  341. hd.n.bytes = d.b[:]
  342. return &hd
  343. }
  344. func (h *XMLHandle) SetInterfaceExt(rt reflect.Type, tag uint64, ext InterfaceExt) (err error) {
  345. return h.SetExt(rt, tag, &setExtWrapper{i: ext})
  346. }
  347. var _ decDriver = (*xmlDecDriver)(nil)
  348. var _ encDriver = (*xmlEncDriver)(nil)