| 1 |
""" |
| 2 |
This module defines the hyperscan backends for `.GitIgnoreSpec`, revision 2, |
| 3 |
used in benchmarking, but not included in the released library. |
| 4 |
""" |
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
from collections.abc import ( |
| 8 |
Sequence) |
| 9 |
from typing import ( |
| 10 |
Any, |
| 11 |
Callable, # Replaced by `collections.abc.Callable` in 3.9.2. |
| 12 |
Optional, # Replaced by `X | None` in 3.10. |
| 13 |
Union) # Replaced by `X | Y` in 3.10. |
| 14 |
from typing_extensions import ( |
| 15 |
override) # Added in 3.12. |
| 16 |
|
| 17 |
try: |
| 18 |
import hyperscan |
| 19 |
except ModuleNotFoundError: |
| 20 |
hyperscan = None |
| 21 |
|
| 22 |
from pathspec._backends.hyperscan._base import ( |
| 23 |
HS_FLAGS, |
| 24 |
HyperscanExprDat) |
| 25 |
from pathspec._backends.hyperscan.gitignore import ( |
| 26 |
_DIR_MARK_CG, |
| 27 |
_DIR_MARK_OPT) |
| 28 |
from pathspec._backends.hyperscan.pathspec import ( |
| 29 |
HyperscanPsBackend) |
| 30 |
from pathspec.pattern import ( |
| 31 |
RegexPattern) |
| 32 |
from pathspec.patterns.gitignore.spec import ( |
| 33 |
GitIgnoreSpecPattern, |
| 34 |
_BYTES_ENCODING) |
| 35 |
|
| 36 |
|
| 37 |
class _HyperscanGiR2BaseBackend(HyperscanPsBackend): |
| 38 |
""" |
| 39 |
The :class:`_HyperscanGiR2BaseBackend` base class uses a hyperscan database in |
| 40 |
block mode for matching files. |
| 41 |
""" |
| 42 |
|
| 43 |
@override |
| 44 |
@staticmethod |
| 45 |
def _init_db( |
| 46 |
db: hyperscan.Database, |
| 47 |
debug: bool, |
| 48 |
patterns: list[tuple[int, RegexPattern]], |
| 49 |
sort_ids: Optional[Callable[[list[int]], None]], |
| 50 |
) -> list[HyperscanExprDat]: |
| 51 |
# NOTICE: This is the current implementation. |
| 52 |
|
| 53 |
# Prepare patterns. |
| 54 |
expr_data: list[HyperscanExprDat] = [] |
| 55 |
exprs: list[bytes] = [] |
| 56 |
for pattern_index, pattern in patterns: |
| 57 |
if pattern.include is None: |
| 58 |
continue |
| 59 |
|
| 60 |
# Encode regex. |
| 61 |
assert isinstance(pattern, RegexPattern), pattern |
| 62 |
regex = pattern.regex.pattern |
| 63 |
|
| 64 |
use_regexes: list[tuple[Union[str, bytes], bool]] = [] |
| 65 |
if isinstance(pattern, GitIgnoreSpecPattern): |
| 66 |
# GitWildMatch uses capture groups for its directory marker but |
| 67 |
# Hyperscan does not support capture groups. Check for this scenario. |
| 68 |
if isinstance(regex, str): |
| 69 |
regex_str = regex |
| 70 |
else: |
| 71 |
assert isinstance(regex, bytes), regex |
| 72 |
regex_str = regex.decode(_BYTES_ENCODING) |
| 73 |
|
| 74 |
if _DIR_MARK_CG in regex_str: |
| 75 |
# Found directory marker. |
| 76 |
if regex_str.endswith(_DIR_MARK_OPT): |
| 77 |
# Regex has optional directory marker. Split regex into directory |
| 78 |
# and file variants. |
| 79 |
base_regex = regex_str[:-len(_DIR_MARK_OPT)] |
| 80 |
use_regexes.append((f'{base_regex}/', True)) |
| 81 |
use_regexes.append((f'{base_regex}$', False)) |
| 82 |
else: |
| 83 |
# Remove capture group. |
| 84 |
base_regex = regex_str.replace(_DIR_MARK_CG, '/') |
| 85 |
use_regexes.append((base_regex, True)) |
| 86 |
|
| 87 |
if not use_regexes: |
| 88 |
# No special case for regex. |
| 89 |
use_regexes.append((regex, False)) |
| 90 |
|
| 91 |
for regex, is_dir_pattern in use_regexes: |
| 92 |
if isinstance(regex, bytes): |
| 93 |
regex_bytes = regex |
| 94 |
else: |
| 95 |
assert isinstance(regex, str), regex |
| 96 |
regex_bytes = regex.encode('utf8') |
| 97 |
|
| 98 |
expr_data.append(HyperscanExprDat( |
| 99 |
include=pattern.include, |
| 100 |
index=pattern_index, |
| 101 |
is_dir_pattern=is_dir_pattern, |
| 102 |
)) |
| 103 |
exprs.append(regex_bytes) |
| 104 |
|
| 105 |
# Compile patterns. |
| 106 |
db.compile( |
| 107 |
expressions=exprs, |
| 108 |
ids=list(range(len(exprs))), |
| 109 |
elements=len(exprs), |
| 110 |
flags=HS_FLAGS, |
| 111 |
) |
| 112 |
return expr_data |
| 113 |
|
| 114 |
@override |
| 115 |
@staticmethod |
| 116 |
def _make_db() -> hyperscan.Database: |
| 117 |
raise NotImplementedError() |
| 118 |
|
| 119 |
|
| 120 |
class _HyperscanGiR2BlockBaseBackend(_HyperscanGiR2BaseBackend): |
| 121 |
""" |
| 122 |
The :class:`_HyperscanGiR2BlockBaseBackend` base class uses a hyperscan |
| 123 |
database in block mode for matching files. |
| 124 |
""" |
| 125 |
|
| 126 |
@override |
| 127 |
@staticmethod |
| 128 |
def _make_db() -> hyperscan.Database: |
| 129 |
return hyperscan.Database(mode=hyperscan.HS_MODE_BLOCK) |
| 130 |
|
| 131 |
|
| 132 |
class HyperscanGiR2BlockClosureBackend(_HyperscanGiR2BlockBaseBackend): |
| 133 |
""" |
| 134 |
The :class:`HyperscanGiR2BlockClosureBackend` class uses a hyperscan database |
| 135 |
in block mode for matching files, and uses a closure to capture state. |
| 136 |
""" |
| 137 |
|
| 138 |
# Prevent accidental usage. |
| 139 |
_out: tuple[()] |
| 140 |
|
| 141 |
@override |
| 142 |
def match_file(self, file: str) -> tuple[Optional[bool], Optional[int]]: |
| 143 |
out_include: Optional[bool] = None |
| 144 |
out_index: Optional[int] = -1 |
| 145 |
out_priority = 0 |
| 146 |
|
| 147 |
def on_match( |
| 148 |
expr_id: int, _from: int, _to: int, _flags: int, _context: Any, |
| 149 |
) -> Optional[bool]: |
| 150 |
nonlocal out_include, out_index, out_priority |
| 151 |
expr_dat = self._expr_data[expr_id] |
| 152 |
|
| 153 |
is_dir_pattern = expr_dat.is_dir_pattern |
| 154 |
if is_dir_pattern: |
| 155 |
# Pattern matched by a directory pattern. |
| 156 |
priority = 1 |
| 157 |
else: |
| 158 |
# Pattern matched by a file pattern. |
| 159 |
priority = 2 |
| 160 |
|
| 161 |
# WARNING: Hyperscan does not guarantee matches will be produced in |
| 162 |
# order! |
| 163 |
include = expr_dat.include |
| 164 |
index = expr_dat.index |
| 165 |
if ( |
| 166 |
(include and is_dir_pattern and index > out_index) |
| 167 |
or (priority == out_priority and index > out_index) |
| 168 |
or priority > out_priority |
| 169 |
): |
| 170 |
out_include = include |
| 171 |
out_index = index |
| 172 |
out_priority = priority |
| 173 |
|
| 174 |
self._db.scan(file.encode('utf8'), match_event_handler=on_match) |
| 175 |
|
| 176 |
if out_index == -1: |
| 177 |
out_index = None |
| 178 |
|
| 179 |
return (out_include, out_index) |
| 180 |
|
| 181 |
|
| 182 |
class HyperscanGiR2BlockStateBackend(_HyperscanGiR2BlockBaseBackend): |
| 183 |
""" |
| 184 |
The :class:`HyperscanGiR2BlockStateBackend` class uses a hyperscan database in |
| 185 |
block mode for matching files, and stores state in variables. |
| 186 |
""" |
| 187 |
|
| 188 |
# Change type hint. |
| 189 |
_out: tuple[Optional[bool], int, int] |
| 190 |
|
| 191 |
def __init__(self, patterns: Sequence[RegexPattern]) -> None: |
| 192 |
super().__init__(patterns) |
| 193 |
self._out = (None, -1, 0) |
| 194 |
|
| 195 |
@override |
| 196 |
def match_file(self, file: str) -> tuple[Optional[bool], Optional[int]]: |
| 197 |
self._out = (None, -1, 0) |
| 198 |
self._db.scan(file.encode('utf8'), match_event_handler=self.__on_match) |
| 199 |
|
| 200 |
out_include, out_index = self._out[:2] |
| 201 |
if out_index == -1: |
| 202 |
out_index = None |
| 203 |
|
| 204 |
return (out_include, out_index) |
| 205 |
|
| 206 |
@override |
| 207 |
def __on_match( |
| 208 |
self, |
| 209 |
expr_id: int, |
| 210 |
_from: int, |
| 211 |
_to: int, |
| 212 |
_flags: int, |
| 213 |
_context: Any, |
| 214 |
) -> Optional[bool]: |
| 215 |
expr_dat = self._expr_data[expr_id] |
| 216 |
|
| 217 |
is_dir_pattern = expr_dat.is_dir_pattern |
| 218 |
if is_dir_pattern: |
| 219 |
# Pattern matched by a directory pattern. |
| 220 |
priority = 1 |
| 221 |
else: |
| 222 |
# Pattern matched by a file pattern. |
| 223 |
priority = 2 |
| 224 |
|
| 225 |
# WARNING: Hyperscan does not guarantee matches will be produced in order! |
| 226 |
include = expr_dat.include |
| 227 |
index = expr_dat.index |
| 228 |
prev_index = self._out[1] |
| 229 |
prev_priority = self._out[2] |
| 230 |
if ( |
| 231 |
(include and is_dir_pattern and index > prev_index) |
| 232 |
or (priority == prev_priority and index > prev_index) |
| 233 |
or priority > prev_priority |
| 234 |
): |
| 235 |
self._out = (include, index, priority) |
| 236 |
|
| 237 |
|
| 238 |
class _HyperscanGiR2StreamBaseBackend(_HyperscanGiR2BaseBackend): |
| 239 |
""" |
| 240 |
The :class:`_HyperscanGiR2StreamBaseBackend` base class uses a hyperscan |
| 241 |
database in streaming mode for matching files. |
| 242 |
""" |
| 243 |
|
| 244 |
@override |
| 245 |
@staticmethod |
| 246 |
def _make_db() -> hyperscan.Database: |
| 247 |
return hyperscan.Database(mode=hyperscan.HS_MODE_STREAM) |
| 248 |
|
| 249 |
|
| 250 |
class HyperscanGiR2StreamClosureBackend(_HyperscanGiR2StreamBaseBackend): |
| 251 |
""" |
| 252 |
The :class:`HyperscanGiR2StreamClosureBackend` class uses a hyperscan database |
| 253 |
in streaming mode for matching files, and uses a closure to capture state. |
| 254 |
""" |
| 255 |
|
| 256 |
# Prevent accidental usage. |
| 257 |
_out: tuple[()] |
| 258 |
|
| 259 |
@override |
| 260 |
def match_file(self, file: str) -> tuple[Optional[bool], Optional[int]]: |
| 261 |
out_include: Optional[bool] = None |
| 262 |
out_index: Optional[int] = -1 |
| 263 |
out_priority = 0 |
| 264 |
|
| 265 |
def on_match( |
| 266 |
expr_id: int, _from: int, _to: int, _flags: int, _context: Any, |
| 267 |
) -> Optional[bool]: |
| 268 |
nonlocal out_include, out_index, out_priority |
| 269 |
expr_dat = self._expr_data[expr_id] |
| 270 |
|
| 271 |
is_dir_pattern = expr_dat.is_dir_pattern |
| 272 |
if is_dir_pattern: |
| 273 |
# Pattern matched by a directory pattern. |
| 274 |
priority = 1 |
| 275 |
else: |
| 276 |
# Pattern matched by a file pattern. |
| 277 |
priority = 2 |
| 278 |
|
| 279 |
# WARNING: Hyperscan does not guarantee matches will be produced in |
| 280 |
# order! |
| 281 |
include = expr_dat.include |
| 282 |
index = expr_dat.index |
| 283 |
if ( |
| 284 |
(include and is_dir_pattern and index > out_index) |
| 285 |
or (priority == out_priority and index > out_index) |
| 286 |
or priority > out_priority |
| 287 |
): |
| 288 |
out_include = include |
| 289 |
out_index = index |
| 290 |
out_priority = priority |
| 291 |
|
| 292 |
with self._db.stream(match_event_handler=on_match) as stream: |
| 293 |
stream.scan(file.encode('utf8')) |
| 294 |
|
| 295 |
if out_index == -1: |
| 296 |
out_index = None |
| 297 |
|
| 298 |
return (out_include, out_index) |