Skip to content

Commit 88e4bbe

Browse files
committed
fix: most of the type hint issues
1 parent f77b505 commit 88e4bbe

File tree

1 file changed

+135
-29
lines changed

1 file changed

+135
-29
lines changed

src/pyconverter/xml2py/ast_tree.py

Lines changed: 135 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,35 @@
5151
'``"``': "``",
5252
}
5353

54+
word_digit = [
55+
'zero',
56+
'one',
57+
'two',
58+
'three',
59+
'four',
60+
'five',
61+
'six',
62+
'seven',
63+
'eight',
64+
'nine',
65+
]
66+
67+
superlatif = ["st", "nd", "rd", "th"]
68+
69+
superlatif_digit = [
70+
'',
71+
'first',
72+
'second',
73+
'third',
74+
'fourth',
75+
'fifth',
76+
'sixth',
77+
'seventh',
78+
'eighth',
79+
'ninth',
80+
]
81+
82+
5483
CLEANUP = {
5584
",, ": ", ",
5685
", , ": ", ",
@@ -86,6 +115,31 @@ def to_py_name(name, name_map=None):
86115
else:
87116
return name
88117

118+
def get_iter_values(name: str):
119+
"""Get the values of an iterator."""
120+
output = re.search(r"([a-zA-Z_]*)(\d*)", name.strip())
121+
groups = output.groups()
122+
return groups[0], int(groups[1])
123+
124+
def get_quant_iter_pos(name: str) -> tuple:
125+
"""
126+
Get the values of a quantity iterator.
127+
128+
Parameters
129+
----------
130+
name : str
131+
Name of the parameter containing the iterator.
132+
133+
Returns
134+
-------
135+
tuple
136+
Tuple containing the iteration value and the position of the iterator.
137+
"""
138+
output = re.search(r"(?<=\+)\d*", name.strip()) # find the number after the '+'
139+
iter = output.group()
140+
position = output.span()
141+
return int(iter), position
142+
89143

90144
# ############################################################################
91145
# Element class
@@ -1963,8 +2017,6 @@ def _parse_list_entry(self):
19632017
for item in self._list_entry:
19642018
if isinstance(item, VarlistEntry):
19652019
if len(Argument(item).multiple_args)>0:
1966-
print("IT'S TRUE : ")
1967-
print(Argument(item).multiple_args)
19682020
for arg in Argument(item).multiple_args:
19692021
self._arguments.append(arg)
19702022
else:
@@ -1994,12 +2046,54 @@ def __init__(self, element:str | Element, description:Element | None=None) -> No
19942046
def multiple_args(self):
19952047
additional_args = []
19962048
if "," in str(self._name):
1997-
for item_name in str(self._name).split(","):
1998-
print(item_name)
1999-
if item_name.strip() == "":
2000-
continue
2001-
arg_name = item_name.strip()
2002-
additional_args.append(Argument(arg_name, self._description))
2049+
split_name = str(self._name).split(",")
2050+
if ". . ." not in str(self._name) or "..." not in str(self._name):
2051+
for item_name in split_name:
2052+
if item_name.strip() == "":
2053+
continue
2054+
arg_name = item_name.strip()
2055+
additional_args.append(Argument(arg_name, self._description))
2056+
else:
2057+
for i, item_name in enumerate(split_name):
2058+
item_name = item_name.strip()
2059+
if item_name == "":
2060+
continue
2061+
elif ". . ." in item_name or "..." in item_name:
2062+
if "+" in split_name[i+1]:
2063+
number_final_iter, (initial_pos_final, end_pos_final) = get_quant_iter_pos(split_name[i+1])
2064+
if "+" in split_name[i-1]:
2065+
number_prev_iter, (initial_pos_prev, end_pos_prev) = get_quant_iter_pos(split_name[i-1])
2066+
else :
2067+
number_prev_iter = 0
2068+
2069+
for j in range(number_prev_iter+1, number_final_iter):
2070+
arg_name = split_name[i+1].strip()
2071+
arg_name = f"{arg_name[:initial_pos_final]}{j}{arg_name[end_pos_final:]}"
2072+
additional_args.append(Argument(arg_name, self._description))
2073+
else:
2074+
print(repr(split_name[i-1]), repr(split_name[i+1]))
2075+
k = i
2076+
while split_name[k-1].strip() == "" and k-1 >= 0:
2077+
k -= 1
2078+
print(k, "SPLIT NAME : ", split_name[k-1].strip())
2079+
if split_name[k-1].strip() == "":
2080+
raise ValueError("The argument name is not consistent.")
2081+
name_iter_prev, number_iter_prev = get_iter_values(split_name[k-1])
2082+
name_iter_next, number_iter_next = get_iter_values(split_name[i+1])
2083+
if name_iter_prev != name_iter_next:
2084+
print(name_iter_prev, name_iter_next)
2085+
logging.warning(f"The argument name is not consistent : {name_iter_prev} != {name_iter_next}")
2086+
logging.info("Applying the longest name for the argument list as it's probably coming from a typography.")
2087+
if len(name_iter_prev) > len(name_iter_next):
2088+
name_iter_next = name_iter_prev
2089+
else:
2090+
name_iter_prev = name_iter_next
2091+
else:
2092+
for j in range(number_iter_prev+1, number_iter_next):
2093+
arg_name = f"{name_iter_prev}{j}"
2094+
additional_args.append(Argument(arg_name, self._description))
2095+
else:
2096+
additional_args.append(Argument(item_name, self._description))
20032097
return additional_args
20042098

20052099
def rec_find(self, _type: str, terms=None) -> Element | None:
@@ -2051,20 +2145,28 @@ def str_types(self, join_str: str) -> str:
20512145
@property
20522146
def py_arg_name(self) -> str:
20532147
"""Python-compatible term."""
2054-
arg = str(self._name).lower()
2055-
2148+
arg = str(self._name).lower().strip()
2149+
2150+
if arg[0].isdigit():
2151+
if arg[1].isdigit():
2152+
raise ValueError(f"The code needs to be expanded to handle numbers")
2153+
elif arg[1:3] not in superlatif:
2154+
arg = f"{word_digit[int(arg[0])]}{arg[1:]}"
2155+
else:
2156+
arg = f"{superlatif_digit[int(arg[0])]}{arg[3:]}"
2157+
2158+
arg = arg.replace("(" , "_").replace(")", "_").replace("+", "plus").replace("blank", "").replace("-", "_").replace("'", "")
2159+
arg = arg.strip()
2160+
2161+
while len(arg) > 0 and arg[-1] == "_":
2162+
arg = arg[:-1]
2163+
20562164
if arg == "type":
20572165
arg = "type_"
20582166

2059-
elif "," in arg:
2060-
2061-
for item_name in arg.split(","):
2062-
if item_name.strip() == "":
2063-
continue
2064-
arg_name = item_name.strip()
2065-
Argument(arg_name, self._description)
2066-
2067-
2167+
elif arg == "class":
2168+
arg = "class_"
2169+
20682170
return f"{arg}"
20692171

20702172
def resized_description(self, description: str|None=None, max_length: int =100, indent: str="") -> List[str]:
@@ -2076,21 +2178,23 @@ def resized_description(self, description: str|None=None, max_length: int =100,
20762178

20772179
def to_py_docstring(self, max_length=100, indent="", links=None, base_url=None, fcache=None) -> List[str]:
20782180
"""Return a list of string to enable converting the element to an RST format."""
2079-
2080-
docstring = [f"{indent}{self.py_arg_name} : {self.str_types(" or ")}"]
2081-
rst_description = self._description.to_rst(indent=indent, max_length = max_length, links=links, base_url=base_url, fcache=fcache)
2082-
if not "* " in rst_description:
2083-
list_description = self.resized_description(rst_description, max_length, indent)
2181+
if self.py_arg_name not in ["--","–",""]:
2182+
docstring = [f"{indent}{self.py_arg_name} : {self.str_types(" or ")}"]
2183+
rst_description = self._description.to_rst(indent=indent, max_length = max_length, links=links, base_url=base_url, fcache=fcache)
2184+
if not "* " in rst_description:
2185+
list_description = self.resized_description(rst_description, max_length, indent)
2186+
else:
2187+
list_description = rst_description.split("\n")
2188+
2189+
docstring = [f"{indent}{self.py_arg_name} : {self.str_types(" or ")}"]
2190+
docstring.extend(list_description)
20842191
else:
2085-
list_description = rst_description.split("\n")
2086-
2087-
docstring = [f"{indent}{self.py_arg_name} : {self.str_types(" or ")}"]
2088-
docstring.extend(list_description)
2192+
docstring = []
20892193
return docstring
20902194

20912195
def to_py_signature(self) -> str:
20922196
"""Return the Python signature of the argument."""
2093-
if self.py_arg_name != "--" and self.py_arg_name != "–":
2197+
if self.py_arg_name not in ["--","–",""]:
20942198
kwarg = f'{self.py_arg_name}: {self.str_types(" | ")}=""'
20952199
else:
20962200
kwarg = None
@@ -2158,11 +2262,13 @@ def arg_desc(self) -> List[Argument]:
21582262
):
21592263
for child in elem:
21602264
if isinstance(child, Variablelist):
2265+
print("COMMAND : ", self.name)
21612266
arguments = ArgumentList(child).arguments
21622267
continue
21632268
else:
21642269
for elem in refsyn:
21652270
if isinstance(elem, Variablelist):
2271+
print("COMMAND : ", self.name)
21662272
arguments = ArgumentList(elem).arguments
21672273
continue
21682274
return arguments

0 commit comments

Comments
 (0)