Skip to content

Commit edff17e

Browse files
committed
Ruff rules for comprehensions, performance, and simplicity
1 parent 06cebfc commit edff17e

22 files changed

+69
-134
lines changed

tools/building.py

Lines changed: 9 additions & 13 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')
@@ -426,10 +425,7 @@ def eval_ctors(js_file, wasm_file, debug_info):
426425
if kept_ctors:
427426
args += ['--kept-exports=' + ','.join(kept_ctors)]
428427
else:
429-
if settings.EXPECT_MAIN:
430-
ctor = '_start'
431-
else:
432-
ctor = '_initialize'
428+
ctor = '_start' if settings.EXPECT_MAIN else '_initialize'
433429
args = ['--ctors=' + ctor, '--kept-exports=' + ctor]
434430
if settings.EVAL_CTORS == 2:
435431
args += ['--ignore-external-input']
@@ -749,10 +745,10 @@ def minify_wasm_js(js_file, wasm_file, expensive_optimizations, debug_info):
749745

750746

751747
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'])
748+
internal_start_stop_symbols = {'__start_em_asm', '__stop_em_asm',
749+
'__start_em_js', '__stop_em_js',
750+
'__start_em_lib_deps', '__stop_em_lib_deps',
751+
'__em_lib_deps'}
756752
internal_prefixes = ('__em_js__', '__em_lib_deps')
757753
return name in internal_start_stop_symbols or any(name.startswith(p) for p in internal_prefixes)
758754

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/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/feature_matrix.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -106,16 +106,16 @@ def report_missing(setting_name):
106106
setting_value = getattr(settings, setting_name)
107107
logger.debug(f'cannot use {feature.name} because {setting_name} is too old: {setting_value}')
108108

109-
if settings.MIN_CHROME_VERSION < min_versions['chrome']:
109+
if min_versions['chrome'] > settings.MIN_CHROME_VERSION:
110110
report_missing('MIN_CHROME_VERSION')
111111
return False
112-
if settings.MIN_FIREFOX_VERSION < min_versions['firefox']:
112+
if min_versions['firefox'] > settings.MIN_FIREFOX_VERSION:
113113
report_missing('MIN_FIREFOX_VERSION')
114114
return False
115-
if settings.MIN_SAFARI_VERSION < min_versions['safari']:
115+
if min_versions['safari'] > settings.MIN_SAFARI_VERSION:
116116
report_missing('MIN_SAFARI_VERSION')
117117
return False
118-
if 'node' in min_versions and settings.MIN_NODE_VERSION < min_versions['node']:
118+
if 'node' in min_versions and min_versions['node'] > settings.MIN_NODE_VERSION:
119119
report_missing('MIN_NODE_VERSION')
120120
return False
121121
return True

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: 7 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,7 @@ 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+
input_files.extend(read_file(jslib) for jslib in sorted(glob.glob(utils.path_from_root('src') + '/library*.js')))
221220
for jslib in settings.JS_LIBRARIES:
222221
if not os.path.isabs(jslib):
223222
jslib = utils.path_from_root('src', jslib)
@@ -626,7 +625,7 @@ def check_browser_versions():
626625

627626
if settings.LEGACY_VM_SUPPORT:
628627
# Default all browser versions to zero
629-
for key in min_version_settings.keys():
628+
for key in min_version_settings:
630629
default_setting(key, 0)
631630

632631
for key, oldest in min_version_settings.items():
@@ -967,9 +966,8 @@ def phase_linker_setup(options, state, newargs):
967966
if settings.MINIMAL_RUNTIME_STREAMING_WASM_COMPILATION and settings.MINIMAL_RUNTIME_STREAMING_WASM_INSTANTIATION:
968967
exit_with_error('MINIMAL_RUNTIME_STREAMING_WASM_COMPILATION and MINIMAL_RUNTIME_STREAMING_WASM_INSTANTIATION are mutually exclusive!')
969968

970-
if options.emrun:
971-
if settings.MINIMAL_RUNTIME:
972-
exit_with_error('--emrun is not compatible with MINIMAL_RUNTIME')
969+
if options.emrun and settings.MINIMAL_RUNTIME:
970+
exit_with_error('--emrun is not compatible with MINIMAL_RUNTIME')
973971

974972
if options.use_closure_compiler:
975973
settings.USE_CLOSURE_COMPILER = 1
@@ -2943,7 +2941,7 @@ def process_dynamic_libs(dylibs, lib_dirs):
29432941
dylibs += extras
29442942
for dylib in dylibs:
29452943
exports = webassembly.get_exports(dylib)
2946-
exports = set(e.name for e in exports)
2944+
exports = {e.name for e in exports}
29472945
# EM_JS function are exports with a special prefix. We need to strip
29482946
# this prefix to get the actual symbol name. For the main module, this
29492947
# is handled by extract_metadata.py.
@@ -2957,7 +2955,7 @@ def process_dynamic_libs(dylibs, lib_dirs):
29572955
# TODO(sbc): Integrate with metadata.invoke_funcs that comes from the
29582956
# main module to avoid creating new invoke functions at runtime.
29592957
imports = set(imports)
2960-
imports = set(i for i in imports if not i.startswith('invoke_'))
2958+
imports = {i for i in imports if not i.startswith('invoke_')}
29612959
weak_imports = webassembly.get_weak_imports(dylib)
29622960
strong_imports = sorted(imports.difference(weak_imports))
29632961
logger.debug('Adding symbols requirements from `%s`: %s', dylib, imports)

0 commit comments

Comments
 (0)