Repository navigation
Expand file tree
/
Copy pathPrintXML.cpp
More file actions
1407 lines (1298 loc) · 43.4 KB
/
Copy pathPrintXML.cpp
File metadata and controls
1407 lines (1298 loc) · 43.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright © 2026 Ivyware Pty Ltd, Khrustal & Mann
// MELBOURNE, VICTORIA, AUSTRALIA, 3000
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// PrintXML - XML projection of a P3PmsgItem tree, and the reader that takes
// one back. See PrintXML.h for the mapping and for why each half of it is
// what it is.
//
#include "stdafx.h"
#include "PrintXML.h"
#include "MsgValue.h"
#include "../Msgcore/Msgexception.h"
///////////////////////////////////////////////////////////////////////
// The reserved vocabulary
// NOTES: All of it under one prefix, and the prefix is one no item name can
// carry: P3Pmsg_IsValidItemname refuses the colon outright. That is
// what puts these names in a space of their own without a single
// collision test anywhere in the file.
// : A URN rather than an http URL. A namespace name is an identifier and
// nothing fetches it, and an http one invites a reader to try -
// earning a 404 that says nothing about whether the document is valid.
#define XMLNS_P2P _T("urn:ivyware:msgcore:p2p")
#define XML_PREFIX _T("p2p:")
#define XML_TAG_ITEM _T("p2p:item")
#define XML_TAG_VALUE _T("p2p:value")
#define XML_ATTR_TYPE _T("p2p:type")
#define XML_ATTR_NULL _T("p2p:null")
#define XML_ATTR_NAME _T("p2p:name")
#define XML_ATTR_ATTR _T("p2p:attr")
#define XML_ATTR_LIST _T("p2p:list")
#define XML_ATTR_VECT _T("p2p:vect")
///////////////////////////////////////////////////////////////////////
// File-local helpers
//
// Whether strText is a number as JSON spells one.
// NOTES: JSON's grammar rather than a looser one, and the leading-zero rule is
// the reason to borrow it: "007" is a part number, a postcode or an
// account, and every one of them is ruined by coming back as 7. XML has
// no types of its own to settle this, so the question only arises with
// SetTypes(false) - with types on, p2p:type has already answered it.
//
static bool
PrintXML_IsNumber ( const CString& strText )
{
const int nLength = strText.GetLength ( );
int nPos = 0;
if ( nLength == 0 )
return false;
if ( strText[nPos] == _T('-') )
nPos++;
const int nIntFrom = nPos;
while ( nPos < nLength && strText[nPos] >= _T('0') && strText[nPos] <= _T('9') )
nPos++;
if ( nPos == nIntFrom )
return false;
// A leading zero may only stand alone.
if ( strText[nIntFrom] == _T('0') && nPos - nIntFrom > 1 )
return false;
if ( nPos < nLength && strText[nPos] == _T('.') )
{
nPos++;
const int nFracFrom = nPos;
while ( nPos < nLength && strText[nPos] >= _T('0') && strText[nPos] <= _T('9') )
nPos++;
if ( nPos == nFracFrom )
return false;
}
if ( nPos < nLength && ( strText[nPos] == _T('e') || strText[nPos] == _T('E') ) )
{
nPos++;
if ( nPos < nLength && ( strText[nPos] == _T('+') || strText[nPos] == _T('-') ) )
nPos++;
const int nExpFrom = nPos;
while ( nPos < nLength && strText[nPos] >= _T('0') && strText[nPos] <= _T('9') )
nPos++;
if ( nPos == nExpFrom )
return false;
}
return nPos == nLength;
}
static bool
PrintXML_IsSpace ( TCHAR c )
{
// The four XML calls whitespace, and no others.
return c == _T(' ') || c == _T('\t') || c == _T('\r') || c == _T('\n');
}
static bool
PrintXML_IsBlank ( const CString& strText )
{
for ( int i = 0; i < strText.GetLength ( ); i++ )
if ( !PrintXML_IsSpace ( strText[i] ) )
return false;
return true;
}
//
// Fills a scalar MsgValue from the text of an element.
// NOTES: The KIND is inferred from the text and the TYPE is carried alongside
// it, because ParseScalar prefers the type and falls back to the kind -
// so the same tree is right whether or not the document had types. The
// one thing the kind must get right when there IS a type is that it is
// not Value_Null, which is what would make ParseScalar ignore the type.
//
static void
PrintXML_SetScalar ( MsgValue& oValue, const CString& strText,
LPCTSTR lpszType, bool bNull )
{
if ( bNull )
{
oValue.SetScalar ( MsgPrint::Value_Null, _T("") );
return;
}
MsgPrint::ValueKind_e eKind = MsgPrint::Value_String;
if ( strText.Compare ( _T("true") ) == 0 || strText.Compare ( _T("false") ) == 0 )
eKind = MsgPrint::Value_Bool;
else if ( PrintXML_IsNumber ( strText ) )
eKind = MsgPrint::Value_Number;
oValue.SetScalar ( eKind, (LPCTSTR)strText );
if ( lpszType )
oValue.SetType ( lpszType );
}
///////////////////////////////////////////////////////////////////////
// Constructors and destructor
PrintXML::PrintXML ( ) noexcept
{
}
PrintXML::PrintXML ( LPCTSTR lpszText )
{
// SetText, not an assignment to m_strText: it is the one place the held
// text and the error state are kept in step, and a renderer built from a
// document has to start with no error exactly as SetText leaves one.
SetText ( lpszText );
}
PrintXML::PrintXML ( const PrintXML& rhs )
: MsgPrint ( rhs )
{
m_bDeclaration = rhs.m_bDeclaration;
m_bTypes = rhs.m_bTypes;
}
PrintXML::~PrintXML ( )
{
}
///////////////////////////////////////////////////////////////////////
// Operators
PrintXML&
PrintXML::operator = ( const PrintXML& rhs )
{
if ( this == &rhs )
return *this;
MsgPrint::operator = ( rhs );
m_bDeclaration = rhs.m_bDeclaration;
m_bTypes = rhs.m_bTypes;
return *this;
}
///////////////////////////////////////////////////////////////////////
// Rendering
//
// Renders oItem and everything beneath it as an XML document, REPLACING
// whatever this renderer held.
//
// Parameters: P3PmsgItem& oItem
// Manager, item, list or vector to render
//
// Returns: MsgPrint&
// This renderer, so the text can be read from the expression
//
MsgPrint&
PrintXML::Render ( P3PmsgItem& oItem )
{
m_strText.Empty ( );
try
{
if ( m_bDeclaration )
{
Append ( _T("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") );
AppendBreak ( 0 );
}
// The root element names the node and carries the namespace
// declaration. There is no unrooted form to offer: an XML document IS
// one element, and one without a name is not a document.
RenderNode ( oItem, oItem.c_name ( ), false, true, 0 );
return *this;
}
// A throw from the traversal - not from a cell, which RenderScalar absorbs
// by itself - leaves a half-built document, and half an XML document is
// worse than none: every unclosed element reports as an error at the end
// of the file rather than where the trouble was. Empty it instead, so
// IsEmpty() is the answer to "did this work".
catch_pP2Pevent_Cancel
catch_ALL_Cancel
m_strText.Empty ( );
return *this;
}
///////////////////////////////////////////////////////////////////////
// Properties
bool
PrintXML::SetDeclaration ( bool bDeclaration ) noexcept
{
const bool bPrevious = m_bDeclaration;
m_bDeclaration = bDeclaration;
return bPrevious;
}
bool
PrintXML::GetDeclaration ( ) const noexcept
{
return m_bDeclaration;
}
bool
PrintXML::SetTypes ( bool bTypes ) noexcept
{
const bool bPrevious = m_bTypes;
m_bTypes = bTypes;
return bPrevious;
}
bool
PrintXML::GetTypes ( ) const noexcept
{
return m_bTypes;
}
///////////////////////////////////////////////////////////////////////
// Implementation
//
// Emits one complete element - its start tag, its content and its end tag.
//
// Parameters: P3PmsgItem& oItem
// Node to render
//
// LPCTSTR lpszName
// Its Msgcore name, or nullptr for an unnamed entry of a vector
//
// bool bAttr
// Whether it is one of its parent's attributes
//
// bool bRoot
// Whether it carries the namespace declaration
//
// int nDepth
// Nesting level, for the indent
//
void
PrintXML::RenderNode ( P3PmsgItem& oItem, LPCTSTR lpszName, bool bAttr,
bool bRoot, int nDepth )
{
const CString strTag = lpszName ? XmlName ( lpszName ) : CString ( XML_TAG_ITEM );
// The start tag, up to but not including its closing angle bracket -
// which of the three ways it closes is not known until the content is.
CString strOpen ( _T("<") );
strOpen += strTag;
if ( bRoot )
{
strOpen += _T(" xmlns:p2p=\"");
strOpen += XMLNS_P2P;
strOpen += _T("\"");
}
// Only when the two differ, which is the common case not happening: an
// ordinary name is its own tag and says so by the attribute's absence.
if ( lpszName && strTag.Compare ( lpszName ) != 0 )
{
strOpen += _T(" ");
strOpen += XML_ATTR_NAME;
strOpen += _T("=\"");
strOpen += EscapeAttr ( lpszName );
strOpen += _T("\"");
}
if ( bAttr )
{
strOpen += _T(" ");
strOpen += XML_ATTR_ATTR;
strOpen += _T("=\"true\"");
}
if ( nDepth > m_nDepthMax )
{
// The ceiling, not a structural case. A tree cannot reach it; a store
// whose links were corrupted can, and an unbounded descent on one is a
// stack overflow rather than a diagnostic.
Append ( (LPCTSTR)strOpen );
Append ( _T(" ") );
Append ( XML_ATTR_NULL );
Append ( _T("=\"true\"/>") );
return;
}
const bool bList = oItem.r_Object().IsList ( );
const bool bVect = oItem.r_Object().IsVect ( );
const bool bDesc = !oItem.r_Desc().IsEmpty ( );
const bool bAttrs = m_bAttributes && !oItem.r_Attr().IsEmpty ( );
if ( bList )
{
strOpen += _T(" ");
strOpen += XML_ATTR_LIST;
strOpen += _T("=\"true\"");
}
else if ( bVect )
{
strOpen += _T(" ");
strOpen += XML_ATTR_VECT;
strOpen += _T("=\"true\"");
}
// A LEAF, which is what the great majority of nodes are: its value is its
// own text, and no p2p:value is needed to say so.
if ( !bList && !bVect && !bDesc && !bAttrs )
{
CString strValue;
if ( RenderScalar ( oItem.r_data(), strValue ) == Value_Null )
{
// Empty is a present, empty string, so a NULL cell has to say more
// than nothing - otherwise the two come back the same.
Append ( (LPCTSTR)strOpen );
Append ( _T(" ") );
Append ( XML_ATTR_NULL );
Append ( _T("=\"true\"/>") );
return;
}
Append ( (LPCTSTR)strOpen );
Append ( (LPCTSTR)TypeAttr ( oItem.r_data() ) );
Append ( _T(">") );
Append ( (LPCTSTR)EscapeText ( (LPCTSTR)strValue ) );
Append ( _T("</") );
Append ( (LPCTSTR)strTag );
Append ( _T(">") );
return;
}
// A node with children. Its own value, if it has one, goes in a
// <p2p:value> element rather than beside them: an element that holds both
// text and elements is mixed content, and a reader that has to work out
// which whitespace was meant is a reader that gets it wrong.
Append ( (LPCTSTR)strOpen );
Append ( _T(">") );
const int nBefore = m_strText.GetLength ( );
if ( bList )
RenderList ( dynamic_cast<P3PmsgList&>(oItem), nDepth );
else if ( bVect )
RenderVect ( dynamic_cast<P3PmsgVect&>(oItem), nDepth );
else
RenderOwnValue ( oItem.r_data(), nDepth + 1 );
if ( bAttrs )
RenderAttrChildren ( oItem.r_Attr(), nDepth + 1 );
if ( bDesc )
RenderDescChildren ( oItem.r_Desc(), nDepth + 1 );
// The break before the end tag belongs to the children, so an element
// that emitted none stays on one line: <Flat p2p:list="true"></Flat>.
if ( m_strText.GetLength ( ) != nBefore )
AppendBreak ( nDepth );
Append ( _T("</") );
Append ( (LPCTSTR)strTag );
Append ( _T(">") );
}
//
// A list is a chain of data entries and nothing else, so every entry is a
// <p2p:item> holding one scalar.
//
void
PrintXML::RenderList ( P3PmsgList& oList, int nDepth )
{
VBLaddr aEntry = oList.GetHeadPos ( );
while ( aEntry )
{
P3PmsgData& oEntry = oList.GetNext ( aEntry );
AppendBreak ( nDepth + 1 );
CString strValue;
if ( RenderScalar ( oEntry, strValue ) == Value_Null )
{
Append ( _T("<") );
Append ( XML_TAG_ITEM );
Append ( _T(" ") );
Append ( XML_ATTR_NULL );
Append ( _T("=\"true\"/>") );
continue;
}
Append ( _T("<") );
Append ( XML_TAG_ITEM );
Append ( (LPCTSTR)TypeAttr ( oEntry ) );
Append ( _T(">") );
Append ( (LPCTSTR)EscapeText ( (LPCTSTR)strValue ) );
Append ( _T("</") );
Append ( XML_TAG_ITEM );
Append ( _T(">") );
}
}
//
// A vector holds ELEMENTS, which may themselves be items, lists or vectors,
// so each one goes back through RenderNode under the unnamed tag.
// NOTES: r_item(i) walks the cursor to element i and the reference it returns
// is invalidated by the next walk - which is why nothing here holds one
// across an iteration.
//
void
PrintXML::RenderVect ( P3PmsgVect& oVect, int nDepth )
{
const VBLelem nCount = oVect.GetCount ( );
for ( VBLelem i = 0; i < nCount; i++ )
{
AppendBreak ( nDepth + 1 );
try
{
RenderNode ( oVect.r_item ( (int)i ), nullptr, false, false, nDepth + 1 );
}
// An element the vector cannot instantiate is one element, not one
// document. Report it as null and carry on, the same call RenderScalar
// makes for a cell that disagrees with its own type byte.
catch_pP2Pevent_Cancel
catch_ALL_Cancel
}
}
//
// Attributes, one element each, marked p2p:attr so the reader puts them back
// on the attribute branch rather than the descendant one.
//
void
PrintXML::RenderAttrChildren ( P3PmsgAttr& oAttr, int nDepth )
{
P3PmsgCurs& oCurs = oAttr.r_Curs ( );
for ( int i = 0; oCurs.Goto ( i ); i++ )
{
P3PmsgItem& oItem = oCurs.r_item ( );
AppendBreak ( nDepth );
RenderNode ( oItem, oItem.c_name ( ), true, false, nDepth );
}
}
//
// Descendants, one element each, under their own names.
//
void
PrintXML::RenderDescChildren ( P3PmsgDesc& oDesc, int nDepth )
{
P3PmsgCurs& oCurs = oDesc.r_Curs ( );
for ( int i = 0; oCurs.Goto ( i ); i++ )
{
P3PmsgItem& oItem = oCurs.r_item ( );
AppendBreak ( nDepth );
RenderNode ( oItem, oItem.c_name ( ), false, false, nDepth );
}
}
//
// The <p2p:value> of a node that carries children, and NOTHING AT ALL when it
// has no value of its own - which is the common case for a pure container,
// and writing an empty one for every one of them would say nothing at length.
//
void
PrintXML::RenderOwnValue ( P3PmsgData& oData, int nDepth )
{
CString strValue;
if ( RenderScalar ( oData, strValue ) == Value_Null )
return;
AppendBreak ( nDepth );
Append ( _T("<") );
Append ( XML_TAG_VALUE );
Append ( (LPCTSTR)TypeAttr ( oData ) );
Append ( _T(">") );
Append ( (LPCTSTR)EscapeText ( (LPCTSTR)strValue ) );
Append ( _T("</") );
Append ( XML_TAG_VALUE );
Append ( _T(">") );
}
CString
PrintXML::TypeAttr ( P3PmsgData& oData ) const
{
CString strOut;
if ( !m_bTypes )
return strOut;
const CString strType = TypeName ( oData );
if ( strType.IsEmpty ( ) )
return strOut;
strOut += _T(" ");
strOut += XML_ATTR_TYPE;
strOut += _T("=\"");
strOut += EscapeAttr ( (LPCTSTR)strType );
strOut += _T("\"");
return strOut;
}
//
// Character data escaping.
// NOTES: The three that must be escaped, plus the carriage return, which must
// be escaped for a reason nothing about XML syntax suggests: a reader
// NORMALISES line endings before the application sees them, turning a
// raw CR or CRLF into a single LF. A store holding "\r\n" would come
// back holding "\n", and is what survives.
// : A control character below U+0020 other than tab, CR and LF is
// DROPPED. XML 1.0 has no representation for one - not a raw character
// and not a reference either - so the choice is between losing the
// character and emitting a document no parser will read.
// : The apostrophe is not escaped. It is legal as itself in character
// data, and ' is the one predefined entity a reader is most
// likely to be surprised by.
//
CString
PrintXML::EscapeText ( LPCTSTR lpszText )
{
CString strOut;
if ( lpszText == nullptr )
return strOut;
for ( const TCHAR *p = lpszText; *p; ++p )
{
switch ( *p )
{
case _T('&'): strOut += _T("&"); break;
case _T('<'): strOut += _T("<"); break;
case _T('>'): strOut += _T(">"); break;
case _T('\r'): strOut += _T(" "); break;
default:
if ( (unsigned int)*p < 0x20u && *p != _T('\t') && *p != _T('\n') )
break; // Unrepresentable; dropped
strOut += *p;
break;
}
}
return strOut;
}
//
// Attribute-value escaping, which is stricter than character data for one
// reason: a reader normalises every whitespace character inside an attribute
// to a space, so a tab or a newline that is written literally does not come
// back. All three go out as references.
//
CString
PrintXML::EscapeAttr ( LPCTSTR lpszText )
{
CString strOut;
if ( lpszText == nullptr )
return strOut;
for ( const TCHAR *p = lpszText; *p; ++p )
{
switch ( *p )
{
case _T('&'): strOut += _T("&"); break;
case _T('<'): strOut += _T("<"); break;
case _T('>'): strOut += _T(">"); break;
case _T('\"'): strOut += _T("""); break;
case _T('\t'): strOut += _T("	"); break;
case _T('\n'): strOut += _T(" "); break;
case _T('\r'): strOut += _T(" "); break;
default:
if ( (unsigned int)*p < 0x20u )
break; // Unrepresentable; dropped
strOut += *p;
break;
}
}
return strOut;
}
//
// Reduces a Msgcore item name to an XML tag name.
// NOTES: Everything outside [A-Za-z0-9_-] becomes an underscore, and a name
// that cannot START one takes an underscore prefix. Non-ASCII letters
// fold too, which XML would in fact accept - see the header for why a
// tag whose legality depends on which XML version the reader
// implements is worse than an obviously-ASCII one.
// : Names beginning "xml" in any case are reserved by the specification
// and take the same prefix.
// : THE ORIGINAL NAME IS NOT LOST. RenderNode writes p2p:name whenever
// this returns something other than what it was given.
//
CString
PrintXML::XmlName ( LPCTSTR lpszName )
{
CString strOut;
if ( lpszName )
{
for ( const TCHAR *p = lpszName; *p; ++p )
{
const unsigned int uCode = (unsigned int)*p;
if ( ( uCode >= (unsigned int)_T('A') && uCode <= (unsigned int)_T('Z') ) ||
( uCode >= (unsigned int)_T('a') && uCode <= (unsigned int)_T('z') ) ||
( uCode >= (unsigned int)_T('0') && uCode <= (unsigned int)_T('9') ) ||
uCode == (unsigned int)_T('_') || uCode == (unsigned int)_T('-') )
strOut += *p;
else
strOut += _T('_');
}
}
if ( strOut.IsEmpty ( ) )
return CString ( _T("item") );
const TCHAR chFirst = strOut[0];
const bool bLetter = ( chFirst >= _T('A') && chFirst <= _T('Z') )
|| ( chFirst >= _T('a') && chFirst <= _T('z') )
|| chFirst == _T('_');
if ( !bLetter || strOut.Left ( 3 ).CompareNoCase ( _T("xml") ) == 0 )
{
CString strPrefixed ( _T("_") );
strPrefixed += strOut;
return strPrefixed;
}
return strOut;
}
///////////////////////////////////////////////////////////////////////
// Parsing
//
// Reads the XML document this renderer holds into oItem, REPLACING everything
// oItem held.
//
// Parameters: P3PmsgItem& oItem
// Manager, item, list or vector to write into
//
// Returns: MsgPrint&
// This renderer, so GetError() can be read from the expression
//
// NOTES: TWO PASSES, and the first one touches nothing. The document becomes a
// MsgValue tree first and only a tree that parsed to its end is written
// to the store - because the write REPLACES, and a truncated node
// holding half a document is worse than the node the caller still had.
// : The root element's NAME is discarded. A document identifies a node,
// it does not rename one, and the name of the node being written into
// is the store's own - exactly what the JSON dialect does with the key
// of its rooted wrapper.
//
MsgPrint&
PrintXML::Parse ( P3PmsgItem& oItem )
{
ClearError ( );
try
{
int nPos = 0;
if ( !ReadProlog ( nPos ) )
return *this;
CString strTag;
XmlAttrs oAttrs;
bool bEmpty = false;
if ( !ReadStartTag ( strTag, oAttrs, bEmpty, nPos ) )
return *this;
MsgValue oRoot;
if ( !ReadElementBody ( oRoot, strTag, oAttrs, bEmpty, nPos, 0 ) )
return *this;
// Comments and processing instructions are legal AFTER the root element
// as well as before it. Anything else at this point is a second root,
// which is the one thing an XML document may not have.
for ( ;; )
{
SkipSpace ( nPos );
if ( LooksLike ( _T("<!--"), nPos ) )
{
if ( !SkipComment ( nPos ) )
return *this;
continue;
}
if ( LooksLike ( _T("<?"), nPos ) )
{
if ( !SkipPI ( nPos ) )
return *this;
continue;
}
break;
}
if ( nPos < m_strText.GetLength ( ) )
{
SetError ( _T("Trailing text after the root element"), nPos );
return *this;
}
BuildItem ( oItem, oRoot, 0 );
return *this;
}
// A throw from the store side - a name the format refuses, a heap that
// cannot grow. The document was legal and the store would not take it,
// which is a different failure from a syntax error and says so.
catch_pP2Pevent_Cancel
catch_ALL_Cancel
SetError ( _T("The store refused the document"), -1 );
return *this;
}
///////////////////////////////////////////////////////////////////////
// Reading - the start tag's attributes
LPCTSTR
PrintXML::XmlAttrs::Find ( LPCTSTR lpszName ) const
{
for ( size_t i = 0; i < oNames.size ( ); i++ )
if ( oNames[i].Compare ( lpszName ) == 0 )
return (LPCTSTR)oValues[i];
return nullptr;
}
bool
PrintXML::XmlAttrs::Flag ( LPCTSTR lpszName ) const
{
LPCTSTR lpszValue = Find ( lpszName );
return lpszValue != nullptr && CString ( lpszValue ).Compare ( _T("true") ) == 0;
}
///////////////////////////////////////////////////////////////////////
// Reading
// NOTES: A recursive descent over m_strText, by character offset. Each Read
// leaves nPos on the first character it did not consume, and returns
// false having called SetError - which keeps the FIRST message, so the
// unwind does not overwrite a mismatched end tag on line 40 with
// "unexpected end of document".
void
PrintXML::SkipSpace ( int& nPos ) const
{
const int nLength = m_strText.GetLength ( );
while ( nPos < nLength && PrintXML_IsSpace ( m_strText[nPos] ) )
nPos++;
}
bool
PrintXML::LooksLike ( LPCTSTR lpszWord, int nPos ) const
{
const int nLength = m_strText.GetLength ( );
for ( int i = 0; lpszWord[i]; i++ )
if ( nPos + i >= nLength || m_strText[nPos + i] != lpszWord[i] )
return false;
return true;
}
//
// Everything before the root element: the XML declaration, comments,
// processing instructions and a document type declaration, every one of them
// optional and every one of them skipped.
// NOTES: The declaration is not BELIEVED, only skipped - its encoding names
// the bytes of a file, and by the time a document is in this object it
// has already been decoded. GetDeclaration() says what a RENDER writes
// and nothing about what a parse will accept.
//
bool
PrintXML::ReadProlog ( int& nPos )
{
for ( ;; )
{
SkipSpace ( nPos );
if ( LooksLike ( _T("<!--"), nPos ) )
{
if ( !SkipComment ( nPos ) )
return false;
continue;
}
if ( LooksLike ( _T("<?"), nPos ) )
{
if ( !SkipPI ( nPos ) )
return false;
continue;
}
if ( LooksLike ( _T("<!DOCTYPE"), nPos ) )
{
// Skipped rather than read, INTERNAL SUBSET AND ALL. This reader
// resolves the five predefined entities and nothing else, so a
// declared one would be reported as unknown wherever it was used -
// which is a clearer failure than silently taking half a DTD's word
// for the shape of the document.
const int nLength = m_strText.GetLength ( );
while ( nPos < nLength && m_strText[nPos] != _T('>') && m_strText[nPos] != _T('[') )
nPos++;
if ( nPos < nLength && m_strText[nPos] == _T('[') )
{
while ( nPos < nLength && m_strText[nPos] != _T(']') )
nPos++;
while ( nPos < nLength && m_strText[nPos] != _T('>') )
nPos++;
}
if ( nPos >= nLength )
{
SetError ( _T("Unterminated document type declaration"), nPos );
return false;
}
nPos++;
continue;
}
break;
}
if ( nPos >= m_strText.GetLength ( ) || m_strText[nPos] != _T('<') )
{
SetError ( _T("No root element - an XML document is exactly one"), nPos );
return false;
}
return true;
}
bool
PrintXML::SkipComment ( int& nPos )
{
const int nLength = m_strText.GetLength ( );
const int nFrom = nPos;
nPos += 4; // <!--
while ( nPos < nLength && !LooksLike ( _T("-->"), nPos ) )
nPos++;
if ( nPos >= nLength )
{
SetError ( _T("Unterminated comment"), nFrom );
return false;
}
nPos += 3;
return true;
}
bool
PrintXML::SkipPI ( int& nPos )
{
const int nLength = m_strText.GetLength ( );
const int nFrom = nPos;
nPos += 2; // <?
while ( nPos < nLength && !LooksLike ( _T("?>"), nPos ) )
nPos++;
if ( nPos >= nLength )
{
SetError ( _T("Unterminated processing instruction"), nFrom );
return false;
}
nPos += 2;
return true;
}
//
// An XML Name. Deliberately WIDER than what XmlName writes: this reader takes
// documents from elsewhere, and refusing a tag it would never itself have
// produced would make it useless for exactly the case an XML dialect exists
// for. The colon is accepted because the reserved prefix needs it.
//
bool
PrintXML::ReadName ( CString& strOut, int& nPos ) const
{
const int nLength = m_strText.GetLength ( );
strOut.Empty ( );
while ( nPos < nLength )
{
const TCHAR c = m_strText[nPos];
const unsigned int uCode = (unsigned int)c;
if ( ( uCode >= (unsigned int)_T('A') && uCode <= (unsigned int)_T('Z') ) ||
( uCode >= (unsigned int)_T('a') && uCode <= (unsigned int)_T('z') ) ||
( uCode >= (unsigned int)_T('0') && uCode <= (unsigned int)_T('9') ) ||
c == _T('_') || c == _T('-') || c == _T('.') || c == _T(':') ||
uCode >= 0x80u )
{
strOut += c;
nPos++;
continue;
}
break;
}
return !strOut.IsEmpty ( );
}
//
// Consumes one start tag, '<' through '>', and every attribute in it.
//
bool
PrintXML::ReadStartTag ( CString& strTag, XmlAttrs& oAttrs, bool& bEmpty, int& nPos )
{
const int nLength = m_strText.GetLength ( );
bEmpty = false;
oAttrs.oNames.clear ( );
oAttrs.oValues.clear ( );
if ( nPos >= nLength || m_strText[nPos] != _T('<') )
{
SetError ( _T("Expecting an element"), nPos );
return false;
}
nPos++;
if ( !ReadName ( strTag, nPos ) )
{
SetError ( _T("Expecting a tag name after '<'"), nPos );
return false;
}
for ( ;; )
{
SkipSpace ( nPos );
if ( nPos >= nLength )
{
SetError ( _T("Unterminated start tag"), nPos );
return false;
}
if ( m_strText[nPos] == _T('>') )
{
nPos++;
return true;
}
if ( m_strText[nPos] == _T('/') )
{
nPos++;
if ( nPos >= nLength || m_strText[nPos] != _T('>') )
{
SetError ( _T("Expecting '>' after '/' in an empty element"), nPos );
return false;
}
nPos++;
bEmpty = true;
return true;
}
CString strName;
if ( !ReadName ( strName, nPos ) )
{
SetError ( _T("Expecting an attribute name, '>' or '/>'"), nPos );
return false;
}
SkipSpace ( nPos );
if ( nPos >= nLength || m_strText[nPos] != _T('=') )
{
SetError ( _T("Expecting '=' after an attribute name"), nPos );
return false;
}
nPos++;
SkipSpace ( nPos );
CString strValue;
if ( !ReadAttrValue ( strValue, nPos ) )
return false;
oAttrs.oNames.push_back ( strName );
oAttrs.oValues.push_back ( strValue );
}
}
bool
PrintXML::ReadAttrValue ( CString& strOut, int& nPos )
{
const int nLength = m_strText.GetLength ( );
strOut.Empty ( );
if ( nPos >= nLength
|| ( m_strText[nPos] != _T('\"') && m_strText[nPos] != _T('\'') ) )
{
SetError ( _T("An attribute value must be quoted"), nPos );
return false;
}
const TCHAR chDelim = m_strText[nPos];
nPos++;
while ( nPos < nLength )
{
const TCHAR c = m_strText[nPos];
if ( c == chDelim )
{
nPos++;
return true;
}
if ( c == _T('<') )
{
SetError ( _T("'<' is not allowed in an attribute value"), nPos );