-
Notifications
You must be signed in to change notification settings - Fork 61
/
json_parser.cuh
1709 lines (1557 loc) · 51.2 KB
/
json_parser.cuh
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 (c) 2024, NVIDIA CORPORATION.
*
* 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.
*/
#pragma once
#include "ftos_converter.cuh"
#include <cudf/strings/detail/convert/string_to_float.cuh>
#include <cudf/strings/string_view.hpp>
#include <cudf/types.hpp>
#include <thrust/pair.h>
#include <thrust/tuple.h>
namespace spark_rapids_jni {
/**
* write style when writing out JSON string
*/
enum class escape_style {
// e.g.: '\\r' is a string with 2 chars '\' 'r', writes 1 char '\r'
UNESCAPED,
// e.g.: '"' is a string with 1 char '"', writes out 4 chars '"' '\' '\"'
// '"'
ESCAPED
};
/**
* @brief Maximum JSON nesting depth
* JSON with a greater depth is invalid
* If set this to be a greater value, should update `context_stack`
*/
constexpr int max_json_nesting_depth = 64;
//
/**
* Define the maximum JSON number length. Negative or zero means no
* limitation.
*
* By default, maximum JSON number length is negative one, means no
* limitation.
*
* e.g.: The length of number -123.45e-67 is 7. if maximum JSON number length
* is 6, then this number is a invalid number.
*/
constexpr int max_num_len = 1000;
/**
* JSON token enum
*/
enum class json_token {
// start token
INIT = 0,
// successfully parsed the whole JSON string
SUCCESS,
// get error when parsing JSON string
ERROR,
// '{'
START_OBJECT,
// '}'
END_OBJECT,
// '['
START_ARRAY,
// ']'
END_ARRAY,
// e.g.: key1 in {"key1" : "value1"}
FIELD_NAME,
// e.g.: value1 in {"key1" : "value1"}
VALUE_STRING,
// e.g.: 123 in {"key1" : 123}
VALUE_NUMBER_INT,
// e.g.: 1.25 in {"key1" : 1.25}
VALUE_NUMBER_FLOAT,
// e.g.: true in {"key1" : true}
VALUE_TRUE,
// e.g.: false in {"key1" : false}
VALUE_FALSE,
// e.g.: null in {"key1" : null}
VALUE_NULL
};
/**
* This is similar to cudf::string_view, but cudf::string_view enforces
* UTF-8 encoding, which adds overhead that is not needed for this process.
*/
class char_range {
public:
__device__ inline char_range(char const* const start, cudf::size_type const len)
: _data(start), _len(len)
{
}
__device__ inline char_range(cudf::string_view const& input)
: _data(input.data()), _len(input.size_bytes())
{
}
// Warning it looks like there is some kind of a bug in CUDA where you don't want to initialize
// a member variable with a static method like this.
__device__ inline static char_range null() { return char_range(nullptr, 0); }
__device__ inline char_range(char_range const&) = default;
__device__ inline char_range(char_range&&) = default;
__device__ inline char_range& operator=(char_range const&) = default;
__device__ inline char_range& operator=(char_range&&) = default;
__device__ inline ~char_range() = default;
__device__ inline cudf::size_type size() const { return _len; }
__device__ inline char const* data() const { return _data; }
__device__ inline char const* start() const { return _data; }
__device__ inline char const* end() const { return _data + _len; }
__device__ inline bool eof(cudf::size_type pos) const { return pos >= _len; }
__device__ inline bool is_null() const { return _data == nullptr; }
__device__ inline bool is_empty() const { return _len == 0; }
__device__ inline char operator[](cudf::size_type pos) const { return _data[pos]; }
__device__ inline cudf::string_view slice_sv(cudf::size_type pos, cudf::size_type len) const
{
return cudf::string_view(_data + pos, len);
}
__device__ inline char_range slice(cudf::size_type pos, cudf::size_type len) const
{
return char_range(_data + pos, len);
}
private:
char const* _data;
cudf::size_type _len;
};
/**
* A char_range that keeps track of where in the data it currently is.
*/
class char_range_reader {
public:
__device__ inline explicit char_range_reader(char_range range) : _range(range), _pos(0) {}
__device__ inline char_range_reader(char_range range, cudf::size_type start)
: _range(range), _pos(start)
{
}
__device__ inline bool eof() const { return _range.eof(_pos); }
__device__ inline bool is_null() const { return _range.is_null(); }
__device__ inline void next() { _pos++; }
__device__ inline char current_char() const { return _range[_pos]; }
__device__ inline cudf::size_type pos() const { return _pos; }
private:
char_range _range;
cudf::size_type _pos;
};
/**
* JSON parser, provides token by token parsing.
* Follow Jackson JSON format by default.
*
*
* For JSON format:
* Refer to https://www.json.org/json-en.html.
*
* Note: This is not conventional as it allows
* single quotes and unescaped control characters
* to match what SPARK does for get_json_object
*
* White space can only be 4 chars: ' ', '\n', '\r', '\t',
* Jackson does not allow other control chars as white spaces.
*
* Valid number examples:
* 0, 102, -0, -102, 0.3, -0.3
* 1e-5, 1E+5, 1e0, 1E0, 1.3e5
* 1e01 : allow leading zeor after 'e'
*
* Invalid number examples:
* 00, -00 Leading zeroes not allowed
* infinity, +infinity, -infinity
* 1e, 1e+, 1e-, -1., 1.
*
* Valid string examples:
* "\'" , "\"" , '\'' , '\"' , '"' , "'"
*
* Valid string: "ascii_control_chars"
* here `ascii_control_chars` represents control chars which in Ascii code
* range: [0, 32)
*
*/
class json_parser {
public:
__device__ inline explicit json_parser(char_range _chars)
: chars(_chars), curr_pos(0), current_token(json_token::INIT)
{
}
private:
/**
* @brief get the bit value for specified bit from a int64 number
*/
__device__ inline bool get_bit_value(int64_t number, int bitIndex)
{
// Shift the number right by the bitIndex to bring the desired bit to the rightmost position
long shifted = number >> bitIndex;
// Extract the rightmost bit by performing a bitwise AND with 1
bool bit_value = shifted & 1;
return bit_value;
}
/**
* @brief set the bit value for specified bit to a int64 number
*/
__device__ inline void set_bit_value(int64_t& number, int bit_index, bool bit_value)
{
// Create a mask with a 1 at the desired bit index
long mask = 1L << bit_index;
if (bit_value) {
// Set the bit to 1 by performing a bitwise OR with the mask
number |= mask;
} else {
// Set the bit to 0 by performing a bitwise AND with the complement of the mask
number &= ~mask;
}
}
/**
* is current position EOF
*/
__device__ inline bool eof(cudf::size_type pos) const { return pos >= chars.size(); }
__device__ inline bool eof() const { return curr_pos >= chars.size(); }
/**
* is hex digits: 0-9, A-F, a-f
*/
__device__ inline bool is_hex_digit(char c) const
{
return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f');
}
/**
* is 0 to 9 digit
*/
__device__ inline bool is_digit(char c) const { return (c >= '0' && c <= '9'); }
/**
* is white spaces: ' ', '\t', '\n' '\r'
*/
__device__ inline bool is_whitespace(char c) const
{
return c == ' ' || c == '\t' || c == '\n' || c == '\r';
}
/**
* skips 4 characters: ' ', '\t', '\n' '\r'
*/
__device__ inline void skip_whitespaces()
{
while (!eof() && is_whitespace(chars[curr_pos])) {
curr_pos++;
}
}
/**
* check current char, if it's expected, then plus the position
*/
__device__ inline bool try_skip(char_range_reader& reader, char expected)
{
if (!reader.eof() && reader.current_char() == expected) {
reader.next();
return true;
}
return false;
}
__device__ inline bool try_skip(cudf::size_type& pos, char expected)
{
if (!eof(pos) && chars[pos] == expected) {
pos++;
return true;
}
return false;
}
/**
* try to push current context into stack
* if nested depth exceeds limitation, return false
*/
__device__ inline bool try_push_context(json_token token)
{
if (stack_size < max_json_nesting_depth) {
push_context(token);
return true;
} else {
return false;
}
}
/**
* record the nested state into stack: JSON object or JSON array
*/
__device__ inline void push_context(json_token token)
{
bool v = json_token::START_OBJECT == token ? true : false;
set_bit_value(context_stack, stack_size, v);
stack_size++;
}
/**
* whether the top of nested context stack is JSON object context
* true is object, false is array
* only has two contexts: object or array
*/
__device__ inline bool is_object_context()
{
return get_bit_value(context_stack, stack_size - 1);
}
/**
* pop top context from stack
*/
__device__ inline void pop_curr_context() { stack_size--; }
/**
* is context stack is empty
*/
__device__ inline bool is_context_stack_empty() { return stack_size == 0; }
__device__ inline void set_current_error() { current_token = json_token::ERROR; }
/**
* parse the first value token from current position
* e.g., after finished this function:
* current token is START_OBJECT if current value is object
* current token is START_ARRAY if current value is array
* current token is string/num/true/false/null if current value is terminal
* current token is ERROR if parse failed
*/
__device__ inline void parse_first_token_in_value_and_set_current()
{
current_token_start_pos = curr_pos;
// already checked eof
char c = chars[curr_pos];
switch (c) {
case '{':
if (!try_push_context(json_token::START_OBJECT)) {
set_current_error();
} else {
curr_pos++;
current_token = json_token::START_OBJECT;
}
break;
case '[':
if (!try_push_context(json_token::START_ARRAY)) {
set_current_error();
} else {
curr_pos++;
current_token = json_token::START_ARRAY;
}
break;
case '"':
// fall through
case '\'': parse_string_and_set_current(); break;
case 't':
curr_pos++;
parse_true_and_set_current();
break;
case 'f':
curr_pos++;
parse_false_and_set_current();
break;
case 'n':
curr_pos++;
parse_null_and_set_current();
break;
default: parse_number_and_set_current(); break;
}
}
// =========== Parse string begin ===========
/**
* parse quoted string and set current token
*/
__device__ inline void parse_string_and_set_current()
{
// TODO eventually chars should be a reader so we can just pass it in...
char_range_reader reader(chars, curr_pos);
auto [success, end_char_pos] = try_parse_string(reader);
if (success) {
// TODO remove end_char_pos, and just get it from the reader...
curr_pos = end_char_pos;
current_token = json_token::VALUE_STRING;
} else {
set_current_error();
}
}
/**
* transform int value from [0, 15] to hex char
*/
__device__ inline char to_hex_char(unsigned int v)
{
if (v < 10)
return '0' + v;
else
return 'A' + (v - 10);
}
/**
* escape control char ( ASCII code value [0, 32) )
* e.g.: \0 (ASCII code 0) will be escaped to 6 chars: \u0000
* e.g.: \10 (ASCII code 0) will be escaped to 2 chars: \n
* @param char to be escaped, c should in range [0, 31)
* @param[out] escape output
*/
__device__ inline int escape_char(unsigned char c, char* output)
{
if (nullptr == output) {
switch (c) {
case 8: // \b
case 9: // \t
case 10: // \n
case 12: // \f
case 13: return 2; // \r
default: return 6; // \u0000
}
}
switch (c) {
case 8:
output[0] = '\\';
output[1] = 'b';
return 2;
case 9:
output[0] = '\\';
output[1] = 't';
return 2;
case 10:
output[0] = '\\';
output[1] = 'n';
return 2;
case 12:
output[0] = '\\';
output[1] = 'f';
return 2;
case 13:
output[0] = '\\';
output[1] = 'r';
return 2;
default:
output[0] = '\\';
output[1] = 'u';
output[2] = '0';
output[3] = '0';
// write high digit
if (c >= 16) {
output[4] = '1';
} else {
output[4] = '0';
}
// write low digit
unsigned int v = c % 16;
output[5] = to_hex_char(v);
return 6;
}
}
__device__ inline int write_string(char_range_reader& str,
char* copy_destination,
escape_style w_style)
{
if (str.eof()) { return 0; }
char const quote_char = str.current_char();
int output_size_bytes = 0;
// write the first " if write style is escaped
if (escape_style::ESCAPED == w_style) {
output_size_bytes++;
if (nullptr != copy_destination) { *copy_destination++ = '"'; }
}
// skip left quote char
// No need to check because we just read it in.
str.next();
// scan string content
while (!str.eof()) {
char const c = str.current_char();
int const v = static_cast<int>(c);
if (c == quote_char) {
// path 1: match closing quote char
str.next();
// write the end " if write style is escaped
if (escape_style::ESCAPED == w_style) {
output_size_bytes++;
if (nullptr != copy_destination) { *copy_destination++ = '"'; }
}
return output_size_bytes;
} else if (v >= 0 && v < 32) {
// path 2: unescaped control char
// copy if enabled, unescape mode, write 1 char
if (escape_style::UNESCAPED == w_style) {
output_size_bytes++;
if (copy_destination != nullptr) { *copy_destination++ = str.current_char(); }
} else {
// escape_style::ESCAPED
int const escape_chars = escape_char(str.current_char(), copy_destination);
if (copy_destination != nullptr) { copy_destination += escape_chars; }
output_size_bytes += escape_chars;
}
str.next();
} else if ('\\' == c) {
// path 3: escape path
str.next();
char_range_reader to_match(char_range::null());
if (!try_skip_escape_part(str, to_match, copy_destination, w_style, output_size_bytes)) {
return output_size_bytes;
}
} else {
// path 4: safe code point
// handle single unescaped " char; happens when string is quoted by char '
// e.g.: 'A"' string, escape to "A\\"" (5 chars: " A \ " ")
if ('\"' == c && escape_style::ESCAPED == w_style) {
if (copy_destination != nullptr) { *copy_destination++ = '\\'; }
output_size_bytes++;
}
if (copy_destination != nullptr) { *copy_destination++ = c; }
str.next();
output_size_bytes++;
}
}
// technically this is an error state, but we will do our best from here...
return output_size_bytes;
}
/**
* utility for parsing string, this function does not update the parser
* internal try parse quoted string using passed `quote_char` `quote_char` can
* be ' or " For UTF-8 encoding: Single byte char: The most significant bit of
* the byte is always 0 Two-byte characters: The leading bits of the first
* byte are 110, and the leading bits of the second byte are 10. Three-byte
* characters: The leading bits of the first byte are 1110, and the leading
* bits of the second and third bytes are 10. Four-byte characters: The
* leading bits of the first byte are 11110, and the leading bits of the
* second, third, and fourth bytes are 10. Because JSON structural chars([ ] {
* } , :), string quote char(" ') and Escape char \ are all Ascii(The leading
* bit is 0), so it's safe that do not convert byte array to UTF-8 char.
*
* When quote is " grammar is:
*
* STRING
* : '"' (ESC | SAFECODEPOINT)* '"'
* ;
*
* fragment ESC
* : '\\' (["\\/bfnrt] | UNICODE)
* ;
*
* fragment UNICODE
* : 'u' HEX HEX HEX HEX
* ;
*
* fragment HEX
* : [0-9a-fA-F]
* ;
*
* fragment SAFECODEPOINT
* // 1 not " or '
* // 2 not \
* // 3 non control character: Ascii value not in [0, 32)
* : ~ ["\\\u0000-\u001F]
* ;
*
* @param str string to parse
* @param to_match expected match str
* @param w_style the escape style for writing.
* @return a pair of success and length, where success is true if the string
* is valid and length is the number of bytes needed to encode the string
* in the given style.
*/
__device__ inline std::pair<bool, cudf::size_type> try_parse_string(
char_range_reader& str,
char_range_reader to_match = char_range_reader(char_range::null()),
escape_style w_style = escape_style::UNESCAPED)
{
if (str.eof()) { return std::make_pair(false, 0); }
char const quote_char = str.current_char();
int output_size_bytes = 0;
// write the first " if write style is escaped
if (escape_style::ESCAPED == w_style) { output_size_bytes++; }
// skip left quote char
// We don't need to actually verify what it is, because we just read it.
str.next();
// scan string content
while (!str.eof()) {
char c = str.current_char();
int v = static_cast<int>(c);
if (c == quote_char) {
// path 1: match closing quote char
str.next();
// match check, the last char in match_str is quote_char
if (!to_match.is_null() && !to_match.eof()) { return std::make_pair(false, 0); }
// write the end " if write style is escaped
if (escape_style::ESCAPED == w_style) { output_size_bytes++; }
return std::make_pair(true, str.pos());
} else if (v >= 0 && v < 32) {
// path 2: unescaped control char
// copy if enabled, escape mode, write more chars
if (escape_style::ESCAPED == w_style) {
int escape_chars = escape_char(str.current_char(), nullptr);
output_size_bytes += (escape_chars - 1);
}
// check match if enabled
if (!try_match_char(to_match, str.current_char())) { return std::make_pair(false, 0); }
str.next();
output_size_bytes++;
continue;
} else if ('\\' == c) {
// path 3: escape path
str.next();
char* copy_dest_nullptr = nullptr;
if (!try_skip_escape_part(str, to_match, copy_dest_nullptr, w_style, output_size_bytes)) {
return std::make_pair(false, 0);
}
} else {
// path 4: safe code point
// handle single unescaped " char; happens when string is quoted by char '
// e.g.: 'A"' string, escape to "A\\"" (5 chars: " A \ " ")
if ('\"' == c && escape_style::ESCAPED == w_style) { output_size_bytes++; }
if (!try_skip_safe_code_point(str, c)) { return std::make_pair(false, 0); }
// check match if enabled
if (!try_match_char(to_match, c)) { return std::make_pair(false, 0); }
output_size_bytes++;
}
}
return std::make_pair(false, 0);
}
__device__ inline bool try_match_char(char_range_reader& reader, char c)
{
if (!reader.is_null()) {
if (!reader.eof() && reader.current_char() == c) {
reader.next();
return true;
} else {
return false;
}
} else {
return true;
}
}
/**
* skip the second char in \", \', \\, \/, \b, \f, \n, \r, \t;
* skip the HEX chars in \u HEX HEX HEX HEX.
* @return positive escaped ASCII value if success, -1 otherwise
*/
__device__ inline bool try_skip_escape_part(char_range_reader& str,
char_range_reader& to_match,
char*& copy_dest,
escape_style w_style,
int& output_size_bytes)
{
// already skipped the first '\'
// try skip second part
if (!str.eof()) {
char const c = str.current_char();
switch (c) {
// path 1: \", \', \\, \/, \b, \f, \n, \r, \t
case '\"':
if (nullptr != copy_dest && escape_style::UNESCAPED == w_style) { *copy_dest++ = c; }
if (escape_style::ESCAPED == w_style) {
if (copy_dest != nullptr) {
*copy_dest++ = '\\';
*copy_dest++ = '"';
}
output_size_bytes++;
}
if (!try_match_char(to_match, c)) { return false; }
output_size_bytes++;
str.next();
return true;
case '\'':
// for both unescaped/escaped writes a single char '
if (nullptr != copy_dest) { *copy_dest++ = c; }
if (!try_match_char(to_match, c)) { return false; }
output_size_bytes++;
str.next();
return true;
case '\\':
if (nullptr != copy_dest && escape_style::UNESCAPED == w_style) { *copy_dest++ = c; }
if (escape_style::ESCAPED == w_style) {
if (copy_dest != nullptr) {
*copy_dest++ = '\\';
*copy_dest++ = '\\';
}
output_size_bytes++;
}
if (!try_match_char(to_match, c)) { return false; }
output_size_bytes++;
str.next();
return true;
case '/':
// for both unescaped/escaped writes a single char /
if (nullptr != copy_dest) { *copy_dest++ = c; }
if (!try_match_char(to_match, c)) { return false; }
output_size_bytes++;
str.next();
return true;
case 'b':
if (nullptr != copy_dest && escape_style::UNESCAPED == w_style) { *copy_dest++ = '\b'; }
if (escape_style::ESCAPED == w_style) {
if (copy_dest != nullptr) {
*copy_dest++ = '\\';
*copy_dest++ = 'b';
}
output_size_bytes++;
}
if (!try_match_char(to_match, '\b')) { return false; }
output_size_bytes++;
str.next();
return true;
case 'f':
if (nullptr != copy_dest && escape_style::UNESCAPED == w_style) { *copy_dest++ = '\f'; }
if (escape_style::ESCAPED == w_style) {
if (copy_dest != nullptr) {
*copy_dest++ = '\\';
*copy_dest++ = 'f';
}
output_size_bytes++;
}
if (!try_match_char(to_match, '\f')) { return false; }
output_size_bytes++;
str.next();
return true;
case 'n':
if (nullptr != copy_dest && escape_style::UNESCAPED == w_style) { *copy_dest++ = '\n'; }
if (escape_style::ESCAPED == w_style) {
if (copy_dest != nullptr) {
*copy_dest++ = '\\';
*copy_dest++ = 'n';
}
output_size_bytes++;
}
if (!try_match_char(to_match, '\n')) { return false; }
output_size_bytes++;
str.next();
return true;
case 'r':
if (nullptr != copy_dest && escape_style::UNESCAPED == w_style) { *copy_dest++ = '\r'; }
if (escape_style::ESCAPED == w_style) {
if (copy_dest != nullptr) {
*copy_dest++ = '\\';
*copy_dest++ = 'r';
}
output_size_bytes++;
}
if (!try_match_char(to_match, '\r')) { return false; }
output_size_bytes++;
str.next();
return true;
case 't':
if (nullptr != copy_dest && escape_style::UNESCAPED == w_style) { *copy_dest++ = '\t'; }
if (escape_style::ESCAPED == w_style) {
if (copy_dest != nullptr) {
*copy_dest++ = '\\';
*copy_dest++ = 't';
}
output_size_bytes++;
}
if (!try_match_char(to_match, '\t')) { return false; }
output_size_bytes++;
str.next();
return true;
// path 1 done: \", \', \\, \/, \b, \f, \n, \r, \t
case 'u':
// path 2: \u HEX HEX HEX HEX
str.next();
// for both unescaped/escaped writes corresponding utf8 bytes, no need
// to pass in write style
return try_skip_unicode(str, to_match, copy_dest, output_size_bytes);
default:
// path 3: invalid
return false;
}
} else {
// eof, no escaped char after char '\'
return false;
}
}
/**
* parse:
* fragment SAFECODEPOINT
* // 1 not " or '
* // 2 not \
* // 3 non control character: Ascii value not in [0, 32)
* : ~ ["\\\u0000-\u001F]
* ;
*/
__device__ inline bool try_skip_safe_code_point(char_range_reader& str, char c)
{
// 1 the char is not quoted(' or ") char, here satisfy, do not need to check
// again
// 2. the char is not \, here satisfy, do not need to check again
// 3. chars not in [0, 32)
int v = static_cast<int>(c);
if (!(v >= 0 && v < 32)) {
str.next();
return true;
} else {
return false;
}
}
/**
* convert chars 0-9, a-f, A-F to int value
*/
__device__ inline uint8_t hex_value(char c)
{
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return 0;
}
/**
* @brief Returns the number of bytes in the specified character.
*
* @param character Single character
* @return Number of bytes
*/
__device__ cudf::size_type bytes_in_char_utf8(cudf::char_utf8 character)
{
return 1 + static_cast<cudf::size_type>((character & 0x0000'FF00u) > 0) +
static_cast<cudf::size_type>((character & 0x00FF'0000u) > 0) +
static_cast<cudf::size_type>((character & 0xFF00'0000u) > 0);
}
/**
* @brief Converts a character code-point value into a UTF-8 character.
*
* @param unchr Character code-point to convert.
* @return Single UTF-8 character.
*/
__device__ cudf::char_utf8 codepoint_to_utf8(uint32_t unchr)
{
cudf::char_utf8 utf8 = 0;
if (unchr < 0x0000'0080) {
// single byte utf8
utf8 = unchr;
} else if (unchr < 0x0000'0800) {
// double byte utf8
utf8 = (unchr << 2) & 0x1F00;
utf8 |= (unchr & 0x3F);
utf8 |= 0x0000'C080;
} else if (unchr < 0x0001'0000) {
// triple byte utf8
utf8 = (unchr << 4) & 0x0F'0000;
utf8 |= (unchr << 2) & 0x00'3F00;
utf8 |= (unchr & 0x3F);
utf8 |= 0x00E0'8080;
} else if (unchr < 0x0011'0000) {
// quadruple byte utf8
utf8 = (unchr << 6) & 0x0700'0000;
utf8 |= (unchr << 4) & 0x003F'0000;
utf8 |= (unchr << 2) & 0x0000'3F00;
utf8 |= (unchr & 0x3F);
utf8 |= 0xF080'8080u;
}
return utf8;
}
/**
* @brief Place a char_utf8 value into a char array.
*
* @param character Single character
* @param[out] str Output array.
* @return The number of bytes in the character
*/
__device__ cudf::size_type from_char_utf8(cudf::char_utf8 character, char* str)
{
cudf::size_type const chr_width = bytes_in_char_utf8(character);
for (cudf::size_type idx = 0; idx < chr_width; ++idx) {
str[chr_width - idx - 1] = static_cast<char>(character) & 0xFF;
character = character >> 8;
}
return chr_width;
}
/**
* try skip 4 HEX chars
* in pattern: '\\' 'u' HEX HEX HEX HEX, it's a code point of unicode
*/
__device__ bool try_skip_unicode(char_range_reader& str,
char_range_reader& to_match,
char*& copy_dest,
int& output_size_bytes)
{
// already parsed \u
// now we expect 4 hex chars.
cudf::char_utf8 code_point = 0;
for (size_t i = 0; i < 4; i++) {
if (str.eof()) { return false; }
char const c = str.current_char();
str.next();
if (!is_hex_digit(c)) { return false; }
code_point = (code_point * 16) + hex_value(c);
}
auto utf_char = codepoint_to_utf8(code_point);
// write utf8 bytes.
// In UTF-8, the maximum number of bytes used to encode a single character
// is 4
char buff[4];
cudf::size_type const bytes = from_char_utf8(utf_char, buff);
output_size_bytes += bytes;
// TODO I think if we do an escape sequence for \n/etc it will return
// the wrong thing....
if (nullptr != copy_dest) {
for (cudf::size_type i = 0; i < bytes; i++) {
*copy_dest++ = buff[i];
}
}
if (!to_match.is_null()) {
for (cudf::size_type i = 0; i < bytes; i++) {
if (!(to_match.eof() && to_match.current_char() == buff[i])) { return false; }
to_match.next();
}
}
return true;
}
// =========== Parse string end ===========
// =========== Parse number begin ===========
/**
* parse number, grammar is:
* NUMBER
* : '-'? INT ('.' [0-9]+)? EXP?