blob: 4f72e9e08a39985dfc9fcf517564c3d20b4120bd [file] [log] [blame]
Guido van Rossumaa895c71993-06-10 14:43:53 +00001#! /ufs/guido/bin/sgi/python
2#! /usr/local/bin/python
3
4# Perform massive identifier substitution on C source files.
5# This actually tokenizes the files (to some extent) so it can
6# avoid making substitutions inside strings or comments.
7# Inside strings, substitutions are never made; inside comments,
8# it is a user option (on by default).
9#
10# The substitutions are read from one or more files whose lines,
11# when not empty, after stripping comments starting with #,
12# must contain exactly two words separated by whitespace: the
13# old identifier and its replacement.
14#
15# The option -r reverses the sense of the substitutions (this may be
16# useful to undo a particular substitution).
17#
18# If the old identifier is prefixed with a '*' (with no intervening
19# whitespace), then it will not be substituted inside comments.
20#
21# Command line arguments are files or directories to be processed.
22# Directories are searched recursively for files whose name looks
23# like a C file (ends in .h or .c). The special filename '-' means
24# operate in filter mode: read stdin, write stdout.
25#
26# Symbolic links are always ignored (except as explicit directory
27# arguments).
28#
29# The original files are kept as back-up with a "~" suffix.
30#
31# Changes made are reported to stdout in a diff-like format.
32#
33# NB: by changing only the function fixline() you can turn this
34# into a program for different changes to C source files; by
35# changing the function wanted() you can make a different selection of
36# files.
37
38import sys
39import regex
40import string
41import os
42from stat import *
43import getopt
44
45err = sys.stderr.write
46dbg = err
47rep = sys.stdout.write
48
49def usage():
50 err('Usage: ' + sys.argv[0] + \
51 ' [-r] [-s file] ... file-or-directory ...\n')
52 err('\n')
53 err('-r : reverse direction for following -s options\n')
54 err('-s substfile : add a file of substitutions\n')
55 err('\n')
56 err('Each non-empty non-comment line in a substitution file must\n')
57 err('contain exactly two words: an identifier and its replacement.\n')
58 err('Comments start with a # character and end at end of line.\n')
59
60def main():
61 try:
62 opts, args = getopt.getopt(sys.argv[1:], 'rs:')
63 except getopt.error, msg:
64 err('Options error: ' + str(msg) + '\n')
65 usage()
66 sys.exit(2)
67 bad = 0
68 if not args: # No arguments
69 usage()
70 sys.exit(2)
71 for opt, arg in opts:
72 if opt == '-r':
73 setreverse()
74 if opt == '-s':
75 addsubst(arg)
76 for arg in args:
77 if os.path.isdir(arg):
78 if recursedown(arg): bad = 1
79 elif os.path.islink(arg):
80 err(arg + ': will not process symbolic links\n')
81 bad = 1
82 else:
83 if fix(arg): bad = 1
84 sys.exit(bad)
85
86# Change this regular expression to select a different set of files
87Wanted = '^[a-zA-Z0-9_]+\.[ch]$'
88def wanted(name):
89 return regex.match(Wanted, name) >= 0
90
91def recursedown(dirname):
92 dbg('recursedown(' + `dirname` + ')\n')
93 bad = 0
94 try:
95 names = os.listdir(dirname)
96 except os.error, msg:
97 err(dirname + ': cannot list directory: ' + str(msg) + '\n')
98 return 1
99 names.sort()
100 subdirs = []
101 for name in names:
102 if name in (os.curdir, os.pardir): continue
103 fullname = os.path.join(dirname, name)
104 if os.path.islink(fullname): pass
105 elif os.path.isdir(fullname):
106 subdirs.append(fullname)
107 elif wanted(name):
108 if fix(fullname): bad = 1
109 for fullname in subdirs:
110 if recursedown(fullname): bad = 1
111 return bad
112
113def fix(filename):
114## dbg('fix(' + `filename` + ')\n')
115 if filename == '-':
116 # Filter mode
117 f = sys.stdin
118 g = sys.stdout
119 else:
120 # File replacement mode
121 try:
122 f = open(filename, 'r')
123 except IOError, msg:
124 err(filename + ': cannot open: ' + str(msg) + '\n')
125 return 1
126 head, tail = os.path.split(filename)
127 tempname = os.path.join(head, '@' + tail)
128 g = None
129 # If we find a match, we rewind the file and start over but
130 # now copy everything to a temp file.
131 lineno = 0
132 initfixline()
133 while 1:
134 line = f.readline()
135 if not line: break
136 lineno = lineno + 1
137 while line[-2:] == '\\\n':
138 nextline = f.readline()
139 if not nextline: break
140 line = line + nextline
141 lineno = lineno + 1
142 newline = fixline(line)
143 if newline != line:
144 if g is None:
145 try:
146 g = open(tempname, 'w')
147 except IOError, msg:
148 f.close()
149 err(tempname+': cannot create: '+\
150 str(msg)+'\n')
151 return 1
152 f.seek(0)
153 lineno = 0
154 initfixline()
155 rep(filename + ':\n')
156 continue # restart from the beginning
157 rep(`lineno` + '\n')
158 rep('< ' + line)
159 rep('> ' + newline)
160 if g is not None:
161 g.write(newline)
162
163 # End of file
164 if filename == '-': return 0 # Done in filter mode
165 f.close()
166 if not g: return 0 # No changes
167
168 # Finishing touch -- move files
169
170 # First copy the file's mode to the temp file
171 try:
172 statbuf = os.stat(filename)
173 os.chmod(tempname, statbuf[ST_MODE] & 07777)
174 except os.error, msg:
175 err(tempname + ': warning: chmod failed (' + str(msg) + ')\n')
176 # Then make a backup of the original file as filename~
177 try:
178 os.rename(filename, filename + '~')
179 except os.error, msg:
180 err(filename + ': warning: backup failed (' + str(msg) + ')\n')
181 # Now move the temp file to the original file
182 try:
183 os.rename(tempname, filename)
184 except os.error, msg:
185 err(filename + ': rename failed (' + str(msg) + ')\n')
186 return 1
187 # Return succes
188 return 0
189
190# Tokenizing ANSI C (partly)
191
192Identifier = '[a-zA-Z_][a-zA-Z0-9_]+'
193String = '"\([^\n\\"]\|\\\\.\)*"'
194Char = '\'\([^\n\\\']\|\\\\.\)*\''
195CommentStart = '/\*'
196CommentEnd = '\*/'
197
198Hexnumber = '0[xX][0-9a-fA-F]*[uUlL]*'
199Octnumber = '0[0-7]*[uUlL]*'
200Decnumber = '[1-9][0-9]*[uUlL]*'
201Intnumber = Hexnumber + '\|' + Octnumber + '\|' + Decnumber
202Exponent = '[eE][-+]?[0-9]+'
203Pointfloat = '\([0-9]+\.[0-9]*\|\.[0-9]+\)\(' + Exponent + '\)?'
204Expfloat = '[0-9]+' + Exponent
205Floatnumber = Pointfloat + '\|' + Expfloat
206Number = Floatnumber + '\|' + Intnumber
207
208# Anything else is an operator -- don't list this explicitly because of '/*'
209
210OutsideComment = (Identifier, Number, String, Char, CommentStart)
211OutsideCommentPattern = '\(' + string.joinfields(OutsideComment, '\|') + '\)'
212OutsideCommentProgram = regex.compile(OutsideCommentPattern)
213
214InsideComment = (Identifier, Number, CommentEnd)
215InsideCommentPattern = '\(' + string.joinfields(InsideComment, '\|') + '\)'
216InsideCommentProgram = regex.compile(InsideCommentPattern)
217
218def initfixline():
219 global Program
220 Program = OutsideCommentProgram
221
222def fixline(line):
223 global Program
224## print '-->', `line`
225 i = 0
226 while i < len(line):
227 i = Program.search(line, i)
228 if i < 0: break
229 found = Program.group(0)
230## if Program is InsideCommentProgram: print '...',
231## else: print ' ',
232## print found
233 if len(found) == 2:
234 if found == '/*':
235 Program = InsideCommentProgram
236 elif found == '*/':
237 Program = OutsideCommentProgram
238 n = len(found)
239 if Dict.has_key(found):
240 subst = Dict[found]
241 if Program is InsideCommentProgram:
242 if NotInComment.has_key(found):
243 pass
244## print 'Ignored in comment:',
245## print found, '-->', subst
246## print 'Line:', line,
247 subst = found
248 else:
249## print 'Substituting in comment:',
250## print found, '-->', subst
251## print 'Line:', line,
252 line = line[:i] + subst + line[i+n:]
253 n = len(subst)
254 i = i + n
255 return line
256
257Reverse = 0
258def setreverse():
259 global Reverse
260 Reverse = (not Reverse)
261
262Dict = {}
263NotInComment = {}
264def addsubst(substfile):
265 try:
266 fp = open(substfile, 'r')
267 except IOError, msg:
268 err(substfile + ': cannot read substfile: ' + str(msg) + '\n')
269 sys.exit(1)
270 lineno = 0
271 while 1:
272 line = fp.readline()
273 if not line: break
274 lineno = lineno + 1
275 try:
276 i = string.index(line, '#')
277 except string.index_error:
278 i = -1 # Happens to delete trailing \n
279 words = string.split(line[:i])
280 if not words: continue
281 if len(words) <> 2:
282 err(substfile + ':' + `lineno` + \
283 ': warning: bad line: ' + line)
284 continue
285 if Reverse:
286 [value, key] = words
287 else:
288 [key, value] = words
289 if value[0] == '*':
290 value = value[1:]
291 if key[0] == '*':
292 key = key[1:]
293 NotInComment[key] = value
294 if Dict.has_key(key):
295 err(substfile + ':' + `lineno` + \
296 ': warning: overriding: ' + \
297 key + ' ' + value + '\n')
298 err(substfile + ':' + `lineno` + \
299 ': warning: previous: ' + Dict[key] + '\n')
300 Dict[key] = value
301 fp.close()
302
303main()