Skip to content

Commit 44d51c8

Browse files
authored
Ruff rules for comprehensions, performance, and simplicity (#23040)
Only in the `tools/` directory apply ruff rules for comprehensions, performance, and simplicity. * https://docs.astral.sh/ruff * https://docs.astral.sh/ruff/rules/#flake8-comprehensions-c4 * https://docs.astral.sh/ruff/rules/#perflint-perf * https://docs.astral.sh/ruff/rules/#flake8-simplify-sim This pull request was roughly created via the command: `ruff --select=C4,PERF,Q,SIM --ignore=SIM108,SIM300 lint.flake8-quotes.inline-quotes=single --fix --unsafe-fixes`
1 parent f526386 commit 44d51c8

20 files changed

+63
-99
lines changed

tools/building.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ def side_module_external_deps(external_symbols):
114114
sym = demangle_c_symbol_name(sym)
115115
if sym in external_symbols:
116116
deps = deps.union(external_symbols[sym])
117-
return sorted(list(deps))
117+
return sorted(deps)
118118

119119

120120
def create_stub_object(external_symbols):
@@ -184,12 +184,11 @@ def lld_flags_for_executable(external_symbols):
184184
c_exports += side_module_external_deps(external_symbols)
185185
for export in c_exports:
186186
if settings.ERROR_ON_UNDEFINED_SYMBOLS:
187-
cmd.append('--export=' + export)
187+
cmd.append(f'--export={export}')
188188
else:
189-
cmd.append('--export-if-defined=' + export)
189+
cmd.append(f'--export-if-defined={export}')
190190

191-
for e in settings.EXPORT_IF_DEFINED:
192-
cmd.append('--export-if-defined=' + e)
191+
cmd.extend(f'--export-if-defined={e}' for e in settings.EXPORT_IF_DEFINED)
193192

194193
if settings.RELOCATABLE:
195194
cmd.append('--experimental-pic')
@@ -749,10 +748,10 @@ def minify_wasm_js(js_file, wasm_file, expensive_optimizations, debug_info):
749748

750749

751750
def is_internal_global(name):
752-
internal_start_stop_symbols = set(['__start_em_asm', '__stop_em_asm',
753-
'__start_em_js', '__stop_em_js',
754-
'__start_em_lib_deps', '__stop_em_lib_deps',
755-
'__em_lib_deps'])
751+
internal_start_stop_symbols = {'__start_em_asm', '__stop_em_asm',
752+
'__start_em_js', '__stop_em_js',
753+
'__start_em_lib_deps', '__stop_em_lib_deps',
754+
'__em_lib_deps'}
756755
internal_prefixes = ('__em_js__', '__em_lib_deps')
757756
return name in internal_start_stop_symbols or any(name.startswith(p) for p in internal_prefixes)
758757

tools/colored_logger.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -99,9 +99,7 @@ def add_coloring_to_emit_ansi(fn):
9999
# add methods we need to the class
100100
def new(*args):
101101
levelno = args[1].levelno
102-
if levelno >= 50:
103-
color = '\x1b[31m' # red
104-
elif levelno >= 40:
102+
if levelno >= 40:
105103
color = '\x1b[31m' # red
106104
elif levelno >= 30:
107105
color = '\x1b[33m' # yellow

tools/determinism_checker.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ def run():
2424
def write(data, subdir):
2525
if not os.path.exists(subdir):
2626
os.mkdir(subdir)
27-
for relevant_file in data.keys():
27+
for relevant_file in data:
2828
Path(os.path.join(subdir, relevant_file)).write_text(data[relevant_file])
2929

3030

tools/emcoverage.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
from glob import glob
3838

3939
import coverage.cmdline # type: ignore
40+
import contextlib
4041

4142
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
4243

@@ -62,10 +63,8 @@ def main():
6263
if sys.argv[1] in ('html', 'report', 'xml'):
6364
old_argv = sys.argv
6465
sys.argv = ['coverage', 'combine'] + glob(os.path.join(store, '*'))
65-
try:
66+
with contextlib.suppress(SystemExit):
6667
coverage.cmdline.main()
67-
except SystemExit:
68-
pass
6968
sys.argv = old_argv + ['-i']
7069
return coverage.cmdline.main()
7170

tools/emdump.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -162,8 +162,8 @@ def merge_entry_to_existing(existing_data, new_entry, total_source_set_size):
162162
name = new_entry['unminified_name']
163163
if name in existing_data:
164164
ex = existing_data[name]
165-
num_times_occurs_1 = ex['num_times_occurs'] if 'num_times_occurs' in ex else 1
166-
num_times_occurs_2 = new_entry['num_times_occurs'] if 'num_times_occurs' in new_entry else 1
165+
num_times_occurs_1 = ex.get('num_times_occurs', 1)
166+
num_times_occurs_2 = new_entry.get('num_times_occurs', 1)
167167
existing_data[name] = {
168168
'lines': ex['lines'] + new_entry['lines'],
169169
'bytes': ex['bytes'] + new_entry['bytes'],
@@ -212,7 +212,7 @@ def analyze_javascript_file_contents(filename, file_contents, total_source_set_s
212212
if asm_start >= 0:
213213
asm_start_brace = file_contents.rfind('{', 0, asm_start)
214214
if asm_start_brace >= 0:
215-
asm_end_brace = brace_map[asm_start_brace] if asm_start_brace in brace_map else file_len
215+
asm_end_brace = brace_map.get(asm_start_brace, file_len)
216216

217217
func_pos = -1
218218
var_pos = -1
@@ -516,7 +516,7 @@ def print_symbol_info(data, total_source_set_size):
516516
continue
517517
if options.only_common and (not e['in_set_1'] or not e['in_set_2']):
518518
continue
519-
prev_bytes = e['prev_bytes'] if 'prev_bytes' in e else 0
519+
prev_bytes = e.get('prev_bytes', 0)
520520
if max(e['bytes'], prev_bytes) < options.filter_size:
521521
continue
522522
if e['bytes'] == prev_bytes and options.only_changes:

tools/emscripten.py

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,7 @@ def set_memory(static_bump):
225225

226226
def report_missing_exports_wasm_only(metadata):
227227
if diagnostics.is_enabled('undefined'):
228-
defined_symbols = set(asmjs_mangle(e) for e in metadata.all_exports)
228+
defined_symbols = {asmjs_mangle(e) for e in metadata.all_exports}
229229
missing = set(settings.USER_EXPORTS) - defined_symbols
230230
for symbol in sorted(missing):
231231
diagnostics.warning('undefined', f'undefined exported symbol: "{symbol}"')
@@ -235,7 +235,7 @@ def report_missing_exports(js_symbols):
235235
if diagnostics.is_enabled('undefined'):
236236
# Report any symbol that was explicitly exported but is present neither
237237
# as a native function nor as a JS library function.
238-
defined_symbols = set(asmjs_mangle(e) for e in settings.WASM_EXPORTS).union(js_symbols)
238+
defined_symbols = {asmjs_mangle(e) for e in settings.WASM_EXPORTS}.union(js_symbols)
239239
missing = set(settings.USER_EXPORTS) - defined_symbols
240240
for symbol in sorted(missing):
241241
diagnostics.warning('undefined', f'undefined exported symbol: "{symbol}"')
@@ -699,15 +699,12 @@ def create_asm_consts(metadata):
699699
asm_consts = {}
700700
for addr, const in metadata.em_asm_consts.items():
701701
body = trim_asm_const_body(const)
702-
args = []
703702
max_arity = 16
704703
arity = 0
705704
for i in range(max_arity):
706-
if ('$' + str(i)) in const:
705+
if f'${i}' in const:
707706
arity = i + 1
708-
for i in range(arity):
709-
args.append('$' + str(i))
710-
args = ', '.join(args)
707+
args = ', '.join(f'${i}' for i in range(arity))
711708
if 'arguments' in body:
712709
# arrow functions don't bind `arguments` so we have to use
713710
# the old function syntax in this case
@@ -717,8 +714,7 @@ def create_asm_consts(metadata):
717714
if settings.RELOCATABLE:
718715
addr += settings.GLOBAL_BASE
719716
asm_consts[addr] = func
720-
asm_consts = [(key, value) for key, value in asm_consts.items()]
721-
asm_consts.sort()
717+
asm_consts = sorted(asm_consts.items())
722718
return asm_consts
723719

724720

@@ -836,10 +832,8 @@ def add_standard_wasm_imports(send_items_map):
836832

837833
def create_sending(metadata, library_symbols):
838834
# Map of wasm imports to mangled/external/JS names
839-
send_items_map = {}
835+
send_items_map = {name: name for name in metadata.invoke_funcs}
840836

841-
for name in metadata.invoke_funcs:
842-
send_items_map[name] = name
843837
for name in metadata.imports:
844838
if name in metadata.em_js_funcs:
845839
send_items_map[name] = name
@@ -903,9 +897,7 @@ def install_wrapper(sym):
903897
# pthread_self and _emscripten_proxy_execute_task_queue are currently called in some
904898
# cases after the runtime has exited.
905899
# TODO: Look into removing these, and improving our robustness around thread termination.
906-
if sym in ('__trap', 'pthread_self', '_emscripten_proxy_execute_task_queue'):
907-
return False
908-
return True
900+
return sym not in {'__trap', 'pthread_self', '_emscripten_proxy_execute_task_queue'}
909901

910902
for name, types in function_exports.items():
911903
nargs = len(types.params)

tools/experimental/reproduceriter.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@
125125
window_location = sys.argv[4] if len(sys.argv) >= 5 else ''
126126
on_idle = sys.argv[5] if len(sys.argv) >= 6 else ''
127127

128-
shell = not not window_location
128+
shell = bool(window_location)
129129

130130
dirs_to_drop = 0 if not os.path.dirname(first_js) else len(os.path.dirname(first_js).split('/'))
131131

tools/file_packager.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -172,10 +172,7 @@ def should_ignore(fullname):
172172
if has_hidden_attribute(fullname):
173173
return True
174174

175-
for p in excluded_patterns:
176-
if fnmatch.fnmatch(fullname, p):
177-
return True
178-
return False
175+
return any(fnmatch.fnmatch(fullname, p) for p in excluded_patterns)
179176

180177

181178
def add(mode, rootpathsrc, rootpathdst):

tools/js_optimizer.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -330,9 +330,7 @@ def write_chunk(chunk, i):
330330

331331
with ToolchainProfiler.profile_block('sort_or_concat'):
332332
# sort functions by size, to make diffing easier and to improve aot times
333-
funcses = []
334-
for out_file in filenames:
335-
funcses.append(split_funcs(utils.read_file(out_file)))
333+
funcses = [split_funcs(utils.read_file(out_file)) for out_file in filenames]
336334
funcs = [item for sublist in funcses for item in sublist]
337335
funcses = None
338336
if not os.environ.get('EMCC_NO_OPT_SORT'):

tools/link.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ def will_metadce():
166166
def setup_environment_settings():
167167
# Environment setting based on user input
168168
environments = settings.ENVIRONMENT.split(',')
169-
if any([x for x in environments if x not in VALID_ENVIRONMENTS]):
169+
if any(x for x in environments if x not in VALID_ENVIRONMENTS):
170170
exit_with_error(f'Invalid environment specified in "ENVIRONMENT": {settings.ENVIRONMENT}. Should be one of: {",".join(VALID_ENVIRONMENTS)}')
171171

172172
settings.ENVIRONMENT_MAY_BE_WEB = not settings.ENVIRONMENT or 'web' in environments
@@ -216,8 +216,8 @@ def get_js_sym_info():
216216
# and can contain full paths to temporary files.
217217
skip_settings = {'PRE_JS_FILES', 'POST_JS_FILES'}
218218
input_files = [json.dumps(settings.external_dict(skip_keys=skip_settings), sort_keys=True, indent=2)]
219-
for jslib in sorted(glob.glob(utils.path_from_root('src') + '/library*.js')):
220-
input_files.append(read_file(jslib))
219+
jslibs = glob.glob(utils.path_from_root('src') + '/library*.js')
220+
input_files.extend(read_file(jslib) for jslib in sorted(jslibs))
221221
for jslib in settings.JS_LIBRARIES:
222222
if not os.path.isabs(jslib):
223223
jslib = utils.path_from_root('src', jslib)
@@ -622,7 +622,7 @@ def check_browser_versions():
622622

623623
if settings.LEGACY_VM_SUPPORT:
624624
# Default all browser versions to zero
625-
for key in min_version_settings.keys():
625+
for key in min_version_settings:
626626
default_setting(key, 0)
627627

628628
for key, oldest in min_version_settings.items():
@@ -964,9 +964,8 @@ def phase_linker_setup(options, state, newargs):
964964
if settings.MINIMAL_RUNTIME_STREAMING_WASM_COMPILATION and settings.MINIMAL_RUNTIME_STREAMING_WASM_INSTANTIATION:
965965
exit_with_error('MINIMAL_RUNTIME_STREAMING_WASM_COMPILATION and MINIMAL_RUNTIME_STREAMING_WASM_INSTANTIATION are mutually exclusive!')
966966

967-
if options.emrun:
968-
if settings.MINIMAL_RUNTIME:
969-
exit_with_error('--emrun is not compatible with MINIMAL_RUNTIME')
967+
if options.emrun and settings.MINIMAL_RUNTIME:
968+
exit_with_error('--emrun is not compatible with MINIMAL_RUNTIME')
970969

971970
if options.use_closure_compiler:
972971
settings.USE_CLOSURE_COMPILER = 1
@@ -2939,7 +2938,7 @@ def process_dynamic_libs(dylibs, lib_dirs):
29392938
dylibs += extras
29402939
for dylib in dylibs:
29412940
exports = webassembly.get_exports(dylib)
2942-
exports = set(e.name for e in exports)
2941+
exports = {e.name for e in exports}
29432942
# EM_JS function are exports with a special prefix. We need to strip
29442943
# this prefix to get the actual symbol name. For the main module, this
29452944
# is handled by extract_metadata.py.
@@ -2953,7 +2952,7 @@ def process_dynamic_libs(dylibs, lib_dirs):
29532952
# TODO(sbc): Integrate with metadata.invoke_funcs that comes from the
29542953
# main module to avoid creating new invoke functions at runtime.
29552954
imports = set(imports)
2956-
imports = set(i for i in imports if not i.startswith('invoke_'))
2955+
imports = {i for i in imports if not i.startswith('invoke_')}
29572956
weak_imports = webassembly.get_weak_imports(dylib)
29582957
strong_imports = sorted(imports.difference(weak_imports))
29592958
logger.debug('Adding symbols requirements from `%s`: %s', dylib, imports)

0 commit comments

Comments
 (0)