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