另客网go项目公用的代码库

xml.go 18KB

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