Replace comfy.parse-based comment parsers with re.sub.

Less code is better, right?
But we lost the ability to report errors for unterminated C block comments.
Current differences from the js version:
We consume unterminated C block comments.
This commit is contained in:
Barry Downes 2023-08-06 09:24:09 +10:00
parent 9efdda21a8
commit ed253b31df

View File

@ -1,67 +1,12 @@
import comfy.parse as parse import re
from comfy.parse import ParseError, ParseLogicError
def strip_c_comments(text, strict=True): def strip_c_comments(text, strict=True):
''' # Processes the text and strips out any C-style block "/* ... */" or line "// ..." comments found.
Processes the text and strips out any C-style block "/* ... */" or line "// ..." comments found. # from old dynamicPrompts.js: return str.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g,'');
''' return re.sub(r'/\*[.\n]*?(?:\*/|$)|//.*', '', text)
out = []
input = parse.Cursor(text)
while True:
if 0: pass
elif input.match(r'\/'):
# C-style block "/* */" or line "//" comment
comment = input.prior()
if 0: pass
elif m := input.match(r'\/'):
# // line comment
if not input.match(r'.*?(?:\n|$)'):
if strict:
raise ParseLogicError(comment, f"Failed to find end of C-style // line comment")
input.match(r'.*') # consume unterminated comment (however that might be possible)
out.append('\n')
elif m := input.match(r'\*'):
# /* ... */ block comment
if not input.match(r'.*?\*\/'):
if strict:
raise ParseError(comment, f"Unterminated C-style /* ... */ block comment")
input.match(r'.*') # consume unterminated comment
out.append(' ')
else:
# it was a literal /, not a comment after all
out.append('/');
elif m := input.match(r'[^/]+'):
out.append(m.group(0))
elif input.match(r'$'):
break;
else:
raise ParseLogicError(input, f"Failed to match")
return ''.join(out)
def strip_hash_comments(text, strict=True): def strip_hash_comments(text, strict=True):
''' # Processes the text and strips out any hash "# ... " comments found.
Processes the text and strips out any hash "# ... " comments found. return re.sub(r'#.*', '', text)
'''
out = []
input = parse.Cursor(text)
while True:
if 0: pass
elif input.match(r'\#'):
comment = input.prior()
# scripting-language-style "# ...\n" comment
if not input.match(r'.*?(?:\n|$)'):
if strict:
raise ParseLogicError(comment, f"Failed to find end of script-style # ... comment")
input.match(r'.*') # consume unterminated comment (however that might be possible)
out.append('\n')
elif m := input.match(r'[^#]+'):
out.append(m.group(0))
elif input.match(r'$'):
break;
else:
raise ParseLogicError(input, f"Failed to match")
return ''.join(out)