-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnorm_align.py
More file actions
212 lines (167 loc) · 5.69 KB
/
norm_align.py
File metadata and controls
212 lines (167 loc) · 5.69 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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
#!/usr/bin/env python3
"""
norm_align.py - Fix MISALIGNED_VAR_DECL for norminette compliance.
Detects groups of consecutive variable declarations inside functions/structs
and aligns all variable names to the same tab-stop column using tab characters.
The target column = next tab stop after the longest type in the group.
Usage: python3 norm_align.py [files...] (default: all *.c *.h in cwd)
"""
import re
import os
import sys
import glob
TAB_W = 4
# Words that can appear in a C type specifier
TYPE_WORDS = {
'static', 'const', 'volatile', 'register', 'extern',
'unsigned', 'signed', 'struct', 'enum', 'union',
'int', 'char', 'float', 'double', 'void',
'short', 'long', 'size_t', 'ssize_t', 'bool',
'int8_t', 'int16_t', 'int32_t', 'int64_t',
'uint8_t', 'uint16_t', 'uint32_t', 'uint64_t',
}
def is_type_word(w):
"""Check if a word is a C type keyword or 42-style typedef (t_xxx)."""
if w in TYPE_WORDS:
return True
if re.match(r'^[tse]_\w+$', w):
return True
# Project-specific typedefs that don't follow t_ convention
if w in ('ucvector', 'uivector'):
return True
return False
def visual_col(s):
"""Compute the visual column width of a string containing tabs."""
col = 0
for c in s:
if c == '\t':
col = ((col // TAB_W) + 1) * TAB_W
else:
col += 1
return col
def next_tab_stop(col):
"""Return the next tab stop strictly after col."""
return ((col // TAB_W) + 1) * TAB_W
def tabs_to_col(from_col, target_col):
"""Return tab characters needed to go from from_col to target_col."""
n = 0
col = from_col
while col < target_col:
col = next_tab_stop(col)
n += 1
return '\t' * max(n, 1)
def parse_var_decl(line):
"""Try to parse a variable declaration from a line.
Returns (indent, type_text, var_text) or None.
- indent: leading tab characters
- type_text: the type part (e.g. 'unsigned int', 'const char')
- var_text: everything after (e.g. '*ptr;', 'x;', 'arr[10];')
"""
# Must start with tab indentation
m = re.match(r'^(\t+)(.+)$', line)
if not m:
return None
indent = m.group(1)
body = m.group(2).rstrip()
# Must end with ;
if not body.endswith(';'):
return None
# Tokenize on whitespace (tabs or spaces)
tokens = body.split()
if len(tokens) < 2:
return None
# First token must be a type word
if not is_type_word(tokens[0]):
return None
# Reject control flow keywords
if tokens[0] in ('return', 'if', 'else', 'while', 'break', 'continue'):
return None
# Consume consecutive type words
type_parts = []
i = 0
while i < len(tokens) and is_type_word(tokens[i]):
type_parts.append(tokens[i])
i += 1
if i >= len(tokens):
return None
type_text = ' '.join(type_parts)
var_text = ' '.join(tokens[i:])
# Variable part must start with *, (, letter, or underscore
if not re.match(r'^[(*_a-zA-Z]', var_text):
return None
# Extract just the variable name part (before any = assignment)
var_name_part = var_text.split('=')[0].strip().rstrip(';').strip()
# Reject function calls / prototypes (contain '(' in the name part)
if '(' in var_name_part and not var_name_part.startswith('(*'):
return None
return (indent, type_text, var_text)
def align_group(group):
"""Given a list of (indent, type_text, var_text) tuples,
return new lines with all variable names aligned to the same tab stop."""
if not group:
return []
# Find the max visual column where type text ends
max_type_end = 0
for indent, type_text, _ in group:
col = visual_col(indent + type_text)
if col > max_type_end:
max_type_end = col
# Target column: next tab stop after the longest type
target = next_tab_stop(max_type_end)
# Rebuild each line
result = []
for indent, type_text, var_text in group:
type_end = visual_col(indent + type_text)
tabs = tabs_to_col(type_end, target)
result.append(indent + type_text + tabs + var_text)
return result
def fix_file(filepath):
"""Fix variable declaration alignment in a file. Returns True if changed."""
with open(filepath, 'r') as f:
lines = f.read().split('\n')
result = []
i = 0
changed = False
while i < len(lines):
parsed = parse_var_decl(lines[i])
if parsed:
# Start collecting a group of consecutive declarations
group = [parsed]
originals = [lines[i]]
j = i + 1
while j < len(lines):
p = parse_var_decl(lines[j])
if p:
group.append(p)
originals.append(lines[j])
j += 1
else:
break
# Align the group
aligned = align_group(group)
for k, new_line in enumerate(aligned):
if new_line != originals[k]:
changed = True
result.extend(aligned)
i = j
else:
result.append(lines[i])
i += 1
if changed:
with open(filepath, 'w') as f:
f.write('\n'.join(result))
return changed
def main():
files = [a for a in sys.argv[1:] if not a.startswith('-')]
if not files:
files = sorted(glob.glob('*.c') + glob.glob('*.h'))
modified = 0
for f in files:
if not os.path.isfile(f):
continue
if fix_file(f):
modified += 1
print(f"Aligned: {f}")
print(f"\nFixed alignment in {modified}/{len(files)} files")
if __name__ == '__main__':
main()