-
Notifications
You must be signed in to change notification settings - Fork 244
/
Copy pathRegexParser.scala
2163 lines (1988 loc) · 78.6 KB
/
RegexParser.scala
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) 2021-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.
*/
package com.nvidia.spark.rapids
import java.sql.SQLException
import scala.collection.mutable.ListBuffer
import com.nvidia.spark.rapids.GpuOverrides.regexMetaChars
import com.nvidia.spark.rapids.RegexParser.toReadableString
/**
* Regular expression parser based on a Pratt Parser design.
*
* The goal of this parser is to build a minimal AST that allows us
* to validate that we can support the expression on the GPU. The goal
* is not to parse with the level of detail that would be required if
* we were building an evaluation engine. For example, operator precedence is
* largely ignored but could be added if we need it later.
*
* The Java and cuDF regular expression documentation has been used as a reference:
*
* Java regex: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
* cuDF regex: https://docs.rapids.ai/api/libcudf/stable/md_regex.html
*
* The following blog posts provide some background on Pratt Parsers and parsing regex.
*
* - https://journal.stuffwithstuff.com/2011/03/19/pratt-parsers-expression-parsing-made-easy/
* - https://matt.might.net/articles/parsing-regex-with-recursive-descent/
*/
class RegexParser(pattern: String) {
// Note that [, ] and \ should be part of Punct, but they are handled separately
private val regexPunct = """!"#$%&'()*+,-./:;<=>?@^_`{|}~"""
private val escapeChars = Map('n' -> '\n', 'r' -> '\r', 't' -> '\t', 'f' -> '\f', 'a' -> '\u0007',
'b' -> '\b', 'e' -> '\u001b')
/** index of current position within the string being parsed */
private var pos = 0
def parse(): RegexAST = {
val ast = parseUntil(() => eof())
if (!eof()) {
throw new RegexUnsupportedException("Failed to parse full regex. Last character parsed was",
Some(pos))
}
ast
}
def parseReplacement(numCaptureGroups: Int): RegexReplacement = {
val sequence = RegexReplacement(new ListBuffer(), numCaptureGroups)
while (!eof()) {
parseReplacementBase() match {
case RegexSequence(parts) =>
sequence.parts ++= parts
case other =>
sequence.parts += other
}
}
sequence
}
private def parseReplacementBase(): RegexAST = {
consume() match {
case '\\' =>
parseBackrefOrEscaped()
case '$' =>
parseBackrefOrLiteralDollar()
case other =>
RegexChar(other)
}
}
private def parseUntil(until: () => Boolean): RegexAST = {
val term = parseTerm(() => until() || peek().contains('|'))
if (!eof() && peek().contains('|')) {
consumeExpected('|')
new RegexChoice(term, parseUntil(until), pos)
} else {
term
}
}
private def parseTerm(until: () => Boolean): RegexAST = {
val sequence = new RegexSequence(new ListBuffer(), pos)
while (!eof() && !until()) {
parseFactor(until) match {
case RegexSequence(parts) =>
sequence.parts ++= parts
case other =>
sequence.parts += other
}
}
sequence
}
private def isValidQuantifierAhead(): Boolean = {
if (peek().contains('{')) {
val bookmark = pos
consumeExpected('{')
val q = parseQuantifierOrLiteralBrace()
pos = bookmark
q match {
case _: QuantifierFixedLength | _: QuantifierVariableLength => true
case _ => false
}
} else {
false
}
}
private def parseFactor(until: () => Boolean): RegexAST = {
var start = pos
var base = parseBase()
base.position = Some(start)
while (!eof() && !until()
&& (peek().exists(ch => ch == '*' || ch == '+' || ch == '?')
|| isValidQuantifierAhead())) {
start = pos
val quantifier = if (peek().contains('{')) {
consumeExpected('{')
parseQuantifierOrLiteralBrace().asInstanceOf[RegexQuantifier]
} else {
SimpleQuantifier(consume())
}
base = new RegexRepetition(base, quantifier, start)
quantifier.position = Some(pos-1)
}
base
}
private def parseBase(): RegexAST = {
val start = pos
val base: RegexAST = consume() match {
case '(' =>
parseGroup()
case '[' =>
parseCharacterClass()
case ']' =>
RegexEscaped(']')
case '}' =>
RegexEscaped('}')
case '\\' =>
parseEscapedCharacter()
case '\u0000' =>
RegexGroup(false, RegexEscaped('0'), None)
case '*' | '+' | '?' =>
throw new RegexUnsupportedException(
"Base expression cannot start with quantifier", Some(pos-1))
case other =>
RegexChar(other)
}
base.position = Some(start)
base
}
private def parseGroup(): RegexAST = {
var captureGroup = if (pos + 1 < pattern.length
&& pattern.charAt(pos) == '?'
&& pattern.charAt(pos+1) == ':') {
pos += 2
false
} else {
true
}
val lookahead = if (pos + 1 < pattern.length
&& "!=".contains(pattern.charAt(pos))) {
pos += 1
captureGroup = false
pattern.charAt(pos-1) match {
case '=' => Some(RegexPositiveLookahead)
case '!' => Some(RegexNegativeLookahead)
}
} else {
None
}
val term = parseUntil(() => peek().contains(')'))
consumeExpected(')')
RegexGroup(captureGroup, term, lookahead)
}
private def parseCharacterClass(): RegexCharacterClass = {
val supportedMetaCharacters = "\\^-[]+."
def getEscapedComponent(): RegexCharacterClassComponent = {
peek() match {
case Some('x') =>
consumeExpected('x')
val hexChar = parseHexDigit
hexChar.codePoint match {
case 0 => hexChar
case codePoint => RegexChar(codePoint.toChar)
}
case Some('0') =>
val octalChar = parseOctalDigit
octalChar.codePoint match {
case 0 => RegexHexDigit("00")
case codePoint => RegexChar(codePoint.toChar)
}
case Some(ch) =>
consumeExpected(ch) match {
// NOTE: Should switch to ASCII mode to simplify and expand this fix
case 'd' => RegexCharacterRange(RegexChar('0'), RegexChar('9'))
// List of character literals with an escape from here, under "Characters"
// https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html
case ch if escapeChars.contains(ch) =>
RegexChar(escapeChars(ch))
case ch =>
if (supportedMetaCharacters.contains(ch)) {
// an escaped metacharacter ('\\', '^', '-', ']', '+')
RegexEscaped(ch)
} else {
throw new RegexUnsupportedException(
s"Unsupported escaped character '$ch' in character class", Some(pos-1))
}
}
case None =>
throw new RegexUnsupportedException(
s"Unclosed character class", Some(pos))
}
}
val start = pos
val characterClass = new RegexCharacterClass(negated = false, characters = ListBuffer(), pos)
// loop until the end of the character class or EOF
var characterClassComplete = false
while (!eof() && !characterClassComplete) {
val ch = consume()
ch match {
case '[' =>
// treat as a literal character and add to the character class
characterClass.append(new RegexChar(ch, pos-1))
case ']' if (!characterClass.negated && pos > start + 1) ||
(characterClass.negated && pos > start + 2) =>
// "[]" is not a valid character class
// "[]a]" is a valid character class containing the characters "]" and "a"
// "[^]a]" is a valid negated character class containing the characters "]" and "a"
characterClassComplete = true
case '^' if pos == start + 1 =>
// Negates the character class, causing it to match a single character not listed in
// the character class. Only valid immediately after the opening '['
characterClass.negated = true
case ch =>
val nextChar: RegexCharacterClassComponent = ch match {
case '\\' =>
getEscapedComponent() match {
case RegexChar(ch) if supportedMetaCharacters.contains(ch) =>
// A hex or octal representation of a meta character gets treated as an escaped
// char. Example: [\x5ea] is treated as [\^a], not just [^a]
RegexEscaped(ch)
case other => other
}
case '&' =>
peek() match {
case Some('&') =>
throw new RegexUnsupportedException("" +
"cuDF does not support class intersection operator &&", Some(pos-1))
case _ => // ignore
}
RegexChar('&')
case '\u0000' =>
RegexHexDigit("00")
case ch =>
RegexChar(ch)
}
nextChar.position = Some(pos-1)
peek() match {
case Some('-') =>
consumeExpected('-')
peek() match {
case Some(']') =>
// '-' at end of class e.g. "[abc-]"
characterClass.append(nextChar)
characterClass.append('-')
case Some('\\') =>
consumeExpected('\\')
characterClass.appendRange(nextChar, getEscapedComponent())
case Some(end) =>
skip()
characterClass.appendRange(nextChar, RegexChar(end))
case _ =>
throw new RegexUnsupportedException(
"Unexpected EOF while parsing character range", Some(pos))
}
case _ =>
characterClass.append(nextChar)
}
}
}
if (!characterClassComplete) {
throw new RegexUnsupportedException(s"Unclosed character class", Some(pos))
}
characterClass
}
/**
* Parse a quantifier in one of the following formats:
*
* {n}
* {n,}
* {n,m} (only valid if m >= n)
*/
private def parseQuantifierOrLiteralBrace(): RegexAST = {
// assumes that '{' has already been consumed
val start = pos
def treatAsLiteralBrace() = {
// this was not a quantifier, just a literal '{'
pos = start + 1
RegexChar('{')
}
consumeInt match {
case Some(minLength) =>
peek() match {
case Some(',') =>
consumeExpected(',')
val max = consumeInt()
if (peek().contains('}')) {
consumeExpected('}')
max match {
case None =>
QuantifierVariableLength(minLength, None)
case Some(m) =>
if (m >= minLength) {
QuantifierVariableLength(minLength, max)
} else {
treatAsLiteralBrace()
}
}
} else {
treatAsLiteralBrace()
}
case Some('}') =>
consumeExpected('}')
QuantifierFixedLength(minLength)
case _ =>
treatAsLiteralBrace()
}
case None =>
treatAsLiteralBrace()
}
}
private def parseBackrefOrEscaped(): RegexAST = {
val start = pos
consumeInt match {
case Some(refNum) =>
RegexBackref(refNum)
case None =>
pos = start
RegexChar('\\')
}
}
private def parseBackrefOrLiteralDollar(): RegexAST = {
val start = pos
def treatAsLiteralDollar() = {
pos = start
RegexChar('$')
}
peek() match {
case Some('{') =>
consumeExpected('{')
val num = consumeInt()
if (peek().contains('}')) {
consumeExpected('}')
num match {
case Some(n) =>
RegexBackref(n)
case _ =>
treatAsLiteralDollar()
}
} else {
treatAsLiteralDollar()
}
case Some(ch) if ch >= '1' && ch <= '9' =>
val num = consumeInt()
num match {
case Some(n) =>
RegexBackref(n)
case _ =>
treatAsLiteralDollar()
}
case _ =>
treatAsLiteralDollar()
}
}
private def parseEscapedCharacter(): RegexAST = {
peek() match {
case None =>
throw new RegexUnsupportedException("Pattern may not end with trailing escape", Some(pos))
case Some(ch) =>
ch match {
case 'A' | 'Z' | 'z' =>
// string anchors
consumeExpected(ch)
RegexEscaped(ch)
case 's' | 'S' | 'd' | 'D' | 'w' | 'W' | 'v' | 'V' | 'h' | 'H' | 'R' =>
// meta sequences
consumeExpected(ch)
RegexEscaped(ch)
case 'B' | 'b' =>
// word boundaries
consumeExpected(ch)
RegexEscaped(ch)
case '[' | ']' | '\\' | '^' | '$' | '.' | '|' | '?' | '*' | '+' | '(' | ')' | '{' | '}' =>
// escaped metacharacter
consumeExpected(ch)
RegexEscaped(ch)
case 'x' =>
consumeExpected(ch)
parseHexDigit
case '0' =>
parseOctalDigit
case 'p' | 'P' =>
parsePredefinedClass
case _ if escapeChars.contains(ch) =>
consumeExpected(ch)
RegexChar(escapeChars(ch))
case _ if regexPunct.contains(ch) =>
// other punctuation
// note that this may include metacharacters from earlier, this is just to
// handle characters not covered by the previous cases earlier
consumeExpected(ch)
RegexEscaped(ch)
case other =>
throw new RegexUnsupportedException(
s"Invalid or unsupported escape character '$other'", Some(pos - 1))
}
}
}
private def parsePredefinedClass: RegexCharacterClass = {
val negated = consume().isUpper
consumeExpected('{')
val start = pos
while(!eof() && pattern.charAt(pos).isLetter) {
pos += 1
}
val className = pattern.substring(start, pos)
def getCharacters(className: String): ListBuffer[RegexCharacterClassComponent] = {
// Character lists from here:
// https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html
className match {
case "Lower" =>
ListBuffer(RegexCharacterRange(RegexChar('a'), RegexChar('z')))
case "Upper" =>
ListBuffer(RegexCharacterRange(RegexChar('A'), RegexChar('Z')))
case "ASCII" =>
ListBuffer(RegexCharacterRange(RegexHexDigit("00"), RegexChar('\u007f')))
case "Alpha" =>
ListBuffer(getCharacters("Lower"), getCharacters("Upper")).flatten
case "Digit" =>
ListBuffer(RegexCharacterRange(RegexChar('0'), RegexChar('9')))
case "Alnum" =>
ListBuffer(getCharacters("Alpha"), getCharacters("Digit")).flatten
case "Punct" =>
val res:ListBuffer[RegexCharacterClassComponent] =
ListBuffer(regexPunct.map(RegexChar): _*)
res ++= ListBuffer(RegexEscaped('['), RegexEscaped(']'), RegexEscaped('\\'))
case "Graph" =>
ListBuffer(getCharacters("Alnum"), getCharacters("Punct")).flatten
case "Print" =>
val res = getCharacters("Graph")
res += RegexChar('\u0020')
case "Blank" =>
ListBuffer(RegexChar(' '), RegexEscaped('t'))
case "Cntrl" =>
ListBuffer(RegexCharacterRange(RegexHexDigit("00"), RegexChar('\u001f')),
RegexChar('\u007f'))
case "XDigit" =>
ListBuffer(RegexCharacterRange(RegexChar('0'), RegexChar('9')),
RegexCharacterRange(RegexChar('a'), RegexChar('f')),
RegexCharacterRange(RegexChar('A'), RegexChar('F')))
case "Space" =>
ListBuffer(" \t\n\u000B\f\r".map(RegexChar): _*)
case _ =>
throw new RegexUnsupportedException(
s"Predefined character class ${className} is not supported", Some(start))
}
}
consumeExpected('}')
RegexCharacterClass(negated, characters = getCharacters(className))
}
private def isHexDigit(ch: Char): Boolean = ch.isDigit ||
(ch >= 'a' && ch <= 'f') ||
(ch >= 'A' && ch <= 'F')
private def parseHexDigit: RegexHexDigit = {
// \xhh The character with hexadecimal value 0xhh
// \x{h...h} The character with hexadecimal value 0xh...h
// (Character.MIN_CODE_POINT <= 0xh...h <= Character.MAX_CODE_POINT)
val varHex = pattern.charAt(pos) == '{'
if (varHex) {
consumeExpected('{')
}
val start = pos
while (!eof() && isHexDigit(pattern.charAt(pos))) {
pos += 1
}
val hexDigit = pattern.substring(start, pos)
if (varHex) {
consumeExpected('}')
} else if (hexDigit.length != 2) {
throw new RegexUnsupportedException(s"Invalid hex digit: $hexDigit", Some(start))
}
val value = Integer.parseInt(hexDigit, 16)
if (value < Character.MIN_CODE_POINT || value > Character.MAX_CODE_POINT) {
throw new RegexUnsupportedException(s"Invalid hex digit: $hexDigit", Some(start))
}
new RegexHexDigit(hexDigit, start - 2)
}
private def isOctalDigit(ch: Char): Boolean = ch >= '0' && ch <= '7'
private def parseOctalDigit: RegexOctalChar = {
// \0n The character with octal value 0n (0 <= n <= 7)
// \0nn The character with octal value 0nn (0 <= n <= 7)
// \0mnn The character with octal value 0mnn (0 <= m <= 3, 0 <= n <= 7)
def parseOctalDigits(n: Integer): RegexOctalChar = {
val octal = pattern.substring(pos, pos + n)
pos += n
new RegexOctalChar(octal, pos)
}
if (!eof() && isOctalDigit(pattern.charAt(pos))) {
if (pos + 1 < pattern.length && isOctalDigit(pattern.charAt(pos + 1))) {
if (pos + 2 < pattern.length && isOctalDigit(pattern.charAt(pos + 2))
&& pattern.charAt(pos) <= '3') {
if (pos + 3 < pattern.length && isOctalDigit(pattern.charAt(pos + 3))
&& pattern.charAt(pos+1) <= '3' && pattern.charAt(pos) == '0') {
parseOctalDigits(4)
} else {
parseOctalDigits(3)
}
} else {
parseOctalDigits(2)
}
} else {
parseOctalDigits(1)
}
} else {
throw new RegexUnsupportedException(
"Invalid octal digit", Some(pos))
}
}
/** Determine if we are at the end of the input */
private def eof(): Boolean = pos == pattern.length
/** Advance the index by one */
private def skip(): Unit = {
if (eof()) {
throw new RegexUnsupportedException("Unexpected EOF", Some(pos))
}
pos += 1
}
/** Get the next character and advance the index by one */
private def consume(): Char = {
if (eof()) {
throw new RegexUnsupportedException("Unexpected EOF", Some(pos))
} else {
pos += 1
pattern.charAt(pos - 1)
}
}
/** Consume the next character if it is the one we expect */
private def consumeExpected(expected: Char): Char = {
val consumed = consume()
if (consumed != expected) {
throw new RegexUnsupportedException(
s"Expected '$expected' but found '$consumed'", Some(pos-1))
}
consumed
}
/** Peek at the next character without consuming it */
private def peek(): Option[Char] = {
if (eof()) {
None
} else {
Some(pattern.charAt(pos))
}
}
private def consumeInt(): Option[Int] = {
val start = pos
while (!eof() && peek().exists(_.isDigit)) {
skip()
}
if (start == pos) {
None
} else {
Some(pattern.substring(start, pos).toInt)
}
}
}
object RegexParser {
private val regexpChars = Set('\u0000', '\\', '.', '^', '$', '\u0007', '\u001b', '\f')
def parse(pattern: String): RegexAST = new RegexParser(pattern).parse
def isRegExpString(s: String): Boolean = {
def isRegExpString(ast: RegexAST): Boolean = ast match {
case RegexChar(ch) => regexpChars.contains(ch)
case RegexEscaped(_) => true
case RegexSequence(parts) => parts.exists(isRegExpString)
case _ => true
}
try {
val parser = new RegexParser(s)
val ast = parser.parse()
isRegExpString(ast)
} catch {
case _: RegexUnsupportedException =>
// if we cannot parse it then assume that it might be valid regexp
true
}
}
def toReadableString(x: String): String = {
x.map {
case '\r' => "\\r"
case '\n' => "\\n"
case '\t' => "\\t"
case '\f' => "\\f"
case '\u0000' => "\\u0000"
case '\u000b' => "\\u000b"
case '\u0085' => "\\u0085"
case '\u2028' => "\\u2028"
case '\u2029' => "\\u2029"
case other => other
}.mkString
}
}
sealed trait RegexMode
object RegexFindMode extends RegexMode
object RegexReplaceMode extends RegexMode
object RegexSplitMode extends RegexMode
sealed trait RegexLookahead
object RegexNegativeLookahead extends RegexLookahead
object RegexPositiveLookahead extends RegexLookahead
sealed class RegexRewriteFlags(val emptyRepetition: Boolean)
/**
* Transpile Java/Spark regular expression to a format that cuDF supports, or throw an exception
* if this is not possible.
*
* @param mode RegexFindMode if matching only (rlike)
RegexReplaceMode if performing a replacement (regexp_replace)
RegexSplitMode if performing a split (string_split)
*/
class CudfRegexTranspiler(mode: RegexMode) {
private val regexPunct = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
private val escapeChars = Map('n' -> '\n', 'r' -> '\r', 't' -> '\t', 'f' -> '\f', 'a' -> '\u0007',
'b' -> '\b', 'e' -> '\u001b')
private def countCaptureGroups(regex: RegexAST): Int = {
regex match {
case RegexSequence(parts) => parts.foldLeft(0)((c, re) => c + countCaptureGroups(re))
case RegexGroup(capture, base, _) =>
if (capture) {
1 + countCaptureGroups(base)
} else {
countCaptureGroups(base)
}
case _ => 0
}
}
/**
* Parse Java regular expression and translate into cuDF regular expression.
*
* @param pattern Regular expression that is valid in Java's engine
* @param extractIndex extraction index for regular expression
* @param repl Optional replacement pattern
* @return Regular expression and optional replacement in cuDF format
*/
def transpile(pattern: String, extractIndex: Option[Int], repl: Option[String]):
(String, Option[String]) = {
val (cudfRegex, replacement) = getTranspiledAST(pattern, extractIndex, repl)
// write out to regex string, performing minor transformations
// such as adding additional escaping
(cudfRegex.toRegexString, replacement.map(_.toRegexString))
}
def getTranspiledAST(
regex: RegexAST,
extractIndex: Option[Int],
repl: Option[String]): (RegexAST, Option[RegexReplacement]) = {
// if we have a replacement, parse the replacement string using the regex parser to account
// for backrefs
val replacement = repl.map(s => new RegexParser(s).parseReplacement(countCaptureGroups(regex)))
// validate that the regex is supported by cuDF
val cudfRegex = transpile(regex, extractIndex, replacement, None)
(cudfRegex, replacement)
}
/**
* Parse Java regular expression and translate into cuDF regular expression in AST form.
*
* @param pattern Regular expression that is valid in Java's engine
* @param extractIndex extraction index for regular expression
* @param repl Optional replacement pattern
* @return Regular expression AST and optional replacement in cuDF format
*/
def getTranspiledAST(
pattern: String,
extractIndex: Option[Int],
repl: Option[String]): (RegexAST, Option[RegexReplacement]) = {
// parse the source regular expression
val regex = new RegexParser(pattern).parse()
getTranspiledAST(regex, extractIndex, repl)
}
def transpileToSplittableString(e: RegexAST): Option[String] = {
e match {
case RegexEscaped(ch) if escapeChars.contains(ch) => Some(escapeChars(ch).toString)
case RegexEscaped(ch) if regexPunct.contains(ch) => Some(ch.toString)
case RegexChar(ch) if !regexMetaChars.contains(ch) => Some(ch.toString)
case RegexSequence(parts) =>
parts.foldLeft[Option[String]](Some("")) { (all, x) =>
all match {
case Some(current) =>
transpileToSplittableString(x) match {
case Some(y) => Some(current + y)
case _ => None
}
case _ => None
}
}
case _ => None
}
}
def transpileToSplittableString(pattern: String): Option[String] = {
try {
val regex = new RegexParser(pattern).parse()
transpileToSplittableString(regex)
} catch {
// treat as regex if we can't parse it
case _: RegexUnsupportedException =>
None
}
}
@scala.annotation.tailrec
private def isRepetition(e: RegexAST, checkZeroLength: Boolean): Boolean = {
e match {
case RegexRepetition(_, _) if !checkZeroLength => true
case RegexRepetition(_, quantifier) => quantifier match {
case SimpleQuantifier(ch) if "*?".contains(ch) => true
case QuantifierFixedLength(length) if length == 0 => true
case QuantifierVariableLength(min, _) if min == 0 => true
case _ => false
}
case RegexGroup(_, term, _) => isRepetition(term, checkZeroLength)
case RegexSequence(parts) if parts.nonEmpty => isRepetition(parts.last, checkZeroLength)
case _ => false
}
}
private def getUnsupportedRepetitionBaseOption(e: RegexAST): Option[RegexAST] = {
e match {
case RegexEscaped(ch) => ch match {
case 'd' | 'w' | 's' | 'S' | 'h' | 'H' | 'v' | 'V' => None
case _ => Some(e)
}
case RegexChar(a) if "$^".contains(a) =>
// example: "$*"
Some(e)
case RegexRepetition(_, _) =>
// example: "a*+"
Some(e)
case RegexSequence(parts) =>
parts.foreach { part => getUnsupportedRepetitionBaseOption(part) match {
case r @ Some(_) => return r
case None =>
}
}
None
case RegexGroup(_, term, _) =>
getUnsupportedRepetitionBaseOption(term)
case _ => None
}
}
private def getUnsupportedRepetitionBase(e: RegexAST): RegexAST = {
getUnsupportedRepetitionBaseOption(e) match {
case None => throw new NoSuchElementException(
s"Expected repetition base ${e.toRegexString} to be unsupported but was actully supported")
case Some(unsupportedTerm) => unsupportedTerm
}
}
private def isSupportedRepetitionBase(e: RegexAST): Boolean = {
getUnsupportedRepetitionBaseOption(e) match {
case None => true
case _ => false
}
}
private val lineTerminatorChars = Seq('\n', '\r', '\u0085', '\u2028', '\u2029')
// from Java 8 documention: a line terminator is a 1 to 2 character sequence that marks
// the end of a line of an input character sequence.
// this method produces a RegexAST which outputs a regular expression to match any possible
// combination of line terminators
private def lineTerminatorMatcher(exclude: Set[Char], excludeCRLF: Boolean,
capture: Boolean): RegexAST = {
val terminatorChars = new ListBuffer[RegexCharacterClassComponent]()
terminatorChars ++= lineTerminatorChars.filter(!exclude.contains(_)).map(RegexChar)
if (terminatorChars.size == 0 && excludeCRLF) {
RegexEmpty()
} else if (terminatorChars.size == 0) {
RegexGroup(capture = capture, RegexSequence(ListBuffer(RegexChar('\r'), RegexChar('\n'))),
None)
} else if (excludeCRLF) {
RegexGroup(capture = capture,
RegexCharacterClass(negated = false, characters = terminatorChars),
None
)
} else {
RegexGroup(capture = capture, RegexParser.parse("\r|\u0085|\u2028|\u2029|\r\n"), None)
}
}
private def negateCharacterClass(
components: ListBuffer[RegexCharacterClassComponent]): RegexAST = {
// There are differences between cuDF and Java handling of `\r`
// in negated character classes. The expression `[^a]` will match
// `\r` in Java but not in cuDF, so we replace `[^a]` with
// `(?:[\r]|[^a])`.
//
// Examples:
//
// `[^a]` => `(?:[\r]|[^a])`
// `[^a\n]` => `(?:[\r]|[^a\n])`
//
// If the negated character class contains `\r` then there is no transformation:
//
// `[^a\r]` => `[^a\r]`
// `[^a\r\n]` => `[^a\r\n]`
val componentsWithoutLinefeed = components.filterNot {
case RegexChar(ch) => ch == '\r'
case RegexEscaped(ch) => ch == 'r'
case RegexCharacterRange(startRegex, RegexChar(end)) =>
val start = startRegex match {
case RegexChar(ch) => ch
case r @ RegexOctalChar(_) => r.codePoint.toChar
case r @ RegexHexDigit(_) => r.codePoint.toChar
case other => throw new RegexUnsupportedException(
s"Unexpected expression at start of character range: ${other.toRegexString}",
other.position)
}
start <= '\r' && end >= '\r'
case _ =>
false
}
if (componentsWithoutLinefeed.length != components.length) {
// no modification needed in this case
RegexCharacterClass(negated = true, ListBuffer(components.toSeq: _*))
} else {
RegexGroup(capture = false,
RegexChoice(
RegexCharacterClass(negated = false,
characters = ListBuffer(RegexChar('\r'))),
RegexCharacterClass(negated = true, ListBuffer(components.toSeq: _*))), None)
}
}
private def transpile(regex: RegexAST, extractIndex: Option[Int],
replacement: Option[RegexReplacement],
previous: Option[RegexAST]): RegexAST = {
def containsBeginAnchor(regex: RegexAST): Boolean = {
contains(regex, {
case RegexChar('^') | RegexEscaped('A') => true
case _ => false
})
}
def containsEndAnchor(regex: RegexAST): Boolean = {
contains(regex, {
case RegexChar('$') | RegexEscaped('z') | RegexEscaped('Z') => true
case _ => false
})
}
def containsNewline(regex: RegexAST): Boolean = {
contains(regex, {
case RegexChar('\r') | RegexEscaped('r') => true
case RegexChar('\n') | RegexEscaped('n') => true
case RegexChar('\u0085') | RegexChar('\u2028') | RegexChar('\u2029') => true
case RegexEscaped('s') | RegexEscaped('v') | RegexEscaped('R') => true
case RegexEscaped('W') | RegexEscaped('D') |
RegexEscaped('S') | RegexEscaped('V') =>
// these would get transpiled to negated character classes
// that include newlines
true
case RegexCharacterClass(true, _) => true
case _ => false
})
}
def containsEmpty(regex: RegexAST): Boolean = {
contains(regex, {
case RegexRepetition(_, term) => term match {
case SimpleQuantifier('*') | SimpleQuantifier('?') => true
case QuantifierFixedLength(0) => true
case QuantifierVariableLength(0, _) => true
case _ => false
}
case _ => false
})
}
// check a pair of regex ast nodes for unsupported combinations
// of end string/line anchors and newlines or optional items
def checkEndAnchorContext(r1: RegexAST, r2: RegexAST): Unit = {
if ((containsEndAnchor(r1) &&
(containsNewline(r2) || containsEmpty(r2) || containsBeginAnchor(r2))) ||
(containsEndAnchor(r2) &&
(containsNewline(r1) || containsBeginAnchor(r1)))) {
throw new RegexUnsupportedException(
s"End of line/string anchor is not supported in this context: " +
s"${toReadableString(r1.toRegexString)}" +
s"${toReadableString(r2.toRegexString)}", r1.position)
}
}
def checkEndAnchorContextSplit(r1: RegexAST, r2: RegexAST): Unit = {
if ((containsEndAnchor(r1) &&
(containsNewline(r2) || containsEmpty(r2) || containsBeginAnchor(r2))) ||
(containsEndAnchor(r2) &&
(containsNewline(r1) || containsEmpty(r1) || containsBeginAnchor(r1)))) {
throw new RegexUnsupportedException(
s"End of line/string anchor is not supported in this context: " +
s"${toReadableString(r1.toRegexString)}" +
s"${toReadableString(r2.toRegexString)}", r1.position)
}
}
def checkUnsupported(regex: RegexAST): Unit = {
regex match {
case RegexSequence(parts) =>
for (i <- 1 until parts.length) {
if (mode == RegexSplitMode) {
checkEndAnchorContextSplit(parts(i - 1), parts(i))
} else {
checkEndAnchorContext(parts(i - 1), parts(i))
}
}
case RegexChoice(l, r) =>
checkUnsupported(l)
checkUnsupported(r)