Skip to content

Commit

Permalink
lint: ruff fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
igordejanovic committed Feb 9, 2024
1 parent ac4104e commit 2025e29
Show file tree
Hide file tree
Showing 15 changed files with 53 additions and 65 deletions.
6 changes: 0 additions & 6 deletions parglare/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,6 @@
Common parsing actions.
"""
import contextlib
import sys

if sys.version < '3':
text = unicode # NOQA
else:
text = str


def pass_none(_, value, *args):
Expand Down
10 changes: 5 additions & 5 deletions parglare/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,8 @@ def replace_newlines(in_str):
def load_python_module(mod_name, mod_path):
"""
Loads Python module from an arbitrary location.
See https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path # noqa
"""
See https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path
""" # noqa: E501
import importlib.util
spec = importlib.util.spec_from_file_location(
mod_name, mod_path)
Expand All @@ -146,13 +146,13 @@ def __call__(self, name_or_f):
If called with action/recognizer name return decorator.
If called over function apply decorator.
"""
is_name = type(name_or_f) is str
is_name = isinstance(name_or_f, str)

def decorator(f):
name = name_or_f if is_name else f.__name__
objects = all.get(name)
if objects:
if type(objects) is list:
if isinstance(objects, list):
objects.append(f)
else:
all[name] = [objects, f]
Expand All @@ -177,7 +177,7 @@ def pos_to_line_col(input_str, position):
if position is None:
return None, None

if type(input_str) is not str:
if not isinstance(input_str, str):
# If we are not parsing string
return 1, position

Expand Down
3 changes: 2 additions & 1 deletion parglare/export.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ def grammar_pda_export(table, file_name):

for symb, goto_state in ((symb, goto) for symb, goto
in state.gotos.items()):
f.write(f'{state.state_id} -> {goto_state.state_id} [label="GOTO:{symb}"]')
f.write(f'{state.state_id} -> {goto_state.state_id}'
f' [label="GOTO:{symb}"]')

f.write("\n}\n")
2 changes: 1 addition & 1 deletion parglare/glr.py
Original file line number Diff line number Diff line change
Expand Up @@ -499,7 +499,7 @@ def _do_error_recovery(self):
level=1, new_line=True)
h_print("Symbols expected: ",
[s.name for s in symbols], level=1)
if type(self.error_recovery) is bool:
if isinstance(self.error_recovery, bool):
# Default recovery
if debug:
prints("\tDoing default error recovery.")
Expand Down
39 changes: 20 additions & 19 deletions parglare/grammar.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ def __init__(self, regex, name=None, re_flags=re.MULTILINE,
except re.error as ex:
regex = esc_control_characters(self._regex)
message = 'Regex compile error in /{}/ (report: "{}")'
raise GrammarError(None, message.format(regex, str(ex)))
raise GrammarError(None, message.format(regex, str(ex))) from ex

def __call__(self, in_str, pos):
m = self.regex.match(in_str, pos)
Expand Down Expand Up @@ -466,10 +466,10 @@ def __init__(self, productions, terminals=None, classes=None, imports=None,
i.grammar = self.grammar
try:
i.load_pgfile()
except OSError:
except OSError as ex:
raise GrammarError(
location=Location(file_name=self.file_path),
message=f'Can\'t import file "{i.file_path}".')
message=f'Can\'t import file "{i.file_path}".') from ex
else:
self.imports = {}

Expand Down Expand Up @@ -529,8 +529,8 @@ def collect_and_unify_symbols(self):
new_symbol.productions.append(production)

# Check grammar actions for rules/symbols.
if new_symbol.action_name:
if new_symbol.action_name != old_symbol.action_name:
if new_symbol.action_name and \
new_symbol.action_name != old_symbol.action_name:
raise GrammarError(
location=new_symbol.location,
message='Multiple different grammar actions '
Expand Down Expand Up @@ -670,11 +670,11 @@ def resolve_symbol_by_name(self, symbol_name, location=None):
import_module_name, name = symbol_name.split('.', 1)
try:
imported_pg_file = self.imports[import_module_name]
except KeyError:
except KeyError as ex:
raise GrammarError(
location=location,
message='Unexisting module "{}" in reference "{}"'
.format(import_module_name, symbol_name))
.format(import_module_name, symbol_name)) from ex
return imported_pg_file.resolve_symbol_by_name(name, location)
else:
return self.symbols_by_name.get(symbol_name, None)
Expand Down Expand Up @@ -895,7 +895,8 @@ def add_productions(productions):
add_productions(rhs_elem.productions)
else:
# This should never happen
raise AssertionError(f"Invalid RHS element type '{type(rhs_elem)}'.")
raise AssertionError(
f"Invalid RHS element type '{type(rhs_elem)}'.")
add_productions(list(self.productions))

def _enumerate_productions(self):
Expand Down Expand Up @@ -1004,8 +1005,8 @@ def _resolve_actions(self, action_overrides=None,
symbol.action = action

# Some sanity checks for actions
if type(symbol.action) is list:
if type(symbol) is Terminal:
if isinstance(symbol.action, list):
if isinstance(symbol, Terminal):
raise ParserInitError(
'Cannot use a list of actions for '
f'terminal "{symbol.name}".')
Expand Down Expand Up @@ -1509,12 +1510,12 @@ def act_pgfile(context, nodes):
imports, productions, terminals = [], [], []
while nodes:
first = nodes.pop(0)
if first and type(first) is list:
if type(first[0]) is PGFileImport:
if first and isinstance(first, list):
if isinstance(first[0], PGFileImport):
imports = first
elif type(first[0]) is Production:
elif isinstance(first[0], Production):
productions = first
elif type(first[0]) is Terminal:
elif isinstance(first[0], Terminal):
terminals = first

for terminal in context.extra.inline_terminals.values():
Expand Down Expand Up @@ -1722,11 +1723,11 @@ def get_production_rule_meta_datas(raw_meta_datas):
meta_datas['nops'] = True
elif meta_data == 'nopse':
meta_datas['nopse'] = True
elif type(meta_data) is int:
elif isinstance(meta_data, int):
meta_datas['priority'] = meta_data
else:
# User meta-data
assert type(meta_data) is list
assert isinstance(meta_data, list)
name, _, value = meta_data
meta_datas.setdefault('user_meta', {})[name] = value
return meta_datas
Expand All @@ -1752,9 +1753,9 @@ def act_production_group(context, nodes):

def _set_term_props(term, props):
for t in props:
if type(t) is int:
if isinstance(t, int):
term.prior = t
elif type(t) is list:
elif isinstance(t, list):
# User meta-data
name, _, value = t
term.add_user_meta_data(name, value)
Expand Down Expand Up @@ -1876,7 +1877,7 @@ def act_gsymbol_string_recognizer(context, nodes):

def act_assignment(_, nodes):
gsymbol_reference = nodes[0]
if type(gsymbol_reference) is list:
if isinstance(gsymbol_reference, list):
# Named match
name, op, gsymbol_reference = gsymbol_reference
else:
Expand Down
19 changes: 8 additions & 11 deletions parglare/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@ def inner_call_actions(node):
else:
assgn_results[a.name] = \
bool(subresults[a.index])
if type(sem_action) is list:
if isinstance(sem_action, list):
if assignments:
result = \
sem_action[
Expand All @@ -412,11 +412,8 @@ def inner_call_actions(node):
else:
result = sem_action(node.context, subresults)
else:
if len(subresults) == 1:
# Unpack if single subresult
result = subresults[0]
else:
result = subresults
result = subresults[0] \
if len(subresults) == 1 else subresults

return result

Expand All @@ -438,15 +435,15 @@ def _skipws(self, head, input_str):
while head.position < in_len \
and input_str[head.position] in self.ws:
head.position += 1
except TypeError:
except TypeError as ex:
raise ParserInitError(
"For parsing non-textual content please "
"set `ws` to `None`.")
"set `ws` to `None`.") from ex
layout_content_ahead = input_str[old_pos:head.position]

if self.debug:
content = layout_content_ahead
if type(layout_content_ahead) is str:
if isinstance(layout_content_ahead, str):
content = content.replace("\n", "\\n")
h_print("Skipping whitespaces:",
f"'{content}'")
Expand Down Expand Up @@ -693,7 +690,7 @@ def _call_reduce_action(self, context, subresults):
else:
assgn_results[a.name] = bool(subresults[a.index])

if type(sem_action) is list:
if isinstance(sem_action, list):
if assignments:
result = sem_action[production.prod_symbol_id](
context, subresults, **assgn_results)
Expand Down Expand Up @@ -770,7 +767,7 @@ def _do_recovery(self):
head = self.parse_stack[-1]
error = self.errors[-1]

if type(self.error_recovery) is bool:
if isinstance(self.error_recovery, bool):
# Default recovery
if debug:
prints("\tDoing default error recovery.")
Expand Down
8 changes: 4 additions & 4 deletions parglare/tables/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,9 +205,9 @@ def create_table(grammar, itemset_type=LR_1, start_production=1,
state_id += 1
else:
# A state with this kernel items already exists.
if itemset_type is LR_1:
# LALR: Try to merge states, i.e. update items follow sets.
if not merge_states(target_state, maybe_new_state):
# LALR: Try to merge states, i.e. update items follow sets.
if itemset_type is LR_1 and \
not merge_states(target_state, maybe_new_state):
target_state = maybe_new_state
state_queue.append(target_state)
state_id += 1
Expand Down Expand Up @@ -261,7 +261,7 @@ def create_table(grammar, itemset_type=LR_1, start_production=1,

# Calculate REDUCTION entries in ACTION tables and resolve possible
# conflicts.
for idx, state in enumerate(states):
for state in states:
actions = state.actions

for item in state.items:
Expand Down
12 changes: 3 additions & 9 deletions parglare/termui.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
import sys

import click

if sys.version < '3':
text = unicode # NOQA
else:
text = str

colors = False

S_ATTENTION = {'fg': 'red', 'bold': True}
Expand Down Expand Up @@ -44,14 +38,14 @@ def style(header, content, level=0, new_line=False, header_style=S_HEADER,
if content:
content_start = level * 8 + len(header) + 1
content_width = width - content_start
content = text(content)
content = str(content)
content = [content[start:start+content_width]
for start in range(0, len(content), content_width)]
content = ('\n' + ' ' * content_start).join(content)
new_line = "\n" if new_line else ""
level = ("\t" * level) if level else ""
return new_line + level + style_message(text(header), header_style) \
+ ((" " + text(content)) if content else "")
return new_line + level + style_message(str(header), header_style) \
+ ((" " + str(content)) if content else "")


def styled_print(header, content, level=0, new_line=False,
Expand Down
4 changes: 2 additions & 2 deletions tests/func/grammar/test_meta_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def test_production_meta_data():
assert prod.some_float == 4.5

with pytest.raises(AttributeError):
prod.non_existing
prod.non_existing # noqa: B018


def test_production_meta_data_must_be_key_value():
Expand Down Expand Up @@ -60,7 +60,7 @@ def test_terminal_meta_data():
assert term_a.label == 'My Label'

with pytest.raises(AttributeError):
term_a.non_existing
term_a.non_existing # noqa: B018


def test_terminal_meta_data_must_be_key_value():
Expand Down
4 changes: 2 additions & 2 deletions tests/func/import/diamond/test_diamond.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@ def test_diamond_import_resolving_and_model_creation():
model = Parser(g).parse(input_str)
assert model
assert model.__class__.__name__ == 'Model'
assert type(model.packages) is list
assert isinstance(model.packages, list)
assert len(model.packages) == 2
assert model.packages[0].name == 'First'
assert type(model.modules) is list
assert isinstance(model.modules, list)
assert len(model.modules) == 1

packageComponent = model.packages[1].body.components[0]
Expand Down
1 change: 1 addition & 0 deletions tests/func/parsing/test_glr_forest_disambiguation.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# ruff: noqa: B023
"""
Forest can be disambiguated by eliminating possibilities in Parent objects.
"""
Expand Down
1 change: 0 additions & 1 deletion tests/func/parsing/test_glr_parsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,6 @@ def test_lexical_ambiguity2():
# Longest match is used to choose FLOAT
forest = parser.parse('42.12')
assert len(forest) == 1
forest[0].symbol.name == 'FLOAT'
assert forest.ambiguities == 0

# Also, longest match will choose FLOAT in both cases
Expand Down
2 changes: 1 addition & 1 deletion tests/func/parsing/test_parse_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def act_sum(context, nodes):
assert context.node.is_nonterm() \
and context.node.symbol.name == 'E'
else:
context.node is None
assert context.node is None

return act_sum

Expand Down
4 changes: 2 additions & 2 deletions tests/func/persistence/compare_table/test_compare_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,10 @@ def test_diamond_import_resolving_and_model_creation():
model = parser.parse(input_str)
assert model
assert model.__class__.__name__ == 'Model'
assert type(model.packages) is list
assert isinstance(model.packages, list)
assert len(model.packages) == 2
assert model.packages[0].name == 'First'
assert type(model.modules) is list
assert isinstance(model.modules, list)
assert len(model.modules) == 1

packageComponent = model.packages[1].body.components[0]
Expand Down
3 changes: 2 additions & 1 deletion tests/func/pglr/test_pglr.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,5 @@ def test_pglr_viz():
result = subprocess.call(['pglr', '--no-colors', 'viz', GRAMMAR_FILE])
assert result == 0
assert os.path.exists(DOT_FILE)
assert 'digraph grammar' in open(DOT_FILE).read()
with open(DOT_FILE) as f:
assert 'digraph grammar' in f.read()

0 comments on commit 2025e29

Please sign in to comment.