Skip to content

Commit 4913e74

Browse files
committed
Parse backreferences and subroutine calls in regexes, do not infer shapes for patterns with subroutine calls
Amp-Thread-ID: https://ampcode.com/threads/T-01a177b5-960f-71d2-a3e2-fa7649f39d2c
1 parent ecc44da commit 4913e74

4 files changed

Lines changed: 263 additions & 108 deletions

File tree

‎build/regex-parser/RegexGrammar.pp3‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,10 @@
8484
// Marker verbs.
8585
%token T_MARKER \(\*:([^)]+)\)
8686

87+
// Backreferences and subroutine calls written as groups: (?P=name), (?R), (?1), (?-1), (?&name), (?P>name).
88+
%token T_NAMED_BACKREFERENCE \(\?P=\w+\)
89+
%token T_SUBROUTINE \(\?(?:R|[+-]?\d+|&\w+|P>\w+)\)
90+
8791
// Groups.
8892
%token T_NAMED_CAPTURING \(\?P?<(.+?)(?<!\\)>
8993
%token T_NON_CAPTURING \(\?:
@@ -120,6 +124,10 @@
120124
%token T_CHARACTER_TYPE \\(?:[CdDhHNRsSvVwWX]|[pP]{[^}]+})
121125
%token T_ANCHOR \\[bBAZzG]|\^|\$
122126
%token T_MATCH_POINT_RESET \\K
127+
// Subroutine calls \g<name>, \g'1' and backreferences \1, \g1, \g{-1}, \g{name}, \k<name>, \k'name', \k{name}.
128+
// Octal escapes like \012 are matched as dynamic characters above.
129+
%token T_SUBROUTINE_G \\g(?:<[^>]+>|'[^']+')
130+
%token T_BACKREFERENCE \\(?:[1-9]\d*|g[+-]?\d+|g\{[+-]?\w+\}|k<\w+>|k'\w+'|k\{\w+\})
123131
%token T_LITERAL \\.|.|\n
124132

125133
Expression -> {
@@ -354,12 +362,21 @@ Capturing -> {
354362
;
355363

356364
Literal -> {
357-
return new RegexNode('token', \strtolower(\substr($children->name, 2)), $children->value);
365+
$names = [
366+
self::T_NAMED_BACKREFERENCE => 'backreference',
367+
self::T_SUBROUTINE_G => 'subroutine',
368+
];
369+
370+
return new RegexNode('token', $names[$children->id] ?? \strtolower(\substr($children->name, 2)), $children->value);
358371
}
359372
: <T_CHARACTER>
360373
| <T_DYNAMIC_CHARACTER>
361374
| <T_CHARACTER_TYPE>
362375
| <T_ANCHOR>
363376
| <T_MATCH_POINT_RESET>
377+
| <T_SUBROUTINE_G>
378+
| <T_BACKREFERENCE>
379+
| <T_NAMED_BACKREFERENCE>
380+
| <T_SUBROUTINE>
364381
| <T_LITERAL>
365382
;

0 commit comments

Comments
 (0)