diff --git a/.flake8 b/.flake8 index 34ff3214151d..3b9d5be2eec1 100644 --- a/.flake8 +++ b/.flake8 @@ -1,5 +1,5 @@ [flake8] -ignore = E111,E114,E501,E261,E266,E121,E402,E241,W504,E741 +ignore = E111,E114,E501,E261,E266,E121,E402,E241,W504,E741,B011 exclude = ./third_party/, # third-party code ./tools/filelock.py, # third-party code diff --git a/emsymbolizer.py b/emsymbolizer.py index 4bc3307cf355..8bcaddccfc58 100755 --- a/emsymbolizer.py +++ b/emsymbolizer.py @@ -87,7 +87,7 @@ def decodeVLQ(string): result = [] shift = 0 value = 0 - for i, c in enumerate(string): + for c in string: try: integer = vlq_map[c] except ValueError: @@ -107,7 +107,7 @@ def decodeVLQ(string): line = 1 col = 1 name = 0 - for i, segment in enumerate(source_map_json['mappings'].split(',')): + for segment in source_map_json['mappings'].split(','): data = decodeVLQ(segment) info = [] diff --git a/requirements-dev.txt b/requirements-dev.txt index e4e3b6c4b4de..1c992dc0af98 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -5,6 +5,7 @@ # Install with `pip3 install -r requirements-dev.txt` flake8==3.9.0 +flake8-bugbear==22.4.25 flake8-unused-arguments==0.0.6 coverage==5.5 diff --git a/site/source/get_wiki.py b/site/source/get_wiki.py index 1d4b14bcc027..899531541f22 100755 --- a/site/source/get_wiki.py +++ b/site/source/get_wiki.py @@ -115,7 +115,7 @@ def ConvertFilesToRst(): length = len(title) # print length headerbar = '' - for number in range(length): + for _ in range(length): headerbar += '=' page_reference = filenamestripped page_reference_link_text = '.. _%s:\n\n' % page_reference diff --git a/tests/common.py b/tests/common.py index 4c4fd1e7c351..f9e1dcbc4253 100644 --- a/tests/common.py +++ b/tests/common.py @@ -643,7 +643,7 @@ def verify_es5(self, filename): self.fail('es-check failed to verify ES5 output compliance') # Build JavaScript code from source code - def build(self, filename, libraries=[], includes=[], force_c=False, js_outfile=True, emcc_args=[], output_basename=None): + def build(self, filename, libraries=None, includes=None, force_c=False, js_outfile=True, emcc_args=None, output_basename=None): suffix = '.js' if js_outfile else '.wasm' compiler = [compiler_for(filename, force_c)] if compiler[0] == EMCC: @@ -661,11 +661,16 @@ def build(self, filename, libraries=[], includes=[], force_c=False, js_outfile=T else: basename = os.path.basename(filename) output = shared.unsuffixed(basename) + suffix - cmd = compiler + [filename, '-o', output] + self.get_emcc_args(main_file=True) + emcc_args + libraries + cmd = compiler + [filename, '-o', output] + self.get_emcc_args(main_file=True) + if emcc_args: + cmd += emcc_args + if libraries: + cmd += libraries if shared.suffix(filename) not in ('.i', '.ii'): # Add the location of the test file to include path. cmd += ['-I.'] - cmd += ['-I' + str(include) for include in includes] + if includes: + cmd += ['-I' + str(include) for include in includes] self.run_process(cmd, stderr=self.stderr_redirect if not DEBUG else None) self.assertExists(output) @@ -729,7 +734,7 @@ def measure_wasm_code_lines(self, wasm): non_data_lines = [line for line in wat_lines if '(data ' not in line] return len(non_data_lines) - def run_js(self, filename, engine=None, args=[], + def run_js(self, filename, engine=None, args=None, output_nicerizer=None, assert_returncode=0, interleaved_output=True): @@ -897,9 +902,11 @@ def get_build_dir(self): ensure_dir(ret) return ret - def get_library(self, name, generated_libs, configure=['sh', './configure'], - configure_args=[], make=['make'], make_args=None, + def get_library(self, name, generated_libs, configure=['sh', './configure'], # noqa + configure_args=None, make=None, make_args=None, env_init=None, cache_name_extra='', native=False): + if make is None: + make = ['make'] if env_init is None: env_init = {} if make_args is None: @@ -929,9 +936,10 @@ def get_library(self, name, generated_libs, configure=['sh', './configure'], return generated_libs print(f'', file=sys.stderr) - if configure is not None: - # Avoid += so we don't mutate the default arg - configure = configure + configure_args + if configure and configure_args: + # Make to copy to avoid mutating default param + configure = list(configure) + configure += configure_args cflags = ' '.join(emcc_args) env_init.setdefault('CFLAGS', cflags) @@ -958,7 +966,7 @@ def run_process(self, cmd, check=True, **args): print(e.stderr) self.fail(f'subprocess exited with non-zero return code({e.returncode}): `{shared.shlex_join(cmd)}`') - def emcc(self, filename, args=[], output_filename=None, **kwargs): + def emcc(self, filename, args=[], output_filename=None, **kwargs): # noqa cmd = [compiler_for(filename), filename] + self.get_emcc_args(ldflags='-c' not in args) + args if output_filename: cmd += ['-o', output_filename] @@ -1047,9 +1055,10 @@ def _test_dylink_dso_needed(self, do_run): so = '.wasm' if self.is_wasm() else '.js' - def ccshared(src, linkto=[]): + def ccshared(src, linkto=None): cmdv = [EMCC, src, '-o', shared.unsuffixed(src) + so, '-sSIDE_MODULE'] + self.get_emcc_args() - cmdv += linkto + if linkto: + cmdv += linkto self.run_process(cmdv) ccshared('liba.cpp') @@ -1076,8 +1085,9 @@ def ccshared(src, linkto=[]): ''', 'a: loaded\na: b (prev: (null))\na: c (prev: b)\n', emcc_args=extra_args) + extra_args = [] for libname in ['liba', 'libb', 'libc']: - self.emcc_args += ['--embed-file', libname + so] + extra_args += ['--embed-file', libname + so] do_run(r''' #include #include @@ -1103,7 +1113,7 @@ def ccshared(src, linkto=[]): return 0; } ''' % locals(), - 'a: loaded\na: b (prev: (null))\na: c (prev: b)\n') + 'a: loaded\na: b (prev: (null))\na: c (prev: b)\n', emcc_args=extra_args) def filtered_js_engines(self): for engine in self.js_engines: @@ -1140,12 +1150,12 @@ def do_run_in_out_file_test(self, *path, **kwargs): return self._build_and_run(srcfile, expected, **kwargs) ## Does a complete test - builds, runs, checks output, etc. - def _build_and_run(self, filename, expected_output, args=[], output_nicerizer=None, + def _build_and_run(self, filename, expected_output, args=None, output_nicerizer=None, no_build=False, - libraries=[], - includes=[], + libraries=None, + includes=None, assert_returncode=0, assert_identical=False, assert_all=False, - check_for_error=True, force_c=False, emcc_args=[], + check_for_error=True, force_c=False, emcc_args=None, interleaved_output=True, regex=False, output_basename=None): @@ -1745,11 +1755,11 @@ def build_library(name, generated_libs, configure, make, - make_args=[], - cache=None, - cache_name=None, - env_init={}, - native=False): + make_args, + cache, + cache_name, + env_init, + native): """Build a library and cache the result. We build the library file once and cache it for all our tests. (We cache in memory since the test directory is destroyed and recreated for each test. Note that we cache diff --git a/tests/gen_large_switchcase.py b/tests/gen_large_switchcase.py index b9a3e527343f..e9f5cef0825f 100755 --- a/tests/gen_large_switchcase.py +++ b/tests/gen_large_switchcase.py @@ -10,7 +10,7 @@ cases = '' i = 1 incr = 1 -for x in range(0, num_cases): +for _ in range(0, num_cases): cases += ' case ' + str(i) + ': return "' + str(i) + str(i) + str(i) + '";\n' i += incr incr = (incr % 5) + 1 diff --git a/tests/jsrun.py b/tests/jsrun.py index 684ddd39747e..15ded322f28d 100644 --- a/tests/jsrun.py +++ b/tests/jsrun.py @@ -16,7 +16,8 @@ DEFAULT_TIMEOUT = 5 * 60 -def make_command(filename, engine, args=[]): +def make_command(filename, engine, args=None): + args = args or [] # if no engine is needed, indicated by None, then there is a native executable # provided which we can just run if engine[0] is None: @@ -85,7 +86,7 @@ def require_engine(engine): sys.exit(1) -def run_js(filename, engine, args=[], +def run_js(filename, engine, args=None, stdin=None, stdout=PIPE, stderr=None, cwd=None, full_output=False, assert_returncode=0, skip_check=False, timeout=DEFAULT_TIMEOUT): diff --git a/tests/runner.py b/tests/runner.py index aeec7040156d..4ecde5a888df 100755 --- a/tests/runner.py +++ b/tests/runner.py @@ -128,7 +128,7 @@ def get_all_tests(modules): def tests_with_expanded_wildcards(args, all_tests): # Process wildcards, e.g. "browser.test_pthread_*" should expand to list all pthread tests new_args = [] - for i, arg in enumerate(args): + for arg in args: if '*' in arg: if arg.startswith('skip:'): arg = arg[5:] diff --git a/tests/test_benchmark.py b/tests/test_benchmark.py index 119c3af7ed97..06e001e39bc2 100644 --- a/tests/test_benchmark.py +++ b/tests/test_benchmark.py @@ -65,7 +65,7 @@ def prepare(self): def bench(self, args, output_parser=None, reps=TEST_REPS, expected_output=None): self.times = [] self.reps = reps - for i in range(reps): + for _ in range(reps): start = time.time() output = self.run(args) if expected_output is not None and expected_output not in output: @@ -125,13 +125,15 @@ def get_size_text(self): class NativeBenchmarker(Benchmarker): - def __init__(self, name, cc, cxx, args=[OPTIMIZATIONS]): + def __init__(self, name, cc, cxx, args=None): self.name = name self.cc = cc self.cxx = cxx - self.args = args.copy() + self.args = args or [OPTIMIZATIONS] def build(self, parent, filename, args, shared_args, emcc_args, native_args, native_exec, lib_builder, has_output_parser): + native_args = native_args or [] + shared_args = shared_args or [] self.parent = parent if lib_builder: env = {'CC': self.cc, 'CXX': self.cxx, 'CXXFLAGS': "-Wno-c++11-narrowing"} @@ -173,15 +175,17 @@ def run_binaryen_opts(filename, opts): class EmscriptenBenchmarker(Benchmarker): - def __init__(self, name, engine, extra_args=[], env={}, binaryen_opts=[]): + def __init__(self, name, engine, extra_args=None, env=None, binaryen_opts=None): self.name = name self.engine = engine - self.extra_args = extra_args.copy() + self.extra_args = extra_args or [] self.env = os.environ.copy() - self.env.update(env) - self.binaryen_opts = binaryen_opts.copy() + if env: + self.env.update(env) + self.binaryen_opts = binaryen_opts or [] def build(self, parent, filename, args, shared_args, emcc_args, native_args, native_exec, lib_builder, has_output_parser): + emcc_args = emcc_args or [] self.filename = filename llvm_root = self.env.get('LLVM') or config.LLVM_ROOT if lib_builder: @@ -190,7 +194,7 @@ def build(self, parent, filename, args, shared_args, emcc_args, native_args, nat # systems (like zlib) if they see a CFLAGS it will override all their # default flags, including optimizations. env_init['CFLAGS'] = ' '.join(LLVM_FEATURE_FLAGS + [OPTIMIZATIONS] + self.extra_args) - emcc_args = emcc_args + lib_builder('js_' + llvm_root, native=False, env_init=env_init) + emcc_args += lib_builder('js_' + llvm_root, native=False, env_init=env_init) final = os.path.dirname(filename) + os.path.sep + self.name + ('_' if self.name else '') + os.path.basename(filename) + '.js' final = final.replace('.cpp', '') try_delete(final) @@ -201,7 +205,9 @@ def build(self, parent, filename, args, shared_args, emcc_args, native_args, nat '-sENVIRONMENT=node,shell', '-sBENCHMARK=%d' % (1 if IGNORE_COMPILATION and not has_output_parser else 0), '-o', final - ] + shared_args + LLVM_FEATURE_FLAGS + ] + LLVM_FEATURE_FLAGS + if shared_args: + cmd += shared_args if common.EMTEST_FORCE64: cmd += ['--profiling'] else: @@ -281,11 +287,11 @@ def get_output_files(self): class CheerpBenchmarker(Benchmarker): - def __init__(self, name, engine, args=[OPTIMIZATIONS], binaryen_opts=[]): + def __init__(self, name, engine, args=None, binaryen_opts=None): self.name = name self.engine = engine - self.args = args.copy() - self.binaryen_opts = binaryen_opts.copy() + self.args = args or [OPTIMIZATIONS] + self.binaryen_opts = binaryen_opts or [] def build(self, parent, filename, args, shared_args, emcc_args, native_args, native_exec, lib_builder, has_output_parser): cheerp_args = [ @@ -435,8 +441,8 @@ def hardcode_arguments(self, code): ''' % DEFAULT_ARG return code - def do_benchmark(self, name, src, expected_output='FAIL', args=[], - emcc_args=[], native_args=[], shared_args=[], + def do_benchmark(self, name, src, expected_output='FAIL', args=None, + emcc_args=None, native_args=None, shared_args=None, force_c=False, reps=TEST_REPS, native_exec=None, output_parser=None, args_processor=None, lib_builder=None, skip_native=False): @@ -809,7 +815,7 @@ def zzz_test_corrections64(self): ''' self.do_benchmark('corrections64', src, 'final:') - def fasta(self, name, double_rep, emcc_args=[]): + def fasta(self, name, double_rep): src = read_file(test_file('fasta.cpp')).replace('double', double_rep) src = src.replace(' const size_t n = ( argc > 1 ) ? atoi( argv[1] ) : 512;', ''' int n; diff --git a/tests/test_browser.py b/tests/test_browser.py index 9a7674f052c6..ced73383f675 100644 --- a/tests/test_browser.py +++ b/tests/test_browser.py @@ -31,7 +31,8 @@ def test_chunked_synchronous_xhr_server(support_byte_ranges, chunkSize, data, checksum, port): class ChunkedServerHandler(BaseHTTPRequestHandler): - def sendheaders(s, extra=[], length=len(data)): + def sendheaders(s, extra=None, length=None): + length = length or len(data) s.send_response(200) s.send_header("Content-Length", str(length)) s.send_header("Access-Control-Allow-Origin", "http://localhost:%s" % port) @@ -41,8 +42,9 @@ def sendheaders(s, extra=[], length=len(data)): s.send_header("Content-type", "application/octet-stream") if support_byte_ranges: s.send_header("Accept-Ranges", "bytes") - for i in extra: - s.send_header(i[0], i[1]) + if extra: + for key, value in extra: + s.send_header(key, value) s.end_headers() def do_HEAD(s): @@ -69,7 +71,7 @@ def do_GET(s): # CORS preflight makes OPTIONS requests which we need to account for. expectedConns = 22 httpd = HTTPServer(('localhost', 11111), ChunkedServerHandler) - for i in range(expectedConns + 1): + for _ in range(expectedConns + 1): httpd.handle_request() @@ -1720,13 +1722,13 @@ def test_chunked_synchronous_xhr(self): time.sleep(2) @requires_graphics_hardware - def test_glgears(self, extra_args=[]): + def test_glgears(self, extra_args=[]): # noqa self.btest('hello_world_gles.c', reference='gears.png', reference_slack=3, args=['-DHAVE_BUILTIN_SINCOS', '-lGL', '-lglut'] + extra_args) @requires_graphics_hardware @requires_threads - def test_glgears_pthreads(self, extra_args=[]): + def test_glgears_pthreads(self, extra_args=[]): # noqa # test that a program that doesn't use pthreads still works with with pthreads enabled # (regression test for https://github.com/emscripten-core/emscripten/pull/8059#issuecomment-488105672) self.test_glgears(['-sUSE_PTHREADS']) @@ -3608,7 +3610,7 @@ def test_dylink_dso_needed(self, inworker): if inworker: self.emcc_args += ['--proxy-to-worker'] - def do_run(src, expected_output, emcc_args=[]): + def do_run(src, expected_output, emcc_args): # XXX there is no infrastructure (yet ?) to retrieve stdout from browser in tests. # -> do the assert about expected output inside browser. # @@ -3636,7 +3638,7 @@ def do_run(src, expected_output, emcc_args=[]): return rtn; } ''' % expected_output) - self.btest_exit(self.in_dir('test_dylink_dso_needed.c'), args=self.get_emcc_args() + ['--post-js', 'post.js'] + emcc_args) + self.btest_exit(self.in_dir('test_dylink_dso_needed.c'), args=['--post-js', 'post.js'] + emcc_args) self._test_dylink_dso_needed(do_run) @@ -3777,7 +3779,7 @@ def test_pthread_in_pthread_pool_size_strict(self): 'closure': (['--closure=1'],), }) @requires_threads - def test_pthread_atomics(self, args=[]): + def test_pthread_atomics(self, args): self.btest_exit(test_file('pthread/test_pthread_atomics.cpp'), args=['-sINITIAL_MEMORY=64MB', '-O3', '-sUSE_PTHREADS', '-sPTHREAD_POOL_SIZE=8', '-g1'] + args) # Test 64-bit atomics. @@ -4176,20 +4178,20 @@ def test_pthread_safe_stack(self): @parameterized({ 'leak': ['test_pthread_lsan_leak', ['-gsource-map']], - 'no_leak': ['test_pthread_lsan_no_leak'], + 'no_leak': ['test_pthread_lsan_no_leak', []], }) @requires_threads @no_firefox('https://github.com/emscripten-core/emscripten/issues/15978') - def test_pthread_lsan(self, name, args=[]): + def test_pthread_lsan(self, name, args): self.btest(test_file('pthread', name + '.cpp'), expected='1', args=['-fsanitize=leak', '-sINITIAL_MEMORY=256MB', '-sUSE_PTHREADS', '-sPROXY_TO_PTHREAD', '--pre-js', test_file('pthread', name + '.js')] + args) @parameterized({ # Reusing the LSan test files for ASan. 'leak': ['test_pthread_lsan_leak', ['-gsource-map']], - 'no_leak': ['test_pthread_lsan_no_leak'], + 'no_leak': ['test_pthread_lsan_no_leak', []], }) @requires_threads - def test_pthread_asan(self, name, args=[]): + def test_pthread_asan(self, name, args): self.btest(test_file('pthread', name + '.cpp'), expected='1', args=['-fsanitize=address', '-sINITIAL_MEMORY=256MB', '-sUSE_PTHREADS', '-sPROXY_TO_PTHREAD', '--pre-js', test_file('pthread', name + '.js')] + args) @requires_threads @@ -4335,7 +4337,7 @@ def test_binaryen_async(self): '': ([],), 'asan': (['-fsanitize=address', '-sINITIAL_MEMORY=128MB'],) }) - def test_manual_wasm_instantiate(self, args=[]): + def test_manual_wasm_instantiate(self, args): self.compile_btest([test_file('manual_wasm_instantiate.cpp'), '-o', 'manual_wasm_instantiate.js'] + args) shutil.copyfile(test_file('manual_wasm_instantiate.html'), 'manual_wasm_instantiate.html') self.run_browser('manual_wasm_instantiate.html', 'wasm instantiation succeeded', '/report_result?1') @@ -4619,10 +4621,10 @@ def test_fetch_stream_file(self): # Strategy: create a large 128MB file, and compile with a small 16MB Emscripten heap, so that the tested file # won't fully fit in the heap. This verifies that streaming works properly. s = '12345678' - for i in range(14): + for _ in range(14): s = s[::-1] + s # length of str will be 2^17=128KB with open('largefile.txt', 'w') as f: - for i in range(1024): + for _ in range(1024): f.write(s) self.btest_exit('fetch/stream_file.cpp', args=['-sFETCH_DEBUG', '-sFETCH', '-sINITIAL_MEMORY=536870912']) @@ -4751,10 +4753,10 @@ def test_minimal_runtime_hello_thread(self, opts): def test_pthread_growth_mainthread(self): self.emcc_args.remove('-Werror') - def run(emcc_args=[]): + def run(emcc_args): self.btest_exit(test_file('pthread/test_pthread_memory_growth_mainthread.c'), args=['-sUSE_PTHREADS', '-sPTHREAD_POOL_SIZE=2', '-sALLOW_MEMORY_GROWTH', '-sINITIAL_MEMORY=32MB', '-sMAXIMUM_MEMORY=256MB'] + emcc_args, also_wasm2js=False) - run() + run([]) run(['-sPROXY_TO_PTHREAD']) # Tests memory growth in a pthread. @@ -4762,10 +4764,10 @@ def run(emcc_args=[]): def test_pthread_growth(self): self.emcc_args.remove('-Werror') - def run(emcc_args=[]): + def run(emcc_args): self.btest_exit(test_file('pthread/test_pthread_memory_growth.c'), args=['-sUSE_PTHREADS', '-sPTHREAD_POOL_SIZE=2', '-sALLOW_MEMORY_GROWTH', '-sINITIAL_MEMORY=32MB', '-sMAXIMUM_MEMORY=256MB', '-g'] + emcc_args, also_wasm2js=False) - run() + run([]) run(['-sASSERTIONS']) run(['-sPROXY_TO_PTHREAD']) diff --git a/tests/test_core.py b/tests/test_core.py index 324ec578af39..3014f8017f58 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -1117,11 +1117,8 @@ def test_longjmp_with_and_without_exceptions(self): self.skipTest('Wasm EH does not work with asan yet') self.emcc_args.append('-fwasm-exceptions') self.v8_args.append('--experimental-wasm-eh') - old_args = self.emcc_args.copy() for arg in ['-fwasm-exceptions', '-fno-exceptions']: - self.emcc_args.append(arg) - self.do_core_test('test_longjmp.c') - self.emcc_args = old_args + self.do_core_test('test_longjmp.c', emcc_args=[arg]) @with_both_eh_sjlj def test_longjmp2(self): @@ -1265,6 +1262,9 @@ def test_exceptions_with_and_without_longjmp(self): def test_exceptions_off(self): self.set_setting('DISABLE_EXCEPTION_CATCHING') for support_longjmp in [0, 1]: + self.set_setting('SUPPORT_LONGJMP', support_longjmp) + if support_longjmp and self.is_wasm64(): + self.skipTest('MEMORY64 does not yet support SJLJ') self.do_runf(test_file('core/test_exceptions.cpp'), assert_returncode=NON_ZERO) @no_wasmfs('https://github.com/emscripten-core/emscripten/issues/16816') @@ -3984,10 +3984,11 @@ def dylink_test(self, main, side, expected=None, header=None, force_c=False, return self.dylink_testf(main, side, expected, force_c, main_module=main_module, **kwargs) - def dylink_testf(self, main, side=None, expected=None, force_c=False, main_emcc_args=[], + def dylink_testf(self, main, side=None, expected=None, force_c=False, main_emcc_args=None, main_module=2, so_name='liblib.so', need_reverse=True, **kwargs): + main_emcc_args = main_emcc_args or [] self.maybe_closure() # Same as dylink_test but takes source code as filenames on disc. old_args = self.emcc_args.copy() @@ -4968,7 +4969,7 @@ def test_dylink_load_compiled_side_module(self): @needs_dylink def test_dylink_dso_needed(self): - def do_run(src, expected_output, emcc_args=[]): + def do_run(src, expected_output, emcc_args=None): create_file('main.c', src + 'int main() { return test_main(); }') self.do_runf('main.c', expected_output, emcc_args=emcc_args) self._test_dylink_dso_needed(do_run) @@ -5825,14 +5826,12 @@ def test_fs_append(self): def test_fs_mmap(self): self.uses_es6 = True - orig_compiler_opts = self.emcc_args.copy() for fs in ['MEMFS', 'NODEFS', 'NODERAWFS']: - self.emcc_args = orig_compiler_opts + ['-D' + fs] if fs == 'NODEFS': self.emcc_args += ['-lnodefs.js'] if fs == 'NODERAWFS': self.emcc_args += ['-lnodefs.js', '-lnoderawfs.js'] - self.do_run_in_out_file_test('fs/test_mmap.c') + self.do_run_in_out_file_test('fs/test_mmap.c', emcc_args=['-D' + fs]) @parameterized({ '': [], @@ -6064,8 +6063,7 @@ def test_unistd_io(self): }) def test_unistd_misc(self, fs): self.set_setting('LLD_REPORT_UNDEFINED') - orig_compiler_opts = self.emcc_args.copy() - self.emcc_args = orig_compiler_opts + ['-D' + fs] + self.emcc_args += ['-D' + fs] if fs == 'NODEFS': self.require_node() self.emcc_args += ['-lnodefs.js'] @@ -6291,19 +6289,20 @@ def test_fasta(self): (20, '''GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTT*cttBtatcatatgctaKggNcataaaSatgtaaaDcDRtBggDtctttataattcBgtcg**tacgtgtagcctagtgtttgtgttgcgttatagtctatttgtggacacagtatggtcaaa**tgacgtcttttgatctgacggcgttaacaaagatactctg*'''), (50, '''GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGA*TCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACAT*cttBtatcatatgctaKggNcataaaSatgtaaaDcDRtBggDtctttataattcBgtcg**tactDtDagcctatttSVHtHttKtgtHMaSattgWaHKHttttagacatWatgtRgaaa**NtactMcSMtYtcMgRtacttctWBacgaa**agatactctgggcaacacacatacttctctcatgttgtttcttcggacctttcataacct**ttcctggcacatggttagctgcacatcacaggattgtaagggtctagtggttcagtgagc**ggaatatcattcgtcggtggtgttaatctatctcggtgtagcttataaatgcatccgtaa**gaatattatgtttatttgtcggtacgttcatggtagtggtgtcgccgatttagacgtaaa**ggcatgtatg*''')] - old = self.emcc_args orig_src = read_file(test_file('fasta.cpp')) def test(extra_args): - self.emcc_args = old + extra_args for t in ['float', 'double']: print(t) src = orig_src.replace('double', t) with open('fasta.cpp', 'w') as f: f.write(src) - self.build('fasta.cpp') + self.build('fasta.cpp', emcc_args=extra_args) for arg, output in results: - self.do_run('fasta.js', output, args=[str(arg)], output_nicerizer=lambda x: x.replace('\n', '*'), no_build=True) + self.do_run('fasta.js', output, args=[str(arg)], + output_nicerizer=lambda x: x.replace('\n', '*'), + no_build=True, + emcc_args=extra_args) shutil.copyfile('fasta.js', '%s.js' % t) test([]) @@ -7007,7 +7006,7 @@ def test_dyncall_specific(self, *args): def test_getValue_setValue(self): # these used to be exported, but no longer are by default - def test(output_prefix='', args=[], assert_returncode=0): + def test(output_prefix='', args=None, assert_returncode=0): src = test_file('core/test_getValue_setValue.cpp') expected = test_file('core/test_getValue_setValue' + output_prefix + '.out') self.do_run_from_file(src, expected, assert_returncode=assert_returncode, emcc_args=args) @@ -7030,7 +7029,7 @@ def test(output_prefix='', args=[], assert_returncode=0): }) def test_FS_exports(self, extra_args): # these used to be exported, but no longer are by default - def test(output_prefix='', args=[], assert_returncode=0): + def test(output_prefix='', args=None, assert_returncode=0): args += extra_args print(args) self.do_runf(test_file('core/FS_exports.cpp'), @@ -7044,7 +7043,7 @@ def test(output_prefix='', args=[], assert_returncode=0): # see that with assertions, we get a nice error message self.set_setting('EXPORTED_RUNTIME_METHODS', []) self.set_setting('ASSERTIONS') - test('_assert', assert_returncode=NON_ZERO) + test('_assert', args=[], assert_returncode=NON_ZERO) self.set_setting('ASSERTIONS', 0) # see that when we export them, things work on the module self.set_setting('EXPORTED_RUNTIME_METHODS', ['FS_createDataFile']) @@ -7052,13 +7051,10 @@ def test(output_prefix='', args=[], assert_returncode=0): def test_legacy_exported_runtime_numbers(self): # these used to be exported, but no longer are by default - def test(output_prefix='', args=[], assert_returncode=0): - old = self.emcc_args.copy() - self.emcc_args += args + def test(output_prefix='', args=None, assert_returncode=0): src = test_file('core/legacy_exported_runtime_numbers.cpp') expected = test_file('core/legacy_exported_runtime_numbers%s.out' % output_prefix) - self.do_run_from_file(src, expected, assert_returncode=assert_returncode) - self.emcc_args = old + self.do_run_from_file(src, expected, assert_returncode=assert_returncode, emcc_args=args) # see that direct usage (not on module) works. we don't export, but the use # keeps it alive through JSDCE @@ -7790,7 +7786,7 @@ def get_dwarf_addr(line, col): def get_wat_addr(call_index): # find the call_index-th call call_loc = -1 - for i in range(call_index + 1): + for _ in range(call_index + 1): call_loc = wat.find('call $out_to_js', call_loc + 1) assert call_loc > 0 # the call begins with the local.get/i32.const printed below it, which is @@ -8222,10 +8218,10 @@ def break_wasm(name): self.run_process([Path(building.get_binaryen_bin(), 'wasm-as'), 'wat.wat', '-o', name, '-g']) return True - def verify_working(args=['0']): + def verify_working(args): self.assertContained('foo_end\n', self.run_js('emscripten_lazy_load_code.js', args=args)) - def verify_broken(args=['0']): + def verify_broken(args): self.assertNotContained('foo_end\n', self.run_js('emscripten_lazy_load_code.js', args=args, assert_returncode=NON_ZERO)) # the first-loaded wasm will not reach the second call, since we call it after lazy-loading. @@ -8233,25 +8229,25 @@ def verify_broken(args=['0']): found_foo_end = break_wasm('emscripten_lazy_load_code.wasm') if not conditional and self.is_optimizing(): self.assertFalse(found_foo_end, 'should have optimized out $foo_end') - verify_working() + verify_working(['0']) # but breaking the second wasm actually breaks us if not break_wasm('emscripten_lazy_load_code.wasm.lazy.wasm'): raise Exception('could not break lazy wasm - missing expected code') - verify_broken() + verify_broken(['0']) # restore shutil.copyfile('emscripten_lazy_load_code.wasm.orig', 'emscripten_lazy_load_code.wasm') shutil.copyfile('emscripten_lazy_load_code.wasm.lazy.wasm.orig', 'emscripten_lazy_load_code.wasm.lazy.wasm') - verify_working() + verify_working(['0']) if conditional: # if we do not call the lazy load function, then we do not need the lazy wasm, # and we do the second call in the first wasm os.remove('emscripten_lazy_load_code.wasm.lazy.wasm') - verify_broken() + verify_broken(['0']) verify_working(['42']) break_wasm('emscripten_lazy_load_code.wasm') - verify_broken() + verify_broken(['0']) # Test basic wasm2js functionality in all core compilation modes. @no_sanitize('no wasm2js support yet in sanitizers') @@ -9398,7 +9394,7 @@ def tearDown(self): try: super(TT, self).tearDown() finally: - for k, v in self.env.items(): + for k in self.env.keys(): del os.environ[k] TT.tearDown = tearDown diff --git a/tests/test_other.py b/tests/test_other.py index c454e99a58e9..602cfb4179a8 100644 --- a/tests/test_other.py +++ b/tests/test_other.py @@ -168,7 +168,7 @@ def assertIsObjectFile(self, filename): def assertIsWasmDylib(self, filename): self.assertTrue(building.is_wasm_dylib(filename)) - def do_other_test(self, testname, emcc_args=[], **kwargs): + def do_other_test(self, testname, emcc_args=None, **kwargs): self.do_run_in_out_file_test('other', testname, emcc_args=emcc_args, **kwargs) def run_on_pty(self, cmd): @@ -647,7 +647,7 @@ def test_emsize(self): expected = read_file(test_file('other/test_emsize.out')) cmd = [emsize, test_file('other/test_emsize.js')] for command in [cmd, cmd + ['--format=sysv']]: - output = self.run_process(cmd, stdout=PIPE).stdout + output = self.run_process(command, stdout=PIPE).stdout self.assertContained(expected, output) def test_emstrip(self): @@ -3642,7 +3642,7 @@ def test_LEGACY_VM_SUPPORT(self): # when modern features are lacking, we can polyfill them or at least warn create_file('pre.js', 'Math.imul = undefined;') - def test(expected, opts=[]): + def test(expected, opts): print(opts) result = self.run_process([EMCC, test_file('hello_world.c'), '--pre-js', 'pre.js'] + opts, stderr=PIPE, check=False) if result.returncode == 0: @@ -3651,7 +3651,7 @@ def test(expected, opts=[]): self.assertContained(expected, result.stderr) # when legacy is needed, we show an error indicating so - test('build with LEGACY_VM_SUPPORT') + test('build with LEGACY_VM_SUPPORT', []) # legacy + disabling wasm works test('hello, world!', ['-sLEGACY_VM_SUPPORT', '-sWASM=0']) @@ -4051,7 +4051,7 @@ def get_minified_middle(symbols_file): return minified_middle def guess_symbols_file_type(symbols_file): - for minified, full in get_symbols_lines(symbols_file): + for _minified, full in get_symbols_lines(symbols_file): # define symbolication file by JS specific entries if full in ['FUNCTION_TABLE', 'HEAP32']: return 'js' @@ -4695,12 +4695,12 @@ def test_dashE(self): __EMSCRIPTEN_major__ __EMSCRIPTEN_minor__ __EMSCRIPTEN_tiny__ EMSCRIPTEN_KEEPALIVE ''') - def test(args=[]): + def test(args): print(args) out = self.run_process([EMXX, 'src.cpp', '-E'] + args, stdout=PIPE).stdout self.assertContained('%d %d %d __attribute__((used))' % (shared.EMSCRIPTEN_VERSION_MAJOR, shared.EMSCRIPTEN_VERSION_MINOR, shared.EMSCRIPTEN_VERSION_TINY), out) - test() + test([]) test(['-lembind']) def test_dashE_respect_dashO(self): @@ -5889,7 +5889,7 @@ def test_libcxx_minimal(self): def test_minimal_dynamic(self, wasm): library_file = 'library.wasm' if wasm else 'library.js' - def test(name, main_args, library_args=[], expected='hello from main\nhello from library', assert_returncode=0): + def test(name, main_args, library_args, expected='hello from main\nhello from library', assert_returncode=0): print(f'testing {name}', main_args, library_args) self.clear() create_file('library.c', r''' @@ -5935,17 +5935,17 @@ def percent_diff(x, y): large = max(x, y) return float(100 * large) / small - 100 - full = test('full', main_args=['-sMAIN_MODULE']) + full = test('full', main_args=['-sMAIN_MODULE'], library_args=[]) # printf is not used in main, but libc was linked in, so it's there printf = test('printf', main_args=['-sMAIN_MODULE'], library_args=['-DUSE_PRINTF']) # main module tests # dce in main, and it fails since puts is not exported - test('dce', main_args=['-sMAIN_MODULE=2'], expected=('cannot', 'undefined'), assert_returncode=NON_ZERO) + test('dce', main_args=['-sMAIN_MODULE=2'], library_args=[], expected=('cannot', 'undefined'), assert_returncode=NON_ZERO) # with exporting, it works - dce = test('dce', main_args=['-sMAIN_MODULE=2', '-sEXPORTED_FUNCTIONS=_main,_puts']) + dce = test('dce', main_args=['-sMAIN_MODULE=2', '-sEXPORTED_FUNCTIONS=_main,_puts'], library_args=[]) # printf is not used in main, and we dce, so we failz dce_fail = test('dce_fail', main_args=['-sMAIN_MODULE=2'], library_args=['-DUSE_PRINTF'], expected=('cannot', 'undefined'), assert_returncode=NON_ZERO) @@ -7099,7 +7099,7 @@ def test(contents): def test_warn_module_print_err(self): error = 'was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)' - def test(contents, expected, args=[], assert_returncode=0): + def test(contents, expected, args=[], assert_returncode=0): # noqa create_file('src.cpp', r''' #include int main() { @@ -7363,10 +7363,10 @@ def test_binaryen_ignore_implicit_traps(self): self.assertEqual(len(set(sizes)), 2) def test_binaryen_passes_extra(self): - def build(args=[]): + def build(args): return self.run_process([EMXX, test_file('hello_world.cpp'), '-O3'] + args, stdout=PIPE).stdout - build() + build([]) base_size = os.path.getsize('a.out.wasm') out = build(['-sBINARYEN_EXTRA_PASSES="--metrics"']) # and --metrics output appears @@ -7385,7 +7385,7 @@ def check_expected_size_in_file(self, desc, filename, size): print(' seen %s size: %d (expected: %d) (delta: %d), ratio to expected: %f' % (desc, size, expected_size, delta, ratio)) self.assertLess(ratio, size_slack) - def run_metadce_test(self, filename, args=[], expected_exists=[], expected_not_exists=[], check_size=True, + def run_metadce_test(self, filename, args=[], expected_exists=[], expected_not_exists=[], check_size=True, # noqa check_sent=True, check_imports=True, check_exports=True, check_funcs=True): # in -Os, -Oz, we remove imports wasm doesn't need @@ -7630,26 +7630,23 @@ def test_legalize_js_ffi(self): def test_no_legalize_js_ffi(self): # test minimal JS FFI legalization for invoke and dyncalls - for (args, js_ffi) in [ - (['-sLEGALIZE_JS_FFI=0', '-sMAIN_MODULE=2', '-O3', '-sDISABLE_EXCEPTION_CATCHING=0'], False), - ]: - print(args) - try_delete('a.out.wasm') - with env_modify({'EMCC_FORCE_STDLIBS': 'libc++'}): - cmd = [EMXX, test_file('other/noffi.cpp'), '-g', '-o', 'a.out.js'] + args - print(' '.join(cmd)) - self.run_process(cmd) - text = self.get_wasm_text('a.out.wasm') - # remove internal comments and extra whitespace - text = re.sub(r'\(;[^;]+;\)', '', text) - text = re.sub(r'\$var\$*.', '', text) - text = re.sub(r'param \$\d+', 'param ', text) - text = re.sub(r' +', ' ', text) - # print("text: %s" % text) - i_legalimport_i64 = re.search(r'\(import.*\$legalimport\$invoke_j.*', text) - e_legalstub_i32 = re.search(r'\(func.*\$legalstub\$dyn.*\(result i32\)', text) - assert i_legalimport_i64, 'legal import not generated for invoke call' - assert e_legalstub_i32, 'legal stub not generated for dyncall' + args = ['-sLEGALIZE_JS_FFI=0', '-sMAIN_MODULE=2', '-O3', '-sDISABLE_EXCEPTION_CATCHING=0'] + try_delete('a.out.wasm') + with env_modify({'EMCC_FORCE_STDLIBS': 'libc++'}): + cmd = [EMXX, test_file('other/noffi.cpp'), '-g', '-o', 'a.out.js'] + args + print(' '.join(cmd)) + self.run_process(cmd) + text = self.get_wasm_text('a.out.wasm') + # remove internal comments and extra whitespace + text = re.sub(r'\(;[^;]+;\)', '', text) + text = re.sub(r'\$var\$*.', '', text) + text = re.sub(r'param \$\d+', 'param ', text) + text = re.sub(r' +', ' ', text) + # print("text: %s" % text) + i_legalimport_i64 = re.search(r'\(import.*\$legalimport\$invoke_j.*', text) + e_legalstub_i32 = re.search(r'\(func.*\$legalstub\$dyn.*\(result i32\)', text) + assert i_legalimport_i64, 'legal import not generated for invoke call' + assert e_legalstub_i32, 'legal stub not generated for dyncall' def test_export_aliasee(self): # build side module @@ -8099,7 +8096,7 @@ def test_archive_thin(self): self.assertContained('hello, world!', self.run_js('a.out.js')) def test_flag_aliases(self): - def assert_aliases_match(flag1, flag2, flagarg, extra_args=[]): + def assert_aliases_match(flag1, flag2, flagarg, extra_args): results = {} for f in (flag1, flag2): self.run_process([EMCC, test_file('hello_world.c'), '-s', f + '=' + flagarg] + extra_args) @@ -8108,8 +8105,8 @@ def assert_aliases_match(flag1, flag2, flagarg, extra_args=[]): self.assertEqual(results[flag1 + '.js'], results[flag2 + '.js'], 'js results should be identical') self.assertEqual(results[flag1 + '.wasm'], results[flag2 + '.wasm'], 'wasm results should be identical') - assert_aliases_match('INITIAL_MEMORY', 'TOTAL_MEMORY', '16777216') - assert_aliases_match('INITIAL_MEMORY', 'TOTAL_MEMORY', '64MB') + assert_aliases_match('INITIAL_MEMORY', 'TOTAL_MEMORY', '16777216', []) + assert_aliases_match('INITIAL_MEMORY', 'TOTAL_MEMORY', '64MB', []) assert_aliases_match('MAXIMUM_MEMORY', 'WASM_MEM_MAX', '16777216', ['-sALLOW_MEMORY_GROWTH']) assert_aliases_match('MAXIMUM_MEMORY', 'BINARYEN_MEM_MAX', '16777216', ['-sALLOW_MEMORY_GROWTH']) @@ -8126,7 +8123,7 @@ def test_IGNORE_CLOSURE_COMPILER_ERRORS(self): } ''') - def test(check, extra=[]): + def test(check, extra): cmd = [EMCC, test_file('hello_world.c'), '-O2', '--closure=1', '--pre-js', 'pre.js'] + extra proc = self.run_process(cmd, check=check, stderr=PIPE) if not check: @@ -8135,7 +8132,7 @@ def test(check, extra=[]): WARNING = 'Variable dupe declared more than once' - proc = test(check=False) + proc = test(check=False, extra=[]) self.assertContained(WARNING, proc.stderr) proc = test(check=True, extra=['-sIGNORE_CLOSURE_COMPILER_ERRORS']) self.assertNotContained(WARNING, proc.stderr) @@ -11335,7 +11332,7 @@ def create_o(name, i): count = 1000 for i in range(count): name = 'a' + str(i) - for j in range(5): + for _ in range(5): name += name create_o(name, i) diff --git a/tests/test_sockets.py b/tests/test_sockets.py index aa3620de1576..91b32b0df16d 100644 --- a/tests/test_sockets.py +++ b/tests/test_sockets.py @@ -69,7 +69,7 @@ def __enter__(self): self.websockify.start() self.processes.append(self.websockify) # Make sure both the actual server and the websocket proxy are running - for i in range(10): + for _ in range(10): try: if self.do_server_check: server_sock = socket.create_connection(('localhost', self.target_port), timeout=1) diff --git a/tools/building.py b/tools/building.py index 31fbfd9ca25b..04b85d27e4b1 100644 --- a/tools/building.py +++ b/tools/building.py @@ -1489,9 +1489,10 @@ def get_binaryen_bin(): binaryen_kept_debug_info = False -def run_binaryen_command(tool, infile, outfile=None, args=[], debug=False, stdout=None): +def run_binaryen_command(tool, infile, outfile=None, args=None, debug=False, stdout=None): cmd = [os.path.join(get_binaryen_bin(), tool)] - cmd += args + if args: + cmd += args if infile: cmd += [infile] if outfile: @@ -1526,7 +1527,7 @@ def run_binaryen_command(tool, infile, outfile=None, args=[], debug=False, stdou return ret -def run_wasm_opt(infile, outfile=None, args=[], **kwargs): +def run_wasm_opt(infile, outfile=None, args=[], **kwargs): # noqa if outfile and (settings.DEBUG_LEVEL < 3 or settings.GENERATE_SOURCE_MAP): # remove any dwarf debug info sections, if the debug level is <3, as # we don't need them; also remove them if we use source maps (which are diff --git a/tools/experimental/reproduceriter.py b/tools/experimental/reproduceriter.py index cf9b4b30b7bb..f0f9eeaedc92 100644 --- a/tools/experimental/reproduceriter.py +++ b/tools/experimental/reproduceriter.py @@ -143,7 +143,7 @@ print('add customizations...') -for parent, dirs, files in os.walk(out_dir): +for parent, _, files in os.walk(out_dir): for filename in files: if filename.endswith('.js'): fullname = os.path.join(parent, filename) diff --git a/tools/ports/__init__.py b/tools/ports/__init__.py index 6daa4c6122fd..b1e80be08297 100644 --- a/tools/ports/__init__.py +++ b/tools/ports/__init__.py @@ -49,7 +49,7 @@ def read_ports(): def get_all_files_under(dirname): - for path, subdirs, files in os.walk(dirname): + for path, _, files in os.walk(dirname): for name in files: yield os.path.join(path, name) @@ -95,9 +95,9 @@ def install_headers(src_dir, pattern='*.h', target=None): shutil.copyfile(f, os.path.join(dest, os.path.basename(f))) @staticmethod - def build_port(src_path, output_path, includes=[], flags=[], exclude_files=[], exclude_dirs=[]): + def build_port(src_path, output_path, includes=[], flags=[], exclude_files=[], exclude_dirs=[]): # noqa srcs = [] - for root, dirs, files in os.walk(src_path, topdown=False): + for root, _, files in os.walk(src_path, topdown=False): if any((excluded in root) for excluded in exclude_dirs): continue for f in files: diff --git a/tools/ports/bullet.py b/tools/ports/bullet.py index 5349b2a3bf19..8c12b44c8e74 100644 --- a/tools/ports/bullet.py +++ b/tools/ports/bullet.py @@ -30,7 +30,7 @@ def create(final): src_path = os.path.join(dest_path, 'bullet', 'src') dest_include_path = ports.get_include_dir('bullet') - for base, dirs, files in os.walk(src_path): + for base, _, files in os.walk(src_path): for f in files: if shared.suffix(f) != '.h': continue @@ -41,9 +41,9 @@ def create(final): shutil.copyfile(fullpath, target) includes = [] - for root, dirs, files in os.walk(src_path, topdown=False): + for base, dirs, _ in os.walk(src_path, topdown=False): for dir in dirs: - includes.append(os.path.join(root, dir)) + includes.append(os.path.join(base, dir)) ports.build_port(src_path, final, includes=includes, exclude_dirs=['MiniCL']) diff --git a/tools/shared.py b/tools/shared.py index 2eef248c9733..ff67f35a97ef 100644 --- a/tools/shared.py +++ b/tools/shared.py @@ -139,7 +139,14 @@ def returncode_to_str(code): # bool 'check': If True (default), raises an exception if any of the subprocesses failed with a nonzero exit code. # string 'route_stdout_to_temp_files_suffix': if not None, all stdouts are instead written to files, and an array of filenames is returned. # bool 'pipe_stdout': If True, an array of stdouts is returned, for each subprocess. -def run_multiple_processes(commands, env=os.environ.copy(), route_stdout_to_temp_files_suffix=None, pipe_stdout=False, check=True, cwd=None): +def run_multiple_processes(commands, + env=None, + route_stdout_to_temp_files_suffix=None, + pipe_stdout=False, + check=True, + cwd=None): + if env is None: + env = os.environ.copy() # By default, avoid using Python multiprocessing library due to a large amount of bugs it has on Windows (#8013, #718, #13785, etc.) # Use EM_PYTHON_MULTIPROCESSING=1 environment variable to enable it. It can be faster, but may not work on Windows. if int(os.getenv('EM_PYTHON_MULTIPROCESSING', '0')): @@ -227,7 +234,7 @@ def check_call(cmd, *args, **kw): exit_with_error("'%s' failed: %s", shlex_join(cmd), str(e)) -def run_js_tool(filename, jsargs=[], node_args=[], **kw): +def run_js_tool(filename, jsargs=[], node_args=[], **kw): # noqa: mutable default args """Execute a javascript tool. This is used by emcc to run parts of the build process that are written diff --git a/tools/system_libs.py b/tools/system_libs.py index 1dc7238a5557..8d3266121e01 100644 --- a/tools/system_libs.py +++ b/tools/system_libs.py @@ -428,8 +428,8 @@ def get_inheritance_tree(cls): """Returns all the classes in the inheritance tree of the current class.""" yield cls for subclass in cls.__subclasses__(): - for subclass in subclass.get_inheritance_tree(): - yield subclass + for cls in subclass.get_inheritance_tree(): + yield cls @classmethod def get_all_variations(cls): diff --git a/tools/webassembly.py b/tools/webassembly.py index 952dccf0d3d6..c898bd03e2ef 100644 --- a/tools/webassembly.py +++ b/tools/webassembly.py @@ -249,16 +249,16 @@ def get_types(self): self.seek(type_section.offset) num_types = self.read_uleb() types = [] - for i in range(num_types): + for _ in range(num_types): params = [] returns = [] type_form = self.read_byte() assert type_form == 0x60 num_params = self.read_uleb() - for j in range(num_params): + for _ in range(num_params): params.append(self.read_type()) num_returns = self.read_uleb() - for j in range(num_returns): + for _ in range(num_returns): returns.append(self.read_type()) types.append(FuncType(params, returns)) return types @@ -350,7 +350,7 @@ def get_exports(self): self.seek(export_section.offset) num_exports = self.read_uleb() exports = [] - for i in range(num_exports): + for _ in range(num_exports): name = self.read_string() kind = ExternType(self.read_byte()) index = self.read_uleb() @@ -367,7 +367,7 @@ def get_imports(self): self.seek(import_section.offset) num_imports = self.read_uleb() imports = [] - for i in range(num_imports): + for _ in range(num_imports): mod = self.read_string() field = self.read_string() kind = ExternType(self.read_byte()) @@ -386,7 +386,7 @@ def get_imports(self): self.read_byte() # attribute type_ = self.read_uleb() else: - assert False + raise AssertionError() imports.append(Import(kind, mod, field, type_)) return imports @@ -399,7 +399,7 @@ def get_globals(self): globls = [] self.seek(global_section.offset) num_globals = self.read_uleb() - for i in range(num_globals): + for _ in range(num_globals): global_type = self.read_type() mutable = self.read_byte() init = self.read_init() @@ -414,7 +414,7 @@ def get_functions(self): functions = [] self.seek(code_section.offset) num_functions = self.read_uleb() - for i in range(num_functions): + for _ in range(num_functions): body_size = self.read_uleb() start = self.tell() functions.append(FunctionBody(start, body_size)) @@ -437,7 +437,7 @@ def get_segments(self): data_section = self.get_section(SecType.DATA) self.seek(data_section.offset) num_segments = self.read_uleb() - for i in range(num_segments): + for _ in range(num_segments): flags = self.read_uleb() if (flags & SEG_PASSIVE): init = None @@ -458,7 +458,7 @@ def get_tables(self): self.seek(table_section.offset) num_tables = self.read_uleb() tables = [] - for i in range(num_tables): + for _ in range(num_tables): elem_type = self.read_type() limits = self.read_limits() tables.append(Table(elem_type, limits))