|
| 1 | +# ============================== Define spec ============================== |
| 2 | +from .base_analysis import BaseDyLinAnalysis |
| 3 | +from dynapyt.instrument.filters import only |
| 4 | + |
| 5 | +from typing import Callable, Tuple, Dict |
| 6 | +import re |
| 7 | + |
| 8 | + |
| 9 | +""" |
| 10 | + RegexpTokenizer pattern must not contain capturing parentheses |
| 11 | + src: https://www.nltk.org/api/nltk.tokenize.regexp.html |
| 12 | +""" |
| 13 | + |
| 14 | + |
| 15 | +def contains_capturing_groups(pattern): |
| 16 | + regex = re.compile(pattern) |
| 17 | + |
| 18 | + if regex.groups > 0: |
| 19 | + # Further check to distinguish capturing from non-capturing by examining the pattern |
| 20 | + # This involves checking all group occurrences in the pattern |
| 21 | + # We need to avoid matching escaped parentheses \( or \) and non-capturing groups (?: ...) |
| 22 | + non_capturing = re.finditer(r'\(\?[:=!]', pattern) |
| 23 | + non_capturing_indices = {match.start() for match in non_capturing} |
| 24 | + |
| 25 | + # Finding all parentheses that could start a group |
| 26 | + all_groups = re.finditer(r'\((?!\?)', pattern) |
| 27 | + for match in all_groups: |
| 28 | + if match.start() not in non_capturing_indices: |
| 29 | + return True # Found at least one capturing group |
| 30 | + return False |
| 31 | + else: |
| 32 | + return False |
| 33 | + |
| 34 | + |
| 35 | +class NLTK_RegexpTokenizerCapturingParentheses(BaseDyLinAnalysis): |
| 36 | + |
| 37 | + def __init__(self, **kwargs) -> None: |
| 38 | + super().__init__(**kwargs) |
| 39 | + self.analysis_name = "NLTK_RegexpTokenizerCapturingParentheses" |
| 40 | + |
| 41 | + @only(patterns=["RegexpTokenizer"]) |
| 42 | + def pre_call( |
| 43 | + self, dyn_ast: str, iid: int, function: Callable, pos_args: Tuple, kw_args: Dict |
| 44 | + ) -> None: |
| 45 | + # The target class names for monitoring |
| 46 | + targets = ["nltk.tokenize.regexp.RegexpTokenizer"] |
| 47 | + |
| 48 | + # Get the class name |
| 49 | + if hasattr(function, '__module__') and hasattr(function, '__name__'): |
| 50 | + class_name = function.__module__ + "." + function.__name__ |
| 51 | + else: |
| 52 | + class_name = None |
| 53 | + |
| 54 | + # Check if the class name is the target ones |
| 55 | + if class_name in targets: |
| 56 | + |
| 57 | + # Spec content |
| 58 | + pattern = None |
| 59 | + if kw_args.get('pattern'): |
| 60 | + pattern = kw_args['pattern'] |
| 61 | + elif len(pos_args) > 1: |
| 62 | + pattern = pos_args[1] |
| 63 | + |
| 64 | + # Check if the regular expression is empty |
| 65 | + if pattern is not None and contains_capturing_groups(pattern): |
| 66 | + |
| 67 | + # Spec content |
| 68 | + self.add_finding( |
| 69 | + iid, |
| 70 | + dyn_ast, |
| 71 | + "B-9", |
| 72 | + f"Must use non_capturing parentheses for RegexpTokenizer pattern at {dyn_ast}." |
| 73 | + ) |
| 74 | +# ========================================================================= |
0 commit comments