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 (' (::|&&|\|\||<=|>=|!=|\|=|==|\+=|-=|\*=|/=|\?|<|\+|-|=|/|:|&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))''',
138 "([^"\n]|\\")*"))''',
150 \#[ \t]*include[ \t]*<[^>]*>))''',
155 def replacement_text (self):
158 def filter_text (self):
159 return self.replacement_text ()
161 class Substring (Chunk):
162 def __init__ (self, source, start, end):
167 def replacement_text (self):
168 s = self.source[self.start:self.end]
170 sys.stderr.write ('CXX Rules')
173 sys.stderr.write ('.')
174 #sys.stderr.write ('\n\n***********\n')
175 #sys.stderr.write (i[0])
176 #sys.stderr.write ('\n***********\n')
177 #sys.stderr.write ('\n=========>>\n')
178 #sys.stderr.write (s)
179 #sys.stderr.write ('\n<<=========\n')
180 s = re.sub (i[0], i[1], s)
182 sys.stderr.write ('done\n')
186 class Snippet (Chunk):
187 def __init__ (self, type, match, format):
194 def replacement_text (self):
195 return self.match.group ('match')
197 def substring (self, s):
198 return self.match.group (s)
201 return `self.__class__` + ' type = ' + self.type
203 class Multiline_comment (Snippet):
204 def __init__ (self, source, match, format):
211 def replacement_text (self):
212 s = self.match.group ('match')
214 sys.stderr.write ('COMMENT Rules')
215 for i in rules[COMMENT]:
217 sys.stderr.write ('.')
218 s = re.sub (i[0], i[1], s)
221 snippet_type_to_class = {
222 'multiline_comment': Multiline_comment,
223 # 'string': Multiline_comment,
224 # 'include': Include_snippet,
227 def find_toplevel_snippets (s, types):
229 sys.stderr.write ('Dissecting')
233 res[i] = re.compile (snippet_res[format][i])
237 ## found = dict (map (lambda x: (x, None),
241 map (lambda x, f = found: f.setdefault (x, None),
244 # We want to search for multiple regexes, without searching
245 # the string multiple times for one regex.
246 # Hence, we use earlier results to limit the string portion
248 # Since every part of the string is traversed at most once for
249 # every type of snippet, this is linear.
253 sys.stderr.write ('.')
257 if not found[type] or found[type][0] < index:
259 m = res[type].search (s[index:endex])
264 if snippet_type_to_class.has_key (type):
265 cl = snippet_type_to_class[type]
266 snip = cl (type, m, format)
267 start = index + m.start ('match')
268 found[type] = (start, snip)
272 or found[type][0] < found[first][0]):
277 # Limiting the search space is a cute
278 # idea, but this *requires* to search
279 # for possible containing blocks
280 # first, at least as long as we do not
281 # search for the start of blocks, but
282 # always/directly for the entire
283 # @block ... @end block.
285 endex = found[first][0]
288 snippets.append (Substring (s, index, len (s)))
291 (start, snip) = found[first]
292 snippets.append (Substring (s, index, start))
293 snippets.append (snip)
295 index = start + len (snip.match.group ('match'))
299 def nitpick_file (outdir, file):
300 s = open (file).read ()
303 for i in rules[GLOBAL_CXX]:
304 t = re.sub (i[0], i[1], t)
306 # FIXME: Containing blocks must be first, see
307 # find_toplevel_snippets.
308 # We leave simple strings be part of the code
312 'singleline_comment',
318 chunks = find_toplevel_snippets (t, snippet_types)
319 #code = filter (lambda x: is_derived_class (x.__class__, Substring),
322 t = string.join (map (lambda x: x.filter_text (), chunks), '')
326 os.system ('mv %s %s~' % (file, file))
328 fixt = os.path.join (outdir,
329 os.path.basename (file))
333 if s != t or indent_p:
336 def indent_file (file):
338 --options=none --quiet -n \
339 --style=gnu --indent=spaces=2 \
340 --max-instatement-indent=60 \
342 --align-pointer=name --pad-oper \
343 --keep-one-line-blocks \
347 sys.stderr.write (astyle)
348 sys.stderr.write ('\n')
353 sys.stdout.write (r'''
355 fixcc [OPTION]... FILE...
359 --lazy skip astyle, if no changes
363 Typical use with LilyPond:
365 fixcc $(find flower lily -name '*cc' -o -name '*hh' | grep -v /out)
370 global indent_p, outdir, verbose_p
371 (options, files) = getopt.getopt (sys.argv[1:], '',
372 ['help', 'lazy', 'outdir=',
374 for (o, a) in options:
380 elif o == '--outdir':
382 elif o == '--verbose':
397 socketdir = '/tmp/fixcc'
398 socketname = 'fixcc%d' % os.getpid ()
401 files = do_options ()
402 if outdir and not os.path.isdir (outdir):
405 sys.stderr.write ('%s...\n' % i)
406 nitpick_file (outdir, i)
409 ## TODO: make this compilable and check with g++
417 public: static char* foo ();
418 std::map<char*,int>* bar (char, char) { return 0; }
426 operator << (ostream & os, String d);
428 typedef struct _t_ligature
431 struct _t_ligature * next;
434 typedef std::map < AFM_Ligature const *, int > Bar;
437 Copyright (C) 1997--2011 Han-Wen Nienhuys <hanwen@cs.uu.nl>
455 a [*++ a] = (char*) foe (*i, &bar) *
457 int operator double ();
458 std::map<char*,int> y =*bar(-*a ,*b);
459 Interval_t<T> & operator*= (T r);
461 int compare (Pqueue_ent < K, T > const& e1, Pqueue_ent < K,T> *e2);
463 if (abs (f)*2 > abs (d) *FUDGE)
466 for (; i<x foo(); foo>bar);
476 1 && * unsmob_moment (lf);
477 line_spanner_ = make_spanner ("DynamicLineSpanner", rq ? rq->*self_scm
485 cookie_io_functions_t Memory_out_stream::functions_ = {
486 Memory_out_stream::reader,
490 int compare (Array < Pitch> *, Array < Pitch> *);
491 original_ = (Grob *) & s;
492 Drul_array< Link_array<Grob> > o;
495 header_.char_info_pos = (6 + header_length) * 4;
496 return ly_bool2scm (*ma < * mb);
508 span_ = make_spanner ("StaffSymbol", SCM_EOL);
514 span_ = make_spanner (StaffSymbol, SCM_EOL);
520 test_file = 'fixcc.cc'
521 open (test_file, 'w').write (TEST)
522 nitpick_file (outdir, test_file)
523 sys.stdout.write (open (test_file).read ())
525 if __name__ == '__main__':