break up the for loop in textpre.py into separate functions

This commit is contained in:
Bryan Bishop 2012-04-26 11:19:34 -05:00
parent 6e083c9b3a
commit 2446153f98
1 changed files with 51 additions and 39 deletions

View File

@ -265,43 +265,38 @@ chars = {
"9": 0xFF "9": 0xFF
} }
for l in sys.stdin: def separate_comment(l):
# skip lines with no quotes """ Separates asm and comments on a single line.
if "\"" not in l: """
sys.stdout.write(l)
continue
asm = "" asm = ""
# strip comments
comment = None comment = None
if ";" in l:
in_quotes = False in_quotes = False
in_comment = False in_comment = False
for letter in l:
# token either belongs to the line or to the comment
for token in l:
if in_comment: if in_comment:
comment += letter comment += token
elif in_quotes and letter != "\"": elif in_quotes and token != "\"":
asm += letter asm += token
elif in_quotes and letter == "\"": elif in_quotes and token == "\"":
in_quotes = False in_quotes = False
asm += letter asm += token
elif not in_quotes and letter == "\"": elif not in_quotes and token == "\"":
in_quotes = True in_quotes = True
asm += letter asm += token
elif not in_quotes and letter != "\"": elif not in_quotes and token != "\"":
if letter == ";": if token == ";":
in_comment = True in_comment = True
comment = ";" comment = ";"
else: else:
asm += letter asm += token
else: return asm, comment
asm = l
# skip asm with no quotes def quote_translator(asm):
if "\"" not in asm: """ Writes asm with quoted text translated into bytes.
sys.stdout.write(l) """
continue
# split by quotes # split by quotes
asms = asm.split("\"") asms = asm.split("\"")
@ -311,16 +306,16 @@ for l in sys.stdin:
if "section" in lowasm \ if "section" in lowasm \
or "include" in lowasm \ or "include" in lowasm \
or "incbin" in lowasm: or "incbin" in lowasm:
sys.stdout.write(l) sys.stdout.write(asm)
continue return
even = False even = False
i = 0 i = 0
for token in asms: for token in asms:
i = i + 1 i = i + 1
if even: if even:
# token is a string to convert to byte values # token is a string to convert to byte values
while len(token): while len(token):
# read a single UTF-8 codepoint # read a single UTF-8 codepoint
char = token[0] char = token[0]
@ -358,10 +353,27 @@ for l in sys.stdin:
if len(token): if len(token):
sys.stdout.write(", ") sys.stdout.write(", ")
# if not even
else: else:
sys.stdout.write(token) sys.stdout.write(token)
even = not even
even = not even
return
for l in sys.stdin:
# strip and store any comment on this line
if ";" in l:
asm, comment = separate_comment(l)
else:
asm = l
comment = None
# convert text to bytes when a quote appears (not in a comment)
if "\"" in asm:
quote_translator(asm)
else:
sys.stdout.write(asm)
# show line comment
if comment != None: if comment != None:
sys.stdout.write(comment) sys.stdout.write(comment)