mirror of https://gitee.com/openkylin/genmai.git
46 lines
1.5 KiB
Python
Executable File
46 lines
1.5 KiB
Python
Executable File
import re
|
|
|
|
class CodeStrip:
|
|
@classmethod
|
|
def c_remove_if0_blocks(cls,code):
|
|
stack = []
|
|
lines = code.split('\n')
|
|
result = []
|
|
in_if0_block = False
|
|
for line in lines:
|
|
stripped_line = line.strip()
|
|
if stripped_line.startswith('#if 0'):
|
|
stack.append(stripped_line)
|
|
continue
|
|
if stripped_line.endswith('#endif'):
|
|
if stack:
|
|
stack.pop()
|
|
else:
|
|
result.append(line)
|
|
continue
|
|
if not stack:
|
|
result.append(line)
|
|
return '\n'.join(result)
|
|
|
|
@classmethod
|
|
def c_remove_comments_and_spaces(cls, code):
|
|
pattern_single_comment = r'//.*'
|
|
pattern_multi_comment = r'/\*[\s\S]*?\*/'
|
|
code = re.sub(pattern_single_comment, '', code, flags=re.MULTILINE)
|
|
code = re.sub(pattern_multi_comment, '', code, flags=re.DOTALL)
|
|
code = re.sub(r'\n\s*\n', '\n', code)
|
|
return code.strip()
|
|
@classmethod
|
|
def code_strip(cls,code,type):
|
|
if type == "c" or type == "cpp":
|
|
code=cls.c_remove_comments_and_spaces(code)
|
|
code=cls.c_remove_if0_blocks(code)
|
|
return code
|
|
else:
|
|
return ""
|
|
|
|
#with open('source.c', 'r') as file:
|
|
# code = file.read()
|
|
#processed_code = CodeStrip.code_strip(code,"c")
|
|
#with open('source_processed.c', 'w') as file:
|
|
# file.write(processed_code) |