3 # fixcc -- nitpick lily's c++ code
6 # * maintainable rules: regexp's using whitespace (?x) and match names
8 # * trailing `*' vs. function definition
9 # * do not break/change indentation of fixcc-clean files
10 # * check lexer, parser
11 # * rewrite in elisp, add to cc-mode
12 # * using regexes is broken by design
32 # space before parenthesis open
33 ('([^\( \]])[ \t]*\(', '\\1 ('),
38 # delete inline double spaces
40 # delete space after parenthesis open
42 # delete space before parenthesis close
44 # delete spaces after prefix
45 ('(--|\+\+)[ \t]*([\w\)])', '\\1\\2'),
46 # delete spaces before postfix
47 ('([\w\)\]])[ \t]*(--|\+\+)', '\\1\\2'),
48 # delete space after parenthesis close
49 #('\)[ \t]*([^\w])', ')\\1'),
50 # delete space around operator
51 # ('([\w\(\)\]])([ \t]*)(::|\.)([ \t]*)([\w\(\)])', '\\1\\3\\5'),
52 ('([\w\(\)\]])([ \t]*)(\.|->)([ \t]*)([\w\(\)])', '\\1\\3\\5'),
53 # delete space after operator
54 ('(::)([ \t]*)([\w\(\)])', '\\1\\3'),
55 # delete superflous space around operator
56 ('([\w\(\)\]])([ \t]+)(&&|\|\||<=|>=|!=|\|=|==|\+=|-=|\*=|/=|\?|<|>|\+|-|=|/|:|&|\||\*)([ \t]+)([\w\(\)])', '\\1 \\3 \\5'),
57 # space around operator1
58 ('([\w\)\]]) *(&&|\|\||<=|>=|!=|\|=|==|\+=|-=|\*=|/=|\?|<|>|=|/|:|&|\||\*) *([\w\(])', '\\1 \\2 \\3'),
59 # space around operator2
60 ('([\w\)\]]) *(&&|\|\||<=|>=|!=|\|=|==|\+=|-=|\*=|/=|\?|<|>|=|/|:|&|\||\*) ([^\w\s])', '\\1 \\2 \\3'),
61 # space around operator3
62 ('([^\w\s]) (&&|\|\||<=|>=|!=|\|=|==|\+=|-=|\*=|/=|\?|<|[^-]>|=|/|:|&|\||\*) *([\w\(])', '\\1 \\2 \\3'),
63 # space around operator4
64 ('([\w\(\)\]]) (\*|/|\+|-) *([-:])', '\\1 \\2 \\3'),
65 # space around +/-; exponent
66 ('([\w\)\]])(\+|-)([_A-Za-z\(])', '\\1 \\2 \\3'),
67 ('([_\dA-Za-df-z\)\]])(\+|-)([\w\(])', '\\1 \\2 \\3'),
69 (' (::|&&|\|\||<=|>=|!=|\|=|==|\+=|-=|\*=|/=|\?|<|>|\+|-|=|/|:|&XXX|\||\*XXX)[ \t]*\n([ \t]*)', '\n\\2\\1 '),
71 ##('(bool|char|const|delete|int|stream|unsigned|void|size_t|struct \w+|[A-Z]\w*|,|;|&&|<|[^-]>|\|\||-|\+)[ \t]*(\*|&)[ \t]*', '\\1 \\2'),
72 ('(bool|char|const|delete|int|stream|unsigned|void|size_t|struct \w+|[A-Z]\w*|,|;|:|=|\?\)|&&|<|[^-]>|\|\||-|\+)[ \t]*(\*|&)[ \t]*', '\\1 \\2'),
73 #to#('(bool|char|const|delete|int|stream|unsigned|void|([A-Z]\w*)|[,])[ \n\t]*(\*|&)[ \t]*', '\\1 \\3'),
74 # pointer with template
75 ('(( *((bool|char|const|delete|int|stream|unsigned|void|size_t|class[ \t]+\w*|[A-Z]\w*|\w+::\w+|[,])[ \*&],*)+)>) *(\*|&) *', '\\1 \\5'),
76 #to#('(( *((bool|char|delete|int|stream|unsigned|void|(class[ \t]+\w*)|([A-Z]\w*)|[,])[ \*&],*)+)>)[ \t\n]*(\*|&) *', '\\1 \\7'),
77 # unary pointer, minus, not
78 ('(return|=) (\*|&|-|!) ([\w\(])', '\\1 \\2\\3'),
79 # space after `operator'
80 ('(\Woperator) *([^\w\s])', '\\1 \\2'),
81 # dangling brace close
82 ('\n[ \t]*(\n[ \t]*})', '\\1'),
84 ('\n[ \t]*\n[ \t]*\n', '\n\n'),
85 # dangling parenthesis open
86 #('[ \t]*\n[ \t]*\([ \t]*\n', '('),
88 # dangling parenthesis close
95 ('(\w)[ \t]*([^\s]*){([ \t]*\n)', '\\1\\2\n{\n'),
96 # brace open backslash
97 ('(\w[^\n]*){[ \t]*\\\\\n', '\\1\\\n{\\\n'),
99 ('}[ \t]*([^\n]*\w[^\n\\\]*)\n', '}\n\\1\n'),
100 # brace close backslash
101 ('}[ \t]*([^\n]*\w[^\n\\\]*)', '\n}\n\\1'),
102 # delete space after `operator'
103 #('(\Woperator) (\W)', '\\1\\2'),
104 # delete space after case, label
105 ('(\W(case|label) ([\w]+)) :', '\\1:'),
106 # delete space before comma
108 # delete space before semicolon
110 # delete space before eol-backslash
111 ('[ \t]*\\\\\n', '\\\n'),
112 # delete trailing whitespace
115 ## Deuglify code that also gets ugly by rules above.
116 # delete newline after typedef struct
117 ('(typedef struct\s+([\w]*\s){([^}]|{[^}]*})*})\s*\n\s*(\w[\w\d]*;)', '\\1 \\4'),
118 # delete spaces around template brackets
119 #('(dynamic_cast|template|([A-Z]\w*))[ \t]*<[ \t]*(( *(bool|char|int|unsigned|void|(class[ \t]+\w*)|([A-Z]\w*)),?)+)[ \t]?(| [\*&])[ \t]*>', '\\1<\\3\\8>'),
120 ('(dynamic_cast|template|typedef|\w+::\w+|[A-Z]\w*)[ \t]*<[ \t]*(( *(bool|char|const|int|unsigned|void|size_t|class[ \t]+\w*|[A-Z]\w*)( *[\*&]?,|[\*&])*)+)[ \t]?(| [\*&])[ \t]*>', '\\1<\\2\\6>'),
121 ('(\w+::\w+|[A-Z]\w*) < ((\w+::\w+|[A-Z]\w*)<[A-Z]\w*>) >', '\\1<\\2 >'),
122 ('((if|while)\s+\(([^\)]|\([^\)]*\))*\))\s*;', '\\1\n;'),
123 ('(for\s+\(([^;]*;[^;]*;([^\)]|\([^\)]*\))*)\))\s*;', '\\1\n;'),
125 ('(}\s*while\s*)(\(([^\)]|\([^\)]*\))*\))\s*;', '\\1\\2;'),
127 ## Fix code that gets broken by rules above.
128 ##('->\s+\*', '->*'),
129 # delete space before #define x()
130 ('#[ \t]*define (\w*)[ \t]*\(', '#define \\1('),
131 # add space in #define x ()
132 ('#[ \t]*define (\w*)(\(([^\(\)]|\([^\(\)]*\))*\)\\n)',
134 # delete space in #include <>
135 ('#[ \t]*include[ \t]*<[ \t]*([^ \t>]*)[ \t]*(/?)[ \t]*([^ \t>]*)[ \t]*>',
136 '#include <\\1\\2\\3>'),
137 # delete backslash before empty line (emacs' indent region is broken)
138 ('\\\\\n\n', '\n\n'),
143 # delete trailing whitespace
145 # delete empty first lines
146 ('(/\*\n)\n*', '\\1'),
147 # delete empty last lines
148 ('\n*(\n\*/)', '\\1'),
149 ## delete newline after start?
151 ## delete newline before end?
156 # Recognize special sequences in the input.
158 # (?P<name>regex) -- Assign result of REGEX to NAME.
159 # *? -- Match non-greedily.
160 # (?m) -- Multiline regex: Make ^ and $ match at each line.
161 # (?s) -- Make the dot match all characters including newline.
162 # (?x) -- Ignore whitespace in patterns.
173 [ \t]*/\*.*?\*/))''',
175 'singleline_comment':
180 [ \t]*//([ \t][^\n]*|)\n))''',
186 "([^"]|(([^\\]|(\\\\))\\"))*"))''',
198 "#[ \t]*include[ \t]*<[^>]*>''',
203 def replacement_text (self):
206 def filter_text (self):
207 return self.replacement_text ()
209 def ly_is_outdated (self):
212 def png_is_outdated (self):
215 class Substring (Chunk):
216 def __init__ (self, source, start, end):
221 def replacement_text (self):
222 s = self.source[self.start:self.end]
224 sys.stderr.write ('CXX Rules')
227 sys.stderr.write ('.')
228 #sys.stderr.write ('\n*********\n')
229 #sys.stderr.write (i[0])
230 #sys.stderr.write ('\n=========\n')
231 #sys.stderr.write (s)
232 #sys.stderr.write ('\n*********\n')
233 s = re.sub (i[0], i[1], s)
235 sys.stderr.write ('done\n')
239 class Snippet (Chunk):
240 def __init__ (self, type, match, format):
247 def replacement_text (self):
248 return self.match.group ('match')
250 def substring (self, s):
251 return self.match.group (s)
254 return `self.__class__` + ' type = ' + self.type
256 class Multiline_comment (Snippet):
257 def __init__ (self, source, match, format):
264 def replacement_text (self):
265 s = self.match.group ('match')
267 sys.stderr.write ('COMMENT Rules')
268 for i in rules[COMMENT]:
270 sys.stderr.write ('.')
271 s = re.sub (i[0], i[1], s)
274 snippet_type_to_class = {
275 'multiline_comment': Multiline_comment,
276 # 'lilypond_block': Lilypond_snippet,
277 # 'lilypond': Lilypond_snippet,
278 # 'include': Include_snippet,
281 def find_toplevel_snippets (s, types):
283 sys.stderr.write ('Dissecting')
287 res[i] = re.compile (snippet_res[format][i])
291 ## found = dict (map (lambda x: (x, None),
295 map (lambda x, f = found: f.setdefault (x, None),
298 # We want to search for multiple regexes, without searching
299 # the string multiple times for one regex.
300 # Hence, we use earlier results to limit the string portion
302 # Since every part of the string is traversed at most once for
303 # every type of snippet, this is linear.
307 sys.stderr.write ('.')
311 if not found[type] or found[type][0] < index:
313 m = res[type].search (s[index:endex])
318 if snippet_type_to_class.has_key (type):
319 cl = snippet_type_to_class[type]
320 snip = cl (type, m, format)
321 start = index + m.start ('match')
322 found[type] = (start, snip)
326 or found[type][0] < found[first][0]):
331 # Limiting the search space is a cute
332 # idea, but this *requires* to search
333 # for possible containing blocks
334 # first, at least as long as we do not
335 # search for the start of blocks, but
336 # always/directly for the entire
337 # @block ... @end block.
339 endex = found[first][0]
342 snippets.append (Substring (s, index, len (s)))
345 (start, snip) = found[first]
346 snippets.append (Substring (s, index, start))
347 snippets.append (snip)
349 index = start + len (snip.match.group ('match'))
353 def nitpick_file (outdir, file):
354 s = open (file).read ()
356 # FIXME: Containing blocks must be first, see
357 # find_toplevel_snippets.
360 'singleline_comment',
365 chunks = find_toplevel_snippets (s, snippet_types)
366 #code = filter (lambda x: is_derived_class (x.__class__, Substring),
369 t = string.join (map (lambda x: x.filter_text (), chunks), '')
373 os.system ('mv %s %s~' % (file, file))
375 fixt = os.path.join (outdir,
376 os.path.basename (file))
380 if s != t or indent_p:
383 def indent_file (file):
390 --eval '(let ((error nil)
391 (version-control nil))
392 (load-library "cc-mode")
394 (indent-region (point-min) (point-max))
395 (if (buffer-modified-p (current-buffer))
396 (save-buffer)))' ''' % vars ()
397 emacsclient = '''emacsclient\
398 --socket-name=%(socketdir)s/%(socketname)s\
400 --eval '(let ((error nil)
401 (version-control nil))
402 (load-library "cc-mode")
403 (find-file "%(file)s")
405 (indent-region (point-min) (point-max))
406 (if (buffer-modified-p (current-buffer))
407 (save-buffer)))' ''' \
409 'socketdir' : socketdir,
410 'socketname' : socketname, }
412 sys.stderr.write (emacs)
413 sys.stderr.write ('\n')
418 sys.stdout.write (r'''
420 fixcc [OPTION]... FILE...
424 --indent reindent, even if no changes
428 Typical use with LilyPond:
430 fixcc $(find flower kpath-guile lily -name '*cc' -o -name '*hh' | grep -v /out)
432 This script is licensed under the GNU GPL
436 global indent_p, outdir, verbose_p
437 (options, files) = getopt.getopt (sys.argv[1:], '',
438 ['help', 'indent', 'outdir=',
440 for (o, a) in options:
444 elif o == '--indent':
446 elif o == '--outdir':
448 elif o == '--verbose':
463 socketdir = '/tmp/fixcc'
464 socketname = 'fixcc%d' % os.getpid ()
469 os.unlink (os.path.join (socketdir, socketname))
470 os.mkdir (socketdir, 0700)
474 --eval '(let ((error nil)
475 (version-control nil))
476 (load-library "server")
477 (setq server-socket-dir "%(socketdir)s")
478 (setq server-name "%(socketname)s")
480 (while t) (sleep 1000))' ''' \
481 % { 'socketdir' : socketdir,
482 'socketname' : socketname, }
487 while not os.path.exists (os.path.join (socketdir, socketname)):
491 #emacsclient should be faster, but this does not work yet
493 files = do_options ()
494 if outdir and not os.path.isdir (outdir):
497 sys.stderr.write ('%s...\n' % i)
498 nitpick_file (outdir, i)
501 ## TODO: make this compilable and check with g++
509 public: static char* foo ();
510 std::map<char*,int>* bar (char, char) { return 0; }
518 operator << (ostream & os, String d);
520 typedef struct _t_ligature
523 struct _t_ligature * next;
526 typedef std::map < AFM_Ligature const *, int > Bar;
543 a [*++ a] = (char*) foe (*i, &bar) *
545 int operator double ();
546 std::map<char*,int> y =*bar(-*a ,*b);
547 Interval_t<T> & operator*= (T r);
549 int compare (Pqueue_ent < K, T > const& e1, Pqueue_ent < K,T> *e2);
551 if (abs (f)*2 > abs (d) *FUDGE)
554 for (; i<x foo(); foo>bar);
564 1 && * unsmob_moment (lf);
565 line_spanner_ = make_spanner ("DynamicLineSpanner", rq ? rq->*self_scm
573 cookie_io_functions_t Memory_out_stream::functions_ = {
574 Memory_out_stream::reader,
578 int compare (Array < Pitch> *, Array < Pitch> *);
579 original_ = (Grob *) & s;
580 Drul_array< Link_array<Grob> > o;
583 header_.char_info_pos = (6 + header_length) * 4;
584 return ly_bool2scm (*ma < * mb);
594 test_file = 'fixcc.cc'
595 open (test_file, 'w').write (TEST)
596 nitpick_file (outdir, test_file)
597 sys.stdout.write (open (test_file).read ())
599 if __name__ == '__main__':