Repository navigation
Expand file tree
/
Copy pathsrcMLOutput.cpp
More file actions
680 lines (550 loc) · 20.9 KB
/
Copy pathsrcMLOutput.cpp
File metadata and controls
680 lines (550 loc) · 20.9 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
// SPDX-License-Identifier: GPL-3.0-only
/**
* @file srcMLOutput.cpp
*
* @copyright Copyright (C) 2003-2024 srcML, LLC. (www.srcML.org)
*
* This file is part of the srcML Toolkit.
*
* Output of the XML format based on srcMLParser
*/
#include <srcMLOutput.hpp>
#undef CONST
#undef VOID
#undef DELETE
#undef INTERFACE
#undef OUT
#undef IN
#undef THIS
#include <srcMLParserTokenTypes.hpp>
#include <srcMLToken.hpp>
// Definition of elements, including name, URI, attributes, and special processing
// Included to take advantage of inlined methods
#include <srcMLOutputElements.hpp>
namespace {
void srcMLTextWriterWriteNamespace(xmlTextWriterPtr xout, const Namespace& ns) {
std::string prefix = "xmlns";
if (!ns.prefix.empty()) {
prefix += ':';
prefix += ns.prefix;
}
xmlTextWriterWriteAttribute(xout, BAD_CAST prefix.data(), BAD_CAST ns.uri.data());
}
// itoa-type function
inline const char* positoa(int n) {
// enough space to store int as string
static constexpr int SIZE = sizeof(int) * 4;
thread_local char s[SIZE] = { 0 };
// create string backwards from 1's place
char* p = s + SIZE - 1;
do {
*--p = '0' + (n % 10);
n /= 10;
} while (n);
// end of string that we are using
return p;
}
}
/**
* srcMLOutput
* @param ints a token stream
* @param filename if output to a file
* @param language the unit language
* @param xml_enc output encoding
* @param op output operations
* @param ts tabstop size
* @param output_buffer if output is to a output buffer
*
* Constructor. Handles all outputs.
*/
srcMLOutput::srcMLOutput(TokenStream* ints,
xmlOutputBuffer* output_buffer,
const char* language,
const char* xml_enc,
OPTION_TYPE& op,
const Attributes& attributes,
const std::optional<std::pair<std::string, std::string>>& processing_instruction,
size_t ts)
: output_buffer(output_buffer), input(ints), unit_language(language),
options(op), xml_encoding(xml_enc), attributes(attributes), processing_instruction(processing_instruction),
tabsize(ts)
{
// open the output text writer stream
xout = xmlNewTextWriter(output_buffer);
}
/**
* initNamespaces
*
* Initialize the output namespaces.
*/
void srcMLOutput::initNamespaces(const Namespaces& otherns) {
// start with the default
namespaces = default_namespaces;
// merge in the other namespaces
namespaces += otherns;
if (depth == 0)
archiveNamespaces = namespaces;
}
/**
* ~srcMLOutput
*
* Destructor. Closes output.
*/
srcMLOutput::~srcMLOutput() {
close();
}
/**
* close
*
* Close/finish the output.
*/
void srcMLOutput::close() {
if (xout) {
if (startedOutput)
xmlTextWriterEndDocument(xout);
xmlFreeTextWriter(xout);
xout = 0;
output_buffer = 0;
} else if (output_buffer) {
xmlOutputBufferClose(output_buffer);
output_buffer = 0;
}
}
void srcMLOutput::outputUnitSeparator() {
processText("\n\n", 2);
}
/**
* setTokenStream
* @param ints token stream to set to.
*
* Set the token stream.
*/
void srcMLOutput::setTokenStream(TokenStream& ints) {
input = &ints;
}
/**
* consume
* @param language unit language attribute
* @param revision unit revision attribute
* @param url unit url attribute
* @param filename unit filename attribute
* @param version unit version attribute
* @param timestamp unit timestamp attribute
* @param hash unit hash attribute
*
* Start consumption of tokens/parsing of source code with unit attributes.
*/
void srcMLOutput::consume(const char* language, const char* revision, const char* url, const char* filename,
const char* version, const char* timestamp, const char* hash, const char* encoding) {
// store attributes so that first occurrence of unit element will be correct
unit_revision = revision;
unit_url = url;
unit_filename = filename;
unit_version = version;
unit_timestamp = timestamp;
unit_language = language;
unit_hash = hash;
unit_encoding = encoding;
Position currentPosition;
while (1) {
const antlr::RefToken& token = input->nextToken();
if (!isoption(options, SRCML_PARSER_OPTION_POSITION)) {
if (token->getType() == antlr::Token::EOF_TYPE)
break;
outputToken(token);
} else {
if (token->getType() == antlr::Token::EOF_TYPE) {
while (!tokenQueue.empty()) {
outputToken(tokenQueue.front());
tokenQueue.pop_front();
}
break;
}
// text token
auto search = process.find(token->getType());
if (!(search != process.end() && search->second.name)) {
// update the text position
currentPosition.append(token->getText(), tabsize);
// save the text
tokenQueue.push_back(token);
// start token but not empty
} else if (isstart(token) && !isempty(token)) {
// set the start line/column
token->setLine(currentPosition.line);
token->setColumn(currentPosition.column + 1);
// save open start elements
startElementStack.push(token);
// save the start element
tokenQueue.push_back(token);
// start token but empty
} else if (isstart(token) && isempty(token)) {
// save the empty element
tokenQueue.push_back(token);
// end token
} else if (isend(token)) {
// most recent start token that will match the current end token
auto matchingStartElement = startElementStack.top();
startElementStack.pop();
// set the end line/column
srcMLToken* qetoken = static_cast<srcMLToken*>(&(*matchingStartElement));
qetoken->endline = currentPosition.line;
qetoken->endcolumn = currentPosition.column;
// save the end token
tokenQueue.push_back(token);
// if there are no open elements, then we are at the root
// and can output all elements in the queue
if (startElementStack.empty()) {
while (!tokenQueue.empty()) {
outputToken(tokenQueue.front());
tokenQueue.pop_front();
}
}
}
}
}
}
/**
* outputXMLDecl
*
* Output the starting xml declaration.
*/
void srcMLOutput::outputXMLDecl() {
// issue the xml declaration, but only if we want to
if (depth == 0 && !isoption(options, SRCML_PARSER_OPTION_NO_XML_DECL))
xmlTextWriterStartDocument(xout, XML_VERSION.data(), xml_encoding, XML_DECLARATION_STANDALONE.data());
}
/**
* outputProcessingInstruction
*
* Output a pre-root preprocessing instruction.
*/
void srcMLOutput::outputProcessingInstruction() {
if (depth == 0 && processing_instruction) {
startedOutput = true;
xmlTextWriterStartPI(xout, BAD_CAST processing_instruction->first.data());
xmlTextWriterWriteString(xout, BAD_CAST processing_instruction->second.data());
xmlTextWriterEndPI(xout);
xmlTextWriterWriteString(xout, BAD_CAST "\n");
}
}
/**
* outputNamespaces
*
* Output the namespaces on the units.
*/
void srcMLOutput::outputNamespaces() {
// based on options, turn on specific namespaces (i.e., mark as used)
if (isoption(options, SRCML_OPTION_CPP_DECLARED))
findNSURI(namespaces, SRCML_CPP_NS_URI)->flags |= NS_USED;
if (isoption(options, SRCML_PARSER_OPTION_POSITION))
findNSURI(namespaces, SRCML_POSITION_NS_URI)->flags |= NS_USED;
if (isoption(options, SRCML_OPTION_DEBUG))
findNSURI(namespaces, SRCML_ERROR_NS_URI)->flags |= NS_USED;
for (const auto& ns : namespaces) {
// output standard namespaces for outer unit or non-archive unit
if (depth == 0 || !isoption(options, SRCML_OPTION_ARCHIVE)) {
// must be required, or on the root and used
if ((ns.flags & NS_STANDARD) && ((ns.flags & NS_REQUIRED) || ((ns.flags & NS_ROOT) && (ns.flags & NS_USED)))) {
srcMLTextWriterWriteNamespace(xout, ns);
continue;
}
// must be user registered
if (ns.flags & NS_REGISTERED && !(ns.flags & NS_STANDARD)) {
srcMLTextWriterWriteNamespace(xout, ns);
continue;
}
}
// output standard namespaces for inner unit or non-archive unit
if (depth == 1 || !isoption(options, SRCML_OPTION_ARCHIVE)) {
// must be required, must not be on the root, and must be used
if ((ns.flags & NS_STANDARD) && !(ns.flags & NS_ROOT) && !(ns.flags & NS_REQUIRED) && (ns.flags & NS_USED)) {
srcMLTextWriterWriteNamespace(xout, ns);
continue;
} else if ((ns.flags & NS_REGISTERED) && (findNSURI(archiveNamespaces, ns.uri) == archiveNamespaces.end())) {
srcMLTextWriterWriteNamespace(xout, ns);
continue;
}
}
}
}
/**
* startUnit
* @param language the language attribute
* @param revision what version of srcML
* @param url the url attribute
* @param filename the filename attribute
* @param version the version attribute
* @param timestamp the timestamp attribute
* @param hash the hash attribute
* @param encoding the encoding attribute
* @param outer is this an outer or inner unit
*
* Output the start of a unit tag.
*/
void srcMLOutput::startUnit(const char* language, const char* revision,
const char* url, const char* filename,
const char* version, const char* timestamp,
const char* hash,
const char* encoding,
const Attributes& unit_attributes,
bool output_macrolist) {
// go with default encoding
if (!encoding || encoding[0] == '\0') {
encoding = "UTF-8";
}
startedOutput = true;
// start of main tag
std::string_view unitprefix = namespaces[SRC].prefix;
xmlTextWriterStartElementNS(xout, BAD_CAST (!unitprefix.empty() ? unitprefix.data() : 0), BAD_CAST "unit", 0);
// output namespaces for root and nested units
if (isoption(options, SRCML_OPTION_NAMESPACE_DECL)) {
outputNamespaces();
}
// options
std::string soptions;
if (isoption(options, SRCML_PARSER_OPTION_CPP_TEXT_ELSE))
soptions = "CPP_TEXT_ELSE";
if (isoption(options, SRCML_PARSER_OPTION_CPP_MARKUP_IF0)) {
if (!soptions.empty())
soptions += ',';
soptions = "CPP_MARKUP_IF0";
}
if (isoption(options, SRCML_OPTION_LINE)) {
if (!soptions.empty())
soptions += ',';
soptions = "LINE";
}
// revision standard attribute
if (revision) {
xmlTextWriterWriteAttribute(xout, BAD_CAST UNIT_ATTRIBUTE_REVISION.data(), BAD_CAST revision);
}
// language standard attribute
if (language) {
xmlTextWriterWriteAttribute(xout, BAD_CAST UNIT_ATTRIBUTE_LANGUAGE.data(), BAD_CAST language);
}
// url standard attribute
if (url) {
xmlTextWriterWriteAttribute(xout, BAD_CAST UNIT_ATTRIBUTE_URL.data(), BAD_CAST url);
}
// filename standard attribute
if (filename) {
xmlTextWriterWriteAttribute(xout, BAD_CAST UNIT_ATTRIBUTE_FILENAME.data(), BAD_CAST filename);
}
// version standard attribute
if (version) {
xmlTextWriterWriteAttribute(xout, BAD_CAST UNIT_ATTRIBUTE_VERSION.data(), BAD_CAST version);
}
// tabsize standard attribute
if (isoption(options, SRCML_PARSER_OPTION_POSITION)) {
std::string tabattribute(namespaces[POS].getPrefix());
if (!tabattribute.empty())
tabattribute += ':';
for (auto c : "tabs"sv)
tabattribute += c;
auto stabsize = std::to_string(tabsize);
xmlTextWriterWriteAttribute(xout, BAD_CAST tabattribute.data(), BAD_CAST stabsize.data());
}
// timestamp standard attribute
if (timestamp) {
xmlTextWriterWriteAttribute(xout, BAD_CAST UNIT_ATTRIBUTE_TIMESTAMP.data(), BAD_CAST timestamp);
}
// hash standard attribute
if (hash) {
xmlTextWriterWriteAttribute(xout, BAD_CAST UNIT_ATTRIBUTE_HASH.data(), BAD_CAST hash);
}
// encoding standard attribute
if (isoption(options, SRCML_PARSER_OPTION_STORE_ENCODING)) {
xmlTextWriterWriteAttribute(xout, BAD_CAST UNIT_ATTRIBUTE_SOURCE_ENCODING.data(), BAD_CAST encoding);
}
// options standard attribute
if (depth == 0 && !soptions.empty()) {
xmlTextWriterWriteAttribute(xout, BAD_CAST UNIT_ATTRIBUTE_OPTIONS.data(), BAD_CAST soptions.data());
}
// custom attributes
for (const auto& attribute : unit_attributes) {
std::string qName;
if (!attribute.prefix.empty()) {
qName += attribute.prefix;
qName += ':';
}
qName += attribute.name;
xmlTextWriterWriteAttribute(xout, BAD_CAST qName.data(), BAD_CAST attribute.value.data());
}
if (output_macrolist)
outputMacroList();
if (depth == 0)
depth = 1;
}
/**
* setMacroList
* @param list the user defined macro list
*
* Set the macro list to use for output.
*/
void srcMLOutput::setMacroList(std::vector<std::string> & list) {
user_macro_list = list;
}
/**
* outputMacroList
*
* Output the stored user defined macro list meta data.
*/
void srcMLOutput::outputMacroList() {
for(std::vector<std::string>::size_type i = 0; i < user_macro_list.size(); i += 2) {
xmlTextWriterStartElement(xout, BAD_CAST "macro-list");
xmlTextWriterWriteAttribute(xout, BAD_CAST "token", BAD_CAST user_macro_list[i].data());
xmlTextWriterWriteAttribute(xout, BAD_CAST "type", BAD_CAST user_macro_list[i + 1].data());
xmlTextWriterEndElement(xout);
}
}
/**
* processText
* @param str text to output
*
* Callback to process/output text.
*/
inline void srcMLOutput::processText(std::string_view str) {
// skip processing empty stings
if (str.empty())
return;
// output any '<', '>', or '&', or any text before
std::size_t p = 0;
auto lastp = p;
while ((p = str.find_first_of("<>&"sv, p)) != str.npos) {
// output section before
xmlTextWriterWriteRawLen(xout, BAD_CAST (unsigned char*) &str.data()[lastp], p - lastp);
// output special characters
if (str[p] == '<') {
xmlTextWriterWriteRawLen(xout, BAD_CAST "<", "<"sv.size());
} else if (str[p] == '>') {
xmlTextWriterWriteRawLen(xout, BAD_CAST ">", ">"sv.size());
} else if (str[p] == '&') {
xmlTextWriterWriteRawLen(xout, BAD_CAST "&", "&"sv.size());
}
++p;
lastp = p;
}
// output remaining text after last '<', '>', or '&', or the entire string if these do not occur
xmlTextWriterWriteRawLen(xout, BAD_CAST (unsigned char*) &str.data()[lastp], str.size() - lastp);
}
/**
* processText
* @param s string to output
* @param size of bytes to output
*
* Callback to process/output text outputting size bytes.
*/
inline void srcMLOutput::processText(const char* s, int size) {
xmlTextWriterWriteRawLen(xout, BAD_CAST (unsigned char*) s, size);
}
/**
* processText
* @param token token to output as text
*
* Callback to process/output token as text.
*/
inline void srcMLOutput::processText(const antlr::RefToken& token) {
processText(token->getText());
}
/**
* processTextPosition
* @param token token to output as text
*
* Callback to process/output token as text with position information.
*/
void srcMLOutput::addPosition(const antlr::RefToken& token) {
srcMLToken* stoken = static_cast<srcMLToken*>(&(*token));
// how we detect empty elements: the position is wrong
if (stoken->endline < stoken->getLine() || (stoken->endline == stoken->getLine() && stoken->endcolumn < stoken->getColumn()))
return;
thread_local const std::string prefix(namespaces[POS].prefix);
thread_local const std::string startAttribute = " " + prefix + (!prefix.empty() ? ":" : "") + "start=\"";
thread_local const std::string endAttribute = " " + prefix + (!prefix.empty() ? ":" : "") + "end=\"";
// highly optimized as this is output for every start tag
// position start attribute, e.g. pos:start="1:4"
xmlOutputBufferWrite(output_buffer, (int) startAttribute.size(), startAttribute.data());
xmlOutputBufferWriteString(output_buffer, positoa(token->getLine()));
xmlOutputBufferWrite(output_buffer, 1, ":");
xmlOutputBufferWriteString(output_buffer, positoa(token->getColumn()));
xmlOutputBufferWrite(output_buffer, 1, "\"");
xmlOutputBufferFlush(output_buffer);
// position end attribute, e.g. pos:end="2:1"
xmlOutputBufferWrite(output_buffer, (int) endAttribute.size(), endAttribute.data());
if (token->getLine() > stoken->endline) {
xmlOutputBufferWriteString(output_buffer, "INVALID_POS(");
}
xmlOutputBufferWriteString(output_buffer, positoa(stoken->endline));
if (token->getLine() > stoken->endline) {
xmlOutputBufferWriteString(output_buffer, ")");
}
xmlOutputBufferWrite(output_buffer, 1, ":");
xmlOutputBufferWriteString(output_buffer, positoa(stoken->endcolumn));
xmlOutputBufferWrite(output_buffer, 1, "\"");
}
void srcMLOutput::processToken(const antlr::RefToken& token, const char* name, const char* prefix, const char* attr_name1, const char* attr_value1,
const char* attr_name2, const char* attr_value2) {
// no name, no token
if (name[0] == 0)
return;
bool isposition = isoption(options, SRCML_PARSER_OPTION_POSITION);
if (isstart(token) || isempty(token)) {
// empty prefixes have to be null for output
if (prefix[0] == '\0')
prefix = 0;
xmlTextWriterStartElementNS(xout, BAD_CAST prefix, BAD_CAST name, 0);
if (attr_name1)
xmlTextWriterWriteAttribute(xout, BAD_CAST attr_name1, BAD_CAST attr_value1);
if (attr_name2)
xmlTextWriterWriteAttribute(xout, BAD_CAST attr_name2, BAD_CAST attr_value2);
if (isposition) {
// save start and end positions for any future previous type
if (token->getType() == srcMLParserTokenTypes::STYPE) {
lastTypeStartPosition = Position(token->getLine(), token->getColumn());
srcMLToken* qetoken = static_cast<srcMLToken*>(&(*token));
lastTypeEndPosition = Position(qetoken->endline, qetoken->endcolumn);
}
// previous type get start and end positions from previous, well type
if (token->getType() == srcMLParserTokenTypes::STYPEPREV) {
token->setLine(lastTypeStartPosition.line);
token->setColumn(lastTypeStartPosition.column);
srcMLToken* qetoken = static_cast<srcMLToken*>(&(*token));
qetoken->endline = lastTypeEndPosition.line;
qetoken->endcolumn = lastTypeEndPosition.column;
}
// if position attributes for non-empty start elements
if (!isempty(token) || token->getType() == srcMLParserTokenTypes::STYPEPREV)
addPosition(token);
}
}
if (!isstart(token) || isempty(token)) {
xmlTextWriterEndElement(xout);
}
}
/**
* outputToken
* @param token token to output
*
* Get callback that output token and output.
*/
inline void srcMLOutput::outputToken(const antlr::RefToken& token) {
// unit element is handled specially
if (srcMLParserTokenTypes::SUNIT == token->getType())
return;
// find the token in the element map. If found and it has a name, then process the token
auto search = process.find(token->getType());
if (search != process.end() && search->second.name) {
const Element& eparts = search->second;
// process the token using the fields in the element
processToken(token, eparts.name,
// use getPrefix() to record that this prefix was used
namespaces[eparts.prefix].getPrefix().data(),
eparts.attr_name,
// if attribute name and no value, then take text from token
eparts.attr_name && eparts.attr_value ? eparts.attr_value : token->getText().data(),
eparts.attr2_name,
eparts.attr2_value);
return;
}
// remainder are treated as text tokens
processText(token);
}