def block_contains_grammar(grammar: ParserElement, code_dest: str, lines: List[str], get_block_fn: Callable, should_have: str = '', should_not_have: str = '', search_for_empty: bool = False) -> List[str]: """ Check block grammar. :param grammar: Pyparsing grammar against which file will be checked. :param code_dest: Source code file to check. :param lines: List of starting lines. :param get_block_fn: Function that gives block code starting at line. :param should_have: A string to search for in the match results. :param should_not_have: A string to search for in the match results. """ vulns = {} vuln_lines = [] if should_have: should_have_re = re.compile(should_have, flags=re.M) if should_not_have: should_not_have_re = re.compile(should_not_have, flags=re.M) with open(code_dest, encoding='latin-1') as code_f: file_lines = code_f.read().splitlines() for line in map(int, lines.split(',')): txt = get_block_fn(file_lines, line) results = grammar.searchString(txt, maxMatches=1) results_str = str(results) is_vulnerable = not search_for_empty if _is_empty_result(results): is_vulnerable = search_for_empty elif should_have and should_have_re.search(results_str): is_vulnerable = search_for_empty elif should_not_have and should_not_have_re.search(results_str): is_vulnerable = search_for_empty if is_vulnerable: vuln_lines.append(line) if vuln_lines: vulns = { code_dest: { 'lines': str(vuln_lines)[1:-1], 'sha256': get_sha256(code_dest), } } return vulns
def _get_match_lines(grammar: ParserElement, code_file: str, lang_spec: dict) -> List[int]: # noqa """ Check grammar in file. :param grammar: Pyparsing grammar against which file will be checked. :param code_file: Source code file to check. :param lang_spec: Contains language-specific syntax elements, such as acceptable file extensions and comment delimiters. :return: List of lines that contain grammar matches. """ affected_lines = [] # We need hashable arguments lang_spec_hashable = tuple(lang_spec.items()) for line_number, line_content in _non_commented_code( code_file, lang_spec_hashable): try: results = grammar.searchString(line_content, maxMatches=1) if not _is_empty_result(results): affected_lines.append(line_number) except ParseException: pass return affected_lines