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
34 # delete gratuitous block
35 ('''\n( |\t)\s*{\n\s*(.*?)(?![{}]|\b(do|for|else|if|switch|while)\b);\n\s*}''',
40 # space before parenthesis open
41 ('([^\( \]])[ \t]*\(', '\\1 ('),
43 ("\([^'],\)[ \t]*", '\1 '),
44 # delete gratuitous block
45 ('''\n( |\t)\s*{\n\s*(.*?)(?![{}]|\b(do|for|else|if|switch|while)\b);\n\s*}''',
49 # delete inline double spaces
51 # delete space after parenthesis open
53 # delete space before parenthesis close
55 # delete spaces after prefix
56 ('(--|\+\+)[ \t]*([\w\)])', '\\1\\2'),
57 # delete spaces before postfix
58 ('([\w\)\]])[ \t]*(--|\+\+)', '\\1\\2'),
59 # delete space after parenthesis close
60 #('\)[ \t]*([^\w])', ')\\1'),
61 # delete space around operator
62 # ('([\w\(\)\]])([ \t]*)(::|\.)([ \t]*)([\w\(\)])', '\\1\\3\\5'),
63 ('([\w\(\)\]])([ \t]*)(\.|->)([ \t]*)([\w\(\)])', '\\1\\3\\5'),
64 # delete space after operator
65 ('(::)([ \t]*)([\w\(\)])', '\\1\\3'),
66 # delete superflous space around operator
67 ('([\w\(\)\]])([ \t]+)(&&|\|\||<=|>=|!=|\|=|==|\+=|-=|\*=|/=|\?|<|>|\+|-|=|/|:|&|\||\*)([ \t]+)([\w\(\)])', '\\1 \\3 \\5'),
68 # space around operator1
69 ('([\w\)\]]) *(&&|\|\||<=|>=|!=|\|=|==|\+=|-=|\*=|/=|\?|<|>|=|/|:|&|\||\*) *([\w\(])', '\\1 \\2 \\3'),
70 # space around operator2
71 ('([\w\)\]]) *(&&|\|\||<=|>=|!=|\|=|==|\+=|-=|\*=|/=|\?|<|>|=|/|:|&|\||\*) ([^\w\s])', '\\1 \\2 \\3'),
72 # space around operator3
73 ('([^\w\s]) (&&|\|\||<=|>=|!=|\|=|==|\+=|-=|\*=|/=|\?|<|[^-]>|=|/|:|&|\||\*) *([\w\(])', '\\1 \\2 \\3'),
74 # space around operator4
75 ('([\w\(\)\]]) (\*|/|\+|-) *([-:])', '\\1 \\2 \\3'),
76 # space around +/-; exponent
77 ('([\w\)\]])(\+|-)([_A-Za-z\(])', '\\1 \\2 \\3'),
78 ('([_\dA-Za-df-z\)\]])(\+|-)([\w\(])', '\\1 \\2 \\3'),
80 (' (::|&&|\|\||<=|>=|!=|\|=|==|\+=|-=|\*=|/=|\?|<|>|\+|-|=|/|:|&XXX|\||\*XXX)[ \t]*\n([ \t]*)', '\n\\2\\1 '),
82 ##('(bool|char|const|delete|int|stream|unsigned|void|size_t|struct \w+|[A-Z]\w*|,|;|&&|<|[^-]>|\|\||-|\+)[ \t]*(\*|&)[ \t]*', '\\1 \\2'),
83 ('(bool|char|const|delete|int|stream|unsigned|void|size_t|struct \w+|[A-Z]\w*|,|;|:|=|\?\)|&&|<|[^-]>|\|\||-|\+)[ \t]*(\*|&)[ \t]*', '\\1 \\2'),
84 #to#('(bool|char|const|delete|int|stream|unsigned|void|([A-Z]\w*)|[,])[ \n\t]*(\*|&)[ \t]*', '\\1 \\3'),
85 # pointer with template
86 ('(( *((bool|char|const|delete|int|stream|unsigned|void|size_t|class[ \t]+\w*|[A-Z]\w*|\w+::\w+|[,])[ \*&],*)+)>) *(\*|&) *', '\\1 \\5'),
87 #to#('(( *((bool|char|delete|int|stream|unsigned|void|(class[ \t]+\w*)|([A-Z]\w*)|[,])[ \*&],*)+)>)[ \t\n]*(\*|&) *', '\\1 \\7'),
88 # unary pointer, minus, not
89 ('(return|=) (\*|&|-|!) ([\w\(])', '\\1 \\2\\3'),
90 # space after `operator'
91 ('(\Woperator) *([^\w\s])', '\\1 \\2'),
92 # dangling brace close
93 ('\n[ \t]*(\n[ \t]*})', '\\1'),
95 ('\n[ \t]*\n[ \t]*\n', '\n\n'),
96 # dangling parenthesis open
97 #('[ \t]*\n[ \t]*\([ \t]*\n', '('),
99 # dangling parenthesis close
106 ('(\w)[ \t]*([^\s]*){([ \t]*\n)', '\\1\\2\n{\n'),
107 # brace open backslash
108 ('(\w[^\n]*){[ \t]*\\\\\n', '\\1\\\n{\\\n'),
110 ("}[ \t]*([^'\n]*\w[^\n\\\]*)\n", '}\n\\1\n'),
111 # brace close backslash
112 ("}[ \t]*([^'\n]*\w[^\n\\\]*)", '\n}\n\\1'),
113 # delete space after `operator'
114 #('(\Woperator) (\W)', '\\1\\2'),
115 # delete space after case, label
116 ('(\W(case|label) ([\w]+)) :', '\\1:'),
117 # delete space before comma
119 # delete space before semicolon
121 # delete space before eol-backslash
122 ('[ \t]*\\\\\n', '\\\n'),
123 # delete trailing whitespace
126 ## Deuglify code that also gets ugly by rules above.
127 # delete newline after typedef struct
128 ('(typedef struct\s+([\w]*\s){([^}]|{[^}]*})*})\s*\n\s*(\w[\w\d]*;)', '\\1 \\4'),
129 # delete spaces around template brackets
130 #('(dynamic_cast|template|([A-Z]\w*))[ \t]*<[ \t]*(( *(bool|char|int|unsigned|void|(class[ \t]+\w*)|([A-Z]\w*)),?)+)[ \t]?(| [\*&])[ \t]*>', '\\1<\\3\\8>'),
131 ('(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>'),
132 ('(\w+::\w+|[A-Z]\w*) < ((\w+::\w+|[A-Z]\w*)<[A-Z]\w*>) >', '\\1<\\2 >'),
133 ('((if|while)\s+\(([^\)]|\([^\)]*\))*\))\s*;', '\\1\n;'),
134 ('(for\s+\(([^;]*;[^;]*;([^\)]|\([^\)]*\))*)\))\s*;', '\\1\n;'),
136 ('(}\s*while\s*)(\(([^\)]|\([^\)]*\))*\))\s*;', '\\1\\2;'),
138 ## Fix code that gets broken by rules above.
139 ##('->\s+\*', '->*'),
140 # delete space before #define x()
141 ('#[ \t]*define (\w*)[ \t]*\(', '#define \\1('),
142 # add space in #define x ()
143 ('#[ \t]*define (\w*)(\(([^\(\)]|\([^\(\)]*\))*\)\\n)',
145 # delete space in #include <>
146 ('#[ \t]*include[ \t]*<[ \t]*([^ \t>]*)[ \t]*(/?)[ \t]*([^ \t>]*)[ \t]*>',
147 '#include <\\1\\2\\3>'),
148 # delete backslash before empty line (emacs' indent region is broken)
149 ('\\\\\n\n', '\n\n'),
154 # delete trailing whitespace
156 # delete empty first lines
157 ('(/\*\n)\n*', '\\1'),
158 # delete empty last lines
159 ('\n*(\n\*/)', '\\1'),
160 ## delete newline after start?
162 ## delete newline before end?
167 # Recognize special sequences in the input.
169 # (?P<name>regex) -- Assign result of REGEX to NAME.
170 # *? -- Match non-greedily.
171 # (?m) -- Multiline regex: Make ^ and $ match at each line.
172 # (?s) -- Make the dot match all characters including newline.
173 # (?x) -- Ignore whitespace in patterns.
181 [ \t]*/\*.*?\*/))''',
183 'singleline_comment':
188 [ \t]*//([ \t][^\n]*|)\n))''',
194 "([^\"\n](\")*)*"))''',
206 "#[ \t]*include[ \t]*<[^>]*>''',
211 def replacement_text (self):
214 def filter_text (self):
215 return self.replacement_text ()
217 class Substring (Chunk):
218 def __init__ (self, source, start, end):
223 def replacement_text (self):
224 s = self.source[self.start:self.end]
226 sys.stderr.write ('CXX Rules')
229 sys.stderr.write ('.')
230 #sys.stderr.write ('\n\n***********\n')
231 #sys.stderr.write (i[0])
232 #sys.stderr.write ('\n***********\n')
233 #sys.stderr.write ('\n=========>>\n')
234 #sys.stderr.write (s)
235 #sys.stderr.write ('\n<<=========\n')
236 s = re.sub (i[0], i[1], s)
238 sys.stderr.write ('done\n')
242 class Snippet (Chunk):
243 def __init__ (self, type, match, format):
250 def replacement_text (self):
251 return self.match.group ('match')
253 def substring (self, s):
254 return self.match.group (s)
257 return `self.__class__` + ' type = ' + self.type
259 class Multiline_comment (Snippet):
260 def __init__ (self, source, match, format):
267 def replacement_text (self):
268 s = self.match.group ('match')
270 sys.stderr.write ('COMMENT Rules')
271 for i in rules[COMMENT]:
273 sys.stderr.write ('.')
274 s = re.sub (i[0], i[1], s)
277 snippet_type_to_class = {
278 'multiline_comment': Multiline_comment,
279 # 'string': Multiline_comment,
280 # 'include': Include_snippet,
283 def find_toplevel_snippets (s, types):
285 sys.stderr.write ('Dissecting')
289 res[i] = re.compile (snippet_res[format][i])
293 ## found = dict (map (lambda x: (x, None),
297 map (lambda x, f = found: f.setdefault (x, None),
300 # We want to search for multiple regexes, without searching
301 # the string multiple times for one regex.
302 # Hence, we use earlier results to limit the string portion
304 # Since every part of the string is traversed at most once for
305 # every type of snippet, this is linear.
309 sys.stderr.write ('.')
313 if not found[type] or found[type][0] < index:
315 m = res[type].search (s[index:endex])
320 if snippet_type_to_class.has_key (type):
321 cl = snippet_type_to_class[type]
322 snip = cl (type, m, format)
323 start = index + m.start ('match')
324 found[type] = (start, snip)
328 or found[type][0] < found[first][0]):
333 # Limiting the search space is a cute
334 # idea, but this *requires* to search
335 # for possible containing blocks
336 # first, at least as long as we do not
337 # search for the start of blocks, but
338 # always/directly for the entire
339 # @block ... @end block.
341 endex = found[first][0]
344 snippets.append (Substring (s, index, len (s)))
347 (start, snip) = found[first]
348 snippets.append (Substring (s, index, start))
349 snippets.append (snip)
351 index = start + len (snip.match.group ('match'))
355 def nitpick_file (outdir, file):
356 s = open (file).read ()
358 for i in rules[GLOBAL_CXX]:
359 s = re.sub (i[0], i[1], s)
361 # FIXME: Containing blocks must be first, see
362 # find_toplevel_snippets.
363 # We leave simple strings be part of the code
366 'singleline_comment',
371 chunks = find_toplevel_snippets (s, snippet_types)
372 #code = filter (lambda x: is_derived_class (x.__class__, Substring),
375 t = string.join (map (lambda x: x.filter_text (), chunks), '')
379 os.system ('mv %s %s~' % (file, file))
381 fixt = os.path.join (outdir,
382 os.path.basename (file))
386 if s != t or indent_p:
389 def indent_file (file):
396 --eval '(let ((error nil)
397 (version-control nil))
398 (load-library "cc
-mode
")
400 (indent-region (point-min) (point-max))
401 (if (buffer-modified-p (current-buffer))
402 (save-buffer)))' ''' % vars ()
403 emacsclient = '''emacsclient\
404 --socket-name=%(socketdir)s/%(socketname)s\
406 --eval '(let ((error nil)
407 (version-control nil))
408 (load-library "cc
-mode
")
409 (find-file "%(file)s")
411 (indent-region (point-min) (point-max))
412 (if (buffer-modified-p (current-buffer))
413 (save-buffer)))' ''' \
415 'socketdir' : socketdir,
416 'socketname' : socketname, }
418 sys.stderr.write (emacs)
419 sys.stderr.write ('\n')
424 sys.stdout.write (r'''
426 fixcc [OPTION]... FILE...
430 --indent reindent, even if no changes
434 Typical use with LilyPond:
436 fixcc $(find flower kpath-guile lily -name '*cc' -o -name '*hh' | grep -v /out)
438 This script is licensed under the GNU GPL
442 global indent_p, outdir, verbose_p
443 (options, files) = getopt.getopt (sys.argv[1:], '',
444 ['help', 'indent', 'outdir=',
446 for (o, a) in options:
450 elif o == '--indent':
452 elif o == '--outdir':
454 elif o == '--verbose':
469 socketdir = '/tmp/fixcc'
470 socketname = 'fixcc%d' % os.getpid ()
475 os.unlink (os.path.join (socketdir, socketname))
476 os.mkdir (socketdir, 0700)
480 --eval '(let ((error nil)
481 (version-control nil))
482 (load-library "server
")
483 (setq server-socket-dir "%(socketdir)s")
484 (setq server-name "%(socketname)s")
486 (while t) (sleep 1000))' ''' \
487 % { 'socketdir' : socketdir,
488 'socketname' : socketname, }
493 while not os.path.exists (os.path.join (socketdir, socketname)):
497 #emacsclient should be faster, but this does not work yet
499 files = do_options ()
500 if outdir and not os.path.isdir (outdir):
503 sys.stderr.write ('%s...\n' % i)
504 nitpick_file (outdir, i)
507 ## TODO: make this compilable and check with g++
515 public: static char* foo ();
516 std::map<char*,int>* bar (char, char) { return 0; }
524 operator << (ostream & os, String d);
526 typedef struct _t_ligature
529 struct _t_ligature * next;
532 typedef std::map < AFM_Ligature const *, int > Bar;
535 (c) 1997--2007 Han-Wen Nienhuys <hanwen@cs.uu.nl>
553 a [*++ a] = (char*) foe (*i, &bar) *
555 int operator double ();
556 std::map<char*,int> y =*bar(-*a ,*b);
557 Interval_t<T> & operator*= (T r);
559 int compare (Pqueue_ent < K, T > const& e1, Pqueue_ent < K,T> *e2);
561 if (abs (f)*2 > abs (d) *FUDGE)
564 for (; i<x foo(); foo>bar);
574 1 && * unsmob_moment (lf);
575 line_spanner_ = make_spanner ("DynamicLineSpanner
", rq ? rq->*self_scm
583 cookie_io_functions_t Memory_out_stream::functions_ = {
584 Memory_out_stream::reader,
588 int compare (Array < Pitch> *, Array < Pitch> *);
589 original_ = (Grob *) & s;
590 Drul_array< Link_array<Grob> > o;
593 header_.char_info_pos = (6 + header_length) * 4;
594 return ly_bool2scm (*ma < * mb);
606 span_ = make_spanner ("StaffSymbol
", SCM_EOL);
612 span_ = make_spanner (StaffSymbol, SCM_EOL);
618 test_file = 'fixcc.cc'
619 open (test_file, 'w').write (TEST)
620 nitpick_file (outdir, test_file)
621 sys.stdout.write (open (test_file).read ())
623 if __name__ == '__main__':