Skip to content

Commit 78a9e4c

Browse files
authored
Merge pull request #662 from boriel/refact/refact_code
Refact/refact code
2 parents 0674535 + 4379073 commit 78a9e4c

8 files changed

Lines changed: 67 additions & 59 deletions

File tree

src/api/global_.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,17 @@
88
# This program is Free Software and is released under the terms of
99
# the GNU General License
1010
# ----------------------------------------------------------------------
11-
from typing import Dict, Final, List, NamedTuple, Optional, Set
11+
from __future__ import annotations
12+
13+
from typing import TYPE_CHECKING, Dict, Final, List, NamedTuple, Optional, Set
1214

1315
from src.api.constants import TYPE, LoopType
1416
from src.api.opcodestemps import OpcodesTemps
1517

18+
if TYPE_CHECKING:
19+
from src.symbols.id_ import SymbolID
20+
21+
1622
# ----------------------------------------------------------------------
1723
# Simple global container for internal constants.
1824
# Internal constants might be architecture dependant. They're set
@@ -86,7 +92,7 @@ class LoopInfo(NamedTuple):
8692
# Function calls pending to check
8793
# Each scope pushes (prepends) an empty list
8894
# ----------------------------------------------------------------------
89-
FUNCTION_CALLS = []
95+
FUNCTION_CALLS: list[SymbolID] = []
9096

9197
# ----------------------------------------------------------------------
9298
# Function level entry ID in which scope we are in. If the list
@@ -102,7 +108,7 @@ class LoopInfo(NamedTuple):
102108
# ----------------------------------------------------------------------
103109
# FUNCTIONS pending to translate after parsing stage
104110
# ----------------------------------------------------------------------
105-
FUNCTIONS = []
111+
FUNCTIONS: list[SymbolID] = []
106112

107113
# ----------------------------------------------------------------------
108114
# Parameter alignment. Must be set by arch.<arch>.__init__
@@ -112,7 +118,7 @@ class LoopInfo(NamedTuple):
112118
# ----------------------------------------------------------------------
113119
# Data type used for array boundaries. Must be an integral
114120
# ----------------------------------------------------------------------
115-
BOUND_TYPE = None # Set to None, so if not set will raise error
121+
BOUND_TYPE: TYPE # Unset, so if not set will raise error
116122

117123
# ----------------------------------------------------------------------
118124
# Data type used for elements size. Must be an integral type
@@ -155,7 +161,7 @@ class LoopInfo(NamedTuple):
155161
# ----------------------------------------------------------------------
156162
# Type used internally for pointer and memory addresses
157163
# ----------------------------------------------------------------------
158-
PTR_TYPE = None
164+
PTR_TYPE: TYPE # Unset, so if not set will raise error
159165

160166
# ----------------------------------------------------------------------
161167
# Character used for name mangling. Usually '_' or '.'

src/api/symboltable/symboltable.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,11 @@
2424
warning_implicit_type,
2525
warning_not_used,
2626
)
27-
from src.api.symboltable.scope import Scope
2827
from src.symbols import sym as symbols
2928
from src.symbols.symbol_ import Symbol
3029

30+
from .scope import Scope
31+
3132

3233
class SymbolTable:
3334
"""Implements a symbol table.

src/arch/__init__.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,22 @@
1-
#!/usr/bin/env python3
21
# -*- coding: utf-8 -*-
3-
# vim:ts=4:et:sw=4:
2+
3+
# ----------------------------------------------------------------------
4+
# Copyleft (K), Jose M. Rodriguez-Rosa (a.k.a. Boriel)
5+
#
6+
# This program is Free Software and is released under the terms of
7+
# the GNUv3 General License
8+
# ----------------------------------------------------------------------
49

510
import importlib
11+
from types import ModuleType
612

713
__all__ = (
814
"zx48k",
915
"zxnext",
1016
)
1117

1218
AVAILABLE_ARCHITECTURES = __all__
13-
target = None
19+
target: ModuleType
1420

1521

1622
def set_target_arch(target_arch: str):

src/arch/z80/optimizer/common.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,4 @@
1717
JUMP_LABELS: Final[set[str]] = set()
1818
MEMORY: Final[list[MemCell]] = [] # Instructions emitted by the backend
1919

20-
# PROC labels name space counter
21-
PROC_COUNTER = 0
22-
2320
BLOCKS: Final[list[BasicBlock]] = [] # Memory blocks

src/arch/z80/optimizer/main.py

Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from collections import defaultdict
2+
13
from src.api.config import OPTIONS
24
from src.api.debug import __DEBUG__
35
from src.api.utils import flatten_list
@@ -8,10 +10,14 @@
810
from .common import JUMP_LABELS, LABELS, MEMORY
911
from .helpers import ALL_REGS, END_PROGRAM_LABEL
1012
from .labelinfo import LabelInfo
13+
from .memcell import MemCell
1114
from .patterns import RE_LABEL, RE_PRAGMA
1215

1316
__all__ = "init", "optimize"
1417

18+
# PROC labels name space counter
19+
PROC_COUNTER: int = 0
20+
1521

1622
def init():
1723
LABELS.clear()
@@ -68,19 +74,19 @@ def cleanup_local_labels(block: BasicBlock) -> None:
6874
"""
6975
global PROC_COUNTER
7076

71-
stack = [[]]
72-
hashes = [{}]
73-
stackprc = [PROC_COUNTER]
74-
used = [{}] # List of hashes of unresolved labels per scope
77+
stack: list[list[str]] = [[]]
78+
hashes: list[dict[str, str]] = [{}]
79+
stackprc: list[int] = [PROC_COUNTER]
80+
used: list[dict[str, list[MemCell]]] = [defaultdict(list)] # List of hashes of unresolved labels per scope
7581

7682
MEMORY[:] = block.mem[:]
7783

7884
for cell in MEMORY:
7985
if cell.inst.upper() == "PROC":
80-
stack += [[]]
81-
hashes += [{}]
82-
stackprc += [PROC_COUNTER]
83-
used += [{}]
86+
stack.append([])
87+
hashes.append({})
88+
stackprc.append(PROC_COUNTER)
89+
used.append(defaultdict(list))
8490
PROC_COUNTER += 1
8591
continue
8692

@@ -99,26 +105,25 @@ def cleanup_local_labels(block: BasicBlock) -> None:
99105
continue
100106

101107
tmp = cell.asm.asm
102-
if tmp.upper()[:5] == "LOCAL":
108+
if tmp.upper().startswith("LOCAL"):
103109
tmp = tmp[5:].split(",")
104110
for lbl in tmp:
105111
lbl = lbl.strip()
106112
if lbl in stack[-1]:
107113
continue
108-
stack[-1] += [lbl]
109-
hashes[-1][lbl] = "PROC%i." % stackprc[-1] + lbl
110-
if used[-1].get(lbl, None) is None:
111-
used[-1][lbl] = []
112114

113-
cell.asm = ";" + cell.asm # Remove it
115+
stack[-1].append(lbl)
116+
hashes[-1][lbl] = f"PROC{stackprc[-1]}.{lbl}"
117+
118+
cell.asm = f";{str(cell.asm)}" # Remove it
114119
continue
115120

116121
if cell.is_label:
117122
label = cell.inst
118123
for i in range(len(stack) - 1, -1, -1):
119124
if label in stack[i]:
120125
label = hashes[i][label]
121-
cell.asm = label + ":"
126+
cell.asm = f"{label}:"
122127
break
123128
continue
124129

@@ -132,10 +137,7 @@ def cleanup_local_labels(block: BasicBlock) -> None:
132137
break
133138

134139
if not labelUsed:
135-
if used[-1].get(label, None) is None:
136-
used[-1][label] = []
137-
138-
used[-1][label] += [cell]
140+
used[-1][label].append(cell)
139141

140142
for i in range(len(MEMORY) - 1, -1, -1):
141143
if MEMORY[i].asm.asm[0] == ";":

src/ast/tree.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@
22
# -*- coding: utf-8 -*-
33

44
import collections.abc
5-
from typing import Iterable, List, Optional, Union
5+
from typing import Iterable, Optional, Union
66

77
from src.api.exception import Error
88

9-
__all__ = ["NotAnAstError", "Tree", "ChildrenList"]
9+
__all__ = "NotAnAstError", "Tree", "ChildrenList"
1010

1111

1212
class NotAnAstError(Error):
@@ -81,7 +81,7 @@ class ChildrenList:
8181
def __init__(self, node: Tree):
8282
assert isinstance(node, Tree)
8383
self.owner = node # Node having this children
84-
self._children: List[Tree] = []
84+
self._children: list[Tree | None] = []
8585

8686
def __getitem__(self, key: Union[int, slice]):
8787
if isinstance(key, int):

src/zxbc/args_config.py

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,18 @@
11
#!/usr/bin/env python3
2-
2+
from __future__ import annotations
33
import os
4-
from typing import List
4+
from typing import TYPE_CHECKING
55

66
import src.api.config
77
import src.api.global_ as gl
88
from src import arch
99
from src.api import debug, errmsg
1010
from src.api.config import OPTIONS
1111
from src.api.utils import open_file
12-
from src.zxbc import args_parser, zxbparser
12+
from src.zxbc import args_parser
13+
14+
if TYPE_CHECKING:
15+
from argparse import Namespace
1316

1417
__all__ = ["FileType", "parse_options", "set_option_defines"]
1518

@@ -21,7 +24,7 @@ class FileType:
2124
TZX = "tzx"
2225

2326

24-
def parse_options(args: List[str] = None):
27+
def parse_options(args: list[str] | None = None) -> Namespace:
2528
"""Parses command line options and setup global Options container"""
2629
parser = args_parser.parser()
2730
options = parser.parse_args(args=args)
@@ -56,7 +59,6 @@ def parse_options(args: List[str] = None):
5659

5760
if options.arch not in arch.AVAILABLE_ARCHITECTURES:
5861
parser.error(f"Invalid architecture '{options.arch}'")
59-
return 2
6062

6163
OPTIONS.architecture = options.arch
6264

@@ -67,7 +69,6 @@ def parse_options(args: List[str] = None):
6769

6870
if duplicated_options:
6971
parser.error(f"Warning(s) {', '.join(duplicated_options)} cannot be enabled " f"and disabled simultaneously")
70-
return 2
7172

7273
for warn_code in enabled_warnings:
7374
errmsg.enable_warning(warn_code)
@@ -103,15 +104,12 @@ def parse_options(args: List[str] = None):
103104

104105
if options.basic and not options.tzx and not options.tap:
105106
parser.error("Option --BASIC and --autorun requires --tzx or tap format")
106-
return 4
107107

108108
if options.append_binary and not options.tzx and not options.tap:
109109
parser.error("Option --append-binary needs either --tap or --tzx")
110-
return 5
111110

112111
if options.asm and options.memory_map:
113112
parser.error("Option --asm and --mmap cannot be used together")
114-
return 6
115113

116114
OPTIONS.use_basic_loader = options.basic
117115
OPTIONS.autorun = options.autorun
@@ -128,12 +126,11 @@ def parse_options(args: List[str] = None):
128126
args = [options.PROGRAM]
129127
if not os.path.exists(options.PROGRAM):
130128
parser.error("No such file or directory: '%s'" % args[0])
131-
return 2
132129

133130
set_option_defines()
134131

135132
OPTIONS.include_path = options.include_path
136-
OPTIONS.input_filename = zxbparser.FILENAME = os.path.basename(args[0])
133+
OPTIONS.input_filename = os.path.basename(args[0])
137134

138135
if not OPTIONS.output_filename:
139136
OPTIONS.output_filename = (
@@ -146,7 +143,7 @@ def parse_options(args: List[str] = None):
146143
return options
147144

148145

149-
def set_option_defines():
146+
def set_option_defines() -> None:
150147
"""Sets some macros automatically, according to options"""
151148
if OPTIONS.memory_check:
152149
OPTIONS.__DEFINES["__MEMORY_CHECK__"] = ""

src/zxbc/zxbparser.py

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -15,20 +15,13 @@
1515
from math import pi as PI
1616

1717
# typings
18-
from typing import List, NamedTuple, Optional
18+
from typing import NamedTuple, Optional
1919

2020
import src.api.config
2121
import src.api.dataref
2222
import src.api.options
23-
import src.api.symboltable
24-
25-
# Compiler API
26-
import src.api.symboltable.symboltable
2723
import src.api.utils
2824

29-
# Lexers and parsers, etc
30-
import src.ply.yacc as yacc
31-
3225
# Symbol Classes
3326
from src import arch
3427

@@ -54,6 +47,12 @@
5447
from src.api.errmsg import error, warning
5548
from src.api.global_ import LoopInfo
5649
from src.api.opcodestemps import OpcodesTemps
50+
51+
# Compiler API
52+
from src.api.symboltable.symboltable import SymbolTable
53+
54+
# Lexers and parsers, etc
55+
from src.ply import yacc
5756
from src.symbols import sym
5857
from src.symbols.id_ import SymbolID
5958
from src.symbols.symbol_ import Symbol
@@ -65,7 +64,7 @@
6564
# Function level entry ID in which scope we are into. If the list
6665
# is empty, we are at global scope
6766
# ----------------------------------------------------------------------
68-
FUNCTION_LEVEL: List[SymbolID] = gl.FUNCTION_LEVEL
67+
FUNCTION_LEVEL: list[SymbolID] = gl.FUNCTION_LEVEL
6968

7069
# ----------------------------------------------------------------------
7170
# Function calls pending to check
@@ -81,7 +80,7 @@
8180
# ----------------------------------------------------------------------
8281
# Global Symbol Table
8382
# ----------------------------------------------------------------------
84-
SYMBOL_TABLE = gl.SYMBOL_TABLE = src.api.symboltable.symboltable.SymbolTable()
83+
SYMBOL_TABLE = gl.SYMBOL_TABLE = SymbolTable()
8584

8685
# ----------------------------------------------------------------------
8786
# Defined user labels. They all are prepended _label_. Line numbers 10,
@@ -92,17 +91,17 @@
9291
# ----------------------------------------------------------------------
9392
# True if we're in the middle of a LET sentence. False otherwise.
9493
# ----------------------------------------------------------------------
95-
LET_ASSIGNMENT = False
94+
LET_ASSIGNMENT: bool = False
9695

9796
# ----------------------------------------------------------------------
9897
# True if PRINT sentence has been used.
9998
# ----------------------------------------------------------------------
100-
PRINT_IS_USED = False
99+
PRINT_IS_USED: bool = False
101100

102101
# ----------------------------------------------------------------------
103102
# Last line number output for checking program key board BREAK
104103
# ----------------------------------------------------------------------
105-
last_brk_linenum = 0
104+
last_brk_linenum: int = 0
106105

107106

108107
# ----------------------------------------------------------------------

0 commit comments

Comments
 (0)