forked from vnotex/vnote
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpegparser.cpp
More file actions
539 lines (437 loc) · 12.8 KB
/
pegparser.cpp
File metadata and controls
539 lines (437 loc) · 12.8 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
#include "pegparser.h"
enum WorkerState
{
Idle,
Busy,
Cancelled,
Finished
};
void PegParseResult::parse(QAtomicInt &p_stop, bool p_fast)
{
if (p_fast) {
return;
}
parseImageRegions(p_stop);
parseHeaderRegions(p_stop);
parseFencedCodeBlockRegions(p_stop);
parseInlineEquationRegions(p_stop);
parseDisplayFormulaRegions(p_stop);
parseHRuleRegions(p_stop);
parseTableRegions(p_stop);
parseTableHeaderRegions(p_stop);
parseTableBorderRegions(p_stop);
}
void PegParseResult::parseImageRegions(QAtomicInt &p_stop)
{
parseRegions(p_stop,
pmh_IMAGE,
m_imageRegions,
false);
}
void PegParseResult::parseHeaderRegions(QAtomicInt &p_stop)
{
// From Qt5.7, the capacity is preserved.
m_headerRegions.clear();
if (isEmpty()) {
return;
}
pmh_element_type hx[6] = {pmh_H1, pmh_H2, pmh_H3, pmh_H4, pmh_H5, pmh_H6};
for (int i = 0; i < 6; ++i) {
pmh_element *elem = m_pmhElements[hx[i]];
while (elem != NULL) {
if (elem->end <= elem->pos) {
elem = elem->next;
continue;
}
if (p_stop.load() == 1) {
return;
}
m_headerRegions.push_back(VElementRegion(m_offset + elem->pos, m_offset + elem->end));
elem = elem->next;
}
}
if (p_stop.load() == 1) {
return;
}
std::sort(m_headerRegions.begin(), m_headerRegions.end());
}
void PegParseResult::parseFencedCodeBlockRegions(QAtomicInt &p_stop)
{
m_codeBlockRegions.clear();
if (isEmpty()) {
return;
}
pmh_element *elem = m_pmhElements[pmh_FENCEDCODEBLOCK];
while (elem != NULL) {
if (elem->end <= elem->pos) {
elem = elem->next;
continue;
}
if (p_stop.load() == 1) {
return;
}
if (!m_codeBlockRegions.contains(m_offset + elem->pos)) {
m_codeBlockRegions.insert(m_offset + elem->pos,
VElementRegion(m_offset + elem->pos, m_offset + elem->end));
}
elem = elem->next;
}
}
void PegParseResult::parseInlineEquationRegions(QAtomicInt &p_stop)
{
parseRegions(p_stop,
pmh_INLINEEQUATION,
m_inlineEquationRegions,
false);
}
void PegParseResult::parseDisplayFormulaRegions(QAtomicInt &p_stop)
{
parseRegions(p_stop,
pmh_DISPLAYFORMULA,
m_displayFormulaRegions,
true);
}
void PegParseResult::parseHRuleRegions(QAtomicInt &p_stop)
{
parseRegions(p_stop,
pmh_HRULE,
m_hruleRegions,
false);
}
void PegParseResult::parseTableRegions(QAtomicInt &p_stop)
{
parseRegions(p_stop,
pmh_TABLE,
m_tableRegions,
true);
}
void PegParseResult::parseTableHeaderRegions(QAtomicInt &p_stop)
{
parseRegions(p_stop,
pmh_TABLEHEADER,
m_tableHeaderRegions,
true);
}
void PegParseResult::parseTableBorderRegions(QAtomicInt &p_stop)
{
parseRegions(p_stop,
pmh_TABLEBORDER,
m_tableBorderRegions,
true);
}
void PegParseResult::parseRegions(QAtomicInt &p_stop,
pmh_element_type p_type,
QVector<VElementRegion> &p_result,
bool p_sort)
{
p_result.clear();
if (isEmpty()) {
return;
}
pmh_element *elem = m_pmhElements[p_type];
while (elem != NULL) {
if (elem->end <= elem->pos) {
elem = elem->next;
continue;
}
if (p_stop.load() == 1) {
return;
}
p_result.push_back(VElementRegion(m_offset + elem->pos, m_offset + elem->end));
elem = elem->next;
}
if (p_sort && p_stop.load() != 1) {
std::sort(p_result.begin(), p_result.end());
}
}
PegParserWorker::PegParserWorker(QObject *p_parent)
: QThread(p_parent),
m_stop(0),
m_state(WorkerState::Idle)
{
}
void PegParserWorker::prepareParse(const QSharedPointer<PegParseConfig> &p_config)
{
Q_ASSERT(m_parseConfig.isNull());
m_state = WorkerState::Busy;
m_parseConfig = p_config;
}
void PegParserWorker::reset()
{
m_parseConfig.reset();
m_parseResult.reset();
m_stop.store(0);
m_state = WorkerState::Idle;
}
void PegParserWorker::stop()
{
m_stop.store(1);
}
void PegParserWorker::run()
{
Q_ASSERT(m_state == WorkerState::Busy);
m_parseResult = parseMarkdown(m_parseConfig, m_stop);
if (isAskedToStop()) {
m_state = WorkerState::Cancelled;
return;
}
m_state = WorkerState::Finished;
}
QSharedPointer<PegParseResult> PegParserWorker::parseMarkdown(const QSharedPointer<PegParseConfig> &p_config,
QAtomicInt &p_stop)
{
QSharedPointer<PegParseResult> result(new PegParseResult(p_config));
if (p_config->m_data.isEmpty()) {
return result;
}
result->m_pmhElements = PegParser::parseMarkdownToElements(p_config);
if (p_stop.load() == 1) {
return result;
}
result->parse(p_stop, p_config->m_fast);
return result;
}
#define NUM_OF_THREADS 2
PegParser::PegParser(QObject *p_parent)
: QObject(p_parent)
{
init();
}
void PegParser::init()
{
for (int i = 0; i < NUM_OF_THREADS; ++i) {
PegParserWorker *th = new PegParserWorker(this);
connect(th, &PegParserWorker::finished,
this, [this, th]() {
handleWorkerFinished(th);
});
m_workers.append(th);
}
}
void PegParser::clear()
{
m_pendingWork.reset();
for (auto const & th : m_workers) {
th->quit();
th->wait();
delete th;
}
m_workers.clear();
}
PegParser::~PegParser()
{
clear();
}
void PegParser::parseAsync(const QSharedPointer<PegParseConfig> &p_config)
{
m_pendingWork = p_config;
pickWorker();
}
QSharedPointer<PegParseResult> PegParser::parse(const QSharedPointer<PegParseConfig> &p_config)
{
QSharedPointer<PegParseResult> result(new PegParseResult(p_config));
if (p_config->m_data.isEmpty()) {
return result;
}
result->m_pmhElements = PegParser::parseMarkdownToElements(p_config);
QAtomicInt stop(0);
result->parse(stop, p_config->m_fast);
return result;
}
void PegParser::handleWorkerFinished(PegParserWorker *p_worker)
{
QSharedPointer<PegParseResult> result;
if (p_worker->state() == WorkerState::Finished) {
result = p_worker->parseResult();
}
p_worker->reset();
pickWorker();
if (!result.isNull()) {
emit parseResultReady(result);
}
}
void PegParser::pickWorker()
{
if (m_pendingWork.isNull()) {
return;
}
bool allBusy = true;
for (auto th : m_workers) {
if (th->state() == WorkerState::Idle) {
scheduleWork(th, m_pendingWork);
m_pendingWork.reset();
return;
} else if (th->state() != WorkerState::Busy) {
allBusy = false;
}
}
if (allBusy) {
// Need to stop the worker with non-minimal timestamp.
int idx = 0;
TimeStamp minTS = m_workers[idx]->workTimeStamp();
if (m_workers.size() > 1) {
if (m_workers[1]->workTimeStamp() > minTS) {
idx = 1;
}
}
m_workers[idx]->stop();
}
}
void PegParser::scheduleWork(PegParserWorker *p_worker,
const QSharedPointer<PegParseConfig> &p_config)
{
Q_ASSERT(p_worker->state() == WorkerState::Idle);
p_worker->reset();
p_worker->prepareParse(p_config);
p_worker->start();
}
QVector<VElementRegion> PegParser::parseImageRegions(const QSharedPointer<PegParseConfig> &p_config)
{
QVector<VElementRegion> regs;
pmh_element **res = PegParser::parseMarkdownToElements(p_config);
if (!res) {
return regs;
}
int offset = p_config->m_offset;
pmh_element *elem = res[pmh_IMAGE];
while (elem != NULL) {
if (elem->end <= elem->pos) {
elem = elem->next;
continue;
}
regs.push_back(VElementRegion(offset + elem->pos, offset + elem->end));
elem = elem->next;
}
pmh_free_elements(res);
return regs;
}
#define MAX_CODE_POINT 65535
#define X_CHAR 86U
#define HAS_UTF8_BOM(x) ( ((*x & 0xFF) == 0xEF)\
&& ((*(x+1) & 0xFF) == 0xBB)\
&& ((*(x+2) & 0xFF) == 0xBF) )
// Calculate the UTF8 code point.
// Return the number of chars consumed.
static inline int utf8CodePoint(const char *p_ch, int &p_codePoint)
{
unsigned char uch = *p_ch;
if ((uch & 0x80) == 0) {
p_codePoint = uch;
return 1;
} else if ((uch & 0xE0) == 0xC0) {
// 110yyyxx 10xxxxxx -> 00000yyy xxxxxxxx
unsigned char uch2 = *(p_ch + 1);
p_codePoint = ((uch & 0x1CL) << 6) + ((uch & 0x3L) << 6) + (uch2 & 0x3FL);
return 2;
} else if ((uch & 0xF0) == 0xE0) {
// 1110yyyy 10yyyyxx 10xxxxxx -> yyyyyyyy xxxxxxxx
unsigned char uch2 = *(p_ch + 1);
unsigned char uch3 = *(p_ch + 2);
p_codePoint = ((uch & 0xF) << 12)
+ ((uch2 & 0x3CL) << 6) + ((uch2 & 0x3L) << 6)
+ (uch3 & 0x3FL);
return 3;
} else if ((uch & 0xF8) == 0xF0) {
// 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -> 000zzzzz yyyyyyyy xxxxxxxx
unsigned char uch2 = *(p_ch + 1);
unsigned char uch3 = *(p_ch + 2);
unsigned char uch4 = *(p_ch + 3);
p_codePoint = ((uch & 0x7L) << 18)
+ ((uch2 & 0x30L) << 12) + ((uch2 & 0xFL) << 12)
+ ((uch3 & 0x3CL) << 6) + ((uch3 & 0x3L) << 6)
+ (uch4 & 0x3FL);
return 4;
} else {
return -1;
}
}
static inline void copyChars(char *p_dest, const char *p_src, int p_num)
{
for (int i = 0; i < p_num; ++i) {
*(p_dest + i) = *(p_src + i);
}
}
// @p_data: UTF-8 data array.
// If @p_data contain unicode characters with code value above 65535, it will break
// it into two characters with code value below 65536.
// Return null if there is no fix. Otherwise, return a fixed copy of the data.
static QSharedPointer<char> tryFixUnicodeData(const char *p_data)
{
bool needFix = false;
int sz = 0;
const char *ch = p_data;
bool hasBOM = false;
if (HAS_UTF8_BOM(ch)) {
hasBOM = true;
ch += 3;
sz += 3;
}
// Calculate the size of fixed data.
while (*ch != '\0') {
int cp;
int nr = utf8CodePoint(ch, cp);
if (nr == -1) {
return NULL;
}
if (cp > MAX_CODE_POINT) {
needFix = true;
ch += nr;
// Use two one-byte chars to replace.
sz += 2;
} else {
ch += nr;
sz += nr;
}
}
if (!needFix) {
return NULL;
}
// Replace those chars with two one-byte chars.
QSharedPointer<char> res(new char[sz + 1]);
char *newChar = res.data();
int idx = 0;
ch = p_data;
if (hasBOM) {
copyChars(newChar + idx, ch, 3);
ch += 3;
idx += 3;
}
while (*ch != '\0') {
int cp;
int nr = utf8CodePoint(ch, cp);
Q_ASSERT(nr > 0);
if (cp > MAX_CODE_POINT) {
*(newChar + idx) = X_CHAR;
*(newChar + idx + 1) = X_CHAR;
ch += nr;
idx += 2;
} else {
copyChars(newChar + idx, ch, nr);
ch += nr;
idx += nr;
}
}
Q_ASSERT(idx == sz);
*(newChar + sz) = '\0';
return res;
}
pmh_element **PegParser::parseMarkdownToElements(const QSharedPointer<PegParseConfig> &p_config)
{
if (p_config->m_data.isEmpty()) {
return NULL;
}
pmh_element **pmhResult = NULL;
// p_config->m_data is encoding in UTF-8.
// QString stores a string of 16-bit QChars. Unicode characters with code values above 65535 are stored using surrogate pairs, i.e., two consecutive QChars.
// Hence, a QString using two QChars to save one code value if it's above 65535, with size()
// returning 2. pmh_markdown_to_elements() will treat it at the size of 1 (expectively).
// To make it work, we split unicode characters whose code value is above 65535 into two unicode
// characters whose code value is below 65535.
char *data = p_config->m_data.data();
QSharedPointer<char> fixedData = tryFixUnicodeData(data);
if (fixedData) {
data = fixedData.data();
}
pmh_markdown_to_elements(data, p_config->m_extensions, &pmhResult);
return pmhResult;
}