3 # fixcc -- indent and space lily's c++ code
5 # This file is part of LilyPond, the GNU music typesetter.
7 # LilyPond is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
12 # LilyPond is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with LilyPond. If not, see <http://www.gnu.org/licenses/>.
20 # Performs string substitution on files, then applies astyle
21 # (http://astyle.sourceforge.net)
23 # Remove prefiltering as the equivalent formatting becomes available in
24 # astyle, or as the prefiltering is deemed un-necessary.
25 # Soon, this script might be replaced by a simple invocation of astyle
45 # delete trailing whitespace
50 # space before parenthesis open
51 ('([\w\)\]])\(', '\\1 ('),
52 # delete inline double spaces
54 # delete space before parenthesis close
56 # delete spaces after prefix
57 ('(--|\+\+) *([\w\(])', '\\1\\2'),
58 # delete spaces before postfix
59 ('([\w\)\]]) *(--|\+\+)', '\\1\\2'),
61 # delete space around operator
62 ('([\w\(\)\]]) *(\.|->) *([\w\(\)])', '\\1\\2\\3'),
63 # delete space after operator
64 ('(::) *([\w\(\)])', '\\1\\2'),
66 # delete superflous space around operator
67 ('([\w\(\)\]]) +(&&|\|\||<=|>=|!=|\|=|==|\+=|-=|\*=|/=|\?|<|>|\+|-|=|/|:|&|\||\*) +([\w\(\)])', '\\1 \\2 \\3'),
69 # trailing operator, but don't un-trail close angle-braces > nor pointer *, and not before a preprocessor line
70 ('(?<!\s) (::|&&|\|\||<=|>=|!=|\|=|==|\+=|-=|\*=|/=|\?|<|\+|-|=|/|:|&XXX|\||\*XXX) *\n( *)([^\s#])', '\n\\2\\1 \\3'),
71 # space after `operator'
72 ('(\Woperator) *([^\w\s])', '\\1 \\2'),
73 # trailing parenthesis open
75 # dangling parenthesis close: Disabled to leave ADD_TRANSLATOR format in place
78 ('\n( *),', ',\n\\1'),
79 # delete space after case, label
80 ('(\W(case|label) [\w]+) :', '\\1:'),
81 # delete space before comma
83 # delete space before semicolon
84 ('([^;]) +;', '\\1;'),
88 # delete backslash before empty line (emacs' indent region is broken)
94 # delete empty first lines
95 ('(/\*\n)\n*', '\\1'),
96 # delete empty last lines
97 ('\n*(\n\*/)', '\\1'),
98 ## delete newline after start?
100 ## delete newline before end?
105 # Recognize special sequences in the input.
107 # (?P<name>regex) -- Assign result of REGEX to NAME.
108 # *? -- Match non-greedily.
109 # (?m) -- Multiline regex: Make ^ and $ match at each line.
110 # (?s) -- Make the dot match all characters including newline.
111 # (?x) -- Ignore whitespace in patterns.
119 \#[ \t]*define[ \t]+([^\n]*\\\n)*[^\n]*))''',
125 [ \t]*/\*.*?\*/))''',
127 'singleline_comment':
129 ^.*? # leave leading spaces for the comment snippet
132 [ \t]*//[^\n]*\n))''',
136 " # leave the leading " character visible to CXX rules
151 \#[ \t]*include[ \t]*<[^>]*>))''',
156 def replacement_text (self):
159 def filter_text (self):
160 return self.replacement_text ()
162 class Substring (Chunk):
163 def __init__ (self, source, start, end):
168 def replacement_text (self):
169 s = self.source[self.start:self.end]
171 sys.stderr.write ('CXX Rules')
174 sys.stderr.write ('.')
175 #sys.stderr.write ('\n\n***********\n')
176 #sys.stderr.write (i[0])
177 #sys.stderr.write ('\n***********\n')
178 #sys.stderr.write ('\n=========>>\n')
179 #sys.stderr.write (s)
180 #sys.stderr.write ('\n<<=========\n')
181 s = re.sub (i[0], i[1], s)
183 sys.stderr.write ('done\n')
187 class Snippet (Chunk):
188 def __init__ (self, type, match, format):
195 def replacement_text (self):
196 return self.match.group ('match')
198 def substring (self, s):
199 return self.match.group (s)
202 return `self.__class__` + ' type = ' + self.type
204 class Multiline_comment (Snippet):
205 def __init__ (self, source, match, format):
212 def replacement_text (self):
213 s = self.match.group ('match')
215 sys.stderr.write ('COMMENT Rules')
216 for i in rules[COMMENT]:
218 sys.stderr.write ('.')
219 s = re.sub (i[0], i[1], s)
222 snippet_type_to_class = {
223 'multiline_comment': Multiline_comment,
224 # 'string': Multiline_comment,
225 # 'include': Include_snippet,
228 def find_toplevel_snippets (s, types):
230 sys.stderr.write ('Dissecting')
234 res[i] = re.compile (snippet_res[format][i])
238 ## found = dict (map (lambda x: (x, None),
242 map (lambda x, f = found: f.setdefault (x, None),
245 # We want to search for multiple regexes, without searching
246 # the string multiple times for one regex.
247 # Hence, we use earlier results to limit the string portion
249 # Since every part of the string is traversed at most once for
250 # every type of snippet, this is linear.
254 sys.stderr.write ('.')
258 if not found[type] or found[type][0] < index:
260 m = res[type].search (s[index:endex])
265 if snippet_type_to_class.has_key (type):
266 cl = snippet_type_to_class[type]
267 snip = cl (type, m, format)
268 start = index + m.start ('match')
269 found[type] = (start, snip)
273 or found[type][0] < found[first][0]):
278 # Limiting the search space is a cute
279 # idea, but this *requires* to search
280 # for possible containing blocks
281 # first, at least as long as we do not
282 # search for the start of blocks, but
283 # always/directly for the entire
284 # @block ... @end block.
286 endex = found[first][0]
289 snippets.append (Substring (s, index, len (s)))
292 (start, snip) = found[first]
293 snippets.append (Substring (s, index, start))
294 snippets.append (snip)
296 index = start + len (snip.match.group ('match'))
300 def nitpick_file (outdir, file):
301 s = open (file).read ()
304 for i in rules[GLOBAL_CXX]:
305 t = re.sub (i[0], i[1], t)
307 # FIXME: Containing blocks must be first, see
308 # find_toplevel_snippets.
309 # We leave simple strings be part of the code
313 'singleline_comment',
319 chunks = find_toplevel_snippets (t, snippet_types)
320 #code = filter (lambda x: is_derived_class (x.__class__, Substring),
323 t = string.join (map (lambda x: x.filter_text (), chunks), '')
327 os.system ('mv %s %s~' % (file, file))
329 fixt = os.path.join (outdir,
330 os.path.basename (file))
334 if s != t or indent_p:
337 def indent_file (file):
339 --options=none --quiet -n \
340 --style=gnu --indent=spaces=2 \
341 --max-instatement-indent=60 \
343 --align-pointer=name --pad-oper \
344 --keep-one-line-blocks \
348 sys.stderr.write (astyle)
349 sys.stderr.write ('\n')
354 sys.stdout.write (r'''
356 fixcc [OPTION]... FILE...
360 --lazy skip astyle, if no changes
364 Typical use with LilyPond:
366 fixcc $(find flower lily -name '*cc' -o -name '*hh' | grep -v /out)
371 global indent_p, outdir, verbose_p
372 (options, files) = getopt.getopt (sys.argv[1:], '',
373 ['help', 'lazy', 'outdir=',
375 for (o, a) in options:
381 elif o == '--outdir':
383 elif o == '--verbose':
398 socketdir = '/tmp/fixcc'
399 socketname = 'fixcc%d' % os.getpid ()
402 files = do_options ()
403 if outdir and not os.path.isdir (outdir):
406 sys.stderr.write ('%s...\n' % i)
407 nitpick_file (outdir, i)
410 ## TODO: make this compilable and check with g++
418 public: static char* foo ();
419 std::map<char*,int>* bar (char, char) { return 0; }
427 operator << (ostream & os, String d);
429 typedef struct _t_ligature
432 struct _t_ligature * next;
435 typedef std::map < AFM_Ligature const *, int > Bar;
438 Copyright (C) 1997--2011 Han-Wen Nienhuys <hanwen@cs.uu.nl>
456 a [*++ a] = (char*) foe (*i, &bar) *
458 int operator double ();
459 std::map<char*,int> y =*bar(-*a ,*b);
460 Interval_t<T> & operator*= (T r);
462 int compare (Pqueue_ent < K, T > const& e1, Pqueue_ent < K,T> *e2);
464 if (abs (f)*2 > abs (d) *FUDGE)
467 for (; i<x foo(); foo>bar);
477 1 && * unsmob_moment (lf);
478 line_spanner_ = make_spanner ("DynamicLineSpanner", rq ? rq->*self_scm
486 cookie_io_functions_t Memory_out_stream::functions_ = {
487 Memory_out_stream::reader,
491 int compare (Array < Pitch> *, Array < Pitch> *);
492 original_ = (Grob *) & s;
493 Drul_array< Link_array<Grob> > o;
496 header_.char_info_pos = (6 + header_length) * 4;
497 return ly_bool2scm (*ma < * mb);
509 span_ = make_spanner ("StaffSymbol", SCM_EOL);
515 span_ = make_spanner (StaffSymbol, SCM_EOL);
521 test_file = 'fixcc.cc'
522 open (test_file, 'w').write (TEST)
523 nitpick_file (outdir, test_file)
524 sys.stdout.write (open (test_file).read ())
526 if __name__ == '__main__':