forked from llvm/mlir-www
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild_pattern_catalog_index.py
More file actions
147 lines (113 loc) · 4.05 KB
/
build_pattern_catalog_index.py
File metadata and controls
147 lines (113 loc) · 4.05 KB
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
#!/usr/bin/env python3
"""
Convert pipe-delimited text file to JSON format for MLIR operation search.
Usage: python convert_to_json.py input.txt output.json
"""
from collections import defaultdict
import json
import os
import re
import sys
def extract_namespace(class_name):
"""Extract namespace from qualified class name."""
# Remove template parameters and anonymous namespace markers
cleaned = re.sub(r"<[^>]*>", "", class_name)
cleaned = re.sub(r"\(anonymous namespace\)::", "", cleaned)
# Split by :: and take all but the last part
parts = cleaned.split("::")
if len(parts) > 1:
return "::".join(parts[:-1])
return ""
def fix_method_name(method):
"""Convert from the logger's method name to a UI-friendly name."""
if method == "notifyOperationReplaced (with op)":
return "replace op with new op"
if method == "notifyOperationReplaced (with values)":
return "replace op with values"
if method == "notifyOperationErased":
return "erase op"
if method == "notifyOperationInserted":
return "insert op"
if method == "notifyOperationModified":
return "modify op"
def parse_line(line):
"""Parse a single line from the input file."""
parts = [part.strip() for part in line.strip().split("|")]
if len(parts) < 3 or parts[0].strip() == "":
return None
class_name = parts[0]
method = parts[1]
operations = parts[2:]
namespace = extract_namespace(class_name)
method = fix_method_name(method)
return {
"className": class_name,
"namespace": namespace,
"method": method,
"operations": operations,
}
def build_reverse_index(entries):
"""Build reverse index from operation names to class entries."""
index = defaultdict(list)
for entry in entries:
for op in entry["operations"]:
index[op].append(
{
"className": entry["className"],
"namespace": entry["namespace"],
"method": entry["method"],
"operations": entry["operations"],
}
)
return dict(index)
def extract_metadata(entries):
"""Extract unique namespaces and methods for filtering."""
namespaces = set()
methods = set()
for entry in entries:
if entry["namespace"]:
namespaces.add(entry["namespace"])
methods.add(entry["method"])
return {"namespaces": sorted(list(namespaces)), "methods": sorted(list(methods))}
def main():
if len(sys.argv) != 3:
print("Usage: python convert_to_json.py input.txt output.json")
sys.exit(1)
input_file = sys.argv[1]
output_file = sys.argv[2]
entries = []
lines = []
try:
with open(input_file, "r", encoding="utf-8") as f:
for line_num, line in enumerate(f, 1):
if not line.strip():
continue
lines.append((line_num, line))
except FileNotFoundError:
print(f"Error: Input file '{input_file}' not found")
sys.exit(1)
for line_num, line in lines:
entry = parse_line(line)
if entry:
entries.append(entry)
else:
print(f"Warning: Skipped malformed line {line_num}: {line.strip()}")
print(f"Parsed {len(entries)} entries")
# Build reverse index
operations_index = build_reverse_index(entries)
print(f"Created index for {len(operations_index)} operations")
# Extract metadata
metadata = extract_metadata(entries)
print(
f"Found {len(metadata['namespaces'])} namespaces and {len(metadata['methods'])} methods"
)
# Create final JSON structure
result = {"operations": operations_index, "metadata": metadata}
directory = os.path.dirname(output_file)
os.makedirs(directory, exist_ok=True)
# Write to output file
with open(output_file, "w", encoding="utf-8") as f:
json.dump(result, f, indent=2, ensure_ascii=False)
print(f"Successfully wrote JSON to {output_file}")
if __name__ == "__main__":
main()