From 55113943ff49fa2fdecc5158dfea5aa252227b36 Mon Sep 17 00:00:00 2001 From: Sam Clegg Date: Sat, 16 May 2026 13:12:24 -0700 Subject: [PATCH] Add some more ruff checks. NFC --- emar.py | 2 +- embuilder.py | 3 ++- emcc.py | 8 +++--- emranlib.py | 2 +- emscan-deps.py | 2 +- emstrip.py | 2 +- pyproject.toml | 8 ++++++ site/source/get_api_items.py | 2 +- site/source/get_wiki.py | 2 +- test/benchmark/benchmark_sse.py | 2 +- test/browser_common.py | 4 +-- test/runner.py | 2 +- test/sockets/socket_relay.py | 2 +- test/test_benchmark.py | 3 ++- test/test_browser.py | 16 ++++++------ test/test_closure_args_port.py | 2 +- test/test_codesize.py | 18 ++++++------- test/test_core.py | 4 +-- test/test_other.py | 27 ++++++++++--------- test/test_sanity.py | 8 +++--- test/test_sockets.py | 30 +++++++++++----------- test/websocket/tcp_echo_server.py | 2 +- tools/building.py | 30 ++++++++++------------ tools/cmdline.py | 2 +- tools/compile.py | 2 +- tools/config.py | 6 ++--- tools/emcoverage.py | 4 +-- tools/emdwp.py | 2 +- tools/emnm.py | 2 +- tools/emscripten.py | 10 ++++---- tools/emsymbolizer.py | 2 +- tools/extract_metadata.py | 14 +++++----- tools/gen_struct_info.py | 27 +++++++++---------- tools/js_optimizer.py | 6 ++--- tools/link.py | 6 ++--- tools/maint/check_for_unused_test_files.py | 2 +- tools/maint/create_dom_pk_codes.py | 2 -- tools/maint/gen_sig_info.py | 4 +-- tools/ports/__init__.py | 4 +-- tools/shared.py | 8 +++--- tools/system_libs.py | 2 ++ tools/webidl_binder.py | 1 - 42 files changed, 148 insertions(+), 139 deletions(-) diff --git a/emar.py b/emar.py index 295f853d2b3d1..593dc547509d0 100755 --- a/emar.py +++ b/emar.py @@ -10,4 +10,4 @@ from tools import shared -shared.exec_process([shared.LLVM_AR] + sys.argv[1:]) +shared.exec_process([shared.LLVM_AR, *sys.argv[1:]]) diff --git a/embuilder.py b/embuilder.py index 46f88d93132fe..9a2ec2953ad00 100755 --- a/embuilder.py +++ b/embuilder.py @@ -101,7 +101,8 @@ # Additional tasks on top of MINIMAL_TASKS that are necessary for PIC testing on # CI (which has slightly more tests than other modes that want to use MINIMAL) -MINIMAL_PIC_TASKS = MINIMAL_TASKS + [ +MINIMAL_PIC_TASKS = [ + *MINIMAL_TASKS, 'libc-mt', 'libc_optz-mt', 'libc_optz-mt-debug', diff --git a/emcc.py b/emcc.py index 9d3d45d0686d6..f770f4a539b06 100644 --- a/emcc.py +++ b/emcc.py @@ -187,7 +187,7 @@ def main(args): if len(args) == 2 and args[1] == '-v': # autoconf likes to see 'GNU' in the output to enable shared object support print(cmdline.version_string(), file=sys.stderr) - return shared.check_call([clang, '-v'] + compile.get_target_flags(), check=False).returncode + return shared.check_call([clang, '-v', *compile.get_target_flags()], check=False).returncode # Additional compiler flags that we treat as if they were passed to us on the # commandline @@ -295,7 +295,7 @@ def main(args): phase_setup(state) if '-print-resource-dir' in args or any(a.startswith('--print-prog-name') for a in args): - shared.exec_process([clang] + compile.get_cflags(tuple(args)) + args) + shared.exec_process([clang, *compile.get_cflags(tuple(args)), *args]) assert False, 'exec_process should not return' if '--cflags' in args: @@ -314,7 +314,7 @@ def main(args): linker_args = separate_linker_flags(newargs)[1] linker_args = [f.value for f in linker_args] # Delay import of link.py to avoid processing this file when only compiling - from tools import link # noqa: PLC0415 + from tools import link link.run_post_link(options.input_files[0], options, linker_args) return 0 @@ -542,7 +542,7 @@ def compile_source_file(input_file): cmd = get_clang_command() if ext == '.pcm': cmd = [c for c in cmd if not c.startswith('-fprebuilt-module-path=')] - cmd += compile_args + ['-c', input_file, '-o', output_file] + cmd += [*compile_args, '-c', input_file, '-o', output_file] if options.requested_debug == '-gsplit-dwarf': # When running in COMPILE_AND_LINK mode we compile objects to a temporary location # but we want the `.dwo` file to be generated in the current working directory, diff --git a/emranlib.py b/emranlib.py index 7a3807f8eaf6b..fc1367886a52a 100755 --- a/emranlib.py +++ b/emranlib.py @@ -14,4 +14,4 @@ from tools import shared -shared.exec_process([shared.LLVM_RANLIB] + sys.argv[1:]) +shared.exec_process([shared.LLVM_RANLIB, *sys.argv[1:]]) diff --git a/emscan-deps.py b/emscan-deps.py index 99ddb59726674..8c49771dbbad8 100755 --- a/emscan-deps.py +++ b/emscan-deps.py @@ -21,4 +21,4 @@ # Add any clang flags that emcc would add. newargs += compile.get_cflags(tuple(argv)) -shared.exec_process([shared.CLANG_SCAN_DEPS] + newargs) +shared.exec_process([shared.CLANG_SCAN_DEPS, *newargs]) diff --git a/emstrip.py b/emstrip.py index 66bbce6b74247..7df6bf33412d7 100755 --- a/emstrip.py +++ b/emstrip.py @@ -29,7 +29,7 @@ def run(): continue new_args.append(arg) - shared.exec_process([llvm_strip] + new_args) + shared.exec_process([llvm_strip, *new_args]) if __name__ == '__main__': diff --git a/pyproject.toml b/pyproject.toml index e0d37a0915848..84204790c2ddc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,4 +1,5 @@ [project] +name = "emscripten" requires-python = ">=3.10" [tool.ruff] @@ -34,6 +35,7 @@ lint.select = [ "PL", "UP", "W", + "RUF", "YTT", ] lint.external = [ "D" ] @@ -76,6 +78,11 @@ lint.ignore = [ "PLW0603", "PLW1510", "PLW2901", + "RUF012", # https://docs.astral.sh/ruff/rules/mutable-class-default/ + "RUF015", # https://docs.astral.sh/ruff/rules/unnecessary-iterable-allocation-for-first-element/ + "RUF027", # https://docs.astral.sh/ruff/rules/missing-f-string-syntax/ + "RUF039", # https://docs.astral.sh/ruff/rules/unraw-re-pattern/ + "RUF067", # https://docs.astral.sh/ruff/rules/non-empty-init-module/ "UP030", # TODO "UP031", # TODO "UP032", # TODO @@ -84,6 +91,7 @@ lint.per-file-ignores."tools/ports/*.py" = [ "ARG001", "ARG005" ] lint.per-file-ignores."test/other/ports/*.py" = [ "ARG001" ] lint.per-file-ignores."test/parallel_testsuite.py" = [ "ARG002" ] lint.per-file-ignores."test/test_benchmark.py" = [ "ARG002" ] +lint.per-file-ignores."test/*.py" = [ "RUF005" ] lint.mccabe.max-complexity = 51 # Recommended: 10 lint.pylint.allow-magic-value-types = [ "bytes", diff --git a/site/source/get_api_items.py b/site/source/get_api_items.py index b5a83882fdb6c..ff56b5875ca0b 100755 --- a/site/source/get_api_items.py +++ b/site/source/get_api_items.py @@ -87,7 +87,7 @@ def exportItems(): def main(): parser = optparse.OptionParser(usage="Usage: %prog [options] version") parser.add_option("-s", "--siteapi", dest="siteapi", default="http://www.developer.nokia.com/Community/Wiki/api.php", help="Location of API") - (options, args) = parser.parse_args() + _options, _args = parser.parse_args() # print 'Site: %s' % options.siteapi parseFiles() exportItems() diff --git a/site/source/get_wiki.py b/site/source/get_wiki.py index 4703133a8bc63..3ecb31187b320 100755 --- a/site/source/get_wiki.py +++ b/site/source/get_wiki.py @@ -197,7 +197,7 @@ def fixcodemarkuplinks(matchobj): def main(): parser = optparse.OptionParser(version="%prog 0.1.1", usage="Usage: %prog [options] version") parser.add_option("-c", "--clonewiki", action="store_true", default=False, dest="clonewiki", help="Clean and clone the latest wiki") - options, args = parser.parse_args() + options = parser.parse_args()[0] print('Clone wiki: %s' % options.clonewiki) if options.clonewiki: diff --git a/test/benchmark/benchmark_sse.py b/test/benchmark/benchmark_sse.py index 6da83958f7b5b..b09226372ceb1 100644 --- a/test/benchmark/benchmark_sse.py +++ b/test/benchmark/benchmark_sse.py @@ -63,7 +63,7 @@ def run_benchmark(benchmark_file, results_file, build_args): print('wasm_results', wasm_results) def strip_comments(text): - return re.sub(r'//.*?\n|/\*.*?\*/', '', text, flags=re.S) # noqa + return re.sub(r'//.*?\n|/\*.*?\*/', '', text, flags=re.S) benchmark_results = strip_comments(wasm_results) print('stripped', benchmark_results) diff --git a/test/browser_common.py b/test/browser_common.py index 310b8a22ebdb5..97d0a55d5f2e1 100644 --- a/test/browser_common.py +++ b/test/browser_common.py @@ -729,7 +729,7 @@ def browser_open(cls, url): if hasattr(config, 'launch_prefix'): browser_args = list(config.launch_prefix) + browser_args - logger.info('Launching browser: %s', str(browser_args)) + logger.info(f'Launching browser: {browser_args}') if (WINDOWS and is_firefox()) or is_safari(): cls.launch_browser_harness_with_proc_snapshot_workaround(parallel_harness, config, browser_args, url) @@ -872,7 +872,7 @@ def run_browser(self, html_file, expected=None, message=None, timeout=None, extr output = self.harness_out_queue.get(block=True, timeout=timeout) except queue.Empty: BrowserCore.unresponsive_tests += 1 - print(f'[unresponsive test: {self.id()} total unresponsive={str(BrowserCore.unresponsive_tests)}]') + print(f'[unresponsive test: {self.id()} total unresponsive={BrowserCore.unresponsive_tests}]') self.browser_restart() # Rather than fail the test here, let fail on the `assertContained` so # that the test can be retried via `extra_tries` diff --git a/test/runner.py b/test/runner.py index 7bdde5e96945b..400e605575485 100755 --- a/test/runner.py +++ b/test/runner.py @@ -460,7 +460,7 @@ def run_tests(options, suite): if utils.get_env_bool('CI'): # output fd must remain open until after testRunner.run() below output = open('out/test-results.xml', 'wb') - import xmlrunner # type: ignore # noqa: PLC0415 + import xmlrunner # type: ignore testRunner = xmlrunner.XMLTestRunner(output=output, verbosity=2, failfast=options.failfast) print('Writing XML test output to ' + os.path.abspath(output.name)) diff --git a/test/sockets/socket_relay.py b/test/sockets/socket_relay.py index 8a64a4db4c00d..77db9eb37ab03 100644 --- a/test/sockets/socket_relay.py +++ b/test/sockets/socket_relay.py @@ -35,7 +35,7 @@ def run(self): s.bind(('127.0.0.1', port)) s.listen(1) print('listener', port, 'waiting for connection') - conn, addr = s.accept() + conn, _addr = s.accept() self.conn = conn while True: time.sleep(0.5) diff --git a/test/test_benchmark.py b/test/test_benchmark.py index 57487d39ccf5f..40eaa24a5f6b4 100644 --- a/test/test_benchmark.py +++ b/test/test_benchmark.py @@ -422,7 +422,8 @@ def setUpClass(cls): pass try: with common.chdir(os.path.expanduser('~/Dev/mozilla-central')): - fingerprint.append('sm: ' + [line for line in run_process(['hg', 'tip'], stdout=PIPE).stdout.splitlines() if 'changeset' in line][0]) + hg_tip = run_process(['hg', 'tip'], stdout=PIPE).stdout + fingerprint.append('sm: ' + next(line for line in hg_tip.splitlines() if 'changeset' in line)) except Exception: pass fingerprint.append('llvm: ' + config.LLVM_ROOT) diff --git a/test/test_browser.py b/test/test_browser.py index 88451046627aa..64880f2bb3fc6 100644 --- a/test/test_browser.py +++ b/test/test_browser.py @@ -1750,9 +1750,9 @@ def book_path(path): for image in images: cflags += ['--preload-file', f'{book_path(image)}@{os.path.basename(image)}'] - lib = [l for l in libs if program in os.path.basename(l)][0] + libs = [l for l in libs if program in os.path.basename(l)] - self.reftest(lib, book_path(program.replace('.o', '.png')), cflags=cflags) + self.reftest(libs[0], book_path(program.replace('.o', '.png')), cflags=cflags) @requires_graphics_hardware @parameterized({ @@ -3292,12 +3292,12 @@ def test_async_iostream(self): # ASYNCIFY_IMPORTS. # To make the test more precise we also use ASYNCIFY_IGNORE_INDIRECT here. @parameterized({ - '': (['-sASYNCIFY_IMPORTS=sync_tunnel,sync_tunnel_bool'],), # noqa - 'pattern_imports': (['-sASYNCIFY_IMPORTS=[sync_tun*]'],), # noqa - 'response': (['-sASYNCIFY_IMPORTS=@filey.txt'],), # noqa - 'nothing': (['-DBAD'],), # noqa - 'empty_list': (['-DBAD', '-sASYNCIFY_IMPORTS=[]'],), # noqa - 'em_js_bad': (['-DBAD', '-DUSE_EM_JS'],), # noqa + '': (['-sASYNCIFY_IMPORTS=sync_tunnel,sync_tunnel_bool'],), + 'pattern_imports': (['-sASYNCIFY_IMPORTS=[sync_tun*]'],), + 'response': (['-sASYNCIFY_IMPORTS=@filey.txt'],), + 'nothing': (['-DBAD'],), + 'empty_list': (['-DBAD', '-sASYNCIFY_IMPORTS=[]'],), + 'em_js_bad': (['-DBAD', '-DUSE_EM_JS'],), }) def test_async_returnvalue(self, args): if '@' in str(args): diff --git a/test/test_closure_args_port.py b/test/test_closure_args_port.py index 7278d136212f3..07f6463667a58 100644 --- a/test/test_closure_args_port.py +++ b/test/test_closure_args_port.py @@ -5,7 +5,7 @@ def get(ports, settings, shared): # noqa: ARG001 return [] -def clear(ports, settings, shared): # noqa: ARG001 +def clear(ports, settings, shared): pass diff --git a/test/test_codesize.py b/test/test_codesize.py index 8a189971ee769..5117273b236a4 100644 --- a/test/test_codesize.py +++ b/test/test_codesize.py @@ -303,9 +303,9 @@ def strip_numeric_suffixes(funcname): 'O1': (['-O1'],), 'O2': (['-O2'],), # in -O3, -Os and -Oz we metadce, and they shrink it down to the minimal output we want - 'O3': (['-O3'],), # noqa - 'Os': (['-Os'],), # noqa - 'Oz': (['-Oz'],), # noqa + 'O3': (['-O3'],), + 'Os': (['-Os'],), + 'Oz': (['-Oz'],), 'Os_mr': (['-Os', '-sMINIMAL_RUNTIME'],), # EVAL_CTORS also removes the __wasm_call_ctors function 'Oz-ctors': (['-Oz', '-sEVAL_CTORS'],), @@ -328,11 +328,11 @@ def test_codesize_minimal_pthreads(self, args): self.run_codesize_test('minimal_main.c', ['-Oz', '-pthread', '-sPROXY_TO_PTHREAD', '-sSTRICT'] + args) @parameterized({ - 'noexcept': (['-O2'],), # noqa + 'noexcept': (['-O2'],), # exceptions increases code size significantly - 'except': (['-O2', '-fexceptions'],), # noqa + 'except': (['-O2', '-fexceptions'],), # exceptions does not pull in demangling by default, which increases code size - 'mangle': (['-O2', '-fexceptions', '-sEXPORTED_FUNCTIONS=_main,_free,___cxa_demangle', '-Wno-deprecated'],), # noqa + 'mangle': (['-O2', '-fexceptions', '-sEXPORTED_FUNCTIONS=_main,_free,___cxa_demangle', '-Wno-deprecated'],), # Wasm EH's code size increase is smaller than that of Emscripten EH 'except_wasm': (['-O2', '-fwasm-exceptions', '-sWASM_LEGACY_EXCEPTIONS=0'],), 'except_wasm_legacy': (['-O2', '-fwasm-exceptions', '-sWASM_LEGACY_EXCEPTIONS'],), @@ -386,7 +386,7 @@ def test_codesize_hello(self, args, kwargs={}): # noqa 'O3_grow_standalone': ('mem.c', ['-O3', '-sALLOW_MEMORY_GROWTH', '-sSTANDALONE_WASM']), # without argc/argv, no support code for them is emitted, even with lto 'O3_standalone_narg_flto': - ('mem_no_argv.c', ['-O3', '-sSTANDALONE_WASM', '-flto']), # noqa + ('mem_no_argv.c', ['-O3', '-sSTANDALONE_WASM', '-flto']), }) def test_codesize_mem(self, filename, args): self.run_codesize_test(filename, args) @@ -400,8 +400,8 @@ def test_codesize_libcxxabi_message(self, args): self.run_codesize_test('libcxxabi_message.cpp', args) @parameterized({ - 'js_fs': (['-O3', '-sNO_WASMFS'],), # noqa - 'wasmfs': (['-O3', '-sWASMFS'],), # noqa + 'js_fs': (['-O3', '-sNO_WASMFS'],), + 'wasmfs': (['-O3', '-sWASMFS'],), }) def test_codesize_files(self, args): self.run_codesize_test('files.cpp', args) diff --git a/test/test_core.py b/test/test_core.py index 83c269119001f..c0fa0736b390c 100644 --- a/test/test_core.py +++ b/test/test_core.py @@ -8028,7 +8028,7 @@ def test_dwarf(self): self.assertIn((8, 3), src_to_addr) def get_dwarf_addr(line, col): - addrs = src_to_addr[(line, col)] + addrs = src_to_addr[line, col] # we assume the simple calls have one address self.assertEqual(len(addrs), 1) return int(addrs[0], 0) @@ -10008,4 +10008,4 @@ def setUp(self): jsmathz = make_run('jsmathz', cflags=['-Oz'], settings={'JS_MATH': 1}) # TestCoreBase is just a shape for the specific subclasses, we don't test it itself -del TestCoreBase # noqa +del TestCoreBase diff --git a/test/test_other.py b/test/test_other.py index 5d0bb9df58e1c..fd278b852d4d9 100644 --- a/test/test_other.py +++ b/test/test_other.py @@ -3,7 +3,6 @@ # University of Illinois/NCSA Open Source License. Both these licenses can be # found in the LICENSE file. -# noqa: E241 import glob import importlib @@ -338,7 +337,7 @@ def run_on_pty(self, cmd): with env_modify({'TERM': 'xterm-color'}): proc = subprocess.Popen(cmd, stdout=slave, stderr=slave) while proc.poll() is None: - r, w, x = select.select([master], [], [], 1) + r, _w, _x = select.select([master], [], [], 1) if r: output.append(os.read(master, 1024)) return (proc.returncode, b''.join(output)) @@ -9513,10 +9512,10 @@ def test_pthreads_growth_and_unsigned(self): read_file('a.out.js')) @parameterized({ - '': ([],), # noqa - 'O3': (['-O3'],), # noqa - 'closure': (['--closure=1'],), # noqa - 'closure_O3': (['--closure=1', '-O3'],), # noqa + '': ([],), + 'O3': (['-O3'],), + 'closure': (['--closure=1'],), + 'closure_O3': (['--closure=1', '-O3'],), }) def test_EM_ASM_ES6(self, args): create_file('src.c', r''' @@ -10769,14 +10768,14 @@ def test_no_excessive_invoke_functions_are_generated_when_exceptions_are_enabled self.assertNotContained('invoke_v', output) @parameterized({ - 'O0': (False, ['-O0']), # noqa - 'O0_emit': (True, ['-O0', '-sEMIT_EMSCRIPTEN_LICENSE']), # noqa - 'O2': (False, ['-O2']), # noqa - 'O2_emit': (True, ['-O2', '-sEMIT_EMSCRIPTEN_LICENSE']), # noqa - 'O2_js_emit': (True, ['-O2', '-sEMIT_EMSCRIPTEN_LICENSE', '-sWASM=0']), # noqa - 'O2_closure': (False, ['-O2', '--closure=1']), # noqa - 'O2_closure_emit': (True, ['-O2', '-sEMIT_EMSCRIPTEN_LICENSE', '--closure=1']), # noqa - 'O2_closure_js_emit': (True, ['-O2', '-sEMIT_EMSCRIPTEN_LICENSE', '--closure=1', '-sWASM=0']), # noqa + 'O0': (False, ['-O0']), + 'O0_emit': (True, ['-O0', '-sEMIT_EMSCRIPTEN_LICENSE']), + 'O2': (False, ['-O2']), + 'O2_emit': (True, ['-O2', '-sEMIT_EMSCRIPTEN_LICENSE']), + 'O2_js_emit': (True, ['-O2', '-sEMIT_EMSCRIPTEN_LICENSE', '-sWASM=0']), + 'O2_closure': (False, ['-O2', '--closure=1']), + 'O2_closure_emit': (True, ['-O2', '-sEMIT_EMSCRIPTEN_LICENSE', '--closure=1']), + 'O2_closure_js_emit': (True, ['-O2', '-sEMIT_EMSCRIPTEN_LICENSE', '--closure=1', '-sWASM=0']), }) def test_emscripten_license(self, expect_license, args): # fastcomp does not support the new license flag diff --git a/test/test_sanity.py b/test/test_sanity.py index 4b56cf58b5cc1..f71f10d7932de 100644 --- a/test/test_sanity.py +++ b/test/test_sanity.py @@ -543,10 +543,10 @@ def test_emconfig(self): utils.write_file(EM_CONFIG, 'asdfasdfasdfasdf\n') # Test both relative and absolute paths to the config - self.run_process([EMCC, '--em-config', os.path.abspath('custom_config')] + MINIMAL_HELLO_WORLD) + self.run_process([EMCC, '--em-config', os.path.abspath('custom_config'), *MINIMAL_HELLO_WORLD]) self.assertContained('Hello, world!', self.run_js('a.out.js')) - self.run_process([EMCC, '--em-config', 'custom_config'] + MINIMAL_HELLO_WORLD) + self.run_process([EMCC, '--em-config', 'custom_config', *MINIMAL_HELLO_WORLD]) self.assertContained('Hello, world!', self.run_js('a.out.js')) def test_emcc_ports(self): @@ -634,7 +634,7 @@ def test_wacky_env(self): restore_and_set_up() def build(): - return self.check_working([EMCC] + MINIMAL_HELLO_WORLD, '') + return self.check_working([EMCC, *MINIMAL_HELLO_WORLD], '') def test(): self.assertContained('Hello, world!', self.run_js('a.out.js')) @@ -670,7 +670,7 @@ def make_fake(report): def test_with_fake(report, expected): make_fake(report) with env_modify({'EMCC_DEBUG': '1'}): - self.check_working([EMCC] + MINIMAL_HELLO_WORLD + ['-c'], expected) + self.check_working([EMCC, *MINIMAL_HELLO_WORLD, '-c'], expected) test_with_fake('got js backend! JavaScript (asm.js, emscripten) backend', 'LLVM has not been built with the WebAssembly backend') delete_dir(shared.CANONICAL_TEMP_DIR) diff --git a/test/test_sockets.py b/test/test_sockets.py index 3519df48bd848..8226f48df0dd1 100644 --- a/test/test_sockets.py +++ b/test/test_sockets.py @@ -75,7 +75,7 @@ def __init__(self, filename, args, listen_port, do_server_check=True): def __enter__(self): try: - import websockify # type: ignore # noqa: PLC0415 + import websockify # type: ignore except ModuleNotFoundError: raise Exception('Unable to import module websockify. Run "python3 -m pip install websockify" or set environment variable EMTEST_SKIP_PYTHON_DEV_PACKAGES=1 to skip this test.') from None @@ -83,7 +83,7 @@ def __enter__(self): # NOTE empty filename support is a hack to support # the current test_enet if self.filename: - cmd = [CLANG_CC, test_file(self.filename), '-o', 'server', '-DSOCKK=%d' % self.target_port] + clang_native.get_clang_native_args() + self.args + cmd = [CLANG_CC, test_file(self.filename), '-o', 'server', f'-DSOCKK={self.target_port}', *clang_native.get_clang_native_args(), *self.args] print(cmd) run_process(cmd, env=clang_native.get_clang_native_env()) process = Popen([os.path.abspath('server')]) @@ -142,16 +142,16 @@ def __enter__(self): # the ws module is installed global npm_checked if not npm_checked: - child = run_process(config.NODE_JS + ['-e', 'require("ws");'], check=False) + child = run_process([*config.NODE_JS, '-e', 'require("ws");'], check=False) assert child.returncode == 0, '"ws" node module not found. Run "npm install" to obtain Node.js dev dependencies, or set environment variable EMTEST_SKIP_NODE_DEV_PACKAGES=1 to skip this test.' npm_checked = True # compile the server suffix = '.mjs' if '-sEXPORT_ES6' in self.args else '.js' - proc = run_process([EMCC, '-Werror', test_file(self.filename), '-o', 'server' + suffix, f'-DSOCKK={self.listen_port}'] + self.args) + proc = run_process([EMCC, '-Werror', test_file(self.filename), '-o', 'server' + suffix, f'-DSOCKK={self.listen_port}', *self.args]) print('Socket server build: out:', proc.stdout or '', '/ err:', proc.stderr or '') - self.process = Popen(config.NODE_JS + ['server' + suffix]) + self.process = Popen([*config.NODE_JS, 'server' + suffix]) return self def __exit__(self, *args, **kwargs): @@ -177,7 +177,7 @@ def __exit__(self, *args, **kwargs): def NodeJsWebSocketEchoServerProcess(): - return BackgroundServerProcess(config.NODE_JS + [test_file('websocket/nodejs_websocket_echo_server.js')]) + return BackgroundServerProcess([*config.NODE_JS, test_file('websocket/nodejs_websocket_echo_server.js')]) def PythonTcpEchoServerProcess(port): @@ -216,17 +216,17 @@ def test_sockets_echo(self, harness_class, port, args): self.skipTest('requires node ws and EMTEST_SKIP_NODE_DEV_PACKAGES=1') with harness_class(test_file('sockets/test_sockets_echo_server.c'), args, port) as harness: - self.btest_exit('sockets/test_sockets_echo_client.c', cflags=['-DSOCKK=%d' % harness.listen_port] + args) + self.btest_exit('sockets/test_sockets_echo_client.c', cflags=[f'-DSOCKK={harness.listen_port}', *args]) @requires_dev_dependency('ws') def test_sockets_echo_pthreads(self): with CompiledServerHarness(test_file('sockets/test_sockets_echo_server.c'), [], 49161) as harness: - self.btest_exit('sockets/test_sockets_echo_client.c', cflags=['-pthread', '-sPROXY_TO_PTHREAD', '-DSOCKK=%d' % harness.listen_port]) + self.btest_exit('sockets/test_sockets_echo_client.c', cflags=['-pthread', '-sPROXY_TO_PTHREAD', f'-DSOCKK={harness.listen_port}']) @requires_dev_dependency('ws') def test_sdl2_sockets_echo(self): with CompiledServerHarness('sockets/sdl2_net_server.c', ['-sUSE_SDL=2', '-sUSE_SDL_NET=2'], 49164) as harness: - self.btest_exit('sockets/sdl2_net_client.c', cflags=['-sUSE_SDL=2', '-sUSE_SDL_NET=2', '-DSOCKK=%d' % harness.listen_port]) + self.btest_exit('sockets/sdl2_net_client.c', cflags=['-sUSE_SDL=2', '-sUSE_SDL_NET=2', f'-DSOCKK={harness.listen_port}']) @parameterized({ 'websockify': [WebsockifyServerHarness, 49166, ['-DTEST_DGRAM=0']], @@ -245,7 +245,7 @@ def test_sockets_async_echo(self, harness_class, port, args): args.append('-DTEST_ASYNC=1') with harness_class(test_file('sockets/test_sockets_echo_server.c'), args, port) as harness: - self.btest_exit('sockets/test_sockets_echo_client.c', cflags=['-DSOCKK=%d' % harness.listen_port] + args) + self.btest_exit('sockets/test_sockets_echo_client.c', cflags=[f'-DSOCKK={harness.listen_port}', *args]) def test_sockets_async_bad_port(self): # Deliberately attempt a connection on a port that will fail to test the error callback and @@ -276,7 +276,7 @@ def test_sockets_echo_bigdata(self, harness_class, port, args): create_file('test_sockets_echo_bigdata.c', src.replace('#define MESSAGE "pingtothepong"', '#define MESSAGE "%s"' % message)) with harness_class(test_file('sockets/test_sockets_echo_server.c'), args, port) as harness: - self.btest_exit('test_sockets_echo_bigdata.c', cflags=[sockets_include, '-DSOCKK=%d' % harness.listen_port] + args) + self.btest_exit('test_sockets_echo_bigdata.c', cflags=[sockets_include, f'-DSOCKK={harness.listen_port}', *args]) @no_windows('This test is Unix-specific.') @requires_python_dev_packages @@ -287,7 +287,7 @@ def test_sockets_partial(self): CompiledServerHarness(test_file('sockets/test_sockets_partial_server.c'), [], 49181), ]: with harness: - self.btest_exit('sockets/test_sockets_partial_client.c', assert_returncode=165, cflags=['-DSOCKK=%d' % harness.listen_port]) + self.btest_exit('sockets/test_sockets_partial_client.c', assert_returncode=165, cflags=[f'-DSOCKK={harness.listen_port}']) @no_windows('This test is Unix-specific.') @requires_python_dev_packages @@ -322,7 +322,7 @@ def test_enet(self): enet = [self.in_dir('enet', '.libs', 'libenet.a'), '-I' + self.in_dir('enet', 'include')] with CompiledServerHarness(test_file('sockets/test_enet_server.c'), enet, 49210) as harness: - self.btest_exit('sockets/test_enet_client.c', cflags=enet + ['-DSOCKK=%d' % harness.listen_port]) + self.btest_exit('sockets/test_enet_client.c', cflags=[*enet, f'-DSOCKK={harness.listen_port}']) @crossplatform @parameterized({ @@ -342,7 +342,7 @@ def test_nodejs_sockets_echo(self, harness_class, port, args): # Basic test of node client against both a Websockified and compiled echo server. with harness_class(test_file('sockets/test_sockets_echo_server.c'), args, port) as harness: expected = 'do_msg_read: read 14 bytes' - self.do_runf('sockets/test_sockets_echo_client.c', expected, cflags=['-DSOCKK=%d' % harness.listen_port] + args) + self.do_runf('sockets/test_sockets_echo_client.c', expected, cflags=[f'-DSOCKK={harness.listen_port}', *args]) def test_nodejs_sockets_connect_failure(self): self.do_runf('sockets/test_sockets_echo_client.c', r'connect failed: (Connection refused|Host is unreachable)', regex=True, cflags=['-DSOCKK=666'], assert_returncode=NON_ZERO) @@ -392,7 +392,7 @@ def test_nodejs_sockets_echo_subprotocol_runtime(self): @requires_dev_dependency('ws') def test_websocket_send(self, args): with NodeJsWebSocketEchoServerProcess(): - self.btest_exit('websocket/test_websocket_send.c', cflags=['-lwebsocket', '-sNO_EXIT_RUNTIME', '-sWEBSOCKET_DEBUG'] + args) + self.btest_exit('websocket/test_websocket_send.c', cflags=['-lwebsocket', '-sNO_EXIT_RUNTIME', '-sWEBSOCKET_DEBUG', *args]) def test_websocket_new(self): self.btest_exit('websocket/test_websocket_new.c', cflags=['-lwebsocket']) diff --git a/test/websocket/tcp_echo_server.py b/test/websocket/tcp_echo_server.py index 5319d56a8be29..e1fb27f915534 100644 --- a/test/websocket/tcp_echo_server.py +++ b/test/websocket/tcp_echo_server.py @@ -8,7 +8,7 @@ def listen(): s.bind(('0.0.0.0', int(sys.argv[1]))) s.listen(10) while True: - conn, address = s.accept() + conn, _address = s.accept() while True: data = conn.recv(2048) if not data: diff --git a/tools/building.py b/tools/building.py index f05b2f628c99d..f2a60385d353c 100644 --- a/tools/building.py +++ b/tools/building.py @@ -126,7 +126,7 @@ def llvm_backend_args(): @ToolchainProfiler.profile() def link_to_object(args, target): - link_lld(args + ['--relocatable'], target) + link_lld([*args, '--relocatable'], target) def side_module_external_deps(external_symbols): @@ -377,7 +377,7 @@ def acorn_optimizer(filename, passes, extra_info=None, return_output=False, work with open(temp, 'a', encoding='utf-8') as f: f.write('// EXTRA_INFO: ' + json.dumps(extra_info)) filename = temp - cmd = config.NODE_JS + [optimizer, filename] + passes + cmd = [*config.NODE_JS, optimizer, filename, *passes] if not worker_js: # Keep JS code comments intact through the acorn optimization pass so that # JSDoc comments will be carried over to a later Closure run. @@ -557,11 +557,10 @@ def closure_compiler(filename, advanced=True, extra_closure_args=None): # Node.js specific externs if settings.ENVIRONMENT_MAY_BE_NODE: - NODE_EXTERNS_BASE = path_from_root('third_party/closure-compiler/node-externs') - NODE_EXTERNS = os.listdir(NODE_EXTERNS_BASE) - NODE_EXTERNS = [os.path.join(NODE_EXTERNS_BASE, name) for name in NODE_EXTERNS - if name.endswith('.js')] - CLOSURE_EXTERNS += [path_from_root('src/closure-externs/node-externs.js')] + NODE_EXTERNS + node_extern_dir = path_from_root('third_party/closure-compiler/node-externs') + node_externs = os.listdir(node_extern_dir) + node_externs = [os.path.join(node_extern_dir, name) for name in node_externs if name.endswith('.js')] + CLOSURE_EXTERNS += [path_from_root('src/closure-externs/node-externs.js'), *node_externs] # V8/SpiderMonkey shell specific externs if settings.ENVIRONMENT_MAY_BE_SHELL: @@ -571,12 +570,11 @@ def closure_compiler(filename, advanced=True, extra_closure_args=None): # Web environment specific externs if settings.ENVIRONMENT_MAY_BE_WEB or settings.ENVIRONMENT_MAY_BE_WORKER: - BROWSER_EXTERNS_BASE = path_from_root('src/closure-externs/browser-externs') - if os.path.isdir(BROWSER_EXTERNS_BASE): - BROWSER_EXTERNS = os.listdir(BROWSER_EXTERNS_BASE) - BROWSER_EXTERNS = [os.path.join(BROWSER_EXTERNS_BASE, name) for name in BROWSER_EXTERNS - if name.endswith('.js')] - CLOSURE_EXTERNS += BROWSER_EXTERNS + browser_externs_dir = path_from_root('src/closure-externs/browser-externs') + if os.path.isdir(browser_externs_dir): + browser_externs = os.listdir(browser_externs_dir) + browser_externs = [os.path.join(browser_externs_dir, name) for name in browser_externs if name.endswith('.js')] + CLOSURE_EXTERNS += browser_externs if settings.DYNCALLS: CLOSURE_EXTERNS += [path_from_root('src/closure-externs/dyncall-externs.js')] @@ -862,8 +860,8 @@ def metadce(js_file, wasm_file, debug_info, last): if settings.MINIFY_WHITESPACE: passes.append('--minify-whitespace') if DEBUG: - logger.debug("unused_imports: %s", str(unused_imports)) - logger.debug("unused_exports: %s", str(unused_exports)) + logger.debug(f'unused_imports: {unused_imports}') + logger.debug(f'unused_exports: {unused_exports}') extra_info = {'unusedImports': unused_imports, 'unusedExports': unused_exports} return acorn_optimizer(js_file, passes, extra_info=extra_info) @@ -917,7 +915,7 @@ def minify_wasm_imports_and_exports(js_file, wasm_file, minify_exports, debug_in parsed = json.loads(out) for imp in parsed['imports']: # the module name is ignored; we assume no collisions can happen there - module, old, new = imp + _module, old, new = imp assert old not in mapping, 'imports must be unique' mapping[old] = new for exp in parsed['exports']: diff --git a/tools/cmdline.py b/tools/cmdline.py index 2069075a18ffb..1b2f6efd033a1 100644 --- a/tools/cmdline.py +++ b/tools/cmdline.py @@ -159,7 +159,7 @@ def in_directory(root, child): # return true, if the common prefix of both is equal to directory # e.g. /a/b/c/d.rst and directory is /a/b, the common prefix is /a/b - return os.path.commonprefix([root, child]) == root + return os.path.commonpath([root, child]) == root for valid_abspath in options.valid_abspaths: if in_directory(valid_abspath, path_name): diff --git a/tools/compile.py b/tools/compile.py index 37fadfe61b3ac..75329d22de15a 100644 --- a/tools/compile.py +++ b/tools/compile.py @@ -50,7 +50,7 @@ def get_clang_flags(user_args): if '-mbulk-memory' not in user_args: flags.append('-mbulk-memory') - if settings.MAIN_MODULE or settings.SIDE_MODULE and '-fPIC' not in user_args: + if (settings.MAIN_MODULE or settings.SIDE_MODULE) and '-fPIC' not in user_args: flags.append('-fPIC') if settings.MAIN_MODULE or settings.SIDE_MODULE or settings.LINKABLE or '-fPIC' in user_args: diff --git a/tools/config.py b/tools/config.py index 147623070bf4a..a0cba4ee082aa 100644 --- a/tools/config.py +++ b/tools/config.py @@ -197,13 +197,13 @@ def generate_config(path): config_data = '\n'.join(config_data) + '\n' # autodetect some default paths llvm_root = os.path.dirname(shutil.which('wasm-ld') or '/usr/bin/wasm-ld') - config_data = config_data.replace('\'{{{ LLVM_ROOT }}}\'', repr(llvm_root)) + config_data = config_data.replace("'{{{ LLVM_ROOT }}}'", repr(llvm_root)) binaryen_root = os.path.dirname(os.path.dirname(shutil.which('wasm-opt') or '/usr/local/bin/wasm-opt')) - config_data = config_data.replace('\'{{{ BINARYEN_ROOT }}}\'', repr(binaryen_root)) + config_data = config_data.replace("'{{{ BINARYEN_ROOT }}}'", repr(binaryen_root)) node = shutil.which('node') or shutil.which('nodejs') or 'node' - config_data = config_data.replace('\'{{{ NODE }}}\'', repr(node)) + config_data = config_data.replace("'{{{ NODE }}}'", repr(node)) # write utils.write_file(path, config_data) diff --git a/tools/emcoverage.py b/tools/emcoverage.py index 3e90a8b5f5eb9..67175def8bf5c 100755 --- a/tools/emcoverage.py +++ b/tools/emcoverage.py @@ -61,10 +61,10 @@ def main(): if sys.argv[1] in {'html', 'report', 'xml'}: old_argv = sys.argv - sys.argv = ['coverage', 'combine'] + glob(os.path.join(store, '*')) + sys.argv = ['coverage', 'combine', *glob(os.path.join(store, '*'))] with contextlib.suppress(SystemExit): coverage.cmdline.main() - sys.argv = old_argv + ['-i'] + sys.argv = [*old_argv, '-i'] return coverage.cmdline.main() if not os.path.exists(sys.argv[1]): diff --git a/tools/emdwp.py b/tools/emdwp.py index 1700215aaa5d1..9a07a7df5464e 100755 --- a/tools/emdwp.py +++ b/tools/emdwp.py @@ -15,4 +15,4 @@ from tools import shared -shared.exec_process([shared.LLVM_DWP] + sys.argv[1:]) +shared.exec_process([shared.LLVM_DWP, *sys.argv[1:]]) diff --git a/tools/emnm.py b/tools/emnm.py index 025b56f561fe7..1d5c4df9e9f61 100755 --- a/tools/emnm.py +++ b/tools/emnm.py @@ -15,4 +15,4 @@ from tools import shared -shared.exec_process([shared.LLVM_NM] + sys.argv[1:]) +shared.exec_process([shared.LLVM_NM, *sys.argv[1:]]) diff --git a/tools/emscripten.py b/tools/emscripten.py index c801a7465a6e0..51530acacebfa 100644 --- a/tools/emscripten.py +++ b/tools/emscripten.py @@ -125,7 +125,7 @@ def update_settings_glue(wasm_file, metadata, base_metadata): settings.WASM_EXPORTS += ['__asyncify_state', '__asyncify_data'] # start with the MVP features, and add any detected features. - building.binaryen_features = ['--mvp-features'] + metadata.features + building.binaryen_features = ['--mvp-features', *metadata.features] if settings.ASYNCIFY == 2: building.binaryen_features += ['--enable-reference-types'] @@ -403,13 +403,13 @@ def emscript(in_wasm, out_wasm, outfile_js, js_syms, finalize=True, base_metadat # check_call doesn't support the `input` argument. if asm_consts: validate = '\n'.join([f'var tmp = {f};' for _, f in asm_consts]) - proc = subprocess.run(config.NODE_JS + ['--check', '-'], input=validate.encode('utf-8')) + proc = subprocess.run([*config.NODE_JS, '--check', '-'], input=validate.encode('utf-8')) if proc.returncode: exit_with_error(f'EM_ASM function validation failed (node returned {proc.returncode})') if em_js_funcs: validate = '\n'.join(em_js_funcs) - proc = subprocess.run(config.NODE_JS + ['--check', '-'], input=validate.encode('utf-8')) + proc = subprocess.run([*config.NODE_JS, '--check', '-'], input=validate.encode('utf-8')) if proc.returncode: exit_with_error(f'EM_JS function validation failed (node returned {proc.returncode})') @@ -614,7 +614,7 @@ def finalize_wasm(infile, outfile, js_syms): unexpected_exports = [asmjs_mangle(e) for e in unexpected_exports] unexpected_exports = [e for e in unexpected_exports if e not in expected_exports] - if not settings.STANDALONE_WASM and 'main' in metadata.all_exports or '__main_argc_argv' in metadata.all_exports: + if (not settings.STANDALONE_WASM and 'main' in metadata.all_exports) or '__main_argc_argv' in metadata.all_exports: if 'EXPORTED_FUNCTIONS' in user_settings and '_main' not in settings.USER_EXPORTS: # If `_main` was unexpectedly exported we assume it was added to # EXPORT_IF_DEFINED by `phase_linker_setup` in order that we can detect @@ -672,7 +672,7 @@ def create_tsd_exported_runtime_methods(metadata): exit_with_error('tsc executable not found in node_modules or in $PATH') # Use the full path from the which command so windows can find tsc. tsc = [tsc] - cmd = tsc + ['--skipLibCheck', # Avoid checking any of the user's types e.g. node_modules/@types. + cmd = [*tsc, '--skipLibCheck', # Avoid checking any of the user's types e.g. node_modules/@types. '--declaration', '--emitDeclarationOnly', '--allowJs', js_doc_file] diff --git a/tools/emsymbolizer.py b/tools/emsymbolizer.py index 1d505614b4d8f..4b1dc1a3308d1 100755 --- a/tools/emsymbolizer.py +++ b/tools/emsymbolizer.py @@ -318,6 +318,6 @@ def get_args(): try: rv = main(get_args()) except (Error, webassembly.InvalidWasmError, OSError) as e: - print(f'{sys.argv[0]}: {str(e)}', file=sys.stderr) + print(f'{sys.argv[0]}: {e}', file=sys.stderr) rv = 1 sys.exit(rv) diff --git a/tools/extract_metadata.py b/tools/extract_metadata.py index cb79d25f617e4..f9a11ada06ed7 100644 --- a/tools/extract_metadata.py +++ b/tools/extract_metadata.py @@ -3,6 +3,8 @@ # University of Illinois/NCSA Open Source License. Both these licenses can be # found in the LICENSE file. +# ruff:noqa: F841 + import logging from dataclasses import dataclass @@ -17,8 +19,8 @@ def skip_function_header(module): num_local_decls = module.read_uleb() while num_local_decls: - local_count = module.read_uleb() # noqa - local_type = module.read_type() # noqa + local_count = module.read_uleb() + local_type = module.read_type() num_local_decls -= 1 @@ -112,10 +114,10 @@ def parse_function_for_memory_inits(module, func_index, offset_map): memory = module.read_uleb() assert memory == 0 case MemoryOpCode.MEMORY_FILL: - memory = module.read_uleb() # noqa + memory = module.read_uleb() assert memory == 0 case MemoryOpCode.MEMORY_DROP: - segment = module.read_uleb() # noqa + segment = module.read_uleb() case _: assert False, "unknown: %s" % opcode case OpCode.ATOMIC_PREFIX: @@ -130,8 +132,8 @@ def parse_function_for_memory_inits(module, func_index, offset_map): case OpCode.BR_TABLE: count = module.read_uleb() for _ in range(count): - depth = module.read_uleb() # noqa - default = module.read_uleb() # noqa + depth = module.read_uleb() + default = module.read_uleb() case _: assert False, "unknown: %s" % opcode diff --git a/tools/gen_struct_info.py b/tools/gen_struct_info.py index be87f3df7606d..7f6a1ecd4d69a 100755 --- a/tools/gen_struct_info.py +++ b/tools/gen_struct_info.py @@ -156,16 +156,17 @@ def gen_inspect_code(self, path: list[str], struct: list[str | dict]): prefix += path[0] with self.child(path[-1]) as scope: - path_for_sizeof = [f'({prefix}){{}}'] + path[1:] + path_for_sizeof = [f'({prefix}){{}}', *path[1:]] scope.set('__size__', '%zu', f'sizeof ({".".join(path_for_sizeof)})') for field in struct: if isinstance(field, dict): # We have to recurse to inspect the nested dict. fname = list(field.keys())[0] - self.gen_inspect_code(path + [fname], field[fname]) + self.gen_inspect_code([*path, fname], field[fname]) else: - scope.set(field, '%zu', f'offsetof({prefix}, {".".join(path[1:] + [field])})') + member = ".".join([*path[1:], field]) + scope.set(field, '%zu', f'offsetof({prefix}, {member})') def generate_c_code(headers): @@ -208,16 +209,16 @@ def generate_cmd(js_file_path, src_file_path, cflags): compiler = shared.EMCC # -O1+ produces calls to iprintf, which libcompiler_rt doesn't support - cmd = [compiler] + cflags + ['-o', js_file_path, src_file_path, - '-O0', - '-Werror', - '-Wno-format', - '-sBOOTSTRAPPING_STRUCT_INFO', - '-sWASM_ASYNC_COMPILATION=0', - '-sINCOMING_MODULE_JS_API=', - '-sSTRICT', - '-sSUPPORT_LONGJMP=0', - '-sASSERTIONS=0'] + cmd = [compiler, *cflags, '-o', js_file_path, src_file_path, + '-O0', + '-Werror', + '-Wno-format', + '-sBOOTSTRAPPING_STRUCT_INFO', + '-sWASM_ASYNC_COMPILATION=0', + '-sINCOMING_MODULE_JS_API=', + '-sSTRICT', + '-sSUPPORT_LONGJMP=0', + '-sASSERTIONS=0'] # Default behavior for emcc is to warn for binaryen version check mismatches # so we should try to match that behavior. diff --git a/tools/js_optimizer.py b/tools/js_optimizer.py index aa905554e83e1..e6a4dd441801b 100755 --- a/tools/js_optimizer.py +++ b/tools/js_optimizer.py @@ -42,7 +42,7 @@ def get_acorn_cmd(): # Use an 8Mb stack (rather than the ~1Mb default) when running the # js optimizer since larger inputs can cause terser to use a lot of stack. node.append('--stack-size=8192') - return node + [ACORN_OPTIMIZER] + return [*node, ACORN_OPTIMIZER] def split_funcs(js): @@ -97,7 +97,7 @@ def minify_shell(self, shell, minify_whitespace): f.write('\n') f.write('// EXTRA_INFO:' + json.dumps(self.serialize())) - cmd = get_acorn_cmd() + [temp_file, 'minifyGlobals'] + cmd = [*get_acorn_cmd(), temp_file, 'minifyGlobals'] if minify_whitespace: cmd.append('--minify-whitespace') output = utils.run_process(cmd, stdout=subprocess.PIPE).stdout @@ -270,7 +270,7 @@ def write_chunk(chunk, i): filenames = [write_chunk(chunk, i) for i, chunk in enumerate(chunks)] with ToolchainProfiler.profile_block('run_optimizer'): - commands = [get_acorn_cmd() + [f] + passes for f in filenames] + commands = [[*get_acorn_cmd(), f, *passes] for f in filenames] filenames = shared.run_multiple_processes(commands, route_stdout_to_temp_files_suffix='js_opt.jo.js') with ToolchainProfiler.profile_block('split_closure_cleanup'): diff --git a/tools/link.py b/tools/link.py index 70fdfe43a2ce8..58f82cd407338 100644 --- a/tools/link.py +++ b/tools/link.py @@ -2071,7 +2071,7 @@ def phase_source_transforms(options): final_js += '.tr.js' posix = not WINDOWS logger.debug('applying transform: %s', options.js_transform) - shared.check_call(remove_quotes(shlex.split(options.js_transform, posix=posix) + [os.path.abspath(final_js)])) + shared.check_call(remove_quotes([*shlex.split(options.js_transform, posix=posix), os.path.abspath(final_js)])) save_intermediate('transformed') @@ -2542,7 +2542,7 @@ def minify_html(filename): logger.debug(f'minifying HTML file {filename}') size_before = os.path.getsize(filename) - shared.check_call(shared.get_npm_cmd('html-minifier-terser') + [filename, '-o', filename] + opts, env=shared.env_with_node_in_path()) + shared.check_call([*shared.get_npm_cmd('html-minifier-terser'), filename, '-o', filename, *opts], env=shared.env_with_node_in_path()) # HTML minifier will turn all null bytes into an escaped two-byte sequence "\0". Turn those back to single byte sequences. def unescape_nulls(filename): @@ -2989,7 +2989,7 @@ def package_files(options, target): rtn.append(object_file) cmd = building.get_command_with_possible_response_file( - [shared.FILE_PACKAGER, utils.replace_suffix(target, '.data')] + file_args) + [shared.FILE_PACKAGER, utils.replace_suffix(target, '.data'), *file_args]) if options.preload_files: # Preloading files uses --pre-js code that runs before the module is loaded. file_code = shared.check_call(cmd, stdout=PIPE).stdout diff --git a/tools/maint/check_for_unused_test_files.py b/tools/maint/check_for_unused_test_files.py index b52347a3767f5..8cd5c9da4d392 100755 --- a/tools/maint/check_for_unused_test_files.py +++ b/tools/maint/check_for_unused_test_files.py @@ -64,7 +64,7 @@ def check_file(dirpath, filename): return # .out files are live if and only if they live alongside a live source file - if ext == '.out' and os.path.exists(stem + '.cpp') or os.path.exists(stem + '.c'): + if ext == '.out' and (os.path.exists(stem + '.cpp') or os.path.exists(stem + '.c')): return # Files under 'core' can be live if they are find in a `do_core_test` call. diff --git a/tools/maint/create_dom_pk_codes.py b/tools/maint/create_dom_pk_codes.py index 552461e594d81..5a8ccd73647ee 100755 --- a/tools/maint/create_dom_pk_codes.py +++ b/tools/maint/create_dom_pk_codes.py @@ -30,8 +30,6 @@ # Use #include in your code to access these IDs. -# ruff: noqa: E241 - import os import random import sys diff --git a/tools/maint/gen_sig_info.py b/tools/maint/gen_sig_info.py index 0d3829125183c..d1535a31cbe95 100755 --- a/tools/maint/gen_sig_info.py +++ b/tools/maint/gen_sig_info.py @@ -183,7 +183,7 @@ def ignore_symbol(s, cxx): 'stackSave', 'stackRestore', 'stackAlloc', 'getTempRet0', 'setTempRet0', }: return True - return cxx and s == '__asctime_r' or s.startswith('__cxa_find_matching_catch') + return (cxx and s == '__asctime_r') or s.startswith('__cxa_find_matching_catch') def create_c_file(filename, symbol_list, header): @@ -354,7 +354,7 @@ def extract_sig_info(sig_info, extra_settings=None, extra_cflags=None, cxx=False sig_info32 = extract_sigs(symbols, obj_file) # Run the same command again with wasm64. - shared.check_call(cmd + ['-m64']) + shared.check_call([*cmd, '-m64']) sig_info64 = extract_sigs(symbols, obj_file) for sym, sig32 in sig_info32.items(): diff --git a/tools/ports/__init__.py b/tools/ports/__init__.py index 28bfe9f5f4eb2..2506bd48add4e 100644 --- a/tools/ports/__init__.py +++ b/tools/ports/__init__.py @@ -241,7 +241,7 @@ def build_port(src_dir, output_path, port_name, includes=[], flags=[], cxxflags= if ext in {'.c', '.cpp'} and not any((excluded in f) for excluded in exclude_files): srcs.append(os.path.join(root, f)) - cflags = system_libs.get_base_cflags(build_dir) + ['-O2', '-I' + src_dir] + flags + cflags = [*system_libs.get_base_cflags(build_dir), '-O2', '-I' + src_dir, *flags] for include in includes: cflags.append('-I' + include) @@ -260,7 +260,7 @@ def build_port(src_dir, output_path, port_name, includes=[], flags=[], cxxflags= obj = os.path.join(build_dir, relpath) + '.o' dirname = os.path.dirname(obj) os.makedirs(dirname, exist_ok=True) - cmd = [shared.EMCC, '-c', src, '-o', obj] + cflags + cmd = [shared.EMCC, '-c', src, '-o', obj, *cflags] if utils.suffix(src) in {'.cc', '.cxx', '.cpp'}: cmd[0] = shared.EMXX cmd += cxxflags diff --git a/tools/shared.py b/tools/shared.py index b817ed5893320..d03cab7dd2bd5 100644 --- a/tools/shared.py +++ b/tools/shared.py @@ -207,7 +207,7 @@ def run_js_tool(filename, jsargs=[], node_args=[], **kw): # noqa: B006 This is used by emcc to run parts of the build process that are implemented in javascript. """ - command = config.NODE_JS + node_args + [filename] + jsargs + command = [*config.NODE_JS, *node_args, filename, *jsargs] return check_call(command, **kw).stdout @@ -215,7 +215,7 @@ def get_npm_cmd(name, missing_ok=False): if utils.WINDOWS: cmd = [path_from_root('node_modules/.bin', name + '.cmd')] else: - cmd = config.NODE_JS + [path_from_root('node_modules/.bin', name)] + cmd = [*config.NODE_JS, path_from_root('node_modules/.bin', name)] if not os.path.exists(cmd[-1]): if missing_ok: return None @@ -285,7 +285,7 @@ def env_with_node_in_path(): def _get_node_version_pair(nodejs): - actual = utils.run_process(nodejs + ['--version'], stdout=PIPE).stdout.strip() + actual = utils.run_process([*nodejs, '--version'], stdout=PIPE).stdout.strip() version = actual.removeprefix('v') version = version.split('-')[0].split('.') version = tuple(int(v) for v in version) @@ -338,7 +338,7 @@ def node_exception_flags(nodejs): @ToolchainProfiler.profile() def check_node(): try: - utils.run_process(config.NODE_JS + ['-e', 'console.log("hello")'], stdout=PIPE) + utils.run_process([*config.NODE_JS, '-e', 'console.log("hello")'], stdout=PIPE) except Exception as e: exit_with_error('the configured node executable (%s) does not seem to work, check the paths in %s (%s)', config.NODE_JS, config.EM_CONFIG, e) diff --git a/tools/system_libs.py b/tools/system_libs.py index 57a9f0315a583..7510cf05c957b 100644 --- a/tools/system_libs.py +++ b/tools/system_libs.py @@ -3,6 +3,8 @@ # University of Illinois/NCSA Open Source License. Both these licenses can be # found in the LICENSE file. +# ruff: noqa: RUF005 + import itertools import logging import os diff --git a/tools/webidl_binder.py b/tools/webidl_binder.py index b9c1d8e70d337..0f37dd4034bf9 100644 --- a/tools/webidl_binder.py +++ b/tools/webidl_binder.py @@ -2,7 +2,6 @@ # Emscripten is available under two separate licenses, the MIT license and the # University of Illinois/NCSA Open Source License. Both these licenses can be # found in the LICENSE file. -# noqa: UP035 """WebIDL binder.