Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 8348165

Browse filesBrowse files
committed
chore: rely on the default inclusions for ruff
1 parent 4f14a31 commit 8348165
Copy full SHA for 8348165

File tree

7 files changed

+126
-67
lines changed
Filter options

7 files changed

+126
-67
lines changed

‎crawl_sourcecode.py

Copy file name to clipboard
+33-29Lines changed: 33 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
""" This script can be used to test the equivalence in parsing between
1+
"""This script can be used to test the equivalence in parsing between
22
rustpython and cpython.
33
44
Usage example:
@@ -8,76 +8,80 @@
88
$ diff cpython.txt rustpython.txt
99
"""
1010

11-
1211
import ast
1312
import sys
1413
import symtable
1514
import dis
1615

1716
filename = sys.argv[1]
18-
print('Crawling file:', filename)
17+
print("Crawling file:", filename)
1918

2019

21-
with open(filename, 'r') as f:
20+
with open(filename, "r") as f:
2221
source = f.read()
2322

2423
t = ast.parse(source)
2524
print(t)
2625

2726
shift = 3
27+
28+
2829
def print_node(node, indent=0):
29-
indents = ' ' * indent
30+
indents = " " * indent
3031
if isinstance(node, ast.AST):
31-
lineno = 'row={}'.format(node.lineno) if hasattr(node, 'lineno') else ''
32+
lineno = "row={}".format(node.lineno) if hasattr(node, "lineno") else ""
3233
print(indents, "NODE", node.__class__.__name__, lineno)
3334
for field in node._fields:
34-
print(indents,'-', field)
35+
print(indents, "-", field)
3536
f = getattr(node, field)
3637
if isinstance(f, list):
3738
for f2 in f:
38-
print_node(f2, indent=indent+shift)
39+
print_node(f2, indent=indent + shift)
3940
else:
40-
print_node(f, indent=indent+shift)
41+
print_node(f, indent=indent + shift)
4142
else:
42-
print(indents, 'OBJ', node)
43+
print(indents, "OBJ", node)
44+
4345

4446
print_node(t)
4547

4648
# print(ast.dump(t))
4749
flag_names = [
48-
'is_referenced',
49-
'is_assigned',
50-
'is_global',
51-
'is_local',
52-
'is_parameter',
53-
'is_free',
50+
"is_referenced",
51+
"is_assigned",
52+
"is_global",
53+
"is_local",
54+
"is_parameter",
55+
"is_free",
5456
]
5557

58+
5659
def print_table(table, indent=0):
57-
indents = ' ' * indent
58-
print(indents, 'table:', table.get_name())
59-
print(indents, ' ', 'name:', table.get_name())
60-
print(indents, ' ', 'type:', table.get_type())
61-
print(indents, ' ', 'line:', table.get_lineno())
62-
print(indents, ' ', 'identifiers:', table.get_identifiers())
63-
print(indents, ' ', 'Syms:')
60+
indents = " " * indent
61+
print(indents, "table:", table.get_name())
62+
print(indents, " ", "name:", table.get_name())
63+
print(indents, " ", "type:", table.get_type())
64+
print(indents, " ", "line:", table.get_lineno())
65+
print(indents, " ", "identifiers:", table.get_identifiers())
66+
print(indents, " ", "Syms:")
6467
for sym in table.get_symbols():
6568
flags = []
6669
for flag_name in flag_names:
6770
func = getattr(sym, flag_name)
6871
if func():
6972
flags.append(flag_name)
70-
print(indents, ' sym:', sym.get_name(), 'flags:', ' '.join(flags))
73+
print(indents, " sym:", sym.get_name(), "flags:", " ".join(flags))
7174
if table.has_children():
72-
print(indents, ' ', 'Child tables:')
75+
print(indents, " ", "Child tables:")
7376
for child in table.get_children():
74-
print_table(child, indent=indent+shift)
77+
print_table(child, indent=indent + shift)
78+
7579

76-
table = symtable.symtable(source, 'a', 'exec')
80+
table = symtable.symtable(source, "a", "exec")
7781
print_table(table)
7882

7983
print()
80-
print('======== dis.dis ========')
84+
print("======== dis.dis ========")
8185
print()
82-
co = compile(source, filename, 'exec')
86+
co = compile(source, filename, "exec")
8387
dis.dis(co)

‎demo_closures.py

Copy file name to clipboard
+2-3Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
1-
2-
31
def foo(x):
42
def bar(z):
53
return z + x
4+
65
return bar
76

7+
88
f = foo(9)
99
g = foo(10)
1010

1111
print(f(2))
1212
print(g(2))
13-

‎ruff.toml

Copy file name to clipboardExpand all lines: ruff.toml
-7Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,4 @@
1-
include = [
2-
"examples/**/*.py",
3-
"extra_tests/**/*.py",
4-
"wasm/**/*.py",
5-
]
6-
71
exclude = [
8-
".*",
92
"Lib",
103
"vm/Lib",
114
"benches",

‎scripts/cargo-llvm-cov.py

Copy file name to clipboardExpand all lines: scripts/cargo-llvm-cov.py
+6-3Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,21 @@
33

44
TARGET = "extra_tests/snippets"
55

6+
67
def run_llvm_cov(file_path: str):
7-
""" Run cargo llvm-cov on a file. """
8+
"""Run cargo llvm-cov on a file."""
89
if file_path.endswith(".py"):
910
command = ["cargo", "llvm-cov", "--no-report", "run", "--", file_path]
1011
subprocess.call(command)
1112

13+
1214
def iterate_files(folder: str):
13-
""" Iterate over all files in a folder. """
15+
"""Iterate over all files in a folder."""
1416
for root, _, files in os.walk(folder):
1517
for file in files:
1618
file_path = os.path.join(root, file)
1719
run_llvm_cov(file_path)
1820

21+
1922
if __name__ == "__main__":
20-
iterate_files(TARGET)
23+
iterate_files(TARGET)

‎scripts/fix_test.py

Copy file name to clipboardExpand all lines: scripts/fix_test.py
+29-5Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,21 +10,26 @@
1010
4. Ensure that there are no unexpected successes in the test.
1111
5. Actually fix the test.
1212
"""
13+
1314
import argparse
1415
import ast
1516
import itertools
1617
import platform
1718
from pathlib import Path
1819

20+
1921
def parse_args():
2022
parser = argparse.ArgumentParser(description="Fix test.")
2123
parser.add_argument("--path", type=Path, help="Path to test file")
2224
parser.add_argument("--force", action="store_true", help="Force modification")
23-
parser.add_argument("--platform", action="store_true", help="Platform specific failure")
25+
parser.add_argument(
26+
"--platform", action="store_true", help="Platform specific failure"
27+
)
2428

2529
args = parser.parse_args()
2630
return args
2731

32+
2833
class Test:
2934
name: str = ""
3035
path: str = ""
@@ -33,6 +38,7 @@ class Test:
3338
def __str__(self):
3439
return f"Test(name={self.name}, path={self.path}, result={self.result})"
3540

41+
3642
class TestResult:
3743
tests_result: str = ""
3844
tests = []
@@ -52,7 +58,11 @@ def parse_results(result):
5258
in_test_results = True
5359
elif line.startswith("-----------"):
5460
in_test_results = False
55-
if in_test_results and not line.startswith("tests") and not line.startswith("["):
61+
if (
62+
in_test_results
63+
and not line.startswith("tests")
64+
and not line.startswith("[")
65+
):
5666
line = line.split(" ")
5767
if line != [] and len(line) > 3:
5868
test = Test()
@@ -67,9 +77,11 @@ def parse_results(result):
6777
test_results.tests_result = res
6878
return test_results
6979

80+
7081
def path_to_test(path) -> list[str]:
7182
return path.split(".")[2:]
7283

84+
7385
def modify_test(file: str, test: list[str], for_platform: bool = False) -> str:
7486
a = ast.parse(file)
7587
lines = file.splitlines()
@@ -84,6 +96,7 @@ def modify_test(file: str, test: list[str], for_platform: bool = False) -> str:
8496
break
8597
return "\n".join(lines)
8698

99+
87100
def modify_test_v2(file: str, test: list[str], for_platform: bool = False) -> str:
88101
a = ast.parse(file)
89102
lines = file.splitlines()
@@ -101,8 +114,13 @@ def modify_test_v2(file: str, test: list[str], for_platform: bool = False) -> st
101114
if fn.name == test[-1]:
102115
assert not for_platform
103116
indent = " " * fn.col_offset
104-
lines.insert(fn.lineno - 1, indent + fixture)
105-
lines.insert(fn.lineno - 1, indent + "# TODO: RUSTPYTHON")
117+
lines.insert(
118+
fn.lineno - 1, indent + fixture
119+
)
120+
lines.insert(
121+
fn.lineno - 1,
122+
indent + "# TODO: RUSTPYTHON",
123+
)
106124
break
107125
case ast.FunctionDef():
108126
if n.name == test[0] and len(test) == 1:
@@ -115,11 +133,17 @@ def modify_test_v2(file: str, test: list[str], for_platform: bool = False) -> st
115133
exit()
116134
return "\n".join(lines)
117135

136+
118137
def run_test(test_name):
119138
print(f"Running test: {test_name}")
120139
rustpython_location = "./target/release/rustpython"
121140
import subprocess
122-
result = subprocess.run([rustpython_location, "-m", "test", "-v", test_name], capture_output=True, text=True)
141+
142+
result = subprocess.run(
143+
[rustpython_location, "-m", "test", "-v", test_name],
144+
capture_output=True,
145+
text=True,
146+
)
123147
return parse_results(result)
124148

125149

‎vm/sre_engine/generate_tests.py

Copy file name to clipboardExpand all lines: vm/sre_engine/generate_tests.py
+22-11Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
assert re._constants.MAGIC == sre_engine_magic
1212

13+
1314
class CompiledPattern:
1415
@classmethod
1516
def compile(cls, pattern, flags=0):
@@ -21,40 +22,50 @@ def compile(cls, pattern, flags=0):
2122
self.flags = re.RegexFlag(flags | p.state.flags)
2223
return self
2324

25+
2426
for k, v in re.RegexFlag.__members__.items():
2527
setattr(CompiledPattern, k, v)
2628

2729

2830
class EscapeRustStr:
2931
hardcoded = {
30-
ord('\r'): '\\r',
31-
ord('\t'): '\\t',
32-
ord('\r'): '\\r',
33-
ord('\n'): '\\n',
34-
ord('\\'): '\\\\',
35-
ord('\''): '\\\'',
36-
ord('\"'): '\\\"',
32+
ord("\r"): "\\r",
33+
ord("\t"): "\\t",
34+
ord("\r"): "\\r",
35+
ord("\n"): "\\n",
36+
ord("\\"): "\\\\",
37+
ord("'"): "\\'",
38+
ord('"'): '\\"',
3739
}
40+
3841
@classmethod
3942
def __class_getitem__(cls, ch):
4043
if (rpl := cls.hardcoded.get(ch)) is not None:
4144
return rpl
42-
if ch in range(0x20, 0x7f):
45+
if ch in range(0x20, 0x7F):
4346
return ch
4447
return f"\\u{{{ch:x}}}"
48+
49+
4550
def rust_str(s):
4651
return '"' + s.translate(EscapeRustStr) + '"'
4752

53+
4854
# matches `// pattern {varname} = re.compile(...)`
49-
pattern_pattern = re.compile(r"^((\s*)\/\/\s*pattern\s+(\w+)\s+=\s+(.+?))$(?:.+?END GENERATED)?", re.M | re.S)
55+
pattern_pattern = re.compile(
56+
r"^((\s*)\/\/\s*pattern\s+(\w+)\s+=\s+(.+?))$(?:.+?END GENERATED)?", re.M | re.S
57+
)
58+
59+
5060
def replace_compiled(m):
5161
line, indent, varname, pattern = m.groups()
5262
pattern = eval(pattern, {"re": CompiledPattern})
5363
pattern = f"Pattern {{ pattern: {rust_str(pattern.pattern)}, code: &{json.dumps(pattern.code)} }}"
54-
return f'''{line}
64+
return f"""{line}
5565
{indent}// START GENERATED by generate_tests.py
5666
{indent}#[rustfmt::skip] let {varname} = {pattern};
57-
{indent}// END GENERATED'''
67+
{indent}// END GENERATED"""
68+
5869

5970
with os.scandir("tests") as t, os.scandir("benches") as b:
6071
for f in chain(t, b):

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.