88import sys
99
1010def minify_cpp (code ):
11- # Remove comments while preserving strings
11+ # Remove comments while preserving strings and macro continuations
1212 lines = code .split ('\n ' )
1313 cleaned_lines = []
1414
@@ -52,6 +52,21 @@ def minify_cpp(code):
5252 # Remove multi-line comments (but preserve #line directives content)
5353 code = re .sub (r'/\*.*?\*/' , '' , code , flags = re .DOTALL )
5454
55+ # Handle multi-line macros: join lines that end with backslash
56+ lines = code .split ('\n ' )
57+ merged_lines = []
58+ i = 0
59+ while i < len (lines ):
60+ line = lines [i ].rstrip ()
61+ # Check if line ends with backslash (macro continuation)
62+ while line .endswith ('\\ ' ) and i + 1 < len (lines ):
63+ line = line [:- 1 ] + ' ' + lines [i + 1 ].lstrip ()
64+ i += 1
65+ merged_lines .append (line )
66+ i += 1
67+
68+ code = '\n ' .join (merged_lines )
69+
5570 # Remove empty lines
5671 code = re .sub (r'\n\s*\n' , '\n ' , code )
5772
@@ -125,7 +140,7 @@ def compress_line(line):
125140 lines = [compress_line (line ) for line in code .split ('\n ' )]
126141
127142 # Join lines intelligently: keep preprocessor directives on their own lines,
128- # and keep a newline after them
143+ # and ensure a newline after them
129144 result_lines = []
130145 for i , line in enumerate (lines ):
131146 if not line :
@@ -138,7 +153,15 @@ def compress_line(line):
138153 # Regular code - try to join with previous line if possible
139154 if result_lines and not result_lines [- 1 ].startswith ('#' ):
140155 # Previous line is not a preprocessor directive, can join
141- result_lines [- 1 ] += line
156+ # But check if previous line looks like a macro invocation (single identifier)
157+ prev_line = result_lines [- 1 ]
158+ # If previous line is a simple identifier, keep it separate (could be macro use)
159+ if prev_line and not any (c in prev_line for c in '();,=[]{}<>+-*/%&|^~' ):
160+ # Previous line might be a macro invocation, keep separate
161+ result_lines .append (line )
162+ else :
163+ # Safe to join
164+ result_lines [- 1 ] += line
142165 else :
143166 # Previous line is a preprocessor directive or this is first line
144167 result_lines .append (line )
0 commit comments