From 7352c448cdd73eccafc21695bde90bd4c61d7255 Mon Sep 17 00:00:00 2001 From: gf712 Date: Tue, 16 Dec 2025 11:11:13 +0000 Subject: [PATCH] precommit hook --- .clang-format-ignore | 2 + .github/workflows/premerge.yml | 4 + .pre-commit-config.yaml | 5 ++ src/ast/AST.cpp | 14 +-- src/ast/optimizers/Optimizers_tests.cpp | 4 +- src/executable/Program.cpp | 4 +- src/executable/bytecode/Bytecode.cpp | 20 +++-- src/executable/bytecode/Bytecode.hpp | 3 +- .../bytecode/codegen/BytecodeGenerator.cpp | 10 +-- .../bytecode/codegen/VariablesResolver.cpp | 4 +- .../bytecode/instructions/BuildList.hpp | 7 +- .../bytecode/instructions/DeleteFast.cpp | 2 +- .../bytecode/instructions/ForIter.hpp | 4 +- .../bytecode/instructions/InplaceOp.cpp | 2 +- .../bytecode/instructions/MakeFunction.cpp | 2 +- .../bytecode/instructions/MakeFunction.hpp | 5 +- src/executable/bytecode/instructions/Push.cpp | 2 +- src/executable/bytecode/instructions/Push.hpp | 5 +- .../PythonToPythonBytecode.cpp | 2 +- src/executable/mlir/Dialect/Python/IR/Ops.cpp | 2 +- .../mlir/Dialect/Python/MLIRGenerator.cpp | 22 ++--- .../LinearScanRegisterAllocation.hpp | 53 ++++++------ .../Target/PythonBytecode/LiveAnalysis.hpp | 86 ++++++++----------- .../PythonBytecode/LiveIntervalAnalysis.hpp | 19 ++-- .../RegisterAllocationLogger.hpp | 4 +- .../RegisterAllocationTypes.hpp | 3 +- .../TranslateToPythonBytecode.cpp | 1 - .../RegisterAllocation_tests.cpp | 12 ++- src/executable/mlir/compile.hpp | 2 +- src/lexer/Lexer_tests.cpp | 6 +- src/memory/Heap.hpp | 2 +- src/runtime/BaseException.cpp | 4 +- src/runtime/CustomPyObject.hpp | 2 +- src/runtime/Exception.hpp | 3 +- src/runtime/ImportError.cpp | 4 +- src/runtime/KeyError.hpp | 4 +- src/runtime/PyAsyncGenerator.cpp | 20 +++-- src/runtime/PyByteArray.cpp | 8 +- src/runtime/PyBytes.cpp | 3 +- src/runtime/PyClassMethod.cpp | 4 +- src/runtime/PyCode.cpp | 4 +- src/runtime/PyComplex.hpp | 2 +- src/runtime/PyCoroutine.cpp | 16 ++-- src/runtime/PyDict.cpp | 3 +- src/runtime/PyFrame.cpp | 2 +- src/runtime/PyFunction.cpp | 50 +++++------ src/runtime/PyGenerator.cpp | 18 ++-- src/runtime/PyGetSetDescriptor.cpp | 8 +- src/runtime/PyInteger.cpp | 12 ++- src/runtime/PyIterator.hpp | 2 +- src/runtime/PyList.cpp | 3 +- src/runtime/PyMappingProxy.cpp | 10 +-- src/runtime/PyMemberDescriptor.cpp | 8 +- src/runtime/PyMemoryView.cpp | 14 +-- src/runtime/PyMemoryView.hpp | 4 +- src/runtime/PyMethodDescriptor.cpp | 4 +- src/runtime/PyNamespace.cpp | 4 +- src/runtime/PyObject.cpp | 36 ++++---- src/runtime/PyProperty.cpp | 14 +-- src/runtime/PySet.cpp | 18 ++-- src/runtime/PySet.hpp | 3 +- src/runtime/PySlice.cpp | 8 +- src/runtime/PySlotWrapper.hpp | 15 ++-- src/runtime/PyString.cpp | 16 +++- src/runtime/PySuper.cpp | 8 +- src/runtime/PyTraceback.cpp | 10 +-- src/runtime/PyType.cpp | 9 +- src/runtime/UnboundLocalError.cpp | 7 +- .../modules/collections/DefaultDict.hpp | 6 +- .../modules/itertools/Permutations.hpp | 2 +- src/runtime/modules/itertools/Product.hpp | 4 +- src/runtime/modules/thread/RLock.hpp | 10 +-- src/runtime/modules/time/module.cpp | 2 +- src/runtime/types/api.hpp | 12 +-- src/runtime/utilities.hpp | 4 +- src/testing/main.cpp | 2 +- src/utilities.hpp | 4 +- src/vm/VM.hpp | 5 +- 78 files changed, 363 insertions(+), 361 deletions(-) create mode 100644 .clang-format-ignore create mode 100644 .pre-commit-config.yaml diff --git a/.clang-format-ignore b/.clang-format-ignore new file mode 100644 index 00000000..7fce7f0a --- /dev/null +++ b/.clang-format-ignore @@ -0,0 +1,2 @@ +src/runtime/frozen/importlib.h +src/runtime/frozen/importlib_external.h \ No newline at end of file diff --git a/.github/workflows/premerge.yml b/.github/workflows/premerge.yml index 2deb9265..7afa4d5a 100644 --- a/.github/workflows/premerge.yml +++ b/.github/workflows/premerge.yml @@ -14,6 +14,10 @@ jobs: steps: - uses: actions/checkout@v4 + - uses: actions/setup-python@v3 + + - uses: pre-commit/action@v3.0.1 + - name: Install LLVM run: | wget https://apt.llvm.org/llvm.sh diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 00000000..7b558688 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,5 @@ +repos: + - repo: https://github.com/pre-commit/mirrors-clang-format + rev: 'v20.1.8' + hooks: + - id: clang-format \ No newline at end of file diff --git a/src/ast/AST.cpp b/src/ast/AST.cpp index 45f0cd7c..7c52320e 100644 --- a/src/ast/AST.cpp +++ b/src/ast/AST.cpp @@ -14,11 +14,8 @@ namespace ast { AST_NODE_TYPES #undef __AST_NODE_TYPE -#define __AST_NODE_TYPE(NodeType) \ - Value *NodeType::codegen(CodeGenerator *generator) const \ - { \ - return generator->visit(this); \ - } +#define __AST_NODE_TYPE(NodeType) \ + Value *NodeType::codegen(CodeGenerator *generator) const { return generator->visit(this); } AST_NODE_TYPES #undef __AST_NODE_TYPE @@ -34,11 +31,8 @@ void NodeVisitor::dispatch(ASTNode *node) #undef __AST_NODE_TYPE } -#define __AST_NODE_TYPE(NodeType) \ - void NodeVisitor::dispatch(NodeType *node) \ - { \ - visit(node); \ - } +#define __AST_NODE_TYPE(NodeType) \ + void NodeVisitor::dispatch(NodeType *node) { visit(node); } AST_NODE_TYPES #undef __AST_NODE_TYPE diff --git a/src/ast/optimizers/Optimizers_tests.cpp b/src/ast/optimizers/Optimizers_tests.cpp index 20d00978..824d1461 100644 --- a/src/ast/optimizers/Optimizers_tests.cpp +++ b/src/ast/optimizers/Optimizers_tests.cpp @@ -1,9 +1,9 @@ #include "ConstantFolding.hpp" #include "ast/AST.hpp" +#include "executable/Program.hpp" #include "parser/Parser.hpp" #include "runtime/Value.hpp" #include "utilities.hpp" -#include "executable/Program.hpp" #include "gtest/gtest.h" @@ -502,7 +502,7 @@ TEST(Optimizer, ConstantFoldIntegerAddition) expected_ast->emplace( std::make_shared(std::vector>{ std::make_shared( "a", ContextType::STORE, SourceLocation{}) }, - std::make_shared(BigIntType{2}, SourceLocation{}), + std::make_shared(BigIntType{ 2 }, SourceLocation{}), "", SourceLocation{})); diff --git a/src/executable/Program.cpp b/src/executable/Program.cpp index 09a69c3f..2e64f33c 100644 --- a/src/executable/Program.cpp +++ b/src/executable/Program.cpp @@ -2,8 +2,8 @@ #include "executable/bytecode/codegen/BytecodeGenerator.hpp" #include "executable/llvm/LLVMGenerator.hpp" #include "executable/mlir/Dialect/Python/MLIRGenerator.hpp" -#include "utilities.hpp" #include "mlir/compile.hpp" +#include "utilities.hpp" Program::Program(std::string &&filename, std::vector &&argv) @@ -34,4 +34,4 @@ std::shared_ptr compile(std::shared_ptr node, } ASSERT_NOT_REACHED(); } -} \ No newline at end of file +}// namespace compiler \ No newline at end of file diff --git a/src/executable/bytecode/Bytecode.cpp b/src/executable/bytecode/Bytecode.cpp index 350e6c75..21cc7379 100644 --- a/src/executable/bytecode/Bytecode.cpp +++ b/src/executable/bytecode/Bytecode.cpp @@ -17,11 +17,11 @@ Bytecode::Bytecode(size_t register_count, InstructionVector instructions, std::shared_ptr program) : Function(register_count, - locals_count, - stack_size, - function_name, - FunctionExecutionBackend::BYTECODE, - std::move(program)), + locals_count, + stack_size, + function_name, + FunctionExecutionBackend::BYTECODE, + std::move(program)), m_instructions(std::move(instructions)) {} @@ -78,8 +78,12 @@ std::unique_ptr Bytecode::deserialize(std::span &buffer instructions.push_back(std::move(instruction)); } - return std::make_unique( - register_count, locals_count, stack_size, function_name, std::move(instructions), std::move(program)); + return std::make_unique(register_count, + locals_count, + stack_size, + function_name, + std::move(instructions), + std::move(program)); } PyResult Bytecode::call(VirtualMachine &vm, Interpreter &interpreter) const @@ -124,7 +128,7 @@ py::PyResult Bytecode::eval_loop(VirtualMachine &vm, Interpreter &int const auto end_instruction_it = end(); for (; vm.instruction_pointer() != end_instruction_it; - vm.set_instruction_pointer(std::next(vm.instruction_pointer()))) { + vm.set_instruction_pointer(std::next(vm.instruction_pointer()))) { ASSERT((*vm.instruction_pointer()).get()); const auto ¤t_ip = vm.instruction_pointer(); const auto &instruction = *current_ip; diff --git a/src/executable/bytecode/Bytecode.hpp b/src/executable/bytecode/Bytecode.hpp index 52e70a6f..2ac8218b 100644 --- a/src/executable/bytecode/Bytecode.hpp +++ b/src/executable/bytecode/Bytecode.hpp @@ -31,7 +31,8 @@ class Bytecode : public Function std::vector serialize() const override; - static std::unique_ptr deserialize(std::span &buffer, std::shared_ptr program); + static std::unique_ptr deserialize(std::span &buffer, + std::shared_ptr program); py::PyResult call(VirtualMachine &, Interpreter &) const override; py::PyResult call_without_setup(VirtualMachine &, Interpreter &) const override; diff --git a/src/executable/bytecode/codegen/BytecodeGenerator.cpp b/src/executable/bytecode/codegen/BytecodeGenerator.cpp index 1a2c3b5f..61fb2986 100644 --- a/src/executable/bytecode/codegen/BytecodeGenerator.cpp +++ b/src/executable/bytecode/codegen/BytecodeGenerator.cpp @@ -34,9 +34,9 @@ #include "executable/bytecode/instructions/Instructions.hpp" #include "executable/bytecode/instructions/Jump.hpp" #include "executable/bytecode/instructions/JumpForward.hpp" +#include "executable/bytecode/instructions/JumpIfExceptionMatch.hpp" #include "executable/bytecode/instructions/JumpIfFalse.hpp" #include "executable/bytecode/instructions/JumpIfFalseOrPop.hpp" -#include "executable/bytecode/instructions/JumpIfExceptionMatch.hpp" #include "executable/bytecode/instructions/JumpIfNotExceptionMatch.hpp" #include "executable/bytecode/instructions/JumpIfTrue.hpp" #include "executable/bytecode/instructions/JumpIfTrueOrPop.hpp" @@ -277,7 +277,7 @@ void BytecodeGenerator::store_name(const std::string &name, BytecodeValue *src) ASSERT(visibility->second->type == VariablesResolver::Scope::Type::CLASS); return *it; } else if (auto it = visibility->second->symbol_map.get_visible_symbol(name); - it.has_value()) { + it.has_value()) { return *it; } else { TODO(); @@ -396,7 +396,7 @@ void BytecodeGenerator::delete_var(const std::string &name) ASSERT(visibility->second->type == VariablesResolver::Scope::Type::CLASS); return *it; } else if (auto it = visibility->second->symbol_map.get_visible_symbol(name); - it.has_value()) { + it.has_value()) { return *it; } else { TODO(); @@ -699,7 +699,7 @@ Value *BytecodeGenerator::generate_function(const FunctionType *node) idx++; } for (size_t idx = node->args()->argument_names().size(); - const auto &arg_name : node->args()->kw_only_argument_names()) { + const auto &arg_name : node->args()->kw_only_argument_names()) { varnames.push_back(arg_name); ASSERT(symbol_map.get_visible_symbol(arg_name).has_value()); if (std::find(cellvars.begin(), cellvars.end(), arg_name) != cellvars.end()) { @@ -950,7 +950,7 @@ Value *BytecodeGenerator::visit(const Lambda *node) idx++; } for (size_t idx = node->args()->argument_names().size(); - const auto &arg_name : node->args()->kw_only_argument_names()) { + const auto &arg_name : node->args()->kw_only_argument_names()) { varnames.push_back(arg_name); ASSERT(symbol_map.get_visible_symbol(arg_name).has_value()); if (std::find(cellvars.begin(), cellvars.end(), arg_name) != cellvars.end()) { diff --git a/src/executable/bytecode/codegen/VariablesResolver.cpp b/src/executable/bytecode/codegen/VariablesResolver.cpp index 6258e612..77230c19 100644 --- a/src/executable/bytecode/codegen/VariablesResolver.cpp +++ b/src/executable/bytecode/codegen/VariablesResolver.cpp @@ -9,7 +9,9 @@ using namespace ast; namespace { bool captured_by_closure(VariablesResolver::Visibility v) -{ return v == VariablesResolver::Visibility::CELL || v == VariablesResolver::Visibility::FREE; } +{ + return v == VariablesResolver::Visibility::CELL || v == VariablesResolver::Visibility::FREE; +} }// namespace diff --git a/src/executable/bytecode/instructions/BuildList.hpp b/src/executable/bytecode/instructions/BuildList.hpp index 2beb9040..da2208c5 100644 --- a/src/executable/bytecode/instructions/BuildList.hpp +++ b/src/executable/bytecode/instructions/BuildList.hpp @@ -9,14 +9,11 @@ class BuildList final : public Instruction size_t m_size; public: - BuildList(Register dst, size_t size) - : m_dst(dst), m_size(size) - {} + BuildList(Register dst, size_t size) : m_dst(dst), m_size(size) {} std::string to_string() const final { - return fmt::format( - "BUILD_LIST r{:<3} (size={})", m_dst, m_size); + return fmt::format("BUILD_LIST r{:<3} (size={})", m_dst, m_size); } py::PyResult execute(VirtualMachine &, Interpreter &) const final; diff --git a/src/executable/bytecode/instructions/DeleteFast.cpp b/src/executable/bytecode/instructions/DeleteFast.cpp index a8080dff..d5dc4bc9 100644 --- a/src/executable/bytecode/instructions/DeleteFast.cpp +++ b/src/executable/bytecode/instructions/DeleteFast.cpp @@ -7,7 +7,7 @@ using namespace py; PyResult DeleteFast::execute(VirtualMachine &vm, Interpreter &) const { vm.stack_local(m_stack_index) = nullptr; - return Ok(py_none()); + return Ok(py_none()); } std::vector DeleteFast::serialize() const diff --git a/src/executable/bytecode/instructions/ForIter.hpp b/src/executable/bytecode/instructions/ForIter.hpp index 17893580..46f8737c 100644 --- a/src/executable/bytecode/instructions/ForIter.hpp +++ b/src/executable/bytecode/instructions/ForIter.hpp @@ -26,9 +26,7 @@ class ForIter final : public Instruction m_exit_label(std::move(exit_label)) {} - ForIter(Register dst, Register src, int32_t offset) - : ForIter(dst, src, offset, int32_t{ 0 }) - {} + ForIter(Register dst, Register src, int32_t offset) : ForIter(dst, src, offset, int32_t{ 0 }) {} ForIter(Register dst, Register src, int32_t offset, int32_t body_offset) : m_dst(dst), m_src(src), m_offset(offset), m_body_offset(body_offset) diff --git a/src/executable/bytecode/instructions/InplaceOp.cpp b/src/executable/bytecode/instructions/InplaceOp.cpp index c307f455..9545b392 100644 --- a/src/executable/bytecode/instructions/InplaceOp.cpp +++ b/src/executable/bytecode/instructions/InplaceOp.cpp @@ -1,7 +1,7 @@ #include "InplaceOp.hpp" +#include "runtime/PyObject.hpp" #include "runtime/Value.hpp" #include "vm/VM.hpp" -#include "runtime/PyObject.hpp" using namespace py; diff --git a/src/executable/bytecode/instructions/MakeFunction.cpp b/src/executable/bytecode/instructions/MakeFunction.cpp index 66214aeb..c97fb607 100644 --- a/src/executable/bytecode/instructions/MakeFunction.cpp +++ b/src/executable/bytecode/instructions/MakeFunction.cpp @@ -14,7 +14,7 @@ PyResult MakeFunction::execute(VirtualMachine &vm, Interpreter &interpret std::vector default_values; default_values.reserve(m_defaults_size); auto *start = vm.sp() - m_defaults_size - m_kw_defaults_size; - while (start != (vm.sp()- m_kw_defaults_size)) { + while (start != (vm.sp() - m_kw_defaults_size)) { default_values.push_back(*start); start = std::next(start); } diff --git a/src/executable/bytecode/instructions/MakeFunction.hpp b/src/executable/bytecode/instructions/MakeFunction.hpp index 3d46f44a..76ab7f3a 100644 --- a/src/executable/bytecode/instructions/MakeFunction.hpp +++ b/src/executable/bytecode/instructions/MakeFunction.hpp @@ -21,7 +21,10 @@ class MakeFunction : public Instruction m_kw_defaults_size(kw_defaults_size), m_captures_tuple(std::move(captures_tuple)) {} - std::string to_string() const final { return fmt::format("MAKE_FUNCTION r{} ({})", m_dst, m_name); } + std::string to_string() const final + { + return fmt::format("MAKE_FUNCTION r{} ({})", m_dst, m_name); + } py::PyResult execute(VirtualMachine &vm, Interpreter &interpreter) const final; diff --git a/src/executable/bytecode/instructions/Push.cpp b/src/executable/bytecode/instructions/Push.cpp index e1a0ce44..c452eca7 100644 --- a/src/executable/bytecode/instructions/Push.cpp +++ b/src/executable/bytecode/instructions/Push.cpp @@ -7,7 +7,7 @@ using namespace py; PyResult Push::execute(VirtualMachine &vm, Interpreter &) const { auto value = vm.reg(m_source); - vm.push(value); + vm.push(value); return Ok(py_none()); } diff --git a/src/executable/bytecode/instructions/Push.hpp b/src/executable/bytecode/instructions/Push.hpp index d478713a..cfda9178 100644 --- a/src/executable/bytecode/instructions/Push.hpp +++ b/src/executable/bytecode/instructions/Push.hpp @@ -8,10 +8,7 @@ class Push final : public Instruction public: Push(Register source) : m_source(source) {} - std::string to_string() const final - { - return fmt::format("PUSH r{:<3}", m_source); - } + std::string to_string() const final { return fmt::format("PUSH r{:<3}", m_source); } py::PyResult execute(VirtualMachine &vm, Interpreter &interpreter) const final; void relocate(size_t) final {} diff --git a/src/executable/mlir/Conversion/PythonToPythonBytecode/PythonToPythonBytecode.cpp b/src/executable/mlir/Conversion/PythonToPythonBytecode/PythonToPythonBytecode.cpp index 7e553eb9..7de4b401 100644 --- a/src/executable/mlir/Conversion/PythonToPythonBytecode/PythonToPythonBytecode.cpp +++ b/src/executable/mlir/Conversion/PythonToPythonBytecode/PythonToPythonBytecode.cpp @@ -1819,7 +1819,7 @@ namespace py { op, BlockRange{ cleanup_block }); } } else if (auto op = mlir::dyn_cast(childOp); - op && !op.getKind().has_value()) { + op && !op.getKind().has_value()) { auto *current = op->getBlock(); auto *next = rewriter.splitBlock(current, op->getIterator()); rewriter.setInsertionPointToEnd(current); diff --git a/src/executable/mlir/Dialect/Python/IR/Ops.cpp b/src/executable/mlir/Dialect/Python/IR/Ops.cpp index a20f0538..867c30a8 100644 --- a/src/executable/mlir/Dialect/Python/IR/Ops.cpp +++ b/src/executable/mlir/Dialect/Python/IR/Ops.cpp @@ -195,7 +195,7 @@ namespace py { getHandlers().end(), [&point]( mlir::Region &handler) { return point.getRegionOrNull() == &handler; }); - it != getHandlers().end()) { + it != getHandlers().end()) { if (std::next(it) != getHandlers().end()) { it++; regions.emplace_back(&*it, it->getArguments()); diff --git a/src/executable/mlir/Dialect/Python/MLIRGenerator.cpp b/src/executable/mlir/Dialect/Python/MLIRGenerator.cpp index 50108bec..faecd838 100644 --- a/src/executable/mlir/Dialect/Python/MLIRGenerator.cpp +++ b/src/executable/mlir/Dialect/Python/MLIRGenerator.cpp @@ -346,7 +346,7 @@ void MLIRGenerator::store_name(std::string_view name, ASSERT(visibility_map->type == VariablesResolver::Scope::Type::CLASS); return it->get().visibility; } else if (auto it = visibility_map->symbol_map.get_visible_symbol(std::string{ name }); - it.has_value()) { + it.has_value()) { return it->get().visibility; } else { TODO(); @@ -434,7 +434,7 @@ MLIRGenerator::MLIRValue *MLIRGenerator::load_name(std::string_view name, ASSERT(visibility_map->type == VariablesResolver::Scope::Type::CLASS); return it->get().visibility; } else if (auto it = visibility_map->symbol_map.get_visible_symbol(std::string{ name }); - it.has_value()) { + it.has_value()) { return it->get().visibility; } else { TODO(); @@ -516,7 +516,7 @@ void MLIRGenerator::delete_name(std::string_view name, const SourceLocation &loc ASSERT(visibility_map->type == VariablesResolver::Scope::Type::CLASS); return it->get().visibility; } else if (auto it = visibility_map->symbol_map.get_visible_symbol(std::string{ name }); - it.has_value()) { + it.has_value()) { return it->get().visibility; } else { TODO(); @@ -1103,7 +1103,7 @@ ast::Value *MLIRGenerator::visit(const ast::Call *node) } arg_values.push_back(static_cast( build_tuple(args, arg_requires_expansion, node->source_location())) - ->value); + ->value); } if (!node->keywords().empty()) { requires_kwargs_expansion = true; } { @@ -1131,7 +1131,7 @@ ast::Value *MLIRGenerator::visit(const ast::Call *node) } keyword_values.push_back(static_cast( build_dict(keys, values, kwarg_requires_expansion, node->source_location())) - ->value); + ->value); } } else { arg_values.reserve(node->args().size()); @@ -1584,9 +1584,9 @@ ast::Value *MLIRGenerator::visit(const ast::For *node) for (const auto &el : node->body()) { el->codegen(this); } if (m_context.builder().getInsertionBlock()->empty() || !m_context.builder() - .getInsertionBlock() - ->back() - .hasTrait()) { + .getInsertionBlock() + ->back() + .hasTrait()) { m_context.builder().create(m_context.builder().getUnknownLoc()); } @@ -2738,9 +2738,9 @@ ast::Value *MLIRGenerator::visit(const ast::Try *node) for (auto el : handler->body()) { el->codegen(this); } if (m_context.builder().getBlock()->empty() || !m_context.builder() - .getBlock() - ->back() - .hasTrait()) { + .getBlock() + ->back() + .hasTrait()) { m_context.builder().create( loc(m_context.builder(), m_context.filename(), node->source_location())); } diff --git a/src/executable/mlir/Target/PythonBytecode/LinearScanRegisterAllocation.hpp b/src/executable/mlir/Target/PythonBytecode/LinearScanRegisterAllocation.hpp index 6c641361..c044a0b0 100644 --- a/src/executable/mlir/Target/PythonBytecode/LinearScanRegisterAllocation.hpp +++ b/src/executable/mlir/Target/PythonBytecode/LinearScanRegisterAllocation.hpp @@ -106,8 +106,8 @@ class LinearScanRegisterAllocation expire_old_intervals(cur, active, inactive, handled, free, logger); // Collect available registers for this interval - auto available_regs = - collect_available_registers(cur, free, inactive, unhandled, *live_interval_analysis); + auto available_regs = collect_available_registers( + cur, free, inactive, unhandled, *live_interval_analysis); if (available_regs.none()) { logger->error("No available registers for {}", to_string(cur.value)); @@ -402,25 +402,31 @@ class LinearScanRegisterAllocation if (std::holds_alternative(input)) { auto forwarded = std::get(input); - if (auto for_iter = mlir::dyn_cast(forwarded.first)) { + if (auto for_iter = mlir::dyn_cast( + forwarded.first)) { logger->debug("Block argument is FOR_ITER loop variable"); auto iterator = for_iter.getIterator(); logger->debug("Iterator value: {}", to_string(iterator)); // Find the iterator's register - if (auto iter_it = value2mem_map.find(iterator); iter_it != value2mem_map.end()) { + if (auto iter_it = value2mem_map.find(iterator); + iter_it != value2mem_map.end()) { if (std::holds_alternative(iter_it->second)) { auto iterator_reg = std::get(iter_it->second).idx; logger->debug("Found iterator register: r{}", iterator_reg); - // Reserve this register for the duration of the loop variable's lifetime + // Reserve this register for the duration of the loop + // variable's lifetime foriter_reserved_regs[cur.value] = iterator_reg; // Mark the iterator register as busy free.set(iterator_reg, false); - logger->info("FOR_ITER FIX: Reserved r{} (iterator) for loop variable {}", - iterator_reg, to_string(cur.value)); + logger->info( + "FOR_ITER FIX: Reserved r{} (iterator) for loop " + "variable {}", + iterator_reg, + to_string(cur.value)); } else { logger->warn("Iterator register is not a Reg!"); } @@ -507,7 +513,8 @@ class LinearScanRegisterAllocation logger->trace("Freed r{} from {}", reg_idx, to_string(interval.value)); // If this was a FOR_ITER loop variable with a reserved iterator register, free it too - if (auto it = foriter_reserved_regs.find(interval.value); it != foriter_reserved_regs.end()) { + if (auto it = foriter_reserved_regs.find(interval.value); + it != foriter_reserved_regs.end()) { auto reserved_reg = it->second; free.set(reserved_reg, true); logger->info("FOR_ITER FIX: Freed reserved iterator register r{}", reserved_reg); @@ -530,10 +537,12 @@ class LinearScanRegisterAllocation logger->trace("Marked r{} as used for {}", reg_idx, to_string(interval.value)); // If this is a FOR_ITER loop variable, also mark the iterator register as used - if (auto it = foriter_reserved_regs.find(interval.value); it != foriter_reserved_regs.end()) { + if (auto it = foriter_reserved_regs.find(interval.value); + it != foriter_reserved_regs.end()) { auto reserved_reg = it->second; free.set(reserved_reg, false); - logger->trace("FOR_ITER FIX: Marked reserved iterator register r{} as used", reserved_reg); + logger->trace( + "FOR_ITER FIX: Marked reserved iterator register r{} as used", reserved_reg); } } @@ -596,25 +605,19 @@ class LinearScanRegisterAllocation // Print header llvm::outs() << "Value | "; - for (size_t t = 0; t < max_timestep; ++t) { - llvm::outs() << llvm::format("%3d", t); - } + for (size_t t = 0; t < max_timestep; ++t) { llvm::outs() << llvm::format("%3d", t); } llvm::outs() << "\n"; // Print separator llvm::outs() << "--------------------------------------------------------+-"; - for (size_t t = 0; t < max_timestep; ++t) { - llvm::outs() << "---"; - } + for (size_t t = 0; t < max_timestep; ++t) { llvm::outs() << "---"; } llvm::outs() << "\n"; // Print each value's liveness for (const auto &interval : live_interval_analysis->sorted_live_intervals) { // Print value name (truncate to 55 chars) std::string value_str = to_string(interval.value); - if (value_str.length() > 55) { - value_str = value_str.substr(0, 52) + "..."; - } + if (value_str.length() > 55) { value_str = value_str.substr(0, 52) + "..."; } llvm::outs() << llvm::format("%-55s", value_str.c_str()) << " | "; // Print liveness for each timestep @@ -652,25 +655,19 @@ class LinearScanRegisterAllocation // Print header llvm::outs() << "Value | "; - for (size_t t = 0; t < max_timestep; ++t) { - llvm::outs() << llvm::format("%3d", t); - } + for (size_t t = 0; t < max_timestep; ++t) { llvm::outs() << llvm::format("%3d", t); } llvm::outs() << "\n"; // Print separator llvm::outs() << "--------------------------------------------------------+-"; - for (size_t t = 0; t < max_timestep; ++t) { - llvm::outs() << "---"; - } + for (size_t t = 0; t < max_timestep; ++t) { llvm::outs() << "---"; } llvm::outs() << "\n"; // Print each value's register assignment for (const auto &interval : live_interval_analysis->sorted_live_intervals) { // Print value name (truncate to 55 chars) std::string value_str = to_string(interval.value); - if (value_str.length() > 55) { - value_str = value_str.substr(0, 52) + "..."; - } + if (value_str.length() > 55) { value_str = value_str.substr(0, 52) + "..."; } llvm::outs() << llvm::format("%-55s", value_str.c_str()) << " | "; // Find register for this value diff --git a/src/executable/mlir/Target/PythonBytecode/LiveAnalysis.hpp b/src/executable/mlir/Target/PythonBytecode/LiveAnalysis.hpp index 993fd8e5..6a639fb9 100644 --- a/src/executable/mlir/Target/PythonBytecode/LiveAnalysis.hpp +++ b/src/executable/mlir/Target/PythonBytecode/LiveAnalysis.hpp @@ -1,8 +1,8 @@ #pragma once +#include "Dialect/EmitPythonBytecode/IR/EmitPythonBytecode.hpp" #include "RegisterAllocationLogger.hpp" #include "RegisterAllocationTypes.hpp" -#include "Dialect/EmitPythonBytecode/IR/EmitPythonBytecode.hpp" #include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h" #include "mlir/Dialect/Func/IR/FuncOps.h" #include "mlir/IR/AsmState.h" @@ -57,7 +57,8 @@ class LiveAnalysis void analyse(mlir::func::FuncOp &fn) { auto logger = get_regalloc_logger(); - logger->info("Starting backward dataflow live analysis for function: {}", fn.getName().str()); + logger->info( + "Starting backward dataflow live analysis for function: {}", fn.getName().str()); auto ®ion = fn.getRegion(); auto sorted_blocks = sortBlocks(region); @@ -134,15 +135,11 @@ class LiveAnalysis // Add operands to Use (if not already defined) for (const auto &operand : op.getOperands()) { - if (!info.def.contains(operand)) { - info.use.insert(operand); - } + if (!info.def.contains(operand)) { info.use.insert(operand); } } // Add results to Def - for (const auto &result : op.getResults()) { - info.def.insert(result); - } + for (const auto &result : op.getResults()) { info.def.insert(result); } } // Handle terminators specially @@ -171,8 +168,7 @@ class LiveAnalysis } } - void handle_conditional_branch( - mlir::emitpybytecode::JumpIfFalse branch, + void handle_conditional_branch(mlir::emitpybytecode::JumpIfFalse branch, std::vector, mlir::BlockArgument>> &block_parameters_to_args) { @@ -189,13 +185,13 @@ class LiveAnalysis } } - void handle_unconditional_branch( - mlir::cf::BranchOp branch, + void handle_unconditional_branch(mlir::cf::BranchOp branch, std::vector, mlir::BlockArgument>> &block_parameters_to_args) { auto *jmp_block = branch.getDest(); - for (const auto &[p, arg] : llvm::zip(branch.getDestOperands(), jmp_block->getArguments())) { + for (const auto &[p, arg] : + llvm::zip(branch.getDestOperands(), jmp_block->getArguments())) { block_parameters_to_args.emplace_back(p, arg); } } @@ -258,21 +254,15 @@ class LiveAnalysis // LiveIn[B] = Use[B] ∪ (LiveOut[B] - Def[B]) info.live_in = info.use; for (const auto &val : info.live_out) { - if (!info.def.contains(val)) { - info.live_in.insert(val); - } + if (!info.def.contains(val)) { info.live_in.insert(val); } } // Add ForwardedOutputs to LiveIn (they're "defined" by the terminator but need // to be live for the successor) - for (const auto &fwd : info.forwarded_outputs) { - info.live_in.insert(fwd); - } + for (const auto &fwd : info.forwarded_outputs) { info.live_in.insert(fwd); } // Check if LiveIn changed - if (info.live_in != old_live_in) { - changed = true; - } + if (info.live_in != old_live_in) { changed = true; } } } @@ -320,14 +310,10 @@ class LiveAnalysis alive_before_op[i] = alive_after; // Remove values defined by this operation (they die here going backward) - for (auto result : op->getResults()) { - alive_before_op[i].erase(result); - } + for (auto result : op->getResults()) { alive_before_op[i].erase(result); } // Add values used by this operation (they need to be alive going backward) - for (auto operand : op->getOperands()) { - alive_before_op[i].insert(operand); - } + for (auto operand : op->getOperands()) { alive_before_op[i].insert(operand); } // Propagate backward for next iteration alive_after = alive_before_op[i]; @@ -344,9 +330,7 @@ class LiveAnalysis // Non-pure operations must be emitted even if results are unused if (!mlir::isPure(op)) { // Re-add any results to ensure they get register assignments - for (auto result : op->getResults()) { - alive_before_op[i].insert(result); - } + for (auto result : op->getResults()) { alive_before_op[i].insert(result); } } } @@ -354,16 +338,16 @@ class LiveAnalysis // (they're "defined" by the terminator but need to be live for the successor) if (!info.operations.empty()) { for (const auto &fwd : info.forwarded_outputs) { - if (info.live_in.contains(fwd)) { - alive_before_op[0].insert(fwd); - } + if (info.live_in.contains(fwd)) { alive_before_op[0].insert(fwd); } } } // Sanity check: alive_before[0] should equal LiveIn // (We computed it backward from LiveOut, should match forward computation) if (!alive_before_op.empty() && alive_before_op[0] != info.live_in) { - logger->warn("Block {} liveness mismatch: alive_before[0] has {} values, LiveIn has {} values", + logger->warn( + "Block {} liveness mismatch: alive_before[0] has {} values, LiveIn has {} " + "values", static_cast(block), alive_before_op[0].size(), info.live_in.size()); @@ -377,9 +361,7 @@ class LiveAnalysis } logger->debug(" Values in alive_before[0] but not LiveIn:"); for (const auto &val : alive_before_op[0]) { - if (!info.live_in.contains(val)) { - logger->debug(" {}", to_string(val)); - } + if (!info.live_in.contains(val)) { logger->debug(" {}", to_string(val)); } } } @@ -403,7 +385,8 @@ class LiveAnalysis end, info.operations.size(), info.live_in.size()); - if (block->getTerminator() && mlir::isa(block->getTerminator())) { + if (block->getTerminator() + && mlir::isa(block->getTerminator())) { logger->debug(" ^ FOR_ITER block"); } } @@ -413,8 +396,8 @@ class LiveAnalysis * Propagate block argument values through liveness information */ void propagate_block_arguments( - const std::vector, mlir::BlockArgument>> - &block_parameters_to_args, + const std::vector, + mlir::BlockArgument>> &block_parameters_to_args, const std::map> &blocks_span) { for (const auto &[param, arg] : block_parameters_to_args) { @@ -451,22 +434,23 @@ class LiveAnalysis value = std::get<0>(std::get(value)); } - auto start = std::visit( - overloaded{ - [this](const auto &v) { return block_input_mappings.find(v); }, - [this](const BlockArgumentInputs &) { - TODO(); - return block_input_mappings.end(); - }, - }, - value); + auto start = + std::visit(overloaded{ + [this](const auto &v) { return block_input_mappings.find(v); }, + [this](const BlockArgumentInputs &) { + TODO(); + return block_input_mappings.end(); + }, + }, + value); auto it = start; while (it != block_input_mappings.end()) { ASSERT(it->second.size() == 1); value = *it->second.begin(); start->second.erase(start->second.begin()); - start->second.insert(mlir::cast(std::get(value))); + start->second.insert( + mlir::cast(std::get(value))); it = block_input_mappings.find(std::get(value)); } } diff --git a/src/executable/mlir/Target/PythonBytecode/LiveIntervalAnalysis.hpp b/src/executable/mlir/Target/PythonBytecode/LiveIntervalAnalysis.hpp index 1eb68abb..d1b1a50e 100644 --- a/src/executable/mlir/Target/PythonBytecode/LiveIntervalAnalysis.hpp +++ b/src/executable/mlir/Target/PythonBytecode/LiveIntervalAnalysis.hpp @@ -118,15 +118,16 @@ class LiveIntervalAnalysis sorted_live_intervals = std::move(unsorted_live_intervals); - logger->info("Live interval analysis complete. Found {} intervals", - sorted_live_intervals.size()); + logger->info( + "Live interval analysis complete. Found {} intervals", sorted_live_intervals.size()); // Log intervals at debug level (temporarily for debugging) for (const auto &interval : sorted_live_intervals) { // Log all intervals, especially GET_ITER if (std::holds_alternative(interval.value)) { auto val = std::get(interval.value); - if (val.getDefiningOp() && mlir::isa(val.getDefiningOp())) { + if (val.getDefiningOp() + && mlir::isa(val.getDefiningOp())) { logger->info("GET_ITER LiveInterval: start={}, end={}, {} sub-intervals", interval.start(), interval.end(), @@ -163,19 +164,21 @@ class LiveIntervalAnalysis values_to_track.push_back(std::get(alive_value)); } else { // BlockArgumentInputs: track all the inputs - const auto &inputs = std::get<1>(std::get(alive_value)); + const auto &inputs = + std::get<1>(std::get(alive_value)); values_to_track.insert(values_to_track.end(), inputs.begin(), inputs.end()); } // Update interval for each value for (auto value : values_to_track) { - auto it = std::find_if(intervals.begin(), intervals.end(), [&value](const auto &interval) { - return interval.value == value; - }); + auto it = std::find_if(intervals.begin(), + intervals.end(), + [&value](const auto &interval) { return interval.value == value; }); if (it == intervals.end()) { // Create new interval - intervals.emplace_back(std::vector{ std::make_tuple(timestep, timestep + 1) }, value); + intervals.emplace_back( + std::vector{ std::make_tuple(timestep, timestep + 1) }, value); } else { // Extend existing interval auto &value_intervals = it->intervals; diff --git a/src/executable/mlir/Target/PythonBytecode/RegisterAllocationLogger.hpp b/src/executable/mlir/Target/PythonBytecode/RegisterAllocationLogger.hpp index 208c2874..5ee9d036 100644 --- a/src/executable/mlir/Target/PythonBytecode/RegisterAllocationLogger.hpp +++ b/src/executable/mlir/Target/PythonBytecode/RegisterAllocationLogger.hpp @@ -2,9 +2,9 @@ #include "mlir/IR/Operation.h" #include "mlir/IR/Value.h" -#include "llvm/Support/raw_ostream.h" -#include "spdlog/spdlog.h" #include "spdlog/sinks/stdout_color_sinks.h" +#include "spdlog/spdlog.h" +#include "llvm/Support/raw_ostream.h" #include #include diff --git a/src/executable/mlir/Target/PythonBytecode/RegisterAllocationTypes.hpp b/src/executable/mlir/Target/PythonBytecode/RegisterAllocationTypes.hpp index a5279308..bbb88f42 100644 --- a/src/executable/mlir/Target/PythonBytecode/RegisterAllocationTypes.hpp +++ b/src/executable/mlir/Target/PythonBytecode/RegisterAllocationTypes.hpp @@ -39,7 +39,8 @@ struct ValueMappingComparator // Map from MLIR values to some type T (used for register assignments, etc.) template -using ValueMapping = std::map, ValueT, ValueMappingComparator>; +using ValueMapping = + std::map, ValueT, ValueMappingComparator>; // Comparator for BlockArgument sets inline constexpr auto block_arg_comparator = [](const mlir::BlockArgument &lhs, diff --git a/src/executable/mlir/Target/PythonBytecode/TranslateToPythonBytecode.cpp b/src/executable/mlir/Target/PythonBytecode/TranslateToPythonBytecode.cpp index 835460fe..d14c0dfc 100644 --- a/src/executable/mlir/Target/PythonBytecode/TranslateToPythonBytecode.cpp +++ b/src/executable/mlir/Target/PythonBytecode/TranslateToPythonBytecode.cpp @@ -79,7 +79,6 @@ #include "executable/bytecode/instructions/YieldLoad.hpp" #include "executable/bytecode/instructions/YieldValue.hpp" -#include "mlir/Analysis/TopologicalSortUtils.h" #include "mlir/Analysis/TopologicalSortUtils.h" #include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h" #include "mlir/Dialect/Func/IR/FuncOps.h" diff --git a/src/executable/mlir/Target/test/PythonBytecode/RegisterAllocation_tests.cpp b/src/executable/mlir/Target/test/PythonBytecode/RegisterAllocation_tests.cpp index 43171bc3..e9b4982f 100644 --- a/src/executable/mlir/Target/test/PythonBytecode/RegisterAllocation_tests.cpp +++ b/src/executable/mlir/Target/test/PythonBytecode/RegisterAllocation_tests.cpp @@ -160,7 +160,9 @@ class RegisterAllocationTest : public ::testing::Test // Parse the MLIR IR that reproduces the FOR_ITER bug mlir::OwningOpRef parseForIterBugIR() - { return mlir::parseSourceString(FORITER_BUG_MLIR, &m_context); } + { + return mlir::parseSourceString(FORITER_BUG_MLIR, &m_context); + } }; /** @@ -220,9 +222,7 @@ TEST_F(RegisterAllocationTest, ForIterIteratorRegisterNotReusedInLoopBody) while (!worklist.empty()) { auto *block = worklist.pop_back_val(); - if (block == loop_exit || loopBlocks.contains(block)) { - continue; - } + if (block == loop_exit || loopBlocks.contains(block)) { continue; } loopBlocks.insert(block); // Add successors to worklist @@ -240,9 +240,7 @@ TEST_F(RegisterAllocationTest, ForIterIteratorRegisterNotReusedInLoopBody) func.walk([&](mlir::emitpybytecode::LoadNameOp op) { // Only collect LOAD_NAME operations that are in loop body blocks - if (loopBlocks.contains(op->getBlock())) { - loopBodyLoadNames.push_back(op.getResult()); - } + if (loopBlocks.contains(op->getBlock())) { loopBodyLoadNames.push_back(op.getResult()); } }); ASSERT_FALSE(loopBodyLoadNames.empty()) << "No LOAD_NAME operations found in loop body"; diff --git a/src/executable/mlir/compile.hpp b/src/executable/mlir/compile.hpp index c6463953..4b8ff06f 100644 --- a/src/executable/mlir/compile.hpp +++ b/src/executable/mlir/compile.hpp @@ -7,7 +7,7 @@ #include namespace ast { - class Module; +class Module; } namespace compiler::mlir { diff --git a/src/lexer/Lexer_tests.cpp b/src/lexer/Lexer_tests.cpp index 94ad914b..275bbe58 100644 --- a/src/lexer/Lexer_tests.cpp +++ b/src/lexer/Lexer_tests.cpp @@ -761,13 +761,11 @@ TEST(Lexer, BreakupLine) "a = \\\n" " 1\n"; - std::vector expected_tokens{ - Token::TokenType::NAME, + std::vector expected_tokens{ Token::TokenType::NAME, Token::TokenType::EQUAL, Token::TokenType::NUMBER, Token::TokenType::NEWLINE, - Token::TokenType::ENDMARKER - }; + Token::TokenType::ENDMARKER }; assert_generates_tokens(program, expected_tokens); } diff --git a/src/memory/Heap.hpp b/src/memory/Heap.hpp index 4b838f71..75eceb73 100644 --- a/src/memory/Heap.hpp +++ b/src/memory/Heap.hpp @@ -1,8 +1,8 @@ #pragma once #include "GarbageCollector.hpp" -#include "utilities.hpp" #include "runtime/forward.hpp" +#include "utilities.hpp" #include #include diff --git a/src/runtime/BaseException.cpp b/src/runtime/BaseException.cpp index 93604589..889b9aaa 100644 --- a/src/runtime/BaseException.cpp +++ b/src/runtime/BaseException.cpp @@ -134,7 +134,9 @@ namespace { std::once_flag base_exception_flag; std::unique_ptr register_base_exception() - { return std::move(klass("BaseException").type); } + { + return std::move(klass("BaseException").type); + } }// namespace std::function()> BaseException::type_factory() diff --git a/src/runtime/CustomPyObject.hpp b/src/runtime/CustomPyObject.hpp index a2ed93d5..407bd9e7 100644 --- a/src/runtime/CustomPyObject.hpp +++ b/src/runtime/CustomPyObject.hpp @@ -7,7 +7,7 @@ class CustomPyObject : public PyBaseObject { public: CustomPyObject(const PyType *type); - + std::string to_string() const override; }; }// namespace py \ No newline at end of file diff --git a/src/runtime/Exception.hpp b/src/runtime/Exception.hpp index 2d5fd2fa..b804c58c 100644 --- a/src/runtime/Exception.hpp +++ b/src/runtime/Exception.hpp @@ -38,7 +38,8 @@ class Exception : public BaseException }; -template inline BaseException *exception(const std::string &message, Args &&...args) +template +inline BaseException *exception(const std::string &message, Args &&...args) { auto *args_tuple = PyTuple::create(PyString::create(fmt::format(message, std::forward(args)...))); diff --git a/src/runtime/ImportError.cpp b/src/runtime/ImportError.cpp index adb9750d..d671ece4 100644 --- a/src/runtime/ImportError.cpp +++ b/src/runtime/ImportError.cpp @@ -68,8 +68,8 @@ namespace { std::unique_ptr register_import_error() { return std::move(klass("ImportError", Exception::class_type()) - .attr("name", &ImportError::m_name) - .type); + .attr("name", &ImportError::m_name) + .type); } }// namespace diff --git a/src/runtime/KeyError.hpp b/src/runtime/KeyError.hpp index 791c906b..0cae1e8b 100644 --- a/src/runtime/KeyError.hpp +++ b/src/runtime/KeyError.hpp @@ -11,7 +11,7 @@ class KeyError : public Exception { friend class ::Heap; template - friend BaseException *key_error(const std::string &message, Args &&... args); + friend BaseException *key_error(const std::string &message, Args &&...args); private: KeyError(PyType *type); @@ -29,7 +29,7 @@ class KeyError : public Exception }; template -inline BaseException *key_error(const std::string &message, Args &&... args) +inline BaseException *key_error(const std::string &message, Args &&...args) { auto msg = PyString::create(fmt::format(message, std::forward(args)...)); ASSERT(msg.is_ok()); diff --git a/src/runtime/PyAsyncGenerator.cpp b/src/runtime/PyAsyncGenerator.cpp index 3b47815c..c2c2a4b3 100644 --- a/src/runtime/PyAsyncGenerator.cpp +++ b/src/runtime/PyAsyncGenerator.cpp @@ -15,7 +15,9 @@ template<> PyAsyncGenerator *as(PyObject *obj) template<> const PyAsyncGenerator *as(const PyObject *obj) { - if (obj->type() == types::async_generator()) { return static_cast(obj); } + if (obj->type() == types::async_generator()) { + return static_cast(obj); + } return nullptr; } @@ -28,12 +30,12 @@ PyAsyncGenerator::PyAsyncGenerator(PyFrame *frame, PyString *name, PyString *qualname) : GeneratorInterface(types::BuiltinTypes::the().async_generator(), - frame, - std::move(stack_frame), - is_running, - code, - name, - qualname) + frame, + std::move(stack_frame), + is_running, + code, + name, + qualname) {} PyResult PyAsyncGenerator::create(PyFrame *frame, @@ -55,8 +57,8 @@ namespace { std::unique_ptr register_async_generator() { return std::move(klass(PyAsyncGenerator::GeneratorTypeName) - .def("close", &PyAsyncGenerator::close) - .type); + .def("close", &PyAsyncGenerator::close) + .type); } }// namespace diff --git a/src/runtime/PyByteArray.cpp b/src/runtime/PyByteArray.cpp index 3ed31935..be5bd773 100644 --- a/src/runtime/PyByteArray.cpp +++ b/src/runtime/PyByteArray.cpp @@ -501,10 +501,10 @@ namespace { std::unique_ptr register_bytearray() { return std::move(klass("bytearray") - .def("find", &PyByteArray::find) - .def("translate", &PyByteArray::translate) - .staticmethod("maketrans", &PyByteArray::maketrans) - .type); + .def("find", &PyByteArray::find) + .def("translate", &PyByteArray::translate) + .staticmethod("maketrans", &PyByteArray::maketrans) + .type); } }// namespace diff --git a/src/runtime/PyBytes.cpp b/src/runtime/PyBytes.cpp index a562f4ce..b18b4d2e 100644 --- a/src/runtime/PyBytes.cpp +++ b/src/runtime/PyBytes.cpp @@ -257,8 +257,7 @@ namespace { std::unique_ptr register_bytes() { - return std::move( - klass("bytes") + return std::move(klass("bytes") .def("decode", [](PyBytes *obj, PyTuple *args, PyDict *kwargs) -> PyResult { std::optional encoding; diff --git a/src/runtime/PyClassMethod.cpp b/src/runtime/PyClassMethod.cpp index eaec4df3..34cbb8f1 100644 --- a/src/runtime/PyClassMethod.cpp +++ b/src/runtime/PyClassMethod.cpp @@ -89,8 +89,8 @@ namespace { std::unique_ptr register_classmethod() { return std::move(klass("classmethod") - .attribute_readonly("__func__", &PyClassMethod::m_callable) - .type); + .attribute_readonly("__func__", &PyClassMethod::m_callable) + .type); } }// namespace diff --git a/src/runtime/PyCode.cpp b/src/runtime/PyCode.cpp index 546c679e..7ebd759a 100644 --- a/src/runtime/PyCode.cpp +++ b/src/runtime/PyCode.cpp @@ -184,9 +184,7 @@ PyResult PyCode::eval(PyObject *globals, [[maybe_unused]] auto scoped_stack = VirtualMachine::the().interpreter().setup_call_stack(m_function, function_frame); - if (m_name == "_combine_flags") { - - } + if (m_name == "_combine_flags") {} for (size_t i = 0; i < cellvars_count(); ++i) { auto cell = PyCell::create(); diff --git a/src/runtime/PyComplex.hpp b/src/runtime/PyComplex.hpp index d8009c8a..93a5fb80 100644 --- a/src/runtime/PyComplex.hpp +++ b/src/runtime/PyComplex.hpp @@ -22,7 +22,7 @@ class PyComplex : public PyBaseObject PyComplex(PyType *, std::complex); -public: + public: static std::function()> type_factory(); PyType *static_type() const override; }; diff --git a/src/runtime/PyCoroutine.cpp b/src/runtime/PyCoroutine.cpp index 3a1dbe3e..8debee36 100644 --- a/src/runtime/PyCoroutine.cpp +++ b/src/runtime/PyCoroutine.cpp @@ -28,12 +28,12 @@ PyCoroutine::PyCoroutine(PyFrame *frame, PyString *name, PyString *qualname) : GeneratorInterface(types::BuiltinTypes::the().coroutine(), - frame, - std::move(stack_frame), - is_running, - code, - name, - qualname) + frame, + std::move(stack_frame), + is_running, + code, + name, + qualname) {} PyResult PyCoroutine::create(PyFrame *frame, @@ -55,8 +55,8 @@ namespace { std::unique_ptr register_coroutine() { return std::move(klass(PyCoroutine::GeneratorTypeName) - .def("close", &PyCoroutine::close) - .type); + .def("close", &PyCoroutine::close) + .type); } }// namespace diff --git a/src/runtime/PyDict.cpp b/src/runtime/PyDict.cpp index 407e1970..ef9f46ce 100644 --- a/src/runtime/PyDict.cpp +++ b/src/runtime/PyDict.cpp @@ -431,8 +431,7 @@ namespace { std::unique_ptr register_dict() { - return std::move( - klass("dict") + return std::move(klass("dict") .def( "get", +[](PyDict *self, PyTuple *args, PyDict *kwargs) { diff --git a/src/runtime/PyFrame.cpp b/src/runtime/PyFrame.cpp index 268f5a5b..210cf50d 100644 --- a/src/runtime/PyFrame.cpp +++ b/src/runtime/PyFrame.cpp @@ -107,7 +107,7 @@ BaseException *PyFrame::pop_exception() { ASSERT(!m_exception_stack->empty()); auto *exception = m_exception_stack->back().exception; - spdlog::debug("PyFrame::pop_exception: @{}", static_cast(this)); + spdlog::debug("PyFrame::pop_exception: @{}", static_cast(this)); spdlog::debug("PyFrame::pop_exception: current exception count {}", m_exception_stack->size()); spdlog::debug("PyFrame::pop_exception: Popped exception {}", exception->to_string()); m_exception_stack->pop_back(); diff --git a/src/runtime/PyFunction.cpp b/src/runtime/PyFunction.cpp index 78c2a2e4..1329d764 100644 --- a/src/runtime/PyFunction.cpp +++ b/src/runtime/PyFunction.cpp @@ -129,31 +129,31 @@ std::function()> PyFunction::type_factory() static std::unique_ptr type = nullptr; std::call_once(function_flag, []() { type = std::move(klass("function") - .attr("__code__", &PyFunction::m_code) - .attr("__globals__", &PyFunction::m_globals) - .attr("__dict__", &PyFunction::m_dict) - .attr("__name__", &PyFunction::m_name) - .attr("__qualname__", &PyFunction::m_qualname) - .attr("__doc__", &PyFunction::m_doc) - .property_readonly("__closure__", - [](PyFunction *self) { return Ok(self->m_closure); }) - .property( - "__doc__", - [](PyFunction *self) { return Ok(self->m_doc); }, - [](PyFunction *self, PyObject *d) { - self->m_doc = d; - return Ok(std::monostate{}); - }) - .property_readonly("__globals__", - [](PyFunction *self) { return Ok(self->m_globals); }) - .property( - "__module__", - [](PyFunction *self) { return Ok(self->m_module); }, - [](PyFunction *self, PyObject *m) { - self->m_module = m; - return Ok(std::monostate{}); - }) - .type); + .attr("__code__", &PyFunction::m_code) + .attr("__globals__", &PyFunction::m_globals) + .attr("__dict__", &PyFunction::m_dict) + .attr("__name__", &PyFunction::m_name) + .attr("__qualname__", &PyFunction::m_qualname) + .attr("__doc__", &PyFunction::m_doc) + .property_readonly( + "__closure__", [](PyFunction *self) { return Ok(self->m_closure); }) + .property( + "__doc__", + [](PyFunction *self) { return Ok(self->m_doc); }, + [](PyFunction *self, PyObject *d) { + self->m_doc = d; + return Ok(std::monostate{}); + }) + .property_readonly( + "__globals__", [](PyFunction *self) { return Ok(self->m_globals); }) + .property( + "__module__", + [](PyFunction *self) { return Ok(self->m_module); }, + [](PyFunction *self, PyObject *m) { + self->m_module = m; + return Ok(std::monostate{}); + }) + .type); }); return std::move(type); }; diff --git a/src/runtime/PyGenerator.cpp b/src/runtime/PyGenerator.cpp index 31710fd3..349c8be1 100644 --- a/src/runtime/PyGenerator.cpp +++ b/src/runtime/PyGenerator.cpp @@ -28,12 +28,12 @@ PyGenerator::PyGenerator(PyFrame *frame, PyString *name, PyString *qualname) : GeneratorInterface(types::BuiltinTypes::the().generator(), - frame, - std::move(stack_frame), - is_running, - code, - name, - qualname) + frame, + std::move(stack_frame), + is_running, + code, + name, + qualname) {} PyResult PyGenerator::create(PyFrame *frame, @@ -55,9 +55,9 @@ namespace { std::unique_ptr register_generator() { return std::move(klass(PyGenerator::GeneratorTypeName) - .def("close", &PyGenerator::close) - .def("send", &PyGenerator::send) - .type); + .def("close", &PyGenerator::close) + .def("send", &PyGenerator::send) + .type); } }// namespace diff --git a/src/runtime/PyGetSetDescriptor.cpp b/src/runtime/PyGetSetDescriptor.cpp index 56385988..890c2ce2 100644 --- a/src/runtime/PyGetSetDescriptor.cpp +++ b/src/runtime/PyGetSetDescriptor.cpp @@ -13,13 +13,17 @@ namespace py { template<> PyGetSetDescriptor *as(PyObject *obj) { - if (obj->type() == types::getset_descriptor()) { return static_cast(obj); } + if (obj->type() == types::getset_descriptor()) { + return static_cast(obj); + } return nullptr; } template<> const PyGetSetDescriptor *as(const PyObject *obj) { - if (obj->type() == types::getset_descriptor()) { return static_cast(obj); } + if (obj->type() == types::getset_descriptor()) { + return static_cast(obj); + } return nullptr; } diff --git a/src/runtime/PyInteger.cpp b/src/runtime/PyInteger.cpp index bd65fcb9..0475652c 100644 --- a/src/runtime/PyInteger.cpp +++ b/src/runtime/PyInteger.cpp @@ -40,10 +40,14 @@ PyInteger::PyInteger(TypePrototype &type, BigIntType value) {} PyInteger::PyInteger(PyType *type, BigIntType value) : PyInteger(type) -{ m_value = Number{ std::move(value) }; } +{ + m_value = Number{ std::move(value) }; +} PyResult PyInteger::create(int64_t value) -{ return PyInteger::create(BigIntType{ value }); } +{ + return PyInteger::create(BigIntType{ value }); +} PyResult PyInteger::create(BigIntType value) { @@ -195,7 +199,9 @@ PyResult PyInteger::__rshift__(const PyObject *obj) const } PyResult PyInteger::bit_length() const -{ return PyInteger::create(mpz_sizeinbase(as_big_int().get_mpz_t(), 2)); } +{ + return PyInteger::create(mpz_sizeinbase(as_big_int().get_mpz_t(), 2)); +} PyResult PyInteger::bit_count() const { diff --git a/src/runtime/PyIterator.hpp b/src/runtime/PyIterator.hpp index a6620c1e..7588fb6f 100644 --- a/src/runtime/PyIterator.hpp +++ b/src/runtime/PyIterator.hpp @@ -23,7 +23,7 @@ class PyIterator : public PyBaseObject PyResult __len__() const; - PyType *static_type() const override; + PyType *static_type() const override; static std::function()> type_factory(); }; diff --git a/src/runtime/PyList.cpp b/src/runtime/PyList.cpp index 6c521c67..7cb52b3c 100644 --- a/src/runtime/PyList.cpp +++ b/src/runtime/PyList.cpp @@ -651,8 +651,7 @@ namespace { std::unique_ptr register_list() { - return std::move( - klass("list") + return std::move(klass("list") .def("append", &PyList::append) .def("extend", &PyList::extend) .def( diff --git a/src/runtime/PyMappingProxy.cpp b/src/runtime/PyMappingProxy.cpp index 1d05da94..f2498dfa 100644 --- a/src/runtime/PyMappingProxy.cpp +++ b/src/runtime/PyMappingProxy.cpp @@ -113,11 +113,11 @@ namespace { std::unique_ptr mappingproxy_reversed() { return std::move(klass("mappingproxy") - .def("get", &PyMappingProxy::get) - .def("items", &PyMappingProxy::items) - .def("keys", &PyMappingProxy::keys) - .def("value", &PyMappingProxy::values) - .type); + .def("get", &PyMappingProxy::get) + .def("items", &PyMappingProxy::items) + .def("keys", &PyMappingProxy::keys) + .def("value", &PyMappingProxy::values) + .type); } }// namespace diff --git a/src/runtime/PyMemberDescriptor.cpp b/src/runtime/PyMemberDescriptor.cpp index 860fdd0a..e159b136 100644 --- a/src/runtime/PyMemberDescriptor.cpp +++ b/src/runtime/PyMemberDescriptor.cpp @@ -12,13 +12,17 @@ namespace py { template<> PyMemberDescriptor *as(PyObject *obj) { - if (obj->type() == types::member_descriptor()) { return static_cast(obj); } + if (obj->type() == types::member_descriptor()) { + return static_cast(obj); + } return nullptr; } template<> const PyMemberDescriptor *as(const PyObject *obj) { - if (obj->type() == types::member_descriptor()) { return static_cast(obj); } + if (obj->type() == types::member_descriptor()) { + return static_cast(obj); + } return nullptr; } diff --git a/src/runtime/PyMemoryView.cpp b/src/runtime/PyMemoryView.cpp index 523cbf56..c52c90ac 100644 --- a/src/runtime/PyMemoryView.cpp +++ b/src/runtime/PyMemoryView.cpp @@ -342,13 +342,13 @@ namespace { std::unique_ptr register_memoryview() { return std::move(klass("memoryview") - .def("cast", &PyMemoryView::cast) - .def("tolist", &PyMemoryView::tolist) - .property_readonly("itemsize", - [](PyMemoryView *view) -> PyResult { - return PyInteger::create(view->itemsize()); - }) - .type); + .def("cast", &PyMemoryView::cast) + .def("tolist", &PyMemoryView::tolist) + .property_readonly("itemsize", + [](PyMemoryView *view) -> PyResult { + return PyInteger::create(view->itemsize()); + }) + .type); } }// namespace diff --git a/src/runtime/PyMemoryView.hpp b/src/runtime/PyMemoryView.hpp index dbdee3aa..edaf893b 100644 --- a/src/runtime/PyMemoryView.hpp +++ b/src/runtime/PyMemoryView.hpp @@ -39,9 +39,7 @@ class PyMemoryView : public PyBaseObject void visit_graph(Visitor &) override; std::string to_string() const override; - size_t itemsize() const { - return m_view.itemsize; - } + size_t itemsize() const { return m_view.itemsize; } private: static PyResult create_view(PyBuffer &main_view); diff --git a/src/runtime/PyMethodDescriptor.cpp b/src/runtime/PyMethodDescriptor.cpp index c988c2ed..e290740c 100644 --- a/src/runtime/PyMethodDescriptor.cpp +++ b/src/runtime/PyMethodDescriptor.cpp @@ -17,7 +17,9 @@ template<> PyMethodDescriptor *as(PyObject *obj) template<> const PyMethodDescriptor *as(const PyObject *obj) { - if (obj->type() == types::method_wrapper()) { return static_cast(obj); } + if (obj->type() == types::method_wrapper()) { + return static_cast(obj); + } return nullptr; } diff --git a/src/runtime/PyNamespace.cpp b/src/runtime/PyNamespace.cpp index 51af0500..c69fe09c 100644 --- a/src/runtime/PyNamespace.cpp +++ b/src/runtime/PyNamespace.cpp @@ -96,8 +96,8 @@ namespace { std::unique_ptr register_namespace() { return std::move(klass("types.SimpleNamespace") - .attribute_readonly("__dict__", &PyNamespace::m_dict) - .type); + .attribute_readonly("__dict__", &PyNamespace::m_dict) + .type); } }// namespace diff --git a/src/runtime/PyObject.cpp b/src/runtime/PyObject.cpp index 22a3c88b..a94eddc3 100644 --- a/src/runtime/PyObject.cpp +++ b/src/runtime/PyObject.cpp @@ -416,7 +416,7 @@ void PyObject::visit_graph(Visitor &visitor) { if (m_attributes) { visitor.visit(*m_attributes); } for (size_t i = 0, offset = type()->underlying_type().basicsize; i < type()->__slots__.size(); - ++i, offset += sizeof(PyObject *)) { + ++i, offset += sizeof(PyObject *)) { auto *slot = *bit_cast(bit_cast(this) + offset); if (slot) { visitor.visit(*slot); } } @@ -491,7 +491,7 @@ PyResult PyObject::richcompare(const PyObject *other, RichCompare op if (auto result = eq(other); result.is_ok() && (result.unwrap() != not_implemented())) { return result; } else if (auto result = other->eq(this); - result.is_ok() && (result.unwrap() != not_implemented())) { + result.is_ok() && (result.unwrap() != not_implemented())) { return result; } } break; @@ -499,7 +499,7 @@ PyResult PyObject::richcompare(const PyObject *other, RichCompare op if (auto result = ge(other); result.is_ok() && (result.unwrap() != not_implemented())) { return result; } else if (auto result = other->le(this); - result.is_ok() && (result.unwrap() != not_implemented())) { + result.is_ok() && (result.unwrap() != not_implemented())) { return result; } } break; @@ -507,7 +507,7 @@ PyResult PyObject::richcompare(const PyObject *other, RichCompare op if (auto result = gt(other); result.is_ok() && (result.unwrap() != not_implemented())) { return result; } else if (auto result = other->lt(this); - result.is_ok() && (result.unwrap() != not_implemented())) { + result.is_ok() && (result.unwrap() != not_implemented())) { return result; } } break; @@ -515,7 +515,7 @@ PyResult PyObject::richcompare(const PyObject *other, RichCompare op if (auto result = le(other); result.is_ok() && (result.unwrap() != not_implemented())) { return result; } else if (auto result = other->ge(this); - result.is_ok() && (result.unwrap() != not_implemented())) { + result.is_ok() && (result.unwrap() != not_implemented())) { return result; } } break; @@ -523,7 +523,7 @@ PyResult PyObject::richcompare(const PyObject *other, RichCompare op if (auto result = lt(other); result.is_ok() && (result.unwrap() != not_implemented())) { return result; } else if (auto result = other->gt(this); - result.is_ok() && (result.unwrap() != not_implemented())) { + result.is_ok() && (result.unwrap() != not_implemented())) { return result; } } break; @@ -531,7 +531,7 @@ PyResult PyObject::richcompare(const PyObject *other, RichCompare op if (auto result = ne(other); result.is_ok() && (result.unwrap() != not_implemented())) { return result; } else if (auto result = other->ne(this); - result.is_ok() && (result.unwrap() != not_implemented())) { + result.is_ok() && (result.unwrap() != not_implemented())) { return result; } } break; @@ -982,11 +982,11 @@ PyResult PyObject::true_() if (type_prototype().__bool__.has_value()) { return call_slot(*type_prototype().__bool__, "__bool__ should return bool", this); } else if (auto mapping = as_mapping(); - mapping.is_ok() && type_prototype().mapping_type_protocol->__len__.has_value()) { + mapping.is_ok() && type_prototype().mapping_type_protocol->__len__.has_value()) { return mapping.unwrap().len().and_then( [](size_t l) -> PyResult { return Ok(l > 0); }); } else if (auto sequence = as_sequence(); - sequence.is_ok() && type_prototype().sequence_type_protocol->__len__.has_value()) { + sequence.is_ok() && type_prototype().sequence_type_protocol->__len__.has_value()) { return sequence.unwrap().len().and_then( [](size_t l) -> PyResult { return Ok(l > 0); }); } else { @@ -1465,15 +1465,15 @@ namespace { std::unique_ptr register_type() { return std::move(klass("object") - .property( - "__class__", - [](PyObject *self) { return Ok(self->type()); }, - [](PyObject *self, PyObject *value) -> PyResult { - (void)self; - (void)value; - TODO(); - }) - .type); + .property( + "__class__", + [](PyObject *self) { return Ok(self->type()); }, + [](PyObject *self, PyObject *value) -> PyResult { + (void)self; + (void)value; + TODO(); + }) + .type); } }// namespace diff --git a/src/runtime/PyProperty.cpp b/src/runtime/PyProperty.cpp index d22ced96..b6c84ebf 100644 --- a/src/runtime/PyProperty.cpp +++ b/src/runtime/PyProperty.cpp @@ -198,13 +198,13 @@ namespace { std::unique_ptr register_property() { return std::move(klass("property") - .def("getter", &PyProperty::getter) - .def("deleter", &PyProperty::deleter) - .def("setter", &PyProperty::setter) - .attr("fget", &PyProperty::m_getter) - .attr("fset", &PyProperty::m_setter) - .attr("fdel", &PyProperty::m_deleter) - .type); + .def("getter", &PyProperty::getter) + .def("deleter", &PyProperty::deleter) + .def("setter", &PyProperty::setter) + .attr("fget", &PyProperty::m_getter) + .attr("fset", &PyProperty::m_setter) + .attr("fdel", &PyProperty::m_deleter) + .type); } }// namespace diff --git a/src/runtime/PySet.cpp b/src/runtime/PySet.cpp index b4e01312..617978ee 100644 --- a/src/runtime/PySet.cpp +++ b/src/runtime/PySet.cpp @@ -374,15 +374,15 @@ namespace { std::unique_ptr register_set() { return std::move(klass("set") - .def("add", &PySet::add) - .def("discard", &PySet::discard) - .def("remove", &PySet::remove) - .def("intersection", &PySet::intersection) - .def("update", &PySet::update) - .def("pop", &PySet::pop) - .def("issubset", &PySet::issubset) - .def("union", &PySet::union_) - .type); + .def("add", &PySet::add) + .def("discard", &PySet::discard) + .def("remove", &PySet::remove) + .def("intersection", &PySet::intersection) + .def("update", &PySet::update) + .def("pop", &PySet::pop) + .def("issubset", &PySet::issubset) + .def("union", &PySet::union_) + .type); } }// namespace diff --git a/src/runtime/PySet.hpp b/src/runtime/PySet.hpp index 31d3fc32..0f637b65 100644 --- a/src/runtime/PySet.hpp +++ b/src/runtime/PySet.hpp @@ -55,7 +55,8 @@ class PySet : public PyBaseObject PyType *static_type() const override; private: - PyResult union_helper(const PyObject *other, SetType &result, bool strict) const; + PyResult + union_helper(const PyObject *other, SetType &result, bool strict) const; PySet(); PySet(SetType elements); diff --git a/src/runtime/PySlice.cpp b/src/runtime/PySlice.cpp index d3e89d45..3b6404c8 100644 --- a/src/runtime/PySlice.cpp +++ b/src/runtime/PySlice.cpp @@ -307,10 +307,10 @@ namespace { std::unique_ptr register_slice() { return std::move(klass("slice") - .attr("start", &PySlice::m_start) - .attr("stop", &PySlice::m_stop) - .attr("step", &PySlice::m_step) - .type); + .attr("start", &PySlice::m_start) + .attr("stop", &PySlice::m_stop) + .attr("step", &PySlice::m_step) + .type); } }// namespace diff --git a/src/runtime/PySlotWrapper.hpp b/src/runtime/PySlotWrapper.hpp index 901bbd16..d4298c73 100644 --- a/src/runtime/PySlotWrapper.hpp +++ b/src/runtime/PySlotWrapper.hpp @@ -224,11 +224,9 @@ constexpr void Slot::initialize( } else if constexpr (std::is_integral_v) { return result.and_then([](auto value) { return PyInteger::create(value); }); } else { - []() - { + []() { static_assert(flag, "unsupported native return type"); - } - (); + }(); } }; auto get_parameter = [&args]() -> PyResult { @@ -251,11 +249,9 @@ constexpr void Slot::initialize( TODO(); } } else { - []() - { + []() { static_assert(flag, "unsupported native parameter type"); - } - (); + }(); } }; if constexpr (flags_ == Flags::Keywords) { @@ -284,8 +280,7 @@ constexpr void Slot::initialize( if (arg1.is_err()) { return Err(arg1.unwrap_err()); } return wrap_result(native_fn(self, arg0.unwrap(), arg1.unwrap())); } else { - []() { static_assert(flag, "unsupported arity"); } - (); + []() { static_assert(flag, "unsupported arity"); }(); } } }; diff --git a/src/runtime/PyString.cpp b/src/runtime/PyString.cpp index 402db1d7..d44de790 100644 --- a/src/runtime/PyString.cpp +++ b/src/runtime/PyString.cpp @@ -233,10 +233,14 @@ PyString::PyString(std::string s) {} PyResult PyString::__hash__() const -{ return Ok(static_cast(std::hash{}(m_value))); } +{ + return Ok(static_cast(std::hash{}(m_value))); +} PyResult PyString::__repr__() const -{ return PyString::create(fmt::format("'{}'", m_value)); } +{ + return PyString::create(fmt::format("'{}'", m_value)); +} PyResult PyString::__str__() const { return Ok(const_cast(this)); } @@ -1927,7 +1931,9 @@ PyStringIterator::PyStringIterator(const PyString &pystring) {} std::string PyStringIterator::to_string() const -{ return fmt::format("", static_cast(this)); } +{ + return fmt::format("", static_cast(this)); +} void PyStringIterator::visit_graph(Visitor &visitor) { @@ -1957,7 +1963,9 @@ namespace { std::once_flag str_iterator_flag; std::unique_ptr register_str_iterator() - { return std::move(klass("str_iterator").type); } + { + return std::move(klass("str_iterator").type); + } }// namespace std::function()> PyStringIterator::type_factory() diff --git a/src/runtime/PySuper.cpp b/src/runtime/PySuper.cpp index 8a344472..0f0ae75d 100644 --- a/src/runtime/PySuper.cpp +++ b/src/runtime/PySuper.cpp @@ -237,10 +237,10 @@ std::function()> PySuper::type_factory() static std::unique_ptr type = nullptr; std::call_once(super_flag, []() { type = std::move(klass("super") - .attribute_readonly("__thisclass__", &PySuper::m_type) - .attribute_readonly("__self__", &PySuper::m_object) - .attribute_readonly("__self_class__", &PySuper::m_object_type) - .type); + .attribute_readonly("__thisclass__", &PySuper::m_type) + .attribute_readonly("__self__", &PySuper::m_object) + .attribute_readonly("__self_class__", &PySuper::m_object_type) + .type); }); return std::move(type); }; diff --git a/src/runtime/PyTraceback.cpp b/src/runtime/PyTraceback.cpp index fbba5225..f3ba9d61 100644 --- a/src/runtime/PyTraceback.cpp +++ b/src/runtime/PyTraceback.cpp @@ -24,8 +24,8 @@ void PyTraceback::visit_graph(Visitor &visitor) PyResult PyTraceback::__repr__() const { return PyString::create(to_string()); } PyTraceback::PyTraceback(PyFrame *tb_frame, size_t tb_lasti, size_t tb_lineno, PyTraceback *tb_next) - : PyBaseObject(types::BuiltinTypes::the().traceback()), m_tb_frame(tb_frame), m_tb_lasti(tb_lasti), - m_tb_lineno(tb_lineno), m_tb_next(tb_next) + : PyBaseObject(types::BuiltinTypes::the().traceback()), m_tb_frame(tb_frame), + m_tb_lasti(tb_lasti), m_tb_lineno(tb_lineno), m_tb_next(tb_next) {} PyResult @@ -46,9 +46,9 @@ namespace { std::unique_ptr register_traceback() { return std::move(klass("traceback") - .attr("tb_frame", &PyTraceback::m_tb_frame) - .attr("tb_next", &PyTraceback::m_tb_next) - .type); + .attr("tb_frame", &PyTraceback::m_tb_frame) + .attr("tb_next", &PyTraceback::m_tb_next) + .type); } }// namespace diff --git a/src/runtime/PyType.cpp b/src/runtime/PyType.cpp index e5b4132e..ceb960ba 100644 --- a/src/runtime/PyType.cpp +++ b/src/runtime/PyType.cpp @@ -262,8 +262,7 @@ namespace { std::unique_ptr register_type_() { - return std::move( - klass("type") + return std::move(klass("type") .def("mro", &PyType::mro) .attr("__mro__", &PyType::__mro__) .classmethod("__prepare__", @@ -1371,7 +1370,7 @@ namespace { .unwrap(); use_generic = true; } else if (auto s = slot.get_member(slot_wrapper->base_type()->underlying_type()); - !s.has_value()) { + !s.has_value()) { // if we don't have a specific slot we get the wrapper from descriptor we found // in the MRO generic = slot_wrapper->base().get().get_member( @@ -1382,8 +1381,8 @@ namespace { use_generic = false; } } else if (auto fn = as(descr); - fn && (fn->method_pointer().has_value() && *fn->method_pointer() == &new_wrapper) - && slot.name == "__new__") { + fn && (fn->method_pointer().has_value() && *fn->method_pointer() == &new_wrapper) + && slot.name == "__new__") { auto &new_slot = type->underlying_type().__new__; ASSERT(new_slot.has_value()); if (std::holds_alternative(*new_slot)) { diff --git a/src/runtime/UnboundLocalError.cpp b/src/runtime/UnboundLocalError.cpp index da56ac54..1a57095f 100644 --- a/src/runtime/UnboundLocalError.cpp +++ b/src/runtime/UnboundLocalError.cpp @@ -7,7 +7,9 @@ namespace py { UnboundLocalError::UnboundLocalError(PyType *type) : Exception(type) {} -UnboundLocalError::UnboundLocalError(PyTuple *args) : Exception(types::BuiltinTypes::the().unbound_local_error(), args) {} +UnboundLocalError::UnboundLocalError(PyTuple *args) + : Exception(types::BuiltinTypes::the().unbound_local_error(), args) +{} PyResult UnboundLocalError::__new__(const PyType *type, PyTuple *args, PyDict *kwargs) { @@ -28,7 +30,8 @@ namespace { std::unique_ptr register_unbound_local_error() { - return std::move(klass("UnboundLocalError", Exception::class_type()).type); + return std::move( + klass("UnboundLocalError", Exception::class_type()).type); } }// namespace diff --git a/src/runtime/modules/collections/DefaultDict.hpp b/src/runtime/modules/collections/DefaultDict.hpp index 212f4135..eee729e2 100644 --- a/src/runtime/modules/collections/DefaultDict.hpp +++ b/src/runtime/modules/collections/DefaultDict.hpp @@ -16,13 +16,13 @@ namespace collections { DefaultDict(PyObject *default_factory); public: - PyResult __init__(PyTuple *args, PyDict *kwargs); + PyResult __init__(PyTuple *args, PyDict *kwargs); static PyType *register_type(PyModule *module); void visit_graph(Visitor &visitor) override; - PyResult __missing__(PyObject *key); + PyResult __missing__(PyObject *key); }; -}// namespace collection +}// namespace collections }// namespace py diff --git a/src/runtime/modules/itertools/Permutations.hpp b/src/runtime/modules/itertools/Permutations.hpp index 3fafe55c..bb798f3d 100644 --- a/src/runtime/modules/itertools/Permutations.hpp +++ b/src/runtime/modules/itertools/Permutations.hpp @@ -11,7 +11,7 @@ namespace itertools { PyList *m_pool{ nullptr }; size_t m_length; size_t m_iterator_length; - size_t m_inner_iteration; + size_t m_inner_iteration; std::vector m_indices; std::vector m_cycles; bool m_done; diff --git a/src/runtime/modules/itertools/Product.hpp b/src/runtime/modules/itertools/Product.hpp index 77da4d9e..31597555 100644 --- a/src/runtime/modules/itertools/Product.hpp +++ b/src/runtime/modules/itertools/Product.hpp @@ -11,8 +11,8 @@ namespace itertools { PyList *m_pools{ nullptr }; size_t m_repeat; - std::vector> m_result; - size_t m_iteration_count{0}; + std::vector> m_result; + size_t m_iteration_count{ 0 }; Product(PyType *); Product(PyList *pools, size_t repeat); diff --git a/src/runtime/modules/thread/RLock.hpp b/src/runtime/modules/thread/RLock.hpp index 705e5ceb..3b214492 100644 --- a/src/runtime/modules/thread/RLock.hpp +++ b/src/runtime/modules/thread/RLock.hpp @@ -119,11 +119,11 @@ class RLock : public PyBaseObject { if (!s_rlock) { s_rlock = klass(module, "RLock") - .def("release", &RLock::release) - .def("acquire", &RLock::acquire) - .def("__enter__", &RLock::__enter__) - .def("__exit__", &RLock::__exit__) - .finalize(); + .def("release", &RLock::release) + .def("acquire", &RLock::acquire) + .def("__enter__", &RLock::__enter__) + .def("__exit__", &RLock::__exit__) + .finalize(); } return s_rlock; } diff --git a/src/runtime/modules/time/module.cpp b/src/runtime/modules/time/module.cpp index d869baf4..96514f8c 100644 --- a/src/runtime/modules/time/module.cpp +++ b/src/runtime/modules/time/module.cpp @@ -50,7 +50,7 @@ PyModule *time_module() PyNativeFunction::create("monotonic_ns", [](PyTuple *, PyDict *) { auto ns = std::chrono::duration_cast( std::chrono::steady_clock::now().time_since_epoch()) - .count(); + .count(); return PyInteger::create(ns); }).unwrap()); diff --git a/src/runtime/types/api.hpp b/src/runtime/types/api.hpp index 361dafb4..a93f6ef3 100644 --- a/src/runtime/types/api.hpp +++ b/src/runtime/types/api.hpp @@ -108,8 +108,7 @@ template struct klass return PyInteger::create(static_cast(value)); } } else { - []() { static_assert(flag, "unsupported member type"); } - (); + []() { static_assert(flag, "unsupported member type"); }(); } TODO(); }, @@ -130,8 +129,7 @@ template struct klass value->type()->name())); } } else { - []() { static_assert(flag, "unsupported member type"); } - (); + []() { static_assert(flag, "unsupported member type"); }(); } return Ok(std::monostate{}); }, @@ -166,8 +164,7 @@ template struct klass } else if constexpr (std::is_same_v) { return PyString::create(static_cast(self)->*member); } else { - []() { static_assert(flag, "unsupported member type"); } - (); + []() { static_assert(flag, "unsupported member type"); }(); } TODO(); }, @@ -186,8 +183,7 @@ template struct klass PyObject *self, PyTuple *args, PyDict *kwargs) -> PyResult { const size_t arg_count = (args ? args->size() : 0) + (kwargs ? kwargs->size() : 0); if (arg_count) { - return Err( - type_error("{}() takes no arguments ({} given)", name, arg_count)); + return Err(type_error("{}() takes no arguments ({} given)", name, arg_count)); } if (kwargs && kwargs->size() > 0) { return Err(type_error("{}() takes no keyword arguments)", name)); diff --git a/src/runtime/utilities.hpp b/src/runtime/utilities.hpp index 3f3392e6..4eb4a002 100644 --- a/src/runtime/utilities.hpp +++ b/src/runtime/utilities.hpp @@ -11,9 +11,7 @@ namespace py { namespace detail { template concept has_output_iterator_error = requires(const T iterator) { - { - iterator.last_error() - } -> std::convertible_to; + { iterator.last_error() } -> std::convertible_to; }; }// namespace detail diff --git a/src/testing/main.cpp b/src/testing/main.cpp index 8c34f117..84215585 100644 --- a/src/testing/main.cpp +++ b/src/testing/main.cpp @@ -1,5 +1,5 @@ -#include "vm/VM.hpp" #include "interpreter/Interpreter.hpp" +#include "vm/VM.hpp" #include "gtest/gtest.h" diff --git a/src/utilities.hpp b/src/utilities.hpp index b022f42d..70c1b395 100644 --- a/src/utilities.hpp +++ b/src/utilities.hpp @@ -79,5 +79,7 @@ typename std::enable_if_t constexpr To bit_cast(const From &from) noexcept -{ return std::bit_cast(from); } +{ + return std::bit_cast(from); +} #endif diff --git a/src/vm/VM.hpp b/src/vm/VM.hpp index 86fea5b5..ccd2a751 100644 --- a/src/vm/VM.hpp +++ b/src/vm/VM.hpp @@ -171,9 +171,8 @@ class VirtualMachine void dump() const; - [[nodiscard]] std::unique_ptr setup_call_stack(size_t register_count, - size_t locals_count, - size_t stack_size); + [[nodiscard]] std::unique_ptr + setup_call_stack(size_t register_count, size_t locals_count, size_t stack_size); void ret(); void set_cleanup(State::CleanupLogic cleanup_type,