|
| 1 | +# |
| 2 | +# Copyright (c) nexB Inc. and others. All rights reserved. |
| 3 | +# ScanCode is a trademark of nexB Inc. |
| 4 | +# SPDX-License-Identifier: Apache-2.0 |
| 5 | +# See http://www.apache.org/licenses/LICENSE-2.0 for the license text. |
| 6 | +# See https://github.com/aboutcode-org/matchcode-toolkit for support or download. |
| 7 | +# See https://aboutcode.org for more information about nexB OSS projects. |
| 8 | +# |
| 9 | + |
| 10 | +import importlib |
| 11 | + |
| 12 | +from tree_sitter import Language |
| 13 | +from tree_sitter import Parser |
| 14 | +from typecode.contenttype import Type |
| 15 | + |
| 16 | + |
| 17 | +class TreeSitterWheelNotInstalled(Exception): |
| 18 | + pass |
| 19 | + |
| 20 | + |
| 21 | +TS_LANGUAGE_CONF = { |
| 22 | + "C": { |
| 23 | + "wheel": "tree_sitter_c", |
| 24 | + "identifiers": ["identifier"], |
| 25 | + "comments": ["comment"], |
| 26 | + }, |
| 27 | + "C++": { |
| 28 | + "wheel": "tree_sitter_cpp", |
| 29 | + "identifiers": ["identifier"], |
| 30 | + "comments": ["comment"], |
| 31 | + }, |
| 32 | + "Go": { |
| 33 | + "wheel": "tree_sitter_go", |
| 34 | + "identifiers": ["identifier"], |
| 35 | + "comments": ["comment"], |
| 36 | + }, |
| 37 | + "Java": { |
| 38 | + "wheel": "tree_sitter_java", |
| 39 | + "identifiers": ["identifier"], |
| 40 | + "comments": ["comment", "block_comment", "line_comment"], |
| 41 | + }, |
| 42 | + "JavaScript": { |
| 43 | + "wheel": "tree_sitter_javascript", |
| 44 | + "identifiers": ["identifier"], |
| 45 | + "comments": ["comment"], |
| 46 | + }, |
| 47 | + "Python": { |
| 48 | + "wheel": "tree_sitter_python", |
| 49 | + "identifiers": ["identifier"], |
| 50 | + "comments": ["comment"], |
| 51 | + }, |
| 52 | + "Rust": { |
| 53 | + "wheel": "tree_sitter_rust", |
| 54 | + "identifiers": ["identifier"], |
| 55 | + "comments": ["comment", "block_comment", "line_comment"], |
| 56 | + }, |
| 57 | +} |
| 58 | + |
| 59 | + |
| 60 | +def get_parser(location): |
| 61 | + """ |
| 62 | + Get the appropriate tree-sitter parser and grammar config for |
| 63 | + file at location. |
| 64 | + """ |
| 65 | + file_type = Type(location) |
| 66 | + language = file_type.programming_language |
| 67 | + |
| 68 | + if not language or language not in TS_LANGUAGE_CONF: |
| 69 | + return |
| 70 | + |
| 71 | + language_info = TS_LANGUAGE_CONF[language] |
| 72 | + wheel = language_info["wheel"] |
| 73 | + |
| 74 | + try: |
| 75 | + grammar = importlib.import_module(wheel) |
| 76 | + except ModuleNotFoundError: |
| 77 | + raise TreeSitterWheelNotInstalled(f"{wheel} package is not installed") |
| 78 | + |
| 79 | + parser = Parser(language=Language(grammar.language())) |
| 80 | + |
| 81 | + return parser, language_info |
| 82 | + |
| 83 | + |
| 84 | +def add_to_mutation_index(node, mutation_index): |
| 85 | + if content := node.text.decode(): |
| 86 | + end_point = node.end_point |
| 87 | + start_point = node.start_point |
| 88 | + mutation_index[(end_point.row, end_point.column)] = { |
| 89 | + "type": node.type, |
| 90 | + "content": content, |
| 91 | + "start_point": (start_point.row, start_point.column), |
| 92 | + "end_point": (end_point.row, end_point.column), |
| 93 | + } |
| 94 | + |
| 95 | + |
| 96 | +def traverse(node, language_info, mutation_index): |
| 97 | + """ |
| 98 | + Recursively traverse the parse tree node and create mutation index. |
| 99 | +
|
| 100 | + Mutation index contains the start, end coordinates and where mutations |
| 101 | + is to be applied, along with the type of mutation. Each mutation entry |
| 102 | + is keyed by a tuple containing the end coordinates. |
| 103 | + """ |
| 104 | + if node.type in language_info.get("identifiers") or node.type in language_info.get("comments"): |
| 105 | + add_to_mutation_index(node=node, mutation_index=mutation_index) |
| 106 | + |
| 107 | + for child in node.children: |
| 108 | + traverse(child, language_info, mutation_index) |
| 109 | + |
| 110 | + |
| 111 | +def apply_mutation(text, start_point, end_point, replacement, successive_line_count): |
| 112 | + """Mutate tokens between start and end points with replacement string.""" |
| 113 | + |
| 114 | + start_row, start_col = start_point |
| 115 | + end_row, end_col = end_point |
| 116 | + |
| 117 | + # Compute 1D mutation position from 2D coordinates |
| 118 | + start_index = successive_line_count[start_row] + start_col |
| 119 | + end_index = successive_line_count[end_row] + end_col |
| 120 | + |
| 121 | + modified_text = text[:start_index] + replacement + text[end_index:] |
| 122 | + modified_lines = modified_text.splitlines(keepends=True) |
| 123 | + |
| 124 | + # Remove empty comment lines. |
| 125 | + if not replacement and modified_lines[start_row].strip() == "": |
| 126 | + del modified_lines[start_row] |
| 127 | + |
| 128 | + return "".join(modified_lines) |
| 129 | + |
| 130 | + |
| 131 | +def get_stem_code(location): |
| 132 | + """ |
| 133 | + Return the stemmed code for the code file at the specified `location`. |
| 134 | +
|
| 135 | + Parse the code using tree-sitter, create a mutation index for tokens that |
| 136 | + need to be replaced or removed, and apply these mutations bottom-up to |
| 137 | + generate the stemmed code. |
| 138 | + """ |
| 139 | + parser_result = get_parser(location) |
| 140 | + if not parser_result: |
| 141 | + return |
| 142 | + |
| 143 | + with open(location, "rb") as f: |
| 144 | + source = f.read() |
| 145 | + mutations = {} |
| 146 | + parser, language_info = parser_result |
| 147 | + tree = parser.parse(source) |
| 148 | + traverse(tree.root_node, language_info, mutations) |
| 149 | + |
| 150 | + # Apply mutations bottom-up |
| 151 | + mutations = dict(sorted(mutations.items(), reverse=True)) |
| 152 | + text = source.decode() |
| 153 | + cur_count = 0 |
| 154 | + lines = text.splitlines(keepends=True) |
| 155 | + successive_line_count = [cur_count := cur_count + len(line) for line in lines] |
| 156 | + successive_line_count.insert(0, 0) |
| 157 | + |
| 158 | + for value in mutations.values(): |
| 159 | + text = apply_mutation( |
| 160 | + text=text, |
| 161 | + end_point=value["end_point"], |
| 162 | + start_point=value["start_point"], |
| 163 | + replacement=("idf" if value["type"] == "identifier" else ""), |
| 164 | + successive_line_count=successive_line_count, |
| 165 | + ) |
| 166 | + return text |
0 commit comments