-
Notifications
You must be signed in to change notification settings - Fork 14
/
InternalRegex.cs
319 lines (243 loc) · 10.9 KB
/
InternalRegex.cs
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
using System;
using System.Collections.Generic;
using System.Threading;
using PCRE.Dfa;
namespace PCRE.Internal
{
internal sealed unsafe class InternalRegex : IDisposable
{
internal const int MaxStackAllocCaptureCount = 32;
private IntPtr _code;
private Dictionary<int, PcreCalloutInfo>? _calloutInfoByPatternPosition;
private PcreMatch? _noMatch;
public string Pattern { get; }
public PcreRegexSettings Settings { get; }
public Dictionary<string, int[]> CaptureNames { get; }
public int CaptureCount { get; }
public int OutputVectorSize => 2 * (CaptureCount + 1);
public bool CanStackAllocOutputVector => CaptureCount <= MaxStackAllocCaptureCount;
public InternalRegex(string pattern, PcreRegexSettings settings)
{
Pattern = pattern;
Settings = settings.AsReadOnly();
Native.compile_result result;
fixed (char* pPattern = pattern)
{
Native.compile_input input;
_ = &input;
input.pattern = pPattern;
input.pattern_length = (uint)pattern.Length;
Settings.FillCompileInput(ref input);
Native.compile(&input, &result);
_code = result.code;
if (_code == IntPtr.Zero || result.error_code != 0)
{
Dispose();
throw new PcrePatternException((PcreErrorCode)result.error_code, $"Invalid pattern '{pattern}': {Native.GetErrorMessage(result.error_code)} at offset {result.error_offset}.");
}
}
CaptureCount = (int)result.capture_count;
CaptureNames = new Dictionary<string, int[]>((int)result.name_count, StringComparer.Ordinal);
var currentItem = result.name_entry_table;
for (var i = 0; i < result.name_count; ++i)
{
var groupIndex = (int)*currentItem;
var groupName = new string(currentItem + 1);
if (CaptureNames.TryGetValue(groupName, out var indexes))
{
Array.Resize(ref indexes, indexes.Length + 1);
indexes[indexes.Length - 1] = groupIndex;
}
else
{
indexes = new[] { groupIndex };
}
CaptureNames[groupName] = indexes;
currentItem += result.name_entry_size;
}
}
~InternalRegex()
{
FreeCode();
}
public void Dispose()
{
FreeCode();
GC.SuppressFinalize(this);
}
private void FreeCode()
{
if (_code != IntPtr.Zero)
{
Native.code_free(_code);
_code = IntPtr.Zero;
}
}
public uint GetInfoUInt32(uint key)
{
uint result;
var errorCode = Native.pattern_info(_code, key, &result);
if (errorCode != 0)
throw new PcreException((PcreErrorCode)errorCode, $"Error in pcre2_pattern_info: {Native.GetErrorMessage(errorCode)}");
return result;
}
public nuint GetInfoNativeInt(uint key)
{
nuint result;
var errorCode = Native.pattern_info(_code, key, &result);
if (errorCode != 0)
throw new PcreException((PcreErrorCode)errorCode, $"Error in pcre2_pattern_info: {Native.GetErrorMessage(errorCode)}");
return result;
}
public PcreMatch Match(string subject,
PcreMatchSettings settings,
int startIndex,
uint additionalOptions,
Func<PcreCallout, PcreCalloutResult>? callout)
{
Native.match_input input;
_ = &input;
settings.FillMatchInput(ref input);
Native.match_result result;
CalloutInterop.CalloutInteropInfo calloutInterop;
var oVectorArray = default(uint[]);
var oVector = CanStackAllocOutputVector
? stackalloc uint[OutputVectorSize]
: oVectorArray = new uint[OutputVectorSize];
fixed (char* pSubject = subject)
fixed (uint* pOVec = &oVector[0])
{
input.code = _code;
input.subject = pSubject;
input.subject_length = (uint)subject.Length;
input.output_vector = pOVec;
input.start_index = (uint)startIndex;
input.additional_options = additionalOptions;
CalloutInterop.Prepare(subject, this, ref input, out calloutInterop, callout);
Native.match(&input, &result);
}
AfterMatch(result, ref calloutInterop);
if (result.result_code == PcreConstants.ERROR_NOMATCH)
return _noMatch ??= new PcreMatch(this);
oVectorArray ??= oVector.ToArray();
return new PcreMatch(subject, this, ref result, oVectorArray);
}
public PcreRefMatch CreateRefMatch()
=> new(this, Span<uint>.Empty);
public PcreRefMatch CreateRefMatch(Span<uint> oVector)
{
#if DEBUG
if (oVector.Length != OutputVectorSize)
throw new InvalidOperationException("Unexpected output vector size.");
#endif
return new PcreRefMatch(this, oVector);
}
public void Match(ref PcreRefMatch match,
ReadOnlySpan<char> subject,
PcreMatchSettings settings,
int startIndex,
uint additionalOptions,
PcreRefCalloutFunc? callout,
uint[]? calloutOutputVector)
{
Native.match_input input;
_ = &input;
settings.FillMatchInput(ref input);
Native.match_result result;
CalloutInterop.CalloutInteropInfo calloutInterop;
var oVectorArray = default(uint[]);
var oVector = match.OutputVector.Length == OutputVectorSize
? match.OutputVector
: CanStackAllocOutputVector
? stackalloc uint[OutputVectorSize]
: oVectorArray = new uint[OutputVectorSize];
fixed (char* pSubject = subject)
fixed (uint* pOVec = &oVector[0])
{
input.code = _code;
input.subject = pSubject;
input.subject_length = (uint)subject.Length;
input.output_vector = pOVec;
input.start_index = (uint)startIndex;
input.additional_options = additionalOptions;
if (input.subject == default && input.subject_length == 0)
input.subject = (char*)1; // PCRE doesn't like null subjects, even if the length is zero
CalloutInterop.Prepare(subject, this, ref input, out calloutInterop, callout, calloutOutputVector);
Native.match(&input, &result);
}
AfterMatch(result, ref calloutInterop);
if (result.result_code != PcreConstants.ERROR_NOMATCH && oVector != match.OutputVector)
oVectorArray ??= oVector.ToArray();
match.Update(subject, result, oVectorArray);
}
public PcreDfaMatchResult DfaMatch(string subject, PcreDfaMatchSettings settings, int startIndex, uint additionalOptions)
{
Native.dfa_match_input input;
_ = &input;
settings.FillMatchInput(ref input);
var oVector = new uint[2 * Math.Max(1, settings.MaxResults)];
Native.match_result result;
CalloutInterop.CalloutInteropInfo calloutInterop;
fixed (char* pSubject = subject)
fixed (uint* pOVec = &oVector[0])
{
input.code = _code;
input.subject = pSubject;
input.subject_length = (uint)subject.Length;
input.output_vector = pOVec;
input.start_index = (uint)startIndex;
input.additional_options = additionalOptions;
CalloutInterop.Prepare(subject, this, ref input, out calloutInterop, settings.Callout);
Native.dfa_match(&input, &result);
}
AfterMatch(result, ref calloutInterop);
return new PcreDfaMatchResult(subject, ref result, oVector);
}
private static void AfterMatch(in Native.match_result result, ref CalloutInterop.CalloutInteropInfo calloutInterop)
{
switch (result.result_code)
{
case PcreConstants.ERROR_NOMATCH:
case PcreConstants.ERROR_PARTIAL:
break;
case PcreConstants.ERROR_CALLOUT:
throw new PcreCalloutException("An exception was thrown by the callout: " + calloutInterop.Exception?.Message, calloutInterop.Exception);
default:
if (result.result_code < 0)
throw new PcreMatchException((PcreErrorCode)result.result_code);
break;
}
}
public IReadOnlyList<PcreCalloutInfo> GetCallouts()
{
var calloutCount = Native.get_callout_count(_code);
if (calloutCount == 0)
return Array.Empty<PcreCalloutInfo>();
var data = calloutCount <= 16
? stackalloc Native.pcre2_callout_enumerate_block[(int)calloutCount]
: new Native.pcre2_callout_enumerate_block[calloutCount];
fixed (Native.pcre2_callout_enumerate_block* pData = &data[0])
{
Native.get_callouts(_code, pData);
}
var result = new List<PcreCalloutInfo>((int)calloutCount);
for (var i = 0; i < data.Length; ++i)
result.Add(new PcreCalloutInfo(ref data[i]));
return result.AsReadOnly();
}
public PcreCalloutInfo? TryGetCalloutInfoByPatternPosition(int patternPosition)
{
if (_calloutInfoByPatternPosition == null)
{
var dict = new Dictionary<int, PcreCalloutInfo>();
foreach (var info in GetCallouts())
dict.Add(info.PatternPosition, info);
Thread.MemoryBarrier();
_calloutInfoByPatternPosition = dict;
}
return _calloutInfoByPatternPosition.TryGetValue(patternPosition, out var result) ? result : null;
}
public PcreCalloutInfo GetCalloutInfoByPatternPosition(int patternPosition)
=> TryGetCalloutInfoByPatternPosition(patternPosition) ?? throw new InvalidOperationException($"Could not retrieve callout info at position {patternPosition}.");
}
}