Skip to content

Commit 01f5cb5

Browse files
committed
making some lines a bit more compact
1 parent 8ea3438 commit 01f5cb5

File tree

9 files changed

+81
-68
lines changed

9 files changed

+81
-68
lines changed

NanoBASIC/__main__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,6 @@
1919
if __name__ == "__main__":
2020
# Parse the file argument
2121
file_parser = ArgumentParser("NanoBASIC")
22-
file_parser.add_argument("basic_file", help="A text file containing NanoBASIC source code.")
22+
file_parser.add_argument("basic_file", help="A text file containing NanoBASIC code.")
2323
arguments = file_parser.parse_args()
2424
execute(arguments.basic_file)

NanoBASIC/interpreter.py

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -74,17 +74,17 @@ def interpret(self, statement: Statement):
7474
if (line_index := self.find_line_index(go_to_line_id)) is not None:
7575
self.statement_index = line_index
7676
else:
77-
raise Interpreter.InterpreterError("Couldn't find GOTO line id.", self.current)
77+
raise Interpreter.InterpreterError("No GOTO line id.", self.current)
7878
case GoSubStatement(line_expr=line_expr):
7979
go_sub_line_id = self.evaluate_numeric(line_expr)
8080
if (line_index := self.find_line_index(go_sub_line_id)) is not None:
8181
self.subroutine_stack.append(self.statement_index + 1) # Setup for RETURN
8282
self.statement_index = line_index
8383
else:
84-
raise Interpreter.InterpreterError("Couldn't find GOSUB line id.", self.current)
84+
raise Interpreter.InterpreterError("No GOSUB line id.", self.current)
8585
case ReturnStatement():
8686
if not self.subroutine_stack: # Check if the stack is empty
87-
raise Interpreter.InterpreterError("Return with no prior corresponding GOSUB.", self.current)
87+
raise Interpreter.InterpreterError("RETURN without GOSUB.", self.current)
8888
self.statement_index = self.subroutine_stack.pop()
8989
case PrintStatement(printables=printables):
9090
accumulated_string: str = ""
@@ -93,7 +93,7 @@ def interpret(self, statement: Statement):
9393
accumulated_string += "\t"
9494
if isinstance(printable, NumericExpression):
9595
accumulated_string += str(self.evaluate_numeric(printable))
96-
else: # Otherwise, it's a string, because that's the only other thing we allow
96+
else: # Otherwise, it's a string
9797
accumulated_string += str(printable)
9898
print(accumulated_string)
9999
self.statement_index += 1
@@ -103,7 +103,8 @@ def interpret(self, statement: Statement):
103103
else:
104104
self.statement_index += 1
105105
case _:
106-
raise Interpreter.InterpreterError(f"Unexpected item {self.current} in statement list.", self.current)
106+
raise Interpreter.InterpreterError(f"Unexpected item {self.current} "
107+
f"in statement list.", self.current)
107108

108109
def evaluate_numeric(self, numeric_expression: NumericExpression) -> int:
109110
match numeric_expression:
@@ -113,12 +114,14 @@ def evaluate_numeric(self, numeric_expression: NumericExpression) -> int:
113114
if name in self.variable_table:
114115
return self.variable_table[name]
115116
else:
116-
raise Interpreter.InterpreterError(f"Var {name} used before initialized.", numeric_expression)
117+
raise Interpreter.InterpreterError(f"Var {name} used "
118+
f"before initialized.", numeric_expression)
117119
case UnaryOperation(operator=operator, expr=expr):
118120
if operator is TokenType.MINUS:
119121
return -self.evaluate_numeric(expr)
120122
else:
121-
raise Interpreter.InterpreterError(f"Expected - but got {operator}.", numeric_expression)
123+
raise Interpreter.InterpreterError(f"Expected - "
124+
f"but got {operator}.", numeric_expression)
122125
case BinaryOperation(operator=operator, left_expr=left, right_expr=right):
123126
if operator is TokenType.PLUS:
124127
return self.evaluate_numeric(left) + self.evaluate_numeric(right)
@@ -129,9 +132,11 @@ def evaluate_numeric(self, numeric_expression: NumericExpression) -> int:
129132
elif operator is TokenType.DIVIDE:
130133
return self.evaluate_numeric(left) // self.evaluate_numeric(right)
131134
else:
132-
raise Interpreter.InterpreterError(f"Unexpected binary operator {operator}.", numeric_expression)
135+
raise Interpreter.InterpreterError(f"Unexpected binary operator "
136+
f"{operator}.", numeric_expression)
133137
case _:
134-
raise Interpreter.InterpreterError("Expected numeric expression.", numeric_expression)
138+
raise Interpreter.InterpreterError("Expected numeric expression.",
139+
numeric_expression)
135140

136141
def evaluate_boolean(self, boolean_expression: BooleanExpression) -> bool:
137142
left = self.evaluate_numeric(boolean_expression.left_expr)
@@ -150,5 +155,5 @@ def evaluate_boolean(self, boolean_expression: BooleanExpression) -> bool:
150155
case TokenType.NOT_EQUAL:
151156
return left != right
152157
case _:
153-
raise Interpreter.InterpreterError(f"Unexpected boolean operator {boolean_expression.operator}.",
154-
boolean_expression)
158+
raise Interpreter.InterpreterError(f"Unexpected boolean operator "
159+
f"{boolean_expression.operator}.", boolean_expression)

NanoBASIC/parser.py

Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def out_of_tokens(self) -> bool:
5252
@property
5353
def current(self) -> Token:
5454
if self.out_of_tokens:
55-
raise (Parser.ParserError(f"Ran out of tokens after {self.previous.kind}.", self.previous))
55+
raise (Parser.ParserError(f"No tokens after {self.previous.kind}.", self.previous))
5656
return self.tokens[self.token_index]
5757

5858
@property
@@ -107,8 +107,10 @@ def parse_print(self, line_id: int) -> PrintStatement:
107107
printables.append(expression)
108108
last_col = expression.col_end
109109
else:
110-
raise Parser.ParserError("Only strings and numeric expressions allowed in print list.", self.current)
111-
if not self.out_of_tokens and self.current.kind is TokenType.COMMA: # Comma means there's more
110+
raise Parser.ParserError("Only strings and numeric expressions "
111+
"allowed in print list.", self.current)
112+
# Comma means there's more to print
113+
if not self.out_of_tokens and self.current.kind is TokenType.COMMA:
112114
self.consume(TokenType.COMMA)
113115
continue
114116
break
@@ -168,8 +170,8 @@ def parse_boolean_expression(self) -> BooleanExpression:
168170
return BooleanExpression(line_num=left.line_num,
169171
col_start=left.col_start, col_end=right.col_end,
170172
operator=operator.kind, left_expr=left, right_expr=right)
171-
raise Parser.ParserError(f"Expected boolean operator inside boolean expression but found {self.current.kind}.",
172-
self.current)
173+
raise Parser.ParserError(f"Expected boolean operator but found "
174+
f"{self.current.kind}.", self.current)
173175

174176
def parse_numeric_expression(self) -> NumericExpression:
175177
left = self.parse_term()
@@ -180,15 +182,15 @@ def parse_numeric_expression(self) -> NumericExpression:
180182
if self.current.kind is TokenType.PLUS:
181183
self.consume(TokenType.PLUS)
182184
right = self.parse_term()
183-
left = BinaryOperation(line_num=left.line_num,
184-
col_start=left.col_start, col_end=right.col_end,
185-
operator=TokenType.PLUS, left_expr=left, right_expr=right)
185+
left = BinaryOperation(line_num=left.line_num, col_start=left.col_start,
186+
col_end=right.col_end, operator=TokenType.PLUS,
187+
left_expr=left, right_expr=right)
186188
elif self.current.kind is TokenType.MINUS:
187189
self.consume(TokenType.MINUS)
188190
right = self.parse_term()
189-
left = BinaryOperation(line_num=left.line_num,
190-
col_start=left.col_start, col_end=right.col_end,
191-
operator=TokenType.MINUS, left_expr=left, right_expr=right)
191+
left = BinaryOperation(line_num=left.line_num, col_start=left.col_start,
192+
col_end=right.col_end, operator=TokenType.MINUS,
193+
left_expr=left, right_expr=right)
192194
else:
193195
break # No more, must be end of expression
194196
return left
@@ -202,15 +204,15 @@ def parse_term(self) -> NumericExpression:
202204
if self.current.kind is TokenType.MULTIPLY:
203205
self.consume(TokenType.MULTIPLY)
204206
right = self.parse_factor()
205-
left = BinaryOperation(line_num=left.line_num,
206-
col_start=left.col_start, col_end=right.col_end,
207-
operator=TokenType.MULTIPLY, left_expr=left, right_expr=right)
207+
left = BinaryOperation(line_num=left.line_num, col_start=left.col_start,
208+
col_end=right.col_end, operator=TokenType.MULTIPLY,
209+
left_expr=left, right_expr=right)
208210
elif self.current.kind is TokenType.DIVIDE:
209211
self.consume(TokenType.DIVIDE)
210212
right = self.parse_factor()
211-
left = BinaryOperation(line_num=left.line_num,
212-
col_start=left.col_start, col_end=right.col_end,
213-
operator=TokenType.DIVIDE, left_expr=left, right_expr=right)
213+
left = BinaryOperation(line_num=left.line_num, col_start=left.col_start,
214+
col_end=right.col_end, operator=TokenType.DIVIDE,
215+
left_expr=left, right_expr=right)
214216
else:
215217
break # No more, must be end of expression
216218
return left
@@ -230,7 +232,7 @@ def parse_factor(self) -> NumericExpression:
230232
self.consume(TokenType.OPEN_PAREN)
231233
expression = self.parse_numeric_expression()
232234
if self.current.kind is not TokenType.CLOSE_PAREN:
233-
raise Parser.ParserError("Expected matching closing parenthesis.", self.current)
235+
raise Parser.ParserError("Expected matching close parenthesis.", self.current)
234236
self.consume(TokenType.CLOSE_PAREN)
235237
return expression
236238
elif self.current.kind is TokenType.MINUS:
@@ -239,4 +241,4 @@ def parse_factor(self) -> NumericExpression:
239241
return UnaryOperation(line_num=minus.line_num,
240242
col_start=minus.col_start, col_end=expression.col_end,
241243
operator=TokenType.MINUS, expr=expression)
242-
raise Parser.ParserError("Couldn't parse numeric expression, unexpected token.", self.current)
244+
raise Parser.ParserError("Unexpected token in numeric expression.", self.current)

NanoBASIC/tokenizer.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,8 @@ def tokenize(text_file: TextIO) -> list[Token]:
8484
if found:
8585
col_end: int = col_start + found.end() - 1
8686
# Store tokens other than comments and whitespace
87-
if possibility is not TokenType.WHITESPACE and possibility is not TokenType.COMMENT:
87+
if (possibility is not TokenType.WHITESPACE
88+
and possibility is not TokenType.COMMENT):
8889
associated_value: str | int | None = None
8990
if possibility.has_associated_value:
9091
if possibility is TokenType.NUMBER:
@@ -93,7 +94,8 @@ def tokenize(text_file: TextIO) -> list[Token]:
9394
associated_value = found.group()
9495
elif possibility is TokenType.STRING: # Remove quote characters
9596
associated_value = found.group(0)[1:-1]
96-
tokens.append(Token(possibility, line_num, col_start, col_end, associated_value))
97+
tokens.append(Token(possibility, line_num, col_start, col_end,
98+
associated_value))
9799
# Continue search from place in line after token
98100
line = line[found.end():]
99101
col_start = col_end + 1

RetroDither/macpaint.py

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525

2626
# Convert an array of bytes where each byte is 0 or 255
2727
# to an array of bits where each byte that is 0 becomes a 1
28-
# and each bit that is 255 becomes a 0
28+
# and each byte that is 255 becomes a 0
2929
def bytes_to_bits(original: array) -> array:
3030
bits_array = array('B')
3131

@@ -65,7 +65,8 @@ def run_length_encode(original_data: array) -> array:
6565
# Find how many of the same bytes are in a row from *start*
6666
def take_same(source: array, start: int) -> int:
6767
count = 0
68-
while start + count + 1 < len(source) and source[start + count] == source[start + count + 1]:
68+
while (start + count + 1 < len(source)
69+
and source[start + count] == source[start + count + 1]):
6970
count += 1
7071
return count + 1 if count > 0 else 0
7172

@@ -76,7 +77,8 @@ def take_same(source: array, start: int) -> int:
7677
index = 0
7778
while index < len(data):
7879
not_same = 0
79-
while ((same := take_same(data, index + not_same)) == 0) and (index + not_same < len(data)):
80+
while (((same := take_same(data, index + not_same)) == 0)
81+
and (index + not_same < len(data))):
8082
not_same += 1
8183
if not_same > 0:
8284
rle_data.append(not_same - 1)
@@ -92,13 +94,13 @@ def take_same(source: array, start: int) -> int:
9294
def macbinary_header(outfile: str, data_size: int) -> array:
9395
macbinary = array('B', [0] * MACBINARY_LENGTH)
9496
filename = Path(outfile).stem
95-
filename = filename[:63] if len(filename) > 63 else filename # limit to 63 characters maximum
97+
filename = filename[:63] if len(filename) > 63 else filename # limit to 63 characters max
9698
macbinary[1] = len(filename) # file name length
9799
macbinary[2:(2 + len(filename))] = array("B", filename.encode("mac_roman")) # file name
98100
macbinary[65:69] = array("B", "PNTG".encode("mac_roman")) # file type
99101
macbinary[69:73] = array("B", "MPNT".encode("mac_roman")) # file creator
100102
macbinary[83:87] = array("B", data_size.to_bytes(4, byteorder='big')) # size of data fork
101-
timestamp = int((datetime.now() - datetime(1904, 1, 1)).total_seconds()) # Mac timestamps are seconds since 1904
103+
timestamp = int((datetime.now() - datetime(1904, 1, 1)).total_seconds()) # Mac timestamp
102104
macbinary[91:95] = array("B", timestamp.to_bytes(4, byteorder='big')) # creation stamp
103105
macbinary[95:99] = array("B", timestamp.to_bytes(4, byteorder='big')) # modification stamp
104106
return macbinary
@@ -109,15 +111,15 @@ def write_macpaint_file(data: array, out_file: str, width: int, height: int):
109111
bits_array = prepare(data, width, height)
110112
rle = run_length_encode(bits_array)
111113
data_size = len(rle) + HEADER_LENGTH # header requires this
112-
output_array = macbinary_header(out_file, data_size) + array('B', [0] * HEADER_LENGTH) + rle
113-
output_array[MACBINARY_LENGTH + 3] = 2 # Data Fork Header Signature
114+
output = macbinary_header(out_file, data_size) + array('B', [0] * HEADER_LENGTH) + rle
115+
output[MACBINARY_LENGTH + 3] = 2 # Data Fork Header Signature
114116
# macbinary format requires that there be padding of 0s up to a
115117
# multiple of 128 bytes for the data fork
116118
padding = 128 - (data_size % 128)
117119
if padding > 0:
118-
output_array += array('B', [0] * padding)
120+
output += array('B', [0] * padding)
119121
with open(out_file + ".bin", "wb") as fp:
120-
output_array.tofile(fp)
122+
output.tofile(fp)
121123

122124
# Alternative version of run_length_encode that doesn't use the helper function
123125
# # https://en.wikipedia.org/wiki/PackBits

StainedGlass/__main__.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,24 +19,25 @@
1919
if __name__ == "__main__":
2020
# Parse the file argument
2121
argument_parser = ArgumentParser("StainedGlass")
22-
argument_parser.add_argument("image_file", help="An image file to paint a stained glass equivalent of.")
22+
argument_parser.add_argument("image_file", help="The input image to be painted.")
2323
argument_parser.add_argument("output_file", help="The final resulting abstract art image.")
2424
argument_parser.add_argument('-t', '--trials', type=int, default=10000,
2525
help='The number of trials to run (default 10000).')
26-
argument_parser.add_argument('-m', '--method', choices=['random', 'average', 'common'], default='average',
27-
help='The method for determining shape colors (default average).')
28-
argument_parser.add_argument('-s', '--shape', choices=['ellipse', 'triangle', 'quadrilateral', 'line'],
29-
default='ellipse',
26+
argument_parser.add_argument('-m', '--method', choices=['random', 'average', 'common'],
27+
default='average',
28+
help='Shape color determination method (default average).')
29+
argument_parser.add_argument('-s', '--shape', choices=['ellipse', 'triangle',
30+
'quadrilateral', 'line'], default='ellipse',
3031
help='The shape type to use (default ellipse).')
3132
argument_parser.add_argument('-l', '--length', type=int, default=256,
32-
help='The length (height) of the final image in pixels (default 256).')
33+
help='The length of the final image in pixels (default 256).')
3334
argument_parser.add_argument('-v', '--vector', default=False, action='store_true',
3435
help='Create vector output. A SVG file will also be output.')
3536
argument_parser.add_argument('-a', '--animate', type=int, default=0,
36-
help='If a number greater than 0 is provided, will create an animated '
37-
'GIF with the number of milliseconds per frame provided.')
37+
help='If greater than 0, will create an animated GIF '
38+
'with the number of milliseconds per frame provided.')
3839
arguments = argument_parser.parse_args()
3940
method = ColorMethod[arguments.method.upper()]
4041
shape_type = ShapeType[arguments.shape.upper()]
41-
StainedGlass(arguments.image_file, arguments.output_file, arguments.trials, method, shape_type, arguments.length,
42-
arguments.vector, arguments.animate)
42+
StainedGlass(arguments.image_file, arguments.output_file, arguments.trials, method,
43+
shape_type, arguments.length, arguments.vector, arguments.animate)

0 commit comments

Comments
 (0)