diff --git a/.clang-tidy b/.clang-tidy index a66d8d18b..3c357f888 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -46,3 +46,39 @@ CheckOptions: value: true - key: 'cppcoreguidelines-special-member-functions.AllowSoleDefaultDtor' value: true + - key: 'readability-identifier-naming.ClassCase' + value: 'lower_case' + - key: 'readability-identifier-naming.ConstexprVariableCase' + value: 'lower_case' + - key: 'readability-identifier-naming.GlobalConstantCase' + value: 'UPPER_CASE' + - key: 'readability-identifier-naming.GlobalVariableCase' + value: 'lower_case' + - key: 'readability-identifier-naming.GlobalVariableIgnoredRegexp' + value: 'and_|not_|equals_|X' + - key: 'readability-identifier-naming.ParameterCase' + value: 'lower_case' + - key: 'readability-identifier-naming.MemberCase' + value: 'lower_case' + - key: 'readability-identifier-naming.PrivateMemberCase' + value: 'lower_case' + - key: 'readability-identifier-naming.PrivateMemberSuffix' + value: '_' + - key: 'readability-identifier-naming.TemplateParameterCase' + value: 'CamelCase' + - key: 'readability-identifier-naming.TypeTemplateParameterIgnoredRegexp' + value: 'expr-type' # https://github.com/llvm/llvm-project/issues/46097 + - key: 'readability-identifier-naming.MethodCase' + value: 'lower_case' + - key: 'readability-identifier-naming.FunctionCase' + value: 'lower_case' + - key: 'readability-identifier-naming.FunctionIgnoredRegexp' + value: 'hook_.*' + - key: 'readability-identifier-naming.EnumCase' + value: 'lower_case' + - key: 'readability-identifier-naming.ScopedEnumConstantCase' + value: 'CamelCase' + - key: 'readability-identifier-naming.EnumConstantCase' + value: 'CamelCase' + - key: 'readability-identifier-naming.LocalVariableCase' + value: 'lower_case' diff --git a/bindings/c/include/kllvm-c/kllvm-c.h b/bindings/c/include/kllvm-c/kllvm-c.h index 47b69ffce..0b2e8e105 100644 --- a/bindings/c/include/kllvm-c/kllvm-c.h +++ b/bindings/c/include/kllvm-c/kllvm-c.h @@ -77,7 +77,7 @@ typedef struct kore_sort kore_sort; typedef struct kore_symbol kore_symbol; typedef struct block block; -/* KOREPattern */ +/* kore_pattern */ char *kore_pattern_dump(kore_pattern const *); @@ -131,7 +131,7 @@ void kore_simplify_binary( block *take_steps(int64_t depth, block *term); -/* KORESort */ +/* kore_sort */ char *kore_sort_dump(kore_sort const *); @@ -145,7 +145,7 @@ bool kore_sort_is_k(kore_sort const *); kore_sort *kore_composite_sort_new(char const *); void kore_composite_sort_add_argument(kore_sort const *, kore_sort const *); -/* KORESymbol */ +/* kore_symbol */ kore_symbol *kore_symbol_new(char const *); diff --git a/bindings/c/lib.cpp b/bindings/c/lib.cpp index c8d59a4d5..546124273 100644 --- a/bindings/c/lib.cpp +++ b/bindings/c/lib.cpp @@ -67,8 +67,8 @@ auto managed(kore_symbol *ptr) { */ extern "C" { -void initStaticObjects(); -void freeAllKoreMem(); +void init_static_objects(); +void free_all_kore_mem(); bool hook_BYTES_mutableBytesEnabled(); } @@ -88,33 +88,33 @@ char kore_definition_macros __attribute__((weak)) = -1; /* Completed types */ struct kore_error { - bool success_ = true; - std::optional message_ = std::nullopt; + bool success = true; + std::optional message = std::nullopt; [[nodiscard]] char const *c_str() const { - if (!success_ && message_.has_value()) { - return message_->c_str(); + if (!success && message.has_value()) { + return message->c_str(); } return nullptr; } void set_error(std::string const &msg) { - success_ = false; - message_ = msg; + success = false; + message = msg; } }; struct kore_pattern { - std::shared_ptr ptr_; + std::shared_ptr ptr; }; struct kore_sort { - std::shared_ptr ptr_; + std::shared_ptr ptr; }; struct kore_symbol { - std::shared_ptr ptr_; + std::shared_ptr ptr; }; /* Error handling */ @@ -124,7 +124,7 @@ kore_error *kore_error_new(void) { } bool kore_error_is_success(kore_error const *err) { - return err->success_; + return err->success; } char const *kore_error_message(kore_error const *err) { @@ -135,10 +135,10 @@ void kore_error_free(kore_error *err) { delete err; } -/* KOREPattern */ +/* kore_pattern */ char *kore_pattern_dump(kore_pattern const *pat) { - return get_c_string(ast_to_string(*pat->ptr_)); + return get_c_string(ast_to_string(*pat->ptr)); } char *kore_pattern_pretty_print(kore_pattern const *pat) { @@ -168,11 +168,11 @@ char *kore_pattern_pretty_print(kore_pattern const *pat) { macros_out << macros; auto pattern_out = std::ofstream(temp_path("pattern.kore"), std::ios::out); - pat->ptr_->print(pattern_out); + pat->ptr->print(pattern_out); } auto ss = std::stringstream{}; - kllvm::printKORE( + kllvm::print_kore( ss, temp_dir_name, temp_path("pattern.kore"), false, false, true); fs::remove_all(temp_dir_name); @@ -183,7 +183,7 @@ char *kore_pattern_pretty_print(kore_pattern const *pat) { void kore_pattern_serialize( kore_pattern const *pat, char **data_out, size_t *size_out) { auto out = kllvm::serializer(); - pat->ptr_->serialize_to(out); + pat->ptr->serialize_to(out); auto const &binary_data = out.data(); auto binary_size = binary_data.size(); @@ -200,12 +200,12 @@ void kore_pattern_free(kore_pattern const *pat) { kore_pattern *kore_pattern_parse(char const *kore_text) { return new kore_pattern{ - kllvm::parser::KOREParser::from_string(kore_text)->pattern()}; + kllvm::parser::kore_parser::from_string(kore_text)->pattern()}; } kore_pattern *kore_pattern_parse_file(char const *filename) { return new kore_pattern{ - kllvm::parser::KOREParser(std::string(filename)).pattern()}; + kllvm::parser::kore_parser(std::string(filename)).pattern()}; } kore_pattern *kore_pattern_new_token(char const *value, kore_sort const *sort) { @@ -222,7 +222,7 @@ kore_pattern *kore_pattern_new_token_with_len( kore_pattern *kore_pattern_new_injection( kore_pattern const *term, kore_sort const *from, kore_sort const *to) { return new kore_pattern{ - kllvm::bindings::make_injection(term->ptr_, from->ptr_, to->ptr_)}; + kllvm::bindings::make_injection(term->ptr, from->ptr, to->ptr)}; } kore_pattern *kore_pattern_make_interpreter_input( @@ -258,15 +258,15 @@ kore_pattern *kore_pattern_make_interpreter_input( } kore_pattern *kore_pattern_desugar_associative(kore_pattern const *pat) { - return new kore_pattern{pat->ptr_->desugarAssociative()}; + return new kore_pattern{pat->ptr->desugar_associative()}; } block *kore_pattern_construct(kore_pattern const *pat) { - return kllvm::bindings::construct_term(pat->ptr_); + return kllvm::bindings::construct_term(pat->ptr); } char *kore_block_dump(block *term) { - auto *hooked_str = printConfigurationToString(term)->data; + auto *hooked_str = print_configuration_to_string(term)->data; auto len = std::strlen(hooked_str); auto *new_str = static_cast(malloc(len + 1)); @@ -286,7 +286,7 @@ bool kore_block_get_bool(block *term) { bool kore_simplify_bool(kore_error *err, kore_pattern const *pattern) { try { - return kllvm::bindings::simplify_to_bool(pattern->ptr_); + return kllvm::bindings::simplify_to_bool(pattern->ptr); } catch (std::exception &e) { if (err == nullptr) { throw; @@ -301,8 +301,8 @@ void kore_simplify( kore_error *err, kore_pattern const *pattern, kore_sort const *sort, char **data_out, size_t *size_out) { try { - auto *block = kllvm::bindings::simplify_to_term(pattern->ptr_, sort->ptr_); - serializeConfiguration( + auto *block = kllvm::bindings::simplify_to_term(pattern->ptr, sort->ptr); + serialize_configuration( block, "SortKItem{}", data_out, size_out, true, true); } catch (std::exception &e) { if (err == nullptr) { @@ -320,8 +320,8 @@ void kore_simplify_binary( auto sort_str = std::unique_ptr( kore_sort_dump(sort), std::free); - auto *block = deserializeConfiguration(data_in, size_in); - serializeConfiguration( + auto *block = deserialize_configuration(data_in, size_in); + serialize_configuration( block, sort_str.get(), data_out, size_out, true, true); } catch (std::exception &e) { if (err == nullptr) { @@ -332,28 +332,29 @@ void kore_simplify_binary( } } -/* KORECompositePattern */ +/* kore_composite_pattern */ kore_pattern *kore_composite_pattern_new(char const *name) { return new kore_pattern{ - kllvm::KORECompositePattern::Create(std::string(name))}; + kllvm::kore_composite_pattern::create(std::string(name))}; } kore_pattern *kore_composite_pattern_from_symbol(kore_symbol *sym) { - return new kore_pattern{kllvm::KORECompositePattern::Create(sym->ptr_.get())}; + return new kore_pattern{ + kllvm::kore_composite_pattern::create(sym->ptr.get())}; } void kore_composite_pattern_add_argument( kore_pattern *pat, kore_pattern const *arg) { if (auto const &cast - = std::dynamic_pointer_cast(pat->ptr_)) { - cast->addArgument(arg->ptr_); + = std::dynamic_pointer_cast(pat->ptr)) { + cast->add_argument(arg->ptr); } else { abort(); } } -/* KOREStringPattern */ +/* kore_string_pattern */ kore_pattern *kore_string_pattern_new(char const *contents) { return kore_string_pattern_new_internal(std::string(contents)); @@ -364,10 +365,10 @@ kore_string_pattern_new_with_len(char const *contents, size_t len) { return kore_string_pattern_new_internal(std::string(contents, len)); } -/* KORESort */ +/* kore_sort */ char *kore_sort_dump(kore_sort const *sort) { - return get_c_string(ast_to_string(*sort->ptr_)); + return get_c_string(ast_to_string(*sort->ptr)); } void kore_sort_free(kore_sort const *sort) { @@ -375,37 +376,37 @@ void kore_sort_free(kore_sort const *sort) { } bool kore_sort_is_concrete(kore_sort const *sort) { - return sort->ptr_->isConcrete(); + return sort->ptr->is_concrete(); } bool kore_sort_is_kitem(kore_sort const *sort) { - return kllvm::bindings::is_sort_kitem(sort->ptr_); + return kllvm::bindings::is_sort_kitem(sort->ptr); } bool kore_sort_is_k(kore_sort const *sort) { - return kllvm::bindings::is_sort_k(sort->ptr_); + return kllvm::bindings::is_sort_k(sort->ptr); } -/* KORECompositeSort */ +/* kore_composite_sort */ kore_sort *kore_composite_sort_new(char const *name) { - return new kore_sort{kllvm::KORECompositeSort::Create(std::string(name))}; + return new kore_sort{kllvm::kore_composite_sort::create(std::string(name))}; } void kore_composite_sort_add_argument( kore_sort const *sort, kore_sort const *arg) { if (auto const &cast - = std::dynamic_pointer_cast(sort->ptr_)) { - cast->addArgument(arg->ptr_); + = std::dynamic_pointer_cast(sort->ptr)) { + cast->add_argument(arg->ptr); } else { abort(); } } -/* KORESymbol */ +/* kore_symbol */ kore_symbol *kore_symbol_new(char const *name) { - return new kore_symbol{kllvm::KORESymbol::Create(std::string(name))}; + return new kore_symbol{kllvm::kore_symbol::create(std::string(name))}; } void kore_symbol_free(kore_symbol const *sym) { @@ -413,21 +414,21 @@ void kore_symbol_free(kore_symbol const *sym) { } char *kore_symbol_dump(kore_symbol const *sym) { - return get_c_string(ast_to_string(*sym->ptr_)); + return get_c_string(ast_to_string(*sym->ptr)); } void kore_symbol_add_formal_argument(kore_symbol *sym, kore_sort const *sort) { - sym->ptr_->addFormalArgument(sort->ptr_); + sym->ptr->add_formal_argument(sort->ptr); } /* Memory management */ void kllvm_init(void) { - initStaticObjects(); + init_static_objects(); } void kllvm_free_all_memory(void) { - freeAllKoreMem(); + free_all_kore_mem(); } bool kllvm_mutable_bytes_enabled(void) { @@ -448,7 +449,7 @@ char *get_c_string(std::string const &str) { } kore_pattern *kore_string_pattern_new_internal(std::string const &str) { - return new kore_pattern{kllvm::KOREStringPattern::Create(str)}; + return new kore_pattern{kllvm::kore_string_pattern::create(str)}; } kore_pattern *kore_pattern_new_token_internal( diff --git a/bindings/core/src/core.cpp b/bindings/core/src/core.cpp index 32e360077..6d2c64ee5 100644 --- a/bindings/core/src/core.cpp +++ b/bindings/core/src/core.cpp @@ -7,51 +7,51 @@ using namespace kllvm; * through any header files, so we pull them in manually here. */ extern "C" { -void *constructInitialConfiguration(KOREPattern const *); +void *construct_initial_configuration(kore_pattern const *); } namespace kllvm::bindings { std::string return_sort_for_label(std::string const &label) { - auto tag = getTagForSymbolName(label.c_str()); - return getReturnSortForTag(tag); + auto tag = get_tag_for_symbol_name(label.c_str()); + return get_return_sort_for_tag(tag); } -std::shared_ptr make_rawTerm( - std::shared_ptr const &term, - std::shared_ptr const &from, - std::shared_ptr const &to) { +std::shared_ptr make_raw_term( + std::shared_ptr const &term, + std::shared_ptr const &from, + std::shared_ptr const &to) { auto inj = make_injection(term, from, to); - auto rawTerm_sym = KORESymbol::Create("rawTerm"); + auto raw_term_sym = kore_symbol::create("rawTerm"); - auto rawTerm = KORECompositePattern::Create(std::move(rawTerm_sym)); - rawTerm->addArgument(inj); + auto raw_term = kore_composite_pattern::create(std::move(raw_term_sym)); + raw_term->add_argument(inj); - return rawTerm; + return raw_term; } -std::shared_ptr make_injection( - std::shared_ptr const &term, - std::shared_ptr const &from, - std::shared_ptr const &to) { - auto inj_sym = KORESymbol::Create("inj"); +std::shared_ptr make_injection( + std::shared_ptr const &term, + std::shared_ptr const &from, + std::shared_ptr const &to) { + auto inj_sym = kore_symbol::create("inj"); - inj_sym->addFormalArgument(from); - inj_sym->addFormalArgument(to); + inj_sym->add_formal_argument(from); + inj_sym->add_formal_argument(to); - auto inj = KORECompositePattern::Create(std::move(inj_sym)); - inj->addArgument(term); + auto inj = kore_composite_pattern::create(std::move(inj_sym)); + inj->add_argument(term); return inj; } -block *construct_term(std::shared_ptr const &pattern) { - return static_cast(constructInitialConfiguration(pattern.get())); +block *construct_term(std::shared_ptr const &pattern) { + return static_cast(construct_initial_configuration(pattern.get())); } -std::shared_ptr term_to_pattern(block *term) { - return termToKorePattern(term); +std::shared_ptr term_to_pattern(block *term) { + return term_to_kore_pattern(term); } bool get_bool(block *term) { @@ -59,58 +59,58 @@ bool get_bool(block *term) { return *(bool *)term->children; } -bool simplify_to_bool(std::shared_ptr const &pattern) { - auto bool_sort = KORECompositeSort::Create("SortBool"); - auto kitem_sort = KORECompositeSort::Create("SortKItem"); +bool simplify_to_bool(std::shared_ptr const &pattern) { + auto bool_sort = kore_composite_sort::create("SortBool"); + auto kitem_sort = kore_composite_sort::create("SortKItem"); auto inj = make_injection(pattern, bool_sort, kitem_sort); return get_bool(construct_term(inj)); } block *simplify_to_term( - std::shared_ptr const &pattern, - std::shared_ptr const &sort) { - auto kitem_sort = KORECompositeSort::Create("SortKItem"); + std::shared_ptr const &pattern, + std::shared_ptr const &sort) { + auto kitem_sort = kore_composite_sort::create("SortKItem"); if (is_sort_kitem(sort) || is_sort_k(sort)) { return construct_term(pattern); } - auto rawTerm = make_rawTerm(pattern, sort, kitem_sort); - return construct_term(rawTerm); + auto raw_term = make_raw_term(pattern, sort, kitem_sort); + return construct_term(raw_term); } -std::shared_ptr simplify( - std::shared_ptr const &pattern, - std::shared_ptr const &sort) { +std::shared_ptr simplify( + std::shared_ptr const &pattern, + std::shared_ptr const &sort) { return term_to_pattern(simplify_to_term(pattern, sort)); } -std::shared_ptr -evaluate_function(std::shared_ptr const &term) { +std::shared_ptr +evaluate_function(std::shared_ptr const &term) { auto term_args = std::vector{}; - for (auto const &arg : term->getArguments()) { + for (auto const &arg : term->get_arguments()) { term_args.push_back(static_cast(construct_term(arg))); } - auto label = ast_to_string(*term->getConstructor()); - auto tag = getTagForSymbolName(label.c_str()); - auto const *return_sort = getReturnSortForTag(tag); - auto *result = evaluateFunctionSymbol(tag, term_args.data()); + auto label = ast_to_string(*term->get_constructor()); + auto tag = get_tag_for_symbol_name(label.c_str()); + auto const *return_sort = get_return_sort_for_tag(tag); + auto *result = evaluate_function_symbol(tag, term_args.data()); - return sortedTermToKorePattern(static_cast(result), return_sort); + return sorted_term_to_kore_pattern(static_cast(result), return_sort); } -bool is_sort_kitem(std::shared_ptr const &sort) { - if (auto composite = std::dynamic_pointer_cast(sort)) { - return composite->getName() == "SortKItem"; +bool is_sort_kitem(std::shared_ptr const &sort) { + if (auto composite = std::dynamic_pointer_cast(sort)) { + return composite->get_name() == "SortKItem"; } return false; } -bool is_sort_k(std::shared_ptr const &sort) { - if (auto composite = std::dynamic_pointer_cast(sort)) { - return composite->getName() == "SortK"; +bool is_sort_k(std::shared_ptr const &sort) { + if (auto composite = std::dynamic_pointer_cast(sort)) { + return composite->get_name() == "SortK"; } return false; diff --git a/bindings/python/ast.cpp b/bindings/python/ast.cpp index 8257e33cf..7960faedb 100644 --- a/bindings/python/ast.cpp +++ b/bindings/python/ast.cpp @@ -70,7 +70,7 @@ auto print_repr_adapter(Args &&...args) { * exception will be thrown. The file pointer will be left at the end of the * pattern's bytes after calling this function. */ -std::shared_ptr read_pattern_from_file(py::object &file_like) { +std::shared_ptr read_pattern_from_file(py::object &file_like) { if (!py::hasattr(file_like, "read")) { throw py::type_error("Argument to read_from is not a file-like object"); } @@ -117,128 +117,132 @@ void bind_ast(py::module_ &m) { /* Declarations */ auto decl_base - = py::class_>( + = py::class_>( ast, "Declaration") - .def("__repr__", print_repr_adapter()) + .def("__repr__", print_repr_adapter()) .def( "add_object_sort_variable", - &KOREDeclaration::addObjectSortVariable) + &kore_declaration::add_object_sort_variable) .def_property_readonly( "object_sort_variables", - &KOREDeclaration::getObjectSortVariables) + &kore_declaration::get_object_sort_variables) .def( "add_attribute", - [](KOREDeclaration &decl, - std::shared_ptr const &arg) { + [](kore_declaration &decl, + std::shared_ptr const &arg) { decl.attributes().add(arg); }) - .def_property_readonly("attributes", [](KOREDeclaration &decl) { + .def_property_readonly("attributes", [](kore_declaration &decl) { return decl.attributes().underlying(); }); py::class_< - KORECompositeSortDeclaration, - std::shared_ptr>( + kore_composite_sort_declaration, + std::shared_ptr>( ast, "CompositeSortDeclaration", decl_base) .def( - py::init(&KORECompositeSortDeclaration::Create), py::arg("name"), + py::init(&kore_composite_sort_declaration::create), py::arg("name"), py::arg("is_hooked") = false) .def_property_readonly( - "is_hooked", &KORECompositeSortDeclaration::isHooked) - .def_property_readonly("name", &KORECompositeSortDeclaration::getName); + "is_hooked", &kore_composite_sort_declaration::is_hooked) + .def_property_readonly( + "name", &kore_composite_sort_declaration::get_name); auto symbol_alias_decl_base = py::class_< - KORESymbolAliasDeclaration, - std::shared_ptr>( + kore_symbol_alias_declaration, + std::shared_ptr>( ast, "SymbolAliasDeclaration", decl_base) .def_property_readonly( - "symbol", &KORESymbolAliasDeclaration::getSymbol); + "symbol", &kore_symbol_alias_declaration::get_symbol); - py::class_>( + py::class_>( ast, "SymbolDeclaration", symbol_alias_decl_base) .def( - py::init(&KORESymbolDeclaration::Create), py::arg("name"), + py::init(&kore_symbol_declaration::create), py::arg("name"), py::arg("is_hooked") = false) - .def_property_readonly("is_hooked", &KORESymbolDeclaration::isHooked); + .def_property_readonly("is_hooked", &kore_symbol_declaration::is_hooked); - py::class_>( + py::class_>( ast, "AliasDeclaration", symbol_alias_decl_base) - .def(py::init(&KOREAliasDeclaration::Create)) - .def("add_variables", &KOREAliasDeclaration::addVariables) + .def(py::init(&kore_alias_declaration::create)) + .def("add_variables", &kore_alias_declaration::add_variables) .def_property_readonly( - "variables", &KOREAliasDeclaration::getBoundVariables) - .def("add_pattern", &KOREAliasDeclaration::addPattern) - .def_property_readonly("pattern", &KOREAliasDeclaration::getPattern); + "variables", &kore_alias_declaration::get_bound_variables) + .def("add_pattern", &kore_alias_declaration::add_pattern) + .def_property_readonly("pattern", &kore_alias_declaration::get_pattern); - py::class_>( + py::class_>( ast, "AxiomDeclaration", decl_base) - .def(py::init(&KOREAxiomDeclaration::Create), py::arg("is_claim") = false) - .def_property_readonly("is_claim", &KOREAxiomDeclaration::isClaim) - .def("add_pattern", &KOREAxiomDeclaration::addPattern) - .def_property_readonly("pattern", &KOREAxiomDeclaration::getPattern); + .def( + py::init(&kore_axiom_declaration::create), + py::arg("is_claim") = false) + .def_property_readonly("is_claim", &kore_axiom_declaration::is_claim) + .def("add_pattern", &kore_axiom_declaration::add_pattern) + .def_property_readonly("pattern", &kore_axiom_declaration::get_pattern); py::class_< - KOREModuleImportDeclaration, - std::shared_ptr>( + kore_module_import_declaration, + std::shared_ptr>( ast, "ModuleImportDeclaration", decl_base) - .def(py::init(&KOREModuleImportDeclaration::Create)) + .def(py::init(&kore_module_import_declaration::create)) .def_property_readonly( - "module_name", &KOREModuleImportDeclaration::getModuleName); - - py::class_>(ast, "Module") - .def(py::init(&KOREModule::Create)) - .def("__repr__", print_repr_adapter()) - .def_property_readonly("name", &KOREModule::getName) - .def("add_declaration", &KOREModule::addDeclaration) - .def_property_readonly("declarations", &KOREModule::getDeclarations) + "module_name", &kore_module_import_declaration::get_module_name); + + py::class_>(ast, "Module") + .def(py::init(&kore_module::create)) + .def("__repr__", print_repr_adapter()) + .def_property_readonly("name", &kore_module::get_name) + .def("add_declaration", &kore_module::add_declaration) + .def_property_readonly("declarations", &kore_module::get_declarations) .def( "add_attribute", - [](KOREModule &decl, - std::shared_ptr const &arg) { + [](kore_module &decl, + std::shared_ptr const &arg) { decl.attributes().add(arg); }) - .def_property_readonly("attributes", [](KOREModule &decl) { + .def_property_readonly("attributes", [](kore_module &decl) { return decl.attributes().underlying(); }); - py::class_>(ast, "Definition") - .def(py::init(&KOREDefinition::Create)) - .def("__repr__", print_repr_adapter()) - .def("add_module", &KOREDefinition::addModule) - .def_property_readonly("modules", &KOREDefinition::getModules) + py::class_>( + ast, "Definition") + .def(py::init(&kore_definition::create)) + .def("__repr__", print_repr_adapter()) + .def("add_module", &kore_definition::add_module) + .def_property_readonly("modules", &kore_definition::get_modules) .def( "add_attribute", - [](KOREDefinition &decl, - std::shared_ptr const &arg) { + [](kore_definition &decl, + std::shared_ptr const &arg) { decl.attributes().add(arg); }) - .def_property_readonly("attributes", [](KOREDefinition &decl) { + .def_property_readonly("attributes", [](kore_definition &decl) { return decl.attributes().underlying(); }); /* Data Types */ - py::enum_(ast, "SortCategory") - .value("Uncomputed", SortCategory::Uncomputed) - .value("Map", SortCategory::Map) - .value("RangeMap", SortCategory::RangeMap) - .value("List", SortCategory::List) - .value("Set", SortCategory::Set) - .value("Int", SortCategory::Int) - .value("Float", SortCategory::Float) - .value("StringBuffer", SortCategory::StringBuffer) - .value("Bool", SortCategory::Bool) - .value("Symbol", SortCategory::Symbol) - .value("Variable", SortCategory::Variable) - .value("MInt", SortCategory::MInt); - - py::class_(ast, "ValueType") - .def(py::init([](SortCategory cat) { - return ValueType{cat, 0}; + py::enum_(ast, "SortCategory") + .value("Uncomputed", sort_category::Uncomputed) + .value("Map", sort_category::Map) + .value("RangeMap", sort_category::RangeMap) + .value("List", sort_category::List) + .value("Set", sort_category::Set) + .value("Int", sort_category::Int) + .value("Float", sort_category::Float) + .value("StringBuffer", sort_category::StringBuffer) + .value("Bool", sort_category::Bool) + .value("Symbol", sort_category::Symbol) + .value("Variable", sort_category::Variable) + .value("MInt", sort_category::MInt); + + py::class_(ast, "value_type") + .def(py::init([](sort_category cat) { + return value_type{cat, 0}; })) - .def(py::init([](SortCategory cat, uint64_t bits) { - return ValueType{cat, bits}; + .def(py::init([](sort_category cat, uint64_t bits) { + return value_type{cat, bits}; })); /* Sorts */ @@ -248,67 +252,67 @@ void bind_ast(py::module_ &m) { // NOLINTBEGIN(misc-redundant-expression) auto sort_base - = py::class_>(ast, "Sort") - .def_property_readonly("is_concrete", &KORESort::isConcrete) - .def("substitute", &KORESort::substitute) - .def("__repr__", print_repr_adapter()) + = py::class_>(ast, "Sort") + .def_property_readonly("is_concrete", &kore_sort::is_concrete) + .def("substitute", &kore_sort::substitute) + .def("__repr__", print_repr_adapter()) .def( "__hash__", - [](KORESort const &sort) { return HashSort{}(sort); }) + [](kore_sort const &sort) { return hash_sort{}(sort); }) .def(py::self == py::self) .def(py::self != py::self); - py::class_>( + py::class_>( ast, "SortVariable", sort_base) - .def(py::init(&KORESortVariable::Create)) - .def_property_readonly("name", &KORESortVariable::getName); + .def(py::init(&kore_sort_variable::create)) + .def_property_readonly("name", &kore_sort_variable::get_name); - py::class_>( + py::class_>( ast, "CompositeSort", sort_base) .def( - py::init(&KORECompositeSort::Create), py::arg("name"), - py::arg("cat") = ValueType{SortCategory::Uncomputed, 0}) - .def_property_readonly("name", &KORECompositeSort::getName) - .def("add_argument", &KORECompositeSort::addArgument) - .def_property_readonly("arguments", &KORECompositeSort::getArguments); + py::init(&kore_composite_sort::create), py::arg("name"), + py::arg("cat") = value_type{sort_category::Uncomputed, 0}) + .def_property_readonly("name", &kore_composite_sort::get_name) + .def("add_argument", &kore_composite_sort::add_argument) + .def_property_readonly("arguments", &kore_composite_sort::get_arguments); /* Symbols */ - py::class_(ast, "Symbol") - .def(py::init(&KORESymbol::Create)) - .def("__repr__", print_repr_adapter()) - .def("add_argument", &KORESymbol::addArgument) - .def_property_readonly("arguments", &KORESymbol::getArguments) - .def("add_formal_argument", &KORESymbol::addFormalArgument) + py::class_(ast, "Symbol") + .def(py::init(&kore_symbol::create)) + .def("__repr__", print_repr_adapter()) + .def("add_argument", &kore_symbol::add_argument) + .def_property_readonly("arguments", &kore_symbol::get_arguments) + .def("add_formal_argument", &kore_symbol::add_formal_argument) .def_property_readonly( - "formal_arguments", &KORESymbol::getFormalArguments) - .def("add_sort", &KORESymbol::addSort) + "formal_arguments", &kore_symbol::get_formal_arguments) + .def("add_sort", &kore_symbol::add_sort) .def_property_readonly( - "sort", py::overload_cast<>(&KORESymbol::getSort, py::const_)) - .def_property_readonly("name", &KORESymbol::getName) - .def_property_readonly("is_concrete", &KORESymbol::isConcrete) - .def_property_readonly("is_builtin", &KORESymbol::isBuiltin) + "sort", py::overload_cast<>(&kore_symbol::get_sort, py::const_)) + .def_property_readonly("name", &kore_symbol::get_name) + .def_property_readonly("is_concrete", &kore_symbol::is_concrete) + .def_property_readonly("is_builtin", &kore_symbol::is_builtin) .def(py::self == py::self) .def(py::self != py::self); - py::class_(ast, "Variable") - .def(py::init(&KOREVariable::Create)) - .def("__repr__", print_repr_adapter()) - .def_property_readonly("name", &KOREVariable::getName); + py::class_(ast, "Variable") + .def(py::init(&kore_variable::create)) + .def("__repr__", print_repr_adapter()) + .def_property_readonly("name", &kore_variable::get_name); // NOLINTEND(misc-redundant-expression) /* Patterns */ auto pattern_base - = py::class_>(ast, "Pattern") - .def(py::init(&KOREPattern::load)) - .def("__repr__", print_repr_adapter()) - .def_property_readonly("sort", &KOREPattern::getSort) - .def("substitute", &KOREPattern::substitute) + = py::class_>(ast, "Pattern") + .def(py::init(&kore_pattern::load)) + .def("__repr__", print_repr_adapter()) + .def_property_readonly("sort", &kore_pattern::get_sort) + .def("substitute", &kore_pattern::substitute) .def( "serialize", - [](KOREPattern const &pattern, bool emit_size) { + [](kore_pattern const &pattern, bool emit_size) { auto out = serializer{}; pattern.serialize_to(out); @@ -330,40 +334,41 @@ void bind_ast(py::module_ &m) { py::arg("strip_raw_term") = true) .def_static("read_from", &read_pattern_from_file); - py::class_>( + py::class_>( ast, "CompositePattern", pattern_base) .def(py::init(py::overload_cast( - &KORECompositePattern::Create))) + &kore_composite_pattern::create))) .def(py::init( - py::overload_cast(&KORECompositePattern::Create))) + py::overload_cast(&kore_composite_pattern::create))) + .def_property_readonly( + "constructor", &kore_composite_pattern::get_constructor) + .def("desugar_associative", &kore_composite_pattern::desugar_associative) + .def("add_argument", &kore_composite_pattern::add_argument) .def_property_readonly( - "constructor", &KORECompositePattern::getConstructor) - .def("desugar_associative", &KORECompositePattern::desugarAssociative) - .def("add_argument", &KORECompositePattern::addArgument) - .def_property_readonly("arguments", &KORECompositePattern::getArguments); + "arguments", &kore_composite_pattern::get_arguments); - py::class_>( + py::class_>( ast, "VariablePattern", pattern_base) - .def(py::init(&KOREVariablePattern::Create)) - .def_property_readonly("name", &KOREVariablePattern::getName); + .def(py::init(&kore_variable_pattern::create)) + .def_property_readonly("name", &kore_variable_pattern::get_name); - py::class_>( + py::class_>( ast, "StringPattern", pattern_base) - .def(py::init(&KOREStringPattern::Create)) - .def_property_readonly("contents", &KOREStringPattern::getContents); + .def(py::init(&kore_string_pattern::create)) + .def_property_readonly("contents", &kore_string_pattern::get_contents); } void bind_parser(py::module_ &mod) { auto parser = mod.def_submodule("parser", "KORE Parser"); - py::class_>(parser, "Parser") + py::class_>(parser, "Parser") .def(py::init()) - .def_static("from_string", &KOREParser::from_string) + .def_static("from_string", &kore_parser::from_string) .def( "pattern", - [](KOREParser &parser) { return std::shared_ptr(parser.pattern()); }) - .def("sort", [](KOREParser &parser) { return parser.sort(); }) - .def("definition", [](KOREParser &parser) { + [](kore_parser &parser) { return std::shared_ptr(parser.pattern()); }) + .def("sort", [](kore_parser &parser) { return parser.sort(); }) + .def("definition", [](kore_parser &parser) { return std::shared_ptr(parser.definition()); }); } @@ -371,71 +376,72 @@ void bind_parser(py::module_ &mod) { void bind_proof_trace(py::module_ &m) { auto proof_trace = m.def_submodule("prooftrace", "K LLVM backend KORE AST"); - auto llvm_step_event - = py::class_>( - proof_trace, "LLVMStepEvent") - .def("__repr__", print_repr_adapter()); + auto step_event + = py::class_>( + proof_trace, "llvm_step_event") + .def("__repr__", print_repr_adapter()); - auto llvm_rewrite_event - = py::class_>( - proof_trace, "LLVMREwriteEvent", llvm_step_event) + auto rewrite_event + = py::class_>( + proof_trace, "LLVMREwriteEvent", step_event) .def_property_readonly( - "rule_ordinal", &LLVMRewriteEvent::getRuleOrdinal) + "rule_ordinal", &llvm_rewrite_event::get_rule_ordinal) .def_property_readonly( - "substitution", &LLVMRewriteEvent::getSubstitution); + "substitution", &llvm_rewrite_event::get_substitution); - [[maybe_unused]] auto llvm_rule_event - = py::class_>( - proof_trace, "LLVMRuleEvent", llvm_rewrite_event); + [[maybe_unused]] auto rule_event + = py::class_>( + proof_trace, "llvm_rule_event", rewrite_event); - [[maybe_unused]] auto llvm_side_condition_event = py::class_< - LLVMSideConditionEvent, std::shared_ptr>( - proof_trace, "LLVMSideConditionEvent", llvm_rewrite_event); + [[maybe_unused]] auto side_condition_event = py::class_< + llvm_side_condition_event, std::shared_ptr>( + proof_trace, "llvm_side_condition_event", rewrite_event); py::class_< - LLVMSideConditionEndEvent, std::shared_ptr>( - proof_trace, "LLVMSideConditionEndEvent", llvm_step_event) + llvm_side_condition_end_event, + std::shared_ptr>( + proof_trace, "llvm_side_condition_end_event", step_event) .def_property_readonly( - "rule_ordinal", &LLVMSideConditionEndEvent::getRuleOrdinal) + "rule_ordinal", &llvm_side_condition_end_event::get_rule_ordinal) .def_property_readonly( - "check_result", &LLVMSideConditionEndEvent::getKOREPattern); + "check_result", &llvm_side_condition_end_event::getkore_pattern); - py::class_>( - proof_trace, "LLVMFunctionEvent", llvm_step_event) - .def_property_readonly("name", &LLVMFunctionEvent::getName) + py::class_>( + proof_trace, "llvm_function_event", step_event) + .def_property_readonly("name", &llvm_function_event::get_name) .def_property_readonly( - "relative_position", &LLVMFunctionEvent::getRelativePosition) - .def_property_readonly("args", &LLVMFunctionEvent::getArguments); + "relative_position", &llvm_function_event::get_relative_position) + .def_property_readonly("args", &llvm_function_event::get_arguments); - py::class_>( - proof_trace, "LLVMHookEvent", llvm_step_event) - .def_property_readonly("name", &LLVMHookEvent::getName) + py::class_>( + proof_trace, "llvm_hook_event", step_event) + .def_property_readonly("name", &llvm_hook_event::get_name) .def_property_readonly( - "relative_position", &LLVMHookEvent::getRelativePosition) - .def_property_readonly("args", &LLVMHookEvent::getArguments) - .def_property_readonly("result", &LLVMHookEvent::getKOREPattern); - - py::class_>(proof_trace, "Argument") - .def("__repr__", print_repr_adapter(true)) - .def_property_readonly("step_event", &LLVMEvent::getStepEvent) - .def_property_readonly("kore_pattern", &LLVMEvent::getKOREPattern) - .def("is_step_event", &LLVMEvent::isStep) - .def("is_kore_pattern", &LLVMEvent::isPattern); - - py::class_>( - proof_trace, "LLVMRewriteTrace") - .def("__repr__", print_repr_adapter()) - .def_property_readonly("version", &LLVMRewriteTrace::getVersion) - .def_property_readonly("pre_trace", &LLVMRewriteTrace::getPreTrace) + "relative_position", &llvm_hook_event::get_relative_position) + .def_property_readonly("args", &llvm_hook_event::get_arguments) + .def_property_readonly("result", &llvm_hook_event::getkore_pattern); + + py::class_>(proof_trace, "Argument") + .def("__repr__", print_repr_adapter(true)) + .def_property_readonly("step_event", &llvm_event::get_step_event) + .def_property_readonly("kore_pattern", &llvm_event::getkore_pattern) + .def("is_step_event", &llvm_event::is_step) + .def("is_kore_pattern", &llvm_event::is_pattern); + + py::class_>( + proof_trace, "llvm_rewrite_trace") + .def("__repr__", print_repr_adapter()) + .def_property_readonly("version", &llvm_rewrite_trace::get_version) + .def_property_readonly("pre_trace", &llvm_rewrite_trace::get_pre_trace) .def_property_readonly( - "initial_config", &LLVMRewriteTrace::getInitialConfig) - .def_property_readonly("trace", &LLVMRewriteTrace::getTrace) + "initial_config", &llvm_rewrite_trace::get_initial_config) + .def_property_readonly("trace", &llvm_rewrite_trace::get_trace) .def_static( "parse", [](py::bytes const &bytes) { - ProofTraceParser Parser(false); + proof_trace_parser parser(false); auto str = std::string(bytes); - return Parser.parse_proof_trace(str); + return parser.parse_proof_trace(str); }, py::arg("bytes")); } diff --git a/bindings/python/runtime.cpp b/bindings/python/runtime.cpp index 9ba7cc821..2159f6107 100644 --- a/bindings/python/runtime.cpp +++ b/bindings/python/runtime.cpp @@ -40,10 +40,10 @@ PYBIND11_DECLARE_HOLDER_TYPE(T, raw_ptr, true); */ extern "C" { -void initStaticObjects(void); -void freeAllKoreMem(void); +void init_static_objects(void); +void free_all_kore_mem(void); block *take_steps(int64_t, block *); -void *constructInitialConfiguration(KOREPattern const *initial); +void *construct_initial_configuration(kore_pattern const *initial); } void bind_runtime(py::module_ &m) { @@ -59,31 +59,31 @@ void bind_runtime(py::module_ &m) { m.def("evaluate_function", bindings::evaluate_function); - m.def("init_static_objects", initStaticObjects); - m.def("free_all_gc_memory", freeAllKoreMem); + m.def("init_static_objects", init_static_objects); + m.def("free_all_gc_memory", free_all_kore_mem); // This class can't be used directly from Python; the mutability semantics // that we get from the Pybind wrappers make it really easy to break things. // We therefore have to wrap it up in some external Python code; see // package/kllvm/__init__.py for the details of the external class. py::class_>(m, "InternalTerm", py::module_local()) - .def(py::init([](KOREPattern const *init) { - return static_cast(constructInitialConfiguration(init)); + .def(py::init([](kore_pattern const *init) { + return static_cast(construct_initial_configuration(init)); })) .def( "__str__", [](block *term) { - auto *k_str = printConfigurationToString(term); + auto *k_str = print_configuration_to_string(term); return std::string(k_str->data, len(k_str)); }) .def("step", [](block *term, int64_t n) { return take_steps(n, term); }) - .def("to_pattern", [](block *term) { return termToKorePattern(term); }) + .def("to_pattern", [](block *term) { return term_to_kore_pattern(term); }) .def( "serialize", [](block *term, bool emit_size) { char *data = nullptr; size_t size = 0; - serializeConfiguration( + serialize_configuration( term, nullptr, &data, &size, emit_size, true); return py::bytes(std::string(data, data + size)); }, @@ -92,13 +92,13 @@ void bind_runtime(py::module_ &m) { "deserialize", [](py::bytes const &bytes) { auto str = std::string(bytes); - return deserializeConfiguration(str.data(), str.size()); + return deserialize_configuration(str.data(), str.size()); }) .def( "_serialize_raw", [](block *term, std::string const &filename, std::string const &sort) { FILE *file = fopen(filename.c_str(), "a"); - serializeRawTermToFile(file, term, sort.c_str(), true); + serialize_raw_term_to_file(file, term, sort.c_str(), true); fclose(file); }); } diff --git a/include/kllvm/ast/AST.h b/include/kllvm/ast/AST.h index f3fd29c3a..dd19251be 100644 --- a/include/kllvm/ast/AST.h +++ b/include/kllvm/ast/AST.h @@ -26,9 +26,9 @@ namespace kllvm { class serializer; -class KORESortVariable; +class kore_sort_variable; -struct HashSort; +struct hash_sort; template using ptr = std::unique_ptr; @@ -36,7 +36,7 @@ using ptr = std::unique_ptr; template using sptr = std::shared_ptr; -std::string decodeKore(std::string); +std::string decode_kore(std::string); /* * Helper function to avoid repeated call-site uses of ostringstream when we @@ -50,78 +50,78 @@ std::string ast_to_string(T &&node, Args &&...args) { return os.str(); } -// KORESort -class KORESort : public std::enable_shared_from_this { +// kore_sort +class kore_sort : public std::enable_shared_from_this { public: using substitution - = std::unordered_map, HashSort>; + = std::unordered_map, hash_sort>; - virtual bool isConcrete() const = 0; - virtual sptr substitute(substitution const &) = 0; + virtual bool is_concrete() const = 0; + virtual sptr substitute(substitution const &) = 0; - virtual bool operator==(KORESort const &other) const = 0; - bool operator!=(KORESort const &other) const { return !(*this == other); } + virtual bool operator==(kore_sort const &other) const = 0; + bool operator!=(kore_sort const &other) const { return !(*this == other); } - virtual void print(std::ostream &Out, unsigned indent = 0) const = 0; - virtual void prettyPrint(std::ostream &Out) const = 0; + virtual void print(std::ostream &out, unsigned indent = 0) const = 0; + virtual void pretty_print(std::ostream &out) const = 0; virtual void serialize_to(serializer &s) const = 0; - virtual ~KORESort() = default; + virtual ~kore_sort() = default; }; -static inline std::ostream &operator<<(std::ostream &out, KORESort const &s) { +static inline std::ostream &operator<<(std::ostream &out, kore_sort const &s) { s.print(out); return out; } -struct HashSort { - size_t operator()(kllvm::KORESort const &s) const noexcept { +struct hash_sort { + size_t operator()(kllvm::kore_sort const &s) const noexcept { return std::hash{}(ast_to_string(s)); } }; -struct EqualSortPtr { - bool operator()(KORESort *const &first, KORESort *const &second) const { +struct equal_sort_ptr { + bool operator()(kore_sort *const &first, kore_sort *const &second) const { return *first == *second; } }; -struct HashSortPtr { - size_t operator()(kllvm::KORESort *const &s) const noexcept { +struct hash_sort_ptr { + size_t operator()(kllvm::kore_sort *const &s) const noexcept { return std::hash{}(ast_to_string(*s)); } }; -size_t hash_value(kllvm::KORESort const &s); +size_t hash_value(kllvm::kore_sort const &s); -class KORESortVariable : public KORESort { +class kore_sort_variable : public kore_sort { private: - std::string name; + std::string name_; public: - static sptr Create(std::string const &Name) { - return sptr(new KORESortVariable(Name)); + static sptr create(std::string const &name) { + return sptr(new kore_sort_variable(name)); } - bool isConcrete() const override { return false; } - sptr substitute(substitution const &subst) override { + bool is_concrete() const override { return false; } + sptr substitute(substitution const &subst) override { return subst.at(*this); } - void print(std::ostream &Out, unsigned indent = 0) const override; - void prettyPrint(std::ostream &Out) const override; + void print(std::ostream &out, unsigned indent = 0) const override; + void pretty_print(std::ostream &out) const override; void serialize_to(serializer &s) const override; - bool operator==(KORESort const &other) const override; + bool operator==(kore_sort const &other) const override; - std::string const &getName() const { return name; } + std::string const &get_name() const { return name_; } private: - KORESortVariable(std::string Name) - : name(std::move(Name)) { } + kore_sort_variable(std::string name) + : name_(std::move(name)) { } }; -enum class SortCategory { +enum class sort_category { Uncomputed, Map, List, @@ -137,129 +137,133 @@ enum class SortCategory { }; // represents the syntactic category of an LLVM backend term at runtime -struct ValueType { +struct value_type { // fundamental category of the term - SortCategory cat; + sort_category cat; // if this is an MInt, the number of bits in the MInt uint64_t bits; - bool operator<(ValueType const &that) const { + bool operator<(value_type const &that) const { return std::make_tuple(this->cat, this->bits) < std::make_tuple(that.cat, that.bits); } }; -class KOREDefinition; +class kore_definition; -class KORECompositeSort : public KORESort { +class kore_composite_sort : public kore_sort { private: - std::string name; - std::vector> arguments; - ValueType category; + std::string name_; + std::vector> arguments_; + value_type category_; public: - static sptr Create( - std::string const &Name, ValueType Cat = {SortCategory::Uncomputed, 0}) { - return sptr(new KORECompositeSort(Name, Cat)); + static sptr create( + std::string const &name, + value_type cat = {sort_category::Uncomputed, 0}) { + return sptr(new kore_composite_sort(name, cat)); } - std::string getName() const { return name; } - ValueType getCategory(KOREDefinition *definition); - std::string getHook(KOREDefinition *definition) const; - static ValueType getCategory(std::string const &hookName); + std::string get_name() const { return name_; } + value_type get_category(kore_definition *definition); + std::string get_hook(kore_definition *definition) const; + static value_type get_category(std::string const &hook_name); - bool isConcrete() const override; - sptr substitute(substitution const &subst) override; + bool is_concrete() const override; + sptr substitute(substitution const &subst) override; - void addArgument(sptr const &Argument); - void print(std::ostream &Out, unsigned indent = 0) const override; - void prettyPrint(std::ostream &out) const override; + void add_argument(sptr const &argument); + void print(std::ostream &out, unsigned indent = 0) const override; + void pretty_print(std::ostream &out) const override; void serialize_to(serializer &s) const override; - bool operator==(KORESort const &other) const override; + bool operator==(kore_sort const &other) const override; - std::vector> const &getArguments() const { return arguments; } + std::vector> const &get_arguments() const { + return arguments_; + } private: - KORECompositeSort(std::string Name, ValueType category) - : name(std::move(Name)) - , category(category) { } + kore_composite_sort(std::string name, value_type category) + : name_(std::move(name)) + , category_(category) { } }; -struct HashSymbol; +struct hash_symbol; -class KORESymbolDeclaration; +class kore_symbol_declaration; -// KORESymbol -class KORESymbol { +// kore_symbol +class kore_symbol { private: - std::string name; + std::string name_; /* At parse time, when parsed as part of a pattern, this will be empty. When parsed as part of a declaration, it contains the signature of the symbol. After instantiateSymbol is called on a symbol that is part of a pattern, it changes from being empty to being the signature of the symbol. instantiateSymbol is called on all object level symbols in - axioms when KOREDefinition::preprocess is called. */ - std::vector> arguments; + axioms when kore_definition::preprocess is called. */ + std::vector> arguments_; /* contains the original arguments to the symbol when parsed as parh of a * pattern. */ - std::vector> formalArguments; + std::vector> formal_arguments_; /** At parse time, when parsed as part of a pattern, this will be null. When parsed as part of a declaration, it contains the return sort of the - symbol. See above re: the behavior of KORESymbol with respect to + symbol. See above re: the behavior of kore_symbol with respect to instantiateSymbol. */ - sptr sort; + sptr sort_; /* the first integer in a continuous range representing the tags of all the polymorphic instantiations of this symbol. If the symbol has no parameters or its parameters are fully specified, firstTag == lastTag. */ - uint32_t firstTag{}; + uint32_t first_tag_{}; /* the last integer in a continuous range representing the tags of all the polymorphic instantiations of this symbol. If the symbol has no parameters or its parameters are fully specified, firstTag == lastTag. */ - uint32_t lastTag{}; + uint32_t last_tag_{}; /* A unique integer representing the layout of the symbol in memory. - See CreateTerm.cpp for more information about the layout of K terms. */ - uint16_t layout{}; + See create_term.cpp for more information about the layout of K terms. */ + uint16_t layout_{}; public: - static ptr Create(std::string const &Name) { - return ptr(new KORESymbol(Name)); + static ptr create(std::string const &name) { + return ptr(new kore_symbol(name)); } - void addArgument(sptr const &Argument); - void addFormalArgument(sptr const &Argument); - void addSort(sptr Sort); - void initPatternArguments() { arguments.swap(formalArguments); } + void add_argument(sptr const &argument); + void add_formal_argument(sptr const &argument); + void add_sort(sptr sort); + void init_pattern_arguments() { arguments_.swap(formal_arguments_); } - [[nodiscard]] std::string const &getName() const { return name; } - [[nodiscard]] std::vector> const &getArguments() const { - return arguments; + [[nodiscard]] std::string const &get_name() const { return name_; } + [[nodiscard]] std::vector> const &get_arguments() const { + return arguments_; } - [[nodiscard]] std::vector> const &getFormalArguments() const { - return formalArguments; + [[nodiscard]] std::vector> const & + get_formal_arguments() const { + return formal_arguments_; } - [[nodiscard]] sptr getSort() const { return sort; } - sptr getSort() { return sort; } - [[nodiscard]] uint32_t getTag() const { - assert(firstTag == lastTag); - return firstTag; + [[nodiscard]] sptr get_sort() const { return sort_; } + sptr get_sort() { return sort_; } + [[nodiscard]] uint32_t get_tag() const { + assert(first_tag_ == last_tag_); + return first_tag_; } - [[nodiscard]] uint32_t getFirstTag() const { return firstTag; } - [[nodiscard]] uint32_t getLastTag() const { return lastTag; } - void setTag(uint32_t val) { firstTag = lastTag = val; } - [[nodiscard]] uint16_t getLayout() const { return layout; } + [[nodiscard]] uint32_t get_first_tag() const { return first_tag_; } + [[nodiscard]] uint32_t get_last_tag() const { return last_tag_; } + void set_tag(uint32_t val) { first_tag_ = last_tag_ = val; } + [[nodiscard]] uint16_t get_layout() const { return layout_; } - void print(std::ostream &Out, unsigned indent = 0) const; - void print(std::ostream &Out, unsigned indent, bool formal) const; + void print(std::ostream &out, unsigned indent = 0) const; + void print(std::ostream &out, unsigned indent, bool formal) const; void serialize_to(serializer &s) const; - bool operator==(KORESymbol const &other) const; - bool operator!=(KORESymbol const &other) const { return !(*this == other); } + bool operator==(kore_symbol const &other) const; + bool operator!=(kore_symbol const &other) const { return !(*this == other); } - std::string layoutString(KOREDefinition *) const; + std::string layout_string(kore_definition *) const; - [[nodiscard]] bool isConcrete() const; - [[nodiscard]] bool isPolymorphic() const; - [[nodiscard]] bool isBuiltin() const; + [[nodiscard]] bool is_concrete() const; + [[nodiscard]] bool is_polymorphic() const; + [[nodiscard]] bool is_builtin() const; /* instantiates this symbol (which should be parsed from a pattern in an axiom) with the sorts corresponding to its actual sort parameters after @@ -268,76 +272,76 @@ class KORESymbol { substitution in the arguments to the pattern that were parsed in braces. The result is that the arguments and sort fields are replaced with the instantiated signature of the symbol. */ - void instantiateSymbol(KORESymbolDeclaration *decl); + void instantiate_symbol(kore_symbol_declaration *decl); - friend HashSymbol; + friend hash_symbol; - friend KOREDefinition; + friend kore_definition; private: - KORESymbol(std::string Name) - : name(std::move(Name)) - , sort(nullptr) { } + kore_symbol(std::string name) + : name_(std::move(name)) + , sort_(nullptr) { } }; -struct HashSymbol { - size_t operator()(kllvm::KORESymbol const &s) const noexcept { +struct hash_symbol { + size_t operator()(kllvm::kore_symbol const &s) const noexcept { size_t hash = 0; - boost::hash_combine(hash, s.name); - for (auto const &arg : s.arguments) { + boost::hash_combine(hash, s.name_); + for (auto const &arg : s.arguments_) { boost::hash_combine(hash, *arg); } return hash; } }; -struct EqualSymbolPtr { - bool operator()(KORESymbol *const &first, KORESymbol *const &second) const { +struct equal_symbol_ptr { + bool operator()(kore_symbol *const &first, kore_symbol *const &second) const { return ast_to_string(*first) == ast_to_string(*second); } }; -struct HashSymbolPtr { - size_t operator()(kllvm::KORESymbol *const &s) const noexcept { +struct hash_symbol_ptr { + size_t operator()(kllvm::kore_symbol *const &s) const noexcept { return std::hash{}(ast_to_string(*s)); } }; -// KOREVariable -class KOREVariable { +// kore_variable +class kore_variable { private: - std::string name; + std::string name_; public: - static ptr Create(std::string const &Name) { - return ptr(new KOREVariable(Name)); + static ptr create(std::string const &name) { + return ptr(new kore_variable(name)); } - [[nodiscard]] std::string getName() const; + [[nodiscard]] std::string get_name() const; - virtual void print(std::ostream &Out, unsigned indent = 0) const; + virtual void print(std::ostream &out, unsigned indent = 0) const; virtual void serialize_to(serializer &s) const; - virtual ~KOREVariable() = default; + virtual ~kore_variable() = default; private: - KOREVariable(std::string Name) - : name(std::move(Name)) { } + kore_variable(std::string name) + : name_(std::move(name)) { } }; -class KOREVariablePattern; +class kore_variable_pattern; -using SortSet = std::unordered_set; +using SortSet = std::unordered_set; using SymbolSet - = std::unordered_set; + = std::unordered_set; using SubsortMap - = std::unordered_map; + = std::unordered_map; using SymbolMap = std::unordered_map< - KORESymbol *, SymbolSet, HashSymbolPtr, EqualSymbolPtr>; + kore_symbol *, SymbolSet, hash_symbol_ptr, equal_symbol_ptr>; using BracketMap = std::unordered_map< - KORESort *, std::vector, HashSortPtr, EqualSortPtr>; + kore_sort *, std::vector, hash_sort_ptr, equal_sort_ptr>; -struct PrettyPrintData { +struct pretty_print_data { // map from symbol name to format attribute specifying how to print that // symbol std::map format; @@ -346,8 +350,8 @@ struct PrettyPrintData { // map from symbol name to terminal pattern std::map terminals; std::map> priorities; - std::map> leftAssoc; - std::map> rightAssoc; + std::map> left_assoc; + std::map> right_assoc; // map from sort name to hook attribute for that sort std::map hook; // map from sort name to bracket for that sort @@ -358,62 +362,63 @@ struct PrettyPrintData { std::set comm; SubsortMap subsorts; // enable coloring - bool hasColor{}; + bool has_color{}; }; -class KOREDeclaration; -class KORECompositePattern; +class kore_declaration; +class kore_composite_pattern; -// KOREPattern -class KOREPattern : public std::enable_shared_from_this { +// kore_pattern +class kore_pattern : public std::enable_shared_from_this { public: /* * Load a pattern from disk, examining the first 4 bytes to see if it's a * binary file or a textual KORE file. */ - static sptr load(std::string const &filename); + static sptr load(std::string const &filename); - virtual ~KOREPattern() = default; + virtual ~kore_pattern() = default; - virtual void print(std::ostream &Out, unsigned indent = 0) const = 0; + virtual void print(std::ostream &out, unsigned indent = 0) const = 0; virtual void serialize_to(serializer &s) const = 0; /* adds all the object level symbols contained recursively in the current pattern to the specified map, mapping their symbol name to the list of all instances of that symbol. */ - virtual void markSymbols(std::map> &) + virtual void mark_symbols(std::map> &) = 0; /* adds all the object level variables contained recursively in the current pattern to the specified map, mapping their variable name to the variable itself. */ - virtual void markVariables(std::map &) + virtual void mark_variables(std::map &) = 0; - virtual sptr getSort() const = 0; + virtual sptr get_sort() const = 0; - using substitution = std::unordered_map>; + using substitution = std::unordered_map>; - virtual sptr substitute(substitution const &) = 0; - virtual sptr expandAliases(KOREDefinition *) = 0; + virtual sptr substitute(substitution const &) = 0; + virtual sptr expand_aliases(kore_definition *) = 0; - virtual void prettyPrint(std::ostream &, PrettyPrintData const &data) const + virtual void pretty_print(std::ostream &, pretty_print_data const &data) const + = 0; + virtual sptr sort_collections(pretty_print_data const &data) = 0; - virtual sptr sortCollections(PrettyPrintData const &data) = 0; - std::set gatherSingletonVars(); - virtual std::map gatherVarCounts() = 0; - virtual sptr filterSubstitution( - PrettyPrintData const &data, std::set const &vars) + std::set gather_singleton_vars(); + virtual std::map gather_var_counts() = 0; + virtual sptr filter_substitution( + pretty_print_data const &data, std::set const &vars) = 0; - virtual sptr dedupeDisjuncts() = 0; + virtual sptr dedupe_disjuncts() = 0; virtual bool matches( substitution &subst, SubsortMap const &subsorts, - SymbolMap const &overloads, sptr subject) + SymbolMap const &overloads, sptr subject) = 0; - sptr expandMacros( + sptr expand_macros( SubsortMap const &subsorts, SymbolMap const &overloads, - std::vector> const &axioms, bool reverse); - virtual sptr unflattenAndOr() = 0; + std::vector> const &axioms, bool reverse); + virtual sptr unflatten_and_or() = 0; /* * Recursively expands productions of the form: @@ -430,493 +435,511 @@ class KOREPattern : public std::enable_shared_from_this { * primarily to be called from language bindings that programatically * construct patterns. */ - virtual sptr desugarAssociative() = 0; + virtual sptr desugar_associative() = 0; - friend KORECompositePattern; + friend kore_composite_pattern; private: - virtual sptr expandMacros( + virtual sptr expand_macros( SubsortMap const &subsorts, SymbolMap const &overloads, - std::vector> const &axioms, bool reverse, - std::set &appliedRules, std::set const ¯oSymbols) + std::vector> const &axioms, bool reverse, + std::set &applied_rules, + std::set const ¯o_symbols) = 0; }; void flatten( - KORECompositePattern *pat, std::string const &name, - std::vector> &result); + kore_composite_pattern *pat, std::string const &name, + std::vector> &result); -class KOREVariablePattern : public KOREPattern { +class kore_variable_pattern : public kore_pattern { private: - ptr name; - sptr sort; + ptr name_; + sptr sort_; public: - static ptr - Create(std::string const &Name, sptr sort) { - ptr Var = KOREVariable::Create(Name); - return ptr( - new KOREVariablePattern(std::move(Var), std::move(sort))); + static ptr + create(std::string const &name, sptr sort) { + ptr var = kore_variable::create(name); + return ptr( + new kore_variable_pattern(std::move(var), std::move(sort))); } - std::string getName() const; - sptr getSort() const override { return sort; } + std::string get_name() const; + sptr get_sort() const override { return sort_; } - void print(std::ostream &Out, unsigned indent = 0) const override; + void print(std::ostream &out, unsigned indent = 0) const override; void serialize_to(serializer &s) const override; void - markSymbols(std::map> &) override { } + mark_symbols(std::map> &) override { } void - markVariables(std::map &map) override { - map.insert({name->getName(), this}); + mark_variables(std::map &map) override { + map.insert({name_->get_name(), this}); } - sptr substitute(substitution const &subst) override { - auto val = subst.find(name->getName()); + sptr substitute(substitution const &subst) override { + auto val = subst.find(name_->get_name()); if (val == subst.end()) { return shared_from_this(); } return val->second; } - sptr expandAliases(KOREDefinition *) override { + sptr expand_aliases(kore_definition *) override { return shared_from_this(); } - sptr sortCollections(PrettyPrintData const &data) override { + sptr sort_collections(pretty_print_data const &data) override { return shared_from_this(); } - sptr dedupeDisjuncts() override { return shared_from_this(); } - std::map gatherVarCounts() override { - return std::map{{name->getName(), 1}}; + sptr dedupe_disjuncts() override { return shared_from_this(); } + std::map gather_var_counts() override { + return std::map{{name_->get_name(), 1}}; } - sptr filterSubstitution( - PrettyPrintData const &data, std::set const &vars) override { + sptr filter_substitution( + pretty_print_data const &data, + std::set const &vars) override { return shared_from_this(); } - sptr desugarAssociative() override { return shared_from_this(); } + sptr desugar_associative() override { + return shared_from_this(); + } - sptr unflattenAndOr() override { return shared_from_this(); } + sptr unflatten_and_or() override { return shared_from_this(); } bool matches( substitution &subst, SubsortMap const &, SymbolMap const &, - sptr subject) override; + sptr subject) override; void - prettyPrint(std::ostream &out, PrettyPrintData const &data) const override; + pretty_print(std::ostream &out, pretty_print_data const &data) const override; private: - sptr expandMacros( + sptr expand_macros( SubsortMap const &, SymbolMap const &, - std::vector> const ¯os, bool reverse, - std::set &appliedRules, - std::set const ¯oSymbols) override { + std::vector> const ¯os, bool reverse, + std::set &applied_rules, + std::set const ¯o_symbols) override { return shared_from_this(); } - KOREVariablePattern(ptr Name, sptr Sort) - : name(std::move(Name)) - , sort(std::move(std::move(Sort))) { } + kore_variable_pattern(ptr name, sptr sort) + : name_(std::move(name)) + , sort_(std::move(std::move(sort))) { } }; -void deallocateSPtrKorePattern(sptr pattern); +void deallocate_s_ptr_kore_pattern(sptr pattern); -class KORECompositePattern : public KOREPattern { +class kore_composite_pattern : public kore_pattern { private: - ptr constructor; - std::vector> arguments; + ptr constructor_; + std::vector> arguments_; public: - static ptr Create(std::string const &Name) { - ptr Sym = KORESymbol::Create(Name); - return ptr(new KORECompositePattern(std::move(Sym))); + static ptr create(std::string const &name) { + ptr sym = kore_symbol::create(name); + return ptr( + new kore_composite_pattern(std::move(sym))); } - static ptr Create(ptr Sym) { - return ptr(new KORECompositePattern(std::move(Sym))); + static ptr create(ptr sym) { + return ptr( + new kore_composite_pattern(std::move(sym))); } - static ptr Create(KORESymbol *Sym) { - ptr newSym = KORESymbol::Create(Sym->getName()); - *newSym = *Sym; - return ptr( - new KORECompositePattern(std::move(newSym))); + static ptr create(kore_symbol *sym) { + ptr new_sym = kore_symbol::create(sym->get_name()); + *new_sym = *sym; + return ptr( + new kore_composite_pattern(std::move(new_sym))); } - sptr getSort() const override { - if (constructor->getName() == "\\dv" - && !constructor->getFormalArguments().empty()) { - if (auto arg = constructor->getFormalArguments()[0]) { + sptr get_sort() const override { + if (constructor_->get_name() == "\\dv" + && !constructor_->get_formal_arguments().empty()) { + if (auto arg = constructor_->get_formal_arguments()[0]) { return arg; } } - return constructor->getSort(); + return constructor_->get_sort(); } - KORESymbol *getConstructor() const { return constructor.get(); } - std::vector> const &getArguments() const { - return arguments; + kore_symbol *get_constructor() const { return constructor_.get(); } + std::vector> const &get_arguments() const { + return arguments_; } - void addArgument(sptr const &Argument); + void add_argument(sptr const &argument); - void print(std::ostream &Out, unsigned indent = 0) const override; + void print(std::ostream &out, unsigned indent = 0) const override; void serialize_to(serializer &s) const override; void - prettyPrint(std::ostream &out, PrettyPrintData const &data) const override; - void markSymbols(std::map> &) override; - void markVariables(std::map &) override; - sptr substitute(substitution const &) override; - sptr expandAliases(KOREDefinition *) override; - sptr sortCollections(PrettyPrintData const &data) override; - sptr dedupeDisjuncts() override; - std::map gatherVarCounts() override; - sptr desugarAssociative() override; - sptr unflattenAndOr() override; - sptr filterSubstitution( - PrettyPrintData const &data, std::set const &vars) override; + pretty_print(std::ostream &out, pretty_print_data const &data) const override; + void + mark_symbols(std::map> &) override; + void + mark_variables(std::map &) override; + sptr substitute(substitution const &) override; + sptr expand_aliases(kore_definition *) override; + sptr sort_collections(pretty_print_data const &data) override; + sptr dedupe_disjuncts() override; + std::map gather_var_counts() override; + sptr desugar_associative() override; + sptr unflatten_and_or() override; + sptr filter_substitution( + pretty_print_data const &data, + std::set const &vars) override; bool matches( substitution &, SubsortMap const &, SymbolMap const &, - sptr) override; + sptr) override; private: - sptr expandMacros( + sptr expand_macros( SubsortMap const &, SymbolMap const &, - std::vector> const ¯os, bool reverse, - std::set &appliedRules, - std::set const ¯oSymbols) override; + std::vector> const ¯os, bool reverse, + std::set &applied_rules, + std::set const ¯o_symbols) override; - friend void ::kllvm::deallocateSPtrKorePattern(sptr pattern); + friend void ::kllvm::deallocate_s_ptr_kore_pattern( + sptr pattern); - KORECompositePattern(ptr Constructor) - : constructor(std::move(Constructor)) { } + kore_composite_pattern(ptr constructor) + : constructor_(std::move(constructor)) { } }; -class KOREStringPattern : public KOREPattern { +class kore_string_pattern : public kore_pattern { private: - std::string contents; + std::string contents_; public: - static ptr Create(std::string const &Contents) { - return ptr(new KOREStringPattern(Contents)); + static ptr create(std::string const &contents) { + return ptr(new kore_string_pattern(contents)); } - std::string getContents() { return contents; } + std::string get_contents() { return contents_; } - void print(std::ostream &Out, unsigned indent = 0) const override; + void print(std::ostream &out, unsigned indent = 0) const override; void serialize_to(serializer &s) const override; - void - prettyPrint(std::ostream &out, PrettyPrintData const &data) const override { + void pretty_print( + std::ostream &out, pretty_print_data const &data) const override { abort(); } void - markSymbols(std::map> &) override { } - void markVariables(std::map &) override { - } - sptr getSort() const override { abort(); } - sptr substitute(substitution const &) override { + mark_symbols(std::map> &) override { } + void + mark_variables(std::map &) override { } + sptr get_sort() const override { abort(); } + sptr substitute(substitution const &) override { return shared_from_this(); } - sptr expandAliases(KOREDefinition *) override { + sptr expand_aliases(kore_definition *) override { return shared_from_this(); } - sptr sortCollections(PrettyPrintData const &data) override { + sptr sort_collections(pretty_print_data const &data) override { return shared_from_this(); } - sptr dedupeDisjuncts() override { return shared_from_this(); } - std::map gatherVarCounts() override { + sptr dedupe_disjuncts() override { return shared_from_this(); } + std::map gather_var_counts() override { return std::map{}; } - sptr desugarAssociative() override { return shared_from_this(); } + sptr desugar_associative() override { + return shared_from_this(); + } - sptr unflattenAndOr() override { return shared_from_this(); } + sptr unflatten_and_or() override { return shared_from_this(); } - sptr filterSubstitution( - PrettyPrintData const &data, std::set const &var) override { + sptr filter_substitution( + pretty_print_data const &data, + std::set const &var) override { return shared_from_this(); } bool matches( substitution &, SubsortMap const &, SymbolMap const &, - sptr subject) override; + sptr subject) override; private: - sptr expandMacros( + sptr expand_macros( SubsortMap const &, SymbolMap const &, - std::vector> const ¯os, bool reverse, - std::set &appliedRules, - std::set const ¯oSymbols) override { + std::vector> const ¯os, bool reverse, + std::set &applied_rules, + std::set const ¯o_symbols) override { return shared_from_this(); } - KOREStringPattern(std::string Contents) - : contents(std::move(Contents)) { } + kore_string_pattern(std::string contents) + : contents_(std::move(contents)) { } }; -// KOREDeclaration -class KOREDeclaration { +// kore_declaration +class kore_declaration { private: attribute_set attributes_; - std::vector> objectSortVariables; + std::vector> object_sort_variables_; public: attribute_set &attributes() { return attributes_; } [[nodiscard]] attribute_set const &attributes() const { return attributes_; } - void addObjectSortVariable(sptr const &SortVariable); - virtual void print(std::ostream &Out, unsigned indent = 0) const = 0; + void add_object_sort_variable(sptr const &sort_variable); + virtual void print(std::ostream &out, unsigned indent = 0) const = 0; - [[nodiscard]] std::vector> const & - getObjectSortVariables() const { - return objectSortVariables; + [[nodiscard]] std::vector> const & + get_object_sort_variables() const { + return object_sort_variables_; } - virtual ~KOREDeclaration() = default; + virtual ~kore_declaration() = default; protected: - void printSortVariables(std::ostream &Out) const; + void print_sort_variables(std::ostream &out) const; }; -class KORECompositeSortDeclaration : public KOREDeclaration { +class kore_composite_sort_declaration : public kore_declaration { private: - bool _isHooked; - std::string sortName; + bool is_hooked_; + std::string sort_name_; public: - static ptr - Create(std::string const &Name, bool isHooked = false) { - return ptr( - new KORECompositeSortDeclaration(Name, isHooked)); + static ptr + create(std::string const &name, bool is_hooked = false) { + return ptr( + new kore_composite_sort_declaration(name, is_hooked)); } - [[nodiscard]] std::string getName() const { return sortName; } - [[nodiscard]] bool isHooked() const { return _isHooked; } + [[nodiscard]] std::string get_name() const { return sort_name_; } + [[nodiscard]] bool is_hooked() const { return is_hooked_; } - void print(std::ostream &Out, unsigned indent = 0) const override; + void print(std::ostream &out, unsigned indent = 0) const override; private: - KORECompositeSortDeclaration(std::string Name, bool _isHooked) - : _isHooked(_isHooked) - , sortName(std::move(Name)) { } + kore_composite_sort_declaration(std::string name, bool is_hooked) + : is_hooked_(is_hooked) + , sort_name_(std::move(name)) { } }; -class KORESymbolAliasDeclaration : public KOREDeclaration { +class kore_symbol_alias_declaration : public kore_declaration { private: - ptr symbol; + ptr symbol_; protected: - KORESymbolAliasDeclaration(ptr Symbol) - : symbol(std::move(Symbol)) { } + kore_symbol_alias_declaration(ptr symbol) + : symbol_(std::move(symbol)) { } public: - [[nodiscard]] KORESymbol *getSymbol() const { return symbol.get(); } + [[nodiscard]] kore_symbol *get_symbol() const { return symbol_.get(); } }; -class KORESymbolDeclaration : public KORESymbolAliasDeclaration { +class kore_symbol_declaration : public kore_symbol_alias_declaration { private: - bool _isHooked; + bool is_hooked_; public: - static ptr - Create(std::string const &Name, bool isHooked = false) { - ptr Sym = KORESymbol::Create(Name); - return ptr( - new KORESymbolDeclaration(std::move(Sym), isHooked)); + static ptr + create(std::string const &name, bool is_hooked = false) { + ptr sym = kore_symbol::create(name); + return ptr( + new kore_symbol_declaration(std::move(sym), is_hooked)); } - [[nodiscard]] bool isHooked() const { return _isHooked; } + [[nodiscard]] bool is_hooked() const { return is_hooked_; } - [[nodiscard]] bool isAnywhere() const; + [[nodiscard]] bool is_anywhere() const; - void print(std::ostream &Out, unsigned indent = 0) const override; + void print(std::ostream &out, unsigned indent = 0) const override; private: - KORESymbolDeclaration(ptr Symbol, bool _isHooked) - : KORESymbolAliasDeclaration(std::move(Symbol)) - , _isHooked(_isHooked) { } + kore_symbol_declaration(ptr symbol, bool is_hooked) + : kore_symbol_alias_declaration(std::move(symbol)) + , is_hooked_(is_hooked) { } }; -class KOREAliasDeclaration : public KORESymbolAliasDeclaration { +class kore_alias_declaration : public kore_symbol_alias_declaration { private: - sptr boundVariables; - sptr pattern; + sptr bound_variables_; + sptr pattern_; public: - static ptr Create(std::string const &Name) { - ptr Sym = KORESymbol::Create(Name); - return ptr(new KOREAliasDeclaration(std::move(Sym))); + static ptr create(std::string const &name) { + ptr sym = kore_symbol::create(name); + return ptr( + new kore_alias_declaration(std::move(sym))); } - void addVariables(sptr variables); - void addPattern(sptr Pattern); - KOREPattern::substitution getSubstitution(KORECompositePattern *subject); - [[nodiscard]] KORECompositePattern *getBoundVariables() const { - return boundVariables.get(); + void add_variables(sptr variables); + void add_pattern(sptr pattern); + kore_pattern::substitution get_substitution(kore_composite_pattern *subject); + [[nodiscard]] kore_composite_pattern *get_bound_variables() const { + return bound_variables_.get(); } - sptr &getPattern() { return pattern; } - void print(std::ostream &Out, unsigned indent = 0) const override; + sptr &get_pattern() { return pattern_; } + void print(std::ostream &out, unsigned indent = 0) const override; private: - KOREAliasDeclaration(ptr Symbol) - : KORESymbolAliasDeclaration(std::move(Symbol)) { } + kore_alias_declaration(ptr symbol) + : kore_symbol_alias_declaration(std::move(symbol)) { } }; -class KOREAxiomDeclaration : public KOREDeclaration { +class kore_axiom_declaration : public kore_declaration { private: - sptr pattern; - unsigned ordinal{}; - bool _isClaim; + sptr pattern_; + unsigned ordinal_{}; + bool is_claim_; - KOREAxiomDeclaration(bool isClaim) - : _isClaim(isClaim) { } + kore_axiom_declaration(bool is_claim) + : is_claim_(is_claim) { } public: - static ptr Create(bool isClaim = false) { - return ptr(new KOREAxiomDeclaration(isClaim)); + static ptr create(bool is_claim = false) { + return ptr(new kore_axiom_declaration(is_claim)); } - void addPattern(sptr Pattern); - void print(std::ostream &Out, unsigned indent = 0) const override; + void add_pattern(sptr pattern); + void print(std::ostream &out, unsigned indent = 0) const override; /* returns true if the axiom is actually required to be translated to llvm and false if it is an axiom pertaining to symbolic execution which is not required for concrete execution. Axioms that are not required are elided - from the definition by KOREDefinition::preprocess. */ - [[nodiscard]] bool isRequired() const; - [[nodiscard]] bool isTopAxiom() const; - [[nodiscard]] bool isClaim() const { return _isClaim; } - [[nodiscard]] KOREPattern *getRightHandSide() const; - [[nodiscard]] std::vector getLeftHandSide() const; - [[nodiscard]] KOREPattern *getRequires() const; - [[nodiscard]] sptr getPattern() const { return pattern; } - [[nodiscard]] unsigned getOrdinal() const { return ordinal; } - - friend KOREDefinition; + from the definition by kore_definition::preprocess. */ + [[nodiscard]] bool is_required() const; + [[nodiscard]] bool is_top_axiom() const; + [[nodiscard]] bool is_claim() const { return is_claim_; } + [[nodiscard]] kore_pattern *get_right_hand_side() const; + [[nodiscard]] std::vector get_left_hand_side() const; + [[nodiscard]] kore_pattern *get_requires() const; + [[nodiscard]] sptr get_pattern() const { return pattern_; } + [[nodiscard]] unsigned get_ordinal() const { return ordinal_; } + + friend kore_definition; }; -class KOREModuleImportDeclaration : public KOREDeclaration { +class kore_module_import_declaration : public kore_declaration { private: - std::string moduleName; + std::string module_name_; public: - static ptr Create(std::string const &Name) { - return ptr( - new KOREModuleImportDeclaration(Name)); + static ptr create(std::string const &name) { + return ptr( + new kore_module_import_declaration(name)); } - [[nodiscard]] std::string const &getModuleName() const { return moduleName; } + [[nodiscard]] std::string const &get_module_name() const { + return module_name_; + } - void print(std::ostream &Out, unsigned indent = 0) const override; + void print(std::ostream &out, unsigned indent = 0) const override; private: - KOREModuleImportDeclaration(std::string Name) - : moduleName(std::move(Name)) { } + kore_module_import_declaration(std::string name) + : module_name_(std::move(name)) { } }; -// KOREModule -class KOREModule { +// kore_module +class kore_module { private: - std::string name; - std::vector> declarations; + std::string name_; + std::vector> declarations_; attribute_set attributes_; public: - static ptr Create(std::string const &Name) { - return ptr(new KOREModule(Name)); + static ptr create(std::string const &name) { + return ptr(new kore_module(name)); } attribute_set &attributes() { return attributes_; } [[nodiscard]] attribute_set const &attributes() const { return attributes_; } - void addDeclaration(sptr Declaration); - void print(std::ostream &Out, unsigned indent = 0) const; + void add_declaration(sptr declaration); + void print(std::ostream &out, unsigned indent = 0) const; - [[nodiscard]] std::string const &getName() const { return name; } - [[nodiscard]] std::vector> const & - getDeclarations() const { - return declarations; + [[nodiscard]] std::string const &get_name() const { return name_; } + [[nodiscard]] std::vector> const & + get_declarations() const { + return declarations_; } private: - KOREModule(std::string Name) - : name(std::move(Name)) { } + kore_module(std::string name) + : name_(std::move(name)) { } }; -// KOREDefinition -class KOREDefinition { +// kore_definition +class kore_definition { public: // Symbol table types - using KOREModuleMapType = std::map; + using kore_moduleMapType = std::map; - using KORESortConstructorMapType = std::map; + using kore_sortConstructorMapType + = std::map; - using KORESymbolMapType = std::map; + using kore_symbolMapType = std::map; - using KORESymbolStringMapType = std::map; + using kore_symbolStringMapType = std::map; - using KORESortVariableMapType = std::map; + using kore_sort_variableMapType = std::map; - using KOREVariableMapType = std::map; + using kore_variableMapType = std::map; - using KORECompositeSortDeclarationMapType - = std::map; - using KORECompositeSortMapType = std::map>; + using kore_composite_sortDeclarationMapType + = std::map; + using kore_composite_sortMapType + = std::map>; - using KORESymbolDeclarationMapType - = std::map; - using KOREAliasDeclarationMapType - = std::map; + using kore_symbol_declarationMapType + = std::map; + using kore_alias_declarationMapType + = std::map; - using KOREAxiomMapType = std::map; + using KOREAxiomMapType = std::map; private: // Symbol tables - KORESortConstructorMapType objectSortConstructors; - KORESymbolMapType objectSymbols; - KORESymbolStringMapType allObjectSymbols; - KORESortVariableMapType objectSortVariables; - KOREVariableMapType objectVariables; - KOREModuleMapType moduleNames; - KORECompositeSortDeclarationMapType sortDeclarations; - KORESymbolDeclarationMapType symbolDeclarations; - KOREAliasDeclarationMapType aliasDeclarations; - KORECompositeSortMapType hookedSorts; - KORESymbolStringMapType freshFunctions; - KOREAxiomMapType ordinals; - - std::vector> modules; + kore_sortConstructorMapType object_sort_constructors_; + kore_symbolMapType object_symbols_; + kore_symbolStringMapType all_object_symbols_; + kore_sort_variableMapType object_sort_variables_; + kore_variableMapType object_variables_; + kore_moduleMapType module_names_; + kore_composite_sortDeclarationMapType sort_declarations_; + kore_symbol_declarationMapType symbol_declarations_; + kore_alias_declarationMapType alias_declarations_; + kore_composite_sortMapType hooked_sorts_; + kore_symbolStringMapType fresh_functions_; + KOREAxiomMapType ordinals_; + + std::vector> modules_; attribute_set attributes_; /* an automatically computed list of all the axioms in the definition */ - std::list axioms; + std::list axioms_; - KORESymbol *injSymbol{}; + kore_symbol *inj_symbol_{}; /* * Insert symbols into this definition that have knowable labels, but cannot * be directly referenced in user code: * - rawTerm(KItem) for serializing non-symbol backend terms */ - void insertReservedSymbols(); + void insert_reserved_symbols(); public: - static ptr Create() { - return std::make_unique(); + static ptr create() { + return std::make_unique(); } /* Preprocesses the definition and prepares it for translation to llvm. This performs the following tasks: * removes axioms for which isRequired() returns false - * sets the arguments field for each KORESymbol to the actual instantiated + * sets the arguments field for each kore_symbol to the actual instantiated sort arguments of the symbol (rather than just their polymorphic parameters - * sets the tag and layout fields on all the KORESymbols declared by the + * sets the tag and layout fields on all the kore_symbols declared by the user in the definition. */ void preprocess(); attribute_set &attributes() { return attributes_; } [[nodiscard]] attribute_set const &attributes() const { return attributes_; } - void addModule(sptr Module); - void print(std::ostream &Out, unsigned indent = 0) const; + void add_module(sptr module); + void print(std::ostream &out, unsigned indent = 0) const; /* * Return the set of sorts that are hooked to a particular hook name. @@ -929,7 +952,7 @@ class KOREDefinition { * well. */ [[nodiscard]] std::unordered_set - getSortsHookedTo(std::string const &hookName) const; + get_sorts_hooked_to(std::string const &hook_name) const; /* * Build this definition's subsort relation from axioms that have the @@ -939,7 +962,7 @@ class KOREDefinition { * * S |-> {T . S is a subsort of T} */ - [[nodiscard]] SubsortMap getSubsorts() const; + [[nodiscard]] SubsortMap get_subsorts() const; /* * Build this definition's overload relation from axioms that have the @@ -949,49 +972,50 @@ class KOREDefinition { * * P |-> {Q . P is a more specific overload of Q} */ - [[nodiscard]] SymbolMap getOverloads() const; + [[nodiscard]] SymbolMap get_overloads() const; - [[nodiscard]] std::vector> const &getModules() const { - return modules; + [[nodiscard]] std::vector> const &get_modules() const { + return modules_; } - [[nodiscard]] KORECompositeSortDeclarationMapType const & - getSortDeclarations() const { - return sortDeclarations; + [[nodiscard]] kore_composite_sortDeclarationMapType const & + get_sort_declarations() const { + return sort_declarations_; } - [[nodiscard]] KORESymbolDeclarationMapType const & - getSymbolDeclarations() const { - return symbolDeclarations; + [[nodiscard]] kore_symbol_declarationMapType const & + get_symbol_declarations() const { + return symbol_declarations_; } - [[nodiscard]] KOREAliasDeclarationMapType const & - getAliasDeclarations() const { - return aliasDeclarations; + [[nodiscard]] kore_alias_declarationMapType const & + get_alias_declarations() const { + return alias_declarations_; } - [[nodiscard]] KORESymbolMapType const &getSymbols() const { - return objectSymbols; + [[nodiscard]] kore_symbolMapType const &get_symbols() const { + return object_symbols_; } - [[nodiscard]] KORESymbolStringMapType const &getAllSymbols() const { - return allObjectSymbols; + [[nodiscard]] kore_symbolStringMapType const &get_all_symbols() const { + return all_object_symbols_; } - [[nodiscard]] KORECompositeSortMapType getHookedSorts() const { - return hookedSorts; + [[nodiscard]] kore_composite_sortMapType get_hooked_sorts() const { + return hooked_sorts_; } - [[nodiscard]] std::list const &getAxioms() const { - return axioms; + [[nodiscard]] std::list const &get_axioms() const { + return axioms_; } - [[nodiscard]] KOREAxiomDeclaration *getAxiomByOrdinal(size_t ordinal) const { - return ordinals.at(ordinal); + [[nodiscard]] kore_axiom_declaration * + get_axiom_by_ordinal(size_t ordinal) const { + return ordinals_.at(ordinal); } - [[nodiscard]] KORESymbolStringMapType const &getFreshFunctions() const { - return freshFunctions; + [[nodiscard]] kore_symbolStringMapType const &get_fresh_functions() const { + return fresh_functions_; } - KORESymbol *getInjSymbol() { return injSymbol; } + kore_symbol *get_inj_symbol() { return inj_symbol_; } }; -void readMultimap( - std::string const &, KORESymbolDeclaration *, +void read_multimap( + std::string const &, kore_symbol_declaration *, std::map> &, attribute_set::key); -sptr stripRawTerm(sptr const &term); +sptr strip_raw_term(sptr const &term); namespace detail { @@ -1004,13 +1028,13 @@ struct header_byte_t; static constexpr char value = V; \ } -VARIANT_HEADER(KORECompositePattern, 0x4); -VARIANT_HEADER(KOREStringPattern, 0x5); -VARIANT_HEADER(KORECompositeSort, 0x6); -VARIANT_HEADER(KORESortVariable, 0x7); -VARIANT_HEADER(KORESymbol, 0x8); -VARIANT_HEADER(KOREVariablePattern, 0x9); -VARIANT_HEADER(KOREVariable, 0xD); +VARIANT_HEADER(kore_composite_pattern, 0x4); +VARIANT_HEADER(kore_string_pattern, 0x5); +VARIANT_HEADER(kore_composite_sort, 0x6); +VARIANT_HEADER(kore_sort_variable, 0x7); +VARIANT_HEADER(kore_symbol, 0x8); +VARIANT_HEADER(kore_variable_pattern, 0x9); +VARIANT_HEADER(kore_variable, 0xD); #undef VARIANT_HEADER diff --git a/include/kllvm/ast/attribute_set.h b/include/kllvm/ast/attribute_set.h index 5421c2a77..82739c722 100644 --- a/include/kllvm/ast/attribute_set.h +++ b/include/kllvm/ast/attribute_set.h @@ -8,7 +8,7 @@ namespace kllvm { -class KORECompositePattern; +class kore_composite_pattern; /** * Type-safe wrapper around a set of KORE attribute patterns. @@ -29,46 +29,46 @@ class KORECompositePattern; */ class attribute_set { public: - using storage_t - = std::unordered_map>; + using storage_t = std::unordered_map< + std::string, std::shared_ptr>; enum class key { - alias, - alias_rec, - anywhere, - assoc, - binder, - bracket, - ceil, - colors, - comm, - concat, - constructor, - element, - format, - fresh_generator, - function, - functional, - hook, - idem, - label, - left, - location, - macro, - macro_rec, - nat, - non_executable, - priorities, - priority, - right, - simplification, - sort_injection, - source, - subsort, - symbol_overload, - terminals, - total, - unit, + Alias, + AliasRec, + Anywhere, + Assoc, + Binder, + Bracket, + Ceil, + Colors, + Comm, + Concat, + Constructor, + Element, + Format, + FreshGenerator, + Function, + Functional, + Hook, + Idem, + Label, + Left, + Location, + Macro, + MacroRec, + Nat, + NonExecutable, + Priorities, + Priority, + Right, + Simplification, + SortInjection, + Source, + Subsort, + SymbolOverload, + Terminals, + Total, + Unit, }; attribute_set() = default; @@ -83,7 +83,7 @@ class attribute_set { * unknown attribute), `std::nullopt` is returned. */ std::optional - add(std::shared_ptr att); + add(std::shared_ptr att); /** * Returns true if there is any attribute with the given key; the arguments of @@ -97,7 +97,7 @@ class attribute_set { * This lookup is unchecked; use `.contains(k)` first if the attribute may not * be present. */ - [[nodiscard]] std::shared_ptr const &get(key k) const; + [[nodiscard]] std::shared_ptr const &get(key k) const; /** * Look up an attribute with the specified key that has the form: diff --git a/include/kllvm/ast/pattern_matching.h b/include/kllvm/ast/pattern_matching.h index 133159613..03f1ee5a9 100644 --- a/include/kllvm/ast/pattern_matching.h +++ b/include/kllvm/ast/pattern_matching.h @@ -158,11 +158,11 @@ struct pattern_forwarder { * * All valid lens types must supply an implementation of: * - * match_result match(std::shared_ptr const&) const + * match_result match(std::shared_ptr const&) const */ struct match_result { bool matches; - std::shared_ptr subject; + std::shared_ptr subject; }; /** @@ -171,7 +171,7 @@ struct match_result { class any_ { public: [[nodiscard]] static match_result - match(std::shared_ptr const &term) { + match(std::shared_ptr const &term) { return {true, nullptr}; } }; @@ -196,7 +196,7 @@ class subject { } [[nodiscard]] match_result - match(std::shared_ptr const &term) const { + match(std::shared_ptr const &term) const { auto inner_result = inner_.match(term); if (inner_result.matches) { @@ -238,14 +238,15 @@ class pattern { * is the only such lens. */ [[nodiscard]] match_result - match(std::shared_ptr const &term) const { - if (auto composite = std::dynamic_pointer_cast(term); - composite && composite->getArguments().size() == arity() - && composite->getConstructor()->getName() == constructor_) { + match(std::shared_ptr const &term) const { + if (auto composite + = std::dynamic_pointer_cast(term); + composite && composite->get_arguments().size() == arity() + && composite->get_constructor()->get_name() == constructor_) { auto results = std::vector{}; detail::enumerate(children_, [&](auto idx, auto const &subpattern) { - results.push_back(subpattern.match(composite->getArguments()[idx])); + results.push_back(subpattern.match(composite->get_arguments()[idx])); }); auto all_match @@ -282,7 +283,7 @@ class pattern { * * The supplied callable should have a signature compatible with: * - * Result (std::shared_ptr const&) + * Result (std::shared_ptr const&) * * where `Result` is a specialisation of `std::optional`. This is required to * allow the supplied callable to _not return a mapped value_ for a subset of @@ -306,7 +307,7 @@ class map { * transformed value of type Result rather than a pattern. */ [[nodiscard]] std::pair - match(std::shared_ptr const &term) const { + match(std::shared_ptr const &term) const { auto [match, subject] = pattern_.match(term); if (!match) { @@ -318,15 +319,15 @@ class map { private: Pattern pattern_; - std::function const &)> func_; + std::function const &)> func_; }; template map(Pattern, Func) -> map< - Pattern, std::invoke_result_t const &>>; + Pattern, std::invoke_result_t const &>>; template -map(Pattern) -> map>>; +map(Pattern) -> map>>; /** * Helper function to allow the precisely deduced type of a `map` constructed @@ -361,7 +362,7 @@ class match_first { : maps_(make_map(first), make_map(rest)...) { } [[nodiscard]] std::pair - match(std::shared_ptr const &term) const { + match(std::shared_ptr const &term) const { result_t result = std::nullopt; bool any = false; diff --git a/include/kllvm/binary/ProofTraceParser.h b/include/kllvm/binary/ProofTraceParser.h index 7d46998e4..c36c78d9b 100644 --- a/include/kllvm/binary/ProofTraceParser.h +++ b/include/kllvm/binary/ProofTraceParser.h @@ -35,216 +35,233 @@ constexpr uint64_t rule_event_sentinel = detail::word(0x22); constexpr uint64_t side_condition_event_sentinel = detail::word(0xEE); constexpr uint64_t side_condition_end_sentinel = detail::word(0x33); -class LLVMStepEvent : public std::enable_shared_from_this { +class llvm_step_event : public std::enable_shared_from_this { public: - virtual void print(std::ostream &Out, unsigned indent = 0U) const = 0; - virtual ~LLVMStepEvent() = default; + virtual void print(std::ostream &out, unsigned indent = 0U) const = 0; + virtual ~llvm_step_event() = default; }; -class LLVMRewriteEvent : public LLVMStepEvent { +class llvm_rewrite_event : public llvm_step_event { public: using substitution_t - = std::map, uint64_t>>; + = std::map, uint64_t>>; private: - uint64_t ruleOrdinal; - substitution_t substitution{}; + uint64_t rule_ordinal_; + substitution_t substitution_{}; protected: - void printSubstitution(std::ostream &Out, unsigned indent = 0U) const; + void print_substitution(std::ostream &out, unsigned indent = 0U) const; public: - LLVMRewriteEvent(uint64_t _ruleOrdinal) - : ruleOrdinal(_ruleOrdinal) { } + llvm_rewrite_event(uint64_t rule_ordinal) + : rule_ordinal_(rule_ordinal) { } - [[nodiscard]] uint64_t getRuleOrdinal() const { return ruleOrdinal; } - [[nodiscard]] substitution_t const &getSubstitution() const { - return substitution; + [[nodiscard]] uint64_t get_rule_ordinal() const { return rule_ordinal_; } + [[nodiscard]] substitution_t const &get_substitution() const { + return substitution_; } - void addSubstitution( - std::string const &name, sptr const &term, + void add_substitution( + std::string const &name, sptr const &term, uint64_t pattern_len) { - substitution.insert( + substitution_.insert( std::make_pair(name, std::make_pair(term, pattern_len))); } - ~LLVMRewriteEvent() override = default; + ~llvm_rewrite_event() override = default; }; -class LLVMRuleEvent : public LLVMRewriteEvent { +class llvm_rule_event : public llvm_rewrite_event { private: - LLVMRuleEvent(uint64_t _ruleOrdinal) - : LLVMRewriteEvent(_ruleOrdinal) { } + llvm_rule_event(uint64_t rule_ordinal) + : llvm_rewrite_event(rule_ordinal) { } public: - static sptr Create(uint64_t _ruleOrdinal) { - return sptr(new LLVMRuleEvent(_ruleOrdinal)); + static sptr create(uint64_t rule_ordinal) { + return sptr(new llvm_rule_event(rule_ordinal)); } - void print(std::ostream &Out, unsigned indent = 0U) const override; + void print(std::ostream &out, unsigned indent = 0U) const override; }; -class LLVMSideConditionEvent : public LLVMRewriteEvent { +class llvm_side_condition_event : public llvm_rewrite_event { private: - LLVMSideConditionEvent(uint64_t _ruleOrdinal) - : LLVMRewriteEvent(_ruleOrdinal) { } + llvm_side_condition_event(uint64_t rule_ordinal) + : llvm_rewrite_event(rule_ordinal) { } public: - static sptr Create(uint64_t _ruleOrdinal) { - return sptr( - new LLVMSideConditionEvent(_ruleOrdinal)); + static sptr create(uint64_t rule_ordinal) { + return sptr( + new llvm_side_condition_event(rule_ordinal)); } - void print(std::ostream &Out, unsigned indent = 0U) const override; + void print(std::ostream &out, unsigned indent = 0U) const override; }; -class LLVMSideConditionEndEvent : public LLVMStepEvent { +class llvm_side_condition_end_event : public llvm_step_event { private: - uint64_t ruleOrdinal; - sptr korePattern{}; - uint64_t patternLength{0U}; + uint64_t rule_ordinal_; + sptr kore_pattern_{}; + uint64_t pattern_length_{0U}; - LLVMSideConditionEndEvent(uint64_t _ruleOrdinal) - : ruleOrdinal(_ruleOrdinal) - , korePattern(nullptr) { } + llvm_side_condition_end_event(uint64_t rule_ordinal) + : rule_ordinal_(rule_ordinal) + , kore_pattern_(nullptr) { } public: - static sptr Create(uint64_t _ruleOrdinal) { - return sptr( - new LLVMSideConditionEndEvent(_ruleOrdinal)); + static sptr create(uint64_t rule_ordinal) { + return sptr( + new llvm_side_condition_end_event(rule_ordinal)); } - [[nodiscard]] uint64_t getRuleOrdinal() const { return ruleOrdinal; } - [[nodiscard]] sptr getKOREPattern() const { return korePattern; } - [[nodiscard]] uint64_t getPatternLength() const { return patternLength; } - void setKOREPattern(sptr _korePattern, uint64_t _patternLength) { - korePattern = std::move(_korePattern); - patternLength = _patternLength; + [[nodiscard]] uint64_t get_rule_ordinal() const { return rule_ordinal_; } + [[nodiscard]] sptr getkore_pattern() const { + return kore_pattern_; + } + [[nodiscard]] uint64_t get_pattern_length() const { return pattern_length_; } + void + setkore_pattern(sptr kore_pattern, uint64_t pattern_length) { + kore_pattern_ = std::move(kore_pattern); + pattern_length_ = pattern_length; } - void print(std::ostream &Out, unsigned indent = 0U) const override; + void print(std::ostream &out, unsigned indent = 0U) const override; }; -class LLVMEvent; +class llvm_event; -class LLVMFunctionEvent : public LLVMStepEvent { +class llvm_function_event : public llvm_step_event { private: - std::string name; - std::string relativePosition; - std::vector arguments; + std::string name_; + std::string relative_position_; + std::vector arguments_; - LLVMFunctionEvent(std::string _name, std::string _relativePosition); + llvm_function_event(std::string name, std::string relative_position); public: - static sptr - Create(std::string const &_name, std::string const &_relativePosition) { - return sptr( - new LLVMFunctionEvent(_name, _relativePosition)); + static sptr + create(std::string const &name, std::string const &relative_position) { + return sptr( + new llvm_function_event(name, relative_position)); } - [[nodiscard]] std::string const &getName() const { return name; } - [[nodiscard]] std::string const &getRelativePosition() const { - return relativePosition; + [[nodiscard]] std::string const &get_name() const { return name_; } + [[nodiscard]] std::string const &get_relative_position() const { + return relative_position_; } - [[nodiscard]] std::vector const &getArguments() const; + [[nodiscard]] std::vector const &get_arguments() const; - void addArgument(LLVMEvent const &argument); + void add_argument(llvm_event const &argument); - void print(std::ostream &Out, unsigned indent = 0U) const override; + void print(std::ostream &out, unsigned indent = 0U) const override; }; -class LLVMHookEvent : public LLVMStepEvent { +class llvm_hook_event : public llvm_step_event { private: - std::string name; - std::string relativePosition; - std::vector arguments; - sptr korePattern; - uint64_t patternLength{0U}; + std::string name_; + std::string relative_position_; + std::vector arguments_; + sptr kore_pattern_; + uint64_t pattern_length_{0U}; - LLVMHookEvent(std::string _name, std::string _relativePosition); + llvm_hook_event(std::string name, std::string relative_position); public: - static sptr - Create(std::string const &_name, std::string const &_relativePosition) { - return sptr(new LLVMHookEvent(_name, _relativePosition)); + static sptr + create(std::string const &name, std::string const &relative_position) { + return sptr(new llvm_hook_event(name, relative_position)); } - [[nodiscard]] std::string const &getName() const { return name; } - [[nodiscard]] std::string const &getRelativePosition() const { - return relativePosition; + [[nodiscard]] std::string const &get_name() const { return name_; } + [[nodiscard]] std::string const &get_relative_position() const { + return relative_position_; + } + [[nodiscard]] std::vector const &get_arguments() const { + return arguments_; } - [[nodiscard]] std::vector const &getArguments() const { - return arguments; + [[nodiscard]] sptr getkore_pattern() const { + return kore_pattern_; } - [[nodiscard]] sptr getKOREPattern() const { return korePattern; } - [[nodiscard]] uint64_t getPatternLength() const { return patternLength; } - void setKOREPattern(sptr _korePattern, uint64_t _patternLength) { - korePattern = std::move(_korePattern); - patternLength = _patternLength; + [[nodiscard]] uint64_t get_pattern_length() const { return pattern_length_; } + void + setkore_pattern(sptr kore_pattern, uint64_t pattern_length) { + kore_pattern_ = std::move(kore_pattern); + pattern_length_ = pattern_length; } - void addArgument(LLVMEvent const &argument); + void add_argument(llvm_event const &argument); - void print(std::ostream &Out, unsigned indent = 0U) const override; + void print(std::ostream &out, unsigned indent = 0U) const override; }; -class LLVMEvent { +class llvm_event { private: - bool isStepEvent{}; - sptr stepEvent{}; - sptr korePattern{}; - uint64_t patternLength{}; + bool is_step_event_{}; + sptr step_event_{}; + sptr kore_pattern_{}; + uint64_t pattern_length_{}; public: - [[nodiscard]] bool isStep() const { return isStepEvent; } - [[nodiscard]] bool isPattern() const { return !isStep(); } - [[nodiscard]] sptr getStepEvent() const { return stepEvent; } - [[nodiscard]] sptr getKOREPattern() const { return korePattern; } - [[nodiscard]] uint64_t getPatternLength() const { return patternLength; } - void setStepEvent(sptr _stepEvent) { - isStepEvent = true; - stepEvent = std::move(_stepEvent); - } - void setKOREPattern(sptr _korePattern, uint64_t _patternLength) { - isStepEvent = false; - korePattern = std::move(_korePattern); - patternLength = _patternLength; - } - void print(std::ostream &Out, bool isArg, unsigned indent = 0U) const; + [[nodiscard]] bool is_step() const { return is_step_event_; } + [[nodiscard]] bool is_pattern() const { return !is_step(); } + [[nodiscard]] sptr get_step_event() const { + return step_event_; + } + [[nodiscard]] sptr getkore_pattern() const { + return kore_pattern_; + } + [[nodiscard]] uint64_t get_pattern_length() const { return pattern_length_; } + void set_step_event(sptr step_event) { + is_step_event_ = true; + step_event_ = std::move(step_event); + } + void + setkore_pattern(sptr kore_pattern, uint64_t pattern_length) { + is_step_event_ = false; + kore_pattern_ = std::move(kore_pattern); + pattern_length_ = pattern_length; + } + void print(std::ostream &out, bool is_arg, unsigned indent = 0U) const; }; -class LLVMRewriteTrace { +class llvm_rewrite_trace { private: - uint32_t version{}; - std::vector preTrace{}; - LLVMEvent initialConfig; - std::vector trace{}; + uint32_t version_{}; + std::vector pre_trace_{}; + llvm_event initial_config_; + std::vector trace_{}; public: - [[nodiscard]] uint32_t getVersion() const { return version; } - [[nodiscard]] std::vector const &getPreTrace() const { - return preTrace; + [[nodiscard]] uint32_t get_version() const { return version_; } + [[nodiscard]] std::vector const &get_pre_trace() const { + return pre_trace_; + } + [[nodiscard]] llvm_event get_initial_config() const { + return initial_config_; } - [[nodiscard]] LLVMEvent getInitialConfig() const { return initialConfig; } - [[nodiscard]] std::vector const &getTrace() const { return trace; } - void setVersion(uint32_t _version) { version = _version; } - void setInitialConfig(LLVMEvent _initialConfig) { - initialConfig = std::move(_initialConfig); + [[nodiscard]] std::vector const &get_trace() const { + return trace_; + } + void set_version(uint32_t v) { version_ = v; } + void set_initial_config(llvm_event initial_config) { + initial_config_ = std::move(initial_config); } - void addPreTraceEvent(LLVMEvent const &event) { preTrace.push_back(event); } - void addTraceEvent(LLVMEvent const &event) { trace.push_back(event); } + void add_pre_trace_event(llvm_event const &event) { + pre_trace_.push_back(event); + } + void add_trace_event(llvm_event const &event) { trace_.push_back(event); } - void print(std::ostream &Out, unsigned indent = 0U) const; + void print(std::ostream &out, unsigned indent = 0U) const; }; -class ProofTraceParser { +class proof_trace_parser { public: - static constexpr uint32_t expectedVersion = 5U; + static constexpr uint32_t expected_version = 5U; private: - bool verbose; + bool verbose_; // Caller needs to check that there are at least 8 bytes remaining in the // stream before peeking @@ -306,7 +323,7 @@ class ProofTraceParser { } template - sptr parse_kore_term(It &ptr, It end, uint64_t &pattern_len) { + sptr parse_kore_term(It &ptr, It end, uint64_t &pattern_len) { if (std::distance(ptr, end) < 11U) { return nullptr; } @@ -359,7 +376,7 @@ class ProofTraceParser { return false; } - if (version != expectedVersion) { + if (version != expected_version) { return false; } @@ -367,7 +384,7 @@ class ProofTraceParser { } template - bool parse_variable(It &ptr, It end, sptr const &event) { + bool parse_variable(It &ptr, It end, sptr const &event) { std::string name; if (!parse_name(ptr, end, name)) { return false; @@ -379,13 +396,13 @@ class ProofTraceParser { return false; } - event->addSubstitution(name, kore_term, pattern_len); + event->add_substitution(name, kore_term, pattern_len); return check_word(ptr, end, kore_end_sentinel); } template - sptr parse_hook(It &ptr, It end) { + sptr parse_hook(It &ptr, It end) { if (!check_word(ptr, end, hook_event_sentinel)) { return nullptr; } @@ -400,15 +417,15 @@ class ProofTraceParser { return nullptr; } - auto event = LLVMHookEvent::Create(name, location); + auto event = llvm_hook_event::create(name, location); while (std::distance(ptr, end) < 8U || peek_word(ptr) != hook_result_sentinel) { - LLVMEvent argument; + llvm_event argument; if (!parse_argument(ptr, end, argument)) { return nullptr; } - event->addArgument(argument); + event->add_argument(argument); } if (!check_word(ptr, end, hook_result_sentinel)) { @@ -420,13 +437,13 @@ class ProofTraceParser { if (!kore_term) { return nullptr; } - event->setKOREPattern(kore_term, pattern_len); + event->setkore_pattern(kore_term, pattern_len); return event; } template - sptr parse_function(It &ptr, It end) { + sptr parse_function(It &ptr, It end) { if (!check_word(ptr, end, function_event_sentinel)) { return nullptr; } @@ -441,15 +458,15 @@ class ProofTraceParser { return nullptr; } - auto event = LLVMFunctionEvent::Create(name, location); + auto event = llvm_function_event::create(name, location); while (std::distance(ptr, end) < 8U || peek_word(ptr) != function_end_sentinel) { - LLVMEvent argument; + llvm_event argument; if (!parse_argument(ptr, end, argument)) { return nullptr; } - event->addArgument(argument); + event->add_argument(argument); } if (!check_word(ptr, end, function_end_sentinel)) { @@ -460,7 +477,7 @@ class ProofTraceParser { } template - sptr parse_config(It &ptr, It end, uint64_t &pattern_len) { + sptr parse_config(It &ptr, It end, uint64_t &pattern_len) { if (!check_word(ptr, end, config_sentinel)) { return nullptr; } @@ -478,7 +495,7 @@ class ProofTraceParser { } template - sptr parse_rule(It &ptr, It end) { + sptr parse_rule(It &ptr, It end) { if (!check_word(ptr, end, rule_event_sentinel)) { return nullptr; } @@ -493,7 +510,7 @@ class ProofTraceParser { return nullptr; } - auto event = LLVMRuleEvent::Create(ordinal); + auto event = llvm_rule_event::create(ordinal); for (auto i = 0; i < arity; i++) { if (!parse_variable(ptr, end, event)) { @@ -505,7 +522,7 @@ class ProofTraceParser { } template - sptr parse_side_condition(It &ptr, It end) { + sptr parse_side_condition(It &ptr, It end) { if (!check_word(ptr, end, side_condition_event_sentinel)) { return nullptr; } @@ -520,7 +537,7 @@ class ProofTraceParser { return nullptr; } - auto event = LLVMSideConditionEvent::Create(ordinal); + auto event = llvm_side_condition_event::create(ordinal); for (auto i = 0; i < arity; i++) { if (!parse_variable(ptr, end, event)) { @@ -532,7 +549,8 @@ class ProofTraceParser { } template - sptr parse_side_condition_end(It &ptr, It end) { + sptr + parse_side_condition_end(It &ptr, It end) { if (!check_word(ptr, end, side_condition_end_sentinel)) { return nullptr; } @@ -542,14 +560,14 @@ class ProofTraceParser { return nullptr; } - auto event = LLVMSideConditionEndEvent::Create(ordinal); + auto event = llvm_side_condition_end_event::create(ordinal); uint64_t pattern_len = 0; auto kore_term = parse_kore_term(ptr, end, pattern_len); if (!kore_term) { return nullptr; } - event->setKOREPattern(kore_term, pattern_len); + event->setkore_pattern(kore_term, pattern_len); if (!check_word(ptr, end, kore_end_sentinel)) { return nullptr; @@ -559,14 +577,14 @@ class ProofTraceParser { } template - bool parse_argument(It &ptr, It end, LLVMEvent &event) { + bool parse_argument(It &ptr, It end, llvm_event &event) { if (std::distance(ptr, end) >= 1U && detail::peek(ptr) == '\x7F') { uint64_t pattern_len = 0; auto kore_term = parse_kore_term(ptr, end, pattern_len); if (!kore_term) { return false; } - event.setKOREPattern(kore_term, pattern_len); + event.setkore_pattern(kore_term, pattern_len); return true; } @@ -582,7 +600,7 @@ class ProofTraceParser { if (!hook_event) { return false; } - event.setStepEvent(hook_event); + event.set_step_event(hook_event); return true; } @@ -591,7 +609,7 @@ class ProofTraceParser { if (!function_event) { return false; } - event.setStepEvent(function_event); + event.set_step_event(function_event); return true; } @@ -600,7 +618,7 @@ class ProofTraceParser { if (!rule_event) { return false; } - event.setStepEvent(rule_event); + event.set_step_event(rule_event); return true; } @@ -609,7 +627,7 @@ class ProofTraceParser { } template - sptr parse_step_event(It &ptr, It end) { + sptr parse_step_event(It &ptr, It end) { if (std::distance(ptr, end) < 8U) { return nullptr; } @@ -631,7 +649,7 @@ class ProofTraceParser { } template - bool parse_event(It &ptr, It end, LLVMEvent &event) { + bool parse_event(It &ptr, It end, llvm_event &event) { if (std::distance(ptr, end) < 8U) { return false; } @@ -642,32 +660,32 @@ class ProofTraceParser { if (!config) { return false; } - event.setKOREPattern(config, pattern_len); + event.setkore_pattern(config, pattern_len); } else { auto step_event = parse_step_event(ptr, end); if (!step_event) { return false; } - event.setStepEvent(step_event); + event.set_step_event(step_event); } return true; } template - bool parse_trace(It &ptr, It end, LLVMRewriteTrace &trace) { + bool parse_trace(It &ptr, It end, llvm_rewrite_trace &trace) { uint32_t version = 0; if (!parse_header(ptr, end, version)) { return false; } - trace.setVersion(version); + trace.set_version(version); while (std::distance(ptr, end) >= 8U && peek_word(ptr) != config_sentinel) { - LLVMEvent event; + llvm_event event; if (!parse_event(ptr, end, event)) { return false; } - trace.addPreTraceEvent(event); + trace.add_pre_trace_event(event); } uint64_t pattern_len = 0; @@ -675,27 +693,27 @@ class ProofTraceParser { if (!config) { return false; } - LLVMEvent config_event; - config_event.setKOREPattern(config, pattern_len); - trace.setInitialConfig(config_event); + llvm_event config_event; + config_event.setkore_pattern(config, pattern_len); + trace.set_initial_config(config_event); while (ptr != end) { - LLVMEvent event; + llvm_event event; if (!parse_event(ptr, end, event)) { return false; } - trace.addTraceEvent(event); + trace.add_trace_event(event); } return true; } public: - ProofTraceParser(bool _verbose); + proof_trace_parser(bool verbose); - std::optional + std::optional parse_proof_trace_from_file(std::string const &filename); - std::optional parse_proof_trace(std::string const &data); + std::optional parse_proof_trace(std::string const &data); }; } // namespace kllvm diff --git a/include/kllvm/binary/deserializer.h b/include/kllvm/binary/deserializer.h index aebece8ad..eaf0e9799 100644 --- a/include/kllvm/binary/deserializer.h +++ b/include/kllvm/binary/deserializer.h @@ -127,27 +127,27 @@ std::string read_string(It &ptr, It end, binary_version version) { } template -sptr read_variable(It &ptr, It end, binary_version version) { - if (peek(ptr) == header_byte) { +sptr read_variable(It &ptr, It end, binary_version version) { + if (peek(ptr) == header_byte) { ++ptr; - return KOREVariable::Create(read_string(ptr, end, version)); + return kore_variable::create(read_string(ptr, end, version)); } return nullptr; } template -ptr read_symbol( - It &ptr, It end, std::vector> &sort_stack, +ptr read_symbol( + It &ptr, It end, std::vector> &sort_stack, binary_version version) { auto arity = read_length(ptr, end, version, 2); auto name = read_string(ptr, end, version); - auto symbol = KORESymbol::Create(name); + auto symbol = kore_symbol::create(name); auto start_idx = sort_stack.size() - arity; for (auto i = start_idx; i < sort_stack.size(); ++i) { - symbol->addFormalArgument(sort_stack[i]); + symbol->add_formal_argument(sort_stack[i]); } for (auto i = 0; i < arity; ++i) { @@ -158,14 +158,14 @@ ptr read_symbol( } template -sptr read_composite_sort( - It &ptr, It end, std::vector> &sort_stack, +sptr read_composite_sort( + It &ptr, It end, std::vector> &sort_stack, binary_version version) { auto arity = read_length(ptr, end, version, 2); - auto new_sort = KORECompositeSort::Create(read_string(ptr, end, version)); + auto new_sort = kore_composite_sort::create(read_string(ptr, end, version)); for (auto i = sort_stack.size() - arity; i < sort_stack.size(); ++i) { - new_sort->addArgument(sort_stack[i]); + new_sort->add_argument(sort_stack[i]); } for (auto i = 0; i < arity; ++i) { @@ -176,28 +176,28 @@ sptr read_composite_sort( } template -sptr read(It &ptr, It end, binary_version version) { - auto term_stack = std::vector>{}; - auto sort_stack = std::vector>{}; - auto symbol = kllvm::ptr{}; +sptr read(It &ptr, It end, binary_version version) { + auto term_stack = std::vector>{}; + auto sort_stack = std::vector>{}; + auto symbol = kllvm::ptr{}; while (ptr < end) { switch (peek(ptr)) { - case header_byte: + case header_byte: ++ptr; term_stack.push_back( - KOREStringPattern::Create(read_string(ptr, end, version))); + kore_string_pattern::create(read_string(ptr, end, version))); break; - case header_byte: { + case header_byte: { ++ptr; - auto new_pattern = KORECompositePattern::Create(std::move(symbol)); + auto new_pattern = kore_composite_pattern::create(std::move(symbol)); symbol = nullptr; auto arity = read_length(ptr, end, version, 2); for (auto i = term_stack.size() - arity; i < term_stack.size(); ++i) { - new_pattern->addArgument(term_stack[i]); + new_pattern->add_argument(term_stack[i]); } for (auto i = 0; i < arity; ++i) { @@ -207,31 +207,32 @@ sptr read(It &ptr, It end, binary_version version) { break; } - case header_byte: { + case header_byte: { ++ptr; auto name = read_variable(ptr, end, version); auto sort = sort_stack.back(); sort_stack.pop_back(); - term_stack.push_back(KOREVariablePattern::Create(name->getName(), sort)); + term_stack.push_back( + kore_variable_pattern::create(name->get_name(), sort)); break; } - case header_byte: { + case header_byte: { ++ptr; symbol = read_symbol(ptr, end, sort_stack, version); break; } - case header_byte: { + case header_byte: { ++ptr; auto name = read_string(ptr, end, version); - sort_stack.push_back(KORESortVariable::Create(name)); + sort_stack.push_back(kore_sort_variable::create(name)); break; } - case header_byte: { + case header_byte: { ++ptr; sort_stack.push_back(read_composite_sort(ptr, end, sort_stack, version)); break; @@ -253,8 +254,8 @@ sptr read(It &ptr, It end, binary_version version) { std::string file_contents(std::string const &fn, int max_bytes = -1); template -sptr -deserialize_pattern(It begin, It end, bool strip_raw_term = true) { +sptr +deserialize_pattern(It begin, It end, bool should_strip_raw_term = true) { // Try to parse the file even if the magic header isn't correct; by the time // we're here we already know that we're trying to parse a binary KORE file. // The header itself gets used by the application when detecting binary vs. @@ -272,15 +273,15 @@ deserialize_pattern(It begin, It end, bool strip_raw_term = true) { auto result = detail::read(begin, end, version); - if (strip_raw_term) { - return stripRawTerm(result); + if (should_strip_raw_term) { + return strip_raw_term(result); } return result; } bool has_binary_kore_header(std::string const &filename); -sptr deserialize_pattern(std::string const &filename); +sptr deserialize_pattern(std::string const &filename); } // namespace kllvm diff --git a/include/kllvm/binary/serializer.h b/include/kllvm/binary/serializer.h index b367aa2fa..e94e267a5 100644 --- a/include/kllvm/binary/serializer.h +++ b/include/kllvm/binary/serializer.h @@ -28,10 +28,10 @@ class serializer { public: enum flags { NONE = 0, - DROP_HEADER = 1, - DROP_ARITY = 2, - DROP_BOTH = 3, - NO_INTERN = 4, + DropHeader = 1, + DropArity = 2, + DropBoth = 3, + NoIntern = 4, }; static constexpr auto magic_header = std::array{'\x7f', 'K', 'O', 'R', 'E'}; diff --git a/include/kllvm/bindings/core/core.h b/include/kllvm/bindings/core/core.h index d1f42dc9c..b3b2a7bbd 100644 --- a/include/kllvm/bindings/core/core.h +++ b/include/kllvm/bindings/core/core.h @@ -14,32 +14,32 @@ namespace kllvm::bindings { std::string return_sort_for_label(std::string const &label); -std::shared_ptr make_injection( - std::shared_ptr const &term, - std::shared_ptr const &from, - std::shared_ptr const &to); +std::shared_ptr make_injection( + std::shared_ptr const &term, + std::shared_ptr const &from, + std::shared_ptr const &to); -block *construct_term(std::shared_ptr const &pattern); +block *construct_term(std::shared_ptr const &pattern); -std::shared_ptr term_to_pattern(block *term); +std::shared_ptr term_to_pattern(block *term); bool get_bool(block *term); -bool simplify_to_bool(std::shared_ptr const &pattern); +bool simplify_to_bool(std::shared_ptr const &pattern); block *simplify_to_term( - std::shared_ptr const &pattern, - std::shared_ptr const &sort); + std::shared_ptr const &pattern, + std::shared_ptr const &sort); -std::shared_ptr simplify( - std::shared_ptr const &pattern, - std::shared_ptr const &sort); +std::shared_ptr simplify( + std::shared_ptr const &pattern, + std::shared_ptr const &sort); -bool is_sort_kitem(std::shared_ptr const &sort); -bool is_sort_k(std::shared_ptr const &sort); +bool is_sort_kitem(std::shared_ptr const &sort); +bool is_sort_k(std::shared_ptr const &sort); -std::shared_ptr -evaluate_function(std::shared_ptr const &term); +std::shared_ptr +evaluate_function(std::shared_ptr const &term); } // namespace kllvm::bindings diff --git a/include/kllvm/codegen/CreateStaticTerm.h b/include/kllvm/codegen/CreateStaticTerm.h index 08b0e2c59..b88d801de 100644 --- a/include/kllvm/codegen/CreateStaticTerm.h +++ b/include/kllvm/codegen/CreateStaticTerm.h @@ -12,23 +12,23 @@ namespace kllvm { -class CreateStaticTerm { +class create_static_term { private: - KOREDefinition *Definition; - llvm::Module *Module; - llvm::LLVMContext &Ctx; + kore_definition *definition_; + llvm::Module *module_; + llvm::LLVMContext &ctx_; llvm::Constant * - notInjectionCase(KORECompositePattern *constructor, llvm::Constant *val); + not_injection_case(kore_composite_pattern *constructor, llvm::Constant *val); public: - CreateStaticTerm(KOREDefinition *Definition, llvm::Module *Module) - : Definition(Definition) - , Module(Module) - , Ctx(Module->getContext()) { } + create_static_term(kore_definition *definition, llvm::Module *module) + : definition_(definition) + , module_(module) + , ctx_(module->getContext()) { } - std::pair operator()(KOREPattern *pattern); - llvm::Constant *createToken(ValueType sort, std::string contents); + std::pair operator()(kore_pattern *pattern); + llvm::Constant *create_token(value_type sort, std::string contents); }; } // namespace kllvm diff --git a/include/kllvm/codegen/CreateTerm.h b/include/kllvm/codegen/CreateTerm.h index 182127a24..c764ee765 100644 --- a/include/kllvm/codegen/CreateTerm.h +++ b/include/kllvm/codegen/CreateTerm.h @@ -10,48 +10,50 @@ namespace kllvm { -class CreateTerm { +class create_term { private: - llvm::StringMap &Substitution; - KOREDefinition *Definition; - llvm::BasicBlock *CurrentBlock; - llvm::Module *Module; - llvm::LLVMContext &Ctx; - bool isAnywhereOwise; - std::set staticTerms; + llvm::StringMap &substitution_; + kore_definition *definition_; + llvm::BasicBlock *current_block_; + llvm::Module *module_; + llvm::LLVMContext &ctx_; + bool is_anywhere_owise_; + std::set static_terms_; llvm::Value *alloc_arg( - KORECompositePattern *pattern, int idx, std::string const &locationStack); - llvm::Value *createHook( - KORECompositePattern *hookAtt, KORECompositePattern *pattern, - std::string const &locationStack = "0"); - llvm::Value *createFunctionCall( - std::string const &name, KORECompositePattern *pattern, bool sret, - bool tailcc, std::string const &locationStack = "0"); - llvm::Value *notInjectionCase( - KORECompositePattern *constructor, llvm::Value *val, - std::string const &locationStack = "0"); - bool populateStaticSet(KOREPattern *pattern); - std::pair createAllocation( - KOREPattern *pattern, std::string const &locationStack = "0"); + kore_composite_pattern *pattern, int idx, + std::string const &location_stack); + llvm::Value *create_hook( + kore_composite_pattern *hook_att, kore_composite_pattern *pattern, + std::string const &location_stack = "0"); + llvm::Value *create_function_call( + std::string const &name, kore_composite_pattern *pattern, bool sret, + bool tailcc, std::string const &location_stack = "0"); + llvm::Value *not_injection_case( + kore_composite_pattern *constructor, llvm::Value *val, + std::string const &location_stack = "0"); + bool populate_static_set(kore_pattern *pattern); + std::pair create_allocation( + kore_pattern *pattern, std::string const &location_stack = "0"); public: - CreateTerm( - llvm::StringMap &Substitution, KOREDefinition *Definition, - llvm::BasicBlock *EntryBlock, llvm::Module *Module, bool isAnywhereOwise) - : Substitution(Substitution) - , Definition(Definition) - , CurrentBlock(EntryBlock) - , Module(Module) - , Ctx(Module->getContext()) - , isAnywhereOwise(isAnywhereOwise) { } + create_term( + llvm::StringMap &substitution, kore_definition *definition, + llvm::BasicBlock *entry_block, llvm::Module *module, + bool is_anywhere_owise) + : substitution_(substitution) + , definition_(definition) + , current_block_(entry_block) + , module_(module) + , ctx_(module->getContext()) + , is_anywhere_owise_(is_anywhere_owise) { } /* adds code to the specified basic block in the specified module which constructs an llvm value corresponding to the specified KORE RHS pattern and substitution in the specified definition, and returns the value itself, along with a boolean indicating whether the resulting term could be an injection. */ - std::pair operator()(KOREPattern *pattern); + std::pair operator()(kore_pattern *pattern); /* creates a call instruction calling a particular LLVM function, abstracting certain ABI and calling convention details: @@ -67,13 +69,13 @@ class CreateTerm { we load the value on return. - tailcc: true if the call should be made via the tailcc calling convention. */ - llvm::Value *createFunctionCall( - std::string const &name, ValueType returnCat, + llvm::Value *create_function_call( + std::string const &name, value_type return_cat, std::vector const &args, bool sret, bool tailcc, - std::string const &locationStack = "0"); + std::string const &location_stack = "0"); - [[nodiscard]] llvm::BasicBlock *getCurrentBlock() const { - return CurrentBlock; + [[nodiscard]] llvm::BasicBlock *get_current_block() const { + return current_block_; } }; @@ -82,67 +84,68 @@ std::string escape(std::string const &str); /* Creates a new llvm::Module with the predefined declarations common to all llvm modules in the llvm backend. */ std::unique_ptr -newModule(std::string const &name, llvm::LLVMContext &Context); +new_module(std::string const &name, llvm::LLVMContext &context); -llvm::StructType *getBlockType( - llvm::Module *Module, KOREDefinition *definition, KORESymbol const *symbol); -uint64_t getBlockHeaderVal( - llvm::Module *Module, KORESymbol const *symbol, llvm::Type *BlockType); -llvm::Value *getBlockHeader( - llvm::Module *Module, KOREDefinition *definition, KORESymbol const *symbol, - llvm::Type *BlockType); +llvm::StructType *get_block_type( + llvm::Module *module, kore_definition *definition, + kore_symbol const *symbol); +uint64_t get_block_header_val( + llvm::Module *module, kore_symbol const *symbol, llvm::Type *block_type); +llvm::Value *get_block_header( + llvm::Module *module, kore_definition *definition, + kore_symbol const *symbol, llvm::Type *block_type); /* returns the llvm::Type corresponding to the type of the result of calling createTerm on the specified pattern. */ -ValueType termType( - KOREPattern *pattern, llvm::StringMap &substitution, - KOREDefinition *definition); +value_type term_type( + kore_pattern *pattern, llvm::StringMap &substitution, + kore_definition *definition); /** creates a function that applies the specified rule once it has matched, and * returns the name of the function. */ -void makeApplyRuleFunction( - KOREAxiomDeclaration *axiom, KOREDefinition *definition, - llvm::Module *Module, bool bigStep = false); -std::string makeApplyRuleFunction( - KOREAxiomDeclaration *axiom, KOREDefinition *definition, - llvm::Module *Module, std::vector const &residuals); +void make_apply_rule_function( + kore_axiom_declaration *axiom, kore_definition *definition, + llvm::Module *module, bool big_step = false); +std::string make_apply_rule_function( + kore_axiom_declaration *axiom, kore_definition *definition, + llvm::Module *module, std::vector const &residuals); /** creates a function that evaluates the side condition of the specified rule, * and returns the name of the function. Returns empty string if function has no * side condition. */ -std::string makeSideConditionFunction( - KOREAxiomDeclaration *axiom, KOREDefinition *definition, - llvm::Module *Module); +std::string make_side_condition_function( + kore_axiom_declaration *axiom, kore_definition *definition, + llvm::Module *module); -extern std::string MAP_STRUCT; -extern std::string LIST_STRUCT; -extern std::string SET_STRUCT; -extern std::string INT_WRAPPER_STRUCT; -extern std::string INT_STRUCT; -extern std::string FLOAT_WRAPPER_STRUCT; -extern std::string FLOAT_STRUCT; -extern std::string BUFFER_STRUCT; -extern std::string BLOCK_STRUCT; -extern std::string BLOCKHEADER_STRUCT; +extern std::string map_struct; +extern std::string list_struct; +extern std::string set_struct; +extern std::string int_wrapper_struct; +extern std::string int_struct; +extern std::string float_wrapper_struct; +extern std::string float_struct; +extern std::string buffer_struct; +extern std::string block_struct; +extern std::string blockheader_struct; -llvm::StructType *getBlockType(llvm::Module *Module); +llvm::StructType *get_block_type(llvm::Module *module); -llvm::Type *getArgType(ValueType cat, llvm::Module *mod); +llvm::Type *get_arg_type(value_type cat, llvm::Module *mod); /* returns the llvm::Type corresponding to the specified KORE sort category */ -llvm::Type *getValueType(ValueType sort, llvm::Module *Module); -llvm::Type *getParamType(ValueType sort, llvm::Module *Module); +llvm::Type *getvalue_type(value_type sort, llvm::Module *module); +llvm::Type *get_param_type(value_type sort, llvm::Module *module); -bool isCollectionSort(ValueType cat); -bool isInjectionSymbol(KOREPattern *p, KORESymbol *sym); +bool is_collection_sort(value_type cat); +bool is_injection_symbol(kore_pattern *p, kore_symbol *sym); -void addAbort(llvm::BasicBlock *block, llvm::Module *Module); +void add_abort(llvm::BasicBlock *block, llvm::Module *module); -llvm::Value *allocateTerm( - llvm::Type *AllocType, llvm::BasicBlock *block, - char const *allocFn = "koreAlloc"); -llvm::Value *allocateTerm( - llvm::Type *AllocType, llvm::Value *Len, llvm::BasicBlock *block, - char const *allocFn = "koreAlloc"); +llvm::Value *allocate_term( + llvm::Type *alloc_type, llvm::BasicBlock *block, + char const *alloc_fn = "kore_alloc"); +llvm::Value *allocate_term( + llvm::Type *alloc_type, llvm::Value *len, llvm::BasicBlock *block, + char const *alloc_fn = "kore_alloc"); } // namespace kllvm #endif // CREATE_TERM_H diff --git a/include/kllvm/codegen/Debug.h b/include/kllvm/codegen/Debug.h index 1969de6b0..3a7a38345 100644 --- a/include/kllvm/codegen/Debug.h +++ b/include/kllvm/codegen/Debug.h @@ -17,39 +17,40 @@ namespace kllvm { -void initDebugInfo(llvm::Module *module, std::string const &filename); -void finalizeDebugInfo(); +void init_debug_info(llvm::Module *module, std::string const &filename); +void finalize_debug_info(); -void initDebugFunction( - std::string const &name, std::string const &linkageName, - llvm::DISubroutineType *type, KOREDefinition *definition, +void init_debug_function( + std::string const &name, std::string const &linkage_name, + llvm::DISubroutineType *type, kore_definition *definition, llvm::Function *func); -void initDebugAxiom(attribute_set const &att); -void initDebugParam( - llvm::Function *func, unsigned argNo, std::string const &name, - ValueType type, std::string const &typeName); -void initDebugGlobal( +void init_debug_axiom(attribute_set const &att); +void init_debug_param( + llvm::Function *func, unsigned arg_no, std::string const &name, + value_type type, std::string const &type_name); +void init_debug_global( std::string const &name, llvm::DIType *type, llvm::GlobalVariable *var); -llvm::DIType *getDebugType(ValueType type, std::string const &typeName); -llvm::DIType *getIntDebugType(); -llvm::DIType *getLongDebugType(); -llvm::DIType *getVoidDebugType(); -llvm::DIType *getBoolDebugType(); -llvm::DIType *getShortDebugType(); -llvm::DIType *getPointerDebugType(llvm::DIType *, std::string const &typeName); +llvm::DIType *get_debug_type(value_type type, std::string const &type_name); +llvm::DIType *get_int_debug_type(); +llvm::DIType *get_long_debug_type(); +llvm::DIType *get_void_debug_type(); +llvm::DIType *get_bool_debug_type(); +llvm::DIType *get_short_debug_type(); llvm::DIType * -getArrayDebugType(llvm::DIType *ty, size_t len, llvm::Align align); -llvm::DIType *getCharPtrDebugType(); -llvm::DIType *getCharDebugType(); -llvm::DIType *getForwardDecl(std::string const &name); +get_pointer_debug_type(llvm::DIType *, std::string const &type_name); +llvm::DIType * +get_array_debug_type(llvm::DIType *ty, size_t len, llvm::Align align); +llvm::DIType *get_char_ptr_debug_type(); +llvm::DIType *get_char_debug_type(); +llvm::DIType *get_forward_decl(std::string const &name); llvm::DISubroutineType * -getDebugFunctionType(llvm::Metadata *, std::vector); +get_debug_function_type(llvm::Metadata *, std::vector); -void setDebugLoc(llvm::Instruction *instr); -void resetDebugLoc(); +void set_debug_loc(llvm::Instruction *instr); +void reset_debug_loc(); } // namespace kllvm #endif diff --git a/include/kllvm/codegen/Decision.h b/include/kllvm/codegen/Decision.h index 33c295909..57adb1193 100644 --- a/include/kllvm/codegen/Decision.h +++ b/include/kllvm/codegen/Decision.h @@ -26,11 +26,11 @@ namespace kllvm { -class Decision; -class LeafNode; -class IterNextNode; +class decision; +class leaf_node; +class iter_next_node; -struct HashVar { +struct hash_var { size_t operator()(std::pair const &s) const noexcept { return std::hash()(s.first) @@ -39,434 +39,438 @@ struct HashVar { }; using var_type = std::pair; -using var_set_type - = std::unordered_map, HashVar>; +using var_set_type = std::unordered_map< + var_type, std::unordered_set, hash_var>; -class DecisionNode { +class decision_node { private: - llvm::BasicBlock *cachedCode = nullptr; - /* completed tracks whether codegen for this DecisionNode has concluded */ - bool completed = false; + llvm::BasicBlock *cached_code_ = nullptr; + /* completed tracks whether codegen for this decision_node has concluded */ + bool completed_ = false; public: - virtual ~DecisionNode() = default; + virtual ~decision_node() = default; - virtual void codegen(Decision *d) = 0; - virtual void preprocess(std::unordered_set &) = 0; - bool beginNode(Decision *d, std::string const &name); + virtual void codegen(decision *d) = 0; + virtual void preprocess(std::unordered_set &) = 0; + bool begin_node(decision *d, std::string const &name); - void setCompleted() { completed = true; } - [[nodiscard]] bool isCompleted() const { return completed; } - [[nodiscard]] uint64_t getChoiceDepth() const { return choiceDepth; } + void set_completed() { completed_ = true; } + [[nodiscard]] bool is_completed() const { return completed_; } + [[nodiscard]] uint64_t get_choice_depth() const { return choice_depth_; } private: - bool preprocessed = false, containsFailNode = false; - uint64_t choiceDepth = 0; - friend class Decision; - friend class SwitchNode; - friend class MakePatternNode; - friend class FunctionNode; - friend class LeafNode; - friend class FailNode; - friend class MakeIteratorNode; - friend class IterNextNode; + bool preprocessed_ = false, containsfail_node_ = false; + uint64_t choice_depth_ = 0; + friend class decision; + friend class switch_node; + friend class make_pattern_node; + friend class function_node; + friend class leaf_node; + friend class fail_node; + friend class make_iterator_node; + friend class iter_next_node; }; -class FailNode : public DecisionNode { +class fail_node : public decision_node { private: - FailNode() = default; + fail_node() = default; - static FailNode instance; + static fail_node instance; public: - ~FailNode() override = default; - static FailNode *get() { return &instance; } + ~fail_node() override = default; + static fail_node *get() { return &instance; } - void codegen(Decision *d) override { abort(); } - void preprocess(std::unordered_set &) override { - containsFailNode = true; + void codegen(decision *d) override { abort(); } + void preprocess(std::unordered_set &) override { + containsfail_node_ = true; } }; -class DecisionCase { +class decision_case { private: /* constructor to switch on. if null, this is a wildcard match. if equal to \\dv, we are matching on a bool or mint literal. */ - KORESymbol *constructor; + kore_symbol *constructor_; /* the names to bind the children of this pattern to. */ - std::vector bindings; + std::vector bindings_; /* the literal int to match on. must have a bit width equal to the size of the sort being matched. */ - llvm::APInt literal; + llvm::APInt literal_; /* the node in the tree to jump to if this constructor is matched */ - DecisionNode *child; + decision_node *child_; public: - DecisionCase( - KORESymbol *constructor, std::vector bindings, - DecisionNode *child) - : constructor(constructor) - , bindings(std::move(std::move(bindings))) - , child(child) { } - DecisionCase(KORESymbol *dv, llvm::APInt literal, DecisionNode *child) - : constructor(dv) - , literal(std::move(std::move(literal))) - , child(child) { } - - [[nodiscard]] KORESymbol *getConstructor() const { return constructor; } - [[nodiscard]] std::vector const &getBindings() const { - return bindings; + decision_case( + kore_symbol *constructor, std::vector bindings, + decision_node *child) + : constructor_(constructor) + , bindings_(std::move(std::move(bindings))) + , child_(child) { } + decision_case(kore_symbol *dv, llvm::APInt literal, decision_node *child) + : constructor_(dv) + , literal_(std::move(std::move(literal))) + , child_(child) { } + + [[nodiscard]] kore_symbol *get_constructor() const { return constructor_; } + [[nodiscard]] std::vector const &get_bindings() const { + return bindings_; } - void addBinding(std::string const &name, ValueType type, llvm::Module *mod) { - bindings.emplace_back(name, getParamType(type, mod)); + void + add_binding(std::string const &name, value_type type, llvm::Module *mod) { + bindings_.emplace_back(name, get_param_type(type, mod)); } - llvm::APInt getLiteral() const { return literal; } - [[nodiscard]] DecisionNode *getChild() const { return child; } + llvm::APInt get_literal() const { return literal_; } + [[nodiscard]] decision_node *get_child() const { return child_; } }; -class SwitchNode : public DecisionNode { +class switch_node : public decision_node { private: /* the list of switch cases */ - std::vector cases; + std::vector cases_; /* the name of the variable being matched on. */ - std::string name; - llvm::Type *type; + std::string name_; + llvm::Type *type_; - bool isCheckNull; + bool is_check_null_; - SwitchNode(std::string name, llvm::Type *type, bool isCheckNull) - : name(std::move(name)) - , type(type) - , isCheckNull(isCheckNull) { } + switch_node(std::string name, llvm::Type *type, bool is_check_null) + : name_(std::move(name)) + , type_(type) + , is_check_null_(is_check_null) { } public: - ~SwitchNode() override = default; - void addCase(DecisionCase const &_case) { cases.push_back(_case); } + ~switch_node() override = default; + void add_case(decision_case const &c) { cases_.push_back(c); } - static SwitchNode * - Create(std::string const &name, llvm::Type *type, bool isCheckNull) { - return new SwitchNode(name, type, isCheckNull); + static switch_node * + create(std::string const &name, llvm::Type *type, bool is_check_null) { + return new switch_node(name, type, is_check_null); } - [[nodiscard]] std::string getName() const { return name; } - [[nodiscard]] llvm::Type *getType() const { return type; } - [[nodiscard]] std::vector const &getCases() const { - return cases; + [[nodiscard]] std::string get_name() const { return name_; } + [[nodiscard]] llvm::Type *get_type() const { return type_; } + [[nodiscard]] std::vector const &get_cases() const { + return cases_; } - void codegen(Decision *d) override; - void preprocess(std::unordered_set &leaves) override { - if (preprocessed) { + void codegen(decision *d) override; + void preprocess(std::unordered_set &leaves) override { + if (preprocessed_) { return; } - bool hasDefault = false; - for (auto const &_case : cases) { - _case.getChild()->preprocess(leaves); - containsFailNode = containsFailNode || _case.getChild()->containsFailNode; - hasDefault = hasDefault || _case.getConstructor() == nullptr; - choiceDepth = std::max(choiceDepth, _case.getChild()->choiceDepth); + bool has_default = false; + for (auto const &c : cases_) { + c.get_child()->preprocess(leaves); + containsfail_node_ + = containsfail_node_ || c.get_child()->containsfail_node_; + has_default = has_default || c.get_constructor() == nullptr; + choice_depth_ = std::max(choice_depth_, c.get_child()->choice_depth_); } - if (!hasDefault) { - containsFailNode = true; + if (!has_default) { + containsfail_node_ = true; } - preprocessed = true; + preprocessed_ = true; } }; -class MakePatternNode : public DecisionNode { +class make_pattern_node : public decision_node { private: - std::string name; - llvm::Type *type; - KOREPattern *pattern; - std::vector uses; - DecisionNode *child; - - MakePatternNode( - std::string name, llvm::Type *type, KOREPattern *pattern, - std::vector &uses, DecisionNode *child) - : name(std::move(name)) - , type(type) - , pattern(pattern) - , uses(uses) - , child(child) { } + std::string name_; + llvm::Type *type_; + kore_pattern *pattern_; + std::vector uses_; + decision_node *child_; + + make_pattern_node( + std::string name, llvm::Type *type, kore_pattern *pattern, + std::vector &uses, decision_node *child) + : name_(std::move(name)) + , type_(type) + , pattern_(pattern) + , uses_(uses) + , child_(child) { } public: - ~MakePatternNode() override = default; - static MakePatternNode *Create( - std::string const &name, llvm::Type *type, KOREPattern *pattern, - std::vector &uses, DecisionNode *child) { - return new MakePatternNode(name, type, pattern, uses, child); + ~make_pattern_node() override = default; + static make_pattern_node *create( + std::string const &name, llvm::Type *type, kore_pattern *pattern, + std::vector &uses, decision_node *child) { + return new make_pattern_node(name, type, pattern, uses, child); } - void codegen(Decision *d) override; - void preprocess(std::unordered_set &leaves) override { - if (preprocessed) { + void codegen(decision *d) override; + void preprocess(std::unordered_set &leaves) override { + if (preprocessed_) { return; } - child->preprocess(leaves); - containsFailNode = containsFailNode || child->containsFailNode; - choiceDepth = child->choiceDepth; - preprocessed = true; + child_->preprocess(leaves); + containsfail_node_ = containsfail_node_ || child_->containsfail_node_; + choice_depth_ = child_->choice_depth_; + preprocessed_ = true; } }; -class FunctionNode : public DecisionNode { +class function_node : public decision_node { private: /* the list of arguments to the function. */ - std::vector> bindings; + std::vector> bindings_; /* the name of the variable to bind to the result of the function. */ - std::string name; + std::string name_; /* the name of the function to call */ - std::string function; + std::string function_; /* the successor node in the tree */ - DecisionNode *child; - ValueType cat; - llvm::Type *type; - - FunctionNode( - std::string name, std::string function, DecisionNode *child, - ValueType cat, llvm::Type *type) - : name(std::move(name)) - , function(std::move(function)) - , child(child) - , cat(cat) - , type(type) { } + decision_node *child_; + value_type cat_; + llvm::Type *type_; + + function_node( + std::string name, std::string function, decision_node *child, + value_type cat, llvm::Type *type) + : name_(std::move(name)) + , function_(std::move(function)) + , child_(child) + , cat_(cat) + , type_(type) { } public: - ~FunctionNode() override = default; - static FunctionNode *Create( - std::string const &name, std::string const &function, DecisionNode *child, - ValueType cat, llvm::Type *type) { - return new FunctionNode(name, function, child, cat, type); + ~function_node() override = default; + static function_node *create( + std::string const &name, std::string const &function, + decision_node *child, value_type cat, llvm::Type *type) { + return new function_node(name, function, child, cat, type); } - [[nodiscard]] std::vector> const & - getBindings() const { - return bindings; + [[nodiscard]] std::vector> const & + get_bindings() const { + return bindings_; } - void addBinding(std::string const &name, ValueType type, llvm::Module *mod) { - bindings.push_back({{name, getParamType(type, mod)}, type}); + void + add_binding(std::string const &name, value_type type, llvm::Module *mod) { + bindings_.push_back({{name, get_param_type(type, mod)}, type}); } - void codegen(Decision *d) override; - void preprocess(std::unordered_set &leaves) override { - if (preprocessed) { + void codegen(decision *d) override; + void preprocess(std::unordered_set &leaves) override { + if (preprocessed_) { return; } - child->preprocess(leaves); - containsFailNode = containsFailNode || child->containsFailNode; - choiceDepth = child->choiceDepth; - preprocessed = true; + child_->preprocess(leaves); + containsfail_node_ = containsfail_node_ || child_->containsfail_node_; + choice_depth_ = child_->choice_depth_; + preprocessed_ = true; } }; -class LeafNode : public DecisionNode { +class leaf_node : public decision_node { private: /* the names in the decision tree of the variables used in the rhs of this rule, in alphabetical order of their names in the rule. */ - std::vector bindings; + std::vector bindings_; /* the name of the function that constructs the rhs of this rule from the substitution */ - std::string name; + std::string name_; - DecisionNode *child = nullptr; + decision_node *child_ = nullptr; - LeafNode(std::string name) - : name(std::move(name)) { } + leaf_node(std::string name) + : name_(std::move(name)) { } public: - ~LeafNode() override = default; - static LeafNode *Create(std::string const &name) { - return new LeafNode(name); + ~leaf_node() override = default; + static leaf_node *create(std::string const &name) { + return new leaf_node(name); } - [[nodiscard]] std::vector const &getBindings() const { - return bindings; + [[nodiscard]] std::vector const &get_bindings() const { + return bindings_; } - void addBinding(std::string const &name, ValueType type, llvm::Module *mod) { - bindings.emplace_back(name, getParamType(type, mod)); + void + add_binding(std::string const &name, value_type type, llvm::Module *mod) { + bindings_.emplace_back(name, get_param_type(type, mod)); } - void setChild(DecisionNode *child) { this->child = child; } + void set_child(decision_node *child) { this->child_ = child; } - void codegen(Decision *d) override; - void preprocess(std::unordered_set &leaves) override { - if (child != nullptr) { - if (preprocessed) { + void codegen(decision *d) override; + void preprocess(std::unordered_set &leaves) override { + if (child_ != nullptr) { + if (preprocessed_) { return; } leaves.insert(this); - child->preprocess(leaves); - containsFailNode = containsFailNode || child->containsFailNode; - choiceDepth = child->choiceDepth; - preprocessed = true; + child_->preprocess(leaves); + containsfail_node_ = containsfail_node_ || child_->containsfail_node_; + choice_depth_ = child_->choice_depth_; + preprocessed_ = true; } else { leaves.insert(this); } } }; -class MakeIteratorNode : public DecisionNode { +class make_iterator_node : public decision_node { private: - std::string collection; - llvm::Type *collectionType; - std::string name; - llvm::Type *type; - std::string hookName; - DecisionNode *child; - - MakeIteratorNode( - std::string collection, llvm::Type *collectionType, std::string name, - llvm::Type *type, std::string hookName, DecisionNode *child) - : collection(std::move(collection)) - , collectionType(collectionType) - , name(std::move(name)) - , type(type) - , hookName(std::move(hookName)) - , child(child) { } + std::string collection_; + llvm::Type *collection_type_; + std::string name_; + llvm::Type *type_; + std::string hook_name_; + decision_node *child_; + + make_iterator_node( + std::string collection, llvm::Type *collection_type, std::string name, + llvm::Type *type, std::string hook_name, decision_node *child) + : collection_(std::move(collection)) + , collection_type_(collection_type) + , name_(std::move(name)) + , type_(type) + , hook_name_(std::move(hook_name)) + , child_(child) { } public: - ~MakeIteratorNode() override = default; - static MakeIteratorNode *Create( - std::string const &collection, llvm::Type *collectionType, - std::string const &name, llvm::Type *type, std::string const &hookName, - DecisionNode *child) { - return new MakeIteratorNode( - collection, collectionType, name, type, hookName, child); + ~make_iterator_node() override = default; + static make_iterator_node *create( + std::string const &collection, llvm::Type *collection_type, + std::string const &name, llvm::Type *type, std::string const &hook_name, + decision_node *child) { + return new make_iterator_node( + collection, collection_type, name, type, hook_name, child); } - void codegen(Decision *d) override; - void preprocess(std::unordered_set &leaves) override { - if (preprocessed) { + void codegen(decision *d) override; + void preprocess(std::unordered_set &leaves) override { + if (preprocessed_) { return; } - child->preprocess(leaves); - containsFailNode = containsFailNode || child->containsFailNode; - choiceDepth = child->choiceDepth; - preprocessed = true; + child_->preprocess(leaves); + containsfail_node_ = containsfail_node_ || child_->containsfail_node_; + choice_depth_ = child_->choice_depth_; + preprocessed_ = true; } }; -class IterNextNode : public DecisionNode { +class iter_next_node : public decision_node { private: - std::string iterator; - llvm::Type *iteratorType; - std::string binding; - llvm::Type *bindingType; - std::string hookName; - DecisionNode *child; - - IterNextNode( - std::string iterator, llvm::Type *iteratorType, std::string binding, - llvm::Type *bindingType, std::string hookName, DecisionNode *child) - : iterator(std::move(iterator)) - , iteratorType(iteratorType) - , binding(std::move(binding)) - , bindingType(bindingType) - , hookName(std::move(hookName)) - , child(child) { } + std::string iterator_; + llvm::Type *iterator_type_; + std::string binding_; + llvm::Type *binding_type_; + std::string hook_name_; + decision_node *child_; + + iter_next_node( + std::string iterator, llvm::Type *iterator_type, std::string binding, + llvm::Type *binding_type, std::string hook_name, decision_node *child) + : iterator_(std::move(iterator)) + , iterator_type_(iterator_type) + , binding_(std::move(binding)) + , binding_type_(binding_type) + , hook_name_(std::move(hook_name)) + , child_(child) { } public: - ~IterNextNode() override = default; - static IterNextNode *Create( - std::string const &iterator, llvm::Type *iteratorType, - std::string const &binding, llvm::Type *bindingType, - std::string const &hookName, DecisionNode *child) { - return new IterNextNode( - iterator, iteratorType, binding, bindingType, hookName, child); + ~iter_next_node() override = default; + static iter_next_node *create( + std::string const &iterator, llvm::Type *iterator_type, + std::string const &binding, llvm::Type *binding_type, + std::string const &hook_name, decision_node *child) { + return new iter_next_node( + iterator, iterator_type, binding, binding_type, hook_name, child); } - void codegen(Decision *d) override; - void preprocess(std::unordered_set &leaves) override { - if (preprocessed) { + void codegen(decision *d) override; + void preprocess(std::unordered_set &leaves) override { + if (preprocessed_) { return; } - child->preprocess(leaves); - containsFailNode = containsFailNode || child->containsFailNode; - choiceDepth = child->choiceDepth + 1; - preprocessed = true; + child_->preprocess(leaves); + containsfail_node_ = containsfail_node_ || child_->containsfail_node_; + choice_depth_ = child_->choice_depth_ + 1; + preprocessed_ = true; } }; -class Decision { +class decision { private: - KOREDefinition *Definition; - llvm::BasicBlock *CurrentBlock; - llvm::BasicBlock *FailureBlock; - llvm::IndirectBrInst *FailJump; - llvm::AllocaInst *ChoiceBuffer; - llvm::AllocaInst *ChoiceDepth; - llvm::BasicBlock *ChoiceBlock{nullptr}; - llvm::Module *Module; - llvm::LLVMContext &Ctx; - ValueType Cat; - llvm::PHINode *FailSubject, *FailPattern, *FailSort; - llvm::AllocaInst *HasSearchResults; - - std::map symbols{}; - - llvm::Value *getTag(llvm::Value *); + kore_definition *definition_; + llvm::BasicBlock *current_block_; + llvm::BasicBlock *failure_block_; + llvm::IndirectBrInst *fail_jump_; + llvm::AllocaInst *choice_buffer_; + llvm::AllocaInst *choice_depth_; + llvm::BasicBlock *choice_block_{nullptr}; + llvm::Module *module_; + llvm::LLVMContext &ctx_; + value_type cat_; + llvm::PHINode *fail_subject_, *fail_pattern_, *fail_sort_; + llvm::AllocaInst *has_search_results_; + + std::map symbols_{}; + + llvm::Value *get_tag(llvm::Value *); llvm::AllocaInst *decl(var_type const &name); - llvm::Constant *stringLiteral(std::string const &str); - llvm::Value *ptrTerm(llvm::Value *val); + llvm::Constant *string_literal(std::string const &str); + llvm::Value *ptr_term(llvm::Value *val); public: - Decision( - KOREDefinition *Definition, llvm::BasicBlock *EntryBlock, - llvm::BasicBlock *FailureBlock, llvm::IndirectBrInst *FailJump, - llvm::AllocaInst *ChoiceBuffer, llvm::AllocaInst *ChoiceDepth, - llvm::Module *Module, ValueType Cat, llvm::PHINode *FailSubject, - llvm::PHINode *FailPattern, llvm::PHINode *FailSort, - llvm::AllocaInst *HasSearchResults) - : Definition(Definition) - , CurrentBlock(EntryBlock) - , FailureBlock(FailureBlock) - , FailJump(FailJump) - , ChoiceBuffer(ChoiceBuffer) - , ChoiceDepth(ChoiceDepth) - , Module(Module) - , Ctx(Module->getContext()) - , Cat(Cat) - , FailSubject(FailSubject) - , FailPattern(FailPattern) - , FailSort(FailSort) - , HasSearchResults(HasSearchResults) { } + decision( + kore_definition *definition, llvm::BasicBlock *entry_block, + llvm::BasicBlock *failure_block, llvm::IndirectBrInst *fail_jump, + llvm::AllocaInst *choice_buffer, llvm::AllocaInst *choice_depth, + llvm::Module *module, value_type cat, llvm::PHINode *fail_subject, + llvm::PHINode *fail_pattern, llvm::PHINode *fail_sort, + llvm::AllocaInst *has_search_results) + : definition_(definition) + , current_block_(entry_block) + , failure_block_(failure_block) + , fail_jump_(fail_jump) + , choice_buffer_(choice_buffer) + , choice_depth_(choice_depth) + , module_(module) + , ctx_(module->getContext()) + , cat_(cat) + , fail_subject_(fail_subject) + , fail_pattern_(fail_pattern) + , fail_sort_(fail_sort) + , has_search_results_(has_search_results) { } /* adds code to the specified basic block to take a single step based on the specified decision tree and return the result of taking that step. */ - void operator()(DecisionNode *entry); + void operator()(decision_node *entry); void store(var_type const &name, llvm::Value *val); llvm::Value *load(var_type const &name); - friend class SwitchNode; - friend class MakePatternNode; - friend class FunctionNode; - friend class LeafNode; - friend class MakeIteratorNode; - friend class IterNextNode; - friend class DecisionNode; + friend class switch_node; + friend class make_pattern_node; + friend class function_node; + friend class leaf_node; + friend class make_iterator_node; + friend class iter_next_node; + friend class decision_node; }; /* construct the function that evaluates the specified function symbol according to the specified decision tree and returns the result of the function. */ -void makeEvalFunction( - KORESymbol *function, KOREDefinition *definition, llvm::Module *module, - DecisionNode *dt); -void makeAnywhereFunction( - KORESymbol *function, KOREDefinition *definition, llvm::Module *module, - DecisionNode *dt); - -void makeStepFunction( - KOREDefinition *definition, llvm::Module *module, DecisionNode *dt, +void make_eval_function( + kore_symbol *function, kore_definition *definition, llvm::Module *module, + decision_node *dt); +void make_anywhere_function( + kore_symbol *function, kore_definition *definition, llvm::Module *module, + decision_node *dt); + +void make_step_function( + kore_definition *definition, llvm::Module *module, decision_node *dt, bool search); -void makeStepFunction( - KOREAxiomDeclaration *axiom, KOREDefinition *definition, - llvm::Module *module, PartialStep res); -void makeMatchReasonFunction( - KOREDefinition *definition, llvm::Module *module, - KOREAxiomDeclaration *axiom, DecisionNode *dt); +void make_step_function( + kore_axiom_declaration *axiom, kore_definition *definition, + llvm::Module *module, partial_step res); +void make_match_reason_function( + kore_definition *definition, llvm::Module *module, + kore_axiom_declaration *axiom, decision_node *dt); } // namespace kllvm #endif // DECISION_H diff --git a/include/kllvm/codegen/DecisionParser.h b/include/kllvm/codegen/DecisionParser.h index dbb095866..8dd679f64 100644 --- a/include/kllvm/codegen/DecisionParser.h +++ b/include/kllvm/codegen/DecisionParser.h @@ -11,30 +11,30 @@ namespace kllvm { -class DecisionNode; +class decision_node; -struct Residual { +struct residual { std::string occurrence; - KOREPattern *pattern{}; + kore_pattern *pattern{}; }; -struct PartialStep { - DecisionNode *dt{}; - std::vector residuals; +struct partial_step { + decision_node *dt{}; + std::vector residuals; }; -DecisionNode *parseYamlDecisionTreeFromString( +decision_node *parse_yamldecision_tree_from_string( llvm::Module *, std::string const &yaml, - std::map const &syms, - std::map> const &sorts); -DecisionNode *parseYamlDecisionTree( + std::map const &syms, + std::map> const &sorts); +decision_node *parse_yamldecision_tree( llvm::Module *, std::string const &filename, - std::map const &syms, - std::map> const &sorts); -PartialStep parseYamlSpecialDecisionTree( + std::map const &syms, + std::map> const &sorts); +partial_step parse_yaml_specialdecision_tree( llvm::Module *, std::string const &filename, - std::map const &syms, - std::map> const &sorts); + std::map const &syms, + std::map> const &sorts); } // namespace kllvm diff --git a/include/kllvm/codegen/EmitConfigParser.h b/include/kllvm/codegen/EmitConfigParser.h index 278a9b084..d8b189578 100644 --- a/include/kllvm/codegen/EmitConfigParser.h +++ b/include/kllvm/codegen/EmitConfigParser.h @@ -7,8 +7,8 @@ namespace kllvm { -void emitConfigParserFunctions( - KOREDefinition *definition, llvm::Module *module); +void emit_config_parser_functions( + kore_definition *definition, llvm::Module *module); } diff --git a/include/kllvm/codegen/Metadata.h b/include/kllvm/codegen/Metadata.h index 22d74f049..55246f81c 100644 --- a/include/kllvm/codegen/Metadata.h +++ b/include/kllvm/codegen/Metadata.h @@ -8,12 +8,12 @@ namespace kllvm { -void addKompiledDirSymbol( +void add_kompiled_dir_symbol( llvm::Module &mod, std::string const &dir, bool debug); -void addMutableBytesFlag(llvm::Module &mod, bool enabled, bool debug); +void add_mutable_bytes_flag(llvm::Module &mod, bool enabled, bool debug); -void addSafePartialFlag(llvm::Module &mod, bool enabled, bool debug); +void add_safe_partial_flag(llvm::Module &mod, bool enabled, bool debug); } // namespace kllvm diff --git a/include/kllvm/codegen/Options.h b/include/kllvm/codegen/Options.h index 18c527490..1357a81dd 100644 --- a/include/kllvm/codegen/Options.h +++ b/include/kllvm/codegen/Options.h @@ -5,16 +5,16 @@ enum class opt_level { O0, O1, O2, O3 }; -extern llvm::cl::OptionCategory CodegenLibCat; - -extern llvm::cl::opt Debug; -extern llvm::cl::opt NoOptimize; -extern llvm::cl::opt EmitObject; -extern llvm::cl::opt BinaryIR; -extern llvm::cl::opt ForceBinary; -extern llvm::cl::opt ProofHintInstrumentation; -extern llvm::cl::opt KeepFramePointer; -extern llvm::cl::opt OptimizationLevel; +extern llvm::cl::OptionCategory codegen_lib_cat; + +extern llvm::cl::opt debug; +extern llvm::cl::opt no_optimize; +extern llvm::cl::opt emit_object; +extern llvm::cl::opt binary_ir; +extern llvm::cl::opt force_binary; +extern llvm::cl::opt proof_hint_instrumentation; +extern llvm::cl::opt keep_frame_pointer; +extern llvm::cl::opt optimization_level; namespace kllvm { diff --git a/include/kllvm/codegen/ProofEvent.h b/include/kllvm/codegen/ProofEvent.h index 3ff7e49d2..647ecea26 100644 --- a/include/kllvm/codegen/ProofEvent.h +++ b/include/kllvm/codegen/ProofEvent.h @@ -13,11 +13,11 @@ namespace kllvm { -class ProofEvent { +class proof_event { private: - KOREDefinition *Definition; - llvm::Module *Module; - llvm::LLVMContext &Ctx; + kore_definition *definition_; + llvm::Module *module_; + llvm::LLVMContext &ctx_; /* * Load the boolean flag that controls whether proof hint output is enabled or @@ -30,7 +30,7 @@ class ProofEvent { * behaviour. */ std::pair - proofBranch(std::string const &label, llvm::BasicBlock *insertAtEnd); + proof_branch(std::string const &label, llvm::BasicBlock *insert_at_end); /* * Set up a standard event prelude by creating a pair of basic blocks for the @@ -41,38 +41,39 @@ class ProofEvent { * `emitGetOutputFileName`. */ std::tuple - eventPrelude(std::string const &label, llvm::BasicBlock *insertAtEnd); + event_prelude(std::string const &label, llvm::BasicBlock *insert_at_end); /* * Emit a call that will serialize `term` to the specified `outputFile` as * binary KORE. This function can be called on any term, but the sort of that * term must be known. */ - llvm::CallInst *emitSerializeTerm( - KORECompositeSort &sort, llvm::Value *outputFile, llvm::Value *term, - llvm::BasicBlock *insertAtEnd); + llvm::CallInst *emit_serialize_term( + kore_composite_sort &sort, llvm::Value *output_file, llvm::Value *term, + llvm::BasicBlock *insert_at_end); /* * Emit a call that will serialize `config` to the specified `outputFile` as * binary KORE. This function does not require a sort, but the configuration * passed must be a top-level configuration. */ - llvm::CallInst *emitSerializeConfiguration( - llvm::Value *outputFile, llvm::Value *config, - llvm::BasicBlock *insertAtEnd); + llvm::CallInst *emit_serialize_configuration( + llvm::Value *output_file, llvm::Value *config, + llvm::BasicBlock *insert_at_end); /* * Emit a call that will serialize `value` to the specified `outputFile`. */ - llvm::CallInst *emitWriteUInt64( - llvm::Value *outputFile, uint64_t value, llvm::BasicBlock *insertAtEnd); + llvm::CallInst *emit_write_uint64( + llvm::Value *output_file, uint64_t value, + llvm::BasicBlock *insert_at_end); /* * Emit a call that will serialize `str` to the specified `outputFile`. */ - llvm::CallInst *emitWriteString( - llvm::Value *outputFile, std::string const &str, - llvm::BasicBlock *insertAtEnd); + llvm::CallInst *emit_write_string( + llvm::Value *output_file, std::string const &str, + llvm::BasicBlock *insert_at_end); /* * Emit an instruction that has no effect and will be removed by optimization @@ -83,56 +84,56 @@ class ProofEvent { * branch is created. If the MergeBlock has no instructions, this has resulted * in a segfault when printing the IR. Adding an effective no-op prevents this. */ - llvm::BinaryOperator *emitNoOp(llvm::BasicBlock *insertAtEnd); + llvm::BinaryOperator *emit_no_op(llvm::BasicBlock *insert_at_end); /* * Emit instructions to load the path of the interpreter's current output * file; used here for binary proof trace data. */ - llvm::LoadInst *emitGetOutputFileName(llvm::BasicBlock *insertAtEnd); + llvm::LoadInst *emit_get_output_file_name(llvm::BasicBlock *insert_at_end); public: - [[nodiscard]] llvm::BasicBlock *hookEvent_pre( + [[nodiscard]] llvm::BasicBlock *hook_event_pre( std::string const &name, llvm::BasicBlock *current_block, - std::string const &locationStack); + std::string const &location_stack); - [[nodiscard]] llvm::BasicBlock *hookEvent_post( - llvm::Value *val, KORECompositeSort *sort, + [[nodiscard]] llvm::BasicBlock *hook_event_post( + llvm::Value *val, kore_composite_sort *sort, llvm::BasicBlock *current_block); - [[nodiscard]] llvm::BasicBlock *hookArg( - llvm::Value *val, KORECompositeSort *sort, + [[nodiscard]] llvm::BasicBlock *hook_arg( + llvm::Value *val, kore_composite_sort *sort, llvm::BasicBlock *current_block); - [[nodiscard]] llvm::BasicBlock *rewriteEvent_pre( - KOREAxiomDeclaration *axiom, uint64_t arity, - std::map vars, + [[nodiscard]] llvm::BasicBlock *rewrite_event_pre( + kore_axiom_declaration *axiom, uint64_t arity, + std::map vars, llvm::StringMap const &subst, llvm::BasicBlock *current_block); - [[nodiscard]] llvm::BasicBlock *rewriteEvent_post( - KOREAxiomDeclaration *axiom, llvm::Value *return_value, + [[nodiscard]] llvm::BasicBlock *rewrite_event_post( + kore_axiom_declaration *axiom, llvm::Value *return_value, llvm::BasicBlock *current_block); - [[nodiscard]] llvm::BasicBlock *functionEvent_pre( - llvm::BasicBlock *current_block, KORECompositePattern *pattern, - std::string const &locationStack); + [[nodiscard]] llvm::BasicBlock *function_event_pre( + llvm::BasicBlock *current_block, kore_composite_pattern *pattern, + std::string const &location_stack); [[nodiscard]] llvm::BasicBlock * - functionEvent_post(llvm::BasicBlock *current_block); + function_event_post(llvm::BasicBlock *current_block); - [[nodiscard]] llvm::BasicBlock *sideConditionEvent_pre( - KOREAxiomDeclaration *axiom, std::vector const &args, + [[nodiscard]] llvm::BasicBlock *side_condition_event_pre( + kore_axiom_declaration *axiom, std::vector const &args, llvm::BasicBlock *current_block); - [[nodiscard]] llvm::BasicBlock *sideConditionEvent_post( - KOREAxiomDeclaration *axiom, llvm::Value *check_result, + [[nodiscard]] llvm::BasicBlock *side_condition_event_post( + kore_axiom_declaration *axiom, llvm::Value *check_result, llvm::BasicBlock *current_block); - ProofEvent(KOREDefinition *Definition, llvm::Module *Module) - : Definition(Definition) - , Module(Module) - , Ctx(Module->getContext()) { } + proof_event(kore_definition *definition, llvm::Module *module) + : definition_(definition) + , module_(module) + , ctx_(module->getContext()) { } }; } // namespace kllvm diff --git a/include/kllvm/codegen/Util.h b/include/kllvm/codegen/Util.h index 252b1b3a0..2834c0e92 100644 --- a/include/kllvm/codegen/Util.h +++ b/include/kllvm/codegen/Util.h @@ -14,11 +14,11 @@ namespace kllvm { // Returns a reference to the function declaration for a memory allocation // function with the given name, adding a declaration to the current module if // one does not yet exist -llvm::Function *koreHeapAlloc(std::string const &name, llvm::Module *module); +llvm::Function *kore_heap_alloc(std::string const &name, llvm::Module *module); // getOrInsertFunction on module, aborting on failure template -llvm::Function *getOrInsertFunction(llvm::Module *module, Ts &&...args) { +llvm::Function *get_or_insert_function(llvm::Module *module, Ts &&...args) { auto callee = module->getOrInsertFunction(std::forward(args)...).getCallee(); auto func = llvm::dyn_cast(callee); diff --git a/include/kllvm/parser/KOREParser.h b/include/kllvm/parser/KOREParser.h index bedd5b9f9..1759cd8c2 100644 --- a/include/kllvm/parser/KOREParser.h +++ b/include/kllvm/parser/KOREParser.h @@ -12,24 +12,24 @@ namespace kllvm::parser { -class KOREParser { +class kore_parser { public: - KOREParser(std::string const &filename) - : scanner(KOREScanner(filename)) - , loc(location(filename)) { } + kore_parser(std::string const &filename) + : scanner_(kore_scanner(filename)) + , loc_(location(filename)) { } - static std::unique_ptr from_string(std::string const &text); + static std::unique_ptr from_string(std::string const &text); - ptr definition(); - sptr pattern(); - sptr sort(); - std::vector> declarations(); + ptr definition(); + sptr pattern(); + sptr sort(); + std::vector> declarations(); - std::pair>> symbol_sort_list(); + std::pair>> symbol_sort_list(); private: - KOREScanner scanner; - location loc; + kore_scanner scanner_; + location loc_; [[noreturn]] static void error(location const &loc, std::string const &err_message); @@ -40,37 +40,38 @@ class KOREParser { void attributes(Node *node); template - void attributesNE(Node *node); + void attributes_ne(Node *node); - void modules(KOREDefinition *node); - ptr module(); + void modules(kore_definition *node); + ptr module(); - void sentences(KOREModule *node); - ptr sentence(); + void sentences(kore_module *node); + ptr sentence(); - void sortVariables(KOREDeclaration *node); - void sortVariablesNE(KOREDeclaration *node); + void sort_variables(kore_declaration *node); + void sort_variables_ne(kore_declaration *node); template void sorts(Node *node); template - void sortsNE(Node *node); + void sorts_ne(Node *node); - sptr _pattern(); - void patterns(KORECompositePattern *node); - void patternsNE(KORECompositePattern *node); - void patterns(std::vector> &node); - void patternsNE(std::vector> &node); + sptr pattern_internal(); + void patterns(kore_composite_pattern *node); + void patterns_ne(kore_composite_pattern *node); + void patterns(std::vector> &node); + void patterns_ne(std::vector> &node); - sptr applicationPattern(); - sptr applicationPattern(std::string const &name); - ptr _applicationPattern(); - ptr _applicationPattern(std::string const &name); + sptr application_pattern(); + sptr application_pattern(std::string const &name); + ptr application_pattern_internal(); + ptr + application_pattern_internal(std::string const &name); struct { std::string data; token tok; - } buffer = {"", token::EMPTY}; + } buffer_ = {"", token::Empty}; }; } // namespace kllvm::parser diff --git a/include/kllvm/parser/KOREScanner.h b/include/kllvm/parser/KOREScanner.h index afb746c7f..3e895b70e 100644 --- a/include/kllvm/parser/KOREScanner.h +++ b/include/kllvm/parser/KOREScanner.h @@ -6,59 +6,59 @@ namespace kllvm::parser { enum class token { - EMPTY, - MODULE, - ENDMODULE, - IMPORT, - SORT, - SYMBOL, - WHERE, - ALIAS, - AXIOM, - CLAIM, - HOOKEDSORT, - HOOKEDSYMBOL, - COLON, - LEFTBRACE, - RIGHTBRACE, - LEFTBRACKET, - RIGHTBRACKET, - LEFTPAREN, - RIGHTPAREN, - COMMA, - COLONEQUAL, - ID, - STRING, - TOKEN_EOF, + Empty, + Module, + EndModule, + Import, + Sort, + Symbol, + Where, + Alias, + Axiom, + Claim, + HookedSort, + HookedSymbol, + Colon, + LeftBrace, + RightBrace, + LeftBracket, + RightBracket, + LeftParen, + RightParen, + Comma, + ColonEqual, + Id, + String, + TokenEof, }; -class KOREScanner { +class kore_scanner { public: - KOREScanner(std::string filename); - ~KOREScanner(); + kore_scanner(std::string filename); + ~kore_scanner(); int scan(); - friend class KOREParser; + friend class kore_parser; using yyscan_t = void *; - KOREScanner(KOREScanner const &other) = delete; - KOREScanner &operator=(KOREScanner const &other) = delete; + kore_scanner(kore_scanner const &other) = delete; + kore_scanner &operator=(kore_scanner const &other) = delete; - KOREScanner(KOREScanner &&other) = delete; - KOREScanner &operator=(KOREScanner &&other) = delete; + kore_scanner(kore_scanner &&other) = delete; + kore_scanner &operator=(kore_scanner &&other) = delete; private: - yyscan_t scanner; + yyscan_t scanner_; token yylex(std::string *lval, location *loc, yyscan_t yyscanner); token yylex(std::string *lval, location *loc) { - return yylex(lval, loc, scanner); + return yylex(lval, loc, scanner_); } void error(location const &loc, std::string const &err_message); std::string codepoint_to_utf8(unsigned long int code, location const &loc); - FILE *in; - std::string stringBuffer; + FILE *in_; + std::string string_buffer_; }; } // namespace kllvm::parser diff --git a/include/kllvm/parser/location.h b/include/kllvm/parser/location.h index 1ef58f1cf..a05ae5c77 100644 --- a/include/kllvm/parser/location.h +++ b/include/kllvm/parser/location.h @@ -14,14 +14,14 @@ class position { void lines(int count = 1) { if (count) { column = 1; - line = add_(line, count, 1); + line = add(line, count, 1); } } - void columns(int count = 1) { column = add_(column, count, 1); } + void columns(int count = 1) { column = add(column, count, 1); } private: - static unsigned add_(unsigned lhs, int rhs, int min) { + static unsigned add(unsigned lhs, int rhs, int min) { return static_cast(std::max(min, static_cast(lhs) + rhs)); } }; diff --git a/include/kllvm/printer/printer.h b/include/kllvm/printer/printer.h index 482c71519..e38df294e 100644 --- a/include/kllvm/printer/printer.h +++ b/include/kllvm/printer/printer.h @@ -8,12 +8,12 @@ namespace kllvm { -sptr -addBrackets(sptr const &, PrettyPrintData const &); +sptr +add_brackets(sptr const &, pretty_print_data const &); -std::ostream &printKORE( - std::ostream &os, std::string const &definitionPath, - std::string const &patternPath, bool hasColor, bool filterSubst, +std::ostream &print_kore( + std::ostream &os, std::string const &definition_path, + std::string const &pattern_path, bool has_color, bool filter_subst, bool pretty = true); } // namespace kllvm diff --git a/include/kllvm/util/temporary_file.h b/include/kllvm/util/temporary_file.h index 73d367deb..286690b38 100644 --- a/include/kllvm/util/temporary_file.h +++ b/include/kllvm/util/temporary_file.h @@ -15,16 +15,16 @@ struct deleter { class temporary_file { private: - int temp_fd; - std::string temp_filename; - std::unique_ptr temp_c_file; - std::optional temp_cpp_file; + int temp_fd_; + std::string temp_filename_; + std::unique_ptr temp_c_file_; + std::optional temp_cpp_file_; public: temporary_file(std::string template_name) - : temp_fd(mkstemp(template_name.data())) - , temp_filename(template_name) { - if (temp_fd == -1) { + : temp_fd_(mkstemp(template_name.data())) + , temp_filename_(template_name) { + if (temp_fd_ == -1) { throw std::runtime_error("Could not create temporary file!"); } } @@ -36,37 +36,37 @@ class temporary_file { temporary_file &operator=(temporary_file &&other) = delete; ~temporary_file() { - close(temp_fd); - remove(temp_filename.data()); + close(temp_fd_); + remove(temp_filename_.data()); } - int descriptor() const { return temp_fd; } + int descriptor() const { return temp_fd_; } - std::string const &filename() const { return temp_filename; } + std::string const &filename() const { return temp_filename_; } FILE *file_pointer(std::string const &mode = "r") { - if (!temp_c_file) { - auto *f = fdopen(temp_fd, mode.data()); + if (!temp_c_file_) { + auto *f = fdopen(temp_fd_, mode.data()); if (f) { - temp_c_file = std::unique_ptr(f); + temp_c_file_ = std::unique_ptr(f); } else { throw std::runtime_error( - "Could not open file " + temp_filename + ": " + "Could not open file " + temp_filename_ + ": " + std::strerror(errno)); } } - return temp_c_file.get(); + return temp_c_file_.get(); } std::ofstream &ofstream() { - if (!temp_cpp_file) { - temp_cpp_file = std::ofstream(temp_filename); + if (!temp_cpp_file_) { + temp_cpp_file_ = std::ofstream(temp_filename_); } - return temp_cpp_file.value(); + return temp_cpp_file_.value(); } void rename(std::string const &new_name) { - std::rename(temp_filename.data(), new_name.data()); + std::rename(temp_filename_.data(), new_name.data()); } }; diff --git a/include/runtime/alloc.h b/include/runtime/alloc.h index 77bee4718..79e35d1e9 100644 --- a/include/runtime/alloc.h +++ b/include/runtime/alloc.h @@ -18,43 +18,43 @@ char oldspace_collection_id(void); size_t youngspace_size(void); // allocates exactly requested bytes into the young generation -void *koreAlloc(size_t requested); +void *kore_alloc(size_t requested); // allocates enough space for a string token whose raw size is requested into // the young generation. rounds up to the nearest 8 bytes and always allocates // at least 16 bytes -void *koreAllocToken(size_t requested); +void *kore_alloc_token(size_t requested); // allocates exactly requested bytes into the old generation -void *koreAllocOld(size_t requested); +void *kore_alloc_old(size_t requested); // allocates enough space for a string token whose raw size is requested into // the old generation. rounds up to the nearest 8 bytes and always allocates at // least 16 bytes -void *koreAllocTokenOld(size_t requested); +void *kore_alloc_token_old(size_t requested); // allocates exactly requested bytes into the always garbage-collected arena. // objects that can potentially survive a collection (i.e. can be reached from // the root during collection) should never be allocated in this arena. -void *koreAllocAlwaysGC(size_t requested); +void *kore_alloc_always_gc(size_t requested); // swaps the two semispace of the young generation as part of garbage collection // if the swapOld flag is set, it also swaps the two semispaces of the old // generation -void koreAllocSwap(bool swapOld); +void kore_alloc_swap(bool swap_old); // resizes the last allocation into the young generation -void *koreResizeLastAlloc(void *oldptr, size_t newrequest, size_t last_size); +void *kore_resize_last_alloc(void *oldptr, size_t newrequest, size_t last_size); // allocator hook for the GMP library -void *koreAllocMP(size_t); +void *kore_alloc_mp(size_t); // reallocator hook for the GMP library -void *koreReallocMP(void *, size_t, size_t); +void *kore_realloc_mp(void *, size_t, size_t); // deallocator hook for the GMP library -void koreFree(void *, size_t); +void kore_free(void *, size_t); // helper allocators for integers and floats // they allocate enough space into the corresponding generation and initialize // the blockheader with the correct length. The size argument is ignored but // exists for uniformity with the standard malloc signature. The caller has to // set the appropriate gc bits. -void *koreAllocInteger(size_t requested); -void *koreAllocFloating(size_t requested); -void *koreAllocIntegerOld(size_t requested); -void *koreAllocFloatingOld(size_t requested); +void *kore_alloc_integer(size_t requested); +void *kore_alloc_floating(size_t requested); +void *kore_alloc_integer_old(size_t requested); +void *kore_alloc_floating_old(size_t requested); #ifdef ALLOC_DBG #define MEM_LOG(...) fprintf(stderr, __VA_ARGS__) diff --git a/include/runtime/arena.h b/include/runtime/arena.h index 9880c341a..8209b1721 100644 --- a/include/runtime/arena.h +++ b/include/runtime/arena.h @@ -34,53 +34,53 @@ using memory_block_header = struct { ((char *)(((uintptr_t)(ptr)-1) & ~(BLOCK_SIZE - 1))) // Resets the given arena. -void arenaReset(struct arena *); +void arena_reset(struct arena *); // Returns the given arena's current allocation semispace ID. // Each arena has 2 semispace IDs one equal to the arena ID and the other equal // to the 1's complement of the arena ID. At any time one of these semispaces // is used for allocation and the other is used for collection. -char getArenaAllocationSemispaceID(const struct arena *); +char get_arena_allocation_semispace_id(const struct arena *); // Returns the given arena's current collection semispace ID. // See above for details. -char getArenaCollectionSemispaceID(const struct arena *); +char get_arena_collection_semispace_id(const struct arena *); // Returns the ID of the semispace where the given address was allocated. // The behavior is undefined if called with an address that has not been // allocated within an arena. -char getArenaSemispaceIDOfObject(void *); +char get_arena_semispace_id_of_object(void *); // Allocates the requested number of bytes as a contiguous region and returns a // pointer to the first allocated byte. // If called with requested size greater than the maximun single allocation // size, the space is allocated in a general (not garbage collected pool). -void *koreArenaAlloc(struct arena *, size_t); +void *kore_arena_alloc(struct arena *, size_t); // Resizes the last allocation as long as the resize does not require a new // block allocation. // Returns the address of the byte following the last newlly allocated byte when // the resize succeeds, returns 0 otherwise. -void *arenaResizeLastAlloc(struct arena *, ssize_t); +void *arena_resize_last_alloc(struct arena *, ssize_t); // Exchanges the current allocation and collection semispaces and clears the new // current allocation semispace by setting its start back to its first block. // It is used before garbage collection. -void arenaSwapAndClear(struct arena *); +void arena_swap_and_clear(struct arena *); // Clears the current allocation space by setting its start back to its first // block. It is used during garbage collection to effectively collect all of the // arena. -void arenaClear(struct arena *); +void arena_clear(struct arena *); // Returns the address of the first byte that belongs in the given arena. // Returns 0 if nothing has been allocated ever in that arena. -char *arenaStartPtr(const struct arena *); +char *arena_start_ptr(const struct arena *); // Returns a pointer to a location holding the address of last allocated // byte in the given arena plus 1. // This address is 0 if nothing has been allocated ever in that arena. -char **arenaEndPtr(struct arena *); +char **arena_end_ptr(struct arena *); // Given a starting pointer to an address allocated in an arena and a size in // bytes, this function returns a pointer to an address allocated in the @@ -91,21 +91,21 @@ char **arenaEndPtr(struct arena *); // 3rd argument: the address of last allocated byte in the arena plus 1 // Return value: the address allocated in the arena after size bytes from the // starting pointer, or 0 if this is equal to the 3rd argument. -char *movePtr(char *, size_t, char const *); +char *move_ptr(char *, size_t, char const *); // Given two pointers to objects allocated in the same arena, return the number // of bytes they are separated by within the virtual block of memory represented // by the blocks of that arena. This difference will include blocks containing // sentinel bytes. Undefined behavior will result if the pointers belong to // different arenas. -ssize_t ptrDiff(char *, char *); +ssize_t ptr_diff(char *, char *); // return the total number of allocatable bytes currently in the arena in its // active semispace. -size_t arenaSize(const struct arena *); +size_t arena_size(const struct arena *); // Deallocates all the memory allocated for registered arenas. -void freeAllMemory(void); +void free_all_memory(void); } #endif // ARENA_H diff --git a/include/runtime/collect.h b/include/runtime/collect.h index b729e9b46..8adfd3491 100644 --- a/include/runtime/collect.h +++ b/include/runtime/collect.h @@ -14,12 +14,12 @@ using BlockEnumerator = std::pair (*)(); // more GC roots other than the top cell of the configuration. // // Example usage: -void registerGCRootsEnumerator(BlockEnumerator); +void register_gc_roots_enumerator(BlockEnumerator); using list_node = immer::detail::rbts::node< - KElem, list::memory_policy, list::bits, list::bits_leaf>; + k_elem, list::memory_policy, list::bits, list::bits_leaf>; using list_impl = immer::detail::rbts::rrbtree< - KElem, list::memory_policy, list::bits, list::bits_leaf>; + k_elem, list::memory_policy, list::bits, list::bits_leaf>; using map_node = map::iterator::node_t; using map_impl = map::iterator::tree_t; using set_node = set::iterator::node_t; @@ -34,9 +34,9 @@ void migrate_list(void *l); void migrate_map(void *m); void migrate_rangemap(void *m); void migrate_set(void *s); -void migrate_collection_node(void **nodePtr); -void setKoreMemoryFunctionsForGMP(void); -void koreCollect(void **, uint8_t, layoutitem *); +void migrate_collection_node(void **node_ptr); +void set_kore_memory_functions_for_gmp(void); +void kore_collect(void **, uint8_t, layoutitem *); } #ifdef GC_DBG diff --git a/include/runtime/header.h b/include/runtime/header.h index 520bcaabc..44a58097f 100644 --- a/include/runtime/header.h +++ b/include/runtime/header.h @@ -25,11 +25,11 @@ #include #include -struct MatchLog { - enum { SUCCESS = 0, FUNCTION, FAIL } kind; +struct match_log { + enum { Success = 0, Function, Fail } kind; char const *function{}; - char const *debugName{}; + char const *debug_name{}; void *result{}; std::vector args{}; @@ -189,29 +189,29 @@ __attribute__((always_inline)) constexpr bool is_heap_block(T const *s) { return is_in_young_gen_hdr(s->h.hdr) || is_in_old_gen_hdr(s->h.hdr); } -class KElem { +class k_elem { public: - KElem() + k_elem() : elem(nullptr) { } - KElem(block *elem) + k_elem(block *elem) : elem(elem) { } - bool operator==(KElem const &other) const { + bool operator==(k_elem const &other) const { return hook_KEQUAL_eq(this->elem, other.elem); } - bool operator!=(KElem const &other) const { return !(*this == other); } + bool operator!=(k_elem const &other) const { return !(*this == other); } - bool operator<(KElem const &other) const { + bool operator<(k_elem const &other) const { return hook_KEQUAL_lt(this->elem, other.elem); } - bool operator>(KElem const &other) const { return other < *this; } + bool operator>(k_elem const &other) const { return other < *this; } - bool operator<=(KElem const &other) const { return !(other < *this); } + bool operator<=(k_elem const &other) const { return !(other < *this); } - bool operator>=(KElem const &other) const { return !(*this < other); } + bool operator>=(k_elem const &other) const { return !(*this < other); } operator block *() const { return elem; } @@ -225,7 +225,7 @@ struct kore_alloc_heap { if (during_gc()) { return ::operator new(size); } - auto *result = (string *)koreAllocToken(size + sizeof(blockheader)); + auto *result = (string *)kore_alloc_token(size + sizeof(blockheader)); init_with_len(result, size); return result->data; } @@ -237,24 +237,27 @@ struct kore_alloc_heap { } }; -struct HashBlock { - size_t operator()(KElem const &block) const noexcept { return hash_k(block); } +struct hash_block { + size_t operator()(k_elem const &block) const noexcept { + return hash_k(block); + } }; -struct KEq { +struct k_eq { bool operator()(block *const &lhs, block *const &rhs) const { return hook_KEQUAL_eq(lhs, rhs); } }; using list = immer::flex_vector< - KElem, immer::memory_policy< - immer::heap_policy, immer::no_refcount_policy, - immer::no_lock_policy>>; -using map - = immer::map, list::memory_policy>; -using set = immer::set, list::memory_policy>; -using rangemap = rng_map::RangeMap; + k_elem, immer::memory_policy< + immer::heap_policy, immer::no_refcount_policy, + immer::no_lock_policy>>; +using map = immer::map< + k_elem, k_elem, hash_block, std::equal_to<>, list::memory_policy>; +using set + = immer::set, list::memory_policy>; +using rangemap = rng_map::RangeMap; using mapiter = struct mapiter { map::iterator curr{}; @@ -286,22 +289,22 @@ using SortSet = set *; using SortRange = block *; using SortRangeMap = rangemap *; -void *constructCompositePattern(uint32_t tag, std::vector &arguments); +void *construct_composite_pattern(uint32_t tag, std::vector &arguments); extern "C" { -block *parseConfiguration(char const *filename); -block *deserializeConfiguration(char *, size_t); +block *parse_configuration(char const *filename); +block *deserialize_configuration(char *, size_t); -void printConfiguration(FILE *file, block *subject); -void printStatistics(FILE *file, uint64_t steps); -string *printConfigurationToString(block *subject); -void printSortedConfigurationToFile( +void print_configuration(FILE *file, block *subject); +void print_statistics(FILE *file, uint64_t steps); +string *print_configuration_to_string(block *subject); +void print_sorted_configuration_to_file( FILE *file, block *subject, char const *sort); -void printConfigurationInternal( +void print_configuration_internal( writer *file, block *subject, char const *sort, bool, void *); -// Returns a shared_ptr to a KOREPattern. The shared_ptr managess the lifetime +// Returns a shared_ptr to a kore_pattern. The shared_ptr managess the lifetime // of the pattern and the pattern will be deallocated when the last reference // to the pattern is destroyed. There may exist references beyond the ones that // are provided to the user via this method, so destroying all values returned @@ -310,9 +313,9 @@ void printConfigurationInternal( // If you need to have access to a function that returns a type with C linkage, // you can use the C bindings, which wrap the return value of this method in // a POD struct. -std::shared_ptr termToKorePattern(block *); -std::shared_ptr -sortedTermToKorePattern(block *, char const *); +std::shared_ptr term_to_kore_pattern(block *); +std::shared_ptr +sorted_term_to_kore_pattern(block *, char const *); // This function injects its argument into KItem before printing, using the sort // argument as the source sort. Doing so allows the term to be pretty-printed @@ -323,69 +326,70 @@ string *debug_print_term(block *subject, char const *sort); mpz_ptr move_int(mpz_t); -void serializeConfigurations( - FILE *file, std::unordered_set results); -void serializeConfiguration( +void serialize_configurations( + FILE *file, std::unordered_set results); +void serialize_configuration( block *subject, char const *sort, char **data_out, size_t *size_out, bool emit_size, bool use_intern); -void serializeConfigurationToFile( +void serialize_configuration_to_file( FILE *file, block *subject, bool emit_size, bool use_intern); -void writeUInt64ToFile(FILE *file, uint64_t i); -void serializeTermToFile( +void write_uint64_to_file(FILE *file, uint64_t i); +void serialize_term_to_file( FILE *file, block *subject, char const *sort, bool use_intern); -void serializeRawTermToFile( +void serialize_raw_term_to_file( FILE *file, void *subject, char const *sort, bool use_intern); -void printVariableToFile(FILE *file, char const *varname); +void print_variable_to_file(FILE *file, char const *varname); // The following functions have to be generated at kompile time // and linked with the interpreter. -uint32_t getTagForSymbolName(char const *symbolname); -struct blockheader getBlockHeaderForSymbol(uint32_t tag); -bool isSymbolAFunction(uint32_t tag); -bool isSymbolABinder(uint32_t tag); -uint32_t getSymbolArity(uint32_t tag); -void storeSymbolChildren(block *symbol, void *children[]); -void *evaluateFunctionSymbol(uint32_t tag, void *arguments[]); -void *getToken(char const *sortname, uint64_t len, char const *tokencontents); -layout *getLayoutData(uint16_t); -uint32_t getInjectionForSortOfTag(uint32_t tag); +uint32_t get_tag_for_symbol_name(char const *symbolname); +struct blockheader get_block_header_for_symbol(uint32_t tag); +bool is_symbol_a_function(uint32_t tag); +bool is_symbol_a_binder(uint32_t tag); +uint32_t get_symbol_arity(uint32_t tag); +void store_symbol_children(block *symbol, void *children[]); +void *evaluate_function_symbol(uint32_t tag, void *arguments[]); +void *get_token(char const *sortname, uint64_t len, char const *tokencontents); +layout *get_layout_data(uint16_t); +uint32_t get_injection_for_sort_of_tag(uint32_t tag); bool hook_STRING_eq(SortString, SortString); -char const *getSymbolNameForTag(uint32_t tag); -char const *getReturnSortForTag(uint32_t tag); -char const **getArgumentSortsForTag(uint32_t tag); -char const *topSort(void); +char const *get_symbol_name_for_tag(uint32_t tag); +char const *get_return_sort_for_tag(uint32_t tag); +char const **get_argument_sorts_for_tag(uint32_t tag); +char const *top_sort(void); -bool symbolIsInstantiation(uint32_t tag); +bool symbol_is_instantiation(uint32_t tag); using visitor = struct { - void (*visitConfig)(writer *, block *, char const *, bool, void *); - void (*visitMap)( + void (*visit_config)(writer *, block *, char const *, bool, void *); + void (*visit_map)( writer *, map *, char const *, char const *, char const *, void *); - void (*visitList)( + void (*visit_list)( writer *, list *, char const *, char const *, char const *, void *); - void (*visitSet)( + void (*visit_set)( writer *, set *, char const *, char const *, char const *, void *); - void (*visitInt)(writer *, mpz_t, char const *, void *); - void (*visitFloat)(writer *, floating *, char const *, void *); - void (*visitBool)(writer *, bool, char const *, void *); - void (*visitStringBuffer)(writer *, stringbuffer *, char const *, void *); - void (*visitMInt)(writer *, size_t *, size_t, char const *, void *); - void (*visitSeparator)(writer *, void *); - void (*visitRangeMap)( + void (*visit_int)(writer *, mpz_t, char const *, void *); + void (*visit_float)(writer *, floating *, char const *, void *); + void (*visit_bool)(writer *, bool, char const *, void *); + void (*visit_string_buffer)(writer *, stringbuffer *, char const *, void *); + void (*visit_m_int)(writer *, size_t *, size_t, char const *, void *); + void (*visit_separator)(writer *, void *); + void (*visit_range_map)( writer *, rangemap *, char const *, char const *, char const *, void *); }; -void printMap( +void print_map( writer *, map *, char const *, char const *, char const *, void *); -void printRangeMap( +void print_range_map( writer *, rangemap *, char const *, char const *, char const *, void *); -void printSet( +void print_set( writer *, set *, char const *, char const *, char const *, void *); -void printList( +void print_list( writer *, list *, char const *, char const *, char const *, void *); -void visitChildren(block *subject, writer *file, visitor *printer, void *state); +void visit_children( + block *subject, writer *file, visitor *printer, void *state); stringbuffer *hook_BUFFER_empty(void); stringbuffer *hook_BUFFER_concat(stringbuffer *buf, string *s); @@ -395,33 +399,35 @@ string *hook_BUFFER_toString(stringbuffer *buf); size_t hook_SET_size_long(set *); -mpz_ptr hook_MINT_import(size_t *i, uint64_t bits, bool isSigned); - -block *dot_k(); +mpz_ptr hook_MINT_import(size_t *i, uint64_t bits, bool is_signed); block *debruijnize(block *); -block *incrementDebruijn(block *); -block *alphaRename(block *); +block *increment_debruijn(block *); +block *alpha_rename(block *); setiter set_iterator(set *); block *set_iterator_next(setiter *); mapiter map_iterator(map *); block *map_iterator_next(mapiter *); -extern uint32_t const first_inj_tag, last_inj_tag; +extern uint32_t const FIRST_INJ_TAG, LAST_INJ_TAG; bool is_injection(block *); block *strip_injection(block *); -block *constructKItemInj(void *subject, char const *sort, bool raw_value); -block *constructRawTerm(void *subject, char const *sort, bool raw_value); +block *construct_k_item_inj(void *subject, char const *sort, bool raw_value); +block *construct_raw_term(void *subject, char const *sort, bool raw_value); + +__attribute__((always_inline)) inline block *dot_k() { + return leaf_block(get_tag_for_symbol_name("dotk{}")); +} } -std::string floatToString(floating const *); +std::string float_to_string(floating const *); void init_float2(floating *, std::string); -std::string intToStringInBase(mpz_t, uint64_t); -std::string intToString(mpz_t); -void printValueOfType( - std::ostream &os, std::string const &definitionPath, void *value, +std::string int_to_string_in_base(mpz_t, uint64_t); +std::string int_to_string(mpz_t); +void print_value_of_type( + std::ostream &os, std::string const &definition_path, void *value, std::string const &type); template diff --git a/lib/ast/AST.cpp b/lib/ast/AST.cpp index 83cb592f8..f2458309a 100644 --- a/lib/ast/AST.cpp +++ b/lib/ast/AST.cpp @@ -20,14 +20,14 @@ using namespace kllvm; -sptr KOREPattern::load(std::string const &filename) { +sptr kore_pattern::load(std::string const &filename) { if (has_binary_kore_header(filename)) { return deserialize_pattern(filename); } - return parser::KOREParser(filename).pattern(); + return parser::kore_parser(filename).pattern(); } -std::string kllvm::decodeKore(std::string kore) { +std::string kllvm::decode_kore(std::string kore) { static std::unordered_map codes; static bool once = true; if (once) { @@ -84,50 +84,50 @@ std::string kllvm::decodeKore(std::string kore) { return result; } -size_t kllvm::hash_value(kllvm::KORESort const &s) { - return HashSort{}(s); +size_t kllvm::hash_value(kllvm::kore_sort const &s) { + return hash_sort{}(s); } -sptr KOREPattern::expandMacros( +sptr kore_pattern::expand_macros( SubsortMap const &subsorts, SymbolMap const &overloads, - std::vector> const &axioms, bool reverse) { - std::set appliedRules; + std::vector> const &axioms, bool reverse) { + std::set applied_rules; - std::set macroSymbols; + std::set macro_symbols; for (auto const &decl : axioms) { - auto *axiom = dynamic_cast(decl.get()); + auto *axiom = dynamic_cast(decl.get()); auto *equals - = dynamic_cast(axiom->getPattern().get()); - auto lhs = equals->getArguments()[reverse ? 1 : 0]; + = dynamic_cast(axiom->get_pattern().get()); + auto lhs = equals->get_arguments()[reverse ? 1 : 0]; - if (auto *lhs_comp = dynamic_cast(lhs.get())) { - macroSymbols.insert(lhs_comp->getConstructor()->getName()); + if (auto *lhs_comp = dynamic_cast(lhs.get())) { + macro_symbols.insert(lhs_comp->get_constructor()->get_name()); } } - return expandMacros( - subsorts, overloads, axioms, reverse, appliedRules, macroSymbols); + return expand_macros( + subsorts, overloads, axioms, reverse, applied_rules, macro_symbols); } -bool KORESortVariable::operator==(KORESort const &other) const { - if (auto const *var = dynamic_cast(&other)) { - return var->name == name; +bool kore_sort_variable::operator==(kore_sort const &other) const { + if (auto const *var = dynamic_cast(&other)) { + return var->name_ == name_; } return false; } -void KORECompositeSort::addArgument(sptr const &Argument) { - arguments.push_back(Argument); +void kore_composite_sort::add_argument(sptr const &argument) { + arguments_.push_back(argument); } -bool KORECompositeSort::operator==(KORESort const &other) const { - if (auto const *sort = dynamic_cast(&other)) { - if (sort->name != name || sort->arguments.size() != arguments.size()) { +bool kore_composite_sort::operator==(kore_sort const &other) const { + if (auto const *sort = dynamic_cast(&other)) { + if (sort->name_ != name_ || sort->arguments_.size() != arguments_.size()) { return false; } - for (int i = 0; i < arguments.size(); ++i) { - if (*sort->arguments[i] != *arguments[i]) { + for (int i = 0; i < arguments_.size(); ++i) { + if (*sort->arguments_[i] != *arguments_[i]) { return false; } } @@ -136,160 +136,161 @@ bool KORECompositeSort::operator==(KORESort const &other) const { return false; } -sptr KORECompositeSort::substitute(substitution const &subst) { +sptr kore_composite_sort::substitute(substitution const &subst) { bool dirty = false; - std::vector> newArgs; - for (auto &arg : arguments) { - auto newArg = arg->substitute(subst); - if (newArg != arg) { + std::vector> new_args; + for (auto &arg : arguments_) { + auto new_arg = arg->substitute(subst); + if (new_arg != arg) { dirty = true; } - newArgs.push_back(newArg); + new_args.push_back(new_arg); } if (dirty) { - sptr retval = Create(name); - retval->arguments = newArgs; + sptr retval = create(name_); + retval->arguments_ = new_args; return retval; } return shared_from_this(); } -ValueType KORECompositeSort::getCategory(KOREDefinition *definition) { - if (category.cat != SortCategory::Uncomputed) { - return category; +value_type kore_composite_sort::get_category(kore_definition *definition) { + if (category_.cat != sort_category::Uncomputed) { + return category_; } - std::string name = getHook(definition); + std::string name = get_hook(definition); if (name == "MINT.MInt") { - if (auto *param = dynamic_cast(arguments[0].get())) { - auto const &att = definition->getSortDeclarations() - .at(param->getName()) + if (auto *param + = dynamic_cast(arguments_[0].get())) { + auto const &att = definition->get_sort_declarations() + .at(param->get_name()) ->attributes(); - auto const &natAtt = att.get(attribute_set::key::nat); - assert(natAtt->getArguments().size() == 1); - auto *strPattern - = dynamic_cast(natAtt->getArguments()[0].get()); - name = name + " " + strPattern->getContents(); + auto const &nat_att = att.get(attribute_set::key::Nat); + assert(nat_att->get_arguments().size() == 1); + auto *str_pattern = dynamic_cast( + nat_att->get_arguments()[0].get()); + name = name + " " + str_pattern->get_contents(); } else { print(std::cerr); abort(); } } - category = getCategory(name); - return category; + category_ = get_category(name); + return category_; } -std::string KORECompositeSort::getHook(KOREDefinition *definition) const { +std::string kore_composite_sort::get_hook(kore_definition *definition) const { auto const &att - = definition->getSortDeclarations().at(this->getName())->attributes(); - if (!att.contains(attribute_set::key::hook)) { + = definition->get_sort_declarations().at(this->get_name())->attributes(); + if (!att.contains(attribute_set::key::Hook)) { return "STRING.String"; } - auto const &hookAtt = att.get(attribute_set::key::hook); - assert(hookAtt->getArguments().size() == 1); - auto *strPattern - = dynamic_cast(hookAtt->getArguments()[0].get()); - return strPattern->getContents(); + auto const &hook_att = att.get(attribute_set::key::Hook); + assert(hook_att->get_arguments().size() == 1); + auto *str_pattern + = dynamic_cast(hook_att->get_arguments()[0].get()); + return str_pattern->get_contents(); } -ValueType KORECompositeSort::getCategory(std::string const &hookName) { - SortCategory category = SortCategory::Uncomputed; +value_type kore_composite_sort::get_category(std::string const &hook_name) { + sort_category category = sort_category::Uncomputed; uint64_t bits = 0; - if (hookName == "MAP.Map") { - category = SortCategory::Map; - } else if (hookName == "RANGEMAP.RangeMap") { - category = SortCategory::RangeMap; - } else if (hookName == "LIST.List") { - category = SortCategory::List; - } else if (hookName == "SET.Set") { - category = SortCategory::Set; - } else if (hookName == "INT.Int") { - category = SortCategory::Int; - } else if (hookName == "FLOAT.Float") { - category = SortCategory::Float; - } else if (hookName == "BUFFER.StringBuffer") { - category = SortCategory::StringBuffer; - } else if (hookName == "BOOL.Bool") { - category = SortCategory::Bool; - } else if (hookName == "KVAR.KVar") { - category = SortCategory::Variable; + if (hook_name == "MAP.Map") { + category = sort_category::Map; + } else if (hook_name == "RANGEMAP.RangeMap") { + category = sort_category::RangeMap; + } else if (hook_name == "LIST.List") { + category = sort_category::List; + } else if (hook_name == "SET.Set") { + category = sort_category::Set; + } else if (hook_name == "INT.Int") { + category = sort_category::Int; + } else if (hook_name == "FLOAT.Float") { + category = sort_category::Float; + } else if (hook_name == "BUFFER.StringBuffer") { + category = sort_category::StringBuffer; + } else if (hook_name == "BOOL.Bool") { + category = sort_category::Bool; + } else if (hook_name == "KVAR.KVar") { + category = sort_category::Variable; // we expect the "hook" of a MInt to be of the form "MINT.MInt N" for some // bitwidth N - } else if (hookName.substr(0, 10) == "MINT.MInt ") { - category = SortCategory::MInt; - bits = std::stoi(hookName.substr(10)); + } else if (hook_name.substr(0, 10) == "MINT.MInt ") { + category = sort_category::MInt; + bits = std::stoi(hook_name.substr(10)); } else { - category = SortCategory::Symbol; + category = sort_category::Symbol; } return {category, bits}; } -void KORESymbol::addArgument(sptr const &Argument) { - arguments.push_back(Argument); +void kore_symbol::add_argument(sptr const &argument) { + arguments_.push_back(argument); } -void KORESymbol::addFormalArgument(sptr const &Argument) { - formalArguments.push_back(Argument); +void kore_symbol::add_formal_argument(sptr const &argument) { + formal_arguments_.push_back(argument); } -void KORESymbol::addSort(sptr Sort) { - sort = std::move(Sort); +void kore_symbol::add_sort(sptr sort) { + this->sort_ = std::move(sort); } -bool KORESymbol::operator==(KORESymbol const &other) const { - if (name != other.name || arguments.size() != other.arguments.size()) { +bool kore_symbol::operator==(kore_symbol const &other) const { + if (name_ != other.name_ || arguments_.size() != other.arguments_.size()) { return false; } - for (int i = 0; i < arguments.size(); ++i) { - if (*arguments[i] != *other.arguments[i]) { + for (int i = 0; i < arguments_.size(); ++i) { + if (*arguments_[i] != *other.arguments_[i]) { return false; } } return true; } -std::string KORESymbol::layoutString(KOREDefinition *definition) const { +std::string kore_symbol::layout_string(kore_definition *definition) const { std::string result; - for (auto const &arg : arguments) { - auto *sort = dynamic_cast(arg.get()); - ValueType cat = sort->getCategory(definition); + for (auto const &arg : arguments_) { + auto *sort = dynamic_cast(arg.get()); + value_type cat = sort->get_category(definition); switch (cat.cat) { - case SortCategory::Map: result.push_back('1'); break; - case SortCategory::RangeMap: result.push_back('b'); break; - case SortCategory::List: result.push_back('2'); break; - case SortCategory::Set: result.push_back('3'); break; - case SortCategory::Int: result.push_back('4'); break; - case SortCategory::Float: result.push_back('5'); break; - case SortCategory::StringBuffer: result.push_back('6'); break; - case SortCategory::Bool: result.push_back('7'); break; - case SortCategory::Variable: result.push_back('8'); break; - case SortCategory::MInt: + case sort_category::Map: result.push_back('1'); break; + case sort_category::RangeMap: result.push_back('b'); break; + case sort_category::List: result.push_back('2'); break; + case sort_category::Set: result.push_back('3'); break; + case sort_category::Int: result.push_back('4'); break; + case sort_category::Float: result.push_back('5'); break; + case sort_category::StringBuffer: result.push_back('6'); break; + case sort_category::Bool: result.push_back('7'); break; + case sort_category::Variable: result.push_back('8'); break; + case sort_category::MInt: result.append("_" + std::to_string(cat.bits) + "_"); - case SortCategory::Symbol: result.push_back('0'); break; - case SortCategory::Uncomputed: abort(); + case sort_category::Symbol: result.push_back('0'); break; + case sort_category::Uncomputed: abort(); } } return result; } -bool KORECompositeSort::isConcrete() const { - return std::all_of(arguments.begin(), arguments.end(), [](auto const &sort) { - return sort->isConcrete(); - }); +bool kore_composite_sort::is_concrete() const { + return std::all_of( + arguments_.begin(), arguments_.end(), + [](auto const &sort) { return sort->is_concrete(); }); } -bool KORESymbol::isConcrete() const { - return std::all_of(arguments.begin(), arguments.end(), [](auto const &sort) { - return sort->isConcrete(); - }); +bool kore_symbol::is_concrete() const { + return std::all_of( + arguments_.begin(), arguments_.end(), + [](auto const &sort) { return sort->is_concrete(); }); } -bool KORESymbol::isPolymorphic() const { - return std::none_of(arguments.begin(), arguments.end(), [](auto const &sort) { - return sort->isConcrete(); - }); +bool kore_symbol::is_polymorphic() const { + return std::none_of( + arguments_.begin(), arguments_.end(), + [](auto const &sort) { return sort->is_concrete(); }); } -static std::unordered_set BUILTINS{ +static std::unordered_set builtins{ "\\and", "\\not", "\\or", @@ -313,126 +314,129 @@ static std::unordered_set BUILTINS{ "allPathGlobally", }; -bool KORESymbol::isBuiltin() const { - return BUILTINS.contains(name); +bool kore_symbol::is_builtin() const { + return builtins.contains(name_); } -void KORESymbol::instantiateSymbol(KORESymbolDeclaration *decl) { - std::vector> instantiated; +void kore_symbol::instantiate_symbol(kore_symbol_declaration *decl) { + std::vector> instantiated; int i = 0; - KORESort::substitution vars; - for (auto const &var : decl->getObjectSortVariables()) { - vars.emplace(*var, formalArguments[i++]); + kore_sort::substitution vars; + for (auto const &var : decl->get_object_sort_variables()) { + vars.emplace(*var, formal_arguments_[i++]); } - for (auto const &sort : decl->getSymbol()->getArguments()) { + for (auto const &sort : decl->get_symbol()->get_arguments()) { instantiated.push_back(sort->substitute(vars)); } - auto returnSort = decl->getSymbol()->sort; - sort = returnSort->substitute(vars); + auto return_sort = decl->get_symbol()->sort_; + sort_ = return_sort->substitute(vars); - arguments = instantiated; + arguments_ = instantiated; } -std::string KOREVariable::getName() const { - return name; +std::string kore_variable::get_name() const { + return name_; } -std::string KOREVariablePattern::getName() const { - return name->getName(); +std::string kore_variable_pattern::get_name() const { + return name_->get_name(); } -void KORECompositePattern::addArgument(sptr const &Argument) { - arguments.push_back(Argument); +void kore_composite_pattern::add_argument(sptr const &argument) { + arguments_.push_back(argument); } -void KORECompositePattern::markSymbols( - std::map> &map) { - if (!constructor->isBuiltin()) { - if (!map.contains(constructor->getName())) { - map.emplace(constructor->getName(), std::vector{}); +void kore_composite_pattern::mark_symbols( + std::map> &map) { + if (!constructor_->is_builtin()) { + if (!map.contains(constructor_->get_name())) { + map.emplace(constructor_->get_name(), std::vector{}); } - map.at(constructor->getName()).push_back(constructor.get()); + map.at(constructor_->get_name()).push_back(constructor_.get()); } - for (auto &arg : arguments) { - arg->markSymbols(map); + for (auto &arg : arguments_) { + arg->mark_symbols(map); } } -void KORECompositePattern::markVariables( - std::map &map) { - for (auto &arg : arguments) { - arg->markVariables(map); +void kore_composite_pattern::mark_variables( + std::map &map) { + for (auto &arg : arguments_) { + arg->mark_variables(map); } } -sptr KORECompositePattern::substitute(substitution const &subst) { - if (arguments.empty()) { +sptr +kore_composite_pattern::substitute(substitution const &subst) { + if (arguments_.empty()) { return shared_from_this(); } - auto ptr = KORECompositePattern::Create(constructor.get()); - auto name = constructor->getName(); + auto ptr = kore_composite_pattern::create(constructor_.get()); + auto name = constructor_->get_name(); if (name == "\\forall" || name == "\\exists") { - ptr->addArgument(arguments[0]); - auto newSubst = subst; - newSubst.erase( - dynamic_cast(arguments[0].get())->getName()); - ptr->addArgument(arguments[1]->substitute(newSubst)); + ptr->add_argument(arguments_[0]); + auto new_subst = subst; + new_subst.erase( + dynamic_cast(arguments_[0].get())->get_name()); + ptr->add_argument(arguments_[1]->substitute(new_subst)); return ptr; } - for (auto &arg : arguments) { - ptr->addArgument(arg->substitute(subst)); + for (auto &arg : arguments_) { + ptr->add_argument(arg->substitute(subst)); } return ptr; } -sptr KORECompositePattern::expandAliases(KOREDefinition *def) { - if (def->getAliasDeclarations().contains(constructor->getName())) { - auto *alias = def->getAliasDeclarations().at(constructor->getName()); - auto subst = alias->getSubstitution(this); - return alias->getPattern()->substitute(subst)->expandAliases(def); +sptr +kore_composite_pattern::expand_aliases(kore_definition *def) { + if (def->get_alias_declarations().contains(constructor_->get_name())) { + auto *alias = def->get_alias_declarations().at(constructor_->get_name()); + auto subst = alias->get_substitution(this); + return alias->get_pattern()->substitute(subst)->expand_aliases(def); } - if (arguments.empty()) { + if (arguments_.empty()) { return shared_from_this(); } - auto ptr = KORECompositePattern::Create(constructor.get()); - for (auto &arg : arguments) { - ptr->addArgument(arg->expandAliases(def)); + auto ptr = kore_composite_pattern::create(constructor_.get()); + for (auto &arg : arguments_) { + ptr->add_argument(arg->expand_aliases(def)); } return ptr; } static int indent = 0; -static bool atNewLine = true; +static bool at_new_line = true; static void newline(std::ostream &out) { out << std::endl; - atNewLine = true; + at_new_line = true; } -static void printIndent(std::ostream &out) { +static void print_indent(std::ostream &out) { constexpr auto indent_size = 2; - if (atNewLine) { + if (at_new_line) { for (int i = 0; i < indent_size * indent; i++) { out << ' '; } - atNewLine = false; + at_new_line = false; } } static void append(std::ostream &out, char c) { - printIndent(out); + print_indent(out); out << c; } static void append(std::ostream &out, std::string const &str) { - printIndent(out); + print_indent(out); out << str; } static void color( - std::ostream &out, std::string const &color, PrettyPrintData const &data) { - if (data.hasColor) { + std::ostream &out, std::string const &color, + pretty_print_data const &data) { + if (data.has_color) { static bool once = true; static std::map colors; if (once) { @@ -668,59 +672,59 @@ std::string enquote(std::string const &str) { return result; } -void KORESortVariable::prettyPrint(std::ostream &out) const { - append(out, name); +void kore_sort_variable::pretty_print(std::ostream &out) const { + append(out, name_); } -void KORECompositeSort::prettyPrint(std::ostream &out) const { - append(out, name.substr(4)); - if (!arguments.empty()) { +void kore_composite_sort::pretty_print(std::ostream &out) const { + append(out, name_.substr(4)); + if (!arguments_.empty()) { append(out, '{'); std::string conn; - for (auto const &sort : arguments) { + for (auto const &sort : arguments_) { append(out, conn); - sort->prettyPrint(out); + sort->pretty_print(out); conn = ","; } append(out, '}'); } } -void KOREVariablePattern::prettyPrint( - std::ostream &out, PrettyPrintData const &data) const { - append(out, decodeKore(getName().substr(3))); +void kore_variable_pattern::pretty_print( + std::ostream &out, pretty_print_data const &data) const { + append(out, decode_kore(get_name().substr(3))); append(out, ':'); - sort->prettyPrint(out); + sort_->pretty_print(out); } // NOLINTNEXTLINE(*-cognitive-complexity) -void KORECompositePattern::prettyPrint( - std::ostream &out, PrettyPrintData const &data) const { - std::string name = getConstructor()->getName(); +void kore_composite_pattern::pretty_print( + std::ostream &out, pretty_print_data const &data) const { + std::string name = get_constructor()->get_name(); if (name == "\\dv") { - auto *s = dynamic_cast( - getConstructor()->getFormalArguments()[0].get()); - bool hasHook = data.hook.contains(s->getName()); - auto *str = dynamic_cast(arguments[0].get()); - if (hasHook) { - auto hook = data.hook.at(s->getName()); + auto *s = dynamic_cast( + get_constructor()->get_formal_arguments()[0].get()); + bool has_hook = data.hook.contains(s->get_name()); + auto *str = dynamic_cast(arguments_[0].get()); + if (has_hook) { + auto hook = data.hook.at(s->get_name()); if (hook == "STRING.String") { - append(out, enquote(str->getContents())); + append(out, enquote(str->get_contents())); } else if (hook == "BYTES.Bytes") { append(out, 'b'); - append(out, enquote(str->getContents())); + append(out, enquote(str->get_contents())); } else { - append(out, str->getContents()); + append(out, str->get_contents()); } } else { - append(out, str->getContents()); + append(out, str->get_contents()); } return; } if (data.format.contains(name)) { auto format = data.format.at(name); - int localIndent = 0; - int localColor = 0; + int local_indent = 0; + int local_color = 0; for (int i = 0; i < format.length(); ++i) { char c = format[i]; if (c == '%') { @@ -733,22 +737,22 @@ void KORECompositePattern::prettyPrint( case 'n': newline(out); break; case 'i': indent++; - localIndent++; + local_indent++; break; case 'd': indent--; - localIndent--; + local_indent--; break; case 'c': if (data.colors.contains(name)) { - if (localColor >= data.colors.at(name).size()) { + if (local_color >= data.colors.at(name).size()) { abort(); } - color(out, data.colors.at(name)[localColor++], data); + color(out, data.colors.at(name)[local_color++], data); } break; case 'r': - if (data.hasColor) { + if (data.has_color) { append(out, RESET_COLOR); } break; @@ -769,29 +773,29 @@ void KORECompositePattern::prettyPrint( } i--; int idx = std::stoi(buf); - if (idx == 0 || idx > arguments.size()) { + if (idx == 0 || idx > arguments_.size()) { abort(); } - KOREPattern *inner = arguments[idx - 1].get(); + kore_pattern *inner = arguments_[idx - 1].get(); bool assoc = false; - if (auto *app = dynamic_cast(inner)) { - if (app->getConstructor()->getName() == constructor->getName() + if (auto *app = dynamic_cast(inner)) { + if (app->get_constructor()->get_name() == constructor_->get_name() && data.assoc.contains(name)) { assoc = true; } if (assoc) { - for (int j = 0; j < localIndent; j++) { + for (int j = 0; j < local_indent; j++) { indent--; } } - inner->prettyPrint(out, data); + inner->pretty_print(out, data); if (assoc) { - for (int j = 0; j < localIndent; j++) { + for (int j = 0; j < local_indent; j++) { indent++; } } } else { - inner->prettyPrint(out, data); + inner->pretty_print(out, data); } break; } @@ -806,18 +810,18 @@ void KORECompositePattern::prettyPrint( } } -struct CompareFirst { - static bool isDigit(char c) { return c >= '0' && c <= '9'; } +struct compare_first { + static bool is_digit(char c) { return c >= '0' && c <= '9'; } - static std::string getChunk(std::string s, size_t slength, size_t marker) { + static std::string get_chunk(std::string s, size_t slength, size_t marker) { std::string chunk; char c = s[marker]; chunk.push_back(c); marker++; - if (isDigit(c)) { + if (is_digit(c)) { while (marker < slength) { c = s[marker]; - if (!isDigit(c)) { + if (!is_digit(c)) { break; } chunk.push_back(c); @@ -826,7 +830,7 @@ struct CompareFirst { } else { while (marker < slength) { c = s[marker]; - if (isDigit(c)) { + if (is_digit(c)) { break; } chunk.push_back(c); @@ -840,29 +844,29 @@ struct CompareFirst { bool operator()(std::pair a, std::pair b) { std::string s1 = a.first; std::string s2 = b.first; - size_t thisMarker = 0; - size_t thatMarker = 0; + size_t this_marker = 0; + size_t that_marker = 0; size_t s1length = s1.length(); size_t s2length = s2.length(); - while (thisMarker < s1length && thatMarker < s2length) { - std::string thisChunk = getChunk(s1, s1length, thisMarker); - thisMarker += thisChunk.length(); - std::string thatChunk = getChunk(s2, s2length, thatMarker); - thatMarker += thatChunk.length(); + while (this_marker < s1length && that_marker < s2length) { + std::string this_chunk = get_chunk(s1, s1length, this_marker); + this_marker += this_chunk.length(); + std::string that_chunk = get_chunk(s2, s2length, that_marker); + that_marker += that_chunk.length(); int result = 0; - if (isDigit(thisChunk[0]) && isDigit(thatChunk[0])) { - size_t thisChunkLength = thisChunk.length(); - result = thisChunkLength - thatChunk.length(); + if (is_digit(this_chunk[0]) && is_digit(that_chunk[0])) { + size_t this_chunk_length = this_chunk.length(); + result = this_chunk_length - that_chunk.length(); if (result == 0) { - for (int i = 0; i < thisChunkLength; i++) { - result = thisChunk[i] - thatChunk[i]; + for (int i = 0; i < this_chunk_length; i++) { + result = this_chunk[i] - that_chunk[i]; if (result != 0) { return result < 0; } } } } else { - result = thisChunk.compare(thatChunk); + result = this_chunk.compare(that_chunk); } if (result != 0) { return result < 0; @@ -873,11 +877,11 @@ struct CompareFirst { }; void kllvm::flatten( - KORECompositePattern *pat, std::string const &name, - std::vector> &result) { - for (auto const &arg : pat->getArguments()) { - if (auto *pat2 = dynamic_cast(arg.get())) { - if (pat2->getConstructor()->getName() == name) { + kore_composite_pattern *pat, std::string const &name, + std::vector> &result) { + for (auto const &arg : pat->get_arguments()) { + if (auto *pat2 = dynamic_cast(arg.get())) { + if (pat2->get_constructor()->get_name() == name) { flatten(pat2, name, result); } else { result.push_back(arg); @@ -888,55 +892,55 @@ void kllvm::flatten( } } -sptr -KORECompositePattern::sortCollections(PrettyPrintData const &data) { - if (arguments.empty()) { +sptr +kore_composite_pattern::sort_collections(pretty_print_data const &data) { + if (arguments_.empty()) { return shared_from_this(); } - std::string name = getConstructor()->getName(); + std::string name = get_constructor()->get_name(); if (data.comm.contains(name) && data.assoc.contains(name)) { - std::vector> items; + std::vector> items; flatten(this, name, items); - std::vector>> printed; - int oldIndent = indent; - bool oldAtNewLine = atNewLine; - atNewLine = false; + std::vector>> printed; + int old_indent = indent; + bool old_at_new_line = at_new_line; + at_new_line = false; indent = 0; - PrettyPrintData newData = data; - newData.hasColor = false; + pretty_print_data new_data = data; + new_data.has_color = false; for (auto &item : items) { - std::ostringstream Out; - item = item->sortCollections(data); - item->prettyPrint(Out, newData); - printed.emplace_back(Out.str(), item); + std::ostringstream out; + item = item->sort_collections(data); + item->pretty_print(out, new_data); + printed.emplace_back(out.str(), item); } - indent = oldIndent; - atNewLine = oldAtNewLine; - std::sort(printed.begin(), printed.end(), CompareFirst{}); + indent = old_indent; + at_new_line = old_at_new_line; + std::sort(printed.begin(), printed.end(), compare_first{}); items.clear(); for (auto &item : printed) { items.push_back(item.second); } - sptr result = items[0]; + sptr result = items[0]; for (int i = 1; i < items.size(); ++i) { - sptr tmp - = KORECompositePattern::Create(constructor.get()); - tmp->addArgument(result); - tmp->addArgument(items[i]); + sptr tmp + = kore_composite_pattern::create(constructor_.get()); + tmp->add_argument(result); + tmp->add_argument(items[i]); result = tmp; } return result; } - sptr result - = KORECompositePattern::Create(constructor.get()); - for (auto &arg : arguments) { - result->addArgument(arg->sortCollections(data)); + sptr result + = kore_composite_pattern::create(constructor_.get()); + for (auto &arg : arguments_) { + result->add_argument(arg->sort_collections(data)); } return result; } -std::set KOREPattern::gatherSingletonVars() { - auto counts = gatherVarCounts(); +std::set kore_pattern::gather_singleton_vars() { + auto counts = gather_var_counts(); std::set result; for (auto const &entry : counts) { if (entry.second == 1) { @@ -946,91 +950,94 @@ std::set KOREPattern::gatherSingletonVars() { return result; } -std::map KORECompositePattern::gatherVarCounts() { +std::map kore_composite_pattern::gather_var_counts() { std::map result; - for (auto &arg : arguments) { - auto childResult = arg->gatherVarCounts(); - for (auto const &entry : childResult) { + for (auto &arg : arguments_) { + auto child_result = arg->gather_var_counts(); + for (auto const &entry : child_result) { result[entry.first] += entry.second; } } return result; } -sptr KORECompositePattern::dedupeDisjuncts() { - if (constructor->getName() != "\\or") { +sptr kore_composite_pattern::dedupe_disjuncts() { + if (constructor_->get_name() != "\\or") { return shared_from_this(); } - std::vector> items; - std::vector> dedupedItems; + std::vector> items; + std::vector> deduped_items; flatten(this, "\\or", items); std::set printed; for (auto const &item : items) { if (printed.insert(ast_to_string(*item)).second) { - dedupedItems.push_back(item); + deduped_items.push_back(item); } } - sptr result = dedupedItems[0]; - for (int i = 1; i < dedupedItems.size(); ++i) { - sptr tmp - = KORECompositePattern::Create(constructor.get()); - tmp->addArgument(result); - tmp->addArgument(dedupedItems[i]); + sptr result = deduped_items[0]; + for (int i = 1; i < deduped_items.size(); ++i) { + sptr tmp + = kore_composite_pattern::create(constructor_.get()); + tmp->add_argument(result); + tmp->add_argument(deduped_items[i]); result = tmp; } return result; } // NOLINTNEXTLINE(*-cognitive-complexity) -sptr KORECompositePattern::filterSubstitution( - PrettyPrintData const &data, std::set const &vars) { - if (constructor->getName() == "\\equals") { - if (auto *var = dynamic_cast(arguments[0].get())) { +sptr kore_composite_pattern::filter_substitution( + pretty_print_data const &data, std::set const &vars) { + if (constructor_->get_name() == "\\equals") { + if (auto *var + = dynamic_cast(arguments_[0].get())) { std::ostringstream ss; - int oldIndent = indent; - bool oldAtNewLine = atNewLine; - atNewLine = true; + int old_indent = indent; + bool old_at_new_line = at_new_line; + at_new_line = true; indent = 0; - var->prettyPrint(ss, data); - indent = oldIndent; - atNewLine = oldAtNewLine; + var->pretty_print(ss, data); + indent = old_indent; + at_new_line = old_at_new_line; std::string name = ss.str(); - if (vars.contains(var->getName()) + if (vars.contains(var->get_name()) && (name[0] == '_' || (name.size() > 1 && (name[0] == '@' || name[0] == '!' || name[0] == '?') && name[1] == '_'))) { - sptr unit = KORECompositePattern::Create("\\top"); - unit->getConstructor()->addFormalArgument( - constructor->getFormalArguments()[1]); + sptr unit + = kore_composite_pattern::create("\\top"); + unit->get_constructor()->add_formal_argument( + constructor_->get_formal_arguments()[1]); return unit; } return shared_from_this(); } return shared_from_this(); } - if (constructor->getName() == "\\and" || constructor->getName() == "\\or") { - sptr result - = KORECompositePattern::Create(constructor.get()); - for (auto &arg : arguments) { - if (constructor->getName() == "\\or") { - std::set vars = arg->gatherSingletonVars(); - result->addArgument(arg->filterSubstitution(data, vars)); + if (constructor_->get_name() == "\\and" + || constructor_->get_name() == "\\or") { + sptr result + = kore_composite_pattern::create(constructor_.get()); + for (auto &arg : arguments_) { + if (constructor_->get_name() == "\\or") { + std::set vars = arg->gather_singleton_vars(); + result->add_argument(arg->filter_substitution(data, vars)); } else { - result->addArgument(arg->filterSubstitution(data, vars)); + result->add_argument(arg->filter_substitution(data, vars)); } } - if (constructor->getName() == "\\and") { - if (auto *composite = dynamic_cast( - result->getArguments()[0].get())) { - if (composite->getConstructor()->getName() == "\\top") { - return result->getArguments()[1]; + if (constructor_->get_name() == "\\and") { + if (auto *composite = dynamic_cast( + result->get_arguments()[0].get())) { + if (composite->get_constructor()->get_name() == "\\top") { + return result->get_arguments()[1]; } } - if (auto *composite = dynamic_cast( - result->getArguments()[1].get())) { - if (composite->getConstructor()->getName() == "\\top") { - return result->getArguments()[0]; + if (auto *composite = dynamic_cast( + result->get_arguments()[1].get())) { + if (composite->get_constructor()->get_name() == "\\top") { + return result->get_arguments()[0]; } } } @@ -1039,43 +1046,43 @@ sptr KORECompositePattern::filterSubstitution( return shared_from_this(); } -sptr KORECompositePattern::desugarAssociative() { - if (constructor->getName() == "\\left-assoc") { +sptr kore_composite_pattern::desugar_associative() { + if (constructor_->get_name() == "\\left-assoc") { if (auto *comp_arg - = dynamic_cast(arguments[0].get())) { - auto accum = comp_arg->arguments[0]->desugarAssociative(); + = dynamic_cast(arguments_[0].get())) { + auto accum = comp_arg->arguments_[0]->desugar_associative(); - for (auto i = 1U; i < comp_arg->arguments.size(); i++) { + for (auto i = 1U; i < comp_arg->arguments_.size(); i++) { auto new_accum - = KORECompositePattern::Create(comp_arg->getConstructor()); - new_accum->addArgument(accum); - new_accum->addArgument(comp_arg->arguments[i]->desugarAssociative()); - accum = ptr(new_accum.release()); + = kore_composite_pattern::create(comp_arg->get_constructor()); + new_accum->add_argument(accum); + new_accum->add_argument(comp_arg->arguments_[i]->desugar_associative()); + accum = ptr(new_accum.release()); } return accum; } - } else if (constructor->getName() == "\\right-assoc") { + } else if (constructor_->get_name() == "\\right-assoc") { if (auto *comp_arg - = dynamic_cast(arguments[0].get())) { - auto accum = comp_arg->arguments[comp_arg->arguments.size() - 1] - ->desugarAssociative(); + = dynamic_cast(arguments_[0].get())) { + auto accum = comp_arg->arguments_[comp_arg->arguments_.size() - 1] + ->desugar_associative(); - for (int i = comp_arg->arguments.size() - 2; i >= 0; i--) { + for (int i = comp_arg->arguments_.size() - 2; i >= 0; i--) { auto new_accum - = KORECompositePattern::Create(comp_arg->getConstructor()); - new_accum->addArgument(comp_arg->arguments[i]->desugarAssociative()); - new_accum->addArgument(accum); - accum = ptr(new_accum.release()); + = kore_composite_pattern::create(comp_arg->get_constructor()); + new_accum->add_argument(comp_arg->arguments_[i]->desugar_associative()); + new_accum->add_argument(accum); + accum = ptr(new_accum.release()); } return accum; } } else { - auto result = KORECompositePattern::Create(constructor.get()); + auto result = kore_composite_pattern::create(constructor_.get()); - for (auto &arg : arguments) { - result->addArgument(arg->desugarAssociative()); + for (auto &arg : arguments_) { + result->add_argument(arg->desugar_associative()); } return result; @@ -1084,72 +1091,74 @@ sptr KORECompositePattern::desugarAssociative() { return shared_from_this(); } -sptr KORECompositePattern::unflattenAndOr() { - if ((constructor->getName() == "\\and" || constructor->getName() == "\\or") - && arguments.size() != 2) { - if (arguments.size() == 1) { - return arguments[0]->unflattenAndOr(); +sptr kore_composite_pattern::unflatten_and_or() { + if ((constructor_->get_name() == "\\and" + || constructor_->get_name() == "\\or") + && arguments_.size() != 2) { + if (arguments_.size() == 1) { + return arguments_[0]->unflatten_and_or(); } - auto accum = arguments[0]->unflattenAndOr(); + auto accum = arguments_[0]->unflatten_and_or(); - for (auto i = 1U; i < arguments.size(); i++) { - auto new_accum = KORECompositePattern::Create(constructor.get()); - new_accum->addArgument(accum); - new_accum->addArgument(arguments[i]->unflattenAndOr()); - accum = ptr(new_accum.release()); + for (auto i = 1U; i < arguments_.size(); i++) { + auto new_accum = kore_composite_pattern::create(constructor_.get()); + new_accum->add_argument(accum); + new_accum->add_argument(arguments_[i]->unflatten_and_or()); + accum = ptr(new_accum.release()); } return accum; } - auto result = KORECompositePattern::Create(constructor.get()); + auto result = kore_composite_pattern::create(constructor_.get()); - for (auto &arg : arguments) { - result->addArgument(arg->unflattenAndOr()); + for (auto &arg : arguments_) { + result->add_argument(arg->unflatten_and_or()); } return result; } -sptr KORECompositePattern::expandMacros( +sptr kore_composite_pattern::expand_macros( SubsortMap const &subsorts, SymbolMap const &overloads, - std::vector> const ¯os, bool reverse, - std::set &appliedRules, std::set const ¯oSymbols) { - sptr applied - = KORECompositePattern::Create(constructor.get()); - for (auto &arg : arguments) { - std::set dummyApplied; - applied->addArgument(arg->expandMacros( - subsorts, overloads, macros, reverse, dummyApplied, macroSymbols)); - } - - if (macroSymbols.find(constructor->getName()) == macroSymbols.end()) { + std::vector> const ¯os, bool reverse, + std::set &applied_rules, + std::set const ¯o_symbols) { + sptr applied + = kore_composite_pattern::create(constructor_.get()); + for (auto &arg : arguments_) { + std::set dummy_applied; + applied->add_argument(arg->expand_macros( + subsorts, overloads, macros, reverse, dummy_applied, macro_symbols)); + } + + if (macro_symbols.find(constructor_->get_name()) == macro_symbols.end()) { return applied; } size_t i = 0; for (auto const &decl : macros) { - if ((decl->attributes().contains(attribute_set::key::macro) - || decl->attributes().contains(attribute_set::key::macro_rec)) + if ((decl->attributes().contains(attribute_set::key::Macro) + || decl->attributes().contains(attribute_set::key::MacroRec)) && reverse) { i++; continue; } - auto *axiom = dynamic_cast(decl.get()); + auto *axiom = dynamic_cast(decl.get()); auto *equals - = dynamic_cast(axiom->getPattern().get()); - auto lhs = equals->arguments[reverse ? 1 : 0]; - auto rhs = equals->arguments[reverse ? 0 : 1]; + = dynamic_cast(axiom->get_pattern().get()); + auto lhs = equals->arguments_[reverse ? 1 : 0]; + auto rhs = equals->arguments_[reverse ? 0 : 1]; substitution subst; bool matches = lhs->matches(subst, subsorts, overloads, applied); if (matches - && (decl->attributes().contains(attribute_set::key::macro_rec) - || decl->attributes().contains(attribute_set::key::alias_rec) - || !appliedRules.contains(i))) { - std::set oldAppliedRules = appliedRules; - appliedRules.insert(i); - auto result = rhs->substitute(subst)->expandMacros( - subsorts, overloads, macros, reverse, appliedRules, macroSymbols); - appliedRules = oldAppliedRules; + && (decl->attributes().contains(attribute_set::key::MacroRec) + || decl->attributes().contains(attribute_set::key::AliasRec) + || !applied_rules.contains(i))) { + std::set old_applied_rules = applied_rules; + applied_rules.insert(i); + auto result = rhs->substitute(subst)->expand_macros( + subsorts, overloads, macros, reverse, applied_rules, macro_symbols); + applied_rules = old_applied_rules; return result; } i++; @@ -1157,76 +1166,78 @@ sptr KORECompositePattern::expandMacros( return applied; } -bool KOREVariablePattern::matches( +bool kore_variable_pattern::matches( substitution &subst, SubsortMap const &subsorts, SymbolMap const &overloads, - sptr subject) { - if (subst[name->getName()]) { - return ast_to_string(*subst[name->getName()]) == ast_to_string(*subject); + sptr subject) { + if (subst[name_->get_name()]) { + return ast_to_string(*subst[name_->get_name()]) == ast_to_string(*subject); } - subst[name->getName()] = subject; + subst[name_->get_name()] = subject; return true; } // NOLINTNEXTLINE(*-cognitive-complexity) -bool KORECompositePattern::matches( +bool kore_composite_pattern::matches( substitution &subst, SubsortMap const &subsorts, SymbolMap const &overloads, - sptr subject) { - auto *subj = dynamic_cast(subject.get()); + sptr subject) { + auto *subj = dynamic_cast(subject.get()); if (!subj) { return false; } - if (*subj->getConstructor() != *getConstructor()) { - if (subj->getConstructor()->getName() == "inj" - && getConstructor()->getName() == "inj") { - if (*subj->getConstructor()->getFormalArguments()[1] - != *getConstructor()->getFormalArguments()[1]) { + if (*subj->get_constructor() != *get_constructor()) { + if (subj->get_constructor()->get_name() == "inj" + && get_constructor()->get_name() == "inj") { + if (*subj->get_constructor()->get_formal_arguments()[1] + != *get_constructor()->get_formal_arguments()[1]) { return false; } - sptr a = subj->getConstructor()->getFormalArguments()[0]; - sptr b = getConstructor()->getFormalArguments()[0]; + sptr a = subj->get_constructor()->get_formal_arguments()[0]; + sptr b = get_constructor()->get_formal_arguments()[0]; if (subsorts.contains(b.get()) && subsorts.at(b.get()).contains(a.get())) { - sptr ba = KORECompositePattern::Create("inj"); - ba->getConstructor()->addFormalArgument(b); - ba->getConstructor()->addFormalArgument(a); - ba->getConstructor()->addArgument(b); - ba->addArgument(arguments[0]); - return ba->matches(subst, subsorts, overloads, subj->getArguments()[0]); + sptr ba = kore_composite_pattern::create("inj"); + ba->get_constructor()->add_formal_argument(b); + ba->get_constructor()->add_formal_argument(a); + ba->get_constructor()->add_argument(b); + ba->add_argument(arguments_[0]); + return ba->matches( + subst, subsorts, overloads, subj->get_arguments()[0]); } if (subsorts.contains(a.get()) && subsorts.at(a.get()).contains(b.get())) { - sptr ab = KORECompositePattern::Create("inj"); - ab->getConstructor()->addFormalArgument(a); - ab->getConstructor()->addFormalArgument(b); - ab->getConstructor()->addArgument(a); - ab->addArgument(subj->getArguments()[0]); - return arguments[0]->matches(subst, subsorts, overloads, ab); + sptr ab = kore_composite_pattern::create("inj"); + ab->get_constructor()->add_formal_argument(a); + ab->get_constructor()->add_formal_argument(b); + ab->get_constructor()->add_argument(a); + ab->add_argument(subj->get_arguments()[0]); + return arguments_[0]->matches(subst, subsorts, overloads, ab); } return false; } - if (subj->getConstructor()->getName() == "inj") { - sptr child = subj->getArguments()[0]; - if (auto *composite = dynamic_cast(child.get())) { - if (overloads.contains(composite->getConstructor()) - && overloads.at(composite->getConstructor()) - .contains(getConstructor())) { - sptr greater - = KORECompositePattern::Create(getConstructor()); - for (int i = 0; i < arguments.size(); i++) { - if (*getConstructor()->getArguments()[i] - != *composite->getConstructor()->getArguments()[i]) { - sptr inj - = KORECompositePattern::Create("inj"); - inj->getConstructor()->addFormalArgument( - composite->getConstructor()->getArguments()[i]); - inj->getConstructor()->addFormalArgument( - getConstructor()->getArguments()[i]); - inj->getConstructor()->addArgument( - composite->getConstructor()->getArguments()[i]); - inj->addArgument(composite->getArguments()[i]); - greater->addArgument(inj); + if (subj->get_constructor()->get_name() == "inj") { + sptr child = subj->get_arguments()[0]; + if (auto *composite + = dynamic_cast(child.get())) { + if (overloads.contains(composite->get_constructor()) + && overloads.at(composite->get_constructor()) + .contains(get_constructor())) { + sptr greater + = kore_composite_pattern::create(get_constructor()); + for (int i = 0; i < arguments_.size(); i++) { + if (*get_constructor()->get_arguments()[i] + != *composite->get_constructor()->get_arguments()[i]) { + sptr inj + = kore_composite_pattern::create("inj"); + inj->get_constructor()->add_formal_argument( + composite->get_constructor()->get_arguments()[i]); + inj->get_constructor()->add_formal_argument( + get_constructor()->get_arguments()[i]); + inj->get_constructor()->add_argument( + composite->get_constructor()->get_arguments()[i]); + inj->add_argument(composite->get_arguments()[i]); + greater->add_argument(inj); } else { - greater->addArgument(composite->getArguments()[i]); + greater->add_argument(composite->get_arguments()[i]); } } return this->matches(subst, subsorts, overloads, greater); @@ -1237,45 +1248,45 @@ bool KORECompositePattern::matches( } return false; } - if (subj->arguments.size() != arguments.size()) { + if (subj->arguments_.size() != arguments_.size()) { return false; } bool match = true; - for (int i = 0; i < subj->arguments.size(); i++) { + for (int i = 0; i < subj->arguments_.size(); i++) { match = match - && arguments[i]->matches( - subst, subsorts, overloads, subj->arguments[i]); + && arguments_[i]->matches( + subst, subsorts, overloads, subj->arguments_[i]); } return match; } -bool KOREStringPattern::matches( +bool kore_string_pattern::matches( substitution &subst, SubsortMap const &subsorts, SymbolMap const &overloads, - sptr subject) { - auto *subj = dynamic_cast(subject.get()); + sptr subject) { + auto *subj = dynamic_cast(subject.get()); if (!subj) { return false; } - return subj->contents == contents; + return subj->contents_ == contents_; } -void KOREDeclaration::addObjectSortVariable( - sptr const &SortVariable) { - objectSortVariables.push_back(SortVariable); +void kore_declaration::add_object_sort_variable( + sptr const &sort_variable) { + object_sort_variables_.push_back(sort_variable); } -void KOREAxiomDeclaration::addPattern(sptr Pattern) { - pattern = std::move(Pattern); +void kore_axiom_declaration::add_pattern(sptr pattern) { + this->pattern_ = std::move(pattern); } -bool KOREAxiomDeclaration::isRequired() const { +bool kore_axiom_declaration::is_required() const { constexpr auto keys_to_drop = std::array{ - attribute_set::key::assoc, attribute_set::key::comm, - attribute_set::key::idem, attribute_set::key::unit, - attribute_set::key::functional, attribute_set::key::constructor, - attribute_set::key::total, attribute_set::key::subsort, - attribute_set::key::ceil, attribute_set::key::non_executable, - attribute_set::key::simplification, + attribute_set::key::Assoc, attribute_set::key::Comm, + attribute_set::key::Idem, attribute_set::key::Unit, + attribute_set::key::Functional, attribute_set::key::Constructor, + attribute_set::key::Total, attribute_set::key::Subsort, + attribute_set::key::Ceil, attribute_set::key::NonExecutable, + attribute_set::key::Simplification, }; return std::none_of( @@ -1283,129 +1294,130 @@ bool KOREAxiomDeclaration::isRequired() const { [this](auto key) { return attributes().contains(key); }); } -bool KOREAxiomDeclaration::isTopAxiom() const { - if (auto *top = dynamic_cast(pattern.get())) { - if (top->getConstructor()->getName() == "\\implies" - && top->getArguments().size() == 2) { - if (auto *bottomPattern = dynamic_cast( - top->getArguments()[0].get())) { - if (bottomPattern->getConstructor()->getName() == "\\bottom" - && bottomPattern->getArguments().empty()) { +bool kore_axiom_declaration::is_top_axiom() const { + if (auto *top = dynamic_cast(pattern_.get())) { + if (top->get_constructor()->get_name() == "\\implies" + && top->get_arguments().size() == 2) { + if (auto *bottom_pattern = dynamic_cast( + top->get_arguments()[0].get())) { + if (bottom_pattern->get_constructor()->get_name() == "\\bottom" + && bottom_pattern->get_arguments().empty()) { return true; } } return false; } - if (top->getConstructor()->getName() == "\\rewrites" - && top->getArguments().size() == 2) { + if (top->get_constructor()->get_name() == "\\rewrites" + && top->get_arguments().size() == 2) { return true; } - if (top->getConstructor()->getName() == "\\and" - && top->getArguments().size() == 2) { + if (top->get_constructor()->get_name() == "\\and" + && top->get_arguments().size() == 2) { return true; } } return false; } -void KOREAliasDeclaration::addVariables(sptr Variables) { - boundVariables = std::move(Variables); +void kore_alias_declaration::add_variables( + sptr variables) { + bound_variables_ = std::move(variables); } -void KOREAliasDeclaration::addPattern(sptr Pattern) { - pattern = std::move(Pattern); +void kore_alias_declaration::add_pattern(sptr pattern) { + this->pattern_ = std::move(pattern); } -KOREPattern::substitution -KOREAliasDeclaration::getSubstitution(KORECompositePattern *subject) { +kore_pattern::substitution +kore_alias_declaration::get_substitution(kore_composite_pattern *subject) { int i = 0; - KOREPattern::substitution result; - for (auto const &arg : boundVariables->getArguments()) { - auto *var = dynamic_cast(arg.get()); + kore_pattern::substitution result; + for (auto const &arg : bound_variables_->get_arguments()) { + auto *var = dynamic_cast(arg.get()); if (!var) { abort(); } - result[var->getName()] = subject->getArguments()[i++]; + result[var->get_name()] = subject->get_arguments()[i++]; } return result; } -bool KORESymbolDeclaration::isAnywhere() const { - return attributes().contains(attribute_set::key::anywhere); +bool kore_symbol_declaration::is_anywhere() const { + return attributes().contains(attribute_set::key::Anywhere); } -void KOREModule::addDeclaration(sptr Declaration) { - declarations.push_back(std::move(Declaration)); +void kore_module::add_declaration(sptr declaration) { + declarations_.push_back(std::move(declaration)); } // Pretty printer -void KORESortVariable::print(std::ostream &Out, unsigned indent) const { - std::string Indent(indent, ' '); - Out << Indent << name; -} - -void KORECompositeSort::print(std::ostream &Out, unsigned indent) const { - std::string Indent(indent, ' '); - Out << Indent << name << "{"; - bool isFirst = true; - for (auto const &Argument : arguments) { - if (!isFirst) { - Out << ","; +void kore_sort_variable::print(std::ostream &out, unsigned ind) const { + auto indent = std::string(ind, ' '); + out << indent << name_; +} + +void kore_composite_sort::print(std::ostream &out, unsigned ind) const { + auto indent = std::string(ind, ' '); + out << indent << name_ << "{"; + bool is_first = true; + for (auto const &argument : arguments_) { + if (!is_first) { + out << ","; } - Argument->print(Out); - isFirst = false; + argument->print(out); + is_first = false; } - Out << "}"; + out << "}"; } -void KORESymbol::print(std::ostream &Out, unsigned indent) const { - print(Out, indent, true); +void kore_symbol::print(std::ostream &out, unsigned ind) const { + print(out, indent, true); } -void KORESymbol::print(std::ostream &Out, unsigned indent, bool formal) const { - std::string Indent(indent, ' '); - Out << Indent << name << "{"; - bool isFirst = true; - for (auto const &Argument : (formal ? formalArguments : arguments)) { - if (!isFirst) { - Out << ", "; +void kore_symbol::print(std::ostream &out, unsigned ind, bool formal) const { + auto indent = std::string(ind, ' '); + out << indent << name_ << "{"; + bool is_first = true; + for (auto const &argument : (formal ? formal_arguments_ : arguments_)) { + if (!is_first) { + out << ", "; } - Argument->print(Out); - isFirst = false; + argument->print(out); + is_first = false; } - Out << "}"; + out << "}"; } -void KOREVariable::print(std::ostream &Out, unsigned indent) const { - std::string Indent(indent, ' '); - Out << Indent << name; +void kore_variable::print(std::ostream &out, unsigned ind) const { + auto indent = std::string(ind, ' '); + out << indent << name_; } -void KOREVariablePattern::print(std::ostream &Out, unsigned indent) const { - std::string Indent(indent, ' '); - Out << Indent; - name->print(Out); - Out << " : "; - sort->print(Out); +void kore_variable_pattern::print(std::ostream &out, unsigned ind) const { + auto indent = std::string(ind, ' '); + out << indent; + name_->print(out); + out << " : "; + sort_->print(out); } -void KORECompositePattern::print(std::ostream &Out, unsigned indent) const { - std::string Indent(indent, ' '); - Out << Indent; - constructor->print(Out); - Out << "("; - bool isFirst = true; - for (auto const &Argument : arguments) { - if (!isFirst) { - Out << ","; +void kore_composite_pattern::print(std::ostream &out, unsigned ind) const { + auto indent = std::string(ind, ' '); + out << indent; + constructor_->print(out); + out << "("; + bool is_first = true; + for (auto const &argument : arguments_) { + if (!is_first) { + out << ","; } - Argument->print(Out); - isFirst = false; + argument->print(out); + is_first = false; } - Out << ")"; + out << ")"; } -static std::string escapeString(std::string const &str) { +static std::string escape_string(std::string const &str) { auto result = std::string{}; for (char c : str) { @@ -1421,222 +1433,222 @@ static std::string escapeString(std::string const &str) { return result; } -void KOREStringPattern::print(std::ostream &Out, unsigned indent) const { - std::string Indent(indent, ' '); - Out << Indent << "\"" << escapeString(contents) << "\""; +void kore_string_pattern::print(std::ostream &out, unsigned ind) const { + auto indent = std::string(ind, ' '); + out << indent << "\"" << escape_string(contents_) << "\""; } -static void printAttributeList( - std::ostream &Out, attribute_set const &attributes, unsigned indent = 0) { +static void print_attribute_list( + std::ostream &out, attribute_set const &attributes, unsigned ind = 0) { - std::string Indent(indent, ' '); - Out << Indent << "["; - bool isFirst = true; + auto indent = std::string(ind, ' '); + out << indent << "["; + bool is_first = true; for (auto const &[name, pattern] : attributes) { - if (!isFirst) { - Out << ","; + if (!is_first) { + out << ","; } - pattern->print(Out); - isFirst = false; + pattern->print(out); + is_first = false; } - Out << "]"; + out << "]"; } -void KOREDeclaration::printSortVariables(std::ostream &Out) const { - Out << "{"; - bool isFirst = true; - for (auto const &Variable : objectSortVariables) { - if (!isFirst) { - Out << ","; +void kore_declaration::print_sort_variables(std::ostream &out) const { + out << "{"; + bool is_first = true; + for (auto const &variable : object_sort_variables_) { + if (!is_first) { + out << ","; } - Variable->print(Out); - isFirst = false; - } - Out << "}"; -} - -void KORECompositeSortDeclaration::print( - std::ostream &Out, unsigned indent) const { - std::string Indent(indent, ' '); - Out << Indent << (_isHooked ? "hooked-sort " : "sort ") << sortName; - printSortVariables(Out); - Out << " "; - printAttributeList(Out, attributes()); -} - -void KORESymbolDeclaration::print(std::ostream &Out, unsigned indent) const { - std::string Indent(indent, ' '); - Out << Indent << (_isHooked ? "hooked-symbol " : "symbol ") - << getSymbol()->getName(); - printSortVariables(Out); - Out << "("; - bool isFirst = true; - for (auto const &Argument : getSymbol()->getArguments()) { - if (!isFirst) { - Out << ","; + variable->print(out); + is_first = false; + } + out << "}"; +} + +void kore_composite_sort_declaration::print( + std::ostream &out, unsigned ind) const { + auto indent = std::string(ind, ' '); + out << indent << (is_hooked_ ? "hooked-sort " : "sort ") << sort_name_; + print_sort_variables(out); + out << " "; + print_attribute_list(out, attributes()); +} + +void kore_symbol_declaration::print(std::ostream &out, unsigned ind) const { + auto indent = std::string(ind, ' '); + out << indent << (is_hooked_ ? "hooked-symbol " : "symbol ") + << get_symbol()->get_name(); + print_sort_variables(out); + out << "("; + bool is_first = true; + for (auto const &argument : get_symbol()->get_arguments()) { + if (!is_first) { + out << ","; } - Argument->print(Out); - isFirst = false; - } - Out << ") : "; - getSymbol()->getSort()->print(Out); - Out << " "; - printAttributeList(Out, attributes()); -} - -void KOREAliasDeclaration::print(std::ostream &Out, unsigned indent) const { - std::string Indent(indent, ' '); - Out << Indent << "alias " << getSymbol()->getName(); - printSortVariables(Out); - Out << "("; - bool isFirst = true; - for (auto const &Argument : getSymbol()->getArguments()) { - if (!isFirst) { - Out << ","; + argument->print(out); + is_first = false; + } + out << ") : "; + get_symbol()->get_sort()->print(out); + out << " "; + print_attribute_list(out, attributes()); +} + +void kore_alias_declaration::print(std::ostream &out, unsigned ind) const { + auto indent = std::string(ind, ' '); + out << indent << "alias " << get_symbol()->get_name(); + print_sort_variables(out); + out << "("; + bool is_first = true; + for (auto const &argument : get_symbol()->get_arguments()) { + if (!is_first) { + out << ","; } - Argument->print(Out); - isFirst = false; - } - Out << ") : "; - getSymbol()->getSort()->print(Out); - Out << " where "; - boundVariables->print(Out); - Out << " := "; - pattern->print(Out); - Out << " "; - printAttributeList(Out, attributes()); -} - -void KOREAxiomDeclaration::print(std::ostream &Out, unsigned indent) const { - std::string Indent(indent, ' '); - Out << Indent << (isClaim() ? "claim " : "axiom "); - printSortVariables(Out); - pattern->print(Out); - Out << " "; - printAttributeList(Out, attributes()); -} - -void KOREModuleImportDeclaration::print( - std::ostream &Out, unsigned indent) const { - std::string Indent(indent, ' '); - Out << Indent << "import " << moduleName; - Out << " "; - printAttributeList(Out, attributes()); -} - -void KOREModule::print(std::ostream &Out, unsigned indent) const { - std::string Indent(indent, ' '); - Out << Indent << "module " << name << "\n"; - bool isFirst = true; - for (auto const &Declaration : declarations) { - if (!isFirst) { - Out << "\n"; + argument->print(out); + is_first = false; + } + out << ") : "; + get_symbol()->get_sort()->print(out); + out << " where "; + bound_variables_->print(out); + out << " := "; + pattern_->print(out); + out << " "; + print_attribute_list(out, attributes()); +} + +void kore_axiom_declaration::print(std::ostream &out, unsigned ind) const { + auto indent = std::string(ind, ' '); + out << indent << (is_claim() ? "claim " : "axiom "); + print_sort_variables(out); + pattern_->print(out); + out << " "; + print_attribute_list(out, attributes()); +} + +void kore_module_import_declaration::print( + std::ostream &out, unsigned ind) const { + auto indent = std::string(ind, ' '); + out << indent << "import " << module_name_; + out << " "; + print_attribute_list(out, attributes()); +} + +void kore_module::print(std::ostream &out, unsigned ind) const { + auto indent = std::string(ind, ' '); + out << indent << "module " << name_ << "\n"; + bool is_first = true; + for (auto const &declaration : declarations_) { + if (!is_first) { + out << "\n"; } - Declaration->print(Out, indent + 2); - Out << "\n"; - isFirst = false; + declaration->print(out, ind + 2); + out << "\n"; + is_first = false; } - Out << Indent << "endmodule\n"; - printAttributeList(Out, attributes(), indent); + out << indent << "endmodule\n"; + print_attribute_list(out, attributes(), ind); } -void KOREDefinition::print(std::ostream &Out, unsigned indent) const { - printAttributeList(Out, attributes(), indent); - Out << "\n"; - for (auto const &Module : modules) { - Out << "\n"; - Module->print(Out, indent); - Out << "\n"; +void kore_definition::print(std::ostream &out, unsigned ind) const { + print_attribute_list(out, attributes(), indent); + out << "\n"; + for (auto const &module : modules_) { + out << "\n"; + module->print(out, indent); + out << "\n"; } } // Binary serialization -void KOREVariablePattern::serialize_to(serializer &s) const { - sort->serialize_to(s); - s.emit(header_byte); - name->serialize_to(s); +void kore_variable_pattern::serialize_to(serializer &s) const { + sort_->serialize_to(s); + s.emit(header_byte); + name_->serialize_to(s); } -void KORECompositePattern::serialize_to(serializer &s) const { +void kore_composite_pattern::serialize_to(serializer &s) const { auto emit_this_arity = s.use_arity(); s.reset_arity_flag(); - for (auto const &arg : arguments) { + for (auto const &arg : arguments_) { arg->serialize_to(s); } - constructor->serialize_to(s); + constructor_->serialize_to(s); - s.emit(header_byte); + s.emit(header_byte); if (emit_this_arity) { - s.emit_length(arguments.size()); + s.emit_length(arguments_.size()); } } -void KOREStringPattern::serialize_to(serializer &s) const { - s.emit(header_byte); - s.emit_string(contents); +void kore_string_pattern::serialize_to(serializer &s) const { + s.emit(header_byte); + s.emit_string(contents_); } -void KORESortVariable::serialize_to(serializer &s) const { - s.emit(header_byte); - s.emit_string(name); +void kore_sort_variable::serialize_to(serializer &s) const { + s.emit(header_byte); + s.emit_string(name_); } -void KORECompositeSort::serialize_to(serializer &s) const { - for (auto const &arg : arguments) { +void kore_composite_sort::serialize_to(serializer &s) const { + for (auto const &arg : arguments_) { arg->serialize_to(s); } - s.emit(header_byte); - s.emit_length(arguments.size()); - s.emit_string(name); + s.emit(header_byte); + s.emit_length(arguments_.size()); + s.emit_string(name_); } -void KORESymbol::serialize_to(serializer &s) const { - for (auto const &arg : formalArguments) { +void kore_symbol::serialize_to(serializer &s) const { + for (auto const &arg : formal_arguments_) { arg->serialize_to(s); } - s.emit(header_byte); - s.emit_length(formalArguments.size()); - s.emit_string(name); + s.emit(header_byte); + s.emit_length(formal_arguments_.size()); + s.emit_string(name_); } -void KOREVariable::serialize_to(serializer &s) const { - s.emit(header_byte); - s.emit_string(name); +void kore_variable::serialize_to(serializer &s) const { + s.emit(header_byte); + s.emit_string(name_); } -void kllvm::readMultimap( - std::string const &name, KORESymbolDeclaration *decl, +void kllvm::read_multimap( + std::string const &name, kore_symbol_declaration *decl, std::map> &output, - attribute_set::key attName) { - if (decl->attributes().contains(attName)) { - KORECompositePattern *att = decl->attributes().get(attName).get(); - for (auto const &pat : att->getArguments()) { - auto *child = dynamic_cast(pat.get()); - output[name].insert(child->getConstructor()->getName()); + attribute_set::key att_name) { + if (decl->attributes().contains(att_name)) { + kore_composite_pattern *att = decl->attributes().get(att_name).get(); + for (auto const &pat : att->get_arguments()) { + auto *child = dynamic_cast(pat.get()); + output[name].insert(child->get_constructor()->get_name()); } } } -// Normally, destruction of KOREPattern would call destructor +// Normally, destruction of kore_pattern would call destructor // of all its subpatterns. This can sometimes exhaust all the stack space. // This function deallocates a pattern iteratively, without recursion. -void kllvm::deallocateSPtrKorePattern(sptr pattern) { - std::vector> vec; +void kllvm::deallocate_s_ptr_kore_pattern(sptr pattern) { + std::vector> vec; vec.push_back(std::move(pattern)); while (!vec.empty()) { - sptr curr = std::move(vec.back()); + sptr curr = std::move(vec.back()); vec.pop_back(); if (auto composite - = std::dynamic_pointer_cast(curr)) { + = std::dynamic_pointer_cast(curr)) { vec.insert( - vec.end(), std::make_move_iterator(composite->arguments.begin()), - std::make_move_iterator(composite->arguments.end())); + vec.end(), std::make_move_iterator(composite->arguments_.begin()), + std::make_move_iterator(composite->arguments_.end())); } } } diff --git a/lib/ast/attribute_set.cpp b/lib/ast/attribute_set.cpp index 893e890d8..658a18395 100644 --- a/lib/ast/attribute_set.cpp +++ b/lib/ast/attribute_set.cpp @@ -9,44 +9,44 @@ namespace { std::unordered_map const &attribute_table() { static std::unordered_map table = { - {attribute_set::key::alias, "alias"}, - {attribute_set::key::alias_rec, "alias-rec"}, - {attribute_set::key::anywhere, "anywhere"}, - {attribute_set::key::assoc, "assoc"}, - {attribute_set::key::binder, "binder"}, - {attribute_set::key::bracket, "bracket"}, - {attribute_set::key::ceil, "ceil"}, - {attribute_set::key::colors, "colors"}, - {attribute_set::key::comm, "comm"}, - {attribute_set::key::concat, "concat"}, - {attribute_set::key::constructor, "constructor"}, - {attribute_set::key::element, "element"}, - {attribute_set::key::format, "format"}, - {attribute_set::key::fresh_generator, "freshGenerator"}, - {attribute_set::key::function, "function"}, - {attribute_set::key::functional, "functional"}, - {attribute_set::key::hook, "hook"}, - {attribute_set::key::idem, "idem"}, - {attribute_set::key::label, "label"}, - {attribute_set::key::left, "left"}, - {attribute_set::key::location, + {attribute_set::key::Alias, "alias"}, + {attribute_set::key::AliasRec, "alias-rec"}, + {attribute_set::key::Anywhere, "anywhere"}, + {attribute_set::key::Assoc, "assoc"}, + {attribute_set::key::Binder, "binder"}, + {attribute_set::key::Bracket, "bracket"}, + {attribute_set::key::Ceil, "ceil"}, + {attribute_set::key::Colors, "colors"}, + {attribute_set::key::Comm, "comm"}, + {attribute_set::key::Concat, "concat"}, + {attribute_set::key::Constructor, "constructor"}, + {attribute_set::key::Element, "element"}, + {attribute_set::key::Format, "format"}, + {attribute_set::key::FreshGenerator, "freshGenerator"}, + {attribute_set::key::Function, "function"}, + {attribute_set::key::Functional, "functional"}, + {attribute_set::key::Hook, "hook"}, + {attribute_set::key::Idem, "idem"}, + {attribute_set::key::Label, "label"}, + {attribute_set::key::Left, "left"}, + {attribute_set::key::Location, "org'Stop'kframework'Stop'attributes'Stop'Location"}, - {attribute_set::key::macro, "macro"}, - {attribute_set::key::macro_rec, "macro-rec"}, - {attribute_set::key::nat, "nat"}, - {attribute_set::key::non_executable, "non-executable"}, - {attribute_set::key::priorities, "priorities"}, - {attribute_set::key::priority, "priority"}, - {attribute_set::key::right, "right"}, - {attribute_set::key::simplification, "simplification"}, - {attribute_set::key::sort_injection, "sortInjection"}, - {attribute_set::key::source, + {attribute_set::key::Macro, "macro"}, + {attribute_set::key::MacroRec, "macro-rec"}, + {attribute_set::key::Nat, "nat"}, + {attribute_set::key::NonExecutable, "non-executable"}, + {attribute_set::key::Priorities, "priorities"}, + {attribute_set::key::Priority, "priority"}, + {attribute_set::key::Right, "right"}, + {attribute_set::key::Simplification, "simplification"}, + {attribute_set::key::SortInjection, "sortInjection"}, + {attribute_set::key::Source, "org'Stop'kframework'Stop'attributes'Stop'Source"}, - {attribute_set::key::subsort, "subsort"}, - {attribute_set::key::symbol_overload, "symbol-overload"}, - {attribute_set::key::terminals, "terminals"}, - {attribute_set::key::total, "total"}, - {attribute_set::key::unit, "unit"}, + {attribute_set::key::Subsort, "subsort"}, + {attribute_set::key::SymbolOverload, "symbol-overload"}, + {attribute_set::key::Terminals, "terminals"}, + {attribute_set::key::Total, "total"}, + {attribute_set::key::Unit, "unit"}, }; return table; } @@ -74,8 +74,8 @@ std::optional string_to_key(std::string const &name) { } // namespace std::optional -attribute_set::add(std::shared_ptr att) { - auto name = att->getConstructor()->getName(); +attribute_set::add(std::shared_ptr att) { + auto name = att->get_constructor()->get_name(); attribute_map_.emplace(name, std::move(att)); return string_to_key(name); } @@ -84,19 +84,19 @@ bool attribute_set::contains(attribute_set::key k) const { return attribute_map_.find(key_to_string(k)) != attribute_map_.end(); } -std::shared_ptr const & +std::shared_ptr const & attribute_set::get(attribute_set::key k) const { return attribute_map_.at(key_to_string(k)); } std::string attribute_set::get_string(attribute_set::key k) const { auto const &attribute_pattern = get(k); - assert(attribute_pattern->getArguments().size() == 1); + assert(attribute_pattern->get_arguments().size() == 1); - auto const &string_arg = std::dynamic_pointer_cast( - attribute_pattern->getArguments()[0]); + auto const &string_arg = std::dynamic_pointer_cast( + attribute_pattern->get_arguments()[0]); - return string_arg->getContents(); + return string_arg->get_contents(); } attribute_set::storage_t const &attribute_set::underlying() const { diff --git a/lib/ast/definition.cpp b/lib/ast/definition.cpp index 9d4dadda8..af7851c7d 100644 --- a/lib/ast/definition.cpp +++ b/lib/ast/definition.cpp @@ -10,14 +10,14 @@ namespace { template std::unordered_map, Hash, Equal> -transitiveClosure(std::unordered_map< - Elem *, std::unordered_set, Hash, Equal> - relations) { +transitive_closure(std::unordered_map< + Elem *, std::unordered_set, Hash, Equal> + relations) { bool dirty = false; do { dirty = false; for (auto &entry : relations) { - SortSet newSucc; + SortSet new_succ; for (auto &elem : entry.second) { auto &relation = relations[elem]; for (auto *elem2 : relation) { @@ -32,13 +32,13 @@ transitiveClosure(std::unordered_map< } // namespace std::unordered_set -KOREDefinition::getSortsHookedTo(std::string const &hookName) const { +kore_definition::get_sorts_hooked_to(std::string const &hook_name) const { auto ret = std::unordered_set{}; - for (auto const &[name, decl] : getSortDeclarations()) { - if (decl->isHooked()) { - if (auto hook = decl->attributes().get_string(attribute_set::key::hook); - hook == hookName) { + for (auto const &[name, decl] : get_sort_declarations()) { + if (decl->is_hooked()) { + if (auto hook = decl->attributes().get_string(attribute_set::key::Hook); + hook == hook_name) { ret.insert(name); } } @@ -47,173 +47,182 @@ KOREDefinition::getSortsHookedTo(std::string const &hookName) const { return ret; } -void KOREDefinition::addModule(sptr Module) { - for (auto const &decl : Module->getDeclarations()) { - if (auto *sortDecl - = dynamic_cast(decl.get())) { - sortDeclarations.insert({sortDecl->getName(), sortDecl}); - auto sort = KORECompositeSort::Create(sortDecl->getName()); +void kore_definition::add_module(sptr module) { + for (auto const &decl : module->get_declarations()) { + if (auto *sort_decl + = dynamic_cast(decl.get())) { + sort_declarations_.insert({sort_decl->get_name(), sort_decl}); + auto sort = kore_composite_sort::create(sort_decl->get_name()); } else if ( - auto *symbolDecl = dynamic_cast(decl.get())) { - symbolDeclarations.insert( - {symbolDecl->getSymbol()->getName(), symbolDecl}); + auto *symbol_decl + = dynamic_cast(decl.get())) { + symbol_declarations_.insert( + {symbol_decl->get_symbol()->get_name(), symbol_decl}); } else if ( - auto *aliasDecl = dynamic_cast(decl.get())) { - aliasDeclarations.insert({aliasDecl->getSymbol()->getName(), aliasDecl}); - } else if (auto *axiom = dynamic_cast(decl.get())) { - axioms.push_back(axiom); + auto *alias_decl = dynamic_cast(decl.get())) { + alias_declarations_.insert( + {alias_decl->get_symbol()->get_name(), alias_decl}); + } else if ( + auto *axiom = dynamic_cast(decl.get())) { + axioms_.push_back(axiom); } } - modules.push_back(std::move(Module)); + modules_.push_back(std::move(module)); } -void KOREDefinition::insertReservedSymbols() { - auto mod = KOREModule::Create("K-RAW-TERM"); - auto decl = KORESymbolDeclaration::Create("rawTerm", true); - auto sort = KORECompositeSort::Create("SortKItem"); +void kore_definition::insert_reserved_symbols() { + auto mod = kore_module::create("K-RAW-TERM"); + auto decl = kore_symbol_declaration::create("rawTerm", true); + auto sort = kore_composite_sort::create("SortKItem"); - decl->getSymbol()->addSort(sort); - decl->getSymbol()->addArgument(sort); - mod->addDeclaration(std::move(decl)); + decl->get_symbol()->add_sort(sort); + decl->get_symbol()->add_argument(sort); + mod->add_declaration(std::move(decl)); - addModule(std::move(mod)); + add_module(std::move(mod)); } -SubsortMap KOREDefinition::getSubsorts() const { +SubsortMap kore_definition::get_subsorts() const { auto subsorts = SubsortMap{}; - for (auto *axiom : axioms) { - if (axiom->attributes().contains(attribute_set::key::subsort)) { - auto const &att = axiom->attributes().get(attribute_set::key::subsort); - auto const &innerSort = att->getConstructor()->getFormalArguments()[0]; - auto const &outerSort = att->getConstructor()->getFormalArguments()[1]; - subsorts[innerSort.get()].insert(outerSort.get()); + for (auto *axiom : axioms_) { + if (axiom->attributes().contains(attribute_set::key::Subsort)) { + auto const &att = axiom->attributes().get(attribute_set::key::Subsort); + auto const &inner_sort + = att->get_constructor()->get_formal_arguments()[0]; + auto const &outer_sort + = att->get_constructor()->get_formal_arguments()[1]; + subsorts[inner_sort.get()].insert(outer_sort.get()); } } - return transitiveClosure(subsorts); + return transitive_closure(subsorts); } -SymbolMap KOREDefinition::getOverloads() const { +SymbolMap kore_definition::get_overloads() const { auto overloads = SymbolMap{}; - for (auto *axiom : axioms) { - if (axiom->attributes().contains(attribute_set::key::symbol_overload)) { + for (auto *axiom : axioms_) { + if (axiom->attributes().contains(attribute_set::key::SymbolOverload)) { auto const &att - = axiom->attributes().get(attribute_set::key::symbol_overload); - auto *innerSymbol = std::dynamic_pointer_cast( - att->getArguments()[1]) - ->getConstructor(); - auto *outerSymbol = std::dynamic_pointer_cast( - att->getArguments()[0]) - ->getConstructor(); - overloads[innerSymbol].insert(outerSymbol); + = axiom->attributes().get(attribute_set::key::SymbolOverload); + auto *inner_symbol = std::dynamic_pointer_cast( + att->get_arguments()[1]) + ->get_constructor(); + auto *outer_symbol = std::dynamic_pointer_cast( + att->get_arguments()[0]) + ->get_constructor(); + overloads[inner_symbol].insert(outer_symbol); } } - return transitiveClosure(overloads); + return transitive_closure(overloads); } // NOLINTNEXTLINE(*-function-cognitive-complexity) -void KOREDefinition::preprocess() { - insertReservedSymbols(); +void kore_definition::preprocess() { + insert_reserved_symbols(); - for (auto *axiom : axioms) { - axiom->pattern = axiom->pattern->expandAliases(this); + for (auto *axiom : axioms_) { + axiom->pattern_ = axiom->pattern_->expand_aliases(this); } - auto symbols = std::map>{}; - unsigned nextOrdinal = 0; - for (auto const &decl : symbolDeclarations) { + auto symbols = std::map>{}; + unsigned next_ordinal = 0; + for (auto const &decl : symbol_declarations_) { if (decl.second->attributes().contains( - attribute_set::key::fresh_generator)) { - auto sort = decl.second->getSymbol()->getSort(); - if (sort->isConcrete()) { - freshFunctions[dynamic_cast(sort.get())->getName()] - = decl.second->getSymbol(); + attribute_set::key::FreshGenerator)) { + auto sort = decl.second->get_symbol()->get_sort(); + if (sort->is_concrete()) { + fresh_functions_[dynamic_cast(sort.get()) + ->get_name()] + = decl.second->get_symbol(); } } } - for (auto iter = axioms.begin(); iter != axioms.end();) { + for (auto iter = axioms_.begin(); iter != axioms_.end();) { auto *axiom = *iter; - axiom->ordinal = nextOrdinal; - ordinals[nextOrdinal++] = axiom; - axiom->pattern->markSymbols(symbols); - if (!axiom->isRequired()) { - iter = axioms.erase(iter); + axiom->ordinal_ = next_ordinal; + ordinals_[next_ordinal++] = axiom; + axiom->pattern_->mark_symbols(symbols); + if (!axiom->is_required()) { + iter = axioms_.erase(iter); } else { ++iter; } } - for (auto &module : modules) { - auto const &declarations = module->getDeclarations(); + for (auto &module : modules_) { + auto const &declarations = module->get_declarations(); for (auto const &declaration : declarations) { - auto *decl = dynamic_cast(declaration.get()); + auto *decl = dynamic_cast(declaration.get()); if (decl == nullptr) { continue; } - if (decl->isHooked() && decl->getObjectSortVariables().empty()) { - KORESymbol *symbol = decl->getSymbol(); - symbols.emplace(symbol->getName(), std::vector{symbol}); + if (decl->is_hooked() && decl->get_object_sort_variables().empty()) { + kore_symbol *symbol = decl->get_symbol(); + symbols.emplace(symbol->get_name(), std::vector{symbol}); } } } for (auto const &entry : symbols) { for (auto *symbol : entry.second) { - auto *decl = symbolDeclarations.at(symbol->getName()); - symbol->instantiateSymbol(decl); + auto *decl = symbol_declarations_.at(symbol->get_name()); + symbol->instantiate_symbol(decl); } } - uint32_t nextSymbol = 0; - uint16_t nextLayout = 1; - auto instantiations = std::unordered_map{}; + uint32_t next_symbol = 0; + uint16_t next_layout = 1; + auto instantiations + = std::unordered_map{}; auto layouts = std::unordered_map{}; auto variables = std::unordered_map>{}; for (auto const &entry : symbols) { - uint32_t firstTag = nextSymbol; + uint32_t first_tag = next_symbol; for (auto *symbol : entry.second) { - if (symbol->isConcrete()) { + if (symbol->is_concrete()) { if (!instantiations.contains(*symbol)) { - instantiations.emplace(*symbol, nextSymbol++); + instantiations.emplace(*symbol, next_symbol++); } - std::string layoutStr = symbol->layoutString(this); - if (!layouts.contains(layoutStr)) { - layouts.emplace(layoutStr, nextLayout++); + std::string layout_str = symbol->layout_string(this); + if (!layouts.contains(layout_str)) { + layouts.emplace(layout_str, next_layout++); } - symbol->firstTag = symbol->lastTag = instantiations.at(*symbol); - symbol->layout = layouts.at(layoutStr); - objectSymbols[symbol->firstTag] = symbol; - allObjectSymbols[ast_to_string(*symbol)] = symbol; + symbol->first_tag_ = symbol->last_tag_ = instantiations.at(*symbol); + symbol->layout_ = layouts.at(layout_str); + object_symbols_[symbol->first_tag_] = symbol; + all_object_symbols_[ast_to_string(*symbol)] = symbol; } } - uint32_t lastTag = nextSymbol - 1; + uint32_t last_tag = next_symbol - 1; if (!entry.second.empty()) { variables.emplace( - entry.first, std::pair{firstTag, lastTag}); + entry.first, std::pair{first_tag, last_tag}); } } for (auto const &entry : symbols) { auto range = variables.at(entry.first); for (auto *symbol : entry.second) { - for (auto const &sort : symbol->getArguments()) { - if (sort->isConcrete()) { - hookedSorts[dynamic_cast(sort.get()) - ->getCategory(this)] - = std::dynamic_pointer_cast(sort); + for (auto const &sort : symbol->get_arguments()) { + if (sort->is_concrete()) { + hooked_sorts_[dynamic_cast(sort.get()) + ->get_category(this)] + = std::dynamic_pointer_cast(sort); } } - if (symbol->getSort()->isConcrete()) { - hookedSorts[dynamic_cast(symbol->getSort().get()) - ->getCategory(this)] - = std::dynamic_pointer_cast(symbol->getSort()); + if (symbol->get_sort()->is_concrete()) { + hooked_sorts_[dynamic_cast( + symbol->get_sort().get()) + ->get_category(this)] + = std::dynamic_pointer_cast( + symbol->get_sort()); } - if (!symbol->isConcrete()) { - if (symbol->isPolymorphic()) { - symbol->firstTag = range.first; - symbol->lastTag = range.second; - auto *decl = symbolDeclarations.at(symbol->getName()); - if (decl->attributes().contains(attribute_set::key::sort_injection)) { - injSymbol = symbol; + if (!symbol->is_concrete()) { + if (symbol->is_polymorphic()) { + symbol->first_tag_ = range.first; + symbol->last_tag_ = range.second; + auto *decl = symbol_declarations_.at(symbol->get_name()); + if (decl->attributes().contains(attribute_set::key::SortInjection)) { + inj_symbol_ = symbol; } } } diff --git a/lib/ast/pattern_matching.cpp b/lib/ast/pattern_matching.cpp index 6ef0c7e66..941b19d34 100644 --- a/lib/ast/pattern_matching.cpp +++ b/lib/ast/pattern_matching.cpp @@ -16,24 +16,24 @@ auto top = R"(\top)"_p; auto X = subject(any); /* - * getPatterns(\top()) = [] - * getPatterns(\and(\in(_, X), Y)) = X : getPatterns(Y) + * get_patterns(\top()) = [] + * get_patterns(\and(\in(_, X), Y)) = X : get_patterns(Y) */ -std::vector -getPatternsImpl(KOREPattern *pat, std::vector &result) { - if (auto *composite = dynamic_cast(pat)) { - if (composite->getConstructor()->getName() == "\\top" - && composite->getArguments().empty()) { +std::vector +get_patterns_impl(kore_pattern *pat, std::vector &result) { + if (auto *composite = dynamic_cast(pat)) { + if (composite->get_constructor()->get_name() == "\\top" + && composite->get_arguments().empty()) { return result; } - if (composite->getConstructor()->getName() == "\\and" - && composite->getArguments().size() == 2) { - if (auto *firstChild = dynamic_cast( - composite->getArguments()[0].get())) { - if (firstChild->getConstructor()->getName() == "\\in" - && firstChild->getArguments().size() == 2) { - result.push_back(firstChild->getArguments()[1].get()); - return getPatternsImpl(composite->getArguments()[1].get(), result); + if (composite->get_constructor()->get_name() == "\\and" + && composite->get_arguments().size() == 2) { + if (auto *first_child = dynamic_cast( + composite->get_arguments()[0].get())) { + if (first_child->get_constructor()->get_name() == "\\in" + && first_child->get_arguments().size() == 2) { + result.push_back(first_child->get_arguments()[1].get()); + return get_patterns_impl(composite->get_arguments()[1].get(), result); } } } @@ -42,44 +42,44 @@ getPatternsImpl(KOREPattern *pat, std::vector &result) { abort(); } -std::optional> -getPatterns(std::shared_ptr const &term) { - auto result = std::vector{}; - return getPatternsImpl(term.get(), result); +std::optional> +get_patterns(std::shared_ptr const &term) { + auto result = std::vector{}; + return get_patterns_impl(term.get(), result); } /* - * getBuiltin(_(X, Y)) = if X is not a builtin then X else Y + * get_builtin(_(X, Y)) = if X is not a builtin then X else Y */ -std::optional> -getBuiltin(std::shared_ptr const &term) { - auto comp = std::dynamic_pointer_cast(term); +std::optional> +get_builtin(std::shared_ptr const &term) { + auto comp = std::dynamic_pointer_cast(term); if (!comp) { return std::nullopt; } - auto lhs = std::dynamic_pointer_cast( - comp->getArguments()[0]); + auto lhs = std::dynamic_pointer_cast( + comp->get_arguments()[0]); if (!lhs) { return std::nullopt; } - if (!lhs->getConstructor()->isBuiltin()) { + if (!lhs->get_constructor()->is_builtin()) { return lhs; } - return comp->getArguments()[1]; + return comp->get_arguments()[1]; } -[[maybe_unused]] std::optional> -getSingleton(std::shared_ptr const &term) { +[[maybe_unused]] std::optional> +get_singleton(std::shared_ptr const &term) { return std::vector{term.get()}; } -std::optional> -getArguments(std::shared_ptr const &term) { - if (auto comp = std::dynamic_pointer_cast(term)) { - auto result = std::vector{}; - for (auto const &arg : comp->getArguments()) { +std::optional> +get_arguments(std::shared_ptr const &term) { + if (auto comp = std::dynamic_pointer_cast(term)) { + auto result = std::vector{}; + for (auto const &arg : comp->get_arguments()) { result.push_back(arg.get()); } return result; @@ -98,14 +98,14 @@ getArguments(std::shared_ptr const &term) { * 4: lhs(\rewrites(\and(\not(_), \and(\equals(_, _), X)), _)) = [X] * 5: lhs(\rewrites(\and(\not(_), \and(\top(), X)), _)) = [X] * 6: lhs(\equals(_(Xs), _)) = Xs - * 7: lhs(\implies(\and(\equals(_, _), X), _)) = getPatterns(X) - * 8: lhs(\implies(\and(\top(), X), _)) = getPatterns(X) - * 9: lhs(\implies(\and(\not(_), \and(\equals(_, _), X)), _)) = getPatterns(X) - * 10: lhs(\implies(\and(\not(_), \and(\top(), X)), _)) = getPatterns(X) + * 7: lhs(\implies(\and(\equals(_, _), X), _)) = get_patterns(X) + * 8: lhs(\implies(\and(\top(), X), _)) = get_patterns(X) + * 9: lhs(\implies(\and(\not(_), \and(\equals(_, _), X)), _)) = get_patterns(X) + * 10: lhs(\implies(\and(\not(_), \and(\top(), X)), _)) = get_patterns(X) * 11: lhs(\implies(\top(), \equals(_(Xs), _))) = Xs * 12: lhs(\implies(\equals(_, _), \equals(_(Xs), _))) = Xs */ -std::vector KOREAxiomDeclaration::getLeftHandSide() const { +std::vector kore_axiom_declaration::get_left_hand_side() const { auto p0 = rewrites(and_(equals_(any, any), X), any); auto p1 = rewrites(and_(X, equals_(any, any)), any); auto p2 = rewrites(and_(top(), X), any); @@ -121,13 +121,13 @@ std::vector KOREAxiomDeclaration::getLeftHandSide() const { auto p12 = implies(equals_(any, any), equals_(X, any)); auto patterns = match_first( - map(p0, getSingleton), map(p1, getSingleton), map(p2, getSingleton), - map(p3, getSingleton), map(p4, getSingleton), map(p5, getSingleton), - map(p6, getArguments), map(p7, getPatterns), map(p8, getPatterns), - map(p9, getPatterns), map(p10, getPatterns), map(p11, getArguments), - map(p12, getArguments)); + map(p0, get_singleton), map(p1, get_singleton), map(p2, get_singleton), + map(p3, get_singleton), map(p4, get_singleton), map(p5, get_singleton), + map(p6, get_arguments), map(p7, get_patterns), map(p8, get_patterns), + map(p9, get_patterns), map(p10, get_patterns), map(p11, get_arguments), + map(p12, get_arguments)); - auto [any_match, result] = patterns.match(pattern); + auto [any_match, result] = patterns.match(pattern_); if (result) { return *result; @@ -140,15 +140,15 @@ std::vector KOREAxiomDeclaration::getLeftHandSide() const { /* * 0: rhs(\implies(_, \equals(_, \and(X, _)))) = X * 1: rhs(\equals(_, X)) = X - * 2: rhs(\rewrites(_, \and(X, Y))) = getBuiltin(\and(X, Y)) + * 2: rhs(\rewrites(_, \and(X, Y))) = get_builtin(\and(X, Y)) */ -KOREPattern *KOREAxiomDeclaration::getRightHandSide() const { +kore_pattern *kore_axiom_declaration::get_right_hand_side() const { auto p0 = implies(any, equals_(any, and_(X, any))); auto p1 = equals_(any, X); auto p2 = rewrites(any, subject(and_(any, any))); - auto patterns = match_first(p0, p1, map(p2, getBuiltin)); - auto [any_match, result] = patterns.match(pattern); + auto patterns = match_first(p0, p1, map(p2, get_builtin)); + auto [any_match, result] = patterns.match(pattern_); if (result) { return result->get(); @@ -171,7 +171,7 @@ KOREPattern *KOREAxiomDeclaration::getRightHandSide() const { * 9: requires(\rewrites(\and(_, \equals(X, _)), _)) = X * 10: requires(\rewrites(\and(_, \top()), _)) = nullptr */ -KOREPattern *KOREAxiomDeclaration::getRequires() const { +kore_pattern *kore_axiom_declaration::get_requires() const { auto p0 = implies(and_(not_(any), and_(top(), any)), any); auto p1 = implies(and_(not_(any), and_(equals_(X, any), any)), any); auto p2 = implies(and_(top(), any), any); @@ -185,7 +185,7 @@ KOREPattern *KOREAxiomDeclaration::getRequires() const { auto p10 = rewrites(and_(any, top()), any); auto patterns = match_first(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10); - auto [any_match, result] = patterns.match(pattern); + auto [any_match, result] = patterns.match(pattern_); if (result) { return result->get(); @@ -202,7 +202,7 @@ KOREPattern *KOREAxiomDeclaration::getRequires() const { /* * strip(rawTerm{}(inj{S, SortKItem{}}(X))) = X */ -sptr kllvm::stripRawTerm(sptr const &term) { +sptr kllvm::strip_raw_term(sptr const &term) { auto [success, inner] = "rawTerm"_p("inj"_p(subject(any))).match(term); if (success && inner) { return inner; diff --git a/lib/binary/ProofTraceParser.cpp b/lib/binary/ProofTraceParser.cpp index 5327c7fd3..7ad0216ec 100644 --- a/lib/binary/ProofTraceParser.cpp +++ b/lib/binary/ProofTraceParser.cpp @@ -6,120 +6,122 @@ namespace kllvm { constexpr auto indent_size = 2U; -LLVMFunctionEvent::LLVMFunctionEvent( - std::string _name, std::string _relativePosition) - : name(std::move(_name)) - , relativePosition(std::move(_relativePosition)) { } +llvm_function_event::llvm_function_event( + std::string name, std::string relative_position) + : name_(std::move(name)) + , relative_position_(std::move(relative_position)) { } -std::vector const &LLVMFunctionEvent::getArguments() const { - return arguments; +std::vector const &llvm_function_event::get_arguments() const { + return arguments_; } -void LLVMFunctionEvent::addArgument(LLVMEvent const &argument) { - arguments.push_back(argument); +void llvm_function_event::add_argument(llvm_event const &argument) { + arguments_.push_back(argument); } -LLVMHookEvent::LLVMHookEvent(std::string _name, std::string _relativePosition) - : name(std::move(_name)) - , relativePosition(std::move(_relativePosition)) - , korePattern(nullptr) { } +llvm_hook_event::llvm_hook_event( + std::string name, std::string relative_position) + : name_(std::move(name)) + , relative_position_(std::move(relative_position)) + , kore_pattern_(nullptr) { } -void LLVMHookEvent::addArgument(LLVMEvent const &argument) { - arguments.push_back(argument); +void llvm_hook_event::add_argument(llvm_event const &argument) { + arguments_.push_back(argument); } -void LLVMRewriteEvent::printSubstitution( - std::ostream &Out, unsigned indent) const { - std::string Indent(indent * indent_size, ' '); - for (auto const &p : substitution) { - Out << fmt::format("{}{} = kore[{}]\n", Indent, p.first, p.second.second); +void llvm_rewrite_event::print_substitution( + std::ostream &out, unsigned ind) const { + std::string indent(ind * indent_size, ' '); + for (auto const &p : substitution_) { + out << fmt::format("{}{} = kore[{}]\n", indent, p.first, p.second.second); } } -void LLVMRuleEvent::print(std::ostream &Out, unsigned indent) const { - std::string Indent(indent * indent_size, ' '); - Out << fmt::format( - "{}rule: {} {}\n", Indent, getRuleOrdinal(), getSubstitution().size()); - printSubstitution(Out, indent + 1U); +void llvm_rule_event::print(std::ostream &out, unsigned ind) const { + std::string indent(ind * indent_size, ' '); + out << fmt::format( + "{}rule: {} {}\n", indent, get_rule_ordinal(), get_substitution().size()); + print_substitution(out, ind + 1U); } -void LLVMSideConditionEvent::print(std::ostream &Out, unsigned indent) const { - std::string Indent(indent * indent_size, ' '); - Out << fmt::format( - "{}side condition entry: {} {}\n", Indent, getRuleOrdinal(), - getSubstitution().size()); - printSubstitution(Out, indent + 1U); +void llvm_side_condition_event::print(std::ostream &out, unsigned ind) const { + std::string indent(ind * indent_size, ' '); + out << fmt::format( + "{}side condition entry: {} {}\n", indent, get_rule_ordinal(), + get_substitution().size()); + print_substitution(out, ind + 1U); } -void LLVMSideConditionEndEvent::print( - std::ostream &Out, unsigned indent) const { - std::string Indent(indent * indent_size, ' '); - Out << fmt::format( - "{}side condition exit: {} kore[{}]\n", Indent, ruleOrdinal, - patternLength); +void llvm_side_condition_end_event::print( + std::ostream &out, unsigned ind) const { + std::string indent(ind * indent_size, ' '); + out << fmt::format( + "{}side condition exit: {} kore[{}]\n", indent, rule_ordinal_, + pattern_length_); } -void LLVMFunctionEvent::print(std::ostream &Out, unsigned indent) const { - std::string Indent(indent * indent_size, ' '); - Out << fmt::format("{}function: {} ({})\n", Indent, name, relativePosition); - for (auto const &arg : arguments) { - arg.print(Out, true, indent + 1U); +void llvm_function_event::print(std::ostream &out, unsigned ind) const { + std::string indent(ind * indent_size, ' '); + out << fmt::format( + "{}function: {} ({})\n", indent, name_, relative_position_); + for (auto const &arg : arguments_) { + arg.print(out, true, ind + 1U); } } -void LLVMHookEvent::print(std::ostream &Out, unsigned indent) const { - std::string Indent(indent * indent_size, ' '); - Out << fmt::format("{}hook: {} ({})\n", Indent, name, relativePosition); - for (auto const &arg : arguments) { - arg.print(Out, true, indent + 1U); +void llvm_hook_event::print(std::ostream &out, unsigned ind) const { + std::string indent(ind * indent_size, ' '); + out << fmt::format("{}hook: {} ({})\n", indent, name_, relative_position_); + for (auto const &arg : arguments_) { + arg.print(out, true, ind + 1U); } - Out << fmt::format("{}hook result: kore[{}]\n", Indent, patternLength); + out << fmt::format("{}hook result: kore[{}]\n", indent, pattern_length_); } -void LLVMEvent::print(std::ostream &Out, bool isArg, unsigned indent) const { - if (isStepEvent) { - stepEvent->print(Out, indent); +void llvm_event::print(std::ostream &out, bool is_arg, unsigned ind) const { + if (is_step_event_) { + step_event_->print(out, ind); } else { - std::string Indent(indent * indent_size, ' '); - Out << fmt::format( - "{}{}: kore[{}]\n", Indent, isArg ? "arg" : "config", patternLength); + std::string indent(ind * indent_size, ' '); + out << fmt::format( + "{}{}: kore[{}]\n", indent, is_arg ? "arg" : "config", pattern_length_); } } -void LLVMRewriteTrace::print(std::ostream &Out, unsigned indent) const { - std::string Indent(indent * indent_size, ' '); - Out << fmt::format("{}version: {}\n", Indent, version); - for (auto const &pre_trace_event : preTrace) { - pre_trace_event.print(Out, false, indent); +void llvm_rewrite_trace::print(std::ostream &out, unsigned ind) const { + std::string indent(ind * indent_size, ' '); + out << fmt::format("{}version: {}\n", indent, version_); + for (auto const &pre_trace_event : pre_trace_) { + pre_trace_event.print(out, false, ind); } - initialConfig.print(Out, false, indent); - for (auto const &trace_event : trace) { - trace_event.print(Out, false, indent); + initial_config_.print(out, false, ind); + for (auto const &trace_event : trace_) { + trace_event.print(out, false, ind); } } -ProofTraceParser::ProofTraceParser(bool _verbose) - : verbose(_verbose) { } +proof_trace_parser::proof_trace_parser(bool verbose) + : verbose_(verbose) { } -std::optional -ProofTraceParser::parse_proof_trace(std::string const &data) { +std::optional +proof_trace_parser::parse_proof_trace(std::string const &data) { auto ptr = data.begin(); - LLVMRewriteTrace trace; + llvm_rewrite_trace trace; bool result = parse_trace(ptr, data.end(), trace); if (!result || ptr != data.end()) { return std::nullopt; } - if (verbose) { + if (verbose_) { trace.print(std::cout); } return trace; } -std::optional -ProofTraceParser::parse_proof_trace_from_file(std::string const &filename) { +std::optional +proof_trace_parser::parse_proof_trace_from_file(std::string const &filename) { auto data = file_contents(filename); return parse_proof_trace(data); } diff --git a/lib/binary/deserializer.cpp b/lib/binary/deserializer.cpp index 6cb570a54..5a1594efb 100644 --- a/lib/binary/deserializer.cpp +++ b/lib/binary/deserializer.cpp @@ -32,7 +32,7 @@ bool has_binary_kore_header(std::string const &filename) { return std::equal(reference.begin(), reference.end(), first_bytes.begin()); } -sptr deserialize_pattern(std::string const &filename) { +sptr deserialize_pattern(std::string const &filename) { auto data = file_contents(filename); return deserialize_pattern(data.begin(), data.end()); } diff --git a/lib/binary/serializer.cpp b/lib/binary/serializer.cpp index a0d13099c..58d63a5e7 100644 --- a/lib/binary/serializer.cpp +++ b/lib/binary/serializer.cpp @@ -17,9 +17,9 @@ serializer::serializer() : serializer(NONE) { } serializer::serializer(flags f) - : use_header_(!(f & DROP_HEADER)) - , use_arity_(!(f & DROP_ARITY)) - , use_intern_(!(f & NO_INTERN)) + : use_header_(!(f & DropHeader)) + , use_arity_(!(f & DropArity)) + , use_intern_(!(f & NoIntern)) , direct_string_prefix_{0x01} , backref_string_prefix_{0x02} , next_idx_(0) { diff --git a/lib/codegen/ApplyPasses.cpp b/lib/codegen/ApplyPasses.cpp index b25df772c..bd1e89510 100644 --- a/lib/codegen/ApplyPasses.cpp +++ b/lib/codegen/ApplyPasses.cpp @@ -27,7 +27,7 @@ using namespace llvm; namespace kllvm { CodeGenOpt::Level get_opt_level() { - switch (OptimizationLevel) { + switch (optimization_level) { case opt_level::O0: return CodeGenOpt::None; case opt_level::O1: return CodeGenOpt::Less; case opt_level::O2: return CodeGenOpt::Default; @@ -45,7 +45,7 @@ void apply_kllvm_opt_passes(llvm::Module &mod) { } void generate_object_file(llvm::Module &mod, llvm::raw_ostream &os) { - if (KeepFramePointer) { + if (keep_frame_pointer) { mod.setFramePointer(FramePointerKind::All); } else { mod.setFramePointer(FramePointerKind::None); diff --git a/lib/codegen/CreateStaticTerm.cpp b/lib/codegen/CreateStaticTerm.cpp index 0f1187574..8e224bf47 100644 --- a/lib/codegen/CreateStaticTerm.cpp +++ b/lib/codegen/CreateStaticTerm.cpp @@ -29,103 +29,105 @@ namespace kllvm { /* create a term, given the assumption that the created term will not be a * triangle injection pair */ -llvm::Constant *CreateStaticTerm::notInjectionCase( - KORECompositePattern *constructor, llvm::Constant *val) { - KORESymbol const *symbol = constructor->getConstructor(); - llvm::StructType *BlockType = getBlockType(Module, Definition, symbol); +llvm::Constant *create_static_term::not_injection_case( + kore_composite_pattern *constructor, llvm::Constant *val) { + kore_symbol const *symbol = constructor->get_constructor(); + llvm::StructType *block_type = get_block_type(module_, definition_, symbol); - std::stringstream koreString; - constructor->print(koreString); - llvm::Constant *Block - = Module->getOrInsertGlobal(koreString.str(), BlockType); - auto *globalVar = llvm::dyn_cast(Block); + std::stringstream kore_string; + constructor->print(kore_string); + llvm::Constant *block + = module_->getOrInsertGlobal(kore_string.str(), block_type); + auto *global_var = llvm::dyn_cast(block); - if (!globalVar->hasInitializer()) { - std::vector blockVals; + if (!global_var->hasInitializer()) { + std::vector block_vals; - llvm::StructType *BlockHeaderType = llvm::StructType::getTypeByName( - Module->getContext(), BLOCKHEADER_STRUCT); - uint64_t headerVal - = getBlockHeaderVal(Module, symbol, BlockType) | NOT_YOUNG_OBJECT_BIT; - llvm::Constant *BlockHeader = llvm::ConstantStruct::get( - BlockHeaderType, + llvm::StructType *block_header_type = llvm::StructType::getTypeByName( + module_->getContext(), blockheader_struct); + uint64_t header_val = get_block_header_val(module_, symbol, block_type) + | NOT_YOUNG_OBJECT_BIT; + llvm::Constant *block_header = llvm::ConstantStruct::get( + block_header_type, llvm::ConstantInt::get( - llvm::Type::getInt64Ty(Module->getContext()), headerVal)); - blockVals.push_back(BlockHeader); + llvm::Type::getInt64Ty(module_->getContext()), header_val)); + block_vals.push_back(block_header); - llvm::ArrayType *EmptyArrayType - = llvm::ArrayType::get(llvm::Type::getInt64Ty(Module->getContext()), 0); - blockVals.push_back(llvm::ConstantArray::get( - EmptyArrayType, llvm::ArrayRef())); + llvm::ArrayType *empty_array_type = llvm::ArrayType::get( + llvm::Type::getInt64Ty(module_->getContext()), 0); + block_vals.push_back(llvm::ConstantArray::get( + empty_array_type, llvm::ArrayRef())); int idx = 2; - for (auto const &child : constructor->getArguments()) { - llvm::Constant *ChildValue = nullptr; + for (auto const &child : constructor->get_arguments()) { + llvm::Constant *child_value = nullptr; if (idx++ == 2 && val != nullptr) { - ChildValue = val; + child_value = val; } else { - ChildValue = (*this)(child.get()).first; + child_value = (*this)(child.get()).first; } - blockVals.push_back(ChildValue); + block_vals.push_back(child_value); } - globalVar->setInitializer(llvm::ConstantExpr::getBitCast( - llvm::ConstantStruct::get(BlockType, blockVals), BlockType)); + global_var->setInitializer(llvm::ConstantExpr::getBitCast( + llvm::ConstantStruct::get(block_type, block_vals), block_type)); } - std::vector Idxs - = {llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), 0)}; + std::vector idxs + = {llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx_), 0)}; return llvm::ConstantExpr::getBitCast( - llvm::ConstantExpr::getInBoundsGetElementPtr(BlockType, globalVar, Idxs), - llvm::PointerType::getUnqual( - llvm::StructType::getTypeByName(Module->getContext(), BLOCK_STRUCT))); + llvm::ConstantExpr::getInBoundsGetElementPtr( + block_type, global_var, idxs), + llvm::PointerType::getUnqual(llvm::StructType::getTypeByName( + module_->getContext(), block_struct))); } std::pair -CreateStaticTerm::operator()(KOREPattern *pattern) { - if (auto *constructor = dynamic_cast(pattern)) { - KORESymbol const *symbol = constructor->getConstructor(); - assert(symbol->isConcrete() && "not supported yet: sort variables"); - if (symbol->getName() == "\\dv") { - auto *sort = dynamic_cast( - symbol->getFormalArguments()[0].get()); - auto *strPattern = dynamic_cast( - constructor->getArguments()[0].get()); +create_static_term::operator()(kore_pattern *pattern) { + if (auto *constructor = dynamic_cast(pattern)) { + kore_symbol const *symbol = constructor->get_constructor(); + assert(symbol->is_concrete() && "not supported yet: sort variables"); + if (symbol->get_name() == "\\dv") { + auto *sort = dynamic_cast( + symbol->get_formal_arguments()[0].get()); + auto *str_pattern = dynamic_cast( + constructor->get_arguments()[0].get()); return std::make_pair( - createToken(sort->getCategory(Definition), strPattern->getContents()), + create_token( + sort->get_category(definition_), str_pattern->get_contents()), false); } - if (symbol->getArguments().empty()) { - llvm::StructType *BlockType - = llvm::StructType::getTypeByName(Module->getContext(), BLOCK_STRUCT); - llvm::Constant *Cast = llvm::ConstantExpr::getIntToPtr( + if (symbol->get_arguments().empty()) { + llvm::StructType *block_type = llvm::StructType::getTypeByName( + module_->getContext(), block_struct); + llvm::Constant *cast = llvm::ConstantExpr::getIntToPtr( llvm::ConstantInt::get( - llvm::Type::getInt64Ty(Ctx), - (((uint64_t)symbol->getTag()) << 32) | 1), - llvm::PointerType::getUnqual(BlockType)); - return std::make_pair(Cast, false); + llvm::Type::getInt64Ty(ctx_), + (((uint64_t)symbol->get_tag()) << 32) | 1), + llvm::PointerType::getUnqual(block_type)); + return std::make_pair(cast, false); } - KORESymbolDeclaration *symbolDecl - = Definition->getSymbolDeclarations().at(symbol->getName()); - if (symbolDecl->attributes().contains(attribute_set::key::sort_injection) - && dynamic_cast(symbol->getArguments()[0].get()) - ->getCategory(Definition) + kore_symbol_declaration *symbol_decl + = definition_->get_symbol_declarations().at(symbol->get_name()); + if (symbol_decl->attributes().contains(attribute_set::key::SortInjection) + && dynamic_cast(symbol->get_arguments()[0].get()) + ->get_category(definition_) .cat - == SortCategory::Symbol) { + == sort_category::Symbol) { std::pair val - = (*this)(constructor->getArguments()[0].get()); + = (*this)(constructor->get_arguments()[0].get()); if (val.second) { - uint32_t tag = symbol->getTag(); - KORESymbol *inj = Definition->getInjSymbol(); - if (tag != (uint32_t)-1 && tag >= inj->getFirstTag() - && tag <= inj->getLastTag()) { + uint32_t tag = symbol->get_tag(); + kore_symbol *inj = definition_->get_inj_symbol(); + if (tag != (uint32_t)-1 && tag >= inj->get_first_tag() + && tag <= inj->get_last_tag()) { return std::make_pair(val.first, true); } - return std::make_pair(notInjectionCase(constructor, val.first), true); + return std::make_pair(not_injection_case(constructor, val.first), true); } - return std::make_pair(notInjectionCase(constructor, val.first), true); + return std::make_pair(not_injection_case(constructor, val.first), true); } - return std::make_pair(notInjectionCase(constructor, nullptr), false); + return std::make_pair(not_injection_case(constructor, nullptr), false); } assert(false && "Something went wrong when trying to allocate a static term"); abort(); @@ -133,73 +135,74 @@ CreateStaticTerm::operator()(KOREPattern *pattern) { // NOLINTBEGIN(*-cognitive-complexity) llvm::Constant * -CreateStaticTerm::createToken(ValueType sort, std::string contents) { +create_static_term::create_token(value_type sort, std::string contents) { switch (sort.cat) { - case SortCategory::Map: - case SortCategory::RangeMap: - case SortCategory::List: - case SortCategory::Set: + case sort_category::Map: + case sort_category::RangeMap: + case sort_category::List: + case sort_category::Set: assert(false && "cannot create tokens of collection category"); - case SortCategory::Int: { - llvm::Constant *global = Module->getOrInsertGlobal( + case sort_category::Int: { + llvm::Constant *global = module_->getOrInsertGlobal( "int_" + contents, llvm::StructType::getTypeByName( - Module->getContext(), INT_WRAPPER_STRUCT)); - auto *globalVar = llvm::dyn_cast(global); - if (!globalVar->hasInitializer()) { + module_->getContext(), int_wrapper_struct)); + auto *global_var = llvm::dyn_cast(global); + if (!global_var->hasInitializer()) { mpz_t value; - char const *dataStart + char const *data_start = contents.at(0) == '+' ? contents.c_str() + 1 : contents.c_str(); - mpz_init_set_str(value, dataStart, 10); + mpz_init_set_str(value, data_start, 10); size_t size = mpz_size(value); int sign = mpz_sgn(value); - llvm::ArrayType *limbsType - = llvm::ArrayType::get(llvm::Type::getInt64Ty(Ctx), size); - llvm::Constant *limbs - = Module->getOrInsertGlobal("int_" + contents + "_limbs", limbsType); - auto *limbsVar = llvm::dyn_cast(limbs); - std::vector allocdLimbs; + llvm::ArrayType *limbs_type + = llvm::ArrayType::get(llvm::Type::getInt64Ty(ctx_), size); + llvm::Constant *limbs = module_->getOrInsertGlobal( + "int_" + contents + "_limbs", limbs_type); + auto *limbs_var = llvm::dyn_cast(limbs); + std::vector allocd_limbs; for (size_t i = 0; i < size; i++) { - allocdLimbs.push_back(llvm::ConstantInt::get( - llvm::Type::getInt64Ty(Ctx), value->_mp_d[i])); + allocd_limbs.push_back(llvm::ConstantInt::get( + llvm::Type::getInt64Ty(ctx_), value->_mp_d[i])); } - limbsVar->setInitializer( - llvm::ConstantArray::get(limbsType, allocdLimbs)); + limbs_var->setInitializer( + llvm::ConstantArray::get(limbs_type, allocd_limbs)); llvm::Constant *hdr = llvm::ConstantStruct::get( llvm::StructType::getTypeByName( - Module->getContext(), BLOCKHEADER_STRUCT), + module_->getContext(), blockheader_struct), llvm::ConstantInt::get( - llvm::Type::getInt64Ty(Ctx), + llvm::Type::getInt64Ty(ctx_), sizeof(mpz_hdr) - sizeof(blockheader) | NOT_YOUNG_OBJECT_BIT)); - llvm::ConstantInt *numLimbs - = llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), size); + llvm::ConstantInt *num_limbs + = llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx_), size); llvm::Constant *mp_size = llvm::ConstantExpr::getMul( - numLimbs, - llvm::ConstantInt::getSigned(llvm::Type::getInt32Ty(Ctx), sign)); - globalVar->setInitializer(llvm::ConstantStruct::get( + num_limbs, + llvm::ConstantInt::getSigned(llvm::Type::getInt32Ty(ctx_), sign)); + global_var->setInitializer(llvm::ConstantStruct::get( llvm::StructType::getTypeByName( - Module->getContext(), INT_WRAPPER_STRUCT), + module_->getContext(), int_wrapper_struct), hdr, llvm::ConstantStruct::get( - llvm::StructType::getTypeByName(Module->getContext(), INT_STRUCT), - numLimbs, mp_size, + llvm::StructType::getTypeByName( + module_->getContext(), int_struct), + num_limbs, mp_size, llvm::ConstantExpr::getPointerCast( - limbsVar, llvm::Type::getInt64PtrTy(Ctx))))); + limbs_var, llvm::Type::getInt64PtrTy(ctx_))))); mpz_clear(value); } - std::vector Idxs - = {llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), 0), - llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1)}; + std::vector idxs + = {llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx_), 0), + llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx_), 1)}; return llvm::ConstantExpr::getInBoundsGetElementPtr( llvm::StructType::getTypeByName( - Module->getContext(), INT_WRAPPER_STRUCT), - globalVar, Idxs); + module_->getContext(), int_wrapper_struct), + global_var, idxs); } - case SortCategory::Float: { - llvm::Constant *global = Module->getOrInsertGlobal( + case sort_category::Float: { + llvm::Constant *global = module_->getOrInsertGlobal( "float_" + contents, llvm::StructType::getTypeByName( - Module->getContext(), FLOAT_WRAPPER_STRUCT)); - auto *globalVar = llvm::dyn_cast(global); - if (!globalVar->hasInitializer()) { + module_->getContext(), float_wrapper_struct)); + auto *global_var = llvm::dyn_cast(global); + if (!global_var->hasInitializer()) { size_t prec = 0; size_t exp = 0; char const last = contents.back(); @@ -222,114 +225,114 @@ CreateStaticTerm::createToken(ValueType sort, std::string contents) { } mpfr_t value; mpfr_init2(value, prec); - int retValue = 0; + int ret_value = 0; if (contents == "+Infinity" || contents == "-Infinity" || contents == "Infinity") { - retValue = mpfr_set_str(value, contents.c_str(), 10, MPFR_RNDN); + ret_value = mpfr_set_str(value, contents.c_str(), 10, MPFR_RNDN); } else { size_t last = contents.find_last_of("fFdDpP"); std::string str_value = contents.substr(0, last); - retValue = mpfr_set_str(value, str_value.c_str(), 10, MPFR_RNDN); + ret_value = mpfr_set_str(value, str_value.c_str(), 10, MPFR_RNDN); } - if (retValue != 0) { + if (ret_value != 0) { throw std::invalid_argument("Can't convert to float"); } size_t size = (prec + 63) / 64; - llvm::ArrayType *limbsType - = llvm::ArrayType::get(llvm::Type::getInt64Ty(Ctx), size); - llvm::Constant *limbs = Module->getOrInsertGlobal( - "float_" + contents + "_limbs", limbsType); - auto *limbsVar = llvm::dyn_cast(limbs); - std::vector allocdLimbs; + llvm::ArrayType *limbs_type + = llvm::ArrayType::get(llvm::Type::getInt64Ty(ctx_), size); + llvm::Constant *limbs = module_->getOrInsertGlobal( + "float_" + contents + "_limbs", limbs_type); + auto *limbs_var = llvm::dyn_cast(limbs); + std::vector allocd_limbs; for (size_t i = 0; i < size; i++) { - allocdLimbs.push_back(llvm::ConstantInt::get( - llvm::Type::getInt64Ty(Ctx), value->_mpfr_d[i])); + allocd_limbs.push_back(llvm::ConstantInt::get( + llvm::Type::getInt64Ty(ctx_), value->_mpfr_d[i])); } - limbsVar->setInitializer( - llvm::ConstantArray::get(limbsType, allocdLimbs)); + limbs_var->setInitializer( + llvm::ConstantArray::get(limbs_type, allocd_limbs)); llvm::Constant *hdr = llvm::ConstantStruct::get( llvm::StructType::getTypeByName( - Module->getContext(), BLOCKHEADER_STRUCT), + module_->getContext(), blockheader_struct), llvm::ConstantInt::get( - llvm::Type::getInt64Ty(Ctx), + llvm::Type::getInt64Ty(ctx_), (sizeof(floating_hdr) - sizeof(blockheader)) | NOT_YOUNG_OBJECT_BIT)); llvm::Constant *expbits - = llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), exp); + = llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx_), exp); llvm::Constant *mpfr_prec - = llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), prec); + = llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx_), prec); llvm::Constant *mpfr_sign = llvm::ConstantInt::getSigned( - llvm::Type::getInt32Ty(Ctx), value->_mpfr_sign); + llvm::Type::getInt32Ty(ctx_), value->_mpfr_sign); llvm::Constant *mpfr_exp = llvm::ConstantInt::getSigned( - llvm::Type::getInt64Ty(Ctx), value->_mpfr_exp); + llvm::Type::getInt64Ty(ctx_), value->_mpfr_exp); // create struct floating with an exponent range and an __mpfr_struct. // Note that we are assuming the format of the struct, but it's unlikely // to change except possibly between major releases which happen less than // once every couple years, because the C++ ABI depends on it. We are also // assuming that the host and target have the same arch, but since we // don't yet support cross compiling anyway, that's a safe assumption. - globalVar->setInitializer(llvm::ConstantStruct::get( + global_var->setInitializer(llvm::ConstantStruct::get( llvm::StructType::getTypeByName( - Module->getContext(), FLOAT_WRAPPER_STRUCT), + module_->getContext(), float_wrapper_struct), hdr, llvm::ConstantStruct::get( llvm::StructType::getTypeByName( - Module->getContext(), FLOAT_STRUCT), + module_->getContext(), float_struct), expbits, llvm::ConstantStruct::getAnon( {mpfr_prec, mpfr_sign, mpfr_exp, llvm::ConstantExpr::getPointerCast( - limbsVar, llvm::Type::getInt64PtrTy(Ctx))})))); + limbs_var, llvm::Type::getInt64PtrTy(ctx_))})))); mpfr_clear(value); } - std::vector Idxs - = {llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), 0), - llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1)}; + std::vector idxs + = {llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx_), 0), + llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx_), 1)}; return llvm::ConstantExpr::getInBoundsGetElementPtr( llvm::StructType::getTypeByName( - Module->getContext(), FLOAT_WRAPPER_STRUCT), - globalVar, Idxs); + module_->getContext(), float_wrapper_struct), + global_var, idxs); } - case SortCategory::StringBuffer: + case sort_category::StringBuffer: assert(false && "not implemented yet: tokens"); - case SortCategory::MInt: { + case sort_category::MInt: { size_t idx = contents.find_first_of("pP"); assert(idx != std::string::npos); uint64_t bits = std::stoi(contents.substr(idx + 1)); return llvm::ConstantInt::get( - llvm::IntegerType::get(Ctx, bits), contents.substr(0, idx), 10); + llvm::IntegerType::get(ctx_, bits), contents.substr(0, idx), 10); } - case SortCategory::Bool: + case sort_category::Bool: return llvm::ConstantInt::get( - llvm::Type::getInt1Ty(Ctx), contents == "true"); - case SortCategory::Variable: - case SortCategory::Symbol: { - llvm::StructType *StringType = llvm::StructType::get( - Ctx, + llvm::Type::getInt1Ty(ctx_), contents == "true"); + case sort_category::Variable: + case sort_category::Symbol: { + llvm::StructType *string_type = llvm::StructType::get( + ctx_, {llvm::StructType::getTypeByName( - Module->getContext(), BLOCKHEADER_STRUCT), - llvm::ArrayType::get(llvm::Type::getInt8Ty(Ctx), contents.size())}); + module_->getContext(), blockheader_struct), + llvm::ArrayType::get(llvm::Type::getInt8Ty(ctx_), contents.size())}); llvm::Constant *global - = Module->getOrInsertGlobal("token_" + escape(contents), StringType); - auto *globalVar = llvm::dyn_cast(global); - if (!globalVar->hasInitializer()) { - llvm::StructType *BlockHeaderType = llvm::StructType::getTypeByName( - Module->getContext(), BLOCKHEADER_STRUCT); + = module_->getOrInsertGlobal("token_" + escape(contents), string_type); + auto *global_var = llvm::dyn_cast(global); + if (!global_var->hasInitializer()) { + llvm::StructType *block_header_type = llvm::StructType::getTypeByName( + module_->getContext(), blockheader_struct); // this object does not live on the young generation, so we need to set // the correct gc bit. - llvm::Constant *BlockHeader = llvm::ConstantStruct::get( - BlockHeaderType, llvm::ConstantInt::get( - llvm::Type::getInt64Ty(Ctx), - contents.size() | NOT_YOUNG_OBJECT_BIT)); - globalVar->setInitializer(llvm::ConstantStruct::get( - StringType, BlockHeader, - llvm::ConstantDataArray::getString(Ctx, contents, false))); + llvm::Constant *block_header = llvm::ConstantStruct::get( + block_header_type, llvm::ConstantInt::get( + llvm::Type::getInt64Ty(ctx_), + contents.size() | NOT_YOUNG_OBJECT_BIT)); + global_var->setInitializer(llvm::ConstantStruct::get( + string_type, block_header, + llvm::ConstantDataArray::getString(ctx_, contents, false))); } return llvm::ConstantExpr::getPointerCast( global, llvm::PointerType::getUnqual(llvm::StructType::getTypeByName( - Module->getContext(), BLOCK_STRUCT))); + module_->getContext(), block_struct))); } - case SortCategory::Uncomputed: abort(); + case sort_category::Uncomputed: abort(); } } // NOLINTEND(*-cognitive-complexity) diff --git a/lib/codegen/CreateTerm.cpp b/lib/codegen/CreateTerm.cpp index 62d1744e3..0e79a5342 100644 --- a/lib/codegen/CreateTerm.cpp +++ b/lib/codegen/CreateTerm.cpp @@ -111,197 +111,199 @@ target triple = "{triple}" ; %layoutN = type { %blockheader, [0 x i64 *], %map, %mpz *, %block * } ; Interface to the configuration parser -declare %block* @parseConfiguration(i8*) -declare void @printConfiguration(i8 *, %block *) +declare %block* @parse_configuration(i8*) +declare void @print_configuration(i8 *, %block *) )LLVM"; return target_dependent + rest; } } // namespace std::unique_ptr -newModule(std::string const &name, llvm::LLVMContext &Context) { - llvm::SMDiagnostic Err; +new_module(std::string const &name, llvm::LLVMContext &context) { + llvm::SMDiagnostic err; auto mod = llvm::parseIR( - *llvm::MemoryBuffer::getMemBuffer(llvm_header()), Err, Context); + *llvm::MemoryBuffer::getMemBuffer(llvm_header()), err, context); if (!mod) { - Err.print("header.ll", llvm::errs()); + err.print("header.ll", llvm::errs()); } return mod; } -std::string MAP_STRUCT = "map"; -std::string RANGEMAP_STRUCT = "rangemap"; -std::string LIST_STRUCT = "list"; -std::string SET_STRUCT = "set"; -std::string INT_WRAPPER_STRUCT = "mpz_hdr"; -std::string INT_STRUCT = "mpz"; -std::string FLOAT_WRAPPER_STRUCT = "floating_hdr"; -std::string FLOAT_STRUCT = "floating"; -std::string BUFFER_STRUCT = "stringbuffer"; -std::string BLOCK_STRUCT = "block"; -std::string BLOCKHEADER_STRUCT = "blockheader"; - -llvm::Type *getParamType(ValueType sort, llvm::Module *Module) { - llvm::Type *type = getValueType(sort, Module); +std::string map_struct = "map"; +std::string rangemap_struct = "rangemap"; +std::string list_struct = "list"; +std::string set_struct = "set"; +std::string int_wrapper_struct = "mpz_hdr"; +std::string int_struct = "mpz"; +std::string float_wrapper_struct = "floating_hdr"; +std::string float_struct = "floating"; +std::string buffer_struct = "stringbuffer"; +std::string block_struct = "block"; +std::string blockheader_struct = "blockheader"; + +llvm::Type *get_param_type(value_type sort, llvm::Module *module) { + llvm::Type *type = getvalue_type(sort, module); switch (sort.cat) { - case SortCategory::Map: - case SortCategory::RangeMap: - case SortCategory::List: - case SortCategory::Set: type = llvm::PointerType::getUnqual(type); break; + case sort_category::Map: + case sort_category::RangeMap: + case sort_category::List: + case sort_category::Set: type = llvm::PointerType::getUnqual(type); break; default: break; } return type; } -llvm::StructType *getBlockType(llvm::Module *Module) { - return llvm::StructType::getTypeByName(Module->getContext(), BLOCK_STRUCT); +llvm::StructType *get_block_type(llvm::Module *module) { + return llvm::StructType::getTypeByName(module->getContext(), block_struct); } -llvm::Type *getValueType(ValueType sort, llvm::Module *Module) { +llvm::Type *getvalue_type(value_type sort, llvm::Module *module) { switch (sort.cat) { - case SortCategory::Map: - return llvm::StructType::getTypeByName(Module->getContext(), MAP_STRUCT); - case SortCategory::RangeMap: + case sort_category::Map: + return llvm::StructType::getTypeByName(module->getContext(), map_struct); + case sort_category::RangeMap: return llvm::StructType::getTypeByName( - Module->getContext(), RANGEMAP_STRUCT); - case SortCategory::List: - return llvm::StructType::getTypeByName(Module->getContext(), LIST_STRUCT); - case SortCategory::Set: - return llvm::StructType::getTypeByName(Module->getContext(), SET_STRUCT); - case SortCategory::Int: + module->getContext(), rangemap_struct); + case sort_category::List: + return llvm::StructType::getTypeByName(module->getContext(), list_struct); + case sort_category::Set: + return llvm::StructType::getTypeByName(module->getContext(), set_struct); + case sort_category::Int: return llvm::PointerType::getUnqual( - llvm::StructType::getTypeByName(Module->getContext(), INT_STRUCT)); - case SortCategory::Float: + llvm::StructType::getTypeByName(module->getContext(), int_struct)); + case sort_category::Float: return llvm::PointerType::getUnqual( - llvm::StructType::getTypeByName(Module->getContext(), FLOAT_STRUCT)); - case SortCategory::StringBuffer: + llvm::StructType::getTypeByName(module->getContext(), float_struct)); + case sort_category::StringBuffer: return llvm::PointerType::getUnqual( - llvm::StructType::getTypeByName(Module->getContext(), BUFFER_STRUCT)); - case SortCategory::Bool: return llvm::Type::getInt1Ty(Module->getContext()); - case SortCategory::MInt: - return llvm::IntegerType::get(Module->getContext(), sort.bits); - case SortCategory::Symbol: - case SortCategory::Variable: + llvm::StructType::getTypeByName(module->getContext(), buffer_struct)); + case sort_category::Bool: return llvm::Type::getInt1Ty(module->getContext()); + case sort_category::MInt: + return llvm::IntegerType::get(module->getContext(), sort.bits); + case sort_category::Symbol: + case sort_category::Variable: return llvm::PointerType::getUnqual( - llvm::StructType::getTypeByName(Module->getContext(), BLOCK_STRUCT)); - case SortCategory::Uncomputed: abort(); + llvm::StructType::getTypeByName(module->getContext(), block_struct)); + case sort_category::Uncomputed: abort(); } } -llvm::StructType *getBlockType( - llvm::Module *Module, KOREDefinition *definition, - KORESymbol const *symbol) { - llvm::StructType *BlockHeaderType = llvm::StructType::getTypeByName( - Module->getContext(), BLOCKHEADER_STRUCT); - llvm::ArrayType *EmptyArrayType - = llvm::ArrayType::get(llvm::Type::getInt64Ty(Module->getContext()), 0); - llvm::SmallVector Types; - Types.push_back(BlockHeaderType); - Types.push_back(EmptyArrayType); - for (auto const &arg : symbol->getArguments()) { - auto *sort = dynamic_cast(arg.get()); - llvm::Type *type = getValueType(sort->getCategory(definition), Module); - Types.push_back(type); +llvm::StructType *get_block_type( + llvm::Module *module, kore_definition *definition, + kore_symbol const *symbol) { + llvm::StructType *block_header_type = llvm::StructType::getTypeByName( + module->getContext(), blockheader_struct); + llvm::ArrayType *empty_array_type + = llvm::ArrayType::get(llvm::Type::getInt64Ty(module->getContext()), 0); + llvm::SmallVector types; + types.push_back(block_header_type); + types.push_back(empty_array_type); + for (auto const &arg : symbol->get_arguments()) { + auto *sort = dynamic_cast(arg.get()); + llvm::Type *type = getvalue_type(sort->get_category(definition), module); + types.push_back(type); } - return llvm::StructType::get(Module->getContext(), Types); + return llvm::StructType::get(module->getContext(), types); } -uint64_t getBlockHeaderVal( - llvm::Module *Module, KORESymbol const *symbol, llvm::Type *BlockType) { - uint64_t headerVal = symbol->getTag(); - uint64_t sizeInBytes = llvm::DataLayout(Module).getTypeAllocSize(BlockType); - assert(sizeInBytes % 8 == 0); - headerVal |= (sizeInBytes / 8) << 32; - headerVal |= (uint64_t)symbol->getLayout() << LAYOUT_OFFSET; - return headerVal; +uint64_t get_block_header_val( + llvm::Module *module, kore_symbol const *symbol, llvm::Type *block_type) { + uint64_t header_val = symbol->get_tag(); + uint64_t size_in_bytes + = llvm::DataLayout(module).getTypeAllocSize(block_type); + assert(size_in_bytes % 8 == 0); + header_val |= (size_in_bytes / 8) << 32; + header_val |= (uint64_t)symbol->get_layout() << LAYOUT_OFFSET; + return header_val; } -llvm::Value *getBlockHeader( - llvm::Module *Module, KOREDefinition *definition, KORESymbol const *symbol, - llvm::Type *BlockType) { - llvm::StructType *BlockHeaderType = llvm::StructType::getTypeByName( - Module->getContext(), BLOCKHEADER_STRUCT); - uint64_t headerVal = getBlockHeaderVal(Module, symbol, BlockType); +llvm::Value *get_block_header( + llvm::Module *module, kore_definition *definition, + kore_symbol const *symbol, llvm::Type *block_type) { + llvm::StructType *block_header_type = llvm::StructType::getTypeByName( + module->getContext(), blockheader_struct); + uint64_t header_val = get_block_header_val(module, symbol, block_type); return llvm::ConstantStruct::get( - BlockHeaderType, + block_header_type, llvm::ConstantInt::get( - llvm::Type::getInt64Ty(Module->getContext()), headerVal)); + llvm::Type::getInt64Ty(module->getContext()), header_val)); } -llvm::Value *allocateTerm( - llvm::Type *AllocType, llvm::BasicBlock *block, char const *allocFn) { - return allocateTerm( - AllocType, llvm::ConstantExpr::getSizeOf(AllocType), block, allocFn); +llvm::Value *allocate_term( + llvm::Type *alloc_type, llvm::BasicBlock *block, char const *alloc_fn) { + return allocate_term( + alloc_type, llvm::ConstantExpr::getSizeOf(alloc_type), block, alloc_fn); } -llvm::Value *allocateTerm( - llvm::Type *AllocType, llvm::Value *Len, llvm::BasicBlock *block, - char const *allocFn) { - llvm::Instruction *Malloc = llvm::CallInst::CreateMalloc( - block, llvm::Type::getInt64Ty(block->getContext()), AllocType, Len, - nullptr, koreHeapAlloc(allocFn, block->getModule())); +llvm::Value *allocate_term( + llvm::Type *alloc_type, llvm::Value *len, llvm::BasicBlock *block, + char const *alloc_fn) { + llvm::Instruction *malloc = llvm::CallInst::CreateMalloc( + block, llvm::Type::getInt64Ty(block->getContext()), alloc_type, len, + nullptr, kore_heap_alloc(alloc_fn, block->getModule())); if (!block->empty()) { - setDebugLoc(&block->back()); + set_debug_loc(&block->back()); } #if LLVM_VERSION_MAJOR < 16 - Malloc->insertAfter(&block->back()); + malloc->insertAfter(&block->back()); #else - Malloc->insertInto(block, block->end()); + malloc->insertInto(block, block->end()); #endif - return Malloc; + return malloc; } -ValueType termType( - KOREPattern *pattern, llvm::StringMap &substitution, - KOREDefinition *definition) { - if (auto *variable = dynamic_cast(pattern)) { - return substitution.lookup(variable->getName()); +value_type term_type( + kore_pattern *pattern, llvm::StringMap &substitution, + kore_definition *definition) { + if (auto *variable = dynamic_cast(pattern)) { + return substitution.lookup(variable->get_name()); } - if (auto *constructor = dynamic_cast(pattern)) { - KORESymbol *symbol = constructor->getConstructor(); - assert(symbol->isConcrete() && "not supported yet: sort variables"); - if (symbol->getName() == "\\dv") { - auto *sort = dynamic_cast( - symbol->getFormalArguments()[0].get()); - return sort->getCategory(definition); + if (auto *constructor = dynamic_cast(pattern)) { + kore_symbol *symbol = constructor->get_constructor(); + assert(symbol->is_concrete() && "not supported yet: sort variables"); + if (symbol->get_name() == "\\dv") { + auto *sort = dynamic_cast( + symbol->get_formal_arguments()[0].get()); + return sort->get_category(definition); } - auto *sort = dynamic_cast(symbol->getSort().get()); - return sort->getCategory(definition); + auto *sort = dynamic_cast(symbol->get_sort().get()); + return sort->get_category(definition); } assert(false && "not supported yet: meta level"); abort(); } -sptr termSort(KOREPattern *pattern) { - if (auto *variable = dynamic_cast(pattern)) { - return variable->getSort(); +sptr term_sort(kore_pattern *pattern) { + if (auto *variable = dynamic_cast(pattern)) { + return variable->get_sort(); } - if (auto *constructor = dynamic_cast(pattern)) { - KORESymbol *symbol = constructor->getConstructor(); - assert(symbol->isConcrete() && "not supported yet: sort variables"); - if (symbol->getName() == "\\dv") { - return symbol->getFormalArguments()[0]; + if (auto *constructor = dynamic_cast(pattern)) { + kore_symbol *symbol = constructor->get_constructor(); + assert(symbol->is_concrete() && "not supported yet: sort variables"); + if (symbol->get_name() == "\\dv") { + return symbol->get_formal_arguments()[0]; } - return symbol->getSort(); + return symbol->get_sort(); } assert(false && "not supported yet: meta level"); abort(); } -llvm::Value *CreateTerm::alloc_arg( - KORECompositePattern *pattern, int idx, std::string const &locationStack) { - KOREPattern *p = pattern->getArguments()[idx].get(); - std::string newLocation = fmt::format("{}:{}", locationStack, idx); - if (isInjectionSymbol(p, Definition->getInjSymbol())) { - newLocation = locationStack; +llvm::Value *create_term::alloc_arg( + kore_composite_pattern *pattern, int idx, + std::string const &location_stack) { + kore_pattern *p = pattern->get_arguments()[idx].get(); + std::string new_location = fmt::format("{}:{}", location_stack, idx); + if (is_injection_symbol(p, definition_->get_inj_symbol())) { + new_location = location_stack; } - llvm::Value *ret = createAllocation(p, newLocation).first; - auto *sort = dynamic_cast(p->getSort().get()); - ProofEvent e(Definition, Module); - CurrentBlock = e.hookArg(ret, sort, CurrentBlock); + llvm::Value *ret = create_allocation(p, new_location).first; + auto *sort = dynamic_cast(p->get_sort().get()); + proof_event e(definition_, module_); + current_block_ = e.hook_arg(ret, sort, current_block_); return ret; } @@ -316,300 +318,304 @@ std::string escape(std::string const &str) { } // NOLINTNEXTLINE(*-cognitive-complexity) -llvm::Value *CreateTerm::createHook( - KORECompositePattern *hookAtt, KORECompositePattern *pattern, - std::string const &locationStack) { - assert(hookAtt->getArguments().size() == 1); - auto *strPattern - = dynamic_cast(hookAtt->getArguments()[0].get()); - std::string name = strPattern->getContents(); +llvm::Value *create_term::create_hook( + kore_composite_pattern *hook_att, kore_composite_pattern *pattern, + std::string const &location_stack) { + assert(hook_att->get_arguments().size() == 1); + auto *str_pattern + = dynamic_cast(hook_att->get_arguments()[0].get()); + std::string name = str_pattern->get_contents(); if (name == "BOOL.and" || name == "BOOL.andThen") { - assert(pattern->getArguments().size() == 2); - llvm::Value *firstArg = alloc_arg(pattern, 0, locationStack); - llvm::BasicBlock *CondBlock = CurrentBlock; - llvm::BasicBlock *TrueBlock - = llvm::BasicBlock::Create(Ctx, "then", CurrentBlock->getParent()); - llvm::BasicBlock *MergeBlock = llvm::BasicBlock::Create( - Ctx, "hook_BOOL_and", CurrentBlock->getParent()); - llvm::BranchInst::Create(TrueBlock, MergeBlock, firstArg, CurrentBlock); - CurrentBlock = TrueBlock; - llvm::Value *secondArg = alloc_arg(pattern, 1, locationStack); - llvm::BranchInst::Create(MergeBlock, CurrentBlock); - llvm::PHINode *Phi = llvm::PHINode::Create( - llvm::Type::getInt1Ty(Ctx), 2, "phi", MergeBlock); - Phi->addIncoming(secondArg, CurrentBlock); - Phi->addIncoming(firstArg, CondBlock); - CurrentBlock = MergeBlock; - return Phi; + assert(pattern->get_arguments().size() == 2); + llvm::Value *first_arg = alloc_arg(pattern, 0, location_stack); + llvm::BasicBlock *cond_block = current_block_; + llvm::BasicBlock *true_block + = llvm::BasicBlock::Create(ctx_, "then", current_block_->getParent()); + llvm::BasicBlock *merge_block = llvm::BasicBlock::Create( + ctx_, "hook_BOOL_and", current_block_->getParent()); + llvm::BranchInst::Create( + true_block, merge_block, first_arg, current_block_); + current_block_ = true_block; + llvm::Value *second_arg = alloc_arg(pattern, 1, location_stack); + llvm::BranchInst::Create(merge_block, current_block_); + llvm::PHINode *phi = llvm::PHINode::Create( + llvm::Type::getInt1Ty(ctx_), 2, "phi", merge_block); + phi->addIncoming(second_arg, current_block_); + phi->addIncoming(first_arg, cond_block); + current_block_ = merge_block; + return phi; } if (name == "BOOL.or" || name == "BOOL.orElse") { - assert(pattern->getArguments().size() == 2); - llvm::Value *firstArg = alloc_arg(pattern, 0, locationStack); - llvm::BasicBlock *CondBlock = CurrentBlock; - llvm::BasicBlock *FalseBlock - = llvm::BasicBlock::Create(Ctx, "else", CurrentBlock->getParent()); - llvm::BasicBlock *MergeBlock = llvm::BasicBlock::Create( - Ctx, "hook_BOOL_or", CurrentBlock->getParent()); - llvm::BranchInst::Create(MergeBlock, FalseBlock, firstArg, CurrentBlock); - CurrentBlock = FalseBlock; - llvm::Value *secondArg = alloc_arg(pattern, 1, locationStack); - llvm::BranchInst::Create(MergeBlock, CurrentBlock); - llvm::PHINode *Phi = llvm::PHINode::Create( - llvm::Type::getInt1Ty(Ctx), 2, "phi", MergeBlock); - Phi->addIncoming(secondArg, CurrentBlock); - Phi->addIncoming(firstArg, CondBlock); - CurrentBlock = MergeBlock; - return Phi; + assert(pattern->get_arguments().size() == 2); + llvm::Value *first_arg = alloc_arg(pattern, 0, location_stack); + llvm::BasicBlock *cond_block = current_block_; + llvm::BasicBlock *false_block + = llvm::BasicBlock::Create(ctx_, "else", current_block_->getParent()); + llvm::BasicBlock *merge_block = llvm::BasicBlock::Create( + ctx_, "hook_BOOL_or", current_block_->getParent()); + llvm::BranchInst::Create( + merge_block, false_block, first_arg, current_block_); + current_block_ = false_block; + llvm::Value *second_arg = alloc_arg(pattern, 1, location_stack); + llvm::BranchInst::Create(merge_block, current_block_); + llvm::PHINode *phi = llvm::PHINode::Create( + llvm::Type::getInt1Ty(ctx_), 2, "phi", merge_block); + phi->addIncoming(second_arg, current_block_); + phi->addIncoming(first_arg, cond_block); + current_block_ = merge_block; + return phi; } if (name == "BOOL.not") { - assert(pattern->getArguments().size() == 1); - llvm::Value *arg = alloc_arg(pattern, 0, locationStack); - llvm::BinaryOperator *Not = llvm::BinaryOperator::Create( + assert(pattern->get_arguments().size() == 1); + llvm::Value *arg = alloc_arg(pattern, 0, location_stack); + llvm::BinaryOperator *neg = llvm::BinaryOperator::Create( llvm::Instruction::Xor, arg, - llvm::ConstantInt::get(llvm::Type::getInt1Ty(Ctx), 1), "hook_BOOL_not", - CurrentBlock); - return Not; + llvm::ConstantInt::get(llvm::Type::getInt1Ty(ctx_), 1), "hook_BOOL_not", + current_block_); + return neg; } if (name == "BOOL.implies") { - assert(pattern->getArguments().size() == 2); - llvm::Value *firstArg = alloc_arg(pattern, 0, locationStack); - llvm::BasicBlock *CondBlock = CurrentBlock; - llvm::BasicBlock *TrueBlock - = llvm::BasicBlock::Create(Ctx, "then", CurrentBlock->getParent()); - llvm::BasicBlock *MergeBlock = llvm::BasicBlock::Create( - Ctx, "hook_BOOL_implies", CurrentBlock->getParent()); - llvm::BranchInst::Create(TrueBlock, MergeBlock, firstArg, CurrentBlock); - CurrentBlock = TrueBlock; - llvm::Value *secondArg = alloc_arg(pattern, 1, locationStack); - llvm::BranchInst::Create(MergeBlock, CurrentBlock); - llvm::PHINode *Phi = llvm::PHINode::Create( - llvm::Type::getInt1Ty(Ctx), 2, "phi", MergeBlock); - Phi->addIncoming(secondArg, CurrentBlock); - Phi->addIncoming( - llvm::ConstantInt::get(llvm::Type::getInt1Ty(Ctx), 1), CondBlock); - CurrentBlock = MergeBlock; - return Phi; + assert(pattern->get_arguments().size() == 2); + llvm::Value *first_arg = alloc_arg(pattern, 0, location_stack); + llvm::BasicBlock *cond_block = current_block_; + llvm::BasicBlock *true_block + = llvm::BasicBlock::Create(ctx_, "then", current_block_->getParent()); + llvm::BasicBlock *merge_block = llvm::BasicBlock::Create( + ctx_, "hook_BOOL_implies", current_block_->getParent()); + llvm::BranchInst::Create( + true_block, merge_block, first_arg, current_block_); + current_block_ = true_block; + llvm::Value *second_arg = alloc_arg(pattern, 1, location_stack); + llvm::BranchInst::Create(merge_block, current_block_); + llvm::PHINode *phi = llvm::PHINode::Create( + llvm::Type::getInt1Ty(ctx_), 2, "phi", merge_block); + phi->addIncoming(second_arg, current_block_); + phi->addIncoming( + llvm::ConstantInt::get(llvm::Type::getInt1Ty(ctx_), 1), cond_block); + current_block_ = merge_block; + return phi; } if (name == "BOOL.ne" || name == "BOOL.xor") { - assert(pattern->getArguments().size() == 2); - llvm::Value *firstArg = alloc_arg(pattern, 0, locationStack); - llvm::Value *secondArg = alloc_arg(pattern, 1, locationStack); - llvm::BinaryOperator *Xor = llvm::BinaryOperator::Create( - llvm::Instruction::Xor, firstArg, secondArg, "hook_BOOL_ne", - CurrentBlock); - return Xor; + assert(pattern->get_arguments().size() == 2); + llvm::Value *first_arg = alloc_arg(pattern, 0, location_stack); + llvm::Value *second_arg = alloc_arg(pattern, 1, location_stack); + llvm::BinaryOperator *xor_op = llvm::BinaryOperator::Create( + llvm::Instruction::Xor, first_arg, second_arg, "hook_BOOL_ne", + current_block_); + return xor_op; } if (name == "BOOL.eq") { - assert(pattern->getArguments().size() == 2); - llvm::Value *firstArg = alloc_arg(pattern, 0, locationStack); - llvm::Value *secondArg = alloc_arg(pattern, 1, locationStack); - auto *Eq = new llvm::ICmpInst( - *CurrentBlock, llvm::CmpInst::ICMP_EQ, firstArg, secondArg, + assert(pattern->get_arguments().size() == 2); + llvm::Value *first_arg = alloc_arg(pattern, 0, location_stack); + llvm::Value *second_arg = alloc_arg(pattern, 1, location_stack); + auto *eq = new llvm::ICmpInst( + *current_block_, llvm::CmpInst::ICMP_EQ, first_arg, second_arg, "hook_BOOL_eq"); - return Eq; + return eq; } if (name == "KEQUAL.ite") { - assert(pattern->getArguments().size() == 3); - llvm::Value *cond = alloc_arg(pattern, 0, locationStack); - llvm::BasicBlock *TrueBlock - = llvm::BasicBlock::Create(Ctx, "then", CurrentBlock->getParent()); - llvm::BasicBlock *FalseBlock - = llvm::BasicBlock::Create(Ctx, "else", CurrentBlock->getParent()); - llvm::BasicBlock *MergeBlock = llvm::BasicBlock::Create( - Ctx, "hook_KEQUAL_ite", CurrentBlock->getParent()); - llvm::BranchInst::Create(TrueBlock, FalseBlock, cond, CurrentBlock); - CurrentBlock = TrueBlock; - llvm::Value *trueArg = alloc_arg(pattern, 1, locationStack); - llvm::BasicBlock *NewTrueBlock = CurrentBlock; - CurrentBlock = FalseBlock; - llvm::Value *falseArg = alloc_arg(pattern, 2, locationStack); - if (trueArg->getType()->isPointerTy() - && !falseArg->getType()->isPointerTy()) { - auto *AllocCollection - = new llvm::AllocaInst(falseArg->getType(), 0, "", CurrentBlock); - new llvm::StoreInst(falseArg, AllocCollection, CurrentBlock); - falseArg = AllocCollection; + assert(pattern->get_arguments().size() == 3); + llvm::Value *cond = alloc_arg(pattern, 0, location_stack); + llvm::BasicBlock *true_block + = llvm::BasicBlock::Create(ctx_, "then", current_block_->getParent()); + llvm::BasicBlock *false_block + = llvm::BasicBlock::Create(ctx_, "else", current_block_->getParent()); + llvm::BasicBlock *merge_block = llvm::BasicBlock::Create( + ctx_, "hook_KEQUAL_ite", current_block_->getParent()); + llvm::BranchInst::Create(true_block, false_block, cond, current_block_); + current_block_ = true_block; + llvm::Value *true_arg = alloc_arg(pattern, 1, location_stack); + llvm::BasicBlock *new_true_block = current_block_; + current_block_ = false_block; + llvm::Value *false_arg = alloc_arg(pattern, 2, location_stack); + if (true_arg->getType()->isPointerTy() + && !false_arg->getType()->isPointerTy()) { + auto *alloc_collection + = new llvm::AllocaInst(false_arg->getType(), 0, "", current_block_); + new llvm::StoreInst(false_arg, alloc_collection, current_block_); + false_arg = alloc_collection; } else if ( - !trueArg->getType()->isPointerTy() - && falseArg->getType()->isPointerTy()) { - auto *AllocCollection - = new llvm::AllocaInst(trueArg->getType(), 0, "", NewTrueBlock); - new llvm::StoreInst(trueArg, AllocCollection, NewTrueBlock); - trueArg = AllocCollection; + !true_arg->getType()->isPointerTy() + && false_arg->getType()->isPointerTy()) { + auto *alloc_collection + = new llvm::AllocaInst(true_arg->getType(), 0, "", new_true_block); + new llvm::StoreInst(true_arg, alloc_collection, new_true_block); + true_arg = alloc_collection; } - llvm::BranchInst::Create(MergeBlock, CurrentBlock); - llvm::BranchInst::Create(MergeBlock, NewTrueBlock); - llvm::PHINode *Phi - = llvm::PHINode::Create(trueArg->getType(), 2, "phi", MergeBlock); - Phi->addIncoming(trueArg, NewTrueBlock); - Phi->addIncoming(falseArg, CurrentBlock); - CurrentBlock = MergeBlock; - return Phi; + llvm::BranchInst::Create(merge_block, current_block_); + llvm::BranchInst::Create(merge_block, new_true_block); + llvm::PHINode *phi + = llvm::PHINode::Create(true_arg->getType(), 2, "phi", merge_block); + phi->addIncoming(true_arg, new_true_block); + phi->addIncoming(false_arg, current_block_); + current_block_ = merge_block; + return phi; } if (name == "MINT.uvalue") { - llvm::Value *mint = alloc_arg(pattern, 0, locationStack); - ValueType cat = dynamic_cast( - pattern->getConstructor()->getArguments()[0].get()) - ->getCategory(Definition); - auto *Type = getValueType(cat, Module); + llvm::Value *mint = alloc_arg(pattern, 0, location_stack); + value_type cat = dynamic_cast( + pattern->get_constructor()->get_arguments()[0].get()) + ->get_category(definition_); + auto *type = getvalue_type(cat, module_); size_t nwords = (cat.bits + 63) / 64; if (nwords == 0) { - auto *staticTerm = new CreateStaticTerm(Definition, Module); - return staticTerm->createToken({SortCategory::Int, 0}, "0"); + auto *static_term = new create_static_term(definition_, module_); + return static_term->create_token({sort_category::Int, 0}, "0"); } - auto *Ptr = allocateTerm( - llvm::Type::getInt64Ty(Ctx), - llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), nwords * 8), - CurrentBlock, "koreAllocAlwaysGC"); + auto *ptr = allocate_term( + llvm::Type::getInt64Ty(ctx_), + llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx_), nwords * 8), + current_block_, "kore_alloc_always_gc"); if (nwords == 1) { - llvm::Value *Word = nullptr; + llvm::Value *word = nullptr; if (cat.bits == 64) { - Word = mint; + word = mint; } else { - Word = new llvm::ZExtInst( - mint, llvm::Type::getInt64Ty(Ctx), "word", CurrentBlock); + word = new llvm::ZExtInst( + mint, llvm::Type::getInt64Ty(ctx_), "word", current_block_); } - new llvm::StoreInst(Word, Ptr, CurrentBlock); + new llvm::StoreInst(word, ptr, current_block_); } else { // nwords >= 2 - llvm::Value *Ptr2 = Ptr; + llvm::Value *ptr2 = ptr; llvm::Value *accum = mint; for (size_t i = 0; i < nwords; i++) { - auto *Word = new llvm::TruncInst( - accum, llvm::Type::getInt64Ty(Ctx), "word", CurrentBlock); - new llvm::StoreInst(Word, Ptr2, CurrentBlock); - Ptr2 = llvm::GetElementPtrInst::Create( - llvm::Type::getInt64Ty(Ctx), Ptr2, - {llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), 1)}, "ptr", - CurrentBlock); + auto *word = new llvm::TruncInst( + accum, llvm::Type::getInt64Ty(ctx_), "word", current_block_); + new llvm::StoreInst(word, ptr2, current_block_); + ptr2 = llvm::GetElementPtrInst::Create( + llvm::Type::getInt64Ty(ctx_), ptr2, + {llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx_), 1)}, "ptr", + current_block_); accum = llvm::BinaryOperator::Create( - llvm::Instruction::LShr, accum, llvm::ConstantInt::get(Type, 64), - "shift", CurrentBlock); + llvm::Instruction::LShr, accum, llvm::ConstantInt::get(type, 64), + "shift", current_block_); } } auto *result = llvm::CallInst::Create( - getOrInsertFunction( - Module, "hook_MINT_import", - getValueType({SortCategory::Int, 0}, Module), - llvm::Type::getInt64PtrTy(Ctx), llvm::Type::getInt64Ty(Ctx), - llvm::Type::getInt1Ty(Ctx)), - {Ptr, llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), cat.bits), - llvm::ConstantInt::getFalse(Ctx)}, - "hook_MINT_uvalue", CurrentBlock); - setDebugLoc(result); + get_or_insert_function( + module_, "hook_MINT_import", + getvalue_type({sort_category::Int, 0}, module_), + llvm::Type::getInt64PtrTy(ctx_), llvm::Type::getInt64Ty(ctx_), + llvm::Type::getInt1Ty(ctx_)), + {ptr, llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx_), cat.bits), + llvm::ConstantInt::getFalse(ctx_)}, + "hook_MINT_uvalue", current_block_); + set_debug_loc(result); return result; } if (name == "MINT.svalue") { - llvm::Value *mint = alloc_arg(pattern, 0, locationStack); - ValueType cat = dynamic_cast( - pattern->getConstructor()->getArguments()[0].get()) - ->getCategory(Definition); - auto *Type = getValueType(cat, Module); + llvm::Value *mint = alloc_arg(pattern, 0, location_stack); + value_type cat = dynamic_cast( + pattern->get_constructor()->get_arguments()[0].get()) + ->get_category(definition_); + auto *type = getvalue_type(cat, module_); size_t nwords = (cat.bits + 63) / 64; if (nwords == 0) { - auto *staticTerm = new CreateStaticTerm(Definition, Module); - return staticTerm->createToken({SortCategory::Int, 0}, "0"); + auto *static_term = new create_static_term(definition_, module_); + return static_term->create_token({sort_category::Int, 0}, "0"); } - auto *Ptr = allocateTerm( - llvm::Type::getInt64Ty(Ctx), - llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), nwords * 8), - CurrentBlock, "koreAllocAlwaysGC"); + auto *ptr = allocate_term( + llvm::Type::getInt64Ty(ctx_), + llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx_), nwords * 8), + current_block_, "kore_alloc_always_gc"); if (nwords == 1) { - llvm::Value *Word = nullptr; + llvm::Value *word = nullptr; if (cat.bits == 64) { - Word = mint; + word = mint; } else { - Word = new llvm::SExtInst( - mint, llvm::Type::getInt64Ty(Ctx), "word", CurrentBlock); + word = new llvm::SExtInst( + mint, llvm::Type::getInt64Ty(ctx_), "word", current_block_); } - new llvm::StoreInst(Word, Ptr, CurrentBlock); + new llvm::StoreInst(word, ptr, current_block_); } else { // nwords >= 2 - llvm::Value *Ptr2 = Ptr; + llvm::Value *ptr2 = ptr; llvm::Value *accum = mint; for (size_t i = 0; i < nwords; i++) { - auto *Word = new llvm::TruncInst( - accum, llvm::Type::getInt64Ty(Ctx), "word", CurrentBlock); - new llvm::StoreInst(Word, Ptr2, CurrentBlock); - Ptr2 = llvm::GetElementPtrInst::Create( - llvm::Type::getInt64Ty(Ctx), Ptr2, - {llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), 1)}, "ptr", - CurrentBlock); + auto *word = new llvm::TruncInst( + accum, llvm::Type::getInt64Ty(ctx_), "word", current_block_); + new llvm::StoreInst(word, ptr2, current_block_); + ptr2 = llvm::GetElementPtrInst::Create( + llvm::Type::getInt64Ty(ctx_), ptr2, + {llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx_), 1)}, "ptr", + current_block_); accum = llvm::BinaryOperator::Create( - llvm::Instruction::AShr, accum, llvm::ConstantInt::get(Type, 64), - "shift", CurrentBlock); + llvm::Instruction::AShr, accum, llvm::ConstantInt::get(type, 64), + "shift", current_block_); } } auto *result = llvm::CallInst::Create( - getOrInsertFunction( - Module, "hook_MINT_import", - getValueType({SortCategory::Int, 0}, Module), - llvm::Type::getInt64PtrTy(Ctx), llvm::Type::getInt64Ty(Ctx), - llvm::Type::getInt1Ty(Ctx)), - {Ptr, llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), cat.bits), - llvm::ConstantInt::getTrue(Ctx)}, - "hook_MINT_svalue", CurrentBlock); - setDebugLoc(result); + get_or_insert_function( + module_, "hook_MINT_import", + getvalue_type({sort_category::Int, 0}, module_), + llvm::Type::getInt64PtrTy(ctx_), llvm::Type::getInt64Ty(ctx_), + llvm::Type::getInt1Ty(ctx_)), + {ptr, llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx_), cat.bits), + llvm::ConstantInt::getTrue(ctx_)}, + "hook_MINT_svalue", current_block_); + set_debug_loc(result); return result; } if (name == "MINT.integer") { - llvm::Value *mpz = alloc_arg(pattern, 0, locationStack); - ValueType cat = dynamic_cast( - pattern->getConstructor()->getSort().get()) - ->getCategory(Definition); - auto *Type = getValueType(cat, Module); - llvm::Instruction *Ptr = llvm::CallInst::Create( - getOrInsertFunction( - Module, "hook_MINT_export", llvm::Type::getInt64PtrTy(Ctx), - getValueType({SortCategory::Int, 0}, Module), - llvm::Type::getInt64Ty(Ctx)), - {mpz, llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), cat.bits)}, - "ptr", CurrentBlock); - setDebugLoc(Ptr); + llvm::Value *mpz = alloc_arg(pattern, 0, location_stack); + value_type cat = dynamic_cast( + pattern->get_constructor()->get_sort().get()) + ->get_category(definition_); + auto *type = getvalue_type(cat, module_); + llvm::Instruction *ptr = llvm::CallInst::Create( + get_or_insert_function( + module_, "hook_MINT_export", llvm::Type::getInt64PtrTy(ctx_), + getvalue_type({sort_category::Int, 0}, module_), + llvm::Type::getInt64Ty(ctx_)), + {mpz, llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx_), cat.bits)}, + "ptr", current_block_); + set_debug_loc(ptr); size_t nwords = (cat.bits + 63) / 64; - llvm::Value *result = llvm::ConstantInt::get(Type, 0); + llvm::Value *result = llvm::ConstantInt::get(type, 0); if (nwords == 0) { return result; } if (nwords == 1) { - auto *Word = new llvm::LoadInst( - llvm::Type::getInt64Ty(Ctx), Ptr, "word", CurrentBlock); + auto *word = new llvm::LoadInst( + llvm::Type::getInt64Ty(ctx_), ptr, "word", current_block_); if (cat.bits == 64) { - return Word; + return word; } - return new llvm::TruncInst(Word, Type, "hook_MINT_integer", CurrentBlock); + return new llvm::TruncInst( + word, type, "hook_MINT_integer", current_block_); } // nwords >= 2 for (size_t i = 0; i < nwords; i++) { - auto *Word = new llvm::LoadInst( - llvm::Type::getInt64Ty(Ctx), Ptr, "word", CurrentBlock); - auto *Zext = new llvm::ZExtInst(Word, Type, "extended", CurrentBlock); - auto *Shl = llvm::BinaryOperator::Create( - llvm::Instruction::Shl, result, llvm::ConstantInt::get(Type, 64), - "shift", CurrentBlock); + auto *word = new llvm::LoadInst( + llvm::Type::getInt64Ty(ctx_), ptr, "word", current_block_); + auto *zext = new llvm::ZExtInst(word, type, "extended", current_block_); + auto *shl = llvm::BinaryOperator::Create( + llvm::Instruction::Shl, result, llvm::ConstantInt::get(type, 64), + "shift", current_block_); result = llvm::BinaryOperator::Create( - llvm::Instruction::Or, Shl, Zext, "or", CurrentBlock); - Ptr = llvm::GetElementPtrInst::Create( - llvm::Type::getInt64Ty(Ctx), Ptr, - {llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), 1)}, "ptr", - CurrentBlock); + llvm::Instruction::Or, shl, zext, "or", current_block_); + ptr = llvm::GetElementPtrInst::Create( + llvm::Type::getInt64Ty(ctx_), ptr, + {llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx_), 1)}, "ptr", + current_block_); } return result; } if (name == "MINT.neg") { - llvm::Value *in = alloc_arg(pattern, 0, locationStack); - return llvm::BinaryOperator::CreateNeg(in, "hook_MINT_neg", CurrentBlock); + llvm::Value *in = alloc_arg(pattern, 0, location_stack); + return llvm::BinaryOperator::CreateNeg(in, "hook_MINT_neg", current_block_); } if (name == "MINT.not") { - llvm::Value *in = alloc_arg(pattern, 0, locationStack); - return llvm::BinaryOperator::CreateNot(in, "hook_MINT_not", CurrentBlock); + llvm::Value *in = alloc_arg(pattern, 0, location_stack); + return llvm::BinaryOperator::CreateNot(in, "hook_MINT_not", current_block_); #define MINT_CMP(hookname, inst) \ } \ if (name == "MINT." #hookname) { \ - llvm::Value *first = alloc_arg(pattern, 0, locationStack); \ - llvm::Value *second = alloc_arg(pattern, 1, locationStack); \ + llvm::Value *first = alloc_arg(pattern, 0, location_stack); \ + llvm::Value *second = alloc_arg(pattern, 1, location_stack); \ return new llvm::ICmpInst( \ - *CurrentBlock, llvm::CmpInst::inst, first, second, \ + *current_block_, llvm::CmpInst::inst, first, second, \ "hook_MINT_" #hookname) MINT_CMP(eq, ICMP_EQ); MINT_CMP(ne, ICMP_NE); @@ -624,11 +630,11 @@ llvm::Value *CreateTerm::createHook( #define MINT_BINOP(hookname, inst) \ } \ if (name == "MINT." #hookname) { \ - llvm::Value *first = alloc_arg(pattern, 0, locationStack); \ - llvm::Value *second = alloc_arg(pattern, 1, locationStack); \ + llvm::Value *first = alloc_arg(pattern, 0, location_stack); \ + llvm::Value *second = alloc_arg(pattern, 1, location_stack); \ return llvm::BinaryOperator::Create( \ llvm::Instruction::inst, first, second, "hook_MINT_" #hookname, \ - CurrentBlock) + current_block_) MINT_BINOP(xor, Xor); MINT_BINOP(or, Or); MINT_BINOP(and, And); @@ -648,40 +654,41 @@ llvm::Value *CreateTerm::createHook( assert(false && "not implemented yet: MInt"); abort(); } - std::string hookName = "hook_" + name.substr(0, name.find('.')) + "_" - + name.substr(name.find('.') + 1); - return createFunctionCall(hookName, pattern, true, false, locationStack); + std::string hook_name = "hook_" + name.substr(0, name.find('.')) + "_" + + name.substr(name.find('.') + 1); + return create_function_call(hook_name, pattern, true, false, location_stack); } // We use tailcc calling convention for apply_rule_* and eval_* functions to // make these K functions tail recursive when their K definitions are tail // recursive. -llvm::Value *CreateTerm::createFunctionCall( - std::string const &name, KORECompositePattern *pattern, bool sret, - bool tailcc, std::string const &locationStack) { - auto event = ProofEvent(Definition, Module); +llvm::Value *create_term::create_function_call( + std::string const &name, kore_composite_pattern *pattern, bool sret, + bool tailcc, std::string const &location_stack) { + auto event = proof_event(definition_, module_); - CurrentBlock = event.functionEvent_pre(CurrentBlock, pattern, locationStack); + current_block_ + = event.function_event_pre(current_block_, pattern, location_stack); std::vector args; - auto *returnSort = dynamic_cast( - pattern->getConstructor()->getSort().get()); - auto returnCat = returnSort->getCategory(Definition); + auto *return_sort = dynamic_cast( + pattern->get_constructor()->get_sort().get()); + auto return_cat = return_sort->get_category(definition_); int i = 0; - for (auto const &sort : pattern->getConstructor()->getArguments()) { - auto *concreteSort = dynamic_cast(sort.get()); - llvm::Value *arg = alloc_arg(pattern, i, locationStack); + for (auto const &sort : pattern->get_constructor()->get_arguments()) { + auto *concrete_sort = dynamic_cast(sort.get()); + llvm::Value *arg = alloc_arg(pattern, i, location_stack); i++; - switch (concreteSort->getCategory(Definition).cat) { - case SortCategory::Map: - case SortCategory::RangeMap: - case SortCategory::List: - case SortCategory::Set: { + switch (concrete_sort->get_category(definition_).cat) { + case sort_category::Map: + case sort_category::RangeMap: + case sort_category::List: + case sort_category::Set: { if (!arg->getType()->isPointerTy()) { - auto *AllocCollection - = new llvm::AllocaInst(arg->getType(), 0, "", CurrentBlock); - new llvm::StoreInst(arg, AllocCollection, CurrentBlock); - args.push_back(AllocCollection); + auto *alloc_collection + = new llvm::AllocaInst(arg->getType(), 0, "", current_block_); + new llvm::StoreInst(arg, alloc_collection, current_block_); + args.push_back(alloc_collection); } else { args.push_back(arg); } @@ -691,121 +698,123 @@ llvm::Value *CreateTerm::createFunctionCall( } } - CurrentBlock = event.functionEvent_post(CurrentBlock); + current_block_ = event.function_event_post(current_block_); - return createFunctionCall(name, returnCat, args, sret, tailcc, locationStack); + return create_function_call( + name, return_cat, args, sret, tailcc, location_stack); } -llvm::Value *CreateTerm::createFunctionCall( - std::string const &name, ValueType returnCat, +llvm::Value *create_term::create_function_call( + std::string const &name, value_type return_cat, std::vector const &args, bool sret, bool tailcc, - std::string const &locationStack) { - llvm::Type *returnType = getValueType(returnCat, Module); + std::string const &location_stack) { + llvm::Type *return_type = getvalue_type(return_cat, module_); std::vector types; bool collection = false; - switch (returnCat.cat) { - case SortCategory::Map: - case SortCategory::RangeMap: - case SortCategory::List: - case SortCategory::Set: collection = true; break; + switch (return_cat.cat) { + case sort_category::Map: + case sort_category::RangeMap: + case sort_category::List: + case sort_category::Set: collection = true; break; default: sret = false; break; } - llvm::Value *AllocSret = nullptr; + llvm::Value *alloc_sret = nullptr; types.reserve(args.size()); for (auto *arg : args) { types.push_back(arg->getType()); } - std::vector realArgs = args; - llvm::Type *sretType = nullptr; + std::vector real_args = args; + llvm::Type *sret_type = nullptr; if (sret) { // we don't use alloca here because the tail call optimization pass for llvm // doesn't handle correctly functions with alloca - AllocSret = allocateTerm(returnType, CurrentBlock, "koreAllocAlwaysGC"); - sretType = returnType; - realArgs.insert(realArgs.begin(), AllocSret); - types.insert(types.begin(), AllocSret->getType()); - returnType = llvm::Type::getVoidTy(Ctx); + alloc_sret + = allocate_term(return_type, current_block_, "kore_alloc_always_gc"); + sret_type = return_type; + real_args.insert(real_args.begin(), alloc_sret); + types.insert(types.begin(), alloc_sret->getType()); + return_type = llvm::Type::getVoidTy(ctx_); } else if (collection) { - returnType = llvm::PointerType::getUnqual(returnType); + return_type = llvm::PointerType::getUnqual(return_type); } - llvm::FunctionType *funcType - = llvm::FunctionType::get(returnType, types, false); - llvm::Function *func = getOrInsertFunction(Module, name, funcType); + llvm::FunctionType *func_type + = llvm::FunctionType::get(return_type, types, false); + llvm::Function *func = get_or_insert_function(module_, name, func_type); - auto *call = llvm::CallInst::Create(func, realArgs, "", CurrentBlock); - setDebugLoc(call); + auto *call = llvm::CallInst::Create(func, real_args, "", current_block_); + set_debug_loc(call); if (tailcc) { call->setCallingConv(llvm::CallingConv::Tail); } if (sret) { - llvm::Attribute sretAttr - = llvm::Attribute::get(Ctx, llvm::Attribute::StructRet, sretType); - func->arg_begin()->addAttr(sretAttr); - call->addParamAttr(0, sretAttr); - return AllocSret; + llvm::Attribute sret_attr + = llvm::Attribute::get(ctx_, llvm::Attribute::StructRet, sret_type); + func->arg_begin()->addAttr(sret_attr); + call->addParamAttr(0, sret_attr); + return alloc_sret; } return call; } /* create a term, given the assumption that the created term will not be a * triangle injection pair */ -llvm::Value *CreateTerm::notInjectionCase( - KORECompositePattern *constructor, llvm::Value *val, - std::string const &locationStack) { - KORESymbol const *symbol = constructor->getConstructor(); - KORESymbolDeclaration *symbolDecl - = Definition->getSymbolDeclarations().at(symbol->getName()); - llvm::StructType *BlockType = getBlockType(Module, Definition, symbol); - llvm::Value *BlockHeader - = getBlockHeader(Module, Definition, symbol, BlockType); +llvm::Value *create_term::not_injection_case( + kore_composite_pattern *constructor, llvm::Value *val, + std::string const &location_stack) { + kore_symbol const *symbol = constructor->get_constructor(); + kore_symbol_declaration *symbol_decl + = definition_->get_symbol_declarations().at(symbol->get_name()); + llvm::StructType *block_type = get_block_type(module_, definition_, symbol); + llvm::Value *block_header + = get_block_header(module_, definition_, symbol, block_type); int idx = 2; std::vector children; - for (auto const &child : constructor->getArguments()) { - llvm::Value *ChildValue = nullptr; + for (auto const &child : constructor->get_arguments()) { + llvm::Value *child_value = nullptr; if (idx == 2 && val != nullptr) { - ChildValue = val; + child_value = val; } else { - std::string newLocation = fmt::format("{}:{}", locationStack, idx - 2); - if (isInjectionSymbol(child.get(), Definition->getInjSymbol())) { - newLocation = locationStack; + std::string new_location = fmt::format("{}:{}", location_stack, idx - 2); + if (is_injection_symbol(child.get(), definition_->get_inj_symbol())) { + new_location = location_stack; } - ChildValue = createAllocation(child.get(), newLocation).first; + child_value = create_allocation(child.get(), new_location).first; } - auto *sort = dynamic_cast(child->getSort().get()); - if (sort && isCollectionSort(sort->getCategory(Definition))) { - ChildValue = new llvm::LoadInst( - BlockType->elements()[idx], ChildValue, "", CurrentBlock); + auto *sort = dynamic_cast(child->get_sort().get()); + if (sort && is_collection_sort(sort->get_category(definition_))) { + child_value = new llvm::LoadInst( + block_type->elements()[idx], child_value, "", current_block_); } - children.push_back(ChildValue); + children.push_back(child_value); idx++; } - llvm::Value *Block = allocateTerm(BlockType, CurrentBlock); - llvm::Value *BlockHeaderPtr = llvm::GetElementPtrInst::CreateInBounds( - BlockType, Block, - {llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), 0), - llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 0)}, - symbol->getName(), CurrentBlock); - new llvm::StoreInst(BlockHeader, BlockHeaderPtr, CurrentBlock); + llvm::Value *block = allocate_term(block_type, current_block_); + llvm::Value *block_header_ptr = llvm::GetElementPtrInst::CreateInBounds( + block_type, block, + {llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx_), 0), + llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx_), 0)}, + symbol->get_name(), current_block_); + new llvm::StoreInst(block_header, block_header_ptr, current_block_); idx = 2; - for (auto &ChildValue : children) { - llvm::Value *ChildPtr = llvm::GetElementPtrInst::CreateInBounds( - BlockType, Block, - {llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), 0), - llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), idx++)}, - "", CurrentBlock); - new llvm::StoreInst(ChildValue, ChildPtr, CurrentBlock); + for (auto &child_value : children) { + llvm::Value *child_ptr = llvm::GetElementPtrInst::CreateInBounds( + block_type, block, + {llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx_), 0), + llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx_), idx++)}, + "", current_block_); + new llvm::StoreInst(child_value, child_ptr, current_block_); } - auto *BlockPtr = llvm::PointerType::getUnqual( - llvm::StructType::getTypeByName(Module->getContext(), BLOCK_STRUCT)); - auto *bitcast = new llvm::BitCastInst(Block, BlockPtr, "", CurrentBlock); - if (symbolDecl->attributes().contains(attribute_set::key::binder)) { + auto *block_ptr = llvm::PointerType::getUnqual( + llvm::StructType::getTypeByName(module_->getContext(), block_struct)); + auto *bitcast = new llvm::BitCastInst(block, block_ptr, "", current_block_); + if (symbol_decl->attributes().contains(attribute_set::key::Binder)) { auto *call = llvm::CallInst::Create( - getOrInsertFunction(Module, "debruijnize", BlockPtr, BlockPtr), bitcast, - "withIndices", CurrentBlock); - setDebugLoc(call); + get_or_insert_function(module_, "debruijnize", block_ptr, block_ptr), + bitcast, "withIndices", current_block_); + set_debug_loc(call); return call; } return bitcast; @@ -813,367 +822,371 @@ llvm::Value *CreateTerm::notInjectionCase( // returns a value and a boolean indicating whether that value could be an // injection -std::pair CreateTerm::operator()(KOREPattern *pattern) { - populateStaticSet(pattern); +std::pair create_term::operator()(kore_pattern *pattern) { + populate_static_set(pattern); - return createAllocation(pattern); + return create_allocation(pattern); } -bool CreateTerm::populateStaticSet(KOREPattern *pattern) { +bool create_term::populate_static_set(kore_pattern *pattern) { bool can_be_static = true; - if (auto *variable = dynamic_cast(pattern)) { + if (auto *variable = dynamic_cast(pattern)) { can_be_static = false; } else if ( - auto *constructor = dynamic_cast(pattern)) { - KORESymbol const *symbol = constructor->getConstructor(); - if (symbol->getName() != "\\dv") { - KORESymbolDeclaration *symbolDecl - = Definition->getSymbolDeclarations().at(symbol->getName()); - if (symbolDecl->attributes().contains(attribute_set::key::function) - || (symbolDecl->attributes().contains(attribute_set::key::anywhere) - && !isAnywhereOwise)) { + auto *constructor = dynamic_cast(pattern)) { + kore_symbol const *symbol = constructor->get_constructor(); + if (symbol->get_name() != "\\dv") { + kore_symbol_declaration *symbol_decl + = definition_->get_symbol_declarations().at(symbol->get_name()); + if (symbol_decl->attributes().contains(attribute_set::key::Function) + || (symbol_decl->attributes().contains(attribute_set::key::Anywhere) + && !is_anywhere_owise_)) { can_be_static = false; } - for (auto const &sptr_nextPattern : constructor->getArguments()) { - KOREPattern *nextPattern = sptr_nextPattern.get(); - can_be_static &= populateStaticSet(nextPattern); + for (auto const &sptr_next_pattern : constructor->get_arguments()) { + kore_pattern *next_pattern = sptr_next_pattern.get(); + can_be_static &= populate_static_set(next_pattern); } } } if (can_be_static) { - staticTerms.insert(pattern); + static_terms_.insert(pattern); } return can_be_static; } -std::pair CreateTerm::createAllocation( - KOREPattern *pattern, std::string const &locationStack) { - if (staticTerms.contains(pattern)) { - auto *staticTerm = new CreateStaticTerm(Definition, Module); - return (*staticTerm)(pattern); +std::pair create_term::create_allocation( + kore_pattern *pattern, std::string const &location_stack) { + if (static_terms_.contains(pattern)) { + auto *static_term = new create_static_term(definition_, module_); + return (*static_term)(pattern); } - if (auto *variable = dynamic_cast(pattern)) { - auto *val = Substitution.lookup(variable->getName()); + if (auto *variable = dynamic_cast(pattern)) { + auto *val = substitution_.lookup(variable->get_name()); if (!val) { - std::cerr << variable->getName() << std::endl; + std::cerr << variable->get_name() << std::endl; abort(); } return std::make_pair(val, true); } - if (auto *constructor = dynamic_cast(pattern)) { - KORESymbol const *symbol = constructor->getConstructor(); - assert(symbol->isConcrete() && "not supported yet: sort variables"); - KORESymbolDeclaration *symbolDecl - = Definition->getSymbolDeclarations().at(symbol->getName()); - if (symbolDecl->attributes().contains(attribute_set::key::function) - || (symbolDecl->attributes().contains(attribute_set::key::anywhere) - && !isAnywhereOwise)) { - if (symbolDecl->attributes().contains(attribute_set::key::hook)) { - auto *sort - = dynamic_cast(constructor->getSort().get()); - auto *strPattern = dynamic_cast( - symbolDecl->attributes() - .get(attribute_set::key::hook) - ->getArguments()[0] + if (auto *constructor = dynamic_cast(pattern)) { + kore_symbol const *symbol = constructor->get_constructor(); + assert(symbol->is_concrete() && "not supported yet: sort variables"); + kore_symbol_declaration *symbol_decl + = definition_->get_symbol_declarations().at(symbol->get_name()); + if (symbol_decl->attributes().contains(attribute_set::key::Function) + || (symbol_decl->attributes().contains(attribute_set::key::Anywhere) + && !is_anywhere_owise_)) { + if (symbol_decl->attributes().contains(attribute_set::key::Hook)) { + auto *sort = dynamic_cast( + constructor->get_sort().get()); + auto *str_pattern = dynamic_cast( + symbol_decl->attributes() + .get(attribute_set::key::Hook) + ->get_arguments()[0] .get()); - std::string name = strPattern->getContents(); + std::string name = str_pattern->get_contents(); - ProofEvent p(Definition, Module); - CurrentBlock = p.hookEvent_pre(name, CurrentBlock, locationStack); - llvm::Value *val = createHook( - symbolDecl->attributes().get(attribute_set::key::hook).get(), - constructor, locationStack); - CurrentBlock = p.hookEvent_post(val, sort, CurrentBlock); + proof_event p(definition_, module_); + current_block_ = p.hook_event_pre(name, current_block_, location_stack); + llvm::Value *val = create_hook( + symbol_decl->attributes().get(attribute_set::key::Hook).get(), + constructor, location_stack); + current_block_ = p.hook_event_post(val, sort, current_block_); return std::make_pair(val, true); } auto fn_name = fmt::format("eval_{}", ast_to_string(*symbol, 0, false)); return std::make_pair( - createFunctionCall(fn_name, constructor, false, true, locationStack), + create_function_call( + fn_name, constructor, false, true, location_stack), true); } if (auto cat - = dynamic_cast(symbol->getArguments()[0].get()) - ->getCategory(Definition) + = dynamic_cast(symbol->get_arguments()[0].get()) + ->get_category(definition_) .cat; - symbolDecl->attributes().contains(attribute_set::key::sort_injection) - && (cat == SortCategory::Symbol)) { - std::pair val = createAllocation( - constructor->getArguments()[0].get(), locationStack); + symbol_decl->attributes().contains(attribute_set::key::SortInjection) + && (cat == sort_category::Symbol)) { + std::pair val = create_allocation( + constructor->get_arguments()[0].get(), location_stack); if (val.second) { - llvm::Instruction *Tag = llvm::CallInst::Create( - getOrInsertFunction( - Module, "getTag", llvm::Type::getInt32Ty(Ctx), - getValueType({SortCategory::Symbol, 0}, Module)), - val.first, "tag", CurrentBlock); - setDebugLoc(Tag); - auto *inj = Definition->getInjSymbol(); - auto *NotStringBlock = llvm::BasicBlock::Create( - Ctx, "notString", CurrentBlock->getParent()); - auto *GeBlock = llvm::BasicBlock::Create( - Ctx, "geFirst", CurrentBlock->getParent()); - auto *FalseBlock = llvm::BasicBlock::Create( - Ctx, "notInjection", CurrentBlock->getParent()); - auto *TrueBlock - = llvm::BasicBlock::Create(Ctx, "merge", CurrentBlock->getParent()); + llvm::Instruction *tag = llvm::CallInst::Create( + get_or_insert_function( + module_, "get_tag", llvm::Type::getInt32Ty(ctx_), + getvalue_type({sort_category::Symbol, 0}, module_)), + val.first, "tag", current_block_); + set_debug_loc(tag); + auto *inj = definition_->get_inj_symbol(); + auto *not_string_block = llvm::BasicBlock::Create( + ctx_, "notString", current_block_->getParent()); + auto *ge_block = llvm::BasicBlock::Create( + ctx_, "geFirst", current_block_->getParent()); + auto *false_block = llvm::BasicBlock::Create( + ctx_, "notInjection", current_block_->getParent()); + auto *true_block = llvm::BasicBlock::Create( + ctx_, "merge", current_block_->getParent()); auto *cmp = new llvm::ICmpInst( - *CurrentBlock, llvm::CmpInst::ICMP_NE, Tag, - llvm::ConstantInt::getSigned(llvm::Type::getInt32Ty(Ctx), -1)); - llvm::BranchInst::Create(NotStringBlock, FalseBlock, cmp, CurrentBlock); + *current_block_, llvm::CmpInst::ICMP_NE, tag, + llvm::ConstantInt::getSigned(llvm::Type::getInt32Ty(ctx_), -1)); + llvm::BranchInst::Create( + not_string_block, false_block, cmp, current_block_); - CurrentBlock = NotStringBlock; + current_block_ = not_string_block; cmp = new llvm::ICmpInst( - *CurrentBlock, llvm::CmpInst::ICMP_UGE, Tag, + *current_block_, llvm::CmpInst::ICMP_UGE, tag, llvm::ConstantInt::get( - llvm::Type::getInt32Ty(Ctx), inj->getFirstTag())); - llvm::BranchInst::Create(GeBlock, FalseBlock, cmp, CurrentBlock); + llvm::Type::getInt32Ty(ctx_), inj->get_first_tag())); + llvm::BranchInst::Create(ge_block, false_block, cmp, current_block_); - CurrentBlock = GeBlock; + current_block_ = ge_block; cmp = new llvm::ICmpInst( - *CurrentBlock, llvm::CmpInst::ICMP_ULE, Tag, + *current_block_, llvm::CmpInst::ICMP_ULE, tag, llvm::ConstantInt::get( - llvm::Type::getInt32Ty(Ctx), inj->getLastTag())); - llvm::BranchInst::Create(TrueBlock, FalseBlock, cmp, CurrentBlock); - - CurrentBlock = FalseBlock; - auto *Cast = notInjectionCase(constructor, val.first, locationStack); - llvm::BranchInst::Create(TrueBlock, CurrentBlock); - - CurrentBlock = TrueBlock; - llvm::PHINode *Phi - = llvm::PHINode::Create(Cast->getType(), 2, "phi", CurrentBlock); - Phi->addIncoming(Cast, FalseBlock); - Phi->addIncoming(val.first, GeBlock); - return std::make_pair(Phi, true); + llvm::Type::getInt32Ty(ctx_), inj->get_last_tag())); + llvm::BranchInst::Create(true_block, false_block, cmp, current_block_); + + current_block_ = false_block; + auto *cast = not_injection_case(constructor, val.first, location_stack); + llvm::BranchInst::Create(true_block, current_block_); + + current_block_ = true_block; + llvm::PHINode *phi + = llvm::PHINode::Create(cast->getType(), 2, "phi", current_block_); + phi->addIncoming(cast, false_block); + phi->addIncoming(val.first, ge_block); + return std::make_pair(phi, true); } return std::make_pair( - notInjectionCase(constructor, val.first, locationStack), true); + not_injection_case(constructor, val.first, location_stack), true); } return std::make_pair( - notInjectionCase(constructor, nullptr, locationStack), false); + not_injection_case(constructor, nullptr, location_stack), false); } assert(false && "not supported yet: meta level"); abort(); } -void addAbort(llvm::BasicBlock *block, llvm::Module *Module) { - llvm::FunctionType *AbortType = llvm::FunctionType::get( - llvm::Type::getVoidTy(Module->getContext()), false); - llvm::Function *AbortFunc = getOrInsertFunction(Module, "abort", AbortType); - AbortFunc->addFnAttr(llvm::Attribute::NoReturn); - llvm::CallInst::Create(AbortFunc, "", block); - new llvm::UnreachableInst(Module->getContext(), block); +void add_abort(llvm::BasicBlock *block, llvm::Module *module) { + llvm::FunctionType *abort_type = llvm::FunctionType::get( + llvm::Type::getVoidTy(module->getContext()), false); + llvm::Function *abort_func + = get_or_insert_function(module, "abort", abort_type); + abort_func->addFnAttr(llvm::Attribute::NoReturn); + llvm::CallInst::Create(abort_func, "", block); + new llvm::UnreachableInst(module->getContext(), block); } -bool makeFunction( - std::string const &name, KOREPattern *pattern, KOREDefinition *definition, - llvm::Module *Module, bool tailcc, bool bigStep, bool apply, - KOREAxiomDeclaration *axiom, std::string const &postfix) { - std::map vars; +bool make_function( + std::string const &name, kore_pattern *pattern, kore_definition *definition, + llvm::Module *module, bool tailcc, bool big_step, bool apply, + kore_axiom_declaration *axiom, std::string const &postfix) { + std::map vars; if (apply) { - for (KOREPattern *lhs : axiom->getLeftHandSide()) { - lhs->markVariables(vars); + for (kore_pattern *lhs : axiom->get_left_hand_side()) { + lhs->mark_variables(vars); } } - pattern->markVariables(vars); - llvm::StringMap params; - std::vector paramTypes; - std::vector paramNames; - std::vector debugArgs; + pattern->mark_variables(vars); + llvm::StringMap params; + std::vector param_types; + std::vector param_names; + std::vector debug_args; for (auto &entry : vars) { auto *sort - = dynamic_cast(entry.second->getSort().get()); + = dynamic_cast(entry.second->get_sort().get()); if (!sort) { // TODO: sort variables return false; } - auto cat = sort->getCategory(definition); - llvm::Type *paramType = getValueType(cat, Module); - debugArgs.push_back(getDebugType(cat, ast_to_string(*sort))); + auto cat = sort->get_category(definition); + llvm::Type *param_type = getvalue_type(cat, module); + debug_args.push_back(get_debug_type(cat, ast_to_string(*sort))); switch (cat.cat) { - case SortCategory::Map: - case SortCategory::RangeMap: - case SortCategory::List: - case SortCategory::Set: - paramType = llvm::PointerType::getUnqual(paramType); + case sort_category::Map: + case sort_category::RangeMap: + case sort_category::List: + case sort_category::Set: + param_type = llvm::PointerType::getUnqual(param_type); break; default: break; } params.insert({entry.first, cat}); - paramTypes.push_back(paramType); - paramNames.push_back(entry.first); + param_types.push_back(param_type); + param_names.push_back(entry.first); } - ValueType returnCat = termType(pattern, params, definition); - auto *returnType = getValueType(returnCat, Module); - switch (returnCat.cat) { - case SortCategory::Map: - case SortCategory::RangeMap: - case SortCategory::List: - case SortCategory::Set: - returnType = llvm::PointerType::getUnqual(returnType); + value_type return_cat = term_type(pattern, params, definition); + auto *return_type = getvalue_type(return_cat, module); + switch (return_cat.cat) { + case sort_category::Map: + case sort_category::RangeMap: + case sort_category::List: + case sort_category::Set: + return_type = llvm::PointerType::getUnqual(return_type); break; default: break; } - llvm::FunctionType *funcType - = llvm::FunctionType::get(returnType, paramTypes, false); - llvm::Function *applyRule = getOrInsertFunction(Module, name, funcType); - initDebugAxiom(axiom->attributes()); - std::string debugName = name; - if (axiom->attributes().contains(attribute_set::key::label)) { - debugName - = axiom->attributes().get_string(attribute_set::key::label) + postfix; + llvm::FunctionType *func_type + = llvm::FunctionType::get(return_type, param_types, false); + llvm::Function *apply_rule = get_or_insert_function(module, name, func_type); + init_debug_axiom(axiom->attributes()); + std::string debug_name = name; + if (axiom->attributes().contains(attribute_set::key::Label)) { + debug_name + = axiom->attributes().get_string(attribute_set::key::Label) + postfix; } - initDebugFunction( - debugName, debugName, - getDebugFunctionType( - getDebugType(returnCat, ast_to_string(*termSort(pattern))), - debugArgs), - definition, applyRule); + init_debug_function( + debug_name, debug_name, + get_debug_function_type( + get_debug_type(return_cat, ast_to_string(*term_sort(pattern))), + debug_args), + definition, apply_rule); if (tailcc) { - applyRule->setCallingConv(llvm::CallingConv::Tail); + apply_rule->setCallingConv(llvm::CallingConv::Tail); } llvm::StringMap subst; llvm::BasicBlock *block - = llvm::BasicBlock::Create(Module->getContext(), "entry", applyRule); + = llvm::BasicBlock::Create(module->getContext(), "entry", apply_rule); int i = 0; - for (auto *val = applyRule->arg_begin(); val != applyRule->arg_end(); + for (auto *val = apply_rule->arg_begin(); val != apply_rule->arg_end(); ++val, ++i) { - subst.insert({paramNames[i], val}); - if (debugArgs[i]) { - initDebugParam( - applyRule, i, paramNames[i], params[paramNames[i]], - llvm::cast(debugArgs[i])->getName().str()); + subst.insert({param_names[i], val}); + if (debug_args[i]) { + init_debug_param( + apply_rule, i, param_names[i], params[param_names[i]], + llvm::cast(debug_args[i])->getName().str()); } } - CreateTerm creator = CreateTerm(subst, definition, block, Module, false); + create_term creator = create_term(subst, definition, block, module, false); llvm::Value *retval = creator(pattern).first; - auto *CurrentBlock = creator.getCurrentBlock(); - if (apply && bigStep) { - CurrentBlock = ProofEvent(definition, Module) - .rewriteEvent_post(axiom, retval, CurrentBlock); + auto *current_block = creator.get_current_block(); + if (apply && big_step) { + current_block = proof_event(definition, module) + .rewrite_event_post(axiom, retval, current_block); } - if (bigStep) { - llvm::Type *blockType = getValueType({SortCategory::Symbol, 0}, Module); - llvm::Function *step = getOrInsertFunction( - Module, "k_step", - llvm::FunctionType::get(blockType, {blockType}, false)); - auto *call = llvm::CallInst::Create(step, {retval}, "", CurrentBlock); - setDebugLoc(call); + if (big_step) { + llvm::Type *block_type = getvalue_type({sort_category::Symbol, 0}, module); + llvm::Function *step = get_or_insert_function( + module, "k_step", + llvm::FunctionType::get(block_type, {block_type}, false)); + auto *call = llvm::CallInst::Create(step, {retval}, "", current_block); + set_debug_loc(call); call->setCallingConv(llvm::CallingConv::Tail); retval = call; } auto *ret - = llvm::ReturnInst::Create(Module->getContext(), retval, CurrentBlock); - setDebugLoc(ret); + = llvm::ReturnInst::Create(module->getContext(), retval, current_block); + set_debug_loc(ret); return true; } -void makeApplyRuleFunction( - KOREAxiomDeclaration *axiom, KOREDefinition *definition, - llvm::Module *Module, bool bigStep) { - KOREPattern *pattern = axiom->getRightHandSide(); - std::string name = "apply_rule_" + std::to_string(axiom->getOrdinal()); - makeFunction( - name, pattern, definition, Module, true, bigStep, true, axiom, ".rhs"); - if (bigStep) { - makeFunction( - name + "_search", pattern, definition, Module, true, false, true, axiom, +void make_apply_rule_function( + kore_axiom_declaration *axiom, kore_definition *definition, + llvm::Module *module, bool big_step) { + kore_pattern *pattern = axiom->get_right_hand_side(); + std::string name = "apply_rule_" + std::to_string(axiom->get_ordinal()); + make_function( + name, pattern, definition, module, true, big_step, true, axiom, ".rhs"); + if (big_step) { + make_function( + name + "_search", pattern, definition, module, true, false, true, axiom, ".rhs"); } } -std::string makeApplyRuleFunction( - KOREAxiomDeclaration *axiom, KOREDefinition *definition, - llvm::Module *Module, std::vector const &residuals) { - std::map vars; +std::string make_apply_rule_function( + kore_axiom_declaration *axiom, kore_definition *definition, + llvm::Module *module, std::vector const &residuals) { + std::map vars; for (auto residual : residuals) { - residual.pattern->markVariables(vars); + residual.pattern->mark_variables(vars); } - for (KOREPattern *lhs : axiom->getLeftHandSide()) { - lhs->markVariables(vars); + for (kore_pattern *lhs : axiom->get_left_hand_side()) { + lhs->mark_variables(vars); } - llvm::StringMap params; - std::vector paramTypes; - std::vector paramNames; - std::vector debugArgs; + llvm::StringMap params; + std::vector param_types; + std::vector param_names; + std::vector debug_args; for (auto &entry : vars) { auto *sort - = dynamic_cast(entry.second->getSort().get()); + = dynamic_cast(entry.second->get_sort().get()); if (!sort) { // TODO: sort variables return ""; } - auto cat = sort->getCategory(definition); - llvm::Type *paramType = getValueType(cat, Module); - debugArgs.push_back(getDebugType(cat, ast_to_string(*sort))); + auto cat = sort->get_category(definition); + llvm::Type *param_type = getvalue_type(cat, module); + debug_args.push_back(get_debug_type(cat, ast_to_string(*sort))); switch (cat.cat) { - case SortCategory::Map: - case SortCategory::RangeMap: - case SortCategory::List: - case SortCategory::Set: - paramType = llvm::PointerType::getUnqual(paramType); + case sort_category::Map: + case sort_category::RangeMap: + case sort_category::List: + case sort_category::Set: + param_type = llvm::PointerType::getUnqual(param_type); break; default: break; } params.insert({entry.first, cat}); - paramTypes.push_back(paramType); - paramNames.push_back(entry.first); + param_types.push_back(param_type); + param_names.push_back(entry.first); } - llvm::FunctionType *funcType = llvm::FunctionType::get( - getValueType({SortCategory::Symbol, 0}, Module), paramTypes, false); - std::string name = "apply_rule_" + std::to_string(axiom->getOrdinal()); + llvm::FunctionType *func_type = llvm::FunctionType::get( + getvalue_type({sort_category::Symbol, 0}, module), param_types, false); + std::string name = "apply_rule_" + std::to_string(axiom->get_ordinal()); - makeFunction( - name + "_search", axiom->getRightHandSide(), definition, Module, true, + make_function( + name + "_search", axiom->get_right_hand_side(), definition, module, true, false, true, axiom, ".rhs"); - llvm::Function *applyRule = getOrInsertFunction(Module, name, funcType); - initDebugAxiom(axiom->attributes()); - initDebugFunction( + llvm::Function *apply_rule = get_or_insert_function(module, name, func_type); + init_debug_axiom(axiom->attributes()); + init_debug_function( name, name, - getDebugFunctionType( - getDebugType({SortCategory::Symbol, 0}, "SortGeneratedTopCell{}"), - debugArgs), - definition, applyRule); - applyRule->setCallingConv(llvm::CallingConv::Tail); + get_debug_function_type( + get_debug_type({sort_category::Symbol, 0}, "SortGeneratedTopCell{}"), + debug_args), + definition, apply_rule); + apply_rule->setCallingConv(llvm::CallingConv::Tail); llvm::StringMap subst; llvm::BasicBlock *block - = llvm::BasicBlock::Create(Module->getContext(), "entry", applyRule); + = llvm::BasicBlock::Create(module->getContext(), "entry", apply_rule); int i = 0; - for (auto *val = applyRule->arg_begin(); val != applyRule->arg_end(); + for (auto *val = apply_rule->arg_begin(); val != apply_rule->arg_end(); ++val, ++i) { - subst.insert({paramNames[i], val}); - if (debugArgs[i]) { - initDebugParam( - applyRule, i, paramNames[i], params[paramNames[i]], - llvm::cast(debugArgs[i])->getName().str()); + subst.insert({param_names[i], val}); + if (debug_args[i]) { + init_debug_param( + apply_rule, i, param_names[i], params[param_names[i]], + llvm::cast(debug_args[i])->getName().str()); } } - CreateTerm creator = CreateTerm(subst, definition, block, Module, false); + create_term creator = create_term(subst, definition, block, module, false); std::vector args; std::vector types; for (auto const &residual : residuals) { llvm::Value *arg = creator(residual.pattern).first; - auto *sort - = dynamic_cast(residual.pattern->getSort().get()); - auto cat = sort->getCategory(definition); + auto *sort = dynamic_cast( + residual.pattern->get_sort().get()); + auto cat = sort->get_category(definition); switch (cat.cat) { - case SortCategory::Map: - case SortCategory::RangeMap: - case SortCategory::List: - case SortCategory::Set: + case sort_category::Map: + case sort_category::RangeMap: + case sort_category::List: + case sort_category::Set: if (!arg->getType()->isPointerTy()) { - auto *ptr = allocateTerm( - arg->getType(), creator.getCurrentBlock(), "koreAllocAlwaysGC"); - new llvm::StoreInst(arg, ptr, creator.getCurrentBlock()); + auto *ptr = allocate_term( + arg->getType(), creator.get_current_block(), + "kore_alloc_always_gc"); + new llvm::StoreInst(arg, ptr, creator.get_current_block()); arg = ptr; } break; @@ -1182,78 +1195,78 @@ std::string makeApplyRuleFunction( args.push_back(arg); types.push_back(arg->getType()); } - llvm::Type *blockType = getValueType({SortCategory::Symbol, 0}, Module); - llvm::Function *step = getOrInsertFunction( - Module, "step_" + std::to_string(axiom->getOrdinal()), - llvm::FunctionType::get(blockType, types, false)); + llvm::Type *block_type = getvalue_type({sort_category::Symbol, 0}, module); + llvm::Function *step = get_or_insert_function( + module, "step_" + std::to_string(axiom->get_ordinal()), + llvm::FunctionType::get(block_type, types, false)); auto *retval - = llvm::CallInst::Create(step, args, "", creator.getCurrentBlock()); - setDebugLoc(retval); + = llvm::CallInst::Create(step, args, "", creator.get_current_block()); + set_debug_loc(retval); retval->setCallingConv(llvm::CallingConv::Tail); llvm::ReturnInst::Create( - Module->getContext(), retval, creator.getCurrentBlock()); + module->getContext(), retval, creator.get_current_block()); return name; } -std::string makeSideConditionFunction( - KOREAxiomDeclaration *axiom, KOREDefinition *definition, - llvm::Module *Module) { - KOREPattern *pattern = axiom->getRequires(); +std::string make_side_condition_function( + kore_axiom_declaration *axiom, kore_definition *definition, + llvm::Module *module) { + kore_pattern *pattern = axiom->get_requires(); if (!pattern) { return ""; } - std::string name = "side_condition_" + std::to_string(axiom->getOrdinal()); - if (makeFunction( - name, pattern, definition, Module, false, false, false, axiom, + std::string name = "side_condition_" + std::to_string(axiom->get_ordinal()); + if (make_function( + name, pattern, definition, module, false, false, false, axiom, ".sc")) { return name; } return ""; } -llvm::Type *getArgType(ValueType cat, llvm::Module *mod) { +llvm::Type *get_arg_type(value_type cat, llvm::Module *mod) { switch (cat.cat) { - case SortCategory::Bool: - case SortCategory::MInt: - case SortCategory::Map: - case SortCategory::RangeMap: - case SortCategory::List: - case SortCategory::Set: { - return getValueType(cat, mod); + case sort_category::Bool: + case sort_category::MInt: + case sort_category::Map: + case sort_category::RangeMap: + case sort_category::List: + case sort_category::Set: { + return getvalue_type(cat, mod); } - case SortCategory::Int: - return llvm::StructType::getTypeByName(mod->getContext(), INT_STRUCT); - case SortCategory::Float: - return llvm::StructType::getTypeByName(mod->getContext(), FLOAT_STRUCT); - case SortCategory::StringBuffer: - return llvm::StructType::getTypeByName(mod->getContext(), BUFFER_STRUCT); - case SortCategory::Symbol: - case SortCategory::Variable: { - return getBlockType(mod); + case sort_category::Int: + return llvm::StructType::getTypeByName(mod->getContext(), int_struct); + case sort_category::Float: + return llvm::StructType::getTypeByName(mod->getContext(), float_struct); + case sort_category::StringBuffer: + return llvm::StructType::getTypeByName(mod->getContext(), buffer_struct); + case sort_category::Symbol: + case sort_category::Variable: { + return get_block_type(mod); } - case SortCategory::Uncomputed: + case sort_category::Uncomputed: default: { abort(); } } } -bool isCollectionSort(ValueType cat) { +bool is_collection_sort(value_type cat) { switch (cat.cat) { - case SortCategory::Map: - case SortCategory::RangeMap: - case SortCategory::List: - case SortCategory::Set: return true; + case sort_category::Map: + case sort_category::RangeMap: + case sort_category::List: + case sort_category::Set: return true; default: return false; } } -bool isInjectionSymbol(KOREPattern *p, KORESymbol *sym) { - if (auto *constructor = dynamic_cast(p)) { - KORESymbol const *symbol = constructor->getConstructor(); - if (symbol->getName() == sym->getName()) { +bool is_injection_symbol(kore_pattern *p, kore_symbol *sym) { + if (auto *constructor = dynamic_cast(p)) { + kore_symbol const *symbol = constructor->get_constructor(); + if (symbol->get_name() == sym->get_name()) { return true; } } diff --git a/lib/codegen/Debug.cpp b/lib/codegen/Debug.cpp index d7c4b0ac4..a18b681fc 100644 --- a/lib/codegen/Debug.cpp +++ b/lib/codegen/Debug.cpp @@ -20,18 +20,18 @@ namespace kllvm { -static llvm::DIBuilder *Dbg; -static llvm::DICompileUnit *DbgCU; -static llvm::DIFile *DbgFile; -static llvm::DISubprogram *DbgSP; -static unsigned DbgLine; -static unsigned DbgColumn; +static llvm::DIBuilder *dbg; +static llvm::DICompileUnit *dbg_cu; +static llvm::DIFile *dbg_file; +static llvm::DISubprogram *dbg_sp; +static unsigned dbg_line; +static unsigned dbg_column; #define DWARF_VERSION 4 -void initDebugInfo(llvm::Module *module, std::string const &filename) { - Dbg = new llvm::DIBuilder(*module); - DbgFile = Dbg->createFile(filename, "."); +void init_debug_info(llvm::Module *module, std::string const &filename) { + dbg = new llvm::DIBuilder(*module); + dbg_file = dbg->createFile(filename, "."); module->addModuleFlag( llvm::Module::Warning, "Debug Info Version", @@ -47,118 +47,121 @@ void initDebugInfo(llvm::Module *module, std::string const &filename) { // arguments to createCompileUnit: // https://github.com/runtimeverification/k/issues/2637 // https://llvm.org/doxygen/classllvm_1_1DIBuilder.html - DbgCU = Dbg->createCompileUnit( - llvm::dwarf::DW_LANG_C, DbgFile, "llvm-kompile-codegen", false, "", 0, "", - llvm::DICompileUnit::DebugEmissionKind::FullDebug, 0, false, false, + dbg_cu = dbg->createCompileUnit( + llvm::dwarf::DW_LANG_C, dbg_file, "llvm-kompile-codegen", false, "", 0, + "", llvm::DICompileUnit::DebugEmissionKind::FullDebug, 0, false, false, llvm::DICompileUnit::DebugNameTableKind::None); } -void finalizeDebugInfo() { - Dbg->finalize(); +void finalize_debug_info() { + dbg->finalize(); } -void initDebugFunction( - std::string const &name, std::string const &linkageName, - llvm::DISubroutineType *type, KOREDefinition *definition, +void init_debug_function( + std::string const &name, std::string const &linkage_name, + llvm::DISubroutineType *type, kore_definition *definition, llvm::Function *func) { - if (!Dbg) { + if (!dbg) { return; } - auto *Unit = Dbg->createFile(DbgFile->getFilename(), DbgFile->getDirectory()); - llvm::DIScope *FContext = Unit; - DbgSP = Dbg->createFunction( - FContext, name, name, Unit, DbgLine, type, DbgLine, + auto *unit + = dbg->createFile(dbg_file->getFilename(), dbg_file->getDirectory()); + llvm::DIScope *f_context = unit; + dbg_sp = dbg->createFunction( + f_context, name, name, unit, dbg_line, type, dbg_line, llvm::DINode::DIFlags::FlagZero, llvm::DISubprogram::SPFlagDefinition); - func->setSubprogram(DbgSP); + func->setSubprogram(dbg_sp); } -void initDebugParam( - llvm::Function *func, unsigned argNo, std::string const &name, - ValueType type, std::string const &typeName) { - if (!Dbg) { +void init_debug_param( + llvm::Function *func, unsigned arg_no, std::string const &name, + value_type type, std::string const &type_name) { + if (!dbg) { return; } - llvm::DILocalVariable *DbgVar = Dbg->createParameterVariable( - DbgSP, name, argNo + 1, DbgFile, DbgLine, getDebugType(type, typeName), - true); - Dbg->insertDbgValueIntrinsic( - func->arg_begin() + argNo, DbgVar, Dbg->createExpression(), - llvm::DILocation::get(func->getContext(), DbgLine, DbgColumn, DbgSP), + llvm::DILocalVariable *dbg_var = dbg->createParameterVariable( + dbg_sp, name, arg_no + 1, dbg_file, dbg_line, + get_debug_type(type, type_name), true); + dbg->insertDbgValueIntrinsic( + func->arg_begin() + arg_no, dbg_var, dbg->createExpression(), + llvm::DILocation::get(func->getContext(), dbg_line, dbg_column, dbg_sp), &func->getEntryBlock()); } -void initDebugGlobal( +void init_debug_global( std::string const &name, llvm::DIType *type, llvm::GlobalVariable *var) { - if (!Dbg) { + if (!dbg) { return; } - resetDebugLoc(); - auto *DbgExp = Dbg->createGlobalVariableExpression( - DbgCU, name, name, DbgFile, DbgLine, type, false); - var->addDebugInfo(DbgExp); + reset_debug_loc(); + auto *dbg_exp = dbg->createGlobalVariableExpression( + dbg_cu, name, name, dbg_file, dbg_line, type, false); + var->addDebugInfo(dbg_exp); } -void initDebugAxiom(attribute_set const &att) { - if (!Dbg) { +void init_debug_axiom(attribute_set const &att) { + if (!dbg) { return; } - if (!att.contains(attribute_set::key::source)) { - resetDebugLoc(); + if (!att.contains(attribute_set::key::Source)) { + reset_debug_loc(); return; } - KORECompositePattern *sourceAtt = att.get(attribute_set::key::source).get(); - assert(sourceAtt->getArguments().size() == 1); - auto *strPattern - = dynamic_cast(sourceAtt->getArguments()[0].get()); - std::string source = strPattern->getContents(); - if (!att.contains(attribute_set::key::location)) { - resetDebugLoc(); + kore_composite_pattern *source_att + = att.get(attribute_set::key::Source).get(); + assert(source_att->get_arguments().size() == 1); + auto *str_pattern = dynamic_cast( + source_att->get_arguments()[0].get()); + std::string source = str_pattern->get_contents(); + if (!att.contains(attribute_set::key::Location)) { + reset_debug_loc(); return; } - KORECompositePattern *locationAtt - = att.get(attribute_set::key::location).get(); - assert(locationAtt->getArguments().size() == 1); - auto *strPattern2 - = dynamic_cast(locationAtt->getArguments()[0].get()); - std::string location = strPattern2->getContents(); + kore_composite_pattern *location_att + = att.get(attribute_set::key::Location).get(); + assert(location_att->get_arguments().size() == 1); + auto *str_pattern2 = dynamic_cast( + location_att->get_arguments()[0].get()); + std::string location = str_pattern2->get_contents(); source = source.substr(7, source.length() - 8); size_t first_comma = location.find_first_of(','); - DbgLine = std::stoi(location.substr(9, first_comma - 9)); - DbgColumn = std::stoi(location.substr( + dbg_line = std::stoi(location.substr(9, first_comma - 9)); + dbg_column = std::stoi(location.substr( first_comma + 1, location.find_first_of(',', first_comma + 1) - first_comma - 1)); - DbgFile = Dbg->createFile(source, DbgFile->getDirectory()); + dbg_file = dbg->createFile(source, dbg_file->getDirectory()); } -void resetDebugLoc() { - if (!Dbg) { +void reset_debug_loc() { + if (!dbg) { return; } - DbgLine = 0; - DbgColumn = 0; - DbgFile = DbgCU->getFile(); + dbg_line = 0; + dbg_column = 0; + dbg_file = dbg_cu->getFile(); } -llvm::DIType *getForwardDecl(std::string const &name) { - if (!Dbg) { +llvm::DIType *get_forward_decl(std::string const &name) { + if (!dbg) { return nullptr; } - auto *Unit = Dbg->createFile(DbgFile->getFilename(), DbgFile->getDirectory()); - return Dbg->createForwardDecl( - llvm::dwarf::DW_TAG_structure_type, name, DbgCU, Unit, 0); + auto *unit + = dbg->createFile(dbg_file->getFilename(), dbg_file->getDirectory()); + return dbg->createForwardDecl( + llvm::dwarf::DW_TAG_structure_type, name, dbg_cu, unit, 0); } -static std::string MAP_STRUCT = "map"; -static std::string RANGEMAP_STRUCT = "rangemap"; -static std::string LIST_STRUCT = "list"; -static std::string SET_STRUCT = "set"; -static std::string INT_STRUCT = "__mpz_struct"; -static std::string FLOAT_STRUCT = "floating"; -static std::string BUFFER_STRUCT = "stringbuffer"; -static std::string BLOCK_STRUCT = "block"; +static std::string map_struct = "map"; +static std::string rangemap_struct = "rangemap"; +static std::string list_struct = "list"; +static std::string set_struct = "set"; +static std::string int_struct = "__mpz_struct"; +static std::string float_struct = "floating"; +static std::string buffer_struct = "stringbuffer"; +static std::string block_struct = "block"; -llvm::DIType *getDebugType(ValueType type, std::string const &typeName) { - if (!Dbg) { +llvm::DIType *get_debug_type(value_type type, std::string const &type_name) { + if (!dbg) { return nullptr; } static std::map types; @@ -172,137 +175,139 @@ llvm::DIType *getDebugType(ValueType type, std::string const &typeName) { llvm::DIType *boolean = nullptr; llvm::DIType *mint = nullptr; llvm::DIType *symbol = nullptr; - if (types[typeName]) { - return types[typeName]; + if (types[type_name]) { + return types[type_name]; } switch (type.cat) { - case SortCategory::Map: - map = getPointerDebugType(getForwardDecl(MAP_STRUCT), typeName); - types[typeName] = map; + case sort_category::Map: + map = get_pointer_debug_type(get_forward_decl(map_struct), type_name); + types[type_name] = map; return map; - case SortCategory::RangeMap: - rangemap = getPointerDebugType(getForwardDecl(RANGEMAP_STRUCT), typeName); - types[typeName] = rangemap; + case sort_category::RangeMap: + rangemap + = get_pointer_debug_type(get_forward_decl(rangemap_struct), type_name); + types[type_name] = rangemap; return rangemap; - case SortCategory::List: - list = getPointerDebugType(getForwardDecl(LIST_STRUCT), typeName); - types[typeName] = list; + case sort_category::List: + list = get_pointer_debug_type(get_forward_decl(list_struct), type_name); + types[type_name] = list; return list; - case SortCategory::Set: - set = getPointerDebugType(getForwardDecl(SET_STRUCT), typeName); - types[typeName] = set; + case sort_category::Set: + set = get_pointer_debug_type(get_forward_decl(set_struct), type_name); + types[type_name] = set; return set; - case SortCategory::Int: - integer = getPointerDebugType(getForwardDecl(INT_STRUCT), typeName); - types[typeName] = integer; + case sort_category::Int: + integer = get_pointer_debug_type(get_forward_decl(int_struct), type_name); + types[type_name] = integer; return integer; - case SortCategory::Float: - floating = getPointerDebugType(getForwardDecl(FLOAT_STRUCT), typeName); - types[typeName] = floating; + case sort_category::Float: + floating + = get_pointer_debug_type(get_forward_decl(float_struct), type_name); + types[type_name] = floating; return floating; - case SortCategory::StringBuffer: - buffer = getPointerDebugType(getForwardDecl(BUFFER_STRUCT), typeName); - types[typeName] = buffer; + case sort_category::StringBuffer: + buffer = get_pointer_debug_type(get_forward_decl(buffer_struct), type_name); + types[type_name] = buffer; return buffer; - case SortCategory::Bool: - boolean = Dbg->createBasicType(typeName, 8, llvm::dwarf::DW_ATE_boolean); - types[typeName] = boolean; + case sort_category::Bool: + boolean = dbg->createBasicType(type_name, 8, llvm::dwarf::DW_ATE_boolean); + types[type_name] = boolean; return boolean; - case SortCategory::MInt: - mint = Dbg->createBasicType( - typeName, type.bits, llvm::dwarf::DW_ATE_unsigned); - types[typeName] = mint; + case sort_category::MInt: + mint = dbg->createBasicType( + type_name, type.bits, llvm::dwarf::DW_ATE_unsigned); + types[type_name] = mint; return mint; - case SortCategory::Symbol: - case SortCategory::Variable: - symbol = getPointerDebugType(getForwardDecl(BLOCK_STRUCT), typeName); - types[typeName] = symbol; + case sort_category::Symbol: + case sort_category::Variable: + symbol = get_pointer_debug_type(get_forward_decl(block_struct), type_name); + types[type_name] = symbol; return symbol; - case SortCategory::Uncomputed: abort(); + case sort_category::Uncomputed: abort(); } } -llvm::DIType *getIntDebugType() { - if (!Dbg) { +llvm::DIType *get_int_debug_type() { + if (!dbg) { return nullptr; } - return Dbg->createBasicType("uint32_t", 32, llvm::dwarf::DW_ATE_unsigned); + return dbg->createBasicType("uint32_t", 32, llvm::dwarf::DW_ATE_unsigned); } -llvm::DIType *getLongDebugType() { - if (!Dbg) { +llvm::DIType *get_long_debug_type() { + if (!dbg) { return nullptr; } - return Dbg->createBasicType("uint64_t", 64, llvm::dwarf::DW_ATE_unsigned); + return dbg->createBasicType("uint64_t", 64, llvm::dwarf::DW_ATE_unsigned); } -llvm::DIType *getBoolDebugType() { - if (!Dbg) { +llvm::DIType *get_bool_debug_type() { + if (!dbg) { return nullptr; } - return Dbg->createBasicType("bool", 8, llvm::dwarf::DW_ATE_boolean); + return dbg->createBasicType("bool", 8, llvm::dwarf::DW_ATE_boolean); } -llvm::DIType *getVoidDebugType() { +llvm::DIType *get_void_debug_type() { return nullptr; } -llvm::DIType *getCharPtrDebugType() { - if (!Dbg) { +llvm::DIType *get_char_ptr_debug_type() { + if (!dbg) { return nullptr; } - return Dbg->createPointerType( - Dbg->createBasicType("char", 8, llvm::dwarf::DW_ATE_signed_char), + return dbg->createPointerType( + dbg->createBasicType("char", 8, llvm::dwarf::DW_ATE_signed_char), sizeof(size_t) * 8); } -llvm::DIType *getCharDebugType() { - if (!Dbg) { +llvm::DIType *get_char_debug_type() { + if (!dbg) { return nullptr; } - return Dbg->createBasicType("char", 8, llvm::dwarf::DW_ATE_signed_char); + return dbg->createBasicType("char", 8, llvm::dwarf::DW_ATE_signed_char); } llvm::DIType * -getPointerDebugType(llvm::DIType *ty, std::string const &typeName) { - if (!Dbg) { +get_pointer_debug_type(llvm::DIType *ty, std::string const &type_name) { + if (!dbg) { return nullptr; } - auto *ptrType = Dbg->createPointerType(ty, sizeof(size_t) * 8); - return Dbg->createTypedef(ptrType, typeName, DbgFile, 0, DbgCU); + auto *ptr_type = dbg->createPointerType(ty, sizeof(size_t) * 8); + return dbg->createTypedef(ptr_type, type_name, dbg_file, 0, dbg_cu); } llvm::DIType * -getArrayDebugType(llvm::DIType *ty, size_t len, llvm::Align align) { - if (!Dbg) { +get_array_debug_type(llvm::DIType *ty, size_t len, llvm::Align align) { + if (!dbg) { return nullptr; } std::vector subscripts; - auto arr = Dbg->getOrCreateArray(subscripts); - return Dbg->createArrayType(len, align.value(), ty, arr); + auto arr = dbg->getOrCreateArray(subscripts); + return dbg->createArrayType(len, align.value(), ty, arr); } -llvm::DIType *getShortDebugType() { - if (!Dbg) { +llvm::DIType *get_short_debug_type() { + if (!dbg) { return nullptr; } - return Dbg->createBasicType("uint16_t", 16, llvm::dwarf::DW_ATE_unsigned); + return dbg->createBasicType("uint16_t", 16, llvm::dwarf::DW_ATE_unsigned); } -llvm::DISubroutineType *getDebugFunctionType( - llvm::Metadata *returnType, std::vector argTypes) { - if (!Dbg) { +llvm::DISubroutineType *get_debug_function_type( + llvm::Metadata *return_type, std::vector arg_types) { + if (!dbg) { return nullptr; } - argTypes.insert(argTypes.begin(), returnType); - return Dbg->createSubroutineType(Dbg->getOrCreateTypeArray(argTypes)); + arg_types.insert(arg_types.begin(), return_type); + return dbg->createSubroutineType(dbg->getOrCreateTypeArray(arg_types)); } -void setDebugLoc(llvm::Instruction *instr) { - if (!Dbg) { +void set_debug_loc(llvm::Instruction *instr) { + if (!dbg) { return; } - instr->setDebugLoc(llvm::DebugLoc( - llvm::DILocation::get(instr->getContext(), DbgLine, DbgColumn, DbgSP))); + instr->setDebugLoc(llvm::DebugLoc(llvm::DILocation::get( + instr->getContext(), dbg_line, dbg_column, dbg_sp))); } } // namespace kllvm diff --git a/lib/codegen/Decision.cpp b/lib/codegen/Decision.cpp index 9e5184d85..4c2f55029 100644 --- a/lib/codegen/Decision.cpp +++ b/lib/codegen/Decision.cpp @@ -39,102 +39,102 @@ namespace kllvm { -static std::string LAYOUTITEM_STRUCT = "layoutitem"; +static std::string layoutitem_struct = "layoutitem"; -FailNode FailNode::instance; +fail_node fail_node::instance; static unsigned max_name_length = 1024 - std::to_string(std::numeric_limits::max()).length(); -void Decision::operator()(DecisionNode *entry) { - if (entry == FailNode::get()) { - if (FailPattern) { +void decision::operator()(decision_node *entry) { + if (entry == fail_node::get()) { + if (fail_pattern_) { llvm::Value *val = load(std::make_pair( - "_1", getValueType({SortCategory::Symbol, 0}, Module))); - FailSubject->addIncoming( + "_1", getvalue_type({sort_category::Symbol, 0}, module_))); + fail_subject_->addIncoming( new llvm::BitCastInst( - val, llvm::Type::getInt8PtrTy(Ctx), "", CurrentBlock), - CurrentBlock); - FailPattern->addIncoming( - stringLiteral("\\bottom{SortGeneratedTopCell{}}()"), CurrentBlock); - FailSort->addIncoming( - stringLiteral("SortGeneratedTopCell{}"), CurrentBlock); + val, llvm::Type::getInt8PtrTy(ctx_), "", current_block_), + current_block_); + fail_pattern_->addIncoming( + string_literal("\\bottom{SortGeneratedTopCell{}}()"), current_block_); + fail_sort_->addIncoming( + string_literal("SortGeneratedTopCell{}"), current_block_); } - llvm::BranchInst::Create(this->FailureBlock, this->CurrentBlock); + llvm::BranchInst::Create(this->failure_block_, this->current_block_); } else { entry->codegen(this); } } -llvm::Value *Decision::ptrTerm(llvm::Value *val) { +llvm::Value *decision::ptr_term(llvm::Value *val) { if (val->getType()->isIntegerTy()) { - val = allocateTerm(val->getType(), CurrentBlock, "koreAllocAlwaysGC"); + val = allocate_term(val->getType(), current_block_, "kore_alloc_always_gc"); } return new llvm::BitCastInst( - val, llvm::Type::getInt8PtrTy(Ctx), "", CurrentBlock); + val, llvm::Type::getInt8PtrTy(ctx_), "", current_block_); } -bool DecisionNode::beginNode(Decision *d, std::string const &name) { - if (isCompleted()) { - llvm::BranchInst::Create(cachedCode, d->CurrentBlock); +bool decision_node::begin_node(decision *d, std::string const &name) { + if (is_completed()) { + llvm::BranchInst::Create(cached_code_, d->current_block_); return true; } - auto *Block = llvm::BasicBlock::Create( - d->Ctx, name.substr(0, max_name_length), d->CurrentBlock->getParent()); - cachedCode = Block; - llvm::BranchInst::Create(Block, d->CurrentBlock); - d->CurrentBlock = Block; + auto *block = llvm::BasicBlock::Create( + d->ctx_, name.substr(0, max_name_length), d->current_block_->getParent()); + cached_code_ = block; + llvm::BranchInst::Create(block, d->current_block_); + d->current_block_ = block; return false; } static std::pair -getFailPattern(DecisionCase const &_case, bool isInt) { - if (isInt) { - size_t bitwidth = _case.getLiteral().getBitWidth(); +get_fail_pattern(decision_case const &c, bool is_int) { + if (is_int) { + size_t bitwidth = c.get_literal().getBitWidth(); if (bitwidth == 1) { return std::make_pair( "SortBool{}", "\\dv{SortBool{}}(\"" - + (_case.getLiteral() == 0 ? std::string("false") - : std::string("true")) + + (c.get_literal() == 0 ? std::string("false") + : std::string("true")) + "\")"); } std::string sort = "SortMInt{Sort" + std::to_string(bitwidth) + "{}}"; llvm::SmallString<25> vec; - _case.getLiteral().toString(vec, 10, false); + c.get_literal().toString(vec, 10, false); return std::make_pair( sort, "\\dv{" + sort + "}(\"" + std::string(vec.c_str()) + "p" + std::to_string(bitwidth) + "\")"); } - auto result = fmt::format("{}(", ast_to_string(*_case.getConstructor())); + auto result = fmt::format("{}(", ast_to_string(*c.get_constructor())); std::string conn; - for (auto const &i : _case.getConstructor()->getArguments()) { + for (auto const &i : c.get_constructor()->get_arguments()) { result += fmt::format("{}Var'Unds':{}", conn, ast_to_string(*i)); conn = ","; } result += ")"; - auto return_sort = ast_to_string(*_case.getConstructor()->getSort()); + auto return_sort = ast_to_string(*c.get_constructor()->get_sort()); return std::make_pair(return_sort, result); } -static std::pair getFailPattern( - std::vector> const - &caseData, - bool isInt, llvm::BasicBlock *FailBlock) { +static std::pair get_fail_pattern( + std::vector> const + &case_data, + bool is_int, llvm::BasicBlock *fail_block) { std::string reason; std::string sort; - for (auto const &entry : caseData) { - auto const &_case = *entry.second; - if (entry.first != FailBlock) { - auto caseReason = getFailPattern(_case, isInt); + for (auto const &entry : case_data) { + auto const &c = *entry.second; + if (entry.first != fail_block) { + auto case_reason = get_fail_pattern(c, is_int); if (reason.empty()) { - reason = caseReason.second; - sort = caseReason.first; + reason = case_reason.second; + sort = case_reason.first; } else { - reason - = fmt::format("\\or{{{}}}({},{})", sort, reason, caseReason.second); + reason = fmt::format( + "\\or{{{}}}({},{})", sort, reason, case_reason.second); } } } @@ -142,181 +142,182 @@ static std::pair getFailPattern( } // NOLINTNEXTLINE(*-cognitive-complexity) -void SwitchNode::codegen(Decision *d) { - if (beginNode(d, "switch" + name)) { +void switch_node::codegen(decision *d) { + if (begin_node(d, "switch" + name_)) { return; } - llvm::Value *val = d->load(std::make_pair(name, type)); - llvm::Value *ptrVal = nullptr; - if (d->FailPattern) { - ptrVal = d->ptrTerm(val); + llvm::Value *val = d->load(std::make_pair(name_, type_)); + llvm::Value *ptr_val = nullptr; + if (d->fail_pattern_) { + ptr_val = d->ptr_term(val); } - llvm::BasicBlock *_default = d->FailureBlock; - DecisionCase const *defaultCase = nullptr; - std::vector> caseData; + llvm::BasicBlock *default_block = d->failure_block_; + decision_case const *default_case = nullptr; + std::vector> case_data; int idx = 0; - bool isInt = false; - for (auto &_case : cases) { - auto *child = _case.getChild(); - llvm::BasicBlock *CaseBlock = nullptr; - if (child == FailNode::get()) { - CaseBlock = d->FailureBlock; + bool is_int = false; + for (auto &c : cases_) { + auto *child = c.get_child(); + llvm::BasicBlock *case_block = nullptr; + if (child == fail_node::get()) { + case_block = d->failure_block_; } else { - CaseBlock = llvm::BasicBlock::Create( - d->Ctx, - name.substr(0, max_name_length) + "_case_" + std::to_string(idx++), - d->CurrentBlock->getParent()); + case_block = llvm::BasicBlock::Create( + d->ctx_, + name_.substr(0, max_name_length) + "_case_" + std::to_string(idx++), + d->current_block_->getParent()); } - if (auto *sym = _case.getConstructor()) { - isInt = isInt || sym->getName() == "\\dv"; - caseData.emplace_back(CaseBlock, &_case); + if (auto *sym = c.get_constructor()) { + is_int = is_int || sym->get_name() == "\\dv"; + case_data.emplace_back(case_block, &c); } else { - _default = CaseBlock; - defaultCase = &_case; + default_block = case_block; + default_case = &c; } } - if (isCheckNull) { + if (is_check_null_) { auto *cast = new llvm::PtrToIntInst( - val, llvm::Type::getInt64Ty(d->Ctx), "", d->CurrentBlock); + val, llvm::Type::getInt64Ty(d->ctx_), "", d->current_block_); auto *cmp = new llvm::ICmpInst( - *d->CurrentBlock, llvm::CmpInst::ICMP_NE, cast, + *d->current_block_, llvm::CmpInst::ICMP_NE, cast, llvm::ConstantExpr::getPtrToInt( llvm::ConstantPointerNull::get( llvm::dyn_cast(val->getType())), - llvm::Type::getInt64Ty(d->Ctx))); + llvm::Type::getInt64Ty(d->ctx_))); val = cmp; - isInt = true; + is_int = true; } - llvm::Value *failSort = nullptr; - llvm::Value *failPattern = nullptr; - if (d->FailPattern) { - auto failReason = getFailPattern(caseData, isInt, d->FailureBlock); - failSort = d->stringLiteral(failReason.first); - failPattern = d->stringLiteral(failReason.second); + llvm::Value *fail_sort = nullptr; + llvm::Value *fail_pattern = nullptr; + if (d->fail_pattern_) { + auto fail_reason = get_fail_pattern(case_data, is_int, d->failure_block_); + fail_sort = d->string_literal(fail_reason.first); + fail_pattern = d->string_literal(fail_reason.second); } - if (isInt) { - auto *_switch = llvm::SwitchInst::Create( - val, _default, cases.size(), d->CurrentBlock); - for (auto &_case : caseData) { - _switch->addCase( - llvm::ConstantInt::get(d->Ctx, _case.second->getLiteral()), - _case.first); + if (is_int) { + auto *switch_inst = llvm::SwitchInst::Create( + val, default_block, cases_.size(), d->current_block_); + for (auto &c : case_data) { + switch_inst->addCase( + llvm::ConstantInt::get(d->ctx_, c.second->get_literal()), c.first); } } else { - if (caseData.empty()) { - llvm::BranchInst::Create(_default, d->CurrentBlock); + if (case_data.empty()) { + llvm::BranchInst::Create(default_block, d->current_block_); } else { - llvm::Value *tagVal = d->getTag(val); - auto *_switch = llvm::SwitchInst::Create( - tagVal, _default, caseData.size(), d->CurrentBlock); - for (auto &_case : caseData) { - _switch->addCase( + llvm::Value *tag_val = d->get_tag(val); + auto *switch_inst = llvm::SwitchInst::Create( + tag_val, default_block, case_data.size(), d->current_block_); + for (auto &c : case_data) { + switch_inst->addCase( llvm::ConstantInt::get( - llvm::Type::getInt32Ty(d->Ctx), - _case.second->getConstructor()->getTag()), - _case.first); + llvm::Type::getInt32Ty(d->ctx_), + c.second->get_constructor()->get_tag()), + c.first); } } } - auto *currChoiceBlock = d->ChoiceBlock; - d->ChoiceBlock = nullptr; - auto *switchBlock = d->CurrentBlock; - for (auto &entry : caseData) { - auto const &_case = *entry.second; - if (entry.first == d->FailureBlock) { - if (d->FailPattern) { - d->FailSubject->addIncoming(ptrVal, switchBlock); - d->FailPattern->addIncoming(failPattern, switchBlock); - d->FailSort->addIncoming(failSort, switchBlock); + auto *curr_choice_block = d->choice_block_; + d->choice_block_ = nullptr; + auto *switch_block = d->current_block_; + for (auto &entry : case_data) { + auto const &switch_case = *entry.second; + if (entry.first == d->failure_block_) { + if (d->fail_pattern_) { + d->fail_subject_->addIncoming(ptr_val, switch_block); + d->fail_pattern_->addIncoming(fail_pattern, switch_block); + d->fail_sort_->addIncoming(fail_sort, switch_block); } continue; } - d->CurrentBlock = entry.first; - if (!isInt) { + d->current_block_ = entry.first; + if (!is_int) { int offset = 0; - llvm::StructType *BlockType - = getBlockType(d->Module, d->Definition, _case.getConstructor()); - auto *Cast = new llvm::BitCastInst( - val, llvm::PointerType::getUnqual(BlockType), "", d->CurrentBlock); - KORESymbolDeclaration *symbolDecl - = d->Definition->getSymbolDeclarations().at( - _case.getConstructor()->getName()); - llvm::Instruction *Renamed = nullptr; - for (auto const &binding : _case.getBindings()) { - llvm::Value *ChildPtr = llvm::GetElementPtrInst::CreateInBounds( - BlockType, Cast, - {llvm::ConstantInt::get(llvm::Type::getInt64Ty(d->Ctx), 0), + llvm::StructType *block_type = get_block_type( + d->module_, d->definition_, switch_case.get_constructor()); + auto *cast = new llvm::BitCastInst( + val, llvm::PointerType::getUnqual(block_type), "", d->current_block_); + kore_symbol_declaration *symbol_decl + = d->definition_->get_symbol_declarations().at( + switch_case.get_constructor()->get_name()); + llvm::Instruction *renamed = nullptr; + for (auto const &binding : switch_case.get_bindings()) { + llvm::Value *child_ptr = llvm::GetElementPtrInst::CreateInBounds( + block_type, cast, + {llvm::ConstantInt::get(llvm::Type::getInt64Ty(d->ctx_), 0), llvm::ConstantInt::get( - llvm::Type::getInt32Ty(d->Ctx), offset + 2)}, - "", d->CurrentBlock); + llvm::Type::getInt32Ty(d->ctx_), offset + 2)}, + "", d->current_block_); - llvm::Value *Child = nullptr; - auto cat = dynamic_cast( - _case.getConstructor()->getArguments()[offset].get()) - ->getCategory(d->Definition); + llvm::Value *child = nullptr; + auto cat + = dynamic_cast( + switch_case.get_constructor()->get_arguments()[offset].get()) + ->get_category(d->definition_); switch (cat.cat) { - case SortCategory::Map: - case SortCategory::RangeMap: - case SortCategory::List: - case SortCategory::Set: Child = ChildPtr; break; + case sort_category::Map: + case sort_category::RangeMap: + case sort_category::List: + case sort_category::Set: child = child_ptr; break; default: - Child = new llvm::LoadInst( - getValueType(cat, d->Module), ChildPtr, - binding.first.substr(0, max_name_length), d->CurrentBlock); + child = new llvm::LoadInst( + getvalue_type(cat, d->module_), child_ptr, + binding.first.substr(0, max_name_length), d->current_block_); break; } - auto *BlockPtr + auto *block_ptr = llvm::PointerType::getUnqual(llvm::StructType::getTypeByName( - d->Module->getContext(), BLOCK_STRUCT)); - if (symbolDecl->attributes().contains(attribute_set::key::binder)) { + d->module_->getContext(), block_struct)); + if (symbol_decl->attributes().contains(attribute_set::key::Binder)) { if (offset == 0) { - Renamed = llvm::CallInst::Create( - getOrInsertFunction( - d->Module, "alphaRename", BlockPtr, BlockPtr), - Child, "renamedVar", d->CurrentBlock); - setDebugLoc(Renamed); - d->store(binding, Renamed); - } else if (offset == _case.getBindings().size() - 1) { - llvm::Instruction *Replaced = llvm::CallInst::Create( - getOrInsertFunction( - d->Module, "replaceBinderIndex", BlockPtr, BlockPtr, - BlockPtr), - {Child, Renamed}, "withUnboundIndex", d->CurrentBlock); - setDebugLoc(Replaced); - d->store(binding, Replaced); + renamed = llvm::CallInst::Create( + get_or_insert_function( + d->module_, "alpha_rename", block_ptr, block_ptr), + child, "renamedVar", d->current_block_); + set_debug_loc(renamed); + d->store(binding, renamed); + } else if (offset == switch_case.get_bindings().size() - 1) { + llvm::Instruction *replaced = llvm::CallInst::Create( + get_or_insert_function( + d->module_, "replace_binder_index", block_ptr, block_ptr, + block_ptr), + {child, renamed}, "withUnboundIndex", d->current_block_); + set_debug_loc(replaced); + d->store(binding, replaced); } else { - d->store(binding, Child); + d->store(binding, child); } } else { - d->store(binding, Child); + d->store(binding, child); } offset++; } } else { - if (currChoiceBlock && _case.getLiteral() == 1) { - auto *PrevDepth = new llvm::LoadInst( - llvm::Type::getInt64Ty(d->Ctx), d->ChoiceDepth, "", - d->CurrentBlock); - auto *CurrDepth = llvm::BinaryOperator::Create( - llvm::Instruction::Add, PrevDepth, - llvm::ConstantInt::get(llvm::Type::getInt64Ty(d->Ctx), 1), "", - d->CurrentBlock); - new llvm::StoreInst(CurrDepth, d->ChoiceDepth, d->CurrentBlock); - - auto *alloc = llvm::cast(d->ChoiceBuffer); + if (curr_choice_block && switch_case.get_literal() == 1) { + auto *prev_depth = new llvm::LoadInst( + llvm::Type::getInt64Ty(d->ctx_), d->choice_depth_, "", + d->current_block_); + auto *curr_depth = llvm::BinaryOperator::Create( + llvm::Instruction::Add, prev_depth, + llvm::ConstantInt::get(llvm::Type::getInt64Ty(d->ctx_), 1), "", + d->current_block_); + new llvm::StoreInst(curr_depth, d->choice_depth_, d->current_block_); + + auto *alloc = llvm::cast(d->choice_buffer_); auto *ty = alloc->getAllocatedType(); - auto *zero = llvm::ConstantInt::get(llvm::Type::getInt64Ty(d->Ctx), 0); - auto *currentElt = llvm::GetElementPtrInst::CreateInBounds( - ty, d->ChoiceBuffer, {zero, CurrDepth}, "", d->CurrentBlock); + auto *zero = llvm::ConstantInt::get(llvm::Type::getInt64Ty(d->ctx_), 0); + auto *current_elt = llvm::GetElementPtrInst::CreateInBounds( + ty, d->choice_buffer_, {zero, curr_depth}, "", d->current_block_); new llvm::StoreInst( llvm::BlockAddress::get( - d->CurrentBlock->getParent(), currChoiceBlock), - currentElt, d->CurrentBlock); - d->FailJump->addDestination(currChoiceBlock); + d->current_block_->getParent(), curr_choice_block), + current_elt, d->current_block_); + d->fail_jump_->addDestination(curr_choice_block); } else if ( - currChoiceBlock && _case.getLiteral() == 0 && d->HasSearchResults) { + curr_choice_block && switch_case.get_literal() == 0 + && d->has_search_results_) { // see https://github.com/runtimeverification/llvm-backend/issues/672 // To summarize, if we are doing a search, and we have already found // at least one rule that applies of a given priority, we need to not @@ -331,51 +332,51 @@ void SwitchNode::codegen(Decision *d) { // are compiled that this subtree contains only lower-priority rules, // in this case we simply jump immediately to the failure node. auto *loaded = new llvm::LoadInst( - llvm::Type::getInt1Ty(d->Ctx), d->HasSearchResults, "", - d->CurrentBlock); - auto *newCaseBlock = llvm::BasicBlock::Create( - d->Ctx, "hasNoSearchResults", d->CurrentBlock->getParent()); + llvm::Type::getInt1Ty(d->ctx_), d->has_search_results_, "", + d->current_block_); + auto *new_case_block = llvm::BasicBlock::Create( + d->ctx_, "hasNoSearchResults", d->current_block_->getParent()); llvm::BranchInst::Create( - d->FailureBlock, newCaseBlock, loaded, d->CurrentBlock); - d->CurrentBlock = newCaseBlock; + d->failure_block_, new_case_block, loaded, d->current_block_); + d->current_block_ = new_case_block; } } - _case.getChild()->codegen(d); + switch_case.get_child()->codegen(d); } - if (defaultCase) { - if (_default != d->FailureBlock) { + if (default_case) { + if (default_block != d->failure_block_) { // process default also - d->CurrentBlock = _default; - defaultCase->getChild()->codegen(d); - } else if (d->FailPattern) { - d->FailSubject->addIncoming(ptrVal, switchBlock); - d->FailPattern->addIncoming(failPattern, switchBlock); - d->FailSort->addIncoming(failSort, switchBlock); + d->current_block_ = default_block; + default_case->get_child()->codegen(d); + } else if (d->fail_pattern_) { + d->fail_subject_->addIncoming(ptr_val, switch_block); + d->fail_pattern_->addIncoming(fail_pattern, switch_block); + d->fail_sort_->addIncoming(fail_sort, switch_block); } } - setCompleted(); + set_completed(); } -void MakePatternNode::codegen(Decision *d) { - if (beginNode(d, "pattern" + name)) { +void make_pattern_node::codegen(decision *d) { + if (begin_node(d, "pattern" + name_)) { return; } - llvm::StringMap finalSubst; - for (auto const &use : uses) { - finalSubst[use.first] = d->load(use); + llvm::StringMap final_subst; + for (auto const &use : uses_) { + final_subst[use.first] = d->load(use); } - CreateTerm creator( - finalSubst, d->Definition, d->CurrentBlock, d->Module, false); - llvm::Value *val = creator(pattern).first; - d->CurrentBlock = creator.getCurrentBlock(); - d->store(std::make_pair(name, type), val); - child->codegen(d); - setCompleted(); + create_term creator( + final_subst, d->definition_, d->current_block_, d->module_, false); + llvm::Value *val = creator(pattern_).first; + d->current_block_ = creator.get_current_block(); + d->store(std::make_pair(name_, type_), val); + child_->codegen(d); + set_completed(); } /* - * The code generation step for FunctionNodes emits a call to addMatchFunction + * The code generation step for function_nodes emits a call to add_match_function * that records why a match failed to apply in the case of side-condition calls * failing. Doing so requires that we store the _type_ of each argument * somewhere, in order that opaque block* values can be safely reinterpreted in @@ -386,211 +387,219 @@ void MakePatternNode::codegen(Decision *d) { * therefore define a compatibility translation between sort categories and what * their corresponding LLVM type _would have been_ before opaque pointers. */ -static std::string legacy_value_type_to_string(ValueType sort) { +static std::string legacy_value_type_to_string(value_type sort) { switch (sort.cat) { - case SortCategory::Int: return "%mpz*"; - case SortCategory::Bool: return "i1"; - case SortCategory::Float: return "%floating*"; - case SortCategory::Symbol: - case SortCategory::Variable: return "%block*"; + case sort_category::Int: return "%mpz*"; + case sort_category::Bool: return "i1"; + case sort_category::Float: return "%floating*"; + case sort_category::Symbol: + case sort_category::Variable: return "%block*"; // Cases below are deliberately not implemented; the return values are // placeholders to help with debugging only. - case SortCategory::Map: return ""; - case SortCategory::RangeMap: return ""; - case SortCategory::List: return ""; - case SortCategory::Set: return ""; - case SortCategory::StringBuffer: return ""; - case SortCategory::MInt: return ""; - case SortCategory::Uncomputed: abort(); + case sort_category::Map: return ""; + case sort_category::RangeMap: return ""; + case sort_category::List: return ""; + case sort_category::Set: return ""; + case sort_category::StringBuffer: return ""; + case sort_category::MInt: return ""; + case sort_category::Uncomputed: abort(); } } -void FunctionNode::codegen(Decision *d) { - if (beginNode(d, "function" + name)) { +void function_node::codegen(decision *d) { + if (begin_node(d, "function" + name_)) { return; } std::vector args; - llvm::StringMap finalSubst; - for (auto [arg, cat] : bindings) { + llvm::StringMap final_subst; + for (auto [arg, cat] : bindings_) { llvm::Value *val = nullptr; if (arg.first.find_first_not_of("-0123456789") == std::string::npos) { val = llvm::ConstantInt::get( - llvm::Type::getInt64Ty(d->Ctx), std::stoi(arg.first)); + llvm::Type::getInt64Ty(d->ctx_), std::stoi(arg.first)); } else { val = d->load(arg); } args.push_back(val); - finalSubst[arg.first] = val; + final_subst[arg.first] = val; } - bool isSideCondition = function.substr(0, 15) == "side_condition_"; - - if (isSideCondition) { - ProofEvent p(d->Definition, d->Module); - size_t ordinal = std::stoll(function.substr(15)); - KOREAxiomDeclaration *axiom = d->Definition->getAxiomByOrdinal(ordinal); - d->CurrentBlock = p.sideConditionEvent_pre(axiom, args, d->CurrentBlock); + bool is_side_condition = function_.substr(0, 15) == "side_condition_"; + + if (is_side_condition) { + proof_event p(d->definition_, d->module_); + size_t ordinal = std::stoll(function_.substr(15)); + kore_axiom_declaration *axiom + = d->definition_->get_axiom_by_ordinal(ordinal); + d->current_block_ + = p.side_condition_event_pre(axiom, args, d->current_block_); } - CreateTerm creator( - finalSubst, d->Definition, d->CurrentBlock, d->Module, false); - auto *Call = creator.createFunctionCall( - function, cat, args, function.substr(0, 5) == "hook_", false); - Call->setName(name.substr(0, max_name_length)); - d->store(std::make_pair(name, type), Call); - - if (isSideCondition) { - ProofEvent p(d->Definition, d->Module); - size_t ordinal = std::stoll(function.substr(15)); - KOREAxiomDeclaration *axiom = d->Definition->getAxiomByOrdinal(ordinal); - d->CurrentBlock = p.sideConditionEvent_post(axiom, Call, d->CurrentBlock); + create_term creator( + final_subst, d->definition_, d->current_block_, d->module_, false); + auto *call = creator.create_function_call( + function_, cat_, args, function_.substr(0, 5) == "hook_", false); + call->setName(name_.substr(0, max_name_length)); + d->store(std::make_pair(name_, type_), call); + + if (is_side_condition) { + proof_event p(d->definition_, d->module_); + size_t ordinal = std::stoll(function_.substr(15)); + kore_axiom_declaration *axiom + = d->definition_->get_axiom_by_ordinal(ordinal); + d->current_block_ + = p.side_condition_event_post(axiom, call, d->current_block_); } - if (d->FailPattern) { - std::string debugName = function; - if (function.substr(0, 5) == "hook_") { - debugName = function.substr(5, function.find_first_of('_', 5) - 5) + "." - + function.substr(function.find_first_of('_', 5) + 1); - } else if (isSideCondition) { - size_t ordinal = std::stoll(function.substr(15)); - KOREAxiomDeclaration *axiom = d->Definition->getAxiomByOrdinal(ordinal); - if (axiom->attributes().contains(attribute_set::key::label)) { - debugName - = axiom->attributes().get_string(attribute_set::key::label) + ".sc"; + if (d->fail_pattern_) { + std::string debug_name = function_; + if (function_.substr(0, 5) == "hook_") { + debug_name = function_.substr(5, function_.find_first_of('_', 5) - 5) + + "." + + function_.substr(function_.find_first_of('_', 5) + 1); + } else if (is_side_condition) { + size_t ordinal = std::stoll(function_.substr(15)); + kore_axiom_declaration *axiom + = d->definition_->get_axiom_by_ordinal(ordinal); + if (axiom->attributes().contains(attribute_set::key::Label)) { + debug_name + = axiom->attributes().get_string(attribute_set::key::Label) + ".sc"; } } - std::vector functionArgs; - functionArgs.push_back(d->stringLiteral(debugName)); - functionArgs.push_back(d->stringLiteral(function)); - auto *tempAllocCall = d->ptrTerm(Call); - if (Call->getType() == llvm::Type::getInt1Ty(d->Ctx)) { + std::vector function_args; + function_args.push_back(d->string_literal(debug_name)); + function_args.push_back(d->string_literal(function_)); + auto *temp_alloc_call = d->ptr_term(call); + if (call->getType() == llvm::Type::getInt1Ty(d->ctx_)) { llvm::Value *zext = new llvm::ZExtInst( - Call, llvm::Type::getInt8Ty(d->Ctx), "", d->CurrentBlock); - new llvm::StoreInst(zext, tempAllocCall, d->CurrentBlock); + call, llvm::Type::getInt8Ty(d->ctx_), "", d->current_block_); + new llvm::StoreInst(zext, temp_alloc_call, d->current_block_); } - functionArgs.push_back(tempAllocCall); + function_args.push_back(temp_alloc_call); for (auto i = 0U; i < args.size(); ++i) { auto *arg = args[i]; - auto cat = bindings[i].second; + auto cat = bindings_[i].second; - auto *tempAllocArg = d->ptrTerm(arg); - if (arg->getType() == llvm::Type::getInt1Ty(d->Ctx)) { + auto *temp_alloc_arg = d->ptr_term(arg); + if (arg->getType() == llvm::Type::getInt1Ty(d->ctx_)) { llvm::Value *zext = new llvm::ZExtInst( - Call, llvm::Type::getInt8Ty(d->Ctx), "", d->CurrentBlock); - new llvm::StoreInst(zext, tempAllocArg, d->CurrentBlock); + call, llvm::Type::getInt8Ty(d->ctx_), "", d->current_block_); + new llvm::StoreInst(zext, temp_alloc_arg, d->current_block_); } - functionArgs.push_back(tempAllocArg); + function_args.push_back(temp_alloc_arg); auto str = legacy_value_type_to_string(cat); - functionArgs.push_back(d->stringLiteral(str)); + function_args.push_back(d->string_literal(str)); } - functionArgs.push_back( - llvm::ConstantPointerNull::get(llvm::Type::getInt8PtrTy(d->Ctx))); + function_args.push_back( + llvm::ConstantPointerNull::get(llvm::Type::getInt8PtrTy(d->ctx_))); auto *call = llvm::CallInst::Create( - getOrInsertFunction( - d->Module, "addMatchFunction", + get_or_insert_function( + d->module_, "add_match_function", llvm::FunctionType::get( - llvm::Type::getVoidTy(d->Ctx), - {llvm::Type::getInt8PtrTy(d->Ctx), - llvm::Type::getInt8PtrTy(d->Ctx), - llvm::Type::getInt8PtrTy(d->Ctx)}, + llvm::Type::getVoidTy(d->ctx_), + {llvm::Type::getInt8PtrTy(d->ctx_), + llvm::Type::getInt8PtrTy(d->ctx_), + llvm::Type::getInt8PtrTy(d->ctx_)}, true)), - functionArgs, "", d->CurrentBlock); - setDebugLoc(call); + function_args, "", d->current_block_); + set_debug_loc(call); } - child->codegen(d); - setCompleted(); + child_->codegen(d); + set_completed(); } -void MakeIteratorNode::codegen(Decision *d) { - if (beginNode(d, "new_iterator" + name)) { +void make_iterator_node::codegen(decision *d) { + if (begin_node(d, "new_iterator" + name_)) { return; } std::vector args; std::vector types; - llvm::Value *arg = d->load(std::make_pair(collection, collectionType)); + llvm::Value *arg = d->load(std::make_pair(collection_, collection_type_)); args.push_back(arg); types.push_back(arg->getType()); - llvm::Type *sretType - = llvm::StructType::getTypeByName(d->Module->getContext(), "iter"); - llvm::Value *AllocSret - = allocateTerm(sretType, d->CurrentBlock, "koreAllocAlwaysGC"); - AllocSret->setName(name.substr(0, max_name_length)); - args.insert(args.begin(), AllocSret); - types.insert(types.begin(), AllocSret->getType()); - - llvm::FunctionType *funcType = llvm::FunctionType::get( - llvm::Type::getVoidTy(d->Module->getContext()), types, false); - llvm::Function *func = getOrInsertFunction(d->Module, hookName, funcType); - auto *call = llvm::CallInst::Create(func, args, "", d->CurrentBlock); - setDebugLoc(call); - llvm::Attribute sretAttr - = llvm::Attribute::get(d->Ctx, llvm::Attribute::StructRet, sretType); - func->arg_begin()->addAttr(sretAttr); - call->addParamAttr(0, sretAttr); - d->store(std::make_pair(name, type), AllocSret); - child->codegen(d); - setCompleted(); + llvm::Type *sret_type + = llvm::StructType::getTypeByName(d->module_->getContext(), "iter"); + llvm::Value *alloc_sret + = allocate_term(sret_type, d->current_block_, "kore_alloc_always_gc"); + alloc_sret->setName(name_.substr(0, max_name_length)); + args.insert(args.begin(), alloc_sret); + types.insert(types.begin(), alloc_sret->getType()); + + llvm::FunctionType *func_type = llvm::FunctionType::get( + llvm::Type::getVoidTy(d->module_->getContext()), types, false); + llvm::Function *func + = get_or_insert_function(d->module_, hook_name_, func_type); + auto *call = llvm::CallInst::Create(func, args, "", d->current_block_); + set_debug_loc(call); + llvm::Attribute sret_attr + = llvm::Attribute::get(d->ctx_, llvm::Attribute::StructRet, sret_type); + func->arg_begin()->addAttr(sret_attr); + call->addParamAttr(0, sret_attr); + d->store(std::make_pair(name_, type_), alloc_sret); + child_->codegen(d); + set_completed(); } -void IterNextNode::codegen(Decision *d) { - if (beginNode(d, "choice" + binding)) { +void iter_next_node::codegen(decision *d) { + if (begin_node(d, "choice" + binding_)) { return; } - d->ChoiceBlock = d->CurrentBlock; - llvm::Value *arg = d->load(std::make_pair(iterator, iteratorType)); + d->choice_block_ = d->current_block_; + llvm::Value *arg = d->load(std::make_pair(iterator_, iterator_type_)); - llvm::FunctionType *funcType = llvm::FunctionType::get( - getValueType({SortCategory::Symbol, 0}, d->Module), {arg->getType()}, + llvm::FunctionType *func_type = llvm::FunctionType::get( + getvalue_type({sort_category::Symbol, 0}, d->module_), {arg->getType()}, false); - llvm::Function *func = getOrInsertFunction(d->Module, hookName, funcType); - auto *Call = llvm::CallInst::Create( - func, {arg}, binding.substr(0, max_name_length), d->CurrentBlock); - setDebugLoc(Call); - d->store(std::make_pair(binding, bindingType), Call); - child->codegen(d); - d->ChoiceBlock = nullptr; - setCompleted(); + llvm::Function *func + = get_or_insert_function(d->module_, hook_name_, func_type); + auto *call = llvm::CallInst::Create( + func, {arg}, binding_.substr(0, max_name_length), d->current_block_); + set_debug_loc(call); + d->store(std::make_pair(binding_, binding_type_), call); + child_->codegen(d); + d->choice_block_ = nullptr; + set_completed(); } -void LeafNode::codegen(Decision *d) { - if (beginNode(d, name)) { +void leaf_node::codegen(decision *d) { + if (begin_node(d, name_)) { return; } - if (d->FailPattern) { + if (d->fail_pattern_) { auto *call = llvm::CallInst::Create( - getOrInsertFunction( - d->Module, "addMatchSuccess", llvm::Type::getVoidTy(d->Ctx)), - {}, "", d->CurrentBlock); - setDebugLoc(call); - llvm::ReturnInst::Create(d->Ctx, d->CurrentBlock); - setCompleted(); + get_or_insert_function( + d->module_, "add_match_success", llvm::Type::getVoidTy(d->ctx_)), + {}, "", d->current_block_); + set_debug_loc(call); + llvm::ReturnInst::Create(d->ctx_, d->current_block_); + set_completed(); return; } std::vector args; std::vector types; - for (auto const &arg : bindings) { + for (auto const &arg : bindings_) { auto *val = d->load(arg); args.push_back(val); types.push_back(val->getType()); } - auto *type = getParamType(d->Cat, d->Module); + auto *type = get_param_type(d->cat_, d->module_); - auto *applyRule = getOrInsertFunction( - d->Module, name, llvm::FunctionType::get(type, types, false)); + auto *apply_rule = get_or_insert_function( + d->module_, name_, llvm::FunctionType::get(type, types, false)); // We are generating code for a function with name beginning apply_rule_\d+; to // retrieve the corresponding ordinal we drop the apply_rule_ prefix. - auto ordinal = std::stoll(name.substr(11)); - auto arity = applyRule->arg_end() - applyRule->arg_begin(); - auto *axiom = d->Definition->getAxiomByOrdinal(ordinal); + auto ordinal = std::stoll(name_.substr(11)); + auto arity = apply_rule->arg_end() - apply_rule->arg_begin(); + auto *axiom = d->definition_->get_axiom_by_ordinal(ordinal); - auto vars = std::map{}; - for (KOREPattern *lhs : axiom->getLeftHandSide()) { - lhs->markVariables(vars); + auto vars = std::map{}; + for (kore_pattern *lhs : axiom->get_left_hand_side()) { + lhs->mark_variables(vars); } - axiom->getRightHandSide()->markVariables(vars); + axiom->get_right_hand_side()->mark_variables(vars); auto subst = llvm::StringMap{}; auto i = 0; @@ -598,55 +607,55 @@ void LeafNode::codegen(Decision *d) { subst[iter->first] = args[i]; } - d->CurrentBlock - = ProofEvent(d->Definition, d->Module) - .rewriteEvent_pre(axiom, arity, vars, subst, d->CurrentBlock); + d->current_block_ + = proof_event(d->definition_, d->module_) + .rewrite_event_pre(axiom, arity, vars, subst, d->current_block_); - auto *Call = llvm::CallInst::Create(applyRule, args, "", d->CurrentBlock); - setDebugLoc(Call); - Call->setCallingConv(llvm::CallingConv::Tail); + auto *call = llvm::CallInst::Create(apply_rule, args, "", d->current_block_); + set_debug_loc(call); + call->setCallingConv(llvm::CallingConv::Tail); - if (child == nullptr) { - llvm::ReturnInst::Create(d->Ctx, Call, d->CurrentBlock); + if (child_ == nullptr) { + llvm::ReturnInst::Create(d->ctx_, call, d->current_block_); } else { new llvm::StoreInst( - llvm::ConstantInt::getTrue(d->Ctx), d->HasSearchResults, - d->CurrentBlock); - auto *Call2 = llvm::CallInst::Create( - getOrInsertFunction( - d->Module, "addSearchResult", + llvm::ConstantInt::getTrue(d->ctx_), d->has_search_results_, + d->current_block_); + auto *call2 = llvm::CallInst::Create( + get_or_insert_function( + d->module_, "add_search_result", llvm::FunctionType::get( - llvm::Type::getVoidTy(d->Ctx), {type}, false)), - {Call}, "", d->CurrentBlock); - setDebugLoc(Call2); - if (child != FailNode::get()) { - child->codegen(d); + llvm::Type::getVoidTy(d->ctx_), {type}, false)), + {call}, "", d->current_block_); + set_debug_loc(call2); + if (child_ != fail_node::get()) { + child_->codegen(d); } else { - llvm::BranchInst::Create(d->FailureBlock, d->CurrentBlock); + llvm::BranchInst::Create(d->failure_block_, d->current_block_); } } - setCompleted(); + set_completed(); } -llvm::Value *Decision::getTag(llvm::Value *val) { +llvm::Value *decision::get_tag(llvm::Value *val) { auto *res = llvm::CallInst::Create( - getOrInsertFunction( - Module, "getTag", llvm::Type::getInt32Ty(Ctx), - getValueType({SortCategory::Symbol, 0}, Module)), - val, "tag", CurrentBlock); - setDebugLoc(res); + get_or_insert_function( + module_, "get_tag", llvm::Type::getInt32Ty(ctx_), + getvalue_type({sort_category::Symbol, 0}, module_)), + val, "tag", current_block_); + set_debug_loc(res); return res; } -llvm::AllocaInst *Decision::decl(var_type const &name) { +llvm::AllocaInst *decision::decl(var_type const &name) { auto *sym = new llvm::AllocaInst( name.second, 0, "", - this->CurrentBlock->getParent()->getEntryBlock().getFirstNonPHI()); - this->symbols[name] = sym; + this->current_block_->getParent()->getEntryBlock().getFirstNonPHI()); + this->symbols_[name] = sym; return sym; } -llvm::Value *Decision::load(var_type const &name) { +llvm::Value *decision::load(var_type const &name) { if (name.first.empty()) { llvm::Type *ty = name.second; if (ty->isPointerTy()) { @@ -659,306 +668,314 @@ llvm::Value *Decision::load(var_type const &name) { } assert(false && "Unbound variable on LHS is neither pointer nor integral"); } - auto *sym = this->symbols[name]; + auto *sym = this->symbols_[name]; if (!sym) { sym = this->decl(name); } auto *alloc = llvm::cast(sym); auto *ty = alloc->getAllocatedType(); return new llvm::LoadInst( - ty, sym, name.first.substr(0, max_name_length), this->CurrentBlock); + ty, sym, name.first.substr(0, max_name_length), this->current_block_); } -void Decision::store(var_type const &name, llvm::Value *val) { - auto *sym = this->symbols[name]; +void decision::store(var_type const &name, llvm::Value *val) { + auto *sym = this->symbols_[name]; if (!sym) { sym = this->decl(name); } - new llvm::StoreInst(val, sym, this->CurrentBlock); + new llvm::StoreInst(val, sym, this->current_block_); } -llvm::Constant *Decision::stringLiteral(std::string const &str) { - auto *Str = llvm::ConstantDataArray::getString(Ctx, str, true); - auto *global = Module->getOrInsertGlobal("str_lit_" + str, Str->getType()); - auto *globalVar = llvm::cast(global); - if (!globalVar->hasInitializer()) { - globalVar->setInitializer(Str); +llvm::Constant *decision::string_literal(std::string const &str) { + auto *str_cst = llvm::ConstantDataArray::getString(ctx_, str, true); + auto *global + = module_->getOrInsertGlobal("str_lit_" + str, str_cst->getType()); + auto *global_var = llvm::cast(global); + if (!global_var->hasInitializer()) { + global_var->setInitializer(str_cst); } - llvm::Constant *zero = llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), 0); + llvm::Constant *zero + = llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx_), 0); auto indices = std::vector{zero, zero}; - auto *Ptr = llvm::ConstantExpr::getInBoundsGetElementPtr( - Str->getType(), globalVar, indices); - return Ptr; + auto *ptr = llvm::ConstantExpr::getInBoundsGetElementPtr( + str_cst->getType(), global_var, indices); + return ptr; } -static void initChoiceBuffer( - DecisionNode *dt, llvm::Module *module, llvm::BasicBlock *block, +static void init_choice_buffer( + decision_node *dt, llvm::Module *module, llvm::BasicBlock *block, llvm::BasicBlock *stuck, llvm::BasicBlock *fail, - llvm::AllocaInst **choiceBufferOut, llvm::AllocaInst **choiceDepthOut, - llvm::IndirectBrInst **jumpOut) { - std::unordered_set leaves; + llvm::AllocaInst **choice_buffer_out, llvm::AllocaInst **choice_depth_out, + llvm::IndirectBrInst **jump_out) { + std::unordered_set leaves; dt->preprocess(leaves); auto *ty = llvm::ArrayType::get( - llvm::Type::getInt8PtrTy(module->getContext()), dt->getChoiceDepth() + 1); - auto *choiceBuffer = new llvm::AllocaInst(ty, 0, "choiceBuffer", block); - auto *choiceDepth = new llvm::AllocaInst( + llvm::Type::getInt8PtrTy(module->getContext()), + dt->get_choice_depth() + 1); + auto *choice_buffer = new llvm::AllocaInst(ty, 0, "choiceBuffer", block); + auto *choice_depth = new llvm::AllocaInst( llvm::Type::getInt64Ty(module->getContext()), 0, "choiceDepth", block); auto *zero = llvm::ConstantInt::get(llvm::Type::getInt64Ty(module->getContext()), 0); - new llvm::StoreInst(zero, choiceDepth, block); - auto *firstElt = llvm::GetElementPtrInst::CreateInBounds( - ty, choiceBuffer, {zero, zero}, "", block); + new llvm::StoreInst(zero, choice_depth, block); + auto *first_elt = llvm::GetElementPtrInst::CreateInBounds( + ty, choice_buffer, {zero, zero}, "", block); new llvm::StoreInst( - llvm::BlockAddress::get(block->getParent(), stuck), firstElt, block); - - auto *currDepth = new llvm::LoadInst( - llvm::Type::getInt64Ty(module->getContext()), choiceDepth, "", fail); - auto *currentElt = llvm::GetElementPtrInst::CreateInBounds( - ty, choiceBuffer, {zero, currDepth}, "", fail); - auto *failAddress - = new llvm::LoadInst(ty->getElementType(), currentElt, "", fail); - auto *newDepth = llvm::BinaryOperator::Create( - llvm::Instruction::Sub, currDepth, + llvm::BlockAddress::get(block->getParent(), stuck), first_elt, block); + + auto *curr_depth = new llvm::LoadInst( + llvm::Type::getInt64Ty(module->getContext()), choice_depth, "", fail); + auto *current_elt = llvm::GetElementPtrInst::CreateInBounds( + ty, choice_buffer, {zero, curr_depth}, "", fail); + auto *fail_address + = new llvm::LoadInst(ty->getElementType(), current_elt, "", fail); + auto *new_depth = llvm::BinaryOperator::Create( + llvm::Instruction::Sub, curr_depth, llvm::ConstantInt::get(llvm::Type::getInt64Ty(module->getContext()), 1), "", fail); - new llvm::StoreInst(newDepth, choiceDepth, fail); + new llvm::StoreInst(new_depth, choice_depth, fail); llvm::IndirectBrInst *jump - = llvm::IndirectBrInst::Create(failAddress, 1, fail); + = llvm::IndirectBrInst::Create(fail_address, 1, fail); jump->addDestination(stuck); - *choiceBufferOut = choiceBuffer; - *choiceDepthOut = choiceDepth; - *jumpOut = jump; + *choice_buffer_out = choice_buffer; + *choice_depth_out = choice_depth; + *jump_out = jump; } -void makeEvalOrAnywhereFunction( - KORESymbol *function, KOREDefinition *definition, llvm::Module *module, - DecisionNode *dt, - void (*addStuck)( - llvm::BasicBlock *, llvm::Module *, KORESymbol *, Decision &, - KOREDefinition *)) { - auto returnSort = dynamic_cast(function->getSort().get()) - ->getCategory(definition); - auto *returnType = getParamType(returnSort, module); - auto *debugReturnType - = getDebugType(returnSort, ast_to_string(*function->getSort())); +void make_eval_or_anywhere_function( + kore_symbol *function, kore_definition *definition, llvm::Module *module, + decision_node *dt, + void (*add_stuck)( + llvm::BasicBlock *, llvm::Module *, kore_symbol *, decision &, + kore_definition *)) { + auto return_sort + = dynamic_cast(function->get_sort().get()) + ->get_category(definition); + auto *return_type = get_param_type(return_sort, module); + auto *debug_return_type + = get_debug_type(return_sort, ast_to_string(*function->get_sort())); std::vector args; - std::vector debugArgs; - std::vector cats; - for (auto const &sort : function->getArguments()) { - auto cat = dynamic_cast(sort.get()) - ->getCategory(definition); - debugArgs.push_back(getDebugType(cat, ast_to_string(*sort))); + std::vector debug_args; + std::vector cats; + for (auto const &sort : function->get_arguments()) { + auto cat = dynamic_cast(sort.get()) + ->get_category(definition); + debug_args.push_back(get_debug_type(cat, ast_to_string(*sort))); switch (cat.cat) { - case SortCategory::Map: - case SortCategory::RangeMap: - case SortCategory::List: - case SortCategory::Set: - args.push_back(llvm::PointerType::getUnqual(getValueType(cat, module))); + case sort_category::Map: + case sort_category::RangeMap: + case sort_category::List: + case sort_category::Set: + args.push_back(llvm::PointerType::getUnqual(getvalue_type(cat, module))); cats.push_back(cat); break; default: - args.push_back(getValueType(cat, module)); + args.push_back(getvalue_type(cat, module)); cats.push_back(cat); break; } } - llvm::FunctionType *funcType - = llvm::FunctionType::get(returnType, args, false); + llvm::FunctionType *func_type + = llvm::FunctionType::get(return_type, args, false); std::string name = fmt::format("eval_{}", ast_to_string(*function, 0, false)); - llvm::Function *matchFunc = getOrInsertFunction(module, name, funcType); - [[maybe_unused]] KORESymbolDeclaration *symbolDecl - = definition->getSymbolDeclarations().at(function->getName()); - initDebugAxiom(symbolDecl->attributes()); - initDebugFunction( - function->getName(), name, - getDebugFunctionType(debugReturnType, debugArgs), definition, matchFunc); - matchFunc->setCallingConv(llvm::CallingConv::Tail); + llvm::Function *match_func = get_or_insert_function(module, name, func_type); + [[maybe_unused]] kore_symbol_declaration *symbol_decl + = definition->get_symbol_declarations().at(function->get_name()); + init_debug_axiom(symbol_decl->attributes()); + init_debug_function( + function->get_name(), name, + get_debug_function_type(debug_return_type, debug_args), definition, + match_func); + match_func->setCallingConv(llvm::CallingConv::Tail); llvm::BasicBlock *block - = llvm::BasicBlock::Create(module->getContext(), "entry", matchFunc); + = llvm::BasicBlock::Create(module->getContext(), "entry", match_func); llvm::BasicBlock *stuck - = llvm::BasicBlock::Create(module->getContext(), "stuck", matchFunc); + = llvm::BasicBlock::Create(module->getContext(), "stuck", match_func); llvm::BasicBlock *fail - = llvm::BasicBlock::Create(module->getContext(), "fail", matchFunc); + = llvm::BasicBlock::Create(module->getContext(), "fail", match_func); - llvm::AllocaInst *choiceBuffer = nullptr; - llvm::AllocaInst *choiceDepth = nullptr; + llvm::AllocaInst *choice_buffer = nullptr; + llvm::AllocaInst *choice_depth = nullptr; llvm::IndirectBrInst *jump = nullptr; - initChoiceBuffer( - dt, module, block, stuck, fail, &choiceBuffer, &choiceDepth, &jump); + init_choice_buffer( + dt, module, block, stuck, fail, &choice_buffer, &choice_depth, &jump); int i = 0; - Decision codegen( - definition, block, fail, jump, choiceBuffer, choiceDepth, module, - returnSort, nullptr, nullptr, nullptr, nullptr); - for (auto *val = matchFunc->arg_begin(); val != matchFunc->arg_end(); + decision codegen( + definition, block, fail, jump, choice_buffer, choice_depth, module, + return_sort, nullptr, nullptr, nullptr, nullptr); + for (auto *val = match_func->arg_begin(); val != match_func->arg_end(); ++val, ++i) { val->setName("_" + std::to_string(i + 1)); codegen.store(std::make_pair(val->getName().str(), val->getType()), val); - initDebugParam( - matchFunc, i, val->getName().str(), cats[i], - ast_to_string(*function->getArguments()[i])); + init_debug_param( + match_func, i, val->getName().str(), cats[i], + ast_to_string(*function->get_arguments()[i])); } - addStuck(stuck, module, function, codegen, definition); + add_stuck(stuck, module, function, codegen, definition); codegen(dt); } -void abortWhenStuck( - llvm::BasicBlock *CurrentBlock, llvm::Module *Module, KORESymbol *symbol, - Decision &codegen, KOREDefinition *d) { - auto &Ctx = Module->getContext(); - symbol = d->getAllSymbols().at(ast_to_string(*symbol)); - auto *BlockType = getBlockType(Module, d, symbol); - llvm::Value *Ptr = nullptr; - auto *BlockPtr = llvm::PointerType::getUnqual( - llvm::StructType::getTypeByName(Module->getContext(), BLOCK_STRUCT)); - if (symbol->getArguments().empty()) { - Ptr = llvm::ConstantExpr::getIntToPtr( +void abort_when_stuck( + llvm::BasicBlock *current_block, llvm::Module *module, kore_symbol *symbol, + decision &codegen, kore_definition *d) { + auto &ctx = module->getContext(); + symbol = d->get_all_symbols().at(ast_to_string(*symbol)); + auto *block_type = get_block_type(module, d, symbol); + llvm::Value *ptr = nullptr; + auto *block_ptr = llvm::PointerType::getUnqual( + llvm::StructType::getTypeByName(module->getContext(), block_struct)); + if (symbol->get_arguments().empty()) { + ptr = llvm::ConstantExpr::getIntToPtr( llvm::ConstantInt::get( - llvm::Type::getInt64Ty(Ctx), - ((uint64_t)symbol->getTag() << 32 | 1)), - getValueType({SortCategory::Symbol, 0}, Module)); + llvm::Type::getInt64Ty(ctx), + ((uint64_t)symbol->get_tag() << 32 | 1)), + getvalue_type({sort_category::Symbol, 0}, module)); } else { - llvm::Value *BlockHeader = getBlockHeader(Module, d, symbol, BlockType); - llvm::Value *Block = allocateTerm(BlockType, CurrentBlock); - llvm::Value *BlockHeaderPtr = llvm::GetElementPtrInst::CreateInBounds( - BlockType, Block, - {llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), 0), - llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 0)}, - symbol->getName(), CurrentBlock); - new llvm::StoreInst(BlockHeader, BlockHeaderPtr, CurrentBlock); - for (int idx = 0; idx < symbol->getArguments().size(); idx++) { - auto cat - = dynamic_cast(symbol->getArguments()[idx].get()) - ->getCategory(d); - auto *type = getParamType(cat, Module); - llvm::Value *ChildValue + llvm::Value *block_header = get_block_header(module, d, symbol, block_type); + llvm::Value *block = allocate_term(block_type, current_block); + llvm::Value *block_header_ptr = llvm::GetElementPtrInst::CreateInBounds( + block_type, block, + {llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx), 0), + llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx), 0)}, + symbol->get_name(), current_block); + new llvm::StoreInst(block_header, block_header_ptr, current_block); + for (int idx = 0; idx < symbol->get_arguments().size(); idx++) { + auto cat = dynamic_cast( + symbol->get_arguments()[idx].get()) + ->get_category(d); + auto *type = get_param_type(cat, module); + llvm::Value *child_value = codegen.load(std::make_pair("_" + std::to_string(idx + 1), type)); - llvm::Value *ChildPtr = llvm::GetElementPtrInst::CreateInBounds( - BlockType, Block, - {llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), 0), - llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), idx + 2)}, - "", CurrentBlock); - if (isCollectionSort(cat)) { - ChildValue = new llvm::LoadInst( - getArgType(cat, Module), ChildValue, "", CurrentBlock); + llvm::Value *child_ptr = llvm::GetElementPtrInst::CreateInBounds( + block_type, block, + {llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx), 0), + llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx), idx + 2)}, + "", current_block); + if (is_collection_sort(cat)) { + child_value = new llvm::LoadInst( + get_arg_type(cat, module), child_value, "", current_block); } - new llvm::StoreInst(ChildValue, ChildPtr, CurrentBlock); + new llvm::StoreInst(child_value, child_ptr, current_block); } - Ptr = new llvm::BitCastInst(Block, BlockPtr, "", CurrentBlock); + ptr = new llvm::BitCastInst(block, block_ptr, "", current_block); } llvm::CallInst::Create( - getOrInsertFunction( - Module, "finish_rewriting", llvm::Type::getVoidTy(Ctx), BlockPtr, - llvm::Type::getInt1Ty(Ctx)), - {Ptr, llvm::ConstantInt::getTrue(Ctx)}, "", CurrentBlock); - new llvm::UnreachableInst(Ctx, CurrentBlock); + get_or_insert_function( + module, "finish_rewriting", llvm::Type::getVoidTy(ctx), block_ptr, + llvm::Type::getInt1Ty(ctx)), + {ptr, llvm::ConstantInt::getTrue(ctx)}, "", current_block); + new llvm::UnreachableInst(ctx, current_block); } -void makeEvalFunction( - KORESymbol *function, KOREDefinition *definition, llvm::Module *module, - DecisionNode *dt) { - makeEvalOrAnywhereFunction(function, definition, module, dt, abortWhenStuck); +void make_eval_function( + kore_symbol *function, kore_definition *definition, llvm::Module *module, + decision_node *dt) { + make_eval_or_anywhere_function( + function, definition, module, dt, abort_when_stuck); } -void addOwise( - llvm::BasicBlock *stuck, llvm::Module *module, KORESymbol *symbol, - Decision &codegen, KOREDefinition *d) { - llvm::StringMap finalSubst; - ptr pat = KORECompositePattern::Create(symbol); - for (int i = 0; i < symbol->getArguments().size(); i++) { +void add_owise( + llvm::BasicBlock *stuck, llvm::Module *module, kore_symbol *symbol, + decision &codegen, kore_definition *d) { + llvm::StringMap final_subst; + ptr pat = kore_composite_pattern::create(symbol); + for (int i = 0; i < symbol->get_arguments().size(); i++) { auto cat - = dynamic_cast(symbol->getArguments()[i].get()) - ->getCategory(d); - auto *type = getParamType(cat, module); + = dynamic_cast(symbol->get_arguments()[i].get()) + ->get_category(d); + auto *type = get_param_type(cat, module); std::string name = "_" + std::to_string(i + 1); - finalSubst[name] = codegen.load(std::make_pair(name, type)); + final_subst[name] = codegen.load(std::make_pair(name, type)); - auto var = KOREVariablePattern::Create(name, symbol->getArguments()[i]); - pat->addArgument(std::move(var)); + auto var = kore_variable_pattern::create(name, symbol->get_arguments()[i]); + pat->add_argument(std::move(var)); } - CreateTerm creator = CreateTerm(finalSubst, d, stuck, module, true); + create_term creator = create_term(final_subst, d, stuck, module, true); llvm::Value *retval = creator(pat.get()).first; - auto returnSort = dynamic_cast(symbol->getSort().get()) - ->getCategory(d); - if (isCollectionSort(returnSort)) { - auto *tempAlloc = allocateTerm( - retval->getType(), creator.getCurrentBlock(), "koreAllocAlwaysGC"); - new llvm::StoreInst(retval, tempAlloc, creator.getCurrentBlock()); - retval = tempAlloc; + auto return_sort + = dynamic_cast(symbol->get_sort().get()) + ->get_category(d); + if (is_collection_sort(return_sort)) { + auto *temp_alloc = allocate_term( + retval->getType(), creator.get_current_block(), "kore_alloc_always_gc"); + new llvm::StoreInst(retval, temp_alloc, creator.get_current_block()); + retval = temp_alloc; } llvm::ReturnInst::Create( - module->getContext(), retval, creator.getCurrentBlock()); + module->getContext(), retval, creator.get_current_block()); } -void makeAnywhereFunction( - KORESymbol *function, KOREDefinition *definition, llvm::Module *module, - DecisionNode *dt) { - makeEvalOrAnywhereFunction(function, definition, module, dt, addOwise); +void make_anywhere_function( + kore_symbol *function, kore_definition *definition, llvm::Module *module, + decision_node *dt) { + make_eval_or_anywhere_function(function, definition, module, dt, add_owise); } -std::pair, llvm::BasicBlock *> stepFunctionHeader( - unsigned ordinal, llvm::Module *module, KOREDefinition *definition, +std::pair, llvm::BasicBlock *> step_function_header( + unsigned ordinal, llvm::Module *module, kore_definition *definition, llvm::BasicBlock *block, llvm::BasicBlock *stuck, - std::vector args, std::vector const &types) { - auto *finished = getOrInsertFunction( + std::vector args, std::vector const &types) { + auto *finished = get_or_insert_function( module, "finished_rewriting", llvm::FunctionType::get( llvm::Type::getInt1Ty(module->getContext()), {}, false)); - auto *isFinished = llvm::CallInst::Create(finished, {}, "", block); - auto *checkCollect = llvm::BasicBlock::Create( + auto *is_finished = llvm::CallInst::Create(finished, {}, "", block); + auto *check_collect = llvm::BasicBlock::Create( module->getContext(), "checkCollect", block->getParent()); - llvm::BranchInst::Create(stuck, checkCollect, isFinished, block); + llvm::BranchInst::Create(stuck, check_collect, is_finished, block); - auto *collection = getOrInsertFunction( + auto *collection = get_or_insert_function( module, "is_collection", llvm::FunctionType::get( llvm::Type::getInt1Ty(module->getContext()), {}, false)); - auto *isCollection = llvm::CallInst::Create(collection, {}, "", checkCollect); - setDebugLoc(isCollection); + auto *is_collection + = llvm::CallInst::Create(collection, {}, "", check_collect); + set_debug_loc(is_collection); auto *collect = llvm::BasicBlock::Create( module->getContext(), "isCollect", block->getParent()); auto *merge = llvm::BasicBlock::Create( module->getContext(), "step", block->getParent()); - llvm::BranchInst::Create(collect, merge, isCollection, checkCollect); + llvm::BranchInst::Create(collect, merge, is_collection, check_collect); unsigned nroots = 0; unsigned i = 0; - std::vector ptrTypes; + std::vector ptr_types; std::vector roots; for (auto type : types) { switch (type.cat) { - case SortCategory::Map: - case SortCategory::RangeMap: - case SortCategory::List: - case SortCategory::Set: + case sort_category::Map: + case sort_category::RangeMap: + case sort_category::List: + case sort_category::Set: nroots++; - ptrTypes.push_back( - llvm::PointerType::getUnqual(getValueType(type, module))); + ptr_types.push_back( + llvm::PointerType::getUnqual(getvalue_type(type, module))); roots.push_back(args[i]); break; - case SortCategory::Int: - case SortCategory::Float: - case SortCategory::StringBuffer: - case SortCategory::Symbol: - case SortCategory::Variable: + case sort_category::Int: + case sort_category::Float: + case sort_category::StringBuffer: + case sort_category::Symbol: + case sort_category::Variable: nroots++; - ptrTypes.push_back(getValueType(type, module)); + ptr_types.push_back(getvalue_type(type, module)); roots.push_back(args[i]); break; - case SortCategory::Bool: - case SortCategory::MInt: break; - case SortCategory::Uncomputed: abort(); + case sort_category::Bool: + case sort_category::MInt: break; + case sort_category::Uncomputed: abort(); } i++; } auto *root_ty = llvm::ArrayType::get( llvm::Type::getInt8PtrTy(module->getContext()), 256); auto *arr = module->getOrInsertGlobal("gc_roots", root_ty); - std::vector> rootPtrs; + std::vector> root_ptrs; for (unsigned i = 0; i < nroots; i++) { auto *ptr = llvm::GetElementPtrInst::CreateInBounds( root_ty, arr, @@ -968,90 +985,90 @@ std::pair, llvm::BasicBlock *> stepFunctionHeader( llvm::Type::getInt64Ty(module->getContext()), i)}, "", collect); auto *casted = new llvm::BitCastInst( - ptr, llvm::PointerType::getUnqual(ptrTypes[i]), "", collect); + ptr, llvm::PointerType::getUnqual(ptr_types[i]), "", collect); new llvm::StoreInst(roots[i], casted, collect); - rootPtrs.emplace_back(casted, ptrTypes[i]); + root_ptrs.emplace_back(casted, ptr_types[i]); } std::vector elements; i = 0; for (auto cat : types) { switch (cat.cat) { - case SortCategory::Map: - case SortCategory::RangeMap: - case SortCategory::List: - case SortCategory::Set: - case SortCategory::StringBuffer: - case SortCategory::Symbol: - case SortCategory::Variable: - case SortCategory::Int: - case SortCategory::Float: + case sort_category::Map: + case sort_category::RangeMap: + case sort_category::List: + case sort_category::Set: + case sort_category::StringBuffer: + case sort_category::Symbol: + case sort_category::Variable: + case sort_category::Int: + case sort_category::Float: elements.push_back(llvm::ConstantStruct::get( llvm::StructType::getTypeByName( - module->getContext(), LAYOUTITEM_STRUCT), + module->getContext(), layoutitem_struct), llvm::ConstantInt::get( llvm::Type::getInt64Ty(module->getContext()), i++ * 8), llvm::ConstantInt::get( llvm::Type::getInt16Ty(module->getContext()), (int)cat.cat + cat.bits))); break; - case SortCategory::Bool: - case SortCategory::MInt: break; - case SortCategory::Uncomputed: abort(); + case sort_category::Bool: + case sort_category::MInt: break; + case sort_category::Uncomputed: abort(); } } - auto *layoutArr = llvm::ConstantArray::get( + auto *layout_arr = llvm::ConstantArray::get( llvm::ArrayType::get( llvm::StructType::getTypeByName( - module->getContext(), LAYOUTITEM_STRUCT), + module->getContext(), layoutitem_struct), elements.size()), elements); auto *layout = module->getOrInsertGlobal( - "layout_item_rule_" + std::to_string(ordinal), layoutArr->getType()); - auto *globalVar = llvm::cast(layout); - if (!globalVar->hasInitializer()) { - globalVar->setInitializer(layoutArr); + "layout_item_rule_" + std::to_string(ordinal), layout_arr->getType()); + auto *global_var = llvm::cast(layout); + if (!global_var->hasInitializer()) { + global_var->setInitializer(layout_arr); } - auto *ptrTy = llvm::PointerType::getUnqual(llvm::ArrayType::get( - llvm::StructType::getTypeByName(module->getContext(), LAYOUTITEM_STRUCT), + auto *ptr_ty = llvm::PointerType::getUnqual(llvm::ArrayType::get( + llvm::StructType::getTypeByName(module->getContext(), layoutitem_struct), 0)); - auto *koreCollect = getOrInsertFunction( - module, "koreCollect", + auto *kore_collect = get_or_insert_function( + module, "kore_collect", llvm::FunctionType::get( llvm::Type::getVoidTy(module->getContext()), - {arr->getType(), llvm::Type::getInt8Ty(module->getContext()), ptrTy}, + {arr->getType(), llvm::Type::getInt8Ty(module->getContext()), ptr_ty}, false)); auto *call = llvm::CallInst::Create( - koreCollect, + kore_collect, {arr, llvm::ConstantInt::get( llvm::Type::getInt8Ty(module->getContext()), nroots), - llvm::ConstantExpr::getBitCast(layout, ptrTy)}, + llvm::ConstantExpr::getBitCast(layout, ptr_ty)}, "", collect); - setDebugLoc(call); + set_debug_loc(call); i = 0; std::vector phis; - for (auto [ptr, pointee_ty] : rootPtrs) { + for (auto [ptr, pointee_ty] : root_ptrs) { auto *loaded = new llvm::LoadInst(pointee_ty, ptr, "", collect); auto *phi = llvm::PHINode::Create(loaded->getType(), 2, "phi", merge); phi->addIncoming(loaded, collect); - phi->addIncoming(roots[i++], checkCollect); + phi->addIncoming(roots[i++], check_collect); phis.push_back(phi); } llvm::BranchInst::Create(merge, collect); i = 0; - unsigned rootIdx = 0; + unsigned root_idx = 0; std::vector results; for (auto type : types) { switch (type.cat) { - case SortCategory::Map: - case SortCategory::RangeMap: - case SortCategory::List: - case SortCategory::Set: - case SortCategory::StringBuffer: - case SortCategory::Symbol: - case SortCategory::Variable: - case SortCategory::Int: - case SortCategory::Float: results.push_back(phis[rootIdx++]); break; + case sort_category::Map: + case sort_category::RangeMap: + case sort_category::List: + case sort_category::Set: + case sort_category::StringBuffer: + case sort_category::Symbol: + case sort_category::Variable: + case sort_category::Int: + case sort_category::Float: results.push_back(phis[root_idx++]); break; default: results.push_back(args[i]); } i++; @@ -1059,184 +1076,187 @@ std::pair, llvm::BasicBlock *> stepFunctionHeader( return std::make_pair(results, merge); } -void makeStepFunction( - KOREDefinition *definition, llvm::Module *module, DecisionNode *dt, +void make_step_function( + kore_definition *definition, llvm::Module *module, decision_node *dt, bool search) { - auto *blockType = getValueType({SortCategory::Symbol, 0}, module); - auto *debugType - = getDebugType({SortCategory::Symbol, 0}, "SortGeneratedTopCell{}"); - llvm::FunctionType *funcType = nullptr; + auto *block_type = getvalue_type({sort_category::Symbol, 0}, module); + auto *debug_type + = get_debug_type({sort_category::Symbol, 0}, "SortGeneratedTopCell{}"); + llvm::FunctionType *func_type = nullptr; std::string name; if (search) { - name = "stepAll"; - funcType = llvm::FunctionType::get( - llvm::Type::getVoidTy(module->getContext()), {blockType}, false); + name = "step_all"; + func_type = llvm::FunctionType::get( + llvm::Type::getVoidTy(module->getContext()), {block_type}, false); } else { name = "k_step"; - funcType = llvm::FunctionType::get(blockType, {blockType}, false); + func_type = llvm::FunctionType::get(block_type, {block_type}, false); } - llvm::Function *matchFunc = getOrInsertFunction(module, name, funcType); - resetDebugLoc(); + llvm::Function *match_func = get_or_insert_function(module, name, func_type); + reset_debug_loc(); if (search) { - initDebugFunction( - name, name, getDebugFunctionType(getVoidDebugType(), {debugType}), - definition, matchFunc); + init_debug_function( + name, name, + get_debug_function_type(get_void_debug_type(), {debug_type}), + definition, match_func); } else { - initDebugFunction( - name, name, getDebugFunctionType(debugType, {debugType}), definition, - matchFunc); + init_debug_function( + name, name, get_debug_function_type(debug_type, {debug_type}), + definition, match_func); } - matchFunc->setCallingConv(llvm::CallingConv::Tail); - auto *val = matchFunc->arg_begin(); + match_func->setCallingConv(llvm::CallingConv::Tail); + auto *val = match_func->arg_begin(); llvm::BasicBlock *block - = llvm::BasicBlock::Create(module->getContext(), "entry", matchFunc); + = llvm::BasicBlock::Create(module->getContext(), "entry", match_func); llvm::BasicBlock *stuck - = llvm::BasicBlock::Create(module->getContext(), "stuck", matchFunc); + = llvm::BasicBlock::Create(module->getContext(), "stuck", match_func); llvm::BasicBlock *pre_stuck - = llvm::BasicBlock::Create(module->getContext(), "pre_stuck", matchFunc); + = llvm::BasicBlock::Create(module->getContext(), "pre_stuck", match_func); llvm::BasicBlock *fail - = llvm::BasicBlock::Create(module->getContext(), "fail", matchFunc); + = llvm::BasicBlock::Create(module->getContext(), "fail", match_func); - llvm::AllocaInst *choiceBuffer = nullptr; - llvm::AllocaInst *choiceDepth = nullptr; + llvm::AllocaInst *choice_buffer = nullptr; + llvm::AllocaInst *choice_depth = nullptr; llvm::IndirectBrInst *jump = nullptr; - initChoiceBuffer( - dt, module, block, pre_stuck, fail, &choiceBuffer, &choiceDepth, &jump); + init_choice_buffer( + dt, module, block, pre_stuck, fail, &choice_buffer, &choice_depth, &jump); - llvm::AllocaInst *HasSearchResults = nullptr; + llvm::AllocaInst *has_search_results = nullptr; if (search) { - HasSearchResults = new llvm::AllocaInst( - llvm::Type::getInt1Ty(module->getContext()), 0, "hasSearchResults", + has_search_results = new llvm::AllocaInst( + llvm::Type::getInt1Ty(module->getContext()), 0, "has_search_results", block); new llvm::StoreInst( - llvm::ConstantInt::getFalse(module->getContext()), HasSearchResults, + llvm::ConstantInt::getFalse(module->getContext()), has_search_results, block); } - initDebugParam( - matchFunc, 0, "subject", {SortCategory::Symbol, 0}, + init_debug_param( + match_func, 0, "subject", {sort_category::Symbol, 0}, "SortGeneratedTopCell{}"); llvm::BranchInst::Create(stuck, pre_stuck); - auto result = stepFunctionHeader( - 0, module, definition, block, stuck, {val}, {{SortCategory::Symbol, 0}}); - auto *collectedVal = result.first[0]; - collectedVal->setName("_1"); - Decision codegen( - definition, result.second, fail, jump, choiceBuffer, choiceDepth, module, - {SortCategory::Symbol, 0}, nullptr, nullptr, nullptr, HasSearchResults); + auto result = step_function_header( + 0, module, definition, block, stuck, {val}, {{sort_category::Symbol, 0}}); + auto *collected_val = result.first[0]; + collected_val->setName("_1"); + decision codegen( + definition, result.second, fail, jump, choice_buffer, choice_depth, + module, {sort_category::Symbol, 0}, nullptr, nullptr, nullptr, + has_search_results); codegen.store( - std::make_pair(collectedVal->getName().str(), collectedVal->getType()), - collectedVal); + std::make_pair(collected_val->getName().str(), collected_val->getType()), + collected_val); if (search) { llvm::ReturnInst::Create(module->getContext(), stuck); } else { auto *phi - = llvm::PHINode::Create(collectedVal->getType(), 2, "phi_1", stuck); + = llvm::PHINode::Create(collected_val->getType(), 2, "phi_1", stuck); phi->addIncoming(val, block); - phi->addIncoming(collectedVal, pre_stuck); + phi->addIncoming(collected_val, pre_stuck); llvm::ReturnInst::Create(module->getContext(), phi, stuck); } codegen(dt); } -void makeMatchReasonFunctionWrapper( - KOREDefinition *definition, llvm::Module *module, - KOREAxiomDeclaration *axiom, std::string const &name) { - auto *blockType = getValueType({SortCategory::Symbol, 0}, module); - llvm::FunctionType *funcType = llvm::FunctionType::get( - llvm::Type::getVoidTy(module->getContext()), {blockType}, false); - std::string wrapperName = "match_" + std::to_string(axiom->getOrdinal()); - llvm::Function *matchFunc - = getOrInsertFunction(module, wrapperName, funcType); - std::string debugName = name; - if (axiom->attributes().contains(attribute_set::key::label)) { - debugName = axiom->attributes().get_string(attribute_set::key::label) - + "_tailcc_" + ".match"; +void make_match_reason_function_wrapper( + kore_definition *definition, llvm::Module *module, + kore_axiom_declaration *axiom, std::string const &name) { + auto *block_type = getvalue_type({sort_category::Symbol, 0}, module); + llvm::FunctionType *func_type = llvm::FunctionType::get( + llvm::Type::getVoidTy(module->getContext()), {block_type}, false); + std::string wrapper_name = "match_" + std::to_string(axiom->get_ordinal()); + llvm::Function *match_func + = get_or_insert_function(module, wrapper_name, func_type); + std::string debug_name = name; + if (axiom->attributes().contains(attribute_set::key::Label)) { + debug_name = axiom->attributes().get_string(attribute_set::key::Label) + + "_tailcc_" + ".match"; } - auto *debugType - = getDebugType({SortCategory::Symbol, 0}, "SortGeneratedTopCell{}"); - resetDebugLoc(); - initDebugFunction( - debugName, debugName, - getDebugFunctionType(getVoidDebugType(), {debugType}), definition, - matchFunc); - matchFunc->setCallingConv(llvm::CallingConv::Tail); + auto *debug_type + = get_debug_type({sort_category::Symbol, 0}, "SortGeneratedTopCell{}"); + reset_debug_loc(); + init_debug_function( + debug_name, debug_name, + get_debug_function_type(get_void_debug_type(), {debug_type}), definition, + match_func); + match_func->setCallingConv(llvm::CallingConv::Tail); llvm::BasicBlock *entry - = llvm::BasicBlock::Create(module->getContext(), "entry", matchFunc); + = llvm::BasicBlock::Create(module->getContext(), "entry", match_func); auto *ci = module->getFunction(name); - auto *call = llvm::CallInst::Create(ci, matchFunc->getArg(0), "", entry); - setDebugLoc(call); + auto *call = llvm::CallInst::Create(ci, match_func->getArg(0), "", entry); + set_debug_loc(call); llvm::ReturnInst::Create(module->getContext(), entry); } -void makeMatchReasonFunction( - KOREDefinition *definition, llvm::Module *module, - KOREAxiomDeclaration *axiom, DecisionNode *dt) { - auto *blockType = getValueType({SortCategory::Symbol, 0}, module); - llvm::FunctionType *funcType = llvm::FunctionType::get( - llvm::Type::getVoidTy(module->getContext()), {blockType}, false); - std::string name = "intern_match_" + std::to_string(axiom->getOrdinal()); - llvm::Function *matchFunc = getOrInsertFunction(module, name, funcType); - std::string debugName = name; - if (axiom->attributes().contains(attribute_set::key::label)) { - debugName - = axiom->attributes().get_string(attribute_set::key::label) + ".match"; +void make_match_reason_function( + kore_definition *definition, llvm::Module *module, + kore_axiom_declaration *axiom, decision_node *dt) { + auto *block_type = getvalue_type({sort_category::Symbol, 0}, module); + llvm::FunctionType *func_type = llvm::FunctionType::get( + llvm::Type::getVoidTy(module->getContext()), {block_type}, false); + std::string name = "intern_match_" + std::to_string(axiom->get_ordinal()); + llvm::Function *match_func = get_or_insert_function(module, name, func_type); + std::string debug_name = name; + if (axiom->attributes().contains(attribute_set::key::Label)) { + debug_name + = axiom->attributes().get_string(attribute_set::key::Label) + ".match"; } - auto *debugType - = getDebugType({SortCategory::Symbol, 0}, "SortGeneratedTopCell{}"); - resetDebugLoc(); - initDebugFunction( - debugName, debugName, - getDebugFunctionType(getVoidDebugType(), {debugType}), definition, - matchFunc); - auto *val = matchFunc->arg_begin(); + auto *debug_type + = get_debug_type({sort_category::Symbol, 0}, "SortGeneratedTopCell{}"); + reset_debug_loc(); + init_debug_function( + debug_name, debug_name, + get_debug_function_type(get_void_debug_type(), {debug_type}), definition, + match_func); + auto *val = match_func->arg_begin(); llvm::BasicBlock *block - = llvm::BasicBlock::Create(module->getContext(), "entry", matchFunc); + = llvm::BasicBlock::Create(module->getContext(), "entry", match_func); llvm::BasicBlock *stuck - = llvm::BasicBlock::Create(module->getContext(), "stuck", matchFunc); + = llvm::BasicBlock::Create(module->getContext(), "stuck", match_func); llvm::BasicBlock *pre_stuck - = llvm::BasicBlock::Create(module->getContext(), "pre_stuck", matchFunc); + = llvm::BasicBlock::Create(module->getContext(), "pre_stuck", match_func); llvm::BasicBlock *fail - = llvm::BasicBlock::Create(module->getContext(), "fail", matchFunc); - llvm::PHINode *FailSubject = llvm::PHINode::Create( + = llvm::BasicBlock::Create(module->getContext(), "fail", match_func); + llvm::PHINode *fail_subject = llvm::PHINode::Create( llvm::Type::getInt8PtrTy(module->getContext()), 0, "subject", fail); - llvm::PHINode *FailPattern = llvm::PHINode::Create( + llvm::PHINode *fail_pattern = llvm::PHINode::Create( llvm::Type::getInt8PtrTy(module->getContext()), 0, "pattern", fail); - llvm::PHINode *FailSort = llvm::PHINode::Create( + llvm::PHINode *fail_sort = llvm::PHINode::Create( llvm::Type::getInt8PtrTy(module->getContext()), 0, "sort", fail); auto *call = llvm::CallInst::Create( - getOrInsertFunction( - module, "addMatchFailReason", + get_or_insert_function( + module, "add_match_fail_reason", llvm::FunctionType::get( llvm::Type::getVoidTy(module->getContext()), - {FailSubject->getType(), FailPattern->getType(), - FailSort->getType()}, + {fail_subject->getType(), fail_pattern->getType(), + fail_sort->getType()}, false)), - {FailSubject, FailPattern, FailSort}, "", fail); - setDebugLoc(call); + {fail_subject, fail_pattern, fail_sort}, "", fail); + set_debug_loc(call); - llvm::AllocaInst *choiceBuffer = nullptr; - llvm::AllocaInst *choiceDepth = nullptr; + llvm::AllocaInst *choice_buffer = nullptr; + llvm::AllocaInst *choice_depth = nullptr; llvm::IndirectBrInst *jump = nullptr; - initChoiceBuffer( - dt, module, block, pre_stuck, fail, &choiceBuffer, &choiceDepth, &jump); + init_choice_buffer( + dt, module, block, pre_stuck, fail, &choice_buffer, &choice_depth, &jump); - initDebugParam( - matchFunc, 0, "subject", {SortCategory::Symbol, 0}, + init_debug_param( + match_func, 0, "subject", {sort_category::Symbol, 0}, "SortGeneratedTopCell{}"); llvm::BranchInst::Create(stuck, pre_stuck); val->setName("_1"); - Decision codegen( - definition, block, fail, jump, choiceBuffer, choiceDepth, module, - {SortCategory::Symbol, 0}, FailSubject, FailPattern, FailSort, nullptr); + decision codegen( + definition, block, fail, jump, choice_buffer, choice_depth, module, + {sort_category::Symbol, 0}, fail_subject, fail_pattern, fail_sort, + nullptr); codegen.store(std::make_pair(val->getName().str(), val->getType()), val); llvm::ReturnInst::Create(module->getContext(), stuck); codegen(dt); - makeMatchReasonFunctionWrapper(definition, module, axiom, name); + make_match_reason_function_wrapper(definition, module, axiom, name); } // TODO: actually collect the return value of this function. Right now it @@ -1248,21 +1268,22 @@ void makeMatchReasonFunction( // it, it should be safe, it will just leak memory. But we don't really care // that much about memory leaks in the compiler right now, so it's probably // fine. -KOREPattern *makePartialTerm( - KOREPattern *term, std::set const &occurrences, +kore_pattern *make_partial_term( + kore_pattern *term, std::set const &occurrences, std::string const &occurrence) { if (occurrences.contains(occurrence)) { - return KOREVariablePattern::Create(occurrence, term->getSort()).release(); + return kore_variable_pattern::create(occurrence, term->get_sort()) + .release(); } - if (auto *pat = dynamic_cast(term)) { - if (pat->getConstructor()->getName() == "\\dv") { + if (auto *pat = dynamic_cast(term)) { + if (pat->get_constructor()->get_name() == "\\dv") { return term; } - ptr result - = KORECompositePattern::Create(pat->getConstructor()); - for (unsigned i = 0; i < pat->getArguments().size(); i++) { - result->addArgument(ptr(makePartialTerm( - dynamic_cast(pat->getArguments()[i].get()), + ptr result + = kore_composite_pattern::create(pat->get_constructor()); + for (unsigned i = 0; i < pat->get_arguments().size(); i++) { + result->add_argument(ptr(make_partial_term( + dynamic_cast(pat->get_arguments()[i].get()), occurrences, "_" + std::to_string(i) + occurrence))); } return result.release(); @@ -1270,99 +1291,99 @@ KOREPattern *makePartialTerm( abort(); } -void makeStepFunction( - KOREAxiomDeclaration *axiom, KOREDefinition *definition, - llvm::Module *module, PartialStep res) { - auto *blockType = getValueType({SortCategory::Symbol, 0}, module); - std::vector argTypes; - std::vector debugTypes; +void make_step_function( + kore_axiom_declaration *axiom, kore_definition *definition, + llvm::Module *module, partial_step res) { + auto *block_type = getvalue_type({sort_category::Symbol, 0}, module); + std::vector arg_types; + std::vector debug_types; for (auto const &res : res.residuals) { - auto *argSort - = dynamic_cast(res.pattern->getSort().get()); - auto cat = argSort->getCategory(definition); - debugTypes.push_back(getDebugType(cat, ast_to_string(*argSort))); + auto *arg_sort + = dynamic_cast(res.pattern->get_sort().get()); + auto cat = arg_sort->get_category(definition); + debug_types.push_back(get_debug_type(cat, ast_to_string(*arg_sort))); switch (cat.cat) { - case SortCategory::Map: - case SortCategory::RangeMap: - case SortCategory::List: - case SortCategory::Set: - argTypes.push_back( - llvm::PointerType::getUnqual(getValueType(cat, module))); + case sort_category::Map: + case sort_category::RangeMap: + case sort_category::List: + case sort_category::Set: + arg_types.push_back( + llvm::PointerType::getUnqual(getvalue_type(cat, module))); break; - default: argTypes.push_back(getValueType(cat, module)); break; + default: arg_types.push_back(getvalue_type(cat, module)); break; } } - auto *blockDebugType - = getDebugType({SortCategory::Symbol, 0}, "SortGeneratedTopCell{}"); - llvm::FunctionType *funcType - = llvm::FunctionType::get(blockType, argTypes, false); - std::string name = "step_" + std::to_string(axiom->getOrdinal()); - llvm::Function *matchFunc = getOrInsertFunction(module, name, funcType); - resetDebugLoc(); - initDebugFunction( - name, name, getDebugFunctionType(blockDebugType, debugTypes), definition, - matchFunc); - matchFunc->setCallingConv(llvm::CallingConv::Tail); - - llvm::StringMap stuckSubst; + auto *block_debug_type + = get_debug_type({sort_category::Symbol, 0}, "SortGeneratedTopCell{}"); + llvm::FunctionType *func_type + = llvm::FunctionType::get(block_type, arg_types, false); + std::string name = "step_" + std::to_string(axiom->get_ordinal()); + llvm::Function *match_func = get_or_insert_function(module, name, func_type); + reset_debug_loc(); + init_debug_function( + name, name, get_debug_function_type(block_debug_type, debug_types), + definition, match_func); + match_func->setCallingConv(llvm::CallingConv::Tail); + + llvm::StringMap stuck_subst; llvm::BasicBlock *block - = llvm::BasicBlock::Create(module->getContext(), "entry", matchFunc); + = llvm::BasicBlock::Create(module->getContext(), "entry", match_func); llvm::BasicBlock *stuck - = llvm::BasicBlock::Create(module->getContext(), "stuck", matchFunc); + = llvm::BasicBlock::Create(module->getContext(), "stuck", match_func); llvm::BasicBlock *pre_stuck - = llvm::BasicBlock::Create(module->getContext(), "pre_stuck", matchFunc); + = llvm::BasicBlock::Create(module->getContext(), "pre_stuck", match_func); llvm::BasicBlock *fail - = llvm::BasicBlock::Create(module->getContext(), "fail", matchFunc); + = llvm::BasicBlock::Create(module->getContext(), "fail", match_func); - llvm::AllocaInst *choiceBuffer = nullptr; - llvm::AllocaInst *choiceDepth = nullptr; + llvm::AllocaInst *choice_buffer = nullptr; + llvm::AllocaInst *choice_depth = nullptr; llvm::IndirectBrInst *jump = nullptr; - initChoiceBuffer( - res.dt, module, block, pre_stuck, fail, &choiceBuffer, &choiceDepth, + init_choice_buffer( + res.dt, module, block, pre_stuck, fail, &choice_buffer, &choice_depth, &jump); llvm::BranchInst::Create(stuck, pre_stuck); std::vector phis; int i = 0; std::vector args; - std::vector types; - for (auto *val = matchFunc->arg_begin(); val != matchFunc->arg_end(); + std::vector types; + for (auto *val = match_func->arg_begin(); val != match_func->arg_end(); ++val, ++i) { args.push_back(val); auto *phi = llvm::PHINode::Create( val->getType(), 2, "phi" + res.residuals[i].occurrence, stuck); phi->addIncoming(val, block); phis.push_back(phi); - auto sort = res.residuals[i].pattern->getSort(); - auto cat = dynamic_cast(sort.get()) - ->getCategory(definition); + auto sort = res.residuals[i].pattern->get_sort(); + auto cat = dynamic_cast(sort.get()) + ->get_category(definition); types.push_back(cat); - initDebugParam( - matchFunc, i, "_" + std::to_string(i + 1), cat, ast_to_string(*sort)); + init_debug_param( + match_func, i, "_" + std::to_string(i + 1), cat, ast_to_string(*sort)); } - auto header = stepFunctionHeader( - axiom->getOrdinal(), module, definition, block, stuck, args, types); + auto header = step_function_header( + axiom->get_ordinal(), module, definition, block, stuck, args, types); i = 0; - Decision codegen( - definition, header.second, fail, jump, choiceBuffer, choiceDepth, module, - {SortCategory::Symbol, 0}, nullptr, nullptr, nullptr, nullptr); + decision codegen( + definition, header.second, fail, jump, choice_buffer, choice_depth, + module, {sort_category::Symbol, 0}, nullptr, nullptr, nullptr, nullptr); for (auto *val : header.first) { val->setName(res.residuals[i].occurrence.substr(0, max_name_length)); codegen.store(std::make_pair(val->getName().str(), val->getType()), val); - stuckSubst.insert({val->getName(), phis[i]}); + stuck_subst.insert({val->getName(), phis[i]}); phis[i++]->addIncoming(val, pre_stuck); } std::set occurrences; for (auto const &residual : res.residuals) { occurrences.insert(residual.occurrence); } - KOREPattern *partialTerm = makePartialTerm( - dynamic_cast(axiom->getRightHandSide()), occurrences, + kore_pattern *partial_term = make_partial_term( + dynamic_cast(axiom->get_right_hand_side()), occurrences, "_1"); - CreateTerm creator(stuckSubst, definition, stuck, module, false); - llvm::Value *retval = creator(partialTerm).first; + create_term creator(stuck_subst, definition, stuck, module, false); + llvm::Value *retval = creator(partial_term).first; llvm::ReturnInst::Create( - module->getContext(), retval, creator.getCurrentBlock()); + module->getContext(), retval, creator.get_current_block()); codegen(res.dt); } diff --git a/lib/codegen/DecisionParser.cpp b/lib/codegen/DecisionParser.cpp index 72cae9ee1..149692136 100644 --- a/lib/codegen/DecisionParser.cpp +++ b/lib/codegen/DecisionParser.cpp @@ -22,16 +22,16 @@ namespace kllvm { -class DTPreprocessor { +class dt_preprocessor { private: - std::map uniqueNodes{}; - std::map const &syms; - std::map> const &sorts; - KORESymbol *dv; - yaml_document_t *doc; - llvm::Module *mod; - - enum Kind { + std::map unique_nodes_{}; + std::map const &syms_; + std::map> const &sorts_; + kore_symbol *dv_; + yaml_document_t *doc_; + llvm::Module *mod_; + + enum kind { Switch, SwitchLiteral, CheckNull, @@ -43,7 +43,7 @@ class DTPreprocessor { Fail }; - Kind getKind(yaml_node_t *node) { + kind get_kind(yaml_node_t *node) { if (node->type == YAML_SCALAR_NODE) { return Fail; } @@ -79,16 +79,16 @@ class DTPreprocessor { yaml_node_pair_t *entry = nullptr; for (entry = node->data.mapping.pairs.start; entry < node->data.mapping.pairs.top; ++entry) { - yaml_node_t *key = yaml_document_get_node(doc, entry->key); + yaml_node_t *key = yaml_document_get_node(doc_, entry->key); if (name == (char *)key->data.scalar.value) { - return yaml_document_get_node(doc, entry->value); + return yaml_document_get_node(doc_, entry->value); } } return nullptr; } yaml_node_t *get(yaml_node_t *node, size_t off) { - return yaml_document_get_node(doc, node->data.sequence.items.start[off]); + return yaml_document_get_node(doc_, node->data.sequence.items.start[off]); } static std::string str(yaml_node_t *node) { @@ -100,20 +100,20 @@ class DTPreprocessor { yaml_node_item_t *entry = nullptr; for (entry = node->data.sequence.items.start; entry < node->data.sequence.items.top; ++entry) { - result.push_back(str(yaml_document_get_node(doc, *entry))); + result.push_back(str(yaml_document_get_node(doc_, *entry))); } return result; } - DTPreprocessor( - std::map const &syms, - std::map> const &sorts, + dt_preprocessor( + std::map const &syms, + std::map> const &sorts, llvm::Module *mod, yaml_document_t *doc) - : syms(syms) - , sorts(sorts) - , dv(KORESymbol::Create("\\dv").release()) - , doc(doc) - , mod(mod) { } + : syms_(syms) + , sorts_(sorts) + , dv_(kore_symbol::create("\\dv").release()) + , doc_(doc) + , mod_(mod) { } static std::string to_string(std::vector const &occurrence) { std::string result; @@ -124,37 +124,38 @@ class DTPreprocessor { return result; } - DecisionNode *function(yaml_node_t *node) { + decision_node *function(yaml_node_t *node) { std::string function = str(get(node, "function")); - std::string hookName = str(get(node, "sort")); - ValueType cat = KORECompositeSort::getCategory(hookName); + std::string hook_name = str(get(node, "sort")); + value_type cat = kore_composite_sort::get_category(hook_name); std::string binding = to_string(vec(get(node, "occurrence"))); auto *child = (*this)(get(node, "next")); - auto *result = FunctionNode::Create( - binding, function, child, cat, getParamType(cat, mod)); + auto *result = function_node::create( + binding, function, child, cat, get_param_type(cat, mod_)); yaml_node_t *vars = get(node, "args"); for (auto *iter = vars->data.sequence.items.start; iter < vars->data.sequence.items.top; ++iter) { - auto *var = yaml_document_get_node(doc, *iter); + auto *var = yaml_document_get_node(doc_, *iter); auto occurrence = vec(get(var, 0)); auto hook = str(get(var, 1)); if (occurrence.size() == 3 && occurrence[0] == "lit" && occurrence[2] == "MINT.MInt 64") { - result->addBinding( - occurrence[1], KORECompositeSort::getCategory(hook), mod); + result->add_binding( + occurrence[1], kore_composite_sort::get_category(hook), mod_); } else { - result->addBinding( - to_string(occurrence), KORECompositeSort::getCategory(hook), mod); + result->add_binding( + to_string(occurrence), kore_composite_sort::get_category(hook), + mod_); } } return result; } - ptr parsePattern( + ptr parse_pattern( yaml_node_t *node, std::vector> &uses) { if (auto *o = get(node, "occurrence")) { @@ -164,15 +165,16 @@ class DTPreprocessor { } else { name = str(o); } - ValueType hook = KORECompositeSort::getCategory(str(get(node, "hook"))); - uses.emplace_back(name, getParamType(hook, mod)); - return KOREVariablePattern::Create(name, sorts.at(hook)); + value_type hook + = kore_composite_sort::get_category(str(get(node, "hook"))); + uses.emplace_back(name, get_param_type(hook, mod_)); + return kore_variable_pattern::create(name, sorts_.at(hook)); } if (get(node, "literal")) { - auto sym = KORESymbol::Create("\\dv"); + auto sym = kore_symbol::create("\\dv"); auto hook = str(get(node, "hook")); - auto sort = sorts.at(KORECompositeSort::getCategory(hook)); + auto sort = sorts_.at(kore_composite_sort::get_category(hook)); auto *lit = get(node, "literal"); auto val = str(lit); if (hook == "BOOL.Bool") { @@ -182,10 +184,10 @@ class DTPreprocessor { val = base64_decode(val); } - sym->addFormalArgument(sort); - sym->addSort(sort); - auto pat = KORECompositePattern::Create(std::move(sym)); - pat->addArgument(KOREStringPattern::Create(val)); + sym->add_formal_argument(sort); + sym->add_sort(sort); + auto pat = kore_composite_pattern::create(std::move(sym)); + pat->add_argument(kore_string_pattern::create(val)); return pat; } @@ -194,181 +196,182 @@ class DTPreprocessor { abort(); } - auto *sym = syms.at(str(get(node, "constructor"))); - auto pat = KORECompositePattern::Create(sym); + auto *sym = syms_.at(str(get(node, "constructor"))); + auto pat = kore_composite_pattern::create(sym); auto *seq = get(node, "args"); for (auto *iter = seq->data.sequence.items.start; iter < seq->data.sequence.items.top; iter++) { - auto *child = yaml_document_get_node(doc, *iter); - pat->addArgument(parsePattern(child, uses)); + auto *child = yaml_document_get_node(doc_, *iter); + pat->add_argument(parse_pattern(child, uses)); } return pat; } - DecisionNode *makePattern(yaml_node_t *node) { + decision_node *make_pattern(yaml_node_t *node) { std::string name = to_string(vec(get(node, "occurrence"))); - llvm::Type *type = getParamType( - KORECompositeSort::getCategory(str(get(node, "sort"))), mod); + llvm::Type *type = get_param_type( + kore_composite_sort::get_category(str(get(node, "sort"))), mod_); std::vector> uses; - ptr pat = parsePattern(get(node, "pattern"), uses); + ptr pat = parse_pattern(get(node, "pattern"), uses); auto *child = (*this)(get(node, "next")); - return MakePatternNode::Create(name, type, pat.release(), uses, child); + return make_pattern_node::create(name, type, pat.release(), uses, child); } - DecisionNode *makeIterator(yaml_node_t *node) { + decision_node *make_iterator(yaml_node_t *node) { auto collection = to_string(vec(get(node, "collection"))); - auto *type = getParamType( - KORECompositeSort::getCategory(str(get(node, "sort"))), mod); - auto hookName = str(get(node, "function")); + auto *type = get_param_type( + kore_composite_sort::get_category(str(get(node, "sort"))), mod_); + auto hook_name = str(get(node, "function")); auto *child = (*this)(get(node, "next")); - return MakeIteratorNode::Create( + return make_iterator_node::create( collection, type, collection + "_iter", llvm::PointerType::getUnqual( - llvm::StructType::getTypeByName(mod->getContext(), "iter")), - hookName, child); + llvm::StructType::getTypeByName(mod_->getContext(), "iter")), + hook_name, child); } - DecisionNode *iterNext(yaml_node_t *node) { + decision_node *iter_next(yaml_node_t *node) { auto iterator = to_string(vec(get(node, "iterator"))) + "_iter"; auto binding = to_string(vec(get(node, "binding"))); - auto *type = getParamType( - KORECompositeSort::getCategory(str(get(node, "sort"))), mod); + auto *type = get_param_type( + kore_composite_sort::get_category(str(get(node, "sort"))), mod_); auto function = str(get(node, "function")); auto *child = (*this)(get(node, "next")); - return IterNextNode::Create( + return iter_next_node::create( iterator, llvm::PointerType::getUnqual( - llvm::StructType::getTypeByName(mod->getContext(), "iter")), + llvm::StructType::getTypeByName(mod_->getContext(), "iter")), binding, type, function, child); } - DecisionNode *switchCase(Kind kind, yaml_node_t *node) { + decision_node *switch_case(kind kind, yaml_node_t *node) { yaml_node_t *list = get(node, "specializations"); auto occurrence = vec(get(node, "occurrence")); std::string name = to_string(occurrence); - llvm::Type *type = getParamType( - KORECompositeSort::getCategory(str(get(node, "sort"))), mod); - auto *result = SwitchNode::Create(name, type, kind == CheckNull); + llvm::Type *type = get_param_type( + kore_composite_sort::get_category(str(get(node, "sort"))), mod_); + auto *result = switch_node::create(name, type, kind == CheckNull); for (auto *iter = list->data.sequence.items.start; iter < list->data.sequence.items.top; ++iter) { - auto *_case = yaml_document_get_node(doc, *iter); + auto *c = yaml_document_get_node(doc_, *iter); std::vector> bindings; - KORESymbol *symbol = nullptr; + kore_symbol *symbol = nullptr; if (kind == SwitchLiteral || kind == CheckNull) { - symbol = dv; + symbol = dv_; } else { - std::string symName = str(get(_case, 0)); - symbol = syms.at(symName); + std::string sym_name = str(get(c, 0)); + symbol = syms_.at(sym_name); if (!symbol) { - std::cerr << symName << std::endl; + std::cerr << sym_name << std::endl; abort(); } - for (unsigned i = 0; i < symbol->getArguments().size(); ++i) { - auto newOccurrence = occurrence; - newOccurrence.insert(newOccurrence.begin(), std::to_string(i)); - std::string binding = to_string(newOccurrence); - std::string hook = str(get(get(_case, 2), i)); + for (unsigned i = 0; i < symbol->get_arguments().size(); ++i) { + auto new_occurrence = occurrence; + new_occurrence.insert(new_occurrence.begin(), std::to_string(i)); + std::string binding = to_string(new_occurrence); + std::string hook = str(get(get(c, 2), i)); bindings.emplace_back( - binding, getParamType(KORECompositeSort::getCategory(hook), mod)); + binding, + get_param_type(kore_composite_sort::get_category(hook), mod_)); } } - DecisionNode *child = (*this)(get(_case, 1)); + decision_node *child = (*this)(get(c, 1)); switch (kind) { case SwitchLiteral: { unsigned bitwidth = stoi(str(get(node, "bitwidth"))); - result->addCase({symbol, {bitwidth, str(get(_case, 0)), 10}, child}); + result->add_case({symbol, {bitwidth, str(get(c, 0)), 10}, child}); break; } - case Switch: result->addCase({symbol, bindings, child}); break; + case Switch: result->add_case({symbol, bindings, child}); break; case CheckNull: - result->addCase({symbol, {1, str(get(_case, 0)), 10}, child}); + result->add_case({symbol, {1, str(get(c, 0)), 10}, child}); break; default: assert(false && "not reachable"); abort(); } } - auto *_case = get(node, "default"); - if (_case->type != YAML_SCALAR_NODE || !str(_case).empty()) { - DecisionNode *child = (*this)(_case); - result->addCase( + auto *c = get(node, "default"); + if (c->type != YAML_SCALAR_NODE || !str(c).empty()) { + decision_node *child = (*this)(c); + result->add_case( {nullptr, std::vector>{}, child}); } return result; } - DecisionNode *leaf(yaml_node_t *node) { + decision_node *leaf(yaml_node_t *node) { int action = stoi(str(get(get(node, "action"), 0))); std::string name = "apply_rule_" + std::to_string(action); if (auto *next = get(node, "next")) { name = name + "_search"; } - auto *result = LeafNode::Create(name); + auto *result = leaf_node::create(name); yaml_node_t *vars = get(get(node, "action"), 1); for (auto *iter = vars->data.sequence.items.start; iter < vars->data.sequence.items.top; ++iter) { - auto *var = yaml_document_get_node(doc, *iter); + auto *var = yaml_document_get_node(doc_, *iter); auto occurrence = vec(get(var, 0)); auto hook = str(get(var, 1)); - ValueType cat = KORECompositeSort::getCategory(hook); - result->addBinding(to_string(occurrence), cat, mod); + value_type cat = kore_composite_sort::get_category(hook); + result->add_binding(to_string(occurrence), cat, mod_); } if (auto *next = get(node, "next")) { auto *child = (*this)(next); - result->setChild(child); + result->set_child(child); } return result; } - DecisionNode *operator()(yaml_node_t *node) { - auto *unique = uniqueNodes[node]; + decision_node *operator()(yaml_node_t *node) { + auto *unique = unique_nodes_[node]; if (unique) { return unique; } - Kind kind = getKind(node); - DecisionNode *ret = nullptr; + kind kind = get_kind(node); + decision_node *ret = nullptr; switch (kind) { - case Fail: ret = FailNode::get(); break; + case Fail: ret = fail_node::get(); break; case Function: ret = function(node); break; - case MakePattern: ret = makePattern(node); break; + case MakePattern: ret = make_pattern(node); break; case SwitchLiteral: case Switch: - case CheckNull: ret = switchCase(kind, node); break; + case CheckNull: ret = switch_case(kind, node); break; case Leaf: ret = leaf(node); break; - case MakeIterator: ret = makeIterator(node); break; - case IterNext: ret = iterNext(node); break; + case MakeIterator: ret = make_iterator(node); break; + case IterNext: ret = iter_next(node); break; } - uniqueNodes[node] = ret; + unique_nodes_[node] = ret; return ret; } - PartialStep makeResiduals(yaml_node_t *residuals, DecisionNode *dt) { - std::vector res; + partial_step makeresiduals(yaml_node_t *residuals, decision_node *dt) { + std::vector res; for (auto *iter = residuals->data.sequence.items.start; iter < residuals->data.sequence.items.top; ++iter) { - Residual r; - yaml_node_t *listNode = yaml_document_get_node(doc, *iter); - r.occurrence = to_string(vec(get(listNode, 1))); + residual r; + yaml_node_t *list_node = yaml_document_get_node(doc_, *iter); + r.occurrence = to_string(vec(get(list_node, 1))); std::vector> uses; - r.pattern = parsePattern(get(listNode, 0), uses).release(); + r.pattern = parse_pattern(get(list_node, 0), uses).release(); res.push_back(r); } - PartialStep retval; + partial_step retval; retval.dt = dt; retval.residuals = res; return retval; } }; -DecisionNode *parseYamlDecisionTreeFromString( +decision_node *parse_yamldecision_tree_from_string( llvm::Module *mod, std::string const &yaml, - std::map const &syms, - std::map> const &sorts) { + std::map const &syms, + std::map> const &sorts) { yaml_parser_t parser; yaml_document_t doc; yaml_parser_initialize(&parser); @@ -380,16 +383,16 @@ DecisionNode *parseYamlDecisionTreeFromString( if (!root) { throw std::runtime_error("Failed to parse decision tree from YAML string"); } - auto *result = DTPreprocessor(syms, sorts, mod, &doc)(root); + auto *result = dt_preprocessor(syms, sorts, mod, &doc)(root); yaml_document_delete(&doc); yaml_parser_delete(&parser); return result; } -DecisionNode *parseYamlDecisionTree( +decision_node *parse_yamldecision_tree( llvm::Module *mod, std::string const &filename, - std::map const &syms, - std::map> const &sorts) { + std::map const &syms, + std::map> const &sorts) { yaml_parser_t parser; yaml_document_t doc; yaml_parser_initialize(&parser); @@ -401,17 +404,17 @@ DecisionNode *parseYamlDecisionTree( throw std::runtime_error( fmt::format("Failed to parse decision tree from file: {}", filename)); } - auto *result = DTPreprocessor(syms, sorts, mod, &doc)(root); + auto *result = dt_preprocessor(syms, sorts, mod, &doc)(root); yaml_document_delete(&doc); yaml_parser_delete(&parser); fclose(f); return result; } -PartialStep parseYamlSpecialDecisionTree( +partial_step parse_yaml_specialdecision_tree( llvm::Module *mod, std::string const &filename, - std::map const &syms, - std::map> const &sorts) { + std::map const &syms, + std::map> const &sorts) { yaml_parser_t parser; yaml_document_t doc; yaml_parser_initialize(&parser); @@ -423,9 +426,9 @@ PartialStep parseYamlSpecialDecisionTree( throw std::runtime_error(fmt::format( "Failed to parse special decision tree from file: {}", filename)); } - auto pp = DTPreprocessor(syms, sorts, mod, &doc); + auto pp = dt_preprocessor(syms, sorts, mod, &doc); auto *dt = pp(pp.get(root, 0)); - auto result = pp.makeResiduals(pp.get(root, 1), dt); + auto result = pp.makeresiduals(pp.get(root, 1), dt); yaml_document_delete(&doc); yaml_parser_delete(&parser); fclose(f); diff --git a/lib/codegen/EmitConfigParser.cpp b/lib/codegen/EmitConfigParser.cpp index 227b947e7..aff00accd 100644 --- a/lib/codegen/EmitConfigParser.cpp +++ b/lib/codegen/EmitConfigParser.cpp @@ -42,232 +42,237 @@ namespace kllvm { -static llvm::Constant *getSymbolNamePtr( - KORESymbol *symbol, llvm::BasicBlock *SetBlockName, llvm::Module *module) { - llvm::LLVMContext &Ctx = module->getContext(); +static llvm::Constant *get_symbol_name_ptr( + kore_symbol *symbol, llvm::BasicBlock *set_block_name, + llvm::Module *module) { + llvm::LLVMContext &ctx = module->getContext(); auto name = ast_to_string(*symbol); - if (SetBlockName) { - SetBlockName->setName(name); + if (set_block_name) { + set_block_name->setName(name); } - auto *Str = llvm::ConstantDataArray::getString(Ctx, name, true); + auto *str = llvm::ConstantDataArray::getString(ctx, name, true); auto *global = module->getOrInsertGlobal( - fmt::format("sym_name_{}", name), Str->getType()); - auto *globalVar = llvm::dyn_cast(global); - if (!globalVar->hasInitializer()) { - globalVar->setInitializer(Str); + fmt::format("sym_name_{}", name), str->getType()); + auto *global_var = llvm::dyn_cast(global); + if (!global_var->hasInitializer()) { + global_var->setInitializer(str); } - llvm::Constant *zero = llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), 0); + llvm::Constant *zero = llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx), 0); auto indices = std::vector{zero, zero}; - auto *Ptr = llvm::ConstantExpr::getInBoundsGetElementPtr( - Str->getType(), globalVar, indices); - return Ptr; + auto *ptr = llvm::ConstantExpr::getInBoundsGetElementPtr( + str->getType(), global_var, indices); + return ptr; } -static llvm::Function *getStrcmp(llvm::Module *module) { - llvm::LLVMContext &Ctx = module->getContext(); +static llvm::Function *get_strcmp(llvm::Module *module) { + llvm::LLVMContext &ctx = module->getContext(); auto *type = llvm::FunctionType::get( - llvm::Type::getInt32Ty(Ctx), - {llvm::Type::getInt8PtrTy(Ctx), llvm::Type::getInt8PtrTy(Ctx)}, false); - return getOrInsertFunction(module, "strcmp", type); + llvm::Type::getInt32Ty(ctx), + {llvm::Type::getInt8PtrTy(ctx), llvm::Type::getInt8PtrTy(ctx)}, false); + return get_or_insert_function(module, "strcmp", type); } -static void -emitGetTagForSymbolName(KOREDefinition *definition, llvm::Module *module) { - llvm::LLVMContext &Ctx = module->getContext(); +static void emit_get_tag_for_symbol_name( + kore_definition *definition, llvm::Module *module) { + llvm::LLVMContext &ctx = module->getContext(); auto *type = llvm::FunctionType::get( - llvm::Type::getInt32Ty(Ctx), {llvm::Type::getInt8PtrTy(Ctx)}, false); - auto *func = getOrInsertFunction(module, "getTagForSymbolNameInternal", type); - auto *CurrentBlock = llvm::BasicBlock::Create(Ctx, ""); - auto *MergeBlock = llvm::BasicBlock::Create(Ctx, "exit"); - auto *Phi = llvm::PHINode::Create( - llvm::Type::getInt32Ty(Ctx), definition->getSymbols().size(), "phi", - MergeBlock); - auto const &syms = definition->getAllSymbols(); - llvm::Function *Strcmp = getStrcmp(module); + llvm::Type::getInt32Ty(ctx), {llvm::Type::getInt8PtrTy(ctx)}, false); + auto *func = get_or_insert_function( + module, "get_tag_for_symbol_name_internal", type); + auto *current_block = llvm::BasicBlock::Create(ctx, ""); + auto *merge_block = llvm::BasicBlock::Create(ctx, "exit"); + auto *phi = llvm::PHINode::Create( + llvm::Type::getInt32Ty(ctx), definition->get_symbols().size(), "phi", + merge_block); + auto const &syms = definition->get_all_symbols(); + llvm::Function *strcmp = get_strcmp(module); for (auto const &entry : syms) { - uint32_t tag = entry.second->getTag(); + uint32_t tag = entry.second->get_tag(); auto *symbol = entry.second; - CurrentBlock->insertInto(func); - auto *Ptr = getSymbolNamePtr(symbol, CurrentBlock, module); + current_block->insertInto(func); + auto *ptr = get_symbol_name_ptr(symbol, current_block, module); auto *compare = llvm::CallInst::Create( - Strcmp, {func->arg_begin(), Ptr}, "", CurrentBlock); + strcmp, {func->arg_begin(), ptr}, "", current_block); auto *icmp = new llvm::ICmpInst( - *CurrentBlock, llvm::CmpInst::ICMP_EQ, compare, - llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 0)); - auto *FalseBlock = llvm::BasicBlock::Create(Ctx, ""); - llvm::BranchInst::Create(MergeBlock, FalseBlock, icmp, CurrentBlock); - Phi->addIncoming( - llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), tag), CurrentBlock); - CurrentBlock = FalseBlock; + *current_block, llvm::CmpInst::ICMP_EQ, compare, + llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx), 0)); + auto *false_block = llvm::BasicBlock::Create(ctx, ""); + llvm::BranchInst::Create(merge_block, false_block, icmp, current_block); + phi->addIncoming( + llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx), tag), + current_block); + current_block = false_block; } - Phi->addIncoming( - llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), ERROR_TAG), - CurrentBlock); - llvm::BranchInst::Create(MergeBlock, CurrentBlock); - CurrentBlock->insertInto(func); - llvm::ReturnInst::Create(Ctx, Phi, MergeBlock); - MergeBlock->insertInto(func); + phi->addIncoming( + llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx), ERROR_TAG), + current_block); + llvm::BranchInst::Create(merge_block, current_block); + current_block->insertInto(func); + llvm::ReturnInst::Create(ctx, phi, merge_block); + merge_block->insertInto(func); } -static std::string STRING_STRUCT = "string"; -static std::string LAYOUT_STRUCT = "layout"; -static std::string LAYOUTITEM_STRUCT = "layoutitem"; +static std::string string_struct = "string"; +static std::string layout_struct = "layout"; +static std::string layoutitem_struct = "layoutitem"; -static void emitDataTableForSymbol( +static void emit_data_table_for_symbol( std::string const &name, llvm::Type *ty, llvm::DIType *dity, - KOREDefinition *definition, llvm::Module *module, - llvm::Constant *getter(KOREDefinition *, llvm::Module *, KORESymbol *)) { - llvm::LLVMContext &Ctx = module->getContext(); - std::vector argTypes; - argTypes.push_back(llvm::Type::getInt32Ty(Ctx)); - auto *func = getOrInsertFunction( - module, name, llvm::FunctionType::get(ty, argTypes, false)); - initDebugFunction( - name, name, getDebugFunctionType(dity, {getIntDebugType()}), definition, - func); - auto *EntryBlock = llvm::BasicBlock::Create(Ctx, "entry", func); - auto *MergeBlock = llvm::BasicBlock::Create(Ctx, "exit"); - auto *stuck = llvm::BasicBlock::Create(Ctx, "stuck"); - auto const &syms = definition->getSymbols(); + kore_definition *definition, llvm::Module *module, + llvm::Constant *getter(kore_definition *, llvm::Module *, kore_symbol *)) { + llvm::LLVMContext &ctx = module->getContext(); + std::vector arg_types; + arg_types.push_back(llvm::Type::getInt32Ty(ctx)); + auto *func = get_or_insert_function( + module, name, llvm::FunctionType::get(ty, arg_types, false)); + init_debug_function( + name, name, get_debug_function_type(dity, {get_int_debug_type()}), + definition, func); + auto *entry_block = llvm::BasicBlock::Create(ctx, "entry", func); + auto *merge_block = llvm::BasicBlock::Create(ctx, "exit"); + auto *stuck = llvm::BasicBlock::Create(ctx, "stuck"); + auto const &syms = definition->get_symbols(); auto *icmp = new llvm::ICmpInst( - *EntryBlock, llvm::CmpInst::ICMP_ULE, func->arg_begin(), + *entry_block, llvm::CmpInst::ICMP_ULE, func->arg_begin(), llvm::ConstantInt::get( - llvm::Type::getInt32Ty(Ctx), syms.rbegin()->first)); - llvm::BranchInst::Create(MergeBlock, stuck, icmp, EntryBlock); - auto *tableType = llvm::ArrayType::get(ty, syms.size()); - auto *table = module->getOrInsertGlobal("table_" + name, tableType); - auto *globalVar = llvm::cast(table); - initDebugGlobal( + llvm::Type::getInt32Ty(ctx), syms.rbegin()->first)); + llvm::BranchInst::Create(merge_block, stuck, icmp, entry_block); + auto *table_type = llvm::ArrayType::get(ty, syms.size()); + auto *table = module->getOrInsertGlobal("table_" + name, table_type); + auto *global_var = llvm::cast(table); + init_debug_global( "table_" + name, - getArrayDebugType( + get_array_debug_type( dity, syms.size(), llvm::DataLayout(module).getABITypeAlign(ty)), - globalVar); + global_var); std::vector values; for (auto entry : syms) { auto *symbol = entry.second; auto *val = getter(definition, module, symbol); values.push_back(val); } - if (!globalVar->hasInitializer()) { - globalVar->setInitializer(llvm::ConstantArray::get(tableType, values)); + if (!global_var->hasInitializer()) { + global_var->setInitializer(llvm::ConstantArray::get(table_type, values)); } auto *offset = new llvm::ZExtInst( - func->arg_begin(), llvm::Type::getInt64Ty(Ctx), "", MergeBlock); - llvm::Constant *zero = llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), 0); + func->arg_begin(), llvm::Type::getInt64Ty(ctx), "", merge_block); + llvm::Constant *zero = llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx), 0); auto *retval = llvm::GetElementPtrInst::Create( - tableType, globalVar, {zero, offset}, "", MergeBlock); - MergeBlock->insertInto(func); - auto *load = new llvm::LoadInst(ty, retval, "", MergeBlock); - llvm::ReturnInst::Create(Ctx, load, MergeBlock); - addAbort(stuck, module); + table_type, global_var, {zero, offset}, "", merge_block); + merge_block->insertInto(func); + auto *load = new llvm::LoadInst(ty, retval, "", merge_block); + llvm::ReturnInst::Create(ctx, load, merge_block); + add_abort(stuck, module); stuck->insertInto(func); } -static void emitDataForSymbol( +static void emit_data_for_symbol( std::string const &name, llvm::Type *ty, llvm::DIType *dity, - KOREDefinition *definition, llvm::Module *module, bool isEval, + kore_definition *definition, llvm::Module *module, bool is_eval, std::pair getter( - KOREDefinition *, llvm::Module *, KORESymbol *, llvm::Instruction *)) { - llvm::LLVMContext &Ctx = module->getContext(); - std::vector argTypes; - argTypes.push_back(llvm::Type::getInt32Ty(Ctx)); - if (isEval) { + kore_definition *, llvm::Module *, kore_symbol *, + llvm::Instruction *)) { + llvm::LLVMContext &ctx = module->getContext(); + std::vector arg_types; + arg_types.push_back(llvm::Type::getInt32Ty(ctx)); + if (is_eval) { auto *ty = llvm::PointerType::getUnqual( - llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx), 0)); - argTypes.push_back(ty); + llvm::ArrayType::get(llvm::Type::getInt8PtrTy(ctx), 0)); + arg_types.push_back(ty); } - auto *func = getOrInsertFunction( - module, name, llvm::FunctionType::get(ty, argTypes, false)); - if (!isEval) { - initDebugFunction( - name, name, getDebugFunctionType(dity, {getIntDebugType()}), definition, - func); + auto *func = get_or_insert_function( + module, name, llvm::FunctionType::get(ty, arg_types, false)); + if (!is_eval) { + init_debug_function( + name, name, get_debug_function_type(dity, {get_int_debug_type()}), + definition, func); } - auto *EntryBlock = llvm::BasicBlock::Create(Ctx, "entry", func); - auto *MergeBlock = llvm::BasicBlock::Create(Ctx, "exit"); - auto *stuck = llvm::BasicBlock::Create(Ctx, "stuck"); - auto const &syms = definition->getSymbols(); - auto *Switch = llvm::SwitchInst::Create( - func->arg_begin(), stuck, syms.size(), EntryBlock); - auto *Phi = llvm::PHINode::Create( - ty, definition->getSymbols().size(), "phi", MergeBlock); + auto *entry_block = llvm::BasicBlock::Create(ctx, "entry", func); + auto *merge_block = llvm::BasicBlock::Create(ctx, "exit"); + auto *stuck = llvm::BasicBlock::Create(ctx, "stuck"); + auto const &syms = definition->get_symbols(); + auto *switch_inst = llvm::SwitchInst::Create( + func->arg_begin(), stuck, syms.size(), entry_block); + auto *phi = llvm::PHINode::Create( + ty, definition->get_symbols().size(), "phi", merge_block); for (auto entry : syms) { uint32_t tag = entry.first; auto *symbol = entry.second; - auto *decl = definition->getSymbolDeclarations().at(symbol->getName()); - bool isFunc = decl->attributes().contains(attribute_set::key::function) - || decl->attributes().contains(attribute_set::key::anywhere); - if (isEval && !isFunc) { + auto *decl = definition->get_symbol_declarations().at(symbol->get_name()); + bool is_func = decl->attributes().contains(attribute_set::key::Function) + || decl->attributes().contains(attribute_set::key::Anywhere); + if (is_eval && !is_func) { continue; } - auto *CaseBlock - = llvm::BasicBlock::Create(Ctx, "tag" + std::to_string(tag), func); - auto *Branch = llvm::BranchInst::Create(MergeBlock, CaseBlock); - auto pair = getter(definition, module, symbol, Branch); - Phi->addIncoming(pair.first, pair.second); - Switch->addCase( - llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), tag), CaseBlock); + auto *case_block + = llvm::BasicBlock::Create(ctx, "tag" + std::to_string(tag), func); + auto *branch = llvm::BranchInst::Create(merge_block, case_block); + auto pair = getter(definition, module, symbol, branch); + phi->addIncoming(pair.first, pair.second); + switch_inst->addCase( + llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx), tag), case_block); } - llvm::ReturnInst::Create(Ctx, Phi, MergeBlock); - MergeBlock->insertInto(func); - addAbort(stuck, module); + llvm::ReturnInst::Create(ctx, phi, merge_block); + merge_block->insertInto(func); + add_abort(stuck, module); stuck->insertInto(func); } -static std::pair getHeader( - KOREDefinition *definition, llvm::Module *module, KORESymbol *symbol, +static std::pair get_header( + kore_definition *definition, llvm::Module *module, kore_symbol *symbol, llvm::Instruction *inst) { - auto *BlockType = getBlockType(module, definition, symbol); + auto *block_type = get_block_type(module, definition, symbol); return std::make_pair( - getBlockHeader(module, definition, symbol, BlockType), inst->getParent()); + get_block_header(module, definition, symbol, block_type), + inst->getParent()); } static void -emitGetBlockHeaderForSymbol(KOREDefinition *def, llvm::Module *mod) { - emitDataForSymbol( - "getBlockHeaderForSymbol", - llvm::StructType::getTypeByName(mod->getContext(), BLOCKHEADER_STRUCT), - getForwardDecl(BLOCKHEADER_STRUCT), def, mod, false, getHeader); +emit_get_block_header_for_symbol(kore_definition *def, llvm::Module *mod) { + emit_data_for_symbol( + "get_block_header_for_symbol", + llvm::StructType::getTypeByName(mod->getContext(), blockheader_struct), + get_forward_decl(blockheader_struct), def, mod, false, get_header); } -static std::pair getFunction( - KOREDefinition *def, llvm::Module *mod, KORESymbol *symbol, +static std::pair get_function( + kore_definition *def, llvm::Module *mod, kore_symbol *symbol, llvm::Instruction *inst) { - auto *decl = def->getSymbolDeclarations().at(symbol->getName()); - bool res = decl->attributes().contains(attribute_set::key::function) - || decl->attributes().contains(attribute_set::key::anywhere); + auto *decl = def->get_symbol_declarations().at(symbol->get_name()); + bool res = decl->attributes().contains(attribute_set::key::Function) + || decl->attributes().contains(attribute_set::key::Anywhere); return std::make_pair( llvm::ConstantInt::get(llvm::Type::getInt1Ty(mod->getContext()), res), inst->getParent()); } -static void emitIsSymbolAFunction(KOREDefinition *def, llvm::Module *mod) { - emitDataForSymbol( - "isSymbolAFunction", llvm::Type::getInt1Ty(mod->getContext()), - getBoolDebugType(), def, mod, false, getFunction); +static void emit_is_symbol_a_function(kore_definition *def, llvm::Module *mod) { + emit_data_for_symbol( + "is_symbol_a_function", llvm::Type::getInt1Ty(mod->getContext()), + get_bool_debug_type(), def, mod, false, get_function); } static llvm::Constant * -getBinder(KOREDefinition *def, llvm::Module *mod, KORESymbol *symbol) { - auto *decl = def->getSymbolDeclarations().at(symbol->getName()); - bool res = decl->attributes().contains(attribute_set::key::binder); +get_binder(kore_definition *def, llvm::Module *mod, kore_symbol *symbol) { + auto *decl = def->get_symbol_declarations().at(symbol->get_name()); + bool res = decl->attributes().contains(attribute_set::key::Binder); return llvm::ConstantInt::get(llvm::Type::getInt1Ty(mod->getContext()), res); } -static void emitIsSymbolABinder(KOREDefinition *def, llvm::Module *mod) { - emitDataTableForSymbol( - "isSymbolABinder", llvm::Type::getInt1Ty(mod->getContext()), - getBoolDebugType(), def, mod, getBinder); +static void emit_is_symbol_a_binder(kore_definition *def, llvm::Module *mod) { + emit_data_table_for_symbol( + "is_symbol_a_binder", llvm::Type::getInt1Ty(mod->getContext()), + get_bool_debug_type(), def, mod, get_binder); } -static std::pair getInjection( - KOREDefinition *def, llvm::Module *mod, KORESymbol *symbol, +static std::pair get_injection( + kore_definition *def, llvm::Module *mod, kore_symbol *symbol, llvm::Instruction *inst) { llvm::Constant *tag = llvm::ConstantInt::get(llvm::Type::getInt32Ty(mod->getContext()), 0); - for (auto sym : def->getSymbols()) { - if (sym.second->getName() == "inj" - && *sym.second->getArguments()[0] == *symbol->getSort()) { + for (auto sym : def->get_symbols()) { + if (sym.second->get_name() == "inj" + && *sym.second->get_arguments()[0] == *symbol->get_sort()) { tag = llvm::ConstantInt::get( llvm::Type::getInt32Ty(mod->getContext()), sym.first); break; @@ -277,821 +282,839 @@ static std::pair getInjection( } static void -emitGetInjectionForSortOfTag(KOREDefinition *def, llvm::Module *mod) { - emitDataForSymbol( - "getInjectionForSortOfTag", llvm::Type::getInt32Ty(mod->getContext()), - getIntDebugType(), def, mod, false, getInjection); +emit_get_injection_for_sort_of_tag(kore_definition *def, llvm::Module *mod) { + emit_data_for_symbol( + "get_injection_for_sort_of_tag", + llvm::Type::getInt32Ty(mod->getContext()), get_int_debug_type(), def, mod, + false, get_injection); } static llvm::Constant * -getArity(KOREDefinition *, llvm::Module *mod, KORESymbol *symbol) { +get_arity(kore_definition *, llvm::Module *mod, kore_symbol *symbol) { return llvm::ConstantInt::get( - llvm::Type::getInt32Ty(mod->getContext()), symbol->getArguments().size()); + llvm::Type::getInt32Ty(mod->getContext()), + symbol->get_arguments().size()); } -static void emitGetSymbolArity(KOREDefinition *def, llvm::Module *mod) { - emitDataTableForSymbol( - "getSymbolArity", llvm::Type::getInt32Ty(mod->getContext()), - getIntDebugType(), def, mod, getArity); +static void emit_get_symbol_arity(kore_definition *def, llvm::Module *mod) { + emit_data_table_for_symbol( + "get_symbol_arity", llvm::Type::getInt32Ty(mod->getContext()), + get_int_debug_type(), def, mod, get_arity); } -static llvm::Value *getArgValue( - llvm::Value *ArgumentsArray, int idx, llvm::BasicBlock *CaseBlock, - ValueType cat, llvm::Module *mod) { - llvm::LLVMContext &Ctx = mod->getContext(); - llvm::Constant *zero = llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), 0); +static llvm::Value *get_arg_value( + llvm::Value *arguments_array, int idx, llvm::BasicBlock *case_block, + value_type cat, llvm::Module *mod) { + llvm::LLVMContext &ctx = mod->getContext(); + llvm::Constant *zero = llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx), 0); - auto *i8_ptr_ty = llvm::Type::getInt8PtrTy(Ctx); + auto *i8_ptr_ty = llvm::Type::getInt8PtrTy(ctx); auto *addr = llvm::GetElementPtrInst::Create( - llvm::ArrayType::get(i8_ptr_ty, 0), ArgumentsArray, - {zero, llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), idx)}, "", - CaseBlock); - llvm::Value *arg = new llvm::LoadInst(i8_ptr_ty, addr, "", CaseBlock); + llvm::ArrayType::get(i8_ptr_ty, 0), arguments_array, + {zero, llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx), idx)}, "", + case_block); + llvm::Value *arg = new llvm::LoadInst(i8_ptr_ty, addr, "", case_block); switch (cat.cat) { - case SortCategory::Bool: - case SortCategory::MInt: { - auto *val_ty = getValueType(cat, mod); + case sort_category::Bool: + case sort_category::MInt: { + auto *val_ty = getvalue_type(cat, mod); auto *cast = new llvm::BitCastInst( - arg, llvm::PointerType::getUnqual(val_ty), "", CaseBlock); - auto *load = new llvm::LoadInst(val_ty, cast, "", CaseBlock); + arg, llvm::PointerType::getUnqual(val_ty), "", case_block); + auto *load = new llvm::LoadInst(val_ty, cast, "", case_block); arg = load; break; } - case SortCategory::Map: - case SortCategory::RangeMap: - case SortCategory::List: - case SortCategory::Set: + case sort_category::Map: + case sort_category::RangeMap: + case sort_category::List: + case sort_category::Set: arg = new llvm::BitCastInst( - arg, llvm::PointerType::getUnqual(getValueType(cat, mod)), "", - CaseBlock); + arg, llvm::PointerType::getUnqual(getvalue_type(cat, mod)), "", + case_block); break; - case SortCategory::Int: - case SortCategory::Float: - case SortCategory::StringBuffer: - case SortCategory::Symbol: - case SortCategory::Variable: - arg = new llvm::BitCastInst(arg, getValueType(cat, mod), "", CaseBlock); + case sort_category::Int: + case sort_category::Float: + case sort_category::StringBuffer: + case sort_category::Symbol: + case sort_category::Variable: + arg = new llvm::BitCastInst(arg, getvalue_type(cat, mod), "", case_block); break; - case SortCategory::Uncomputed: abort(); + case sort_category::Uncomputed: abort(); } return arg; } -static std::pair getEval( - KOREDefinition *def, llvm::Module *mod, KORESymbol *symbol, +static std::pair get_eval( + kore_definition *def, llvm::Module *mod, kore_symbol *symbol, llvm::Instruction *inst) { - llvm::LLVMContext &Ctx = mod->getContext(); - llvm::BasicBlock *CaseBlock = inst->getParent(); + llvm::LLVMContext &ctx = mod->getContext(); + llvm::BasicBlock *case_block = inst->getParent(); inst->removeFromParent(); - llvm::Function *func = CaseBlock->getParent(); - llvm::Value *ArgumentsArray = func->arg_begin() + 1; + llvm::Function *func = case_block->getParent(); + llvm::Value *arguments_array = func->arg_begin() + 1; int idx = 0; llvm::StringMap subst; - auto pattern = KORECompositePattern::Create(symbol); - for (auto const &sort : symbol->getArguments()) { - ValueType cat - = dynamic_cast(sort.get())->getCategory(def); - llvm::Value *arg = getArgValue(ArgumentsArray, idx, CaseBlock, cat, mod); + auto pattern = kore_composite_pattern::create(symbol); + for (auto const &sort : symbol->get_arguments()) { + value_type cat + = dynamic_cast(sort.get())->get_category(def); + llvm::Value *arg + = get_arg_value(arguments_array, idx, case_block, cat, mod); std::string name = "_" + std::to_string(idx++); subst.insert({name, arg}); - pattern->addArgument(KOREVariablePattern::Create(name, sort)); + pattern->add_argument(kore_variable_pattern::create(name, sort)); } - CreateTerm creator(subst, def, CaseBlock, mod, false); + create_term creator(subst, def, case_block, mod, false); llvm::Value *result = creator(pattern.get()).first; llvm::Value *retval = nullptr; - ValueType cat = dynamic_cast(symbol->getSort().get()) - ->getCategory(def); + value_type cat = dynamic_cast(symbol->get_sort().get()) + ->get_category(def); switch (cat.cat) { - case SortCategory::Int: - case SortCategory::Float: - case SortCategory::StringBuffer: - case SortCategory::Symbol: - case SortCategory::Variable: - case SortCategory::Map: - case SortCategory::RangeMap: - case SortCategory::List: - case SortCategory::Set: + case sort_category::Int: + case sort_category::Float: + case sort_category::StringBuffer: + case sort_category::Symbol: + case sort_category::Variable: + case sort_category::Map: + case sort_category::RangeMap: + case sort_category::List: + case sort_category::Set: retval = new llvm::BitCastInst( - result, llvm::Type::getInt8PtrTy(Ctx), "", creator.getCurrentBlock()); + result, llvm::Type::getInt8PtrTy(ctx), "", creator.get_current_block()); break; - case SortCategory::Bool: - case SortCategory::MInt: { - llvm::Instruction *Malloc = llvm::CallInst::CreateMalloc( - creator.getCurrentBlock(), llvm::Type::getInt64Ty(Ctx), + case sort_category::Bool: + case sort_category::MInt: { + llvm::Instruction *malloc = llvm::CallInst::CreateMalloc( + creator.get_current_block(), llvm::Type::getInt64Ty(ctx), result->getType(), llvm::ConstantExpr::getSizeOf(result->getType()), nullptr, nullptr); - Malloc->insertAfter(&creator.getCurrentBlock()->back()); - new llvm::StoreInst(result, Malloc, creator.getCurrentBlock()); + malloc->insertAfter(&creator.get_current_block()->back()); + new llvm::StoreInst(result, malloc, creator.get_current_block()); retval = new llvm::BitCastInst( - Malloc, llvm::Type::getInt8PtrTy(Ctx), "", creator.getCurrentBlock()); + malloc, llvm::Type::getInt8PtrTy(ctx), "", creator.get_current_block()); break; } - case SortCategory::Uncomputed: abort(); + case sort_category::Uncomputed: abort(); } - inst->insertAfter(&creator.getCurrentBlock()->back()); - return std::make_pair(retval, creator.getCurrentBlock()); + inst->insertAfter(&creator.get_current_block()->back()); + return std::make_pair(retval, creator.get_current_block()); } -static void emitEvaluateFunctionSymbol(KOREDefinition *def, llvm::Module *mod) { - emitDataForSymbol( - "evaluateFunctionSymbol", llvm::Type::getInt8PtrTy(mod->getContext()), - nullptr, def, mod, true, getEval); +static void +emit_evaluate_function_symbol(kore_definition *def, llvm::Module *mod) { + emit_data_for_symbol( + "evaluate_function_symbol", llvm::Type::getInt8PtrTy(mod->getContext()), + nullptr, def, mod, true, get_eval); } static void -emitGetTagForFreshSort(KOREDefinition *definition, llvm::Module *module) { - llvm::LLVMContext &Ctx = module->getContext(); - auto *func = getOrInsertFunction( - module, "getTagForFreshSort", llvm::Type::getInt32Ty(Ctx), - llvm::Type::getInt8PtrTy(Ctx)); - auto *CurrentBlock = llvm::BasicBlock::Create(Ctx, ""); - auto *MergeBlock = llvm::BasicBlock::Create(Ctx, "exit"); - auto *Phi = llvm::PHINode::Create( - llvm::Type::getInt32Ty(Ctx), definition->getSortDeclarations().size(), - "phi", MergeBlock); - auto const &sorts = definition->getSortDeclarations(); - llvm::Function *Strcmp = getStrcmp(module); - llvm::Constant *zero = llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), 0); +emit_get_tag_for_fresh_sort(kore_definition *definition, llvm::Module *module) { + llvm::LLVMContext &ctx = module->getContext(); + auto *func = get_or_insert_function( + module, "get_tag_for_fresh_sort", llvm::Type::getInt32Ty(ctx), + llvm::Type::getInt8PtrTy(ctx)); + auto *current_block = llvm::BasicBlock::Create(ctx, ""); + auto *merge_block = llvm::BasicBlock::Create(ctx, "exit"); + auto *phi = llvm::PHINode::Create( + llvm::Type::getInt32Ty(ctx), definition->get_sort_declarations().size(), + "phi", merge_block); + auto const &sorts = definition->get_sort_declarations(); + llvm::Function *strcmp = get_strcmp(module); + llvm::Constant *zero = llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx), 0); llvm::Constant *zero32 - = llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 0); - bool hasCase = false; + = llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx), 0); + bool has_case = false; for (auto const &entry : sorts) { std::string name = entry.first; - if (!definition->getFreshFunctions().contains(name)) { + if (!definition->get_fresh_functions().contains(name)) { continue; } - hasCase = true; - CurrentBlock->insertInto(func); - CurrentBlock->setName("is_" + name); - auto *Str = llvm::ConstantDataArray::getString(Ctx, name, true); + has_case = true; + current_block->insertInto(func); + current_block->setName("is_" + name); + auto *str = llvm::ConstantDataArray::getString(ctx, name, true); auto *global - = module->getOrInsertGlobal("sort_name_" + name, Str->getType()); - auto *globalVar = llvm::cast(global); - if (!globalVar->hasInitializer()) { - globalVar->setInitializer(Str); + = module->getOrInsertGlobal("sort_name_" + name, str->getType()); + auto *global_var = llvm::cast(global); + if (!global_var->hasInitializer()) { + global_var->setInitializer(str); } auto indices = std::vector{zero, zero}; - auto *Ptr = llvm::ConstantExpr::getInBoundsGetElementPtr( - Str->getType(), globalVar, indices); + auto *ptr = llvm::ConstantExpr::getInBoundsGetElementPtr( + str->getType(), global_var, indices); auto *compare = llvm::CallInst::Create( - Strcmp, {func->arg_begin(), Ptr}, "", CurrentBlock); + strcmp, {func->arg_begin(), ptr}, "", current_block); auto *icmp = new llvm::ICmpInst( - *CurrentBlock, llvm::CmpInst::ICMP_EQ, compare, zero32); - auto *FalseBlock = llvm::BasicBlock::Create(Ctx, ""); - auto *CaseBlock = llvm::BasicBlock::Create(Ctx, name, func); - llvm::BranchInst::Create(CaseBlock, FalseBlock, icmp, CurrentBlock); - auto *symbol = definition->getFreshFunctions().at(name); - Phi->addIncoming( + *current_block, llvm::CmpInst::ICMP_EQ, compare, zero32); + auto *false_block = llvm::BasicBlock::Create(ctx, ""); + auto *case_block = llvm::BasicBlock::Create(ctx, name, func); + llvm::BranchInst::Create(case_block, false_block, icmp, current_block); + auto *symbol = definition->get_fresh_functions().at(name); + phi->addIncoming( llvm::ConstantInt::get( - llvm::Type::getInt32Ty(Ctx), - definition->getAllSymbols().at(ast_to_string(*symbol))->getTag()), - CaseBlock); - llvm::BranchInst::Create(MergeBlock, CaseBlock); - CurrentBlock = FalseBlock; + llvm::Type::getInt32Ty(ctx), definition->get_all_symbols() + .at(ast_to_string(*symbol)) + ->get_tag()), + case_block); + llvm::BranchInst::Create(merge_block, case_block); + current_block = false_block; } - CurrentBlock->insertInto(func); - addAbort(CurrentBlock, module); - if (hasCase) { - llvm::ReturnInst::Create(Ctx, Phi, MergeBlock); - MergeBlock->insertInto(func); + current_block->insertInto(func); + add_abort(current_block, module); + if (has_case) { + llvm::ReturnInst::Create(ctx, phi, merge_block); + merge_block->insertInto(func); } } -static void emitGetToken(KOREDefinition *definition, llvm::Module *module) { - llvm::LLVMContext &Ctx = module->getContext(); - auto *getTokenType = llvm::FunctionType::get( - llvm::Type::getInt8PtrTy(Ctx), - {llvm::Type::getInt8PtrTy(Ctx), llvm::Type::getInt64Ty(Ctx), - llvm::Type::getInt8PtrTy(Ctx)}, +static void emit_get_token(kore_definition *definition, llvm::Module *module) { + llvm::LLVMContext &ctx = module->getContext(); + auto *get_token_type = llvm::FunctionType::get( + llvm::Type::getInt8PtrTy(ctx), + {llvm::Type::getInt8PtrTy(ctx), llvm::Type::getInt64Ty(ctx), + llvm::Type::getInt8PtrTy(ctx)}, false); - auto *func = getOrInsertFunction(module, "getToken", getTokenType); - auto *CurrentBlock = llvm::BasicBlock::Create(Ctx, ""); - auto *MergeBlock = llvm::BasicBlock::Create(Ctx, "exit"); - auto *Phi = llvm::PHINode::Create( - llvm::Type::getInt8PtrTy(Ctx), definition->getSortDeclarations().size(), - "phi", MergeBlock); - auto const &sorts = definition->getSortDeclarations(); - llvm::Function *Strcmp = getStrcmp(module); - llvm::Function *StringEqual = getOrInsertFunction( - module, "string_equal", llvm::Type::getInt1Ty(Ctx), - llvm::Type::getInt8PtrTy(Ctx), llvm::Type::getInt8PtrTy(Ctx), - llvm::Type::getInt64Ty(Ctx), llvm::Type::getInt64Ty(Ctx)); - llvm::Constant *zero = llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), 0); + auto *func = get_or_insert_function(module, "get_token", get_token_type); + auto *current_block = llvm::BasicBlock::Create(ctx, ""); + auto *merge_block = llvm::BasicBlock::Create(ctx, "exit"); + auto *phi = llvm::PHINode::Create( + llvm::Type::getInt8PtrTy(ctx), definition->get_sort_declarations().size(), + "phi", merge_block); + auto const &sorts = definition->get_sort_declarations(); + llvm::Function *strcmp = get_strcmp(module); + llvm::Function *string_equal = get_or_insert_function( + module, "string_equal", llvm::Type::getInt1Ty(ctx), + llvm::Type::getInt8PtrTy(ctx), llvm::Type::getInt8PtrTy(ctx), + llvm::Type::getInt64Ty(ctx), llvm::Type::getInt64Ty(ctx)); + llvm::Constant *zero = llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx), 0); llvm::Constant *zero32 - = llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 0); + = llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx), 0); for (auto const &entry : sorts) { std::string name = entry.first; - if (!entry.second->getObjectSortVariables().empty()) { + if (!entry.second->get_object_sort_variables().empty()) { // TODO: MINT in initial configuration continue; } - auto sort = KORECompositeSort::Create(name); - ValueType cat = sort->getCategory(definition); - if (cat.cat == SortCategory::Symbol || cat.cat == SortCategory::Variable) { + auto sort = kore_composite_sort::create(name); + value_type cat = sort->get_category(definition); + if (cat.cat == sort_category::Symbol + || cat.cat == sort_category::Variable) { continue; } - CurrentBlock->insertInto(func); - CurrentBlock->setName("is_" + name); - auto *Str = llvm::ConstantDataArray::getString(Ctx, name, true); + current_block->insertInto(func); + current_block->setName("is_" + name); + auto *str = llvm::ConstantDataArray::getString(ctx, name, true); auto *global - = module->getOrInsertGlobal("sort_name_" + name, Str->getType()); - auto *globalVar = llvm::dyn_cast(global); - if (!globalVar->hasInitializer()) { - globalVar->setInitializer(Str); + = module->getOrInsertGlobal("sort_name_" + name, str->getType()); + auto *global_var = llvm::dyn_cast(global); + if (!global_var->hasInitializer()) { + global_var->setInitializer(str); } auto indices = std::vector{zero, zero}; - auto *Ptr = llvm::ConstantExpr::getInBoundsGetElementPtr( - Str->getType(), globalVar, indices); + auto *ptr = llvm::ConstantExpr::getInBoundsGetElementPtr( + str->getType(), global_var, indices); auto *compare = llvm::CallInst::Create( - Strcmp, {func->arg_begin(), Ptr}, "", CurrentBlock); + strcmp, {func->arg_begin(), ptr}, "", current_block); auto *icmp = new llvm::ICmpInst( - *CurrentBlock, llvm::CmpInst::ICMP_EQ, compare, zero32); - auto *FalseBlock = llvm::BasicBlock::Create(Ctx, ""); - auto *CaseBlock = llvm::BasicBlock::Create(Ctx, name, func); - llvm::BranchInst::Create(CaseBlock, FalseBlock, icmp, CurrentBlock); + *current_block, llvm::CmpInst::ICMP_EQ, compare, zero32); + auto *false_block = llvm::BasicBlock::Create(ctx, ""); + auto *case_block = llvm::BasicBlock::Create(ctx, name, func); + llvm::BranchInst::Create(case_block, false_block, icmp, current_block); switch (cat.cat) { - case SortCategory::Map: - case SortCategory::RangeMap: - case SortCategory::List: - case SortCategory::Set: - case SortCategory::StringBuffer: - case SortCategory::MInt: + case sort_category::Map: + case sort_category::RangeMap: + case sort_category::List: + case sort_category::Set: + case sort_category::StringBuffer: + case sort_category::MInt: // TODO: tokens - addAbort(CaseBlock, module); + add_abort(case_block, module); break; - case SortCategory::Bool: { - auto *Str = llvm::ConstantDataArray::getString(Ctx, "true", false); - auto *global = module->getOrInsertGlobal("bool_true", Str->getType()); - auto *globalVar = llvm::dyn_cast(global); - if (!globalVar->hasInitializer()) { - globalVar->setInitializer(Str); + case sort_category::Bool: { + auto *str = llvm::ConstantDataArray::getString(ctx, "true", false); + auto *global = module->getOrInsertGlobal("bool_true", str->getType()); + auto *global_var = llvm::dyn_cast(global); + if (!global_var->hasInitializer()) { + global_var->setInitializer(str); } - auto *Ptr = llvm::ConstantExpr::getInBoundsGetElementPtr( - Str->getType(), globalVar, indices); - auto *Len = llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), 4); + auto *ptr = llvm::ConstantExpr::getInBoundsGetElementPtr( + str->getType(), global_var, indices); + auto *len = llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx), 4); auto *compare = llvm::CallInst::Create( - StringEqual, {func->arg_begin() + 2, Ptr, func->arg_begin() + 1, Len}, - "", CaseBlock); - llvm::Instruction *Malloc = llvm::CallInst::CreateMalloc( - CaseBlock, llvm::Type::getInt64Ty(Ctx), compare->getType(), + string_equal, + {func->arg_begin() + 2, ptr, func->arg_begin() + 1, len}, "", + case_block); + llvm::Instruction *malloc = llvm::CallInst::CreateMalloc( + case_block, llvm::Type::getInt64Ty(ctx), compare->getType(), llvm::ConstantExpr::getSizeOf(compare->getType()), nullptr, nullptr); - Malloc->insertAfter(&CaseBlock->back()); - new llvm::StoreInst(compare, Malloc, CaseBlock); + malloc->insertAfter(&case_block->back()); + new llvm::StoreInst(compare, malloc, case_block); auto *result = new llvm::BitCastInst( - Malloc, llvm::Type::getInt8PtrTy(Ctx), "", CaseBlock); - Phi->addIncoming(result, CaseBlock); - llvm::BranchInst::Create(MergeBlock, CaseBlock); + malloc, llvm::Type::getInt8PtrTy(ctx), "", case_block); + phi->addIncoming(result, case_block); + llvm::BranchInst::Create(merge_block, case_block); break; } - case SortCategory::Float: { - llvm::Type *Float - = llvm::StructType::getTypeByName(module->getContext(), FLOAT_STRUCT); - llvm::Value *Term = allocateTerm(Float, CaseBlock, "koreAllocFloating"); - llvm::Function *InitFloat = getOrInsertFunction( - module, "init_float", llvm::Type::getVoidTy(Ctx), - llvm::PointerType::getUnqual(Float), llvm::Type::getInt8PtrTy(Ctx)); + case sort_category::Float: { + llvm::Type *float_ty + = llvm::StructType::getTypeByName(module->getContext(), float_struct); + llvm::Value *term + = allocate_term(float_ty, case_block, "kore_alloc_floating"); + llvm::Function *init_float = get_or_insert_function( + module, "init_float", llvm::Type::getVoidTy(ctx), + llvm::PointerType::getUnqual(float_ty), + llvm::Type::getInt8PtrTy(ctx)); llvm::CallInst::Create( - InitFloat, {Term, func->arg_begin() + 2}, "", CaseBlock); + init_float, {term, func->arg_begin() + 2}, "", case_block); auto *cast = new llvm::BitCastInst( - Term, llvm::Type::getInt8PtrTy(Ctx), "", CaseBlock); - Phi->addIncoming(cast, CaseBlock); - llvm::BranchInst::Create(MergeBlock, CaseBlock); + term, llvm::Type::getInt8PtrTy(ctx), "", case_block); + phi->addIncoming(cast, case_block); + llvm::BranchInst::Create(merge_block, case_block); break; } - case SortCategory::Int: { - auto const &thirdArg = func->arg_begin() + 2; - llvm::Value *FirstChar = new llvm::LoadInst( - llvm::Type::getInt8Ty(Ctx), thirdArg, "", CaseBlock); - llvm::Constant *asciiPlus - = llvm::ConstantInt::get(llvm::Type::getInt8Ty(Ctx), 43); - auto *icmpFirst = new llvm::ICmpInst( - *CaseBlock, llvm::CmpInst::ICMP_EQ, FirstChar, asciiPlus); - auto *IfIsPlus = llvm::BasicBlock::Create(Ctx, "if_is_plus", func); - auto *ElseNoPlus = llvm::BasicBlock::Create(Ctx, "else_no_plus", func); - llvm::BranchInst::Create(IfIsPlus, ElseNoPlus, icmpFirst, CaseBlock); + case sort_category::Int: { + auto const &third_arg = func->arg_begin() + 2; + llvm::Value *first_char = new llvm::LoadInst( + llvm::Type::getInt8Ty(ctx), third_arg, "", case_block); + llvm::Constant *ascii_plus + = llvm::ConstantInt::get(llvm::Type::getInt8Ty(ctx), 43); + auto *icmp_first = new llvm::ICmpInst( + *case_block, llvm::CmpInst::ICMP_EQ, first_char, ascii_plus); + auto *if_is_plus = llvm::BasicBlock::Create(ctx, "if_is_plus", func); + auto *else_no_plus = llvm::BasicBlock::Create(ctx, "else_no_plus", func); + llvm::BranchInst::Create( + if_is_plus, else_no_plus, icmp_first, case_block); llvm::Constant *one - = llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1); - llvm::Value *Pruned = llvm::GetElementPtrInst::CreateInBounds( - llvm::Type::getInt8Ty(Ctx), func->arg_begin() + 2, {one}, "", - IfIsPlus); - llvm::BranchInst::Create(ElseNoPlus, IfIsPlus); - auto *phiStr = llvm::PHINode::Create( - llvm::Type::getInt8PtrTy(Ctx), 2, "", ElseNoPlus); - phiStr->addIncoming(func->arg_begin() + 2, CaseBlock); - phiStr->addIncoming(Pruned, IfIsPlus); - CaseBlock = ElseNoPlus; - llvm::Type *Int - = llvm::StructType::getTypeByName(module->getContext(), INT_STRUCT); - llvm::Value *Term = allocateTerm(Int, CaseBlock, "koreAllocInteger"); - llvm::Function *MpzInitSet = getOrInsertFunction( - module, "__gmpz_init_set_str", llvm::Type::getInt32Ty(Ctx), - llvm::PointerType::getUnqual(Int), llvm::Type::getInt8PtrTy(Ctx), - llvm::Type::getInt32Ty(Ctx)); - auto *Call = llvm::CallInst::Create( - MpzInitSet, - {Term, phiStr, - llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 10)}, - "", CaseBlock); + = llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx), 1); + llvm::Value *pruned = llvm::GetElementPtrInst::CreateInBounds( + llvm::Type::getInt8Ty(ctx), func->arg_begin() + 2, {one}, "", + if_is_plus); + llvm::BranchInst::Create(else_no_plus, if_is_plus); + auto *phi_str = llvm::PHINode::Create( + llvm::Type::getInt8PtrTy(ctx), 2, "", else_no_plus); + phi_str->addIncoming(func->arg_begin() + 2, case_block); + phi_str->addIncoming(pruned, if_is_plus); + case_block = else_no_plus; + llvm::Type *int_ty + = llvm::StructType::getTypeByName(module->getContext(), int_struct); + llvm::Value *term + = allocate_term(int_ty, case_block, "kore_alloc_integer"); + llvm::Function *mpz_init_set = get_or_insert_function( + module, "__gmpz_init_set_str", llvm::Type::getInt32Ty(ctx), + llvm::PointerType::getUnqual(int_ty), llvm::Type::getInt8PtrTy(ctx), + llvm::Type::getInt32Ty(ctx)); + auto *call = llvm::CallInst::Create( + mpz_init_set, + {term, phi_str, + llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx), 10)}, + "", case_block); auto *icmp = new llvm::ICmpInst( - *CaseBlock, llvm::CmpInst::ICMP_EQ, Call, zero32); - auto *AbortBlock = llvm::BasicBlock::Create(Ctx, "invalid_int", func); - addAbort(AbortBlock, module); + *case_block, llvm::CmpInst::ICMP_EQ, call, zero32); + auto *abort_block = llvm::BasicBlock::Create(ctx, "invalid_int", func); + add_abort(abort_block, module); auto *cast = new llvm::BitCastInst( - Term, llvm::Type::getInt8PtrTy(Ctx), "", CaseBlock); - llvm::BranchInst::Create(MergeBlock, AbortBlock, icmp, CaseBlock); - Phi->addIncoming(cast, CaseBlock); + term, llvm::Type::getInt8PtrTy(ctx), "", case_block); + llvm::BranchInst::Create(merge_block, abort_block, icmp, case_block); + phi->addIncoming(cast, case_block); break; } - case SortCategory::Variable: - case SortCategory::Symbol: break; - case SortCategory::Uncomputed: abort(); + case sort_category::Variable: + case sort_category::Symbol: break; + case sort_category::Uncomputed: abort(); } - CurrentBlock = FalseBlock; + current_block = false_block; } - CurrentBlock->setName("symbol"); - CurrentBlock->insertInto(func); - auto *StringType - = llvm::StructType::getTypeByName(module->getContext(), STRING_STRUCT); - auto *Len = llvm::BinaryOperator::Create( + current_block->setName("symbol"); + current_block->insertInto(func); + auto *string_type + = llvm::StructType::getTypeByName(module->getContext(), string_struct); + auto *len = llvm::BinaryOperator::Create( llvm::Instruction::Add, func->arg_begin() + 1, - llvm::ConstantExpr::getSizeOf(StringType), "", CurrentBlock); - llvm::Value *Block - = allocateTerm(StringType, Len, CurrentBlock, "koreAllocToken"); - auto *HdrPtr = llvm::GetElementPtrInst::CreateInBounds( - StringType, Block, {zero, zero32, zero32}, "", CurrentBlock); - auto *BlockSize - = module->getOrInsertGlobal("BLOCK_SIZE", llvm::Type::getInt64Ty(Ctx)); - auto *BlockSizeVal = new llvm::LoadInst( - llvm::Type::getInt64Ty(Ctx), BlockSize, "", CurrentBlock); - auto *BlockAllocSize = llvm::BinaryOperator::Create( - llvm::Instruction::Sub, BlockSizeVal, - llvm::ConstantExpr::getSizeOf(llvm::Type::getInt8PtrTy(Ctx)), "", - CurrentBlock); + llvm::ConstantExpr::getSizeOf(string_type), "", current_block); + llvm::Value *block + = allocate_term(string_type, len, current_block, "kore_alloc_token"); + auto *hdr_ptr = llvm::GetElementPtrInst::CreateInBounds( + string_type, block, {zero, zero32, zero32}, "", current_block); + auto *block_size + = module->getOrInsertGlobal("BLOCK_SIZE", llvm::Type::getInt64Ty(ctx)); + auto *block_size_val = new llvm::LoadInst( + llvm::Type::getInt64Ty(ctx), block_size, "", current_block); + auto *block_alloc_size = llvm::BinaryOperator::Create( + llvm::Instruction::Sub, block_size_val, + llvm::ConstantExpr::getSizeOf(llvm::Type::getInt8PtrTy(ctx)), "", + current_block); auto *icmp = new llvm::ICmpInst( - *CurrentBlock, llvm::CmpInst::ICMP_UGT, Len, BlockAllocSize); - auto *Mask = llvm::SelectInst::Create( + *current_block, llvm::CmpInst::ICMP_UGT, len, block_alloc_size); + auto *mask = llvm::SelectInst::Create( icmp, - llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), NOT_YOUNG_OBJECT_BIT), - llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), 0), "", CurrentBlock); - auto *HdrOred = llvm::BinaryOperator::Create( - llvm::Instruction::Or, func->arg_begin() + 1, Mask, "", CurrentBlock); - new llvm::StoreInst(HdrOred, HdrPtr, CurrentBlock); - llvm::Function *Memcpy = getOrInsertFunction( - module, "memcpy", llvm::Type::getInt8PtrTy(Ctx), - llvm::Type::getInt8PtrTy(Ctx), llvm::Type::getInt8PtrTy(Ctx), - llvm::Type::getInt64Ty(Ctx)); - auto *StrPtr = llvm::GetElementPtrInst::CreateInBounds( - StringType, Block, - {zero, llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1), zero}, "", - CurrentBlock); + llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx), NOT_YOUNG_OBJECT_BIT), + llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx), 0), "", + current_block); + auto *hdr_ored = llvm::BinaryOperator::Create( + llvm::Instruction::Or, func->arg_begin() + 1, mask, "", current_block); + new llvm::StoreInst(hdr_ored, hdr_ptr, current_block); + llvm::Function *memcpy = get_or_insert_function( + module, "memcpy", llvm::Type::getInt8PtrTy(ctx), + llvm::Type::getInt8PtrTy(ctx), llvm::Type::getInt8PtrTy(ctx), + llvm::Type::getInt64Ty(ctx)); + auto *str_ptr = llvm::GetElementPtrInst::CreateInBounds( + string_type, block, + {zero, llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx), 1), zero}, "", + current_block); llvm::CallInst::Create( - Memcpy, {StrPtr, func->arg_begin() + 2, func->arg_begin() + 1}, "", - CurrentBlock); + memcpy, {str_ptr, func->arg_begin() + 2, func->arg_begin() + 1}, "", + current_block); auto *cast = new llvm::BitCastInst( - Block, llvm::Type::getInt8PtrTy(Ctx), "", CurrentBlock); - llvm::BranchInst::Create(MergeBlock, CurrentBlock); - Phi->addIncoming(cast, CurrentBlock); - llvm::ReturnInst::Create(Ctx, Phi, MergeBlock); - MergeBlock->insertInto(func); + block, llvm::Type::getInt8PtrTy(ctx), "", current_block); + llvm::BranchInst::Create(merge_block, current_block); + phi->addIncoming(cast, current_block); + llvm::ReturnInst::Create(ctx, phi, merge_block); + merge_block->insertInto(func); } -static llvm::PointerType *makeWriterType(llvm::LLVMContext &Ctx) { +static llvm::PointerType *make_writer_type(llvm::LLVMContext &ctx) { std::string const name = "writer"; static auto types = std::map{}; - if (types.find(&Ctx) == types.end()) { - types[&Ctx] - = llvm::PointerType::getUnqual(llvm::StructType::create(Ctx, name)); + if (types.find(&ctx) == types.end()) { + types[&ctx] + = llvm::PointerType::getUnqual(llvm::StructType::create(ctx, name)); } - return types.at(&Ctx); + return types.at(&ctx); } -static llvm::PointerType *makeVisitorType( - llvm::LLVMContext &Ctx, llvm::Type *file, llvm::Type *item, int numStrs, - int numBools) { +static llvm::PointerType *make_visitor_type( + llvm::LLVMContext &ctx, llvm::Type *file, llvm::Type *item, int num_strs, + int num_bools) { std::vector types; types.push_back(file); types.push_back(item); - for (int i = 0; i < numStrs; i++) { - types.push_back(llvm::Type::getInt8PtrTy(Ctx)); + for (int i = 0; i < num_strs; i++) { + types.push_back(llvm::Type::getInt8PtrTy(ctx)); } - for (int i = 0; i < numBools; i++) { - types.push_back(llvm::Type::getInt1Ty(Ctx)); + for (int i = 0; i < num_bools; i++) { + types.push_back(llvm::Type::getInt1Ty(ctx)); } - types.push_back(llvm::Type::getInt8PtrTy(Ctx)); + types.push_back(llvm::Type::getInt8PtrTy(ctx)); return llvm::PointerType::getUnqual( - llvm::FunctionType::get(llvm::Type::getVoidTy(Ctx), types, false)); + llvm::FunctionType::get(llvm::Type::getVoidTy(ctx), types, false)); } -static llvm::StructType * -makePackedVisitorStructureType(llvm::LLVMContext &Ctx, llvm::Module *module) { +static llvm::StructType *make_packed_visitor_structure_type( + llvm::LLVMContext &ctx, llvm::Module *module) { std::string const name = "visitor"; static auto types = std::map{}; - auto *file = makeWriterType(Ctx); + auto *file = make_writer_type(ctx); - if (types.find(&Ctx) == types.end()) { - auto elementTypes = std::vector{ - {makeVisitorType( - Ctx, file, getValueType({SortCategory::Symbol, 0}, module), 1, 1), - makeVisitorType( - Ctx, file, + if (types.find(&ctx) == types.end()) { + auto element_types = std::vector{ + {make_visitor_type( + ctx, file, getvalue_type({sort_category::Symbol, 0}, module), 1, + 1), + make_visitor_type( + ctx, file, llvm::PointerType::getUnqual( - getValueType({SortCategory::Map, 0}, module)), + getvalue_type({sort_category::Map, 0}, module)), 3, 0), - makeVisitorType( - Ctx, file, + make_visitor_type( + ctx, file, llvm::PointerType::getUnqual( - getValueType({SortCategory::List, 0}, module)), + getvalue_type({sort_category::List, 0}, module)), 3, 0), - makeVisitorType( - Ctx, file, + make_visitor_type( + ctx, file, llvm::PointerType::getUnqual( - getValueType({SortCategory::Set, 0}, module)), + getvalue_type({sort_category::Set, 0}, module)), 3, 0), - makeVisitorType( - Ctx, file, getValueType({SortCategory::Int, 0}, module), 1, 0), - makeVisitorType( - Ctx, file, getValueType({SortCategory::Float, 0}, module), 1, 0), - makeVisitorType( - Ctx, file, getValueType({SortCategory::Bool, 0}, module), 1, 0), - makeVisitorType( - Ctx, file, getValueType({SortCategory::StringBuffer, 0}, module), + make_visitor_type( + ctx, file, getvalue_type({sort_category::Int, 0}, module), 1, 0), + make_visitor_type( + ctx, file, getvalue_type({sort_category::Float, 0}, module), 1, 0), + make_visitor_type( + ctx, file, getvalue_type({sort_category::Bool, 0}, module), 1, 0), + make_visitor_type( + ctx, file, getvalue_type({sort_category::StringBuffer, 0}, module), 1, 0), llvm::PointerType::getUnqual(llvm::FunctionType::get( - llvm::Type::getVoidTy(Ctx), - {file, llvm::Type::getInt64PtrTy(Ctx), llvm::Type::getInt64Ty(Ctx), - llvm::Type::getInt8PtrTy(Ctx), llvm::Type::getInt8PtrTy(Ctx)}, + llvm::Type::getVoidTy(ctx), + {file, llvm::Type::getInt64PtrTy(ctx), llvm::Type::getInt64Ty(ctx), + llvm::Type::getInt8PtrTy(ctx), llvm::Type::getInt8PtrTy(ctx)}, false)), llvm::PointerType::getUnqual(llvm::FunctionType::get( - llvm::Type::getVoidTy(Ctx), {file, llvm::Type::getInt8PtrTy(Ctx)}, + llvm::Type::getVoidTy(ctx), {file, llvm::Type::getInt8PtrTy(ctx)}, false)), - makeVisitorType( - Ctx, file, + make_visitor_type( + ctx, file, llvm::PointerType::getUnqual( - getValueType({SortCategory::RangeMap, 0}, module)), + getvalue_type({sort_category::RangeMap, 0}, module)), 3, 0)}}; - auto *structTy = llvm::StructType::create(Ctx, elementTypes, name); - types[&Ctx] = structTy; + auto *struct_ty = llvm::StructType::create(ctx, element_types, name); + types[&ctx] = struct_ty; } - return types.at(&Ctx); + return types.at(&ctx); } -static void emitTraversal( - std::string const &name, KOREDefinition *definition, llvm::Module *module, - bool isVisitor, +static void emit_traversal( + std::string const &name, kore_definition *definition, llvm::Module *module, + bool is_visitor, void getter( - KOREDefinition *, llvm::Module *, KORESymbol *, llvm::BasicBlock *, + kore_definition *, llvm::Module *, kore_symbol *, llvm::BasicBlock *, std::vector const &callbacks)) { - llvm::LLVMContext &Ctx = module->getContext(); - std::vector argTypes; + llvm::LLVMContext &ctx = module->getContext(); + std::vector arg_types; - auto *block_ty = getBlockType(module); - argTypes.push_back(block_ty->getPointerTo()); + auto *block_ty = get_block_type(module); + arg_types.push_back(block_ty->getPointerTo()); - if (isVisitor) { + if (is_visitor) { // cf runtime/util/header.h visitChildren - auto *file = makeWriterType(Ctx); - argTypes.push_back(file); - argTypes.push_back( - makePackedVisitorStructureType(Ctx, module)->getPointerTo()); - argTypes.push_back(llvm::Type::getInt8PtrTy(Ctx)); + auto *file = make_writer_type(ctx); + arg_types.push_back(file); + arg_types.push_back( + make_packed_visitor_structure_type(ctx, module)->getPointerTo()); + arg_types.push_back(llvm::Type::getInt8PtrTy(ctx)); } else { - argTypes.push_back(llvm::PointerType::getUnqual( - llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx), 0))); + arg_types.push_back(llvm::PointerType::getUnqual( + llvm::ArrayType::get(llvm::Type::getInt8PtrTy(ctx), 0))); } - auto *func = llvm::cast(getOrInsertFunction( + auto *func = llvm::cast(get_or_insert_function( module, name, - llvm::FunctionType::get(llvm::Type::getVoidTy(Ctx), argTypes, false))); - llvm::Constant *zero = llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), 0); + llvm::FunctionType::get(llvm::Type::getVoidTy(ctx), arg_types, false))); + llvm::Constant *zero = llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx), 0); llvm::Constant *zero32 - = llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 0); - auto *EntryBlock = llvm::BasicBlock::Create(Ctx, "entry", func); + = llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx), 0); + auto *entry_block = llvm::BasicBlock::Create(ctx, "entry", func); - auto *HdrPtr = llvm::GetElementPtrInst::CreateInBounds( - block_ty, func->arg_begin(), {zero, zero32, zero32}, "", EntryBlock); - auto *Hdr - = new llvm::LoadInst(llvm::Type::getInt64Ty(Ctx), HdrPtr, "", EntryBlock); - auto *Tag - = new llvm::TruncInst(Hdr, llvm::Type::getInt32Ty(Ctx), "", EntryBlock); + auto *hdr_ptr = llvm::GetElementPtrInst::CreateInBounds( + block_ty, func->arg_begin(), {zero, zero32, zero32}, "", entry_block); + auto *hdr = new llvm::LoadInst( + llvm::Type::getInt64Ty(ctx), hdr_ptr, "", entry_block); + auto *tag + = new llvm::TruncInst(hdr, llvm::Type::getInt32Ty(ctx), "", entry_block); auto callbacks = std::vector{}; - if (isVisitor) { - auto *visitorStruct = func->getArg(2); - auto *visitorType = makePackedVisitorStructureType(Ctx, module); + if (is_visitor) { + auto *visitor_struct = func->getArg(2); + auto *visitor_type = make_packed_visitor_structure_type(ctx, module); - for (auto i = 0; i < visitorType->getNumElements(); ++i) { + for (auto i = 0; i < visitor_type->getNumElements(); ++i) { auto *ptr = llvm::GetElementPtrInst::CreateInBounds( - visitorType, visitorStruct, - {zero, llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), i)}, "", - EntryBlock); + visitor_type, visitor_struct, + {zero, llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx), i)}, "", + entry_block); callbacks.push_back(new llvm::LoadInst( - visitorType->getTypeAtIndex(i), ptr, "", EntryBlock)); + visitor_type->getTypeAtIndex(i), ptr, "", entry_block)); } } - auto *stuck = llvm::BasicBlock::Create(Ctx, "stuck"); - auto const &syms = definition->getSymbols(); - auto *Switch = llvm::SwitchInst::Create(Tag, stuck, syms.size(), EntryBlock); + auto *stuck = llvm::BasicBlock::Create(ctx, "stuck"); + auto const &syms = definition->get_symbols(); + auto *switch_inst + = llvm::SwitchInst::Create(tag, stuck, syms.size(), entry_block); for (auto entry : syms) { uint32_t tag = entry.first; auto *symbol = entry.second; - if (symbol->getArguments().empty()) { + if (symbol->get_arguments().empty()) { continue; } - auto *CaseBlock - = llvm::BasicBlock::Create(Ctx, "tag" + std::to_string(tag), func); - Switch->addCase( - llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), tag), CaseBlock); - getter(definition, module, symbol, CaseBlock, callbacks); - llvm::ReturnInst::Create(Ctx, CaseBlock); + auto *case_block + = llvm::BasicBlock::Create(ctx, "tag" + std::to_string(tag), func); + switch_inst->addCase( + llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx), tag), case_block); + getter(definition, module, symbol, case_block, callbacks); + llvm::ReturnInst::Create(ctx, case_block); } - addAbort(stuck, module); + add_abort(stuck, module); stuck->insertInto(func); } -static void getStore( - KOREDefinition *definition, llvm::Module *module, KORESymbol *symbol, - llvm::BasicBlock *CaseBlock, std::vector const &) { - llvm::LLVMContext &Ctx = module->getContext(); - llvm::Constant *zero = llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), 0); - llvm::Function *func = CaseBlock->getParent(); - llvm::Value *ArgumentsArray = func->arg_begin() + 1; +static void get_store( + kore_definition *definition, llvm::Module *module, kore_symbol *symbol, + llvm::BasicBlock *case_block, std::vector const &) { + llvm::LLVMContext &ctx = module->getContext(); + llvm::Constant *zero = llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx), 0); + llvm::Function *func = case_block->getParent(); + llvm::Value *arguments_array = func->arg_begin() + 1; int idx = 0; - auto *BlockType = getBlockType(module, definition, symbol); + auto *block_type = get_block_type(module, definition, symbol); auto *cast = new llvm::BitCastInst( - func->arg_begin(), llvm::PointerType::getUnqual(BlockType), "", - CaseBlock); - for (auto const &sort : symbol->getArguments()) { - ValueType cat = dynamic_cast(sort.get()) - ->getCategory(definition); - llvm::Value *arg = getArgValue(ArgumentsArray, idx, CaseBlock, cat, module); - llvm::Type *arg_ty = getArgType(cat, module); - llvm::Value *ChildPtr = llvm::GetElementPtrInst::CreateInBounds( - BlockType, cast, - {zero, llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), idx++ + 2)}, - "", CaseBlock); - if (isCollectionSort(cat)) { - arg = new llvm::LoadInst(arg_ty, arg, "", CaseBlock); + func->arg_begin(), llvm::PointerType::getUnqual(block_type), "", + case_block); + for (auto const &sort : symbol->get_arguments()) { + value_type cat = dynamic_cast(sort.get()) + ->get_category(definition); + llvm::Value *arg + = get_arg_value(arguments_array, idx, case_block, cat, module); + llvm::Type *arg_ty = get_arg_type(cat, module); + llvm::Value *child_ptr = llvm::GetElementPtrInst::CreateInBounds( + block_type, cast, + {zero, llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx), idx++ + 2)}, + "", case_block); + if (is_collection_sort(cat)) { + arg = new llvm::LoadInst(arg_ty, arg, "", case_block); } - new llvm::StoreInst(arg, ChildPtr, CaseBlock); + new llvm::StoreInst(arg, child_ptr, case_block); } } static void -emitStoreSymbolChildren(KOREDefinition *definition, llvm::Module *module) { - emitTraversal("storeSymbolChildren", definition, module, false, getStore); +emit_store_symbol_children(kore_definition *definition, llvm::Module *module) { + emit_traversal("store_symbol_children", definition, module, false, get_store); } -static llvm::Constant *getSymbolName( - KOREDefinition *definition, llvm::Module *module, KORESymbol *symbol) { - return getSymbolNamePtr(symbol, nullptr, module); +static llvm::Constant *get_symbol_name( + kore_definition *definition, llvm::Module *module, kore_symbol *symbol) { + return get_symbol_name_ptr(symbol, nullptr, module); } -static void emitGetSymbolNameForTag(KOREDefinition *def, llvm::Module *mod) { - emitDataTableForSymbol( - "getSymbolNameForTag", llvm::Type::getInt8PtrTy(mod->getContext()), - getCharPtrDebugType(), def, mod, getSymbolName); +static void +emit_get_symbol_name_for_tag(kore_definition *def, llvm::Module *mod) { + emit_data_table_for_symbol( + "get_symbol_name_for_tag", llvm::Type::getInt8PtrTy(mod->getContext()), + get_char_ptr_debug_type(), def, mod, get_symbol_name); } -static void visitCollection( - KOREDefinition *definition, llvm::Module *module, - KORECompositeSort *compositeSort, llvm::Function *func, - llvm::Value *ChildPtr, llvm::BasicBlock *CaseBlock, llvm::Value *callback, +static void visit_collection( + kore_definition *definition, llvm::Module *module, + kore_composite_sort *composite_sort, llvm::Function *func, + llvm::Value *child_ptr, llvm::BasicBlock *case_block, llvm::Value *callback, llvm::Value *state_ptr) { - llvm::LLVMContext &Ctx = module->getContext(); - llvm::Constant *zero = llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), 0); + llvm::LLVMContext &ctx = module->getContext(); + llvm::Constant *zero = llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx), 0); auto indices = std::vector{zero, zero}; - auto *sortDecl - = definition->getSortDeclarations().at(compositeSort->getName()); - llvm::Constant *concatPtr = nullptr; - if (sortDecl->attributes().contains(attribute_set::key::concat)) { - auto *concat = (KORECompositePattern *)sortDecl->attributes() - .get(attribute_set::key::concat) - ->getArguments()[0] + auto *sort_decl + = definition->get_sort_declarations().at(composite_sort->get_name()); + llvm::Constant *concat_ptr = nullptr; + if (sort_decl->attributes().contains(attribute_set::key::Concat)) { + auto *concat = (kore_composite_pattern *)sort_decl->attributes() + .get(attribute_set::key::Concat) + ->get_arguments()[0] .get(); - concatPtr = getSymbolNamePtr(concat->getConstructor(), nullptr, module); + concat_ptr + = get_symbol_name_ptr(concat->get_constructor(), nullptr, module); } else { - concatPtr = llvm::ConstantPointerNull::get(llvm::Type::getInt8PtrTy(Ctx)); + concat_ptr = llvm::ConstantPointerNull::get(llvm::Type::getInt8PtrTy(ctx)); } - auto *unit = (KORECompositePattern *)sortDecl->attributes() - .get(attribute_set::key::unit) - ->getArguments()[0] + auto *unit = (kore_composite_pattern *)sort_decl->attributes() + .get(attribute_set::key::Unit) + ->get_arguments()[0] .get(); - auto *unitPtr = getSymbolNamePtr(unit->getConstructor(), nullptr, module); - auto *element = (KORECompositePattern *)sortDecl->attributes() - .get(attribute_set::key::element) - ->getArguments()[0] + auto *unit_ptr + = get_symbol_name_ptr(unit->get_constructor(), nullptr, module); + auto *element = (kore_composite_pattern *)sort_decl->attributes() + .get(attribute_set::key::Element) + ->get_arguments()[0] .get(); - auto *elementPtr - = getSymbolNamePtr(element->getConstructor(), nullptr, module); - auto *file = makeWriterType(Ctx); - auto *i8_ptr_ty = llvm::Type::getInt8PtrTy(Ctx); - auto *fnType = llvm::FunctionType::get( - llvm::Type::getVoidTy(Ctx), - {file, ChildPtr->getType(), i8_ptr_ty, i8_ptr_ty, i8_ptr_ty, i8_ptr_ty}, + auto *element_ptr + = get_symbol_name_ptr(element->get_constructor(), nullptr, module); + auto *file = make_writer_type(ctx); + auto *i8_ptr_ty = llvm::Type::getInt8PtrTy(ctx); + auto *fn_type = llvm::FunctionType::get( + llvm::Type::getVoidTy(ctx), + {file, child_ptr->getType(), i8_ptr_ty, i8_ptr_ty, i8_ptr_ty, i8_ptr_ty}, false); llvm::CallInst::Create( - fnType, callback, - {func->arg_begin() + 1, ChildPtr, unitPtr, elementPtr, concatPtr, + fn_type, callback, + {func->arg_begin() + 1, child_ptr, unit_ptr, element_ptr, concat_ptr, state_ptr}, - "", CaseBlock); + "", case_block); } // NOLINTNEXTLINE(*-cognitive-complexity) -static void getVisitor( - KOREDefinition *definition, llvm::Module *module, KORESymbol *symbol, - llvm::BasicBlock *CaseBlock, std::vector const &callbacks) { - llvm::LLVMContext &Ctx = module->getContext(); - llvm::Constant *zero = llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), 0); +static void get_visitor( + kore_definition *definition, llvm::Module *module, kore_symbol *symbol, + llvm::BasicBlock *case_block, std::vector const &callbacks) { + llvm::LLVMContext &ctx = module->getContext(); + llvm::Constant *zero = llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx), 0); auto indices = std::vector{zero, zero}; - llvm::Function *func = CaseBlock->getParent(); + llvm::Function *func = case_block->getParent(); int idx = 0; - auto *BlockType = getBlockType(module, definition, symbol); + auto *block_type = get_block_type(module, definition, symbol); auto *cast = new llvm::BitCastInst( - func->arg_begin(), llvm::PointerType::getUnqual(BlockType), "", - CaseBlock); + func->arg_begin(), llvm::PointerType::getUnqual(block_type), "", + case_block); unsigned i = 0; - auto *file = makeWriterType(Ctx); + auto *file = make_writer_type(ctx); auto *state_ptr = func->arg_end() - 1; - for (auto const &sort : symbol->getArguments()) { - auto *compositeSort = dynamic_cast(sort.get()); - ValueType cat = compositeSort->getCategory(definition); - llvm::Value *ChildPtr = llvm::GetElementPtrInst::CreateInBounds( - BlockType, cast, - {zero, llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), idx++ + 2)}, - "", CaseBlock); - llvm::Value *Child = new llvm::LoadInst( - getValueType(cat, module), ChildPtr, "", CaseBlock); + for (auto const &sort : symbol->get_arguments()) { + auto *composite_sort = dynamic_cast(sort.get()); + value_type cat = composite_sort->get_category(definition); + llvm::Value *child_ptr = llvm::GetElementPtrInst::CreateInBounds( + block_type, cast, + {zero, llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx), idx++ + 2)}, + "", case_block); + llvm::Value *child = new llvm::LoadInst( + getvalue_type(cat, module), child_ptr, "", case_block); auto sort_name = ast_to_string(*sort); - auto *Str = llvm::ConstantDataArray::getString(Ctx, sort_name, true); + auto *str = llvm::ConstantDataArray::getString(ctx, sort_name, true); auto *global = module->getOrInsertGlobal( - fmt::format("sort_name_{}", sort_name), Str->getType()); - auto *globalVar = llvm::dyn_cast(global); - if (!globalVar->hasInitializer()) { - globalVar->setInitializer(Str); + fmt::format("sort_name_{}", sort_name), str->getType()); + auto *global_var = llvm::dyn_cast(global); + if (!global_var->hasInitializer()) { + global_var->setInitializer(str); } - llvm::Constant *CharPtr = llvm::ConstantExpr::getInBoundsGetElementPtr( - Str->getType(), global, indices); + llvm::Constant *char_ptr = llvm::ConstantExpr::getInBoundsGetElementPtr( + str->getType(), global, indices); switch (cat.cat) { - case SortCategory::Variable: - case SortCategory::Symbol: + case sort_category::Variable: + case sort_category::Symbol: llvm::CallInst::Create( llvm::FunctionType::get( - llvm::Type::getVoidTy(Ctx), - {file, Child->getType(), llvm::Type::getInt8PtrTy(Ctx), - llvm::Type::getInt1Ty(Ctx), llvm::Type::getInt8PtrTy(Ctx)}, + llvm::Type::getVoidTy(ctx), + {file, child->getType(), llvm::Type::getInt8PtrTy(ctx), + llvm::Type::getInt1Ty(ctx), llvm::Type::getInt8PtrTy(ctx)}, false), callbacks.at(0), - {func->arg_begin() + 1, Child, CharPtr, + {func->arg_begin() + 1, child, char_ptr, llvm::ConstantInt::get( - llvm::Type::getInt1Ty(Ctx), cat.cat == SortCategory::Variable), + llvm::Type::getInt1Ty(ctx), cat.cat == sort_category::Variable), state_ptr}, - "", CaseBlock); + "", case_block); break; - case SortCategory::Int: + case sort_category::Int: llvm::CallInst::Create( llvm::FunctionType::get( - llvm::Type::getVoidTy(Ctx), - {file, Child->getType(), llvm::Type::getInt8PtrTy(Ctx), - llvm::Type::getInt8PtrTy(Ctx)}, + llvm::Type::getVoidTy(ctx), + {file, child->getType(), llvm::Type::getInt8PtrTy(ctx), + llvm::Type::getInt8PtrTy(ctx)}, false), - callbacks.at(4), {func->arg_begin() + 1, Child, CharPtr, state_ptr}, - "", CaseBlock); + callbacks.at(4), {func->arg_begin() + 1, child, char_ptr, state_ptr}, + "", case_block); break; - case SortCategory::Float: + case sort_category::Float: llvm::CallInst::Create( llvm::FunctionType::get( - llvm::Type::getVoidTy(Ctx), - {file, Child->getType(), llvm::Type::getInt8PtrTy(Ctx), - llvm::Type::getInt8PtrTy(Ctx)}, + llvm::Type::getVoidTy(ctx), + {file, child->getType(), llvm::Type::getInt8PtrTy(ctx), + llvm::Type::getInt8PtrTy(ctx)}, false), - callbacks.at(5), {func->arg_begin() + 1, Child, CharPtr, state_ptr}, - "", CaseBlock); + callbacks.at(5), {func->arg_begin() + 1, child, char_ptr, state_ptr}, + "", case_block); break; - case SortCategory::Bool: + case sort_category::Bool: llvm::CallInst::Create( llvm::FunctionType::get( - llvm::Type::getVoidTy(Ctx), - {file, Child->getType(), llvm::Type::getInt8PtrTy(Ctx), - llvm::Type::getInt8PtrTy(Ctx)}, + llvm::Type::getVoidTy(ctx), + {file, child->getType(), llvm::Type::getInt8PtrTy(ctx), + llvm::Type::getInt8PtrTy(ctx)}, false), - callbacks.at(6), {func->arg_begin() + 1, Child, CharPtr, state_ptr}, - "", CaseBlock); + callbacks.at(6), {func->arg_begin() + 1, child, char_ptr, state_ptr}, + "", case_block); break; - case SortCategory::StringBuffer: + case sort_category::StringBuffer: llvm::CallInst::Create( llvm::FunctionType::get( - llvm::Type::getVoidTy(Ctx), - {file, Child->getType(), llvm::Type::getInt8PtrTy(Ctx), - llvm::Type::getInt8PtrTy(Ctx)}, + llvm::Type::getVoidTy(ctx), + {file, child->getType(), llvm::Type::getInt8PtrTy(ctx), + llvm::Type::getInt8PtrTy(ctx)}, false), - callbacks.at(7), {func->arg_begin() + 1, Child, CharPtr, state_ptr}, - "", CaseBlock); + callbacks.at(7), {func->arg_begin() + 1, child, char_ptr, state_ptr}, + "", case_block); break; - case SortCategory::MInt: { + case sort_category::MInt: { llvm::Value *mint = new llvm::LoadInst( - getArgType(cat, module), ChildPtr, "mint", CaseBlock); + get_arg_type(cat, module), child_ptr, "mint", case_block); size_t nwords = (cat.bits + 63) / 64; auto *nbits - = llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), cat.bits); - auto *fnType = llvm::FunctionType::get( - llvm::Type::getVoidTy(Ctx), - {file, llvm::Type::getInt64PtrTy(Ctx), llvm::Type::getInt64Ty(Ctx), - llvm::Type::getInt8PtrTy(Ctx), llvm::Type::getInt8PtrTy(Ctx)}, + = llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx), cat.bits); + auto *fn_type = llvm::FunctionType::get( + llvm::Type::getVoidTy(ctx), + {file, llvm::Type::getInt64PtrTy(ctx), llvm::Type::getInt64Ty(ctx), + llvm::Type::getInt8PtrTy(ctx), llvm::Type::getInt8PtrTy(ctx)}, false); if (nwords == 0) { llvm::CallInst::Create( - fnType, func->arg_begin() + 10, + fn_type, func->arg_begin() + 10, {func->arg_begin() + 1, - llvm::ConstantPointerNull::get(llvm::Type::getInt64PtrTy(Ctx)), - nbits, CharPtr, state_ptr}, - "", CaseBlock); + llvm::ConstantPointerNull::get(llvm::Type::getInt64PtrTy(ctx)), + nbits, char_ptr, state_ptr}, + "", case_block); } else { - auto *Ptr = allocateTerm( - llvm::Type::getInt64Ty(Ctx), - llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), nwords * 8), - CaseBlock, "koreAllocAlwaysGC"); + auto *ptr = allocate_term( + llvm::Type::getInt64Ty(ctx), + llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx), nwords * 8), + case_block, "kore_alloc_always_gc"); if (nwords == 1) { - llvm::Value *Word = nullptr; + llvm::Value *word = nullptr; if (cat.bits == 64) { - Word = mint; + word = mint; } else { - Word = new llvm::ZExtInst( - mint, llvm::Type::getInt64Ty(Ctx), "word", CaseBlock); + word = new llvm::ZExtInst( + mint, llvm::Type::getInt64Ty(ctx), "word", case_block); } - new llvm::StoreInst(Word, Ptr, CaseBlock); + new llvm::StoreInst(word, ptr, case_block); } else { // nwords >= 2 - llvm::Value *Ptr2 = Ptr; + llvm::Value *ptr2 = ptr; llvm::Value *accum = mint; for (size_t i = 0; i < nwords; i++) { - auto *Word = new llvm::TruncInst( - accum, llvm::Type::getInt64Ty(Ctx), "word", CaseBlock); - new llvm::StoreInst(Word, Ptr2, CaseBlock); - Ptr2 = llvm::GetElementPtrInst::Create( - llvm::Type::getInt64Ty(Ctx), Ptr2, - {llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), 1)}, "ptr", - CaseBlock); + auto *word = new llvm::TruncInst( + accum, llvm::Type::getInt64Ty(ctx), "word", case_block); + new llvm::StoreInst(word, ptr2, case_block); + ptr2 = llvm::GetElementPtrInst::Create( + llvm::Type::getInt64Ty(ctx), ptr2, + {llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx), 1)}, "ptr", + case_block); accum = llvm::BinaryOperator::Create( llvm::Instruction::LShr, accum, llvm::ConstantInt::get(mint->getType(), 64), "shift", - CaseBlock); + case_block); } } llvm::CallInst::Create( - fnType, callbacks.at(8), - {func->arg_begin() + 1, Ptr, nbits, CharPtr, state_ptr}, "", - CaseBlock); + fn_type, callbacks.at(8), + {func->arg_begin() + 1, ptr, nbits, char_ptr, state_ptr}, "", + case_block); } break; } - case SortCategory::Map: - visitCollection( - definition, module, compositeSort, func, ChildPtr, CaseBlock, + case sort_category::Map: + visit_collection( + definition, module, composite_sort, func, child_ptr, case_block, callbacks.at(1), state_ptr); break; - case SortCategory::RangeMap: - visitCollection( - definition, module, compositeSort, func, ChildPtr, CaseBlock, + case sort_category::RangeMap: + visit_collection( + definition, module, composite_sort, func, child_ptr, case_block, callbacks.at(10), state_ptr); break; - case SortCategory::Set: - visitCollection( - definition, module, compositeSort, func, ChildPtr, CaseBlock, + case sort_category::Set: + visit_collection( + definition, module, composite_sort, func, child_ptr, case_block, callbacks.at(3), state_ptr); break; - case SortCategory::List: { - visitCollection( - definition, module, compositeSort, func, ChildPtr, CaseBlock, + case sort_category::List: { + visit_collection( + definition, module, composite_sort, func, child_ptr, case_block, callbacks.at(2), state_ptr); break; } - case SortCategory::Uncomputed: abort(); + case sort_category::Uncomputed: abort(); } - if (i != symbol->getArguments().size() - 1) { + if (i != symbol->get_arguments().size() - 1) { llvm::CallInst::Create( llvm::FunctionType::get( - llvm::Type::getVoidTy(Ctx), {file, llvm::Type::getInt8PtrTy(Ctx)}, + llvm::Type::getVoidTy(ctx), {file, llvm::Type::getInt8PtrTy(ctx)}, false), - callbacks.at(9), {func->arg_begin() + 1, state_ptr}, "", CaseBlock); + callbacks.at(9), {func->arg_begin() + 1, state_ptr}, "", case_block); } i++; } } -static llvm::Constant *getOffsetOfMember( +static llvm::Constant *get_offset_of_member( [[maybe_unused]] llvm::Module *mod, llvm::StructType *struct_ty, int nth_member) { #if LLVM_VERSION_MAJOR >= 17 @@ -1105,170 +1128,171 @@ static llvm::Constant *getOffsetOfMember( #endif } -static llvm::Constant *getLayoutData( - uint16_t layout, KORESymbol *symbol, llvm::Module *module, - KOREDefinition *def) { - uint8_t len = symbol->getArguments().size(); +static llvm::Constant *get_layout_data( + uint16_t layout, kore_symbol *symbol, llvm::Module *module, + kore_definition *def) { + uint8_t len = symbol->get_arguments().size(); std::vector elements; - llvm::LLVMContext &Ctx = module->getContext(); - auto *BlockType = getBlockType(module, def, symbol); + llvm::LLVMContext &ctx = module->getContext(); + auto *block_type = get_block_type(module, def, symbol); int i = 2; - for (auto const &sort : symbol->getArguments()) { - ValueType cat - = dynamic_cast(sort.get())->getCategory(def); - auto *offset = getOffsetOfMember( - module, BlockType, + for (auto const &sort : symbol->get_arguments()) { + value_type cat + = dynamic_cast(sort.get())->get_category(def); + auto *offset = get_offset_of_member( + module, block_type, i++); //llvm::ConstantExpr::getOffsetOf(BlockType, i++); elements.push_back(llvm::ConstantStruct::get( llvm::StructType::getTypeByName( - module->getContext(), LAYOUTITEM_STRUCT), + module->getContext(), layoutitem_struct), offset, llvm::ConstantInt::get( - llvm::Type::getInt16Ty(Ctx), (int)cat.cat + cat.bits))); + llvm::Type::getInt16Ty(ctx), (int)cat.cat + cat.bits))); } - auto *Arr = llvm::ConstantArray::get( + auto *arr = llvm::ConstantArray::get( llvm::ArrayType::get( llvm::StructType::getTypeByName( - module->getContext(), LAYOUTITEM_STRUCT), + module->getContext(), layoutitem_struct), len), elements); auto *global = module->getOrInsertGlobal( - "layout_item_" + std::to_string(layout), Arr->getType()); - auto *globalVar = llvm::cast(global); - if (!globalVar->hasInitializer()) { - globalVar->setInitializer(Arr); + "layout_item_" + std::to_string(layout), arr->getType()); + auto *global_var = llvm::cast(global); + if (!global_var->hasInitializer()) { + global_var->setInitializer(arr); } - llvm::Constant *zero = llvm::ConstantInt::get(llvm::Type::getInt64Ty(Ctx), 0); + llvm::Constant *zero = llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx), 0); auto indices = std::vector{zero, zero}; - auto *Ptr = llvm::ConstantExpr::getInBoundsGetElementPtr( - Arr->getType(), globalVar, indices); + auto *ptr = llvm::ConstantExpr::getInBoundsGetElementPtr( + arr->getType(), global_var, indices); std::string name = "layout_" + std::to_string(layout); auto *global2 = module->getOrInsertGlobal( name, - llvm::StructType::getTypeByName(module->getContext(), LAYOUT_STRUCT)); - auto *globalVar2 = llvm::cast(global2); - initDebugGlobal(name, getForwardDecl(LAYOUT_STRUCT), globalVar2); - if (!globalVar2->hasInitializer()) { - globalVar2->setInitializer(llvm::ConstantStruct::get( - llvm::StructType::getTypeByName(module->getContext(), LAYOUT_STRUCT), - llvm::ConstantInt::get(llvm::Type::getInt8Ty(Ctx), len), Ptr)); + llvm::StructType::getTypeByName(module->getContext(), layout_struct)); + auto *global_var2 = llvm::cast(global2); + init_debug_global(name, get_forward_decl(layout_struct), global_var2); + if (!global_var2->hasInitializer()) { + global_var2->setInitializer(llvm::ConstantStruct::get( + llvm::StructType::getTypeByName(module->getContext(), layout_struct), + llvm::ConstantInt::get(llvm::Type::getInt8Ty(ctx), len), ptr)); } - return globalVar2; + return global_var2; } -static void emitLayouts(KOREDefinition *definition, llvm::Module *module) { - std::map layouts; - for (auto entry : definition->getSymbols()) { - layouts[entry.second->getLayout()] = entry.second; +static void emit_layouts(kore_definition *definition, llvm::Module *module) { + std::map layouts; + for (auto entry : definition->get_symbols()) { + layouts[entry.second->get_layout()] = entry.second; } - llvm::LLVMContext &Ctx = module->getContext(); - std::vector argTypes; - argTypes.push_back(llvm::Type::getInt16Ty(Ctx)); - auto *func = llvm::cast(getOrInsertFunction( - module, "getLayoutData", + llvm::LLVMContext &ctx = module->getContext(); + std::vector arg_types; + arg_types.push_back(llvm::Type::getInt16Ty(ctx)); + auto *func = llvm::cast(get_or_insert_function( + module, "get_layout_data", llvm::FunctionType::get( llvm::PointerType::getUnqual(llvm::StructType::getTypeByName( - module->getContext(), LAYOUT_STRUCT)), - argTypes, false))); - initDebugFunction( - "getLayoutData", "getLayoutData", - getDebugFunctionType( - getPointerDebugType(getForwardDecl(LAYOUT_STRUCT), "layout *"), - {getShortDebugType()}), + module->getContext(), layout_struct)), + arg_types, false))); + init_debug_function( + "get_layout_data", "get_layout_data", + get_debug_function_type( + get_pointer_debug_type(get_forward_decl(layout_struct), "layout *"), + {get_short_debug_type()}), definition, func); - auto *EntryBlock = llvm::BasicBlock::Create(Ctx, "entry", func); - auto *MergeBlock = llvm::BasicBlock::Create(Ctx, "exit"); - auto *stuck = llvm::BasicBlock::Create(Ctx, "stuck"); - auto *Switch = llvm::SwitchInst::Create( - func->arg_begin(), stuck, layouts.size(), EntryBlock); - auto *Phi = llvm::PHINode::Create( + auto *entry_block = llvm::BasicBlock::Create(ctx, "entry", func); + auto *merge_block = llvm::BasicBlock::Create(ctx, "exit"); + auto *stuck = llvm::BasicBlock::Create(ctx, "stuck"); + auto *switch_inst = llvm::SwitchInst::Create( + func->arg_begin(), stuck, layouts.size(), entry_block); + auto *phi = llvm::PHINode::Create( llvm::PointerType::getUnqual( - llvm::StructType::getTypeByName(module->getContext(), LAYOUT_STRUCT)), - layouts.size(), "phi", MergeBlock); + llvm::StructType::getTypeByName(module->getContext(), layout_struct)), + layouts.size(), "phi", merge_block); for (auto entry : layouts) { uint16_t layout = entry.first; auto *symbol = entry.second; - auto *CaseBlock = llvm::BasicBlock::Create( - Ctx, "layout" + std::to_string(layout), func); - llvm::BranchInst::Create(MergeBlock, CaseBlock); - auto *data = getLayoutData(layout, symbol, module, definition); - Phi->addIncoming(data, CaseBlock); - Switch->addCase( - llvm::ConstantInt::get(llvm::Type::getInt16Ty(Ctx), layout), CaseBlock); + auto *case_block = llvm::BasicBlock::Create( + ctx, "layout" + std::to_string(layout), func); + llvm::BranchInst::Create(merge_block, case_block); + auto *data = get_layout_data(layout, symbol, module, definition); + phi->addIncoming(data, case_block); + switch_inst->addCase( + llvm::ConstantInt::get(llvm::Type::getInt16Ty(ctx), layout), + case_block); } - llvm::ReturnInst::Create(Ctx, Phi, MergeBlock); - MergeBlock->insertInto(func); - addAbort(stuck, module); + llvm::ReturnInst::Create(ctx, phi, merge_block); + merge_block->insertInto(func); + add_abort(stuck, module); stuck->insertInto(func); } -static void emitVisitChildren(KOREDefinition *def, llvm::Module *mod) { - emitTraversal("visitChildren", def, mod, true, getVisitor); +static void emit_visit_children(kore_definition *def, llvm::Module *mod) { + emit_traversal("visit_children", def, mod, true, get_visitor); } -static void emitInjTags(KOREDefinition *def, llvm::Module *mod) { - llvm::LLVMContext &Ctx = mod->getContext(); +static void emit_inj_tags(kore_definition *def, llvm::Module *mod) { + llvm::LLVMContext &ctx = mod->getContext(); auto *global - = mod->getOrInsertGlobal("first_inj_tag", llvm::Type::getInt32Ty(Ctx)); - auto *globalVar = llvm::cast(global); - globalVar->setConstant(true); - if (!globalVar->hasInitializer()) { - globalVar->setInitializer(llvm::ConstantInt::get( - llvm::Type::getInt32Ty(Ctx), def->getInjSymbol()->getFirstTag())); + = mod->getOrInsertGlobal("FIRST_INJ_TAG", llvm::Type::getInt32Ty(ctx)); + auto *global_var = llvm::cast(global); + global_var->setConstant(true); + if (!global_var->hasInitializer()) { + global_var->setInitializer(llvm::ConstantInt::get( + llvm::Type::getInt32Ty(ctx), def->get_inj_symbol()->get_first_tag())); } - global = mod->getOrInsertGlobal("last_inj_tag", llvm::Type::getInt32Ty(Ctx)); - globalVar = llvm::cast(global); - globalVar->setConstant(true); - if (!globalVar->hasInitializer()) { - globalVar->setInitializer(llvm::ConstantInt::get( - llvm::Type::getInt32Ty(Ctx), def->getInjSymbol()->getLastTag())); + global = mod->getOrInsertGlobal("LAST_INJ_TAG", llvm::Type::getInt32Ty(ctx)); + global_var = llvm::cast(global); + global_var->setConstant(true); + if (!global_var->hasInitializer()) { + global_var->setInitializer(llvm::ConstantInt::get( + llvm::Type::getInt32Ty(ctx), def->get_inj_symbol()->get_last_tag())); } } -static void emitSortTable(KOREDefinition *def, llvm::Module *mod) { - auto getter = [](KOREDefinition *definition, llvm::Module *module, - KORESymbol *symbol) -> llvm::Constant * { +static void emit_sort_table(kore_definition *def, llvm::Module *mod) { + auto getter = [](kore_definition *definition, llvm::Module *module, + kore_symbol *symbol) -> llvm::Constant * { auto &ctx = module->getContext(); - auto *subtableType = llvm::ArrayType::get( - llvm::Type::getInt8PtrTy(ctx), symbol->getArguments().size()); + auto *subtable_type = llvm::ArrayType::get( + llvm::Type::getInt8PtrTy(ctx), symbol->get_arguments().size()); auto *subtable = module->getOrInsertGlobal( - fmt::format("sorts_{}", ast_to_string(*symbol)), subtableType); - auto *subtableVar = llvm::dyn_cast(subtable); - initDebugGlobal( - "sorts_" + symbol->getName(), - getArrayDebugType( - getCharPtrDebugType(), symbol->getArguments().size(), + fmt::format("sorts_{}", ast_to_string(*symbol)), subtable_type); + auto *subtable_var = llvm::dyn_cast(subtable); + init_debug_global( + "sorts_" + symbol->get_name(), + get_array_debug_type( + get_char_ptr_debug_type(), symbol->get_arguments().size(), llvm::DataLayout(module).getABITypeAlign( llvm::Type::getInt8PtrTy(ctx))), - subtableVar); + subtable_var); llvm::Constant *zero = llvm::ConstantInt::get(llvm::Type::getInt64Ty(ctx), 0); auto indices = std::vector{zero, zero}; std::vector subvalues; - for (const auto &i : symbol->getArguments()) { + for (const auto &i : symbol->get_arguments()) { auto arg_str = ast_to_string(*i); - auto *strType = llvm::ArrayType::get( + auto *str_type = llvm::ArrayType::get( llvm::Type::getInt8Ty(ctx), arg_str.size() + 1); - auto *sortName = module->getOrInsertGlobal( - fmt::format("sort_name_{}", arg_str), strType); + auto *sort_name = module->getOrInsertGlobal( + fmt::format("sort_name_{}", arg_str), str_type); subvalues.push_back(llvm::ConstantExpr::getInBoundsGetElementPtr( - strType, sortName, indices)); + str_type, sort_name, indices)); } - subtableVar->setInitializer( - llvm::ConstantArray::get(subtableType, subvalues)); + subtable_var->setInitializer( + llvm::ConstantArray::get(subtable_type, subvalues)); return llvm::ConstantExpr::getInBoundsGetElementPtr( - subtableType, subtableVar, indices); + subtable_type, subtable_var, indices); }; auto *i8_ptr_ty = llvm::Type::getInt8PtrTy(mod->getContext()); auto *entry_ty = llvm::PointerType::getUnqual(i8_ptr_ty); - auto *debug_ty = getPointerDebugType(getCharPtrDebugType(), "char **"); + auto *debug_ty = get_pointer_debug_type(get_char_ptr_debug_type(), "char **"); - emitDataTableForSymbol( - "getArgumentSortsForTag", entry_ty, debug_ty, def, mod, getter); + emit_data_table_for_symbol( + "get_argument_sorts_for_tag", entry_ty, debug_ty, def, mod, getter); } /* @@ -1280,12 +1304,12 @@ static void emitSortTable(KOREDefinition *def, llvm::Module *mod) { * Each value in the table is a pointer to a global variable containing the * relevant sort name as a null-terminated string. */ -static void emitReturnSortTable(KOREDefinition *def, llvm::Module *mod) { - auto getter = [](KOREDefinition *definition, llvm::Module *module, - KORESymbol *symbol) -> llvm::Constant * { +static void emit_return_sort_table(kore_definition *def, llvm::Module *mod) { + auto getter = [](kore_definition *definition, llvm::Module *module, + kore_symbol *symbol) -> llvm::Constant * { auto &ctx = module->getContext(); - auto sort = symbol->getSort(); + auto sort = symbol->get_sort(); auto sort_str = ast_to_string(*sort); auto *char_type = llvm::Type::getInt8Ty(ctx); @@ -1301,9 +1325,9 @@ static void emitReturnSortTable(KOREDefinition *def, llvm::Module *mod) { str_type, sort_name, std::vector{zero}); }; - emitDataTableForSymbol( - "getReturnSortForTag", llvm::Type::getInt8PtrTy(mod->getContext()), - getCharPtrDebugType(), def, mod, getter); + emit_data_table_for_symbol( + "get_return_sort_for_tag", llvm::Type::getInt8PtrTy(mod->getContext()), + get_char_ptr_debug_type(), def, mod, getter); } /* @@ -1313,45 +1337,46 @@ static void emitReturnSortTable(KOREDefinition *def, llvm::Module *mod) { * tag_of(inj{SortA{}, SortKItem{}}) |-> true * tag_of(someSymbol{}) |-> false */ -static void emitSymbolIsInstantiation(KOREDefinition *def, llvm::Module *mod) { - auto getter = [](KOREDefinition *definition, llvm::Module *module, - KORESymbol *symbol) -> llvm::Constant * { +static void +emit_symbol_is_instantiation(kore_definition *def, llvm::Module *mod) { + auto getter = [](kore_definition *definition, llvm::Module *module, + kore_symbol *symbol) -> llvm::Constant * { auto &ctx = module->getContext(); auto *bool_ty = llvm::Type::getInt1Ty(ctx); return llvm::ConstantInt::get( - bool_ty, !symbol->getFormalArguments().empty()); + bool_ty, !symbol->get_formal_arguments().empty()); }; - emitDataTableForSymbol( - "symbolIsInstantiation", llvm::Type::getInt1Ty(mod->getContext()), - getBoolDebugType(), def, mod, getter); + emit_data_table_for_symbol( + "symbol_is_instantiation", llvm::Type::getInt1Ty(mod->getContext()), + get_bool_debug_type(), def, mod, getter); } -void emitConfigParserFunctions( - KOREDefinition *definition, llvm::Module *module) { - emitGetTagForSymbolName(definition, module); - emitGetBlockHeaderForSymbol(definition, module); - emitIsSymbolAFunction(definition, module); - emitIsSymbolABinder(definition, module); - emitStoreSymbolChildren(definition, module); - emitEvaluateFunctionSymbol(definition, module); - emitGetToken(definition, module); - emitGetTagForFreshSort(definition, module); - emitGetInjectionForSortOfTag(definition, module); - emitGetSymbolArity(definition, module); - - emitGetSymbolNameForTag(definition, module); - emitVisitChildren(definition, module); - - emitLayouts(definition, module); - - emitInjTags(definition, module); - - emitSortTable(definition, module); - emitReturnSortTable(definition, module); - emitSymbolIsInstantiation(definition, module); +void emit_config_parser_functions( + kore_definition *definition, llvm::Module *module) { + emit_get_tag_for_symbol_name(definition, module); + emit_get_block_header_for_symbol(definition, module); + emit_is_symbol_a_function(definition, module); + emit_is_symbol_a_binder(definition, module); + emit_store_symbol_children(definition, module); + emit_evaluate_function_symbol(definition, module); + emit_get_token(definition, module); + emit_get_tag_for_fresh_sort(definition, module); + emit_get_injection_for_sort_of_tag(definition, module); + emit_get_symbol_arity(definition, module); + + emit_get_symbol_name_for_tag(definition, module); + emit_visit_children(definition, module); + + emit_layouts(definition, module); + + emit_inj_tags(definition, module); + + emit_sort_table(definition, module); + emit_return_sort_table(definition, module); + emit_symbol_is_instantiation(definition, module); } } // namespace kllvm diff --git a/lib/codegen/Metadata.cpp b/lib/codegen/Metadata.cpp index 3c0e0c969..88a332744 100644 --- a/lib/codegen/Metadata.cpp +++ b/lib/codegen/Metadata.cpp @@ -10,11 +10,11 @@ namespace kllvm { namespace { -std::string KOMPILED_DIR = "kompiled_directory"; -std::string STRICT_BYTES = "enable_mutable_bytes"; -std::string SAFE_PARTIAL = "safe_partial"; +std::string kompiled_dir = "kompiled_directory"; +std::string strict_bytes = "enable_mutable_bytes"; +std::string safe_partial = "safe_partial"; -void addBooleanFlag( +void add_boolean_flag( llvm::Module &mod, std::string const &name, bool enabled, bool debug) { auto &ctx = mod.getContext(); @@ -29,19 +29,19 @@ void addBooleanFlag( } if (debug) { - initDebugGlobal(STRICT_BYTES, getBoolDebugType(), global_var); + init_debug_global(strict_bytes, get_bool_debug_type(), global_var); } } } // namespace -void addKompiledDirSymbol( +void add_kompiled_dir_symbol( llvm::Module &mod, std::string const &dir, bool debug) { auto &ctx = mod.getContext(); auto *str = llvm::ConstantDataArray::getString(ctx, dir, true); - auto *global = mod.getOrInsertGlobal(KOMPILED_DIR, str->getType()); + auto *global = mod.getOrInsertGlobal(kompiled_dir, str->getType()); auto *global_var = llvm::cast(global); if (!global_var->hasInitializer()) { @@ -49,16 +49,16 @@ void addKompiledDirSymbol( } if (debug) { - initDebugGlobal(KOMPILED_DIR, getCharDebugType(), global_var); + init_debug_global(kompiled_dir, get_char_debug_type(), global_var); } } -void addMutableBytesFlag(llvm::Module &mod, bool enabled, bool debug) { - addBooleanFlag(mod, STRICT_BYTES, enabled, debug); +void add_mutable_bytes_flag(llvm::Module &mod, bool enabled, bool debug) { + add_boolean_flag(mod, strict_bytes, enabled, debug); } -void addSafePartialFlag(llvm::Module &mod, bool enabled, bool debug) { - addBooleanFlag(mod, SAFE_PARTIAL, enabled, debug); +void add_safe_partial_flag(llvm::Module &mod, bool enabled, bool debug) { + add_boolean_flag(mod, safe_partial, enabled, debug); } } // namespace kllvm diff --git a/lib/codegen/Options.cpp b/lib/codegen/Options.cpp index 5b51429c0..affc36395 100644 --- a/lib/codegen/Options.cpp +++ b/lib/codegen/Options.cpp @@ -2,58 +2,58 @@ using namespace llvm; -cl::OptionCategory CodegenLibCat("Internal codegen options"); +cl::OptionCategory codegen_lib_cat("Internal codegen options"); -cl::opt ProofHintInstrumentation( +cl::opt proof_hint_instrumentation( "proof-hint-instrumentation", llvm::cl::desc("Enable instrumentation for generation of proof hints"), - llvm::cl::cat(CodegenLibCat)); + llvm::cl::cat(codegen_lib_cat)); -cl::opt KeepFramePointer( +cl::opt keep_frame_pointer( "fno-omit-frame-pointer", cl::desc("Keep frame pointer in compiled code for debugging purposes"), - cl::cat(CodegenLibCat)); + cl::cat(codegen_lib_cat)); -cl::opt OptimizationLevel( +cl::opt optimization_level( cl::desc("Choose optimization level"), cl::values( clEnumVal(opt_level::O0, "No optimizations"), clEnumVal(opt_level::O1, "Enable trivial optimizations"), clEnumVal(opt_level::O2, "Enable default optimizations"), clEnumVal(opt_level::O3, "Enable expensive optimizations")), - cl::cat(CodegenLibCat)); + cl::cat(codegen_lib_cat)); -cl::opt Debug( +cl::opt debug( "debug", cl::desc("Enable debug information"), cl::ZeroOrMore, - cl::cat(CodegenLibCat)); + cl::cat(codegen_lib_cat)); -cl::opt NoOptimize( +cl::opt no_optimize( "no-optimize", cl::desc("Don't run optimization passes before producing output"), - cl::cat(CodegenLibCat)); + cl::cat(codegen_lib_cat)); -cl::opt EmitObject( +cl::opt emit_object( "emit-object", cl::desc("Directly emit an object file to avoid separately invoking llc"), - cl::cat(CodegenLibCat)); + cl::cat(codegen_lib_cat)); -cl::opt BinaryIR( +cl::opt binary_ir( "binary-ir", cl::desc("Emit binary IR rather than text"), - cl::cat(CodegenLibCat)); + cl::cat(codegen_lib_cat)); -cl::opt ForceBinary( +cl::opt force_binary( "f", cl::desc("Force binary bitcode output to stdout"), cl::Hidden, - cl::cat(CodegenLibCat)); + cl::cat(codegen_lib_cat)); namespace kllvm { void validate_codegen_args(bool is_tty) { - if (EmitObject && (BinaryIR || NoOptimize)) { + if (emit_object && (binary_ir || no_optimize)) { throw std::runtime_error( "Cannot specify --emit-object with --binary-ir or --no-optimize"); } - if ((EmitObject || BinaryIR) && is_tty && !ForceBinary) { + if ((emit_object || binary_ir) && is_tty && !force_binary) { throw std::runtime_error( "Not printing binary file to stdout; use -o to specify output path " "or force binary with -f\n"); diff --git a/lib/codegen/ProofEvent.cpp b/lib/codegen/ProofEvent.cpp index 603712a47..3fac99829 100644 --- a/lib/codegen/ProofEvent.cpp +++ b/lib/codegen/ProofEvent.cpp @@ -18,201 +18,206 @@ namespace kllvm { namespace { template -llvm::Constant *createGlobalSortStringPtr( - IRBuilder &B, KORECompositeSort &sort, llvm::Module *mod) { - return B.CreateGlobalStringPtr( - ast_to_string(sort), fmt::format("{}_str", sort.getName()), 0, mod); +llvm::Constant *create_global_sort_string_ptr( + IRBuilder &b, kore_composite_sort &sort, llvm::Module *mod) { + return b.CreateGlobalStringPtr( + ast_to_string(sort), fmt::format("{}_str", sort.get_name()), 0, mod); } } // namespace -llvm::CallInst *ProofEvent::emitSerializeTerm( - KORECompositeSort &sort, llvm::Value *outputFile, llvm::Value *term, - llvm::BasicBlock *insertAtEnd) { - auto B = llvm::IRBuilder(insertAtEnd); +llvm::CallInst *proof_event::emit_serialize_term( + kore_composite_sort &sort, llvm::Value *output_file, llvm::Value *term, + llvm::BasicBlock *insert_at_end) { + auto b = llvm::IRBuilder(insert_at_end); - auto cat = sort.getCategory(Definition); - auto *sort_name_ptr = createGlobalSortStringPtr(B, sort, Module); + auto cat = sort.get_category(definition_); + auto *sort_name_ptr = create_global_sort_string_ptr(b, sort, module_); - auto *void_ty = llvm::Type::getVoidTy(Ctx); - auto *i8_ptr_ty = llvm::Type::getInt8PtrTy(Ctx); - auto *i1_ty = llvm::Type::getInt1Ty(Ctx); + auto *void_ty = llvm::Type::getVoidTy(ctx_); + auto *i8_ptr_ty = llvm::Type::getInt8PtrTy(ctx_); + auto *i1_ty = llvm::Type::getInt1Ty(ctx_); - if (cat.cat == SortCategory::Symbol || cat.cat == SortCategory::Variable) { - auto *block_ty = getValueType({SortCategory::Symbol, 0}, Module); + if (cat.cat == sort_category::Symbol || cat.cat == sort_category::Variable) { + auto *block_ty = getvalue_type({sort_category::Symbol, 0}, module_); auto *func_ty = llvm::FunctionType::get( void_ty, {i8_ptr_ty, block_ty, i8_ptr_ty, i1_ty}, false); auto *serialize - = getOrInsertFunction(Module, "serializeTermToFile", func_ty); + = get_or_insert_function(module_, "serialize_term_to_file", func_ty); - return B.CreateCall( + return b.CreateCall( serialize, - {outputFile, term, sort_name_ptr, llvm::ConstantInt::getFalse(Ctx)}); + {output_file, term, sort_name_ptr, llvm::ConstantInt::getFalse(ctx_)}); } if (term->getType()->isIntegerTy()) { - term = B.CreateIntToPtr(term, i8_ptr_ty); + term = b.CreateIntToPtr(term, i8_ptr_ty); } else { - term = B.CreatePointerCast(term, i8_ptr_ty); + term = b.CreatePointerCast(term, i8_ptr_ty); } auto *func_ty = llvm::FunctionType::get( void_ty, {i8_ptr_ty, i8_ptr_ty, i8_ptr_ty, i1_ty}, false); auto *serialize - = getOrInsertFunction(Module, "serializeRawTermToFile", func_ty); + = get_or_insert_function(module_, "serialize_raw_term_to_file", func_ty); - return B.CreateCall( + return b.CreateCall( serialize, - {outputFile, term, sort_name_ptr, llvm::ConstantInt::getFalse(Ctx)}); + {output_file, term, sort_name_ptr, llvm::ConstantInt::getFalse(ctx_)}); } -llvm::CallInst *ProofEvent::emitSerializeConfiguration( - llvm::Value *outputFile, llvm::Value *config, - llvm::BasicBlock *insertAtEnd) { - auto *void_ty = llvm::Type::getVoidTy(Ctx); - auto *i8_ptr_ty = llvm::Type::getInt8PtrTy(Ctx); - auto *block_ty = getValueType({SortCategory::Symbol, 0}, Module); - auto *i1_ty = llvm::Type::getInt1Ty(Ctx); +llvm::CallInst *proof_event::emit_serialize_configuration( + llvm::Value *output_file, llvm::Value *config, + llvm::BasicBlock *insert_at_end) { + auto *void_ty = llvm::Type::getVoidTy(ctx_); + auto *i8_ptr_ty = llvm::Type::getInt8PtrTy(ctx_); + auto *block_ty = getvalue_type({sort_category::Symbol, 0}, module_); + auto *i1_ty = llvm::Type::getInt1Ty(ctx_); auto *func_ty = llvm::FunctionType::get( void_ty, {i8_ptr_ty, block_ty, i1_ty, i1_ty}, false); - auto *serialize - = getOrInsertFunction(Module, "serializeConfigurationToFile", func_ty); + auto *serialize = get_or_insert_function( + module_, "serialize_configuration_to_file", func_ty); return llvm::CallInst::Create( serialize, - {outputFile, config, llvm::ConstantInt::getTrue(Ctx), - llvm::ConstantInt::getFalse(Ctx)}, - "", insertAtEnd); + {output_file, config, llvm::ConstantInt::getTrue(ctx_), + llvm::ConstantInt::getFalse(ctx_)}, + "", insert_at_end); } -llvm::CallInst *ProofEvent::emitWriteUInt64( - llvm::Value *outputFile, uint64_t value, llvm::BasicBlock *insertAtEnd) { - auto *void_ty = llvm::Type::getVoidTy(Ctx); - auto *i8_ptr_ty = llvm::Type::getInt8PtrTy(Ctx); - auto *i64_ptr_ty = llvm::Type::getInt64Ty(Ctx); +llvm::CallInst *proof_event::emit_write_uint64( + llvm::Value *output_file, uint64_t value, llvm::BasicBlock *insert_at_end) { + auto *void_ty = llvm::Type::getVoidTy(ctx_); + auto *i8_ptr_ty = llvm::Type::getInt8PtrTy(ctx_); + auto *i64_ptr_ty = llvm::Type::getInt64Ty(ctx_); auto *func_ty = llvm::FunctionType::get(void_ty, {i8_ptr_ty, i64_ptr_ty}, false); - auto *func = getOrInsertFunction(Module, "writeUInt64ToFile", func_ty); + auto *func = get_or_insert_function(module_, "write_uint64_to_file", func_ty); auto *i64_value = llvm::ConstantInt::get(i64_ptr_ty, value); - return llvm::CallInst::Create(func, {outputFile, i64_value}, "", insertAtEnd); + return llvm::CallInst::Create( + func, {output_file, i64_value}, "", insert_at_end); } -llvm::CallInst *ProofEvent::emitWriteString( - llvm::Value *outputFile, std::string const &str, - llvm::BasicBlock *insertAtEnd) { - auto B = llvm::IRBuilder(insertAtEnd); +llvm::CallInst *proof_event::emit_write_string( + llvm::Value *output_file, std::string const &str, + llvm::BasicBlock *insert_at_end) { + auto b = llvm::IRBuilder(insert_at_end); - auto *void_ty = llvm::Type::getVoidTy(Ctx); - auto *i8_ptr_ty = llvm::Type::getInt8PtrTy(Ctx); + auto *void_ty = llvm::Type::getVoidTy(ctx_); + auto *i8_ptr_ty = llvm::Type::getInt8PtrTy(ctx_); auto *func_ty = llvm::FunctionType::get(void_ty, {i8_ptr_ty, i8_ptr_ty}, false); - auto *print = getOrInsertFunction(Module, "printVariableToFile", func_ty); + auto *print + = get_or_insert_function(module_, "print_variable_to_file", func_ty); - auto *varname = B.CreateGlobalStringPtr(str, "", 0, Module); - return B.CreateCall(print, {outputFile, varname}); + auto *varname = b.CreateGlobalStringPtr(str, "", 0, module_); + return b.CreateCall(print, {output_file, varname}); } -llvm::BinaryOperator *ProofEvent::emitNoOp(llvm::BasicBlock *insertAtEnd) { - auto *i8_ty = llvm::Type::getInt8Ty(Ctx); +llvm::BinaryOperator *proof_event::emit_no_op(llvm::BasicBlock *insert_at_end) { + auto *i8_ty = llvm::Type::getInt8Ty(ctx_); auto *zero = llvm::ConstantInt::get(i8_ty, 0); return llvm::BinaryOperator::Create( - llvm::Instruction::Add, zero, zero, "no-op", insertAtEnd); + llvm::Instruction::Add, zero, zero, "no-op", insert_at_end); } llvm::LoadInst * -ProofEvent::emitGetOutputFileName(llvm::BasicBlock *insertAtEnd) { - auto *i8_ptr_ty = llvm::Type::getInt8PtrTy(Ctx); - auto *fileNamePointer = Module->getOrInsertGlobal("output_file", i8_ptr_ty); - return new llvm::LoadInst(i8_ptr_ty, fileNamePointer, "output", insertAtEnd); +proof_event::emit_get_output_file_name(llvm::BasicBlock *insert_at_end) { + auto *i8_ptr_ty = llvm::Type::getInt8PtrTy(ctx_); + auto *file_name_pointer + = module_->getOrInsertGlobal("output_file", i8_ptr_ty); + return new llvm::LoadInst( + i8_ptr_ty, file_name_pointer, "output", insert_at_end); } -std::pair ProofEvent::proofBranch( - std::string const &label, llvm::BasicBlock *insertAtEnd) { - auto *i1_ty = llvm::Type::getInt1Ty(Ctx); +std::pair proof_event::proof_branch( + std::string const &label, llvm::BasicBlock *insert_at_end) { + auto *i1_ty = llvm::Type::getInt1Ty(ctx_); - auto *proof_output_flag = Module->getOrInsertGlobal("proof_output", i1_ty); + auto *proof_output_flag = module_->getOrInsertGlobal("proof_output", i1_ty); auto *proof_output = new llvm::LoadInst( - i1_ty, proof_output_flag, "proof_output", insertAtEnd); + i1_ty, proof_output_flag, "proof_output", insert_at_end); - auto *f = insertAtEnd->getParent(); + auto *f = insert_at_end->getParent(); auto *true_block - = llvm::BasicBlock::Create(Ctx, fmt::format("if_{}", label), f); + = llvm::BasicBlock::Create(ctx_, fmt::format("if_{}", label), f); auto *merge_block - = llvm::BasicBlock::Create(Ctx, fmt::format("tail_{}", label), f); + = llvm::BasicBlock::Create(ctx_, fmt::format("tail_{}", label), f); - emitNoOp(merge_block); + emit_no_op(merge_block); - llvm::BranchInst::Create(true_block, merge_block, proof_output, insertAtEnd); + llvm::BranchInst::Create( + true_block, merge_block, proof_output, insert_at_end); return {true_block, merge_block}; } std::tuple -ProofEvent::eventPrelude( - std::string const &label, llvm::BasicBlock *insertAtEnd) { - auto [true_block, merge_block] = proofBranch(label, insertAtEnd); - return {true_block, merge_block, emitGetOutputFileName(true_block)}; +proof_event::event_prelude( + std::string const &label, llvm::BasicBlock *insert_at_end) { + auto [true_block, merge_block] = proof_branch(label, insert_at_end); + return {true_block, merge_block, emit_get_output_file_name(true_block)}; } /* * Hook Events */ -llvm::BasicBlock *ProofEvent::hookEvent_pre( +llvm::BasicBlock *proof_event::hook_event_pre( std::string const &name, llvm::BasicBlock *current_block, - std::string const &locationStack) { - if (!ProofHintInstrumentation) { + std::string const &location_stack) { + if (!proof_hint_instrumentation) { return current_block; } auto [true_block, merge_block, outputFile] - = eventPrelude("hookpre", current_block); + = event_prelude("hookpre", current_block); - emitWriteUInt64(outputFile, detail::word(0xAA), true_block); - emitWriteString(outputFile, name, true_block); - emitWriteString(outputFile, locationStack, true_block); + emit_write_uint64(outputFile, detail::word(0xAA), true_block); + emit_write_string(outputFile, name, true_block); + emit_write_string(outputFile, location_stack, true_block); llvm::BranchInst::Create(merge_block, true_block); return merge_block; } -llvm::BasicBlock *ProofEvent::hookEvent_post( - llvm::Value *val, KORECompositeSort *sort, +llvm::BasicBlock *proof_event::hook_event_post( + llvm::Value *val, kore_composite_sort *sort, llvm::BasicBlock *current_block) { - if (!ProofHintInstrumentation) { + if (!proof_hint_instrumentation) { return current_block; } auto [true_block, merge_block, outputFile] - = eventPrelude("hookpost", current_block); + = event_prelude("hookpost", current_block); - emitWriteUInt64(outputFile, detail::word(0xBB), true_block); + emit_write_uint64(outputFile, detail::word(0xBB), true_block); - emitSerializeTerm(*sort, outputFile, val, true_block); + emit_serialize_term(*sort, outputFile, val, true_block); llvm::BranchInst::Create(merge_block, true_block); return merge_block; } -llvm::BasicBlock *ProofEvent::hookArg( - llvm::Value *val, KORECompositeSort *sort, +llvm::BasicBlock *proof_event::hook_arg( + llvm::Value *val, kore_composite_sort *sort, llvm::BasicBlock *current_block) { - if (!ProofHintInstrumentation) { + if (!proof_hint_instrumentation) { return current_block; } auto [true_block, merge_block, outputFile] - = eventPrelude("hookarg", current_block); + = event_prelude("hookarg", current_block); - emitSerializeTerm(*sort, outputFile, val, true_block); + emit_serialize_term(*sort, outputFile, val, true_block); llvm::BranchInst::Create(merge_block, true_block); return merge_block; @@ -222,53 +227,53 @@ llvm::BasicBlock *ProofEvent::hookArg( * Rewrite Events */ -llvm::BasicBlock *ProofEvent::rewriteEvent_pre( - KOREAxiomDeclaration *axiom, uint64_t arity, - std::map vars, +llvm::BasicBlock *proof_event::rewrite_event_pre( + kore_axiom_declaration *axiom, uint64_t arity, + std::map vars, llvm::StringMap const &subst, llvm::BasicBlock *current_block) { - if (!ProofHintInstrumentation) { + if (!proof_hint_instrumentation) { return current_block; } auto [true_block, merge_block, outputFile] - = eventPrelude("rewrite_pre", current_block); + = event_prelude("rewrite_pre", current_block); - emitWriteUInt64(outputFile, detail::word(0x22), true_block); - emitWriteUInt64(outputFile, axiom->getOrdinal(), true_block); - emitWriteUInt64(outputFile, arity, true_block); + emit_write_uint64(outputFile, detail::word(0x22), true_block); + emit_write_uint64(outputFile, axiom->get_ordinal(), true_block); + emit_write_uint64(outputFile, arity, true_block); for (auto entry = subst.begin(); entry != subst.end(); ++entry) { auto key = entry->getKey(); auto *val = entry->getValue(); auto *var = vars[key.str()]; - auto sort = std::dynamic_pointer_cast(var->getSort()); + auto sort = std::dynamic_pointer_cast(var->get_sort()); - emitWriteString(outputFile, key.str(), true_block); - emitSerializeTerm(*sort, outputFile, val, true_block); - emitWriteUInt64(outputFile, detail::word(0xCC), true_block); + emit_write_string(outputFile, key.str(), true_block); + emit_serialize_term(*sort, outputFile, val, true_block); + emit_write_uint64(outputFile, detail::word(0xCC), true_block); } llvm::BranchInst::Create(merge_block, true_block); return merge_block; } -llvm::BasicBlock *ProofEvent::rewriteEvent_post( - KOREAxiomDeclaration *axiom, llvm::Value *return_value, +llvm::BasicBlock *proof_event::rewrite_event_post( + kore_axiom_declaration *axiom, llvm::Value *return_value, llvm::BasicBlock *current_block) { - if (!ProofHintInstrumentation) { + if (!proof_hint_instrumentation) { return current_block; } auto [true_block, merge_block, output_file] - = eventPrelude("rewrite_post", current_block); + = event_prelude("rewrite_post", current_block); - auto return_sort = std::dynamic_pointer_cast( - axiom->getRightHandSide()->getSort()); + auto return_sort = std::dynamic_pointer_cast( + axiom->get_right_hand_side()->get_sort()); - emitWriteUInt64(output_file, detail::word(0xFF), true_block); - emitSerializeTerm(*return_sort, output_file, return_value, true_block); - emitWriteUInt64(output_file, detail::word(0xCC), true_block); + emit_write_uint64(output_file, detail::word(0xFF), true_block); + emit_serialize_term(*return_sort, output_file, return_value, true_block); + emit_write_uint64(output_file, detail::word(0xCC), true_block); llvm::BranchInst::Create(merge_block, true_block); return merge_block; @@ -278,73 +283,73 @@ llvm::BasicBlock *ProofEvent::rewriteEvent_post( * Function Events */ -llvm::BasicBlock *ProofEvent::functionEvent_pre( - llvm::BasicBlock *current_block, KORECompositePattern *pattern, - std::string const &locationStack) { - if (!ProofHintInstrumentation) { +llvm::BasicBlock *proof_event::function_event_pre( + llvm::BasicBlock *current_block, kore_composite_pattern *pattern, + std::string const &location_stack) { + if (!proof_hint_instrumentation) { return current_block; } auto [true_block, merge_block, outputFile] - = eventPrelude("function_pre", current_block); + = event_prelude("function_pre", current_block); - emitWriteUInt64(outputFile, detail::word(0xDD), true_block); - emitWriteString( - outputFile, ast_to_string(*pattern->getConstructor()), true_block); - emitWriteString(outputFile, locationStack, true_block); + emit_write_uint64(outputFile, detail::word(0xDD), true_block); + emit_write_string( + outputFile, ast_to_string(*pattern->get_constructor()), true_block); + emit_write_string(outputFile, location_stack, true_block); llvm::BranchInst::Create(merge_block, true_block); return merge_block; } llvm::BasicBlock * -ProofEvent::functionEvent_post(llvm::BasicBlock *current_block) { - if (!ProofHintInstrumentation) { +proof_event::function_event_post(llvm::BasicBlock *current_block) { + if (!proof_hint_instrumentation) { return current_block; } auto [true_block, merge_block, outputFile] - = eventPrelude("function_post", current_block); + = event_prelude("function_post", current_block); - emitWriteUInt64(outputFile, detail::word(0x11), true_block); + emit_write_uint64(outputFile, detail::word(0x11), true_block); llvm::BranchInst::Create(merge_block, true_block); return merge_block; } -llvm::BasicBlock *ProofEvent::sideConditionEvent_pre( - KOREAxiomDeclaration *axiom, std::vector const &args, +llvm::BasicBlock *proof_event::side_condition_event_pre( + kore_axiom_declaration *axiom, std::vector const &args, llvm::BasicBlock *current_block) { - if (!ProofHintInstrumentation) { + if (!proof_hint_instrumentation) { return current_block; } auto [true_block, merge_block, outputFile] - = eventPrelude("side_condition_pre", current_block); + = event_prelude("side_condition_pre", current_block); - size_t ordinal = axiom->getOrdinal(); + size_t ordinal = axiom->get_ordinal(); size_t arity = args.size(); - emitWriteUInt64(outputFile, detail::word(0xEE), true_block); - emitWriteUInt64(outputFile, ordinal, true_block); - emitWriteUInt64(outputFile, arity, true_block); + emit_write_uint64(outputFile, detail::word(0xEE), true_block); + emit_write_uint64(outputFile, ordinal, true_block); + emit_write_uint64(outputFile, arity, true_block); - KOREPattern *pattern = axiom->getRequires(); - std::map vars; - pattern->markVariables(vars); + kore_pattern *pattern = axiom->get_requires(); + std::map vars; + pattern->mark_variables(vars); int i = 0; for (auto entry = vars.begin(); entry != vars.end(); ++i, ++entry) { - auto varName = entry->first; + auto var_name = entry->first; auto *var = entry->second; auto *val = args[i]; - auto sort = std::dynamic_pointer_cast(var->getSort()); + auto sort = std::dynamic_pointer_cast(var->get_sort()); - emitWriteString(outputFile, varName, true_block); - emitSerializeTerm(*sort, outputFile, val, true_block); - emitWriteUInt64(outputFile, detail::word(0xCC), true_block); + emit_write_string(outputFile, var_name, true_block); + emit_serialize_term(*sort, outputFile, val, true_block); + emit_write_uint64(outputFile, detail::word(0xCC), true_block); } llvm::BranchInst::Create(merge_block, true_block); @@ -352,25 +357,25 @@ llvm::BasicBlock *ProofEvent::sideConditionEvent_pre( return merge_block; } -llvm::BasicBlock *ProofEvent::sideConditionEvent_post( - KOREAxiomDeclaration *axiom, llvm::Value *check_result, +llvm::BasicBlock *proof_event::side_condition_event_post( + kore_axiom_declaration *axiom, llvm::Value *check_result, llvm::BasicBlock *current_block) { - if (!ProofHintInstrumentation) { + if (!proof_hint_instrumentation) { return current_block; } auto [true_block, merge_block, outputFile] - = eventPrelude("side_condition_post", current_block); + = event_prelude("side_condition_post", current_block); - size_t ordinal = axiom->getOrdinal(); + size_t ordinal = axiom->get_ordinal(); - auto check_result_sort = std::dynamic_pointer_cast( - axiom->getRequires()->getSort()); + auto check_result_sort = std::dynamic_pointer_cast( + axiom->get_requires()->get_sort()); - emitWriteUInt64(outputFile, detail::word(0x33), true_block); - emitWriteUInt64(outputFile, ordinal, true_block); - emitSerializeTerm(*check_result_sort, outputFile, check_result, true_block); - emitWriteUInt64(outputFile, detail::word(0xCC), true_block); + emit_write_uint64(outputFile, detail::word(0x33), true_block); + emit_write_uint64(outputFile, ordinal, true_block); + emit_serialize_term(*check_result_sort, outputFile, check_result, true_block); + emit_write_uint64(outputFile, detail::word(0xCC), true_block); llvm::BranchInst::Create(merge_block, true_block); diff --git a/lib/codegen/Util.cpp b/lib/codegen/Util.cpp index c0c2d48d9..d87cba163 100644 --- a/lib/codegen/Util.cpp +++ b/lib/codegen/Util.cpp @@ -14,12 +14,12 @@ namespace kllvm { -llvm::Function *koreHeapAlloc(std::string const &name, llvm::Module *module) { +llvm::Function *kore_heap_alloc(std::string const &name, llvm::Module *module) { llvm::Type *size_type = llvm::Type::getInt64Ty(module->getContext()); - auto *allocType = llvm::FunctionType::get( + auto *alloc_type = llvm::FunctionType::get( llvm::Type::getInt8PtrTy(module->getContext()), llvm::ArrayRef(size_type), false); - return getOrInsertFunction(module, name, allocType); + return get_or_insert_function(module, name, alloc_type); } } // namespace kllvm diff --git a/lib/parser/KOREParser.cpp b/lib/parser/KOREParser.cpp index a9a9c1e8e..122ba2c87 100644 --- a/lib/parser/KOREParser.cpp +++ b/lib/parser/KOREParser.cpp @@ -11,439 +11,440 @@ namespace kllvm::parser { -std::unique_ptr KOREParser::from_string(std::string const &text) { +std::unique_ptr kore_parser::from_string(std::string const &text) { auto temp_file = temporary_file("tmp.parse.XXXXXX"); temp_file.ofstream() << text; - auto parser = std::make_unique(temp_file.filename()); + auto parser = std::make_unique(temp_file.filename()); return parser; } -void KOREParser::error(location const &loc, std::string const &err_message) { +void kore_parser::error(location const &loc, std::string const &err_message) { std::cerr << "Syntax error at " << loc << ": " << err_message << "\n"; exit(-1); } static std::string str(token tok) { switch (tok) { - case token::EMPTY: abort(); - case token::MODULE: return "module"; - case token::ENDMODULE: return "endmodule"; - case token::IMPORT: return "import"; - case token::SORT: return "sort"; - case token::SYMBOL: return "symbol"; - case token::WHERE: return "where"; - case token::ALIAS: return "alias"; - case token::AXIOM: return "axiom"; - case token::CLAIM: return "claim"; - case token::HOOKEDSORT: return "hooked-sort"; - case token::HOOKEDSYMBOL: return "hooked-symbol"; - case token::COLON: return ":"; - case token::LEFTBRACE: return "{"; - case token::RIGHTBRACE: return "}"; - case token::LEFTBRACKET: return "["; - case token::RIGHTBRACKET: return "]"; - case token::LEFTPAREN: return "("; - case token::RIGHTPAREN: return ")"; - case token::COMMA: return ","; - case token::COLONEQUAL: return ":="; - case token::ID: return ""; - case token::STRING: return ""; - case token::TOKEN_EOF: return ""; + case token::Empty: abort(); + case token::Module: return "module"; + case token::EndModule: return "endmodule"; + case token::Import: return "import"; + case token::Sort: return "sort"; + case token::Symbol: return "symbol"; + case token::Where: return "where"; + case token::Alias: return "alias"; + case token::Axiom: return "axiom"; + case token::Claim: return "claim"; + case token::HookedSort: return "hooked-sort"; + case token::HookedSymbol: return "hooked-symbol"; + case token::Colon: return ":"; + case token::LeftBrace: return "{"; + case token::RightBrace: return "}"; + case token::LeftBracket: return "["; + case token::RightBracket: return "]"; + case token::LeftParen: return "("; + case token::RightParen: return ")"; + case token::Comma: return ","; + case token::ColonEqual: return ":="; + case token::Id: return ""; + case token::String: return ""; + case token::TokenEof: return ""; default: abort(); } } -std::string KOREParser::consume(token next) { +std::string kore_parser::consume(token next) { std::string data; - token actual = token::EMPTY; - if (buffer.tok == token::EMPTY) { - actual = scanner.yylex(&data, &loc); + token actual = token::Empty; + if (buffer_.tok == token::Empty) { + actual = scanner_.yylex(&data, &loc_); } else { - actual = buffer.tok; - data = buffer.data; - buffer.tok = token::EMPTY; + actual = buffer_.tok; + data = buffer_.data; + buffer_.tok = token::Empty; } if (actual == next) { return data; } - error(loc, "Expected: " + str(next) + " Actual: " + str(actual)); + error(loc_, "Expected: " + str(next) + " Actual: " + str(actual)); } -token KOREParser::peek() { +token kore_parser::peek() { std::string data; - if (buffer.tok == token::EMPTY) { - buffer.tok = scanner.yylex(&data, &loc); - buffer.data = data; + if (buffer_.tok == token::Empty) { + buffer_.tok = scanner_.yylex(&data, &loc_); + buffer_.data = data; } - return buffer.tok; + return buffer_.tok; } -ptr KOREParser::definition() { - consume(token::LEFTBRACKET); - auto result = KOREDefinition::Create(); +ptr kore_parser::definition() { + consume(token::LeftBracket); + auto result = kore_definition::create(); attributes(result.get()); - consume(token::RIGHTBRACKET); + consume(token::RightBracket); modules(result.get()); - consume(token::TOKEN_EOF); + consume(token::TokenEof); return result; } -sptr KOREParser::pattern() { - auto result = _pattern(); - consume(token::TOKEN_EOF); +sptr kore_parser::pattern() { + auto result = pattern_internal(); + consume(token::TokenEof); return result; } template -void KOREParser::attributes(Node *node) { - if (peek() == token::ID) { - attributesNE(node); +void kore_parser::attributes(Node *node) { + if (peek() == token::Id) { + attributes_ne(node); } } template -void KOREParser::attributesNE(Node *node) { - auto pat = _applicationPattern(); +void kore_parser::attributes_ne(Node *node) { + auto pat = application_pattern_internal(); node->attributes().add(std::move(pat)); - while (peek() == token::COMMA) { - consume(token::COMMA); - pat = _applicationPattern(); + while (peek() == token::Comma) { + consume(token::Comma); + pat = application_pattern_internal(); node->attributes().add(std::move(pat)); } } -void KOREParser::modules(KOREDefinition *node) { +void kore_parser::modules(kore_definition *node) { auto mod = module(); - node->addModule(std::move(mod)); - while (peek() == token::MODULE) { + node->add_module(std::move(mod)); + while (peek() == token::Module) { mod = module(); - node->addModule(std::move(mod)); + node->add_module(std::move(mod)); } } -ptr KOREParser::module() { - consume(token::MODULE); - std::string name = consume(token::ID); - auto mod = KOREModule::Create(name); +ptr kore_parser::module() { + consume(token::Module); + std::string name = consume(token::Id); + auto mod = kore_module::create(name); sentences(mod.get()); - consume(token::ENDMODULE); - consume(token::LEFTBRACKET); + consume(token::EndModule); + consume(token::LeftBracket); attributes(mod.get()); - consume(token::RIGHTBRACKET); + consume(token::RightBracket); return mod; } -void KOREParser::sentences(KOREModule *node) { - while (peek() != token::ENDMODULE) { +void kore_parser::sentences(kore_module *node) { + while (peek() != token::EndModule) { auto decl = sentence(); - node->addDeclaration(std::move(decl)); + node->add_declaration(std::move(decl)); } } -std::vector> KOREParser::declarations() { - std::vector> decls; - while (peek() != token::TOKEN_EOF) { +std::vector> kore_parser::declarations() { + std::vector> decls; + while (peek() != token::TokenEof) { auto decl = sentence(); decls.push_back(std::move(decl)); } return decls; } -ptr KOREParser::sentence() { +ptr kore_parser::sentence() { std::string name; token current = peek(); switch (current) { - case token::IMPORT: { - consume(token::IMPORT); - name = consume(token::ID); - auto import = KOREModuleImportDeclaration::Create(name); - consume(token::LEFTBRACKET); + case token::Import: { + consume(token::Import); + name = consume(token::Id); + auto import = kore_module_import_declaration::create(name); + consume(token::LeftBracket); attributes(import.get()); - consume(token::RIGHTBRACKET); + consume(token::RightBracket); return import; } - case token::SORT: - case token::HOOKEDSORT: { + case token::Sort: + case token::HookedSort: { consume(current); - name = consume(token::ID); - consume(token::LEFTBRACE); - auto sortDecl = KORECompositeSortDeclaration::Create( - name, current == token::HOOKEDSORT); - sortVariables(sortDecl.get()); - consume(token::RIGHTBRACE); - consume(token::LEFTBRACKET); - attributes(sortDecl.get()); - consume(token::RIGHTBRACKET); - return sortDecl; + name = consume(token::Id); + consume(token::LeftBrace); + auto sort_decl = kore_composite_sort_declaration::create( + name, current == token::HookedSort); + sort_variables(sort_decl.get()); + consume(token::RightBrace); + consume(token::LeftBracket); + attributes(sort_decl.get()); + consume(token::RightBracket); + return sort_decl; } - case token::SYMBOL: - case token::HOOKEDSYMBOL: { + case token::Symbol: + case token::HookedSymbol: { consume(current); - name = consume(token::ID); - consume(token::LEFTBRACE); + name = consume(token::Id); + consume(token::LeftBrace); auto symbol - = KORESymbolDeclaration::Create(name, current == token::HOOKEDSYMBOL); - sortVariables(symbol.get()); - consume(token::RIGHTBRACE); - consume(token::LEFTPAREN); - sorts(symbol->getSymbol()); - consume(token::RIGHTPAREN); - consume(token::COLON); - auto returnSort = sort(); - symbol->getSymbol()->addSort(std::move(returnSort)); - consume(token::LEFTBRACKET); + = kore_symbol_declaration::create(name, current == token::HookedSymbol); + sort_variables(symbol.get()); + consume(token::RightBrace); + consume(token::LeftParen); + sorts(symbol->get_symbol()); + consume(token::RightParen); + consume(token::Colon); + auto return_sort = sort(); + symbol->get_symbol()->add_sort(std::move(return_sort)); + consume(token::LeftBracket); attributes(symbol.get()); - consume(token::RIGHTBRACKET); + consume(token::RightBracket); return symbol; } - case token::ALIAS: { - consume(token::ALIAS); - name = consume(token::ID); - consume(token::LEFTBRACE); - auto alias = KOREAliasDeclaration::Create(name); - sortVariables(alias.get()); - consume(token::RIGHTBRACE); - consume(token::LEFTPAREN); - sorts(alias->getSymbol()); - consume(token::RIGHTPAREN); - consume(token::COLON); - auto returnSort = sort(); - alias->getSymbol()->addSort(std::move(returnSort)); - consume(token::WHERE); - auto variables = _applicationPattern(); - alias->addVariables(std::move(variables)); - consume(token::COLONEQUAL); - auto pat = _pattern(); - alias->addPattern(std::move(pat)); - consume(token::LEFTBRACKET); + case token::Alias: { + consume(token::Alias); + name = consume(token::Id); + consume(token::LeftBrace); + auto alias = kore_alias_declaration::create(name); + sort_variables(alias.get()); + consume(token::RightBrace); + consume(token::LeftParen); + sorts(alias->get_symbol()); + consume(token::RightParen); + consume(token::Colon); + auto return_sort = sort(); + alias->get_symbol()->add_sort(std::move(return_sort)); + consume(token::Where); + auto variables = application_pattern_internal(); + alias->add_variables(std::move(variables)); + consume(token::ColonEqual); + auto pat = pattern_internal(); + alias->add_pattern(std::move(pat)); + consume(token::LeftBracket); attributes(alias.get()); - consume(token::RIGHTBRACKET); + consume(token::RightBracket); return alias; } - case token::AXIOM: - case token::CLAIM: { + case token::Axiom: + case token::Claim: { consume(current); - consume(token::LEFTBRACE); - auto axiom = KOREAxiomDeclaration::Create(current == token::CLAIM); - sortVariables(axiom.get()); - consume(token::RIGHTBRACE); - auto pat = _pattern(); - axiom->addPattern(std::move(pat)); - consume(token::LEFTBRACKET); + consume(token::LeftBrace); + auto axiom = kore_axiom_declaration::create(current == token::Claim); + sort_variables(axiom.get()); + consume(token::RightBrace); + auto pat = pattern_internal(); + axiom->add_pattern(std::move(pat)); + consume(token::LeftBracket); attributes(axiom.get()); - consume(token::RIGHTBRACKET); + consume(token::RightBracket); return axiom; } default: error( - loc, "Expected: [import, sort, hooked-sort, symbol, hooked-symbol, " - "alias, axiom, claim] Actual: " - + str(current)); + loc_, "Expected: [import, sort, hooked-sort, symbol, hooked-symbol, " + "alias, axiom, claim] Actual: " + + str(current)); } } -void KOREParser::sortVariables(KOREDeclaration *node) { - if (peek() == token::ID) { - sortVariablesNE(node); +void kore_parser::sort_variables(kore_declaration *node) { + if (peek() == token::Id) { + sort_variables_ne(node); } } -void KOREParser::sortVariablesNE(KOREDeclaration *node) { - std::string name = consume(token::ID); - auto var = KORESortVariable::Create(name); - node->addObjectSortVariable(var); - while (peek() == token::COMMA) { - consume(token::COMMA); - name = consume(token::ID); - var = KORESortVariable::Create(name); - node->addObjectSortVariable(var); +void kore_parser::sort_variables_ne(kore_declaration *node) { + std::string name = consume(token::Id); + auto var = kore_sort_variable::create(name); + node->add_object_sort_variable(var); + while (peek() == token::Comma) { + consume(token::Comma); + name = consume(token::Id); + var = kore_sort_variable::create(name); + node->add_object_sort_variable(var); } } template -void KOREParser::sorts(Node *node) { - if (peek() == token::ID) { - sortsNE(node); +void kore_parser::sorts(Node *node) { + if (peek() == token::Id) { + sorts_ne(node); } } template -void KOREParser::sortsNE(Node *node) { - auto _sort = sort(); - node->addArgument(std::move(_sort)); - while (peek() == token::COMMA) { - consume(token::COMMA); - _sort = sort(); - node->addArgument(std::move(_sort)); +void kore_parser::sorts_ne(Node *node) { + auto s = sort(); + node->add_argument(std::move(s)); + while (peek() == token::Comma) { + consume(token::Comma); + s = sort(); + node->add_argument(std::move(s)); } } -std::pair>> -KOREParser::symbol_sort_list() { - auto ret = std::vector>{}; +std::pair>> +kore_parser::symbol_sort_list() { + auto ret = std::vector>{}; - auto id = consume(token::ID); - consume(token::LEFTBRACE); + auto id = consume(token::Id); + consume(token::LeftBrace); - if (peek() == token::ID) { + if (peek() == token::Id) { ret.push_back(sort()); - while (peek() == token::COMMA) { - consume(token::COMMA); + while (peek() == token::Comma) { + consume(token::Comma); ret.push_back(sort()); } } - consume(token::RIGHTBRACE); + consume(token::RightBrace); return {id, ret}; } -sptr KOREParser::sort() { - std::string name = consume(token::ID); - if (peek() == token::LEFTBRACE) { - consume(token::LEFTBRACE); - auto sort = KORECompositeSort::Create(name); +sptr kore_parser::sort() { + std::string name = consume(token::Id); + if (peek() == token::LeftBrace) { + consume(token::LeftBrace); + auto sort = kore_composite_sort::create(name); sorts(sort.get()); - consume(token::RIGHTBRACE); + consume(token::RightBrace); return sort; } - return KORESortVariable::Create(name); + return kore_sort_variable::create(name); } -sptr KOREParser::_pattern() { +sptr kore_parser::pattern_internal() { token current = peek(); switch (current) { - case token::ID: { - std::string name = consume(token::ID); + case token::Id: { + std::string name = consume(token::Id); current = peek(); switch (current) { - case token::COLON: - consume(token::COLON); - return KOREVariablePattern::Create(name, sort()); - case token::LEFTBRACE: return applicationPattern(name); - default: error(loc, "Expected: [:, {] Actual: " + str(current)); + case token::Colon: + consume(token::Colon); + return kore_variable_pattern::create(name, sort()); + case token::LeftBrace: return application_pattern(name); + default: error(loc_, "Expected: [:, {] Actual: " + str(current)); } } - case token::STRING: return KOREStringPattern::Create(consume(token::STRING)); - default: error(loc, "Expected: [, ] Actual: " + str(current)); + case token::String: + return kore_string_pattern::create(consume(token::String)); + default: error(loc_, "Expected: [, ] Actual: " + str(current)); } } -sptr KOREParser::applicationPattern() { - return applicationPattern(consume(token::ID)); +sptr kore_parser::application_pattern() { + return application_pattern(consume(token::Id)); } -ptr KOREParser::_applicationPattern() { - return _applicationPattern(consume(token::ID)); +ptr kore_parser::application_pattern_internal() { + return application_pattern_internal(consume(token::Id)); } -sptr KOREParser::applicationPattern(std::string const &name) { +sptr kore_parser::application_pattern(std::string const &name) { if (name == "\\left-assoc" || name == "\\right-assoc") { - consume(token::LEFTBRACE); - consume(token::RIGHTBRACE); - consume(token::LEFTPAREN); - std::string symbol = consume(token::ID); - consume(token::LEFTBRACE); - auto pat = KORECompositePattern::Create(symbol); - sorts(pat->getConstructor()); - pat->getConstructor()->initPatternArguments(); - consume(token::RIGHTBRACE); - consume(token::LEFTPAREN); - std::vector> pats; + consume(token::LeftBrace); + consume(token::RightBrace); + consume(token::LeftParen); + std::string symbol = consume(token::Id); + consume(token::LeftBrace); + auto pat = kore_composite_pattern::create(symbol); + sorts(pat->get_constructor()); + pat->get_constructor()->init_pattern_arguments(); + consume(token::RightBrace); + consume(token::LeftParen); + std::vector> pats; patterns(pats); - consume(token::RIGHTPAREN); - consume(token::RIGHTPAREN); + consume(token::RightParen); + consume(token::RightParen); if (name == "\\left-assoc") { - sptr accum = pats[0]; + sptr accum = pats[0]; for (auto i = 1U; i < pats.size(); i++) { - sptr newAccum - = KORECompositePattern::Create(pat->getConstructor()); - newAccum->addArgument(accum); - newAccum->addArgument(pats[i]); - accum = newAccum; + sptr new_accum + = kore_composite_pattern::create(pat->get_constructor()); + new_accum->add_argument(accum); + new_accum->add_argument(pats[i]); + accum = new_accum; } return accum; } - sptr accum = pats[pats.size() - 1]; + sptr accum = pats[pats.size() - 1]; for (int i = pats.size() - 2; i >= 0; i--) { - sptr newAccum - = KORECompositePattern::Create(pat->getConstructor()); - newAccum->addArgument(pats[i]); - newAccum->addArgument(accum); - accum = newAccum; + sptr new_accum + = kore_composite_pattern::create(pat->get_constructor()); + new_accum->add_argument(pats[i]); + new_accum->add_argument(accum); + accum = new_accum; } return accum; } - auto result = _applicationPattern(name); + auto result = application_pattern_internal(name); if (name == "\\or") { - if (result->getArguments().empty()) { - auto pat = KORECompositePattern::Create("\\bottom"); - pat->getConstructor()->addArgument( - result->getConstructor()->getFormalArguments()[0]); - pat->getConstructor()->initPatternArguments(); + if (result->get_arguments().empty()) { + auto pat = kore_composite_pattern::create("\\bottom"); + pat->get_constructor()->add_argument( + result->get_constructor()->get_formal_arguments()[0]); + pat->get_constructor()->init_pattern_arguments(); return pat; } - if (result->getArguments().size() == 1) { - return result->getArguments()[0]; + if (result->get_arguments().size() == 1) { + return result->get_arguments()[0]; } } else if (name == "\\and") { - if (result->getArguments().empty()) { - auto pat = KORECompositePattern::Create("\\top"); - pat->getConstructor()->addArgument( - result->getConstructor()->getFormalArguments()[0]); - pat->getConstructor()->initPatternArguments(); + if (result->get_arguments().empty()) { + auto pat = kore_composite_pattern::create("\\top"); + pat->get_constructor()->add_argument( + result->get_constructor()->get_formal_arguments()[0]); + pat->get_constructor()->init_pattern_arguments(); return pat; } - if (result->getArguments().size() == 1) { - return result->getArguments()[0]; + if (result->get_arguments().size() == 1) { + return result->get_arguments()[0]; } } return result; } -ptr -KOREParser::_applicationPattern(std::string const &name) { - consume(token::LEFTBRACE); - auto pat = KORECompositePattern::Create(name); - sorts(pat->getConstructor()); - pat->getConstructor()->initPatternArguments(); - consume(token::RIGHTBRACE); - consume(token::LEFTPAREN); +ptr +kore_parser::application_pattern_internal(std::string const &name) { + consume(token::LeftBrace); + auto pat = kore_composite_pattern::create(name); + sorts(pat->get_constructor()); + pat->get_constructor()->init_pattern_arguments(); + consume(token::RightBrace); + consume(token::LeftParen); patterns(pat.get()); - consume(token::RIGHTPAREN); + consume(token::RightParen); return pat; } -void KOREParser::patterns(KORECompositePattern *node) { - if (peek() == token::RIGHTPAREN) { +void kore_parser::patterns(kore_composite_pattern *node) { + if (peek() == token::RightParen) { return; } - patternsNE(node); + patterns_ne(node); } -void KOREParser::patternsNE(KORECompositePattern *node) { - auto pat = _pattern(); - node->addArgument(pat); - while (peek() == token::COMMA) { - consume(token::COMMA); - pat = _pattern(); - node->addArgument(pat); +void kore_parser::patterns_ne(kore_composite_pattern *node) { + auto pat = pattern_internal(); + node->add_argument(pat); + while (peek() == token::Comma) { + consume(token::Comma); + pat = pattern_internal(); + node->add_argument(pat); } } -void KOREParser::patterns(std::vector> &node) { - if (peek() == token::RIGHTPAREN) { +void kore_parser::patterns(std::vector> &node) { + if (peek() == token::RightParen) { return; } - patternsNE(node); + patterns_ne(node); } -void KOREParser::patternsNE(std::vector> &node) { - auto pat = _pattern(); +void kore_parser::patterns_ne(std::vector> &node) { + auto pat = pattern_internal(); node.push_back(pat); - while (peek() == token::COMMA) { - consume(token::COMMA); - pat = _pattern(); + while (peek() == token::Comma) { + consume(token::Comma); + pat = pattern_internal(); node.push_back(pat); } } diff --git a/lib/parser/KOREScanner.l b/lib/parser/KOREScanner.l index a6cf7ae4a..5d33ba2a4 100644 --- a/lib/parser/KOREScanner.l +++ b/lib/parser/KOREScanner.l @@ -8,7 +8,7 @@ using namespace kllvm::parser; #undef YY_DECL #define YY_DECL \ - token KOREScanner::yylex(std::string *lval, location *loc, yyscan_t yyscanner) + token kore_scanner::yylex(std::string *lval, location *loc, yyscan_t yyscanner) /* update location on matching */ #define YY_USER_ACTION loc->step(); loc->columns(yyleng); @@ -33,61 +33,61 @@ ident @?[a-zA-Z][a-zA-Z0-9'-]* %{ /* Code executed at the beginning of yylex */ -yyin = in; +yyin = in_; %} "\n" { loc->lines(); } [ \t\r] { /* nothing */ } -"module" { return token::MODULE; } -"endmodule" { return token::ENDMODULE; } -"import" { return token::IMPORT; } -"sort" { return token::SORT; } -"symbol" { return token::SYMBOL; } -"where" { return token::WHERE; } -"alias" { return token::ALIAS; } -"axiom" { return token::AXIOM; } -"claim" { return token::CLAIM; } -"hooked-sort" { return token::HOOKEDSORT; } -"hooked-symbol" { return token::HOOKEDSYMBOL; } - -":" { return token::COLON; } -"{" { return token::LEFTBRACE; } -"}" { return token::RIGHTBRACE; } -"[" { return token::LEFTBRACKET; } -"]" { return token::RIGHTBRACKET; } -"(" { return token::LEFTPAREN; } -")" { return token::RIGHTPAREN; } -"," { return token::COMMA; } -":=" { return token::COLONEQUAL; } +"module" { return token::Module; } +"endmodule" { return token::EndModule; } +"import" { return token::Import; } +"sort" { return token::Sort; } +"symbol" { return token::Symbol; } +"where" { return token::Where; } +"alias" { return token::Alias; } +"axiom" { return token::Axiom; } +"claim" { return token::Claim; } +"hooked-sort" { return token::HookedSort; } +"hooked-symbol" { return token::HookedSymbol; } + +":" { return token::Colon; } +"{" { return token::LeftBrace; } +"}" { return token::RightBrace; } +"[" { return token::LeftBracket; } +"]" { return token::RightBracket; } +"(" { return token::LeftParen; } +")" { return token::RightParen; } +"," { return token::Comma; } +":=" { return token::ColonEqual; } {ident} { *lval = std::string(yytext, yyleng); - return token::ID; + return token::Id; } "\\"{ident} { *lval = std::string(yytext, yyleng); - return token::ID; + return token::Id; } -"\"" { stringBuffer.clear(); BEGIN(STR); } -([\x20-\x7E]{-}[\"\\])* { stringBuffer.append(yytext); } -"\\n" { stringBuffer.push_back('\n'); loc->lines(); } -"\\r" { stringBuffer.push_back('\r'); loc->lines(); } -"\\t" { stringBuffer.push_back('\t'); loc->lines(); } -"\\f" { stringBuffer.push_back('\f'); loc->lines(); } -"\\\"" { stringBuffer.push_back('\"'); } -"\\\\" { stringBuffer.push_back('\\'); } -\\[0-9]{3} { stringBuffer.push_back((yytext[1] - '0') * 64 + (yytext[2] - '0') * 8 + yytext[3] - '0'); } -\\x[0-9a-fA-F]{2} { stringBuffer.push_back(strtol(yytext+2, NULL, 16)); } -\\u[0-9a-fA-F]{4} { stringBuffer.append(codepoint_to_utf8(strtoul(yytext+2, NULL, 16), *loc)); } -\\U[0-9a-fA-F]{8} { stringBuffer.append(codepoint_to_utf8(strtoul(yytext+2, NULL, 16), *loc)); } +"\"" { string_buffer_.clear(); BEGIN(STR); } +([\x20-\x7E]{-}[\"\\])* { string_buffer_.append(yytext); } +"\\n" { string_buffer_.push_back('\n'); loc->lines(); } +"\\r" { string_buffer_.push_back('\r'); loc->lines(); } +"\\t" { string_buffer_.push_back('\t'); loc->lines(); } +"\\f" { string_buffer_.push_back('\f'); loc->lines(); } +"\\\"" { string_buffer_.push_back('\"'); } +"\\\\" { string_buffer_.push_back('\\'); } +\\[0-9]{3} { string_buffer_.push_back((yytext[1] - '0') * 64 + (yytext[2] - '0') * 8 + yytext[3] - '0'); } +\\x[0-9a-fA-F]{2} { string_buffer_.push_back(strtol(yytext+2, NULL, 16)); } +\\u[0-9a-fA-F]{4} { string_buffer_.append(codepoint_to_utf8(strtoul(yytext+2, NULL, 16), *loc)); } +\\U[0-9a-fA-F]{8} { string_buffer_.append(codepoint_to_utf8(strtoul(yytext+2, NULL, 16), *loc)); } "\"" { BEGIN(INITIAL); - *lval = stringBuffer; - return token::STRING; + *lval = string_buffer_; + return token::String; } "/*" { BEGIN(COMM); } @@ -103,33 +103,33 @@ yyin = in; if(YYSTATE != INITIAL) error(*loc, "Either a comment or string hasn't been closed\n"); - return token::TOKEN_EOF; + return token::TokenEof; } <*>. { error(*loc, std::string("Unknown token \"") + yytext + std::string("\"\n")); } %% -KOREScanner::KOREScanner(std::string filename) { - if (!(in = fopen(filename.c_str(), "r"))) { +kore_scanner::kore_scanner(std::string filename) { + if (!(in_ = fopen(filename.c_str(), "r"))) { std::cerr << "Cannot read file: " << filename << "\n"; exit(1); } - yylex_init(&scanner); + yylex_init(&scanner_); } -KOREScanner::~KOREScanner() { - fclose(in); - yylex_destroy(scanner); +kore_scanner::~kore_scanner() { + fclose(in_); + yylex_destroy(scanner_); } -void KOREScanner::error( +void kore_scanner::error( const location &loc, const std::string &err_message) { std::cerr << "Scanner error at " << loc << ": " << err_message << "\n"; exit(-1); } -std::string KOREScanner::codepoint_to_utf8(unsigned long int code, +std::string kore_scanner::codepoint_to_utf8(unsigned long int code, const location &loc) { // Let xxxx... denote the bits of the code point if (code <= 0x7F) { @@ -170,22 +170,22 @@ std::string KOREScanner::codepoint_to_utf8(unsigned long int code, return ""; } -int KOREScanner::scan() { +int kore_scanner::scan() { token token; do { std::string sem; location loc(""); - token = yylex(&sem, &loc, scanner); + token = yylex(&sem, &loc, scanner_); std::string lexeme; switch (token) { - case token::ID: - case token::STRING: + case token::Id: + case token::String: lexeme = sem; break; default: - lexeme = yyget_text(scanner); + lexeme = yyget_text(scanner_); } - } while (token != token::TOKEN_EOF); + } while (token != token::TokenEof); return 0; } diff --git a/lib/printer/addBrackets.cpp b/lib/printer/addBrackets.cpp index 6017e3fc4..fe3b0fbdb 100644 --- a/lib/printer/addBrackets.cpp +++ b/lib/printer/addBrackets.cpp @@ -12,7 +12,7 @@ namespace kllvm { -enum Fixity { EMPTY = 0, BARE_LEFT = 1, BARE_RIGHT = 2, BARE_BOTH = 3 }; +enum fixity { EMPTY = 0, BareLeft = 1, BareRight = 2, BareBoth = 3 }; /** * Get the index of the Nth nonterminal within the list of all terminals and @@ -28,18 +28,18 @@ enum Fixity { EMPTY = 0, BARE_LEFT = 1, BARE_RIGHT = 2, BARE_BOTH = 3 }; * returns: the index of the nonterminal within the list of all nonterminals * and terminals of the production the symbol corresponds to. */ -int getNTPositionInProd(std::string terminals, int position) { - int terminalPos = 0; - int ntIdx = 0; - for (; terminalPos < terminals.size(); terminalPos++) { - if (terminals[terminalPos] == '0') { - if (ntIdx == position) { +int get_nt_position_in_prod(std::string terminals, int position) { + int terminal_pos = 0; + int nt_idx = 0; + for (; terminal_pos < terminals.size(); terminal_pos++) { + if (terminals[terminal_pos] == '0') { + if (nt_idx == position) { break; } - ntIdx++; + nt_idx++; } } - return terminalPos; + return terminal_pos; } /** @@ -48,7 +48,7 @@ int getNTPositionInProd(std::string terminals, int position) { * Out of bounds errors do not occur with this function: if the index is out of * range, `false` is returned, indicating there is not a terminal at that index */ -bool hasTerminalAtIdx(std::string terminals, int position) { +bool has_terminal_at_idx(std::string terminals, int position) { if (position < 0 || position >= terminals.length()) { return false; } @@ -72,17 +72,18 @@ bool hasTerminalAtIdx(std::string terminals, int position) { * nonterminal BARE_BOTH if there are not terminals on either side of this * nonterminal */ -Fixity getFixity(int position, KORESymbol *sym, PrettyPrintData const &data) { +fixity +get_fixity(int position, kore_symbol *sym, pretty_print_data const &data) { int result = EMPTY; - std::string terminals = data.terminals.at(sym->getName()); - int terminalPos = getNTPositionInProd(terminals, position); - if (!hasTerminalAtIdx(terminals, terminalPos + 1)) { - result |= BARE_RIGHT; + std::string terminals = data.terminals.at(sym->get_name()); + int terminal_pos = get_nt_position_in_prod(terminals, position); + if (!has_terminal_at_idx(terminals, terminal_pos + 1)) { + result |= BareRight; } - if (!hasTerminalAtIdx(terminals, terminalPos - 1)) { - result |= BARE_LEFT; + if (!has_terminal_at_idx(terminals, terminal_pos - 1)) { + result |= BareLeft; } - return (Fixity)result; + return (fixity)result; } /** @@ -99,16 +100,16 @@ Fixity getFixity(int position, KORESymbol *sym, PrettyPrintData const &data) { * production BARE_BOTH if there are not terminals on either edge of this * production */ -Fixity getFixity(KORESymbol *sym, PrettyPrintData const &data) { - auto const &name = sym->getName(); +fixity get_fixity(kore_symbol *sym, pretty_print_data const &data) { + auto const &name = sym->get_name(); int result = EMPTY; if (data.terminals.at(name)[0] == '0') { - result = result | BARE_LEFT; + result = result | BareLeft; } if (data.terminals.at(name)[data.terminals.at(name).size() - 1] == '0') { - result = result | BARE_RIGHT; + result = result | BareRight; } - return (Fixity)result; + return (fixity)result; } /** @@ -133,12 +134,13 @@ Fixity getFixity(KORESymbol *sym, PrettyPrintData const &data) { * * returns: the left capture of the term, or NULL if no such term exists */ -KORECompositePattern *getLeftCapture( - KORECompositePattern *previousLeftCapture, KORECompositePattern *outer, - int position, PrettyPrintData const &data) { - Fixity fixity = getFixity(outer->getConstructor(), data); - if (position == 0 && (fixity & BARE_LEFT)) { - return previousLeftCapture; +kore_composite_pattern *get_left_capture( + kore_composite_pattern *previous_left_capture, + kore_composite_pattern *outer, int position, + pretty_print_data const &data) { + fixity fixity = get_fixity(outer->get_constructor(), data); + if (position == 0 && (fixity & BareLeft)) { + return previous_left_capture; } return outer; @@ -167,12 +169,13 @@ KORECompositePattern *getLeftCapture( * returns: the right capture of the term, or NULL if no such term exists */ -KORECompositePattern *getRightCapture( - KORECompositePattern *previousRightCapture, KORECompositePattern *outer, - int position, PrettyPrintData const &data) { - Fixity fixity = getFixity(outer->getConstructor(), data); - if (position == outer->getArguments().size() - 1 && (fixity & BARE_RIGHT)) { - return previousRightCapture; +kore_composite_pattern *get_right_capture( + kore_composite_pattern *previous_right_capture, + kore_composite_pattern *outer, int position, + pretty_print_data const &data) { + fixity fixity = get_fixity(outer->get_constructor(), data); + if (position == outer->get_arguments().size() - 1 && (fixity & BareRight)) { + return previous_right_capture; } return outer; @@ -190,74 +193,74 @@ KORECompositePattern *getRightCapture( * * returns: s1 <= s2 */ -bool lessThanEq(PrettyPrintData const &data, KORESort *s1, KORESort *s2) { +bool less_than_eq(pretty_print_data const &data, kore_sort *s1, kore_sort *s2) { return *s1 == *s2 || (data.subsorts.contains(s1) && data.subsorts.at(s1).contains(s2)); } -sptr -getArgSort(KORESymbol *symbol, int position, sptr firstArgSort) { - if (!symbol->isBuiltin()) { - return symbol->getArguments()[position]; +sptr get_arg_sort( + kore_symbol *symbol, int position, sptr first_arg_sort) { + if (!symbol->is_builtin()) { + return symbol->get_arguments()[position]; } - if (symbol->getName() == "\\and" || symbol->getName() == "\\not" - || symbol->getName() == "\\or" || symbol->getName() == "\\implies" - || symbol->getName() == "\\iff" || symbol->getName() == "\\ceil" - || symbol->getName() == "\\floor" || symbol->getName() == "\\equals" - || symbol->getName() == "\\in" || symbol->getName() == "\\next" - || symbol->getName() == "\\rewrites" - || symbol->getName() == "weakAlwaysFinally" - || symbol->getName() == "weakExistsFinally" - || symbol->getName() == "allPathGlobally") { - return symbol->getFormalArguments()[0]; + if (symbol->get_name() == "\\and" || symbol->get_name() == "\\not" + || symbol->get_name() == "\\or" || symbol->get_name() == "\\implies" + || symbol->get_name() == "\\iff" || symbol->get_name() == "\\ceil" + || symbol->get_name() == "\\floor" || symbol->get_name() == "\\equals" + || symbol->get_name() == "\\in" || symbol->get_name() == "\\next" + || symbol->get_name() == "\\rewrites" + || symbol->get_name() == "weakAlwaysFinally" + || symbol->get_name() == "weakExistsFinally" + || symbol->get_name() == "allPathGlobally") { + return symbol->get_formal_arguments()[0]; } - if (symbol->getName() == "\\forall" || symbol->getName() == "\\exists") { + if (symbol->get_name() == "\\forall" || symbol->get_name() == "\\exists") { if (position == 0) { - assert(firstArgSort != nullptr); - return firstArgSort; + assert(first_arg_sort != nullptr); + return first_arg_sort; } - return symbol->getFormalArguments()[0]; + return symbol->get_formal_arguments()[0]; } - if (symbol->getName() == "\\mu" || symbol->getName() == "\\nu") { - assert(firstArgSort != nullptr); - return firstArgSort; + if (symbol->get_name() == "\\mu" || symbol->get_name() == "\\nu") { + assert(first_arg_sort != nullptr); + return first_arg_sort; } abort(); } -sptr getReturnSort(KOREPattern *pat) { - if (auto *composite = dynamic_cast(pat)) { - auto *symbol = composite->getConstructor(); - if (!symbol->isBuiltin()) { - return pat->getSort(); +sptr get_return_sort(kore_pattern *pat) { + if (auto *composite = dynamic_cast(pat)) { + auto *symbol = composite->get_constructor(); + if (!symbol->is_builtin()) { + return pat->get_sort(); } - if (symbol->getName() == "\\top" || symbol->getName() == "\\bottom" - || symbol->getName() == "\\and" || symbol->getName() == "\\not" - || symbol->getName() == "\\or" || symbol->getName() == "\\implies" - || symbol->getName() == "\\iff" || symbol->getName() == "\\exists" - || symbol->getName() == "\\forall" || symbol->getName() == "\\next" - || symbol->getName() == "\\rewrites" - || symbol->getName() == "weakAlwaysFinally" - || symbol->getName() == "weakExistsFinally" - || symbol->getName() == "allPathGlobally") { - return symbol->getFormalArguments()[0]; + if (symbol->get_name() == "\\top" || symbol->get_name() == "\\bottom" + || symbol->get_name() == "\\and" || symbol->get_name() == "\\not" + || symbol->get_name() == "\\or" || symbol->get_name() == "\\implies" + || symbol->get_name() == "\\iff" || symbol->get_name() == "\\exists" + || symbol->get_name() == "\\forall" || symbol->get_name() == "\\next" + || symbol->get_name() == "\\rewrites" + || symbol->get_name() == "weakAlwaysFinally" + || symbol->get_name() == "weakExistsFinally" + || symbol->get_name() == "allPathGlobally") { + return symbol->get_formal_arguments()[0]; } - if (symbol->getName() == "\\ceil" || symbol->getName() == "\\floor" - || symbol->getName() == "\\equals" || symbol->getName() == "\\in") { - return symbol->getFormalArguments()[1]; + if (symbol->get_name() == "\\ceil" || symbol->get_name() == "\\floor" + || symbol->get_name() == "\\equals" || symbol->get_name() == "\\in") { + return symbol->get_formal_arguments()[1]; } - if (symbol->getName() == "\\mu" || symbol->getName() == "\\nu") { - return composite->getArguments()[0]->getSort(); + if (symbol->get_name() == "\\mu" || symbol->get_name() == "\\nu") { + return composite->get_arguments()[0]->get_sort(); } abort(); } else { - return pat->getSort(); + return pat->get_sort(); } } @@ -278,33 +281,33 @@ sptr getReturnSort(KOREPattern *pat) { * returns: true if priority forbids `inner` to appear inside `outer` at that * position. */ -bool isPriorityWrong( - KORECompositePattern *outer, KORECompositePattern *inner, int position, - PrettyPrintData const &data) { - std::string outerName = outer->getConstructor()->getName(); - std::string innerName = inner->getConstructor()->getName(); - KORESort *innerSort = getReturnSort(inner).get(); - KORESort *outerSort = getArgSort( - outer->getConstructor(), position, - outer->getArguments()[0]->getSort()) - .get(); - if (!lessThanEq(data, innerSort, outerSort)) { +bool is_priority_wrong( + kore_composite_pattern *outer, kore_composite_pattern *inner, int position, + pretty_print_data const &data) { + std::string outer_name = outer->get_constructor()->get_name(); + std::string inner_name = inner->get_constructor()->get_name(); + kore_sort *inner_sort = get_return_sort(inner).get(); + kore_sort *outer_sort = get_arg_sort( + outer->get_constructor(), position, + outer->get_arguments()[0]->get_sort()) + .get(); + if (!less_than_eq(data, inner_sort, outer_sort)) { return true; } - if (data.priorities.contains(outerName) - && data.priorities.at(outerName).contains(innerName)) { + if (data.priorities.contains(outer_name) + && data.priorities.at(outer_name).contains(inner_name)) { return true; } - std::string terminals = data.terminals.at(outerName); - int terminalPos = getNTPositionInProd(terminals, position); - if (data.leftAssoc.contains(outerName) - && data.leftAssoc.at(outerName).contains(innerName) - && terminalPos == terminals.size() - 1) { + std::string terminals = data.terminals.at(outer_name); + int terminal_pos = get_nt_position_in_prod(terminals, position); + if (data.left_assoc.contains(outer_name) + && data.left_assoc.at(outer_name).contains(inner_name) + && terminal_pos == terminals.size() - 1) { return true; } - if (data.rightAssoc.contains(outerName) - && data.rightAssoc.at(outerName).contains(innerName) - && terminalPos == 0) { + if (data.right_assoc.contains(outer_name) + && data.right_assoc.at(outer_name).contains(inner_name) + && terminal_pos == 0) { return true; } return false; @@ -352,48 +355,51 @@ bool isPriorityWrong( * into them by this algorithm, even though they are required. */ // NOLINTNEXTLINE(*-cognitive-complexity) -bool requiresBracketWithSimpleAlgorithm( - KORECompositePattern *outer, KORECompositePattern *leftCapture, - KORECompositePattern *rightCapture, KOREPattern *inner, int position, - PrettyPrintData const &data) { - if (auto *composite = dynamic_cast(inner)) { - std::string innerName = composite->getConstructor()->getName(); - if (innerName == outer->getConstructor()->getName()) { - if (data.assoc.contains(innerName)) { +bool requires_bracket_with_simple_algorithm( + kore_composite_pattern *outer, kore_composite_pattern *left_capture, + kore_composite_pattern *right_capture, kore_pattern *inner, int position, + pretty_print_data const &data) { + if (auto *composite = dynamic_cast(inner)) { + std::string inner_name = composite->get_constructor()->get_name(); + if (inner_name == outer->get_constructor()->get_name()) { + if (data.assoc.contains(inner_name)) { return false; } } - if (innerName == "\\dv") { + if (inner_name == "\\dv") { return false; } - Fixity fixity = getFixity(position, outer->getConstructor(), data); + auto fixity = get_fixity(position, outer->get_constructor(), data); if (fixity == EMPTY) { return false; } - bool priority = isPriorityWrong(outer, composite, position, data); + bool priority = is_priority_wrong(outer, composite, position, data); if (priority) { return true; } - if (data.terminals.at(innerName) == "0") { + if (data.terminals.at(inner_name) == "0") { return false; } - Fixity innerFixity = getFixity(composite->getConstructor(), data); + auto inner_fixity = get_fixity(composite->get_constructor(), data); - if ((innerFixity & BARE_RIGHT) && rightCapture != nullptr) { - bool inversePriority = isPriorityWrong( - composite, rightCapture, composite->getArguments().size() - 1, data); - Fixity rightCaptureFixity - = getFixity(rightCapture->getConstructor(), data); - if (!inversePriority && (rightCaptureFixity & BARE_LEFT)) { + if ((inner_fixity & BareRight) && right_capture != nullptr) { + bool inverse_priority = is_priority_wrong( + composite, right_capture, composite->get_arguments().size() - 1, + data); + auto right_capture_fixity + = get_fixity(right_capture->get_constructor(), data); + if (!inverse_priority && (right_capture_fixity & BareLeft)) { return true; } } - if ((innerFixity & BARE_LEFT) && leftCapture != nullptr) { - bool inversePriority = isPriorityWrong(composite, leftCapture, 0, data); - Fixity leftCaptureFixity = getFixity(leftCapture->getConstructor(), data); - if (!inversePriority && (leftCaptureFixity & BARE_RIGHT)) { + if ((inner_fixity & BareLeft) && left_capture != nullptr) { + bool inverse_priority + = is_priority_wrong(composite, left_capture, 0, data); + auto left_capture_fixity + = get_fixity(left_capture->get_constructor(), data); + if (!inverse_priority && (left_capture_fixity & BareRight)) { return true; } } @@ -403,66 +409,71 @@ bool requiresBracketWithSimpleAlgorithm( return false; } -sptr addBrackets( - sptr inner, KORECompositePattern *outer, - KORECompositePattern *leftCapture, KORECompositePattern *rightCapture, - int position, PrettyPrintData const &data) { - if (auto *innerComposite - = dynamic_cast(inner.get())) { - if (innerComposite->getConstructor()->getName() == "inj") { - return addBrackets( - innerComposite->getArguments()[0], outer, leftCapture, rightCapture, - position, data); +sptr add_brackets( + sptr inner, kore_composite_pattern *outer, + kore_composite_pattern *left_capture, kore_composite_pattern *right_capture, + int position, pretty_print_data const &data) { + if (auto *inner_composite + = dynamic_cast(inner.get())) { + if (inner_composite->get_constructor()->get_name() == "inj") { + return add_brackets( + inner_composite->get_arguments()[0], outer, left_capture, + right_capture, position, data); } } - if (requiresBracketWithSimpleAlgorithm( - outer, leftCapture, rightCapture, inner.get(), position, data)) { - sptr outerSort = getArgSort( - outer->getConstructor(), position, outer->getArguments()[0]->getSort()); - sptr innerSort = getReturnSort(inner.get()); + if (requires_bracket_with_simple_algorithm( + outer, left_capture, right_capture, inner.get(), position, data)) { + sptr outer_sort = get_arg_sort( + outer->get_constructor(), position, + outer->get_arguments()[0]->get_sort()); + sptr inner_sort = get_return_sort(inner.get()); for (auto const &entry : data.brackets) { - bool isCorrectOuterSort = lessThanEq(data, entry.first, outerSort.get()); - if (isCorrectOuterSort) { - for (KORESymbol *s : entry.second) { - bool isCorrectInnerSort = lessThanEq( - data, innerSort.get(), getArgSort(s, 0, nullptr).get()); - if (isCorrectInnerSort) { - sptr result = KORECompositePattern::Create(s); - result->addArgument(inner); + bool is_correct_outer_sort + = less_than_eq(data, entry.first, outer_sort.get()); + if (is_correct_outer_sort) { + for (kore_symbol *s : entry.second) { + bool is_correct_inner_sort = less_than_eq( + data, inner_sort.get(), get_arg_sort(s, 0, nullptr).get()); + if (is_correct_inner_sort) { + sptr result + = kore_composite_pattern::create(s); + result->add_argument(inner); return result; } } } } - sptr result = KORECompositePattern::Create("bracket"); - result->addArgument(inner); - result->getConstructor()->addSort(innerSort); + sptr result + = kore_composite_pattern::create("bracket"); + result->add_argument(inner); + result->get_constructor()->add_sort(inner_sort); return result; } return inner; } -sptr addBrackets( - sptr t, KORECompositePattern *previousLeftCapture, - KORECompositePattern *previousRightCapture, PrettyPrintData const &data) { - if (auto *outer = dynamic_cast(t.get())) { - if (outer->getConstructor()->getName() == "\\dv") { +sptr add_brackets( + sptr t, kore_composite_pattern *previous_left_capture, + kore_composite_pattern *previous_right_capture, + pretty_print_data const &data) { + if (auto *outer = dynamic_cast(t.get())) { + if (outer->get_constructor()->get_name() == "\\dv") { return t; } - std::vector> newItems; + std::vector> new_items; - sptr result - = KORECompositePattern::Create(outer->getConstructor()); + sptr result + = kore_composite_pattern::create(outer->get_constructor()); int position = 0; - for (auto const &inner : outer->getArguments()) { - KORECompositePattern *leftCapture - = getLeftCapture(previousLeftCapture, outer, position, data); - KORECompositePattern *rightCapture - = getRightCapture(previousRightCapture, outer, position, data); - sptr newInner = addBrackets( - inner, outer, leftCapture, rightCapture, position, data); - newInner = addBrackets(newInner, leftCapture, rightCapture, data); - result->addArgument(newInner); + for (auto const &inner : outer->get_arguments()) { + kore_composite_pattern *left_capture + = get_left_capture(previous_left_capture, outer, position, data); + kore_composite_pattern *right_capture + = get_right_capture(previous_right_capture, outer, position, data); + sptr new_inner = add_brackets( + inner, outer, left_capture, right_capture, position, data); + new_inner = add_brackets(new_inner, left_capture, right_capture, data); + result->add_argument(new_inner); position++; } return result; @@ -470,9 +481,9 @@ sptr addBrackets( return t; } -sptr -addBrackets(sptr const &t, PrettyPrintData const &data) { - return addBrackets(t, nullptr, nullptr, data); +sptr +add_brackets(sptr const &t, pretty_print_data const &data) { + return add_brackets(t, nullptr, nullptr, data); } } // namespace kllvm diff --git a/lib/printer/printer.cpp b/lib/printer/printer.cpp index 957b3fee3..821030a7f 100644 --- a/lib/printer/printer.cpp +++ b/lib/printer/printer.cpp @@ -36,7 +36,7 @@ std::string trim(std::string const &s) { return rtrim(ltrim(s)); } -std::map getFormats() { +std::map get_formats() { static std::map formats; static bool once = true; @@ -67,7 +67,7 @@ std::map getFormats() { return formats; } -std::map getTerminals() { +std::map get_terminals() { static std::map terminals; static bool once = true; @@ -98,7 +98,7 @@ std::map getTerminals() { return terminals; } -std::set getAssocs() { +std::set get_assocs() { static std::set assocs; static bool once = true; @@ -112,7 +112,7 @@ std::set getAssocs() { return assocs; } -std::set getComms() { +std::set get_comms() { static std::set comms; static bool once = true; @@ -125,35 +125,35 @@ std::set getComms() { return comms; } -std::map> getLeftAssocs() { - static std::map> leftAssocs; +std::map> get_left_assocs() { + static std::map> left_assocs; static bool once = true; if (once) { - leftAssocs["kseq"].insert("kseq"); - leftAssocs["append"].insert("append"); - leftAssocs["\\and"].insert("\\and"); - leftAssocs["\\or"].insert("\\or"); - leftAssocs["\\rewrites"].insert("\\rewrites"); + left_assocs["kseq"].insert("kseq"); + left_assocs["append"].insert("append"); + left_assocs["\\and"].insert("\\and"); + left_assocs["\\or"].insert("\\or"); + left_assocs["\\rewrites"].insert("\\rewrites"); once = false; } - return leftAssocs; + return left_assocs; } -std::map> getRightAssocs() { - static std::map> rightAssocs; +std::map> get_right_assocs() { + static std::map> right_assocs; static bool once = true; if (once) { - rightAssocs["\\rewrites"].insert("\\rewrites"); + right_assocs["\\rewrites"].insert("\\rewrites"); once = false; } - return rightAssocs; + return right_assocs; } -std::map> getPriorities() { +std::map> get_priorities() { static std::map> priorities; static bool once = true; @@ -208,111 +208,111 @@ std::map> getPriorities() { return priorities; } -ptr const &getDefinition(std::string const &kompiledDir) { - static std::map> cache; +ptr const &get_definition(std::string const &kompiled_dir) { + static std::map> cache; - if (cache.find(kompiledDir) == cache.end()) { - KOREParser parser(kompiledDir + std::string("/syntaxDefinition.kore")); - cache[kompiledDir] = parser.definition(); + if (cache.find(kompiled_dir) == cache.end()) { + kore_parser parser(kompiled_dir + std::string("/syntaxDefinition.kore")); + cache[kompiled_dir] = parser.definition(); } - return cache.at(kompiledDir); + return cache.at(kompiled_dir); } -std::vector> const & -getAxioms(std::string const &kompiledDir) { - static std::map>> cache; +std::vector> const & +get_axioms(std::string const &kompiled_dir) { + static std::map>> cache; - if (cache.find(kompiledDir) == cache.end()) { - KOREParser parser(kompiledDir + std::string("/macros.kore")); - cache[kompiledDir] = parser.declarations(); + if (cache.find(kompiled_dir) == cache.end()) { + kore_parser parser(kompiled_dir + std::string("/macros.kore")); + cache[kompiled_dir] = parser.declarations(); } - return cache.at(kompiledDir); + return cache.at(kompiled_dir); } -struct PreprocessedPrintData { - PrettyPrintData data; +struct preprocessed_print_data { + pretty_print_data data; SymbolMap overloads; }; // NOLINTNEXTLINE(*-cognitive-complexity) -PreprocessedPrintData getPrintData( - ptr const &def, - std::vector> const &axioms, bool hasColor) { - auto formats = getFormats(); - auto terminals = getTerminals(); - auto assocs = getAssocs(); - auto comms = getComms(); - auto leftAssoc = getLeftAssocs(); - auto rightAssoc = getRightAssocs(); - auto priorities = getPriorities(); +preprocessed_print_data get_print_data( + ptr const &def, + std::vector> const &axioms, bool has_color) { + auto formats = get_formats(); + auto terminals = get_terminals(); + auto assocs = get_assocs(); + auto comms = get_comms(); + auto left_assoc = get_left_assocs(); + auto right_assoc = get_right_assocs(); + auto priorities = get_priorities(); BracketMap brackets; std::map hooks; std::map> colors; - auto subsorts = def->getSubsorts(); - auto overloads = def->getOverloads(); + auto subsorts = def->get_subsorts(); + auto overloads = def->get_overloads(); - for (auto const &entry : def->getSymbolDeclarations()) { + for (auto const &entry : def->get_symbol_declarations()) { std::string name = entry.first; - if (entry.second->attributes().contains(attribute_set::key::format)) { + if (entry.second->attributes().contains(attribute_set::key::Format)) { formats[name] - = entry.second->attributes().get_string(attribute_set::key::format); + = entry.second->attributes().get_string(attribute_set::key::Format); terminals[name] = entry.second->attributes().get_string( - attribute_set::key::terminals); + attribute_set::key::Terminals); - if (entry.second->attributes().contains(attribute_set::key::assoc)) { + if (entry.second->attributes().contains(attribute_set::key::Assoc)) { assocs.insert(name); } - if (entry.second->attributes().contains(attribute_set::key::comm)) { + if (entry.second->attributes().contains(attribute_set::key::Comm)) { comms.insert(name); } - if (entry.second->attributes().contains(attribute_set::key::colors)) { - std::string colorAtt - = entry.second->attributes().get_string(attribute_set::key::colors); + if (entry.second->attributes().contains(attribute_set::key::Colors)) { + std::string color_att + = entry.second->attributes().get_string(attribute_set::key::Colors); std::vector color; size_t idx = 0; do { - size_t pos = colorAtt.find_first_of(',', idx); + size_t pos = color_att.find_first_of(',', idx); if (pos == std::string::npos) { - color.push_back(trim(colorAtt.substr(idx))); + color.push_back(trim(color_att.substr(idx))); break; } - color.push_back(trim(colorAtt.substr(idx, pos - idx))); + color.push_back(trim(color_att.substr(idx, pos - idx))); idx = pos + 1; } while (true); colors[name] = color; } - if (entry.second->attributes().contains(attribute_set::key::bracket)) { - brackets[entry.second->getSymbol()->getSort().get()].push_back( - entry.second->getSymbol()); + if (entry.second->attributes().contains(attribute_set::key::Bracket)) { + brackets[entry.second->get_symbol()->get_sort().get()].push_back( + entry.second->get_symbol()); } - readMultimap(name, entry.second, leftAssoc, attribute_set::key::left); - readMultimap(name, entry.second, rightAssoc, attribute_set::key::right); - readMultimap( - name, entry.second, priorities, attribute_set::key::priorities); + read_multimap(name, entry.second, left_assoc, attribute_set::key::Left); + read_multimap(name, entry.second, right_assoc, attribute_set::key::Right); + read_multimap( + name, entry.second, priorities, attribute_set::key::Priorities); } } - for (auto const &entry : def->getSortDeclarations()) { + for (auto const &entry : def->get_sort_declarations()) { std::string name = entry.first; - if (entry.second->attributes().contains(attribute_set::key::hook)) { + if (entry.second->attributes().contains(attribute_set::key::Hook)) { hooks[name] - = entry.second->attributes().get_string(attribute_set::key::hook); + = entry.second->attributes().get_string(attribute_set::key::Hook); } } - PrettyPrintData data - = {formats, colors, terminals, priorities, leftAssoc, rightAssoc, - hooks, brackets, assocs, comms, subsorts, hasColor}; + pretty_print_data data + = {formats, colors, terminals, priorities, left_assoc, right_assoc, + hooks, brackets, assocs, comms, subsorts, has_color}; return {data, overloads}; } @@ -323,60 +323,60 @@ namespace kllvm { using namespace parser; -std::ostream &printKORE( - std::ostream &os, std::string const &definitionPath, - std::string const &patternPath, bool hasColor, bool filterSubst, +std::ostream &print_kore( + std::ostream &os, std::string const &definition_path, + std::string const &pattern_path, bool has_color, bool filter_subst, bool pretty) { - static std::map cache; + static std::map cache; - auto const &def = getDefinition(definitionPath); - auto const &axioms = getAxioms(definitionPath); + auto const &def = get_definition(definition_path); + auto const &axioms = get_axioms(definition_path); - auto getPrintDataOrCached = [&] { - if (cache.find(definitionPath) == cache.end()) { - cache[definitionPath] = getPrintData(def, axioms, hasColor); + auto get_print_data_or_cached = [&] { + if (cache.find(definition_path) == cache.end()) { + cache[definition_path] = get_print_data(def, axioms, has_color); } - return cache.at(definitionPath); + return cache.at(definition_path); }; - auto config = KOREPattern::load(patternPath); - config = config->unflattenAndOr(); - std::map> symbols; - config->markSymbols(symbols); + auto config = kore_pattern::load(pattern_path); + config = config->unflatten_and_or(); + std::map> symbols; + config->mark_symbols(symbols); for (auto const &decl : axioms) { - auto *axiom = dynamic_cast(decl.get()); - axiom->getPattern()->markSymbols(symbols); + auto *axiom = dynamic_cast(decl.get()); + axiom->get_pattern()->mark_symbols(symbols); } for (auto &entry : symbols) { for (auto *symbol : entry.second) { - auto *decl = def->getSymbolDeclarations().at(symbol->getName()); - symbol->instantiateSymbol(decl); + auto *decl = def->get_symbol_declarations().at(symbol->get_name()); + symbol->instantiate_symbol(decl); } } - auto [data, overloads] = getPrintDataOrCached(); + auto [data, overloads] = get_print_data_or_cached(); - sptr expanded - = config->expandMacros(data.subsorts, overloads, axioms, true); - sptr sorted = expanded->sortCollections(data); - sptr filtered; + sptr expanded + = config->expand_macros(data.subsorts, overloads, axioms, true); + sptr sorted = expanded->sort_collections(data); + sptr filtered; - if (filterSubst) { - std::set vars = sorted->gatherSingletonVars(); - filtered = sorted->filterSubstitution(data, vars); - filtered = filtered->dedupeDisjuncts(); - filtered = filtered->sortCollections(data); + if (filter_subst) { + std::set vars = sorted->gather_singleton_vars(); + filtered = sorted->filter_substitution(data, vars); + filtered = filtered->dedupe_disjuncts(); + filtered = filtered->sort_collections(data); } else { filtered = sorted; } - sptr withBrackets = addBrackets(filtered, data); + sptr with_brackets = add_brackets(filtered, data); if (pretty) { - withBrackets->prettyPrint(os, data); + with_brackets->pretty_print(os, data); } else { - withBrackets->print(os); + with_brackets->print(os); } os << std::endl; diff --git a/runtime/alloc/alloc.cpp b/runtime/alloc/alloc.cpp index 0aaf37418..51afdab73 100644 --- a/runtime/alloc/alloc.cpp +++ b/runtime/alloc/alloc.cpp @@ -16,85 +16,86 @@ REGISTER_ARENA(oldspace, OLDSPACE_ID); REGISTER_ARENA(alwaysgcspace, ALWAYSGCSPACE_ID); char *youngspace_ptr() { - return arenaStartPtr(&youngspace); + return arena_start_ptr(&youngspace); } char *oldspace_ptr() { - return arenaStartPtr(&oldspace); + return arena_start_ptr(&oldspace); } char **young_alloc_ptr() { - return arenaEndPtr(&youngspace); + return arena_end_ptr(&youngspace); } char **old_alloc_ptr() { - return arenaEndPtr(&oldspace); + return arena_end_ptr(&oldspace); } char youngspace_collection_id() { - return getArenaCollectionSemispaceID(&youngspace); + return get_arena_collection_semispace_id(&youngspace); } char oldspace_collection_id() { - return getArenaCollectionSemispaceID(&oldspace); + return get_arena_collection_semispace_id(&oldspace); } size_t youngspace_size(void) { - return arenaSize(&youngspace); + return arena_size(&youngspace); } -bool youngspaceAlmostFull(size_t threshold) { - char *nextBlock = *(char **)youngspace.block_start; - if (nextBlock) { +bool youngspace_almost_full(size_t threshold) { + char *next_block = *(char **)youngspace.block_start; + if (next_block) { // not on the last block, so short circuit and assume that we can keep // allocating for now. return false; } - ptrdiff_t freeBytes = youngspace.block_end - youngspace.block; - size_t totalBytes + ptrdiff_t free_bytes = youngspace.block_end - youngspace.block; + size_t total_bytes = youngspace.num_blocks * (BLOCK_SIZE - sizeof(memory_block_header)); - return (totalBytes - freeBytes) * 100 > threshold * 95; + return (total_bytes - free_bytes) * 100 > threshold * 95; } -void koreAllocSwap(bool swapOld) { - arenaSwapAndClear(&youngspace); - arenaClear(&alwaysgcspace); - if (swapOld) { - arenaSwapAndClear(&oldspace); +void kore_alloc_swap(bool swap_old) { + arena_swap_and_clear(&youngspace); + arena_clear(&alwaysgcspace); + if (swap_old) { + arena_swap_and_clear(&oldspace); } } -void setKoreMemoryFunctionsForGMP() { - mp_set_memory_functions(koreAllocMP, koreReallocMP, koreFree); +void set_kore_memory_functions_for_gmp() { + mp_set_memory_functions(kore_alloc_mp, kore_realloc_mp, kore_free); } -__attribute__((always_inline)) void *koreAlloc(size_t requested) { - return koreArenaAlloc(&youngspace, requested); +__attribute__((always_inline)) void *kore_alloc(size_t requested) { + return kore_arena_alloc(&youngspace, requested); } -__attribute__((always_inline)) void *koreAllocToken(size_t requested) { +__attribute__((always_inline)) void *kore_alloc_token(size_t requested) { size_t size = (requested + 7) & ~7; - return koreArenaAlloc(&youngspace, size < 16 ? 16 : size); + return kore_arena_alloc(&youngspace, size < 16 ? 16 : size); } -__attribute__((always_inline)) void *koreAllocOld(size_t requested) { - return koreArenaAlloc(&oldspace, requested); +__attribute__((always_inline)) void *kore_alloc_old(size_t requested) { + return kore_arena_alloc(&oldspace, requested); } -__attribute__((always_inline)) void *koreAllocTokenOld(size_t requested) { +__attribute__((always_inline)) void *kore_alloc_token_old(size_t requested) { size_t size = (requested + 7) & ~7; - return koreArenaAlloc(&oldspace, size < 16 ? 16 : size); + return kore_arena_alloc(&oldspace, size < 16 ? 16 : size); } -__attribute__((always_inline)) void *koreAllocAlwaysGC(size_t requested) { - return koreArenaAlloc(&alwaysgcspace, requested); +__attribute__((always_inline)) void *kore_alloc_always_gc(size_t requested) { + return kore_arena_alloc(&alwaysgcspace, requested); } -void *koreResizeLastAlloc(void *oldptr, size_t newrequest, size_t last_size) { +void * +kore_resize_last_alloc(void *oldptr, size_t newrequest, size_t last_size) { newrequest = (newrequest + 7) & ~7; last_size = (last_size + 7) & ~7; - if (oldptr != *arenaEndPtr(&youngspace) - last_size) { + if (oldptr != *arena_end_ptr(&youngspace) - last_size) { MEM_LOG( "May only reallocate last allocation. Tried to reallocate %p to %zd\n", oldptr, newrequest); @@ -102,51 +103,51 @@ void *koreResizeLastAlloc(void *oldptr, size_t newrequest, size_t last_size) { } ssize_t increase = newrequest - last_size; - if (arenaResizeLastAlloc(&youngspace, increase)) { + if (arena_resize_last_alloc(&youngspace, increase)) { return oldptr; } - void *newptr = koreAlloc(newrequest); + void *newptr = kore_alloc(newrequest); memcpy(newptr, oldptr, last_size); return newptr; } -void *koreAllocMP(size_t requested) { - auto *_new = (string *)koreAllocToken(sizeof(string) + requested); - init_with_len(_new, requested); - return _new->data; +void *kore_alloc_mp(size_t requested) { + auto *new_token = (string *)kore_alloc_token(sizeof(string) + requested); + init_with_len(new_token, requested); + return new_token->data; } -void *koreReallocMP(void *ptr, size_t old_size, size_t new_size) { - auto *_new = (string *)koreAllocToken(sizeof(string) + new_size); +void *kore_realloc_mp(void *ptr, size_t old_size, size_t new_size) { + auto *new_token = (string *)kore_alloc_token(sizeof(string) + new_size); size_t min = old_size > new_size ? new_size : old_size; - memcpy(_new->data, ptr, min); - init_with_len(_new, new_size); - return _new->data; + memcpy(new_token->data, ptr, min); + init_with_len(new_token, new_size); + return new_token->data; } -void koreFree(void *ptr, size_t size) { } +void kore_free(void *ptr, size_t size) { } -__attribute__((always_inline)) void *koreAllocInteger(size_t requested) { - auto *result = (mpz_hdr *)koreAlloc(sizeof(mpz_hdr)); +__attribute__((always_inline)) void *kore_alloc_integer(size_t requested) { + auto *result = (mpz_hdr *)kore_alloc(sizeof(mpz_hdr)); init_with_len(result, sizeof(mpz_hdr) - sizeof(blockheader)); return &result->i; } -__attribute__((always_inline)) void *koreAllocFloating(size_t requested) { - auto *result = (floating_hdr *)koreAlloc(sizeof(floating_hdr)); +__attribute__((always_inline)) void *kore_alloc_floating(size_t requested) { + auto *result = (floating_hdr *)kore_alloc(sizeof(floating_hdr)); init_with_len(result, sizeof(floating_hdr) - sizeof(blockheader)); return &result->f; } -__attribute__((always_inline)) void *koreAllocIntegerOld(size_t requested) { - auto *result = (mpz_hdr *)koreAllocOld(sizeof(mpz_hdr)); +__attribute__((always_inline)) void *kore_alloc_integer_old(size_t requested) { + auto *result = (mpz_hdr *)kore_alloc_old(sizeof(mpz_hdr)); init_with_len(result, sizeof(mpz_hdr) - sizeof(blockheader)); return &result->i; } -__attribute__((always_inline)) void *koreAllocFloatingOld(size_t requested) { - auto *result = (floating_hdr *)koreAllocOld(sizeof(floating_hdr)); +__attribute__((always_inline)) void *kore_alloc_floating_old(size_t requested) { + auto *result = (floating_hdr *)kore_alloc_old(sizeof(floating_hdr)); init_with_len(result, sizeof(floating_hdr) - sizeof(blockheader)); return &result->f; } diff --git a/runtime/alloc/arena.cpp b/runtime/alloc/arena.cpp index e9839db03..284c8fd38 100644 --- a/runtime/alloc/arena.cpp +++ b/runtime/alloc/arena.cpp @@ -17,32 +17,33 @@ mem_block_header(void *ptr) { ((uintptr_t)(ptr)-1) & ~(BLOCK_SIZE - 1)); } -__attribute__((always_inline)) void arenaReset(struct arena *Arena) { - char id = Arena->allocation_semispace_id; +__attribute__((always_inline)) void arena_reset(struct arena *arena) { + char id = arena->allocation_semispace_id; if (id < 0) { - id = ~Arena->allocation_semispace_id; + id = ~arena->allocation_semispace_id; } - Arena->first_block = nullptr; - Arena->block = nullptr; - Arena->block_start = nullptr; - Arena->block_end = nullptr; - Arena->first_collection_block = nullptr; - Arena->num_blocks = 0; - Arena->num_collection_blocks = 0; - Arena->allocation_semispace_id = id; + arena->first_block = nullptr; + arena->block = nullptr; + arena->block_start = nullptr; + arena->block_end = nullptr; + arena->first_collection_block = nullptr; + arena->num_blocks = 0; + arena->num_collection_blocks = 0; + arena->allocation_semispace_id = id; } __attribute__((always_inline)) char -getArenaAllocationSemispaceID(const struct arena *Arena) { - return Arena->allocation_semispace_id; +get_arena_allocation_semispace_id(const struct arena *arena) { + return arena->allocation_semispace_id; } __attribute__((always_inline)) char -getArenaCollectionSemispaceID(const struct arena *Arena) { - return ~Arena->allocation_semispace_id; +get_arena_collection_semispace_id(const struct arena *arena) { + return ~arena->allocation_semispace_id; } -__attribute__((always_inline)) char getArenaSemispaceIDOfObject(void *ptr) { +__attribute__((always_inline)) char +get_arena_semispace_id_of_object(void *ptr) { return mem_block_header(ptr)->semispace; } @@ -75,57 +76,57 @@ static void *megabyte_malloc() { return result; } -static void freshBlock(struct arena *Arena) { - char *nextBlock = nullptr; - if (Arena->block_start == nullptr) { - nextBlock = (char *)megabyte_malloc(); - Arena->first_block = nextBlock; - auto *nextHeader = (memory_block_header *)nextBlock; - nextHeader->next_block = nullptr; - nextHeader->semispace = Arena->allocation_semispace_id; - Arena->num_blocks++; +static void fresh_block(struct arena *arena) { + char *next_block = nullptr; + if (arena->block_start == nullptr) { + next_block = (char *)megabyte_malloc(); + arena->first_block = next_block; + auto *next_header = (memory_block_header *)next_block; + next_header->next_block = nullptr; + next_header->semispace = arena->allocation_semispace_id; + arena->num_blocks++; } else { - nextBlock = *(char **)Arena->block_start; - if (Arena->block != Arena->block_end) { - if (Arena->block_end - Arena->block == 8) { - *(uint64_t *)Arena->block + next_block = *(char **)arena->block_start; + if (arena->block != arena->block_end) { + if (arena->block_end - arena->block == 8) { + *(uint64_t *)arena->block = NOT_YOUNG_OBJECT_BIT; // 8 bit sentinel value } else { - *(uint64_t *)Arena->block = Arena->block_end - Arena->block + *(uint64_t *)arena->block = arena->block_end - arena->block - 8; // 16-bit or more sentinel value } } - if (!nextBlock) { + if (!next_block) { MEM_LOG( "Allocating new block for the first time in arena %d\n", Arena->allocation_semispace_id); - nextBlock = (char *)megabyte_malloc(); - *(char **)Arena->block_start = nextBlock; - auto *nextHeader = (memory_block_header *)nextBlock; - nextHeader->next_block = nullptr; - nextHeader->semispace = Arena->allocation_semispace_id; - Arena->num_blocks++; + next_block = (char *)megabyte_malloc(); + *(char **)arena->block_start = next_block; + auto *next_header = (memory_block_header *)next_block; + next_header->next_block = nullptr; + next_header->semispace = arena->allocation_semispace_id; + arena->num_blocks++; } } - Arena->block = nextBlock + sizeof(memory_block_header); - Arena->block_start = nextBlock; - Arena->block_end = nextBlock + BLOCK_SIZE; + arena->block = next_block + sizeof(memory_block_header); + arena->block_start = next_block; + arena->block_end = next_block + BLOCK_SIZE; MEM_LOG( "New block at %p (remaining %zd)\n", Arena->block, BLOCK_SIZE - sizeof(memory_block_header)); } static __attribute__((noinline)) void * -doAllocSlow(size_t requested, struct arena *Arena) { +do_alloc_slow(size_t requested, struct arena *arena) { MEM_LOG( "Block at %p too small, %zd remaining but %zd needed\n", Arena->block, Arena->block_end - Arena->block, requested); if (requested > BLOCK_SIZE - sizeof(memory_block_header)) { return malloc(requested); } - freshBlock(Arena); - void *result = Arena->block; - Arena->block += requested; + fresh_block(arena); + void *result = arena->block; + arena->block += requested; MEM_LOG( "Allocation at %p (size %zd), next alloc at %p (if it fits)\n", result, requested, Arena->block); @@ -133,12 +134,12 @@ doAllocSlow(size_t requested, struct arena *Arena) { } __attribute__((always_inline)) void * -koreArenaAlloc(struct arena *Arena, size_t requested) { - if (Arena->block + requested > Arena->block_end) { - return doAllocSlow(requested, Arena); +kore_arena_alloc(struct arena *arena, size_t requested) { + if (arena->block + requested > arena->block_end) { + return do_alloc_slow(requested, arena); } - void *result = Arena->block; - Arena->block += requested; + void *result = arena->block; + arena->block += requested; MEM_LOG( "Allocation at %p (size %zd), next alloc at %p (if it fits)\n", result, requested, Arena->block); @@ -146,44 +147,45 @@ koreArenaAlloc(struct arena *Arena, size_t requested) { } __attribute__((always_inline)) void * -arenaResizeLastAlloc(struct arena *Arena, ssize_t increase) { - if (Arena->block + increase <= Arena->block_end) { - Arena->block += increase; - return Arena->block; +arena_resize_last_alloc(struct arena *arena, ssize_t increase) { + if (arena->block + increase <= arena->block_end) { + arena->block += increase; + return arena->block; } return nullptr; } -__attribute__((always_inline)) void arenaSwapAndClear(struct arena *Arena) { - char *tmp = Arena->first_block; - Arena->first_block = Arena->first_collection_block; - Arena->first_collection_block = tmp; - size_t tmp2 = Arena->num_blocks; - Arena->num_blocks = Arena->num_collection_blocks; - Arena->num_collection_blocks = tmp2; - Arena->allocation_semispace_id = ~Arena->allocation_semispace_id; - arenaClear(Arena); +__attribute__((always_inline)) void arena_swap_and_clear(struct arena *arena) { + char *tmp = arena->first_block; + arena->first_block = arena->first_collection_block; + arena->first_collection_block = tmp; + size_t tmp2 = arena->num_blocks; + arena->num_blocks = arena->num_collection_blocks; + arena->num_collection_blocks = tmp2; + arena->allocation_semispace_id = ~arena->allocation_semispace_id; + arena_clear(arena); } -__attribute__((always_inline)) void arenaClear(struct arena *Arena) { - Arena->block = Arena->first_block - ? Arena->first_block + sizeof(memory_block_header) +__attribute__((always_inline)) void arena_clear(struct arena *arena) { + arena->block = arena->first_block + ? arena->first_block + sizeof(memory_block_header) : nullptr; - Arena->block_start = Arena->first_block; - Arena->block_end - = Arena->first_block ? Arena->first_block + BLOCK_SIZE : nullptr; + arena->block_start = arena->first_block; + arena->block_end + = arena->first_block ? arena->first_block + BLOCK_SIZE : nullptr; } -__attribute__((always_inline)) char *arenaStartPtr(const struct arena *Arena) { - return Arena->first_block ? Arena->first_block + sizeof(memory_block_header) +__attribute__((always_inline)) char * +arena_start_ptr(const struct arena *arena) { + return arena->first_block ? arena->first_block + sizeof(memory_block_header) : nullptr; } -__attribute__((always_inline)) char **arenaEndPtr(struct arena *Arena) { - return &Arena->block; +__attribute__((always_inline)) char **arena_end_ptr(struct arena *arena) { + return &arena->block; } -char *movePtr(char *ptr, size_t size, char const *arena_end_ptr) { +char *move_ptr(char *ptr, size_t size, char const *arena_end_ptr) { char *next_ptr = ptr + size; if (next_ptr == arena_end_ptr) { return nullptr; @@ -198,7 +200,7 @@ char *movePtr(char *ptr, size_t size, char const *arena_end_ptr) { return next_block + sizeof(memory_block_header); } -ssize_t ptrDiff(char *ptr1, char *ptr2) { +ssize_t ptr_diff(char *ptr1, char *ptr2) { if (MEM_BLOCK_START(ptr1) == MEM_BLOCK_START(ptr2)) { return ptr1 - ptr2; } @@ -223,17 +225,17 @@ ssize_t ptrDiff(char *ptr1, char *ptr2) { // negate the result. This means that the code might not // terminate if the two pointers do not belong to the same // arena. - return -ptrDiff(ptr2, ptr1); + return -ptr_diff(ptr2, ptr1); } -size_t arenaSize(const struct arena *Arena) { - return (Arena->num_blocks > Arena->num_collection_blocks - ? Arena->num_blocks - : Arena->num_collection_blocks) +size_t arena_size(const struct arena *arena) { + return (arena->num_blocks > arena->num_collection_blocks + ? arena->num_blocks + : arena->num_collection_blocks) * (BLOCK_SIZE - sizeof(memory_block_header)); } -void freeAllMemory() { +void free_all_memory() { auto *superblock = (memory_block_header *)first_superblock_ptr; while (superblock) { auto *next_superblock = (memory_block_header *)superblock->next_superblock; diff --git a/runtime/alloc/register_gc_roots_enum.cpp b/runtime/alloc/register_gc_roots_enum.cpp index a955c0a61..bbb4b2269 100644 --- a/runtime/alloc/register_gc_roots_enum.cpp +++ b/runtime/alloc/register_gc_roots_enum.cpp @@ -3,8 +3,8 @@ #include "runtime/collect.h" #include "runtime/header.h" -std::vector blockEnumerators; +std::vector block_enumerators; -void registerGCRootsEnumerator(BlockEnumerator f) { - blockEnumerators.push_back(f); +void register_gc_roots_enumerator(BlockEnumerator f) { + block_enumerators.push_back(f); } diff --git a/runtime/arithmetic/float.cpp b/runtime/arithmetic/float.cpp index fdf168a5f..b79dd1e67 100644 --- a/runtime/arithmetic/float.cpp +++ b/runtime/arithmetic/float.cpp @@ -87,11 +87,12 @@ SortFloat hook_FLOAT_trunc(SortFloat a) { SortFloat hook_FLOAT_round(SortFloat a, SortInt prec, SortInt exp) { if (!mpz_fits_ulong_p(prec)) { KLLVM_HOOK_INVALID_ARGUMENT( - "Precision out of range: {}", intToString(prec)); + "Precision out of range: {}", int_to_string(prec)); } unsigned long uprec = mpz_get_ui(prec); if (!mpz_fits_ulong_p(exp)) { - KLLVM_HOOK_INVALID_ARGUMENT("Exponent out of range: {}", intToString(exp)); + KLLVM_HOOK_INVALID_ARGUMENT( + "Exponent out of range: {}", int_to_string(exp)); } unsigned long uexp = mpz_get_ui(exp); floating result[1]; @@ -103,7 +104,7 @@ SortFloat hook_FLOAT_round(SortFloat a, SortInt prec, SortInt exp) { mpz_ptr hook_FLOAT_float2int(SortFloat a) { if (!mpfr_number_p(a->f)) { - KLLVM_HOOK_INVALID_ARGUMENT("Not a finite number: {}", floatToString(a)); + KLLVM_HOOK_INVALID_ARGUMENT("Not a finite number: {}", float_to_string(a)); } mpz_t result; mpz_init(result); @@ -114,11 +115,12 @@ mpz_ptr hook_FLOAT_float2int(SortFloat a) { SortFloat hook_FLOAT_int2float(SortInt a, SortInt prec, SortInt exp) { if (!mpz_fits_ulong_p(prec)) { KLLVM_HOOK_INVALID_ARGUMENT( - "Precision out of range: {}", intToString(prec)); + "Precision out of range: {}", int_to_string(prec)); } unsigned long uprec = mpz_get_ui(prec); if (!mpz_fits_ulong_p(exp)) { - KLLVM_HOOK_INVALID_ARGUMENT("Exponent out of range: {}", intToString(exp)); + KLLVM_HOOK_INVALID_ARGUMENT( + "Exponent out of range: {}", int_to_string(exp)); } unsigned long uexp = mpz_get_ui(exp); floating result[1]; @@ -268,11 +270,12 @@ bool hook_FLOAT_isNaN(SortFloat a) { SortFloat hook_FLOAT_maxValue(SortInt prec, SortInt exp) { if (!mpz_fits_ulong_p(prec)) { KLLVM_HOOK_INVALID_ARGUMENT( - "Precision out of range: {}", intToString(prec)); + "Precision out of range: {}", int_to_string(prec)); } unsigned long uprec = mpz_get_ui(prec); if (!mpz_fits_ulong_p(exp)) { - KLLVM_HOOK_INVALID_ARGUMENT("Exponent out of range: {}", intToString(exp)); + KLLVM_HOOK_INVALID_ARGUMENT( + "Exponent out of range: {}", int_to_string(exp)); } unsigned long uexp = mpz_get_ui(exp); floating result[1]; @@ -286,11 +289,12 @@ SortFloat hook_FLOAT_maxValue(SortInt prec, SortInt exp) { SortFloat hook_FLOAT_minValue(SortInt prec, SortInt exp) { if (!mpz_fits_ulong_p(prec)) { KLLVM_HOOK_INVALID_ARGUMENT( - "Precision out of range: {}", intToString(prec)); + "Precision out of range: {}", int_to_string(prec)); } unsigned long uprec = mpz_get_ui(prec); if (!mpz_fits_ulong_p(exp)) { - KLLVM_HOOK_INVALID_ARGUMENT("Exponent out of range: {}", intToString(exp)); + KLLVM_HOOK_INVALID_ARGUMENT( + "Exponent out of range: {}", int_to_string(exp)); } unsigned long uexp = mpz_get_ui(exp); floating result[1]; @@ -429,7 +433,7 @@ SortFloat hook_FLOAT_pow(SortFloat a, SortFloat b) { SortFloat hook_FLOAT_root(SortFloat a, SortInt b) { if (!mpz_fits_ulong_p(b)) { - KLLVM_HOOK_INVALID_ARGUMENT("Root out of range: {}", intToString(b)); + KLLVM_HOOK_INVALID_ARGUMENT("Root out of range: {}", int_to_string(b)); } unsigned long root = mpz_get_ui(b); floating result[1]; @@ -463,11 +467,12 @@ SortFloat hook_FLOAT_rat2float( SortInt numerator, SortInt denominator, SortInt prec, SortInt exp) { if (!mpz_fits_ulong_p(prec)) { KLLVM_HOOK_INVALID_ARGUMENT( - "Precision out of range: {}", intToString(prec)); + "Precision out of range: {}", int_to_string(prec)); } unsigned long uprec = mpz_get_ui(prec); if (!mpz_fits_ulong_p(exp)) { - KLLVM_HOOK_INVALID_ARGUMENT("Exponent out of range: {}", intToString(exp)); + KLLVM_HOOK_INVALID_ARGUMENT( + "Exponent out of range: {}", int_to_string(exp)); } unsigned long uexp = mpz_get_ui(exp); diff --git a/runtime/arithmetic/int.cpp b/runtime/arithmetic/int.cpp index 94e9788c4..fcb4feec6 100644 --- a/runtime/arithmetic/int.cpp +++ b/runtime/arithmetic/int.cpp @@ -13,7 +13,7 @@ SortInt hook_INT_tmod(SortInt a, SortInt b) { mpz_t result; if (mpz_sgn(b) == 0) { KLLVM_HOOK_INVALID_ARGUMENT( - "Modulus by zero: {} % {}", intToString(a), intToString(b)); + "Modulus by zero: {} % {}", int_to_string(a), int_to_string(b)); } mpz_init(result); mpz_tdiv_r(result, a, b); @@ -24,7 +24,7 @@ SortInt hook_INT_emod(SortInt a, SortInt b) { mpz_t result; if (mpz_sgn(b) == 0) { KLLVM_HOOK_INVALID_ARGUMENT( - "Modulus by zero: {} % {}", intToString(a), intToString(b)); + "Modulus by zero: {} % {}", int_to_string(a), int_to_string(b)); } mpz_init(result); mpz_tdiv_r(result, a, b); @@ -90,7 +90,7 @@ SortInt hook_INT_tdiv(SortInt a, SortInt b) { mpz_t result; if (mpz_sgn(b) == 0) { KLLVM_HOOK_INVALID_ARGUMENT( - "Division by zero: {} / {}", intToString(a), intToString(b)); + "Division by zero: {} / {}", int_to_string(a), int_to_string(b)); } mpz_init(result); mpz_tdiv_q(result, a, b); @@ -101,7 +101,7 @@ SortInt hook_INT_ediv(SortInt a, SortInt b) { mpz_t result; if (mpz_sgn(b) == 0) { KLLVM_HOOK_INVALID_ARGUMENT( - "Division by zero: {} / {}", intToString(a), intToString(b)); + "Division by zero: {} / {}", int_to_string(a), int_to_string(b)); } mpz_init(result); if (mpz_sgn(b) >= 0) { @@ -116,8 +116,8 @@ SortInt hook_INT_shl(SortInt a, SortInt b) { mpz_t result; if (!mpz_fits_ulong_p(b)) { KLLVM_HOOK_INVALID_ARGUMENT( - "Left shift amount out of range: {} << {}", intToString(a), - intToString(b)); + "Left shift amount out of range: {} << {}", int_to_string(a), + int_to_string(b)); } mpz_init(result); unsigned long blong = mpz_get_ui(b); @@ -139,8 +139,8 @@ SortInt hook_INT_shr(SortInt a, SortInt b) { if (!mpz_fits_ulong_p(b)) { if (mpz_sgn(b) < 0) { KLLVM_HOOK_INVALID_ARGUMENT( - "Negative right shift amount: {} >> {}", intToString(a), - intToString(b)); + "Negative right shift amount: {} >> {}", int_to_string(a), + int_to_string(b)); } if (mpz_sgn(a) < 0) { mpz_set_si(result, -1); @@ -160,7 +160,7 @@ SortInt hook_INT_pow(SortInt a, SortInt b) { mpz_t result; if (!mpz_fits_ulong_p(b)) { KLLVM_HOOK_INVALID_ARGUMENT( - "Exponent out of range: {} ^ {}", intToString(a), intToString(b)); + "Exponent out of range: {} ^ {}", int_to_string(a), int_to_string(b)); } mpz_init(result); unsigned long blong = mpz_get_ui(b); @@ -176,8 +176,8 @@ SortInt hook_INT_powmod(SortInt a, SortInt b, SortInt mod) { if (mpz_cmp_ui(result, 1) != 0) { mpz_clear(result); KLLVM_HOOK_INVALID_ARGUMENT( - "Modular inverse not defined: {} ^ {} % {}", intToString(a), - intToString(b), intToString(mod)); + "Modular inverse not defined: {} ^ {} % {}", int_to_string(a), + int_to_string(b), int_to_string(mod)); } } mpz_powm(result, a, b, mod); @@ -238,7 +238,7 @@ SortInt hook_INT_log2(SortInt a) { mpz_t result; if (mpz_sgn(a) <= 0) { KLLVM_HOOK_INVALID_ARGUMENT( - "Logarithm of nonpositive integer: log2({})", intToString(a)); + "Logarithm of nonpositive integer: log2({})", int_to_string(a)); } mpz_init(result); size_t log = mpz_sizeinbase(a, 2) - 1; @@ -294,12 +294,12 @@ SortInt hook_INT_bitRange(SortInt i, SortInt off, SortInt len) { return move_int(result); } if (!mpz_fits_ulong_p(len)) { - KLLVM_HOOK_INVALID_ARGUMENT("Length out of range: {}", intToString(len)); + KLLVM_HOOK_INVALID_ARGUMENT("Length out of range: {}", int_to_string(len)); } unsigned long lenlong = mpz_get_ui(len); if (!mpz_fits_ulong_p(off)) { if (mpz_sgn(off) < 0) { - KLLVM_HOOK_INVALID_ARGUMENT("Negative offset: {}", intToString(off)); + KLLVM_HOOK_INVALID_ARGUMENT("Negative offset: {}", int_to_string(off)); } mpz_init(result); if (mpz_sgn(i) < 0) { @@ -341,7 +341,7 @@ SortInt hook_INT_signExtendBitRange(SortInt i, SortInt off, SortInt len) { mpz_t result; if (!mpz_fits_ulong_p(off)) { if (mpz_sgn(off) < 0) { - KLLVM_HOOK_INVALID_ARGUMENT("Negative offset: {}", intToString(off)); + KLLVM_HOOK_INVALID_ARGUMENT("Negative offset: {}", int_to_string(off)); } mpz_init(result); if (mpz_sgn(i) < 0) { @@ -350,7 +350,7 @@ SortInt hook_INT_signExtendBitRange(SortInt i, SortInt off, SortInt len) { return move_int(result); } if (!mpz_fits_ulong_p(len)) { - KLLVM_HOOK_INVALID_ARGUMENT("Length out of range: {}", intToString(len)); + KLLVM_HOOK_INVALID_ARGUMENT("Length out of range: {}", int_to_string(len)); } unsigned long offlong = mpz_get_ui(off); unsigned long lenlong = mpz_get_ui(len); @@ -373,30 +373,28 @@ void int_hash(mpz_t i, void *hasher) { } } -static block *dotK = leaf_block(getTagForSymbolName("dotk{}")); - -gmp_randstate_t kllvm_randState; -bool kllvm_randStateInitialized = false; +gmp_randstate_t kllvm_rand_state; +bool kllvm_rand_state_initialized = false; SortK hook_INT_srand(SortInt seed) { - if (!kllvm_randStateInitialized) { - gmp_randinit_default(kllvm_randState); + if (!kllvm_rand_state_initialized) { + gmp_randinit_default(kllvm_rand_state); } - gmp_randseed(kllvm_randState, seed); - kllvm_randStateInitialized = true; - return dotK; + gmp_randseed(kllvm_rand_state, seed); + kllvm_rand_state_initialized = true; + return dot_k(); } -SortInt hook_INT_rand(SortInt upperBound) { +SortInt hook_INT_rand(SortInt upper_bound) { mpz_t result; mpz_init(result); - if (!kllvm_randStateInitialized) { - gmp_randinit_default(kllvm_randState); + if (!kllvm_rand_state_initialized) { + gmp_randinit_default(kllvm_rand_state); mpz_set_si(result, time(nullptr)); - gmp_randseed(kllvm_randState, result); - kllvm_randStateInitialized = true; + gmp_randseed(kllvm_rand_state, result); + kllvm_rand_state_initialized = true; } - mpz_urandomm(result, kllvm_randState, upperBound); + mpz_urandomm(result, kllvm_rand_state, upper_bound); return move_int(result); } @@ -415,7 +413,7 @@ size_t *hook_MINT_export(mpz_t in, uint64_t bits) { } uint64_t alloccount = nwords > count ? nwords : count; size_t allocsize = alloccount * sizeof(size_t); - auto *allocptr = (size_t *)koreAllocAlwaysGC(allocsize); + auto *allocptr = (size_t *)kore_alloc_always_gc(allocsize); memset(allocptr, 0, allocsize); size_t *exportptr = nwords > count ? allocptr + nwords - count : allocptr; size_t actualcount = 0; @@ -428,7 +426,7 @@ size_t *hook_MINT_export(mpz_t in, uint64_t bits) { return resultptr; } -mpz_ptr hook_MINT_import(size_t *i, uint64_t bits, bool isSigned) { +mpz_ptr hook_MINT_import(size_t *i, uint64_t bits, bool is_signed) { mpz_t result; mpz_t twos; mpz_init(twos); @@ -437,7 +435,7 @@ mpz_ptr hook_MINT_import(size_t *i, uint64_t bits, bool isSigned) { uint64_t nwords = (bits + 63) / 64; mpz_import(twos, nwords, -1, sizeof(size_t), 0, 0, i); - if (isSigned) { + if (is_signed) { signed_extract(result, twos, 0, bits); return move_int(result); } diff --git a/runtime/collect/collect.cpp b/runtime/collect/collect.cpp index 54c300745..a7b64a9d2 100644 --- a/runtime/collect/collect.cpp +++ b/runtime/collect/collect.cpp @@ -27,7 +27,7 @@ static char *last_alloc_ptr; size_t numBytesLiveAtCollection[1 << AGE_WIDTH]; void set_gc_threshold(size_t); size_t get_gc_threshold(void); -bool youngspaceAlmostFull(size_t); +bool youngspace_almost_full(size_t); bool during_gc() { return is_gc; @@ -41,169 +41,169 @@ size_t get_size(uint64_t hdr, uint16_t layout) { return size_hdr(hdr); } -void migrate(block **blockPtr) { - block *currBlock = *blockPtr; - if (is_leaf_block(currBlock) || !is_heap_block(currBlock)) { +void migrate(block **block_ptr) { + block *curr_block = *block_ptr; + if (is_leaf_block(curr_block) || !is_heap_block(curr_block)) { return; } - uint64_t const hdr = currBlock->h.hdr; + uint64_t const hdr = curr_block->h.hdr; INITIALIZE_MIGRATE(); uint16_t layout = layout_hdr(hdr); - size_t lenInBytes = get_size(hdr, layout); - auto **forwardingAddress = (block **)(currBlock + 1); + size_t len_in_bytes = get_size(hdr, layout); + auto **forwarding_address = (block **)(curr_block + 1); if (!hasForwardingAddress) { - block *newBlock = nullptr; + block *new_block = nullptr; if (shouldPromote || (isInOldGen && collect_old)) { - newBlock = (block *)koreAllocOld(lenInBytes); + new_block = (block *)kore_alloc_old(len_in_bytes); } else { - newBlock = (block *)koreAlloc(lenInBytes); + new_block = (block *)kore_alloc(len_in_bytes); } #ifdef GC_DBG - numBytesLiveAtCollection[oldAge] += lenInBytes; + numBytesLiveAtCollection[oldAge] += len_in_bytes; #endif - memcpy(newBlock, currBlock, lenInBytes); - MIGRATE_HEADER(newBlock); - *forwardingAddress = newBlock; - currBlock->h.hdr |= FWD_PTR_BIT; - *blockPtr = newBlock; + memcpy(new_block, curr_block, len_in_bytes); + MIGRATE_HEADER(new_block); + *forwarding_address = new_block; + curr_block->h.hdr |= FWD_PTR_BIT; + *block_ptr = new_block; } else { - *blockPtr = *forwardingAddress; + *block_ptr = *forwarding_address; } } // call this function instead of migrate on objects directly referenced by // shared objects (like collection nodes) that are not tracked by gc -void migrate_once(block **blockPtr) { - block *currBlock = *blockPtr; - if (is_leaf_block(currBlock) || !is_heap_block(currBlock)) { +void migrate_once(block **block_ptr) { + block *curr_block = *block_ptr; + if (is_leaf_block(curr_block) || !is_heap_block(curr_block)) { return; } if (youngspace_collection_id() - == getArenaSemispaceIDOfObject((void *)currBlock) + == get_arena_semispace_id_of_object((void *)curr_block) || oldspace_collection_id() - == getArenaSemispaceIDOfObject((void *)currBlock)) { - migrate(blockPtr); + == get_arena_semispace_id_of_object((void *)curr_block)) { + migrate(block_ptr); } } -static void migrate_string_buffer(stringbuffer **bufferPtr) { - stringbuffer *buffer = *bufferPtr; +static void migrate_string_buffer(stringbuffer **buffer_ptr) { + stringbuffer *buffer = *buffer_ptr; uint64_t const hdr = buffer->h.hdr; uint64_t const cap = len(buffer->contents); INITIALIZE_MIGRATE(); if (!hasForwardingAddress) { - stringbuffer *newBuffer = nullptr; - string *newContents = nullptr; + stringbuffer *new_buffer = nullptr; + string *new_contents = nullptr; if (shouldPromote || (isInOldGen && collect_old)) { - newBuffer = (stringbuffer *)koreAllocOld(sizeof(stringbuffer)); - newContents = (string *)koreAllocTokenOld(sizeof(string) + cap); + new_buffer = (stringbuffer *)kore_alloc_old(sizeof(stringbuffer)); + new_contents = (string *)kore_alloc_token_old(sizeof(string) + cap); } else { - newBuffer = (stringbuffer *)koreAlloc(sizeof(stringbuffer)); - newContents = (string *)koreAllocToken(sizeof(string) + cap); + new_buffer = (stringbuffer *)kore_alloc(sizeof(stringbuffer)); + new_contents = (string *)kore_alloc_token(sizeof(string) + cap); } #ifdef GC_DBG numBytesLiveAtCollection[oldAge] += cap + sizeof(stringbuffer) + sizeof(string); #endif - memcpy(newContents, buffer->contents, sizeof(string) + buffer->strlen); - memcpy(newBuffer, buffer, sizeof(stringbuffer)); - MIGRATE_HEADER(newBuffer); - newBuffer->contents = newContents; - *(stringbuffer **)(buffer->contents) = newBuffer; + memcpy(new_contents, buffer->contents, sizeof(string) + buffer->strlen); + memcpy(new_buffer, buffer, sizeof(stringbuffer)); + MIGRATE_HEADER(new_buffer); + new_buffer->contents = new_contents; + *(stringbuffer **)(buffer->contents) = new_buffer; buffer->h.hdr |= FWD_PTR_BIT; } - *bufferPtr = *(stringbuffer **)(buffer->contents); + *buffer_ptr = *(stringbuffer **)(buffer->contents); } -static void migrate_mpz(mpz_ptr *mpzPtr) { - mpz_hdr *intgr = STRUCT_BASE(mpz_hdr, i, *mpzPtr); +static void migrate_mpz(mpz_ptr *ptr) { + mpz_hdr *intgr = STRUCT_BASE(mpz_hdr, i, *ptr); uint64_t const hdr = intgr->h.hdr; INITIALIZE_MIGRATE(); if (!hasForwardingAddress) { - mpz_hdr *newIntgr = nullptr; - string *newLimbs = nullptr; - bool hasLimbs = intgr->i->_mp_alloc > 0; + mpz_hdr *new_intgr = nullptr; + string *new_limbs = nullptr; + bool has_limbs = intgr->i->_mp_alloc > 0; #ifdef GC_DBG numBytesLiveAtCollection[oldAge] += sizeof(mpz_hdr); #endif - if (hasLimbs) { + if (has_limbs) { string *limbs = STRUCT_BASE(string, data, intgr->i->_mp_d); - size_t lenLimbs = len(limbs); + size_t len_limbs = len(limbs); #ifdef GC_DBG - numBytesLiveAtCollection[oldAge] += lenLimbs + sizeof(string); + numBytesLiveAtCollection[oldAge] += len_limbs + sizeof(string); #endif - assert(intgr->i->_mp_alloc * sizeof(mp_limb_t) == lenLimbs); + assert(intgr->i->_mp_alloc * sizeof(mp_limb_t) == len_limbs); if (shouldPromote || (isInOldGen && collect_old)) { - newIntgr = STRUCT_BASE(mpz_hdr, i, koreAllocIntegerOld(0)); - newLimbs = (string *)koreAllocTokenOld(sizeof(string) + lenLimbs); + new_intgr = STRUCT_BASE(mpz_hdr, i, kore_alloc_integer_old(0)); + new_limbs = (string *)kore_alloc_token_old(sizeof(string) + len_limbs); } else { - newIntgr = STRUCT_BASE(mpz_hdr, i, koreAllocInteger(0)); - newLimbs = (string *)koreAllocToken(sizeof(string) + lenLimbs); + new_intgr = STRUCT_BASE(mpz_hdr, i, kore_alloc_integer(0)); + new_limbs = (string *)kore_alloc_token(sizeof(string) + len_limbs); } - memcpy(newLimbs, limbs, sizeof(string) + lenLimbs); + memcpy(new_limbs, limbs, sizeof(string) + len_limbs); } else { if (shouldPromote || (isInOldGen && collect_old)) { - newIntgr = STRUCT_BASE(mpz_hdr, i, koreAllocIntegerOld(0)); + new_intgr = STRUCT_BASE(mpz_hdr, i, kore_alloc_integer_old(0)); } else { - newIntgr = STRUCT_BASE(mpz_hdr, i, koreAllocInteger(0)); + new_intgr = STRUCT_BASE(mpz_hdr, i, kore_alloc_integer(0)); } } - memcpy(newIntgr, intgr, sizeof(mpz_hdr)); - MIGRATE_HEADER(newIntgr); - if (hasLimbs) { - newIntgr->i->_mp_d = (mp_limb_t *)newLimbs->data; + memcpy(new_intgr, intgr, sizeof(mpz_hdr)); + MIGRATE_HEADER(new_intgr); + if (has_limbs) { + new_intgr->i->_mp_d = (mp_limb_t *)new_limbs->data; } - *(mpz_ptr *)(&intgr->i->_mp_d) = newIntgr->i; + *(mpz_ptr *)(&intgr->i->_mp_d) = new_intgr->i; intgr->h.hdr |= FWD_PTR_BIT; } - *mpzPtr = *(mpz_ptr *)(&intgr->i->_mp_d); + *ptr = *(mpz_ptr *)(&intgr->i->_mp_d); } -static void migrate_floating(floating **floatingPtr) { - floating_hdr *flt = STRUCT_BASE(floating_hdr, f, *floatingPtr); +static void migrate_floating(floating **floating_ptr) { + floating_hdr *flt = STRUCT_BASE(floating_hdr, f, *floating_ptr); uint64_t const hdr = flt->h.hdr; INITIALIZE_MIGRATE(); if (!hasForwardingAddress) { - floating_hdr *newFlt = nullptr; - string *newLimbs = nullptr; + floating_hdr *new_flt = nullptr; + string *new_limbs = nullptr; string *limbs = STRUCT_BASE(string, data, flt->f.f->_mpfr_d - 1); - size_t lenLimbs = len(limbs); + size_t len_limbs = len(limbs); #ifdef GC_DBG numBytesLiveAtCollection[oldAge] - += sizeof(floating_hdr) + sizeof(string) + lenLimbs; + += sizeof(floating_hdr) + sizeof(string) + len_limbs; #endif assert( ((flt->f.f->_mpfr_prec + mp_bits_per_limb - 1) / mp_bits_per_limb) * sizeof(mp_limb_t) - <= lenLimbs); + <= len_limbs); if (shouldPromote || (isInOldGen && collect_old)) { - newFlt = STRUCT_BASE(floating_hdr, f, koreAllocFloatingOld(0)); - newLimbs = (string *)koreAllocTokenOld(sizeof(string) + lenLimbs); + new_flt = STRUCT_BASE(floating_hdr, f, kore_alloc_floating_old(0)); + new_limbs = (string *)kore_alloc_token_old(sizeof(string) + len_limbs); } else { - newFlt = STRUCT_BASE(floating_hdr, f, koreAllocFloating(0)); - newLimbs = (string *)koreAllocToken(sizeof(string) + lenLimbs); + new_flt = STRUCT_BASE(floating_hdr, f, kore_alloc_floating(0)); + new_limbs = (string *)kore_alloc_token(sizeof(string) + len_limbs); } - memcpy(newLimbs, limbs, sizeof(string) + lenLimbs); - memcpy(newFlt, flt, sizeof(floating_hdr)); - MIGRATE_HEADER(newFlt); - newFlt->f.f->_mpfr_d = (mp_limb_t *)newLimbs->data + 1; - *(floating **)(flt->f.f->_mpfr_d) = &newFlt->f; + memcpy(new_limbs, limbs, sizeof(string) + len_limbs); + memcpy(new_flt, flt, sizeof(floating_hdr)); + MIGRATE_HEADER(new_flt); + new_flt->f.f->_mpfr_d = (mp_limb_t *)new_limbs->data + 1; + *(floating **)(flt->f.f->_mpfr_d) = &new_flt->f; flt->h.hdr |= FWD_PTR_BIT; } - *floatingPtr = *(floating **)(flt->f.f->_mpfr_d); + *floating_ptr = *(floating **)(flt->f.f->_mpfr_d); } static void -migrate_child(void *currBlock, layoutitem *args, unsigned i, bool ptr) { - layoutitem *argData = args + i; - void *arg = ((char *)currBlock) + argData->offset; - switch (argData->cat) { +migrate_child(void *curr_block, layoutitem *args, unsigned i, bool ptr) { + layoutitem *arg_data = args + i; + void *arg = ((char *)curr_block) + arg_data->offset; + switch (arg_data->cat) { case MAP_LAYOUT: migrate_map(ptr ? *(map **)arg : arg); break; case RANGEMAP_LAYOUT: migrate_rangemap(ptr ? *(rangemap **)arg : arg); break; case LIST_LAYOUT: migrate_list(ptr ? *(list **)arg : arg); break; @@ -220,21 +220,21 @@ migrate_child(void *currBlock, layoutitem *args, unsigned i, bool ptr) { } static char *evacuate(char *scan_ptr, char **alloc_ptr) { - auto *currBlock = (block *)scan_ptr; - uint64_t const hdr = currBlock->h.hdr; - uint16_t layoutInt = layout_hdr(hdr); - if (layoutInt) { - layout *layoutData = getLayoutData(layoutInt); - for (unsigned i = 0; i < layoutData->nargs; i++) { - migrate_child(currBlock, layoutData->args, i, false); + auto *curr_block = (block *)scan_ptr; + uint64_t const hdr = curr_block->h.hdr; + uint16_t layout_int = layout_hdr(hdr); + if (layout_int) { + layout *layout_data = get_layout_data(layout_int); + for (unsigned i = 0; i < layout_data->nargs; i++) { + migrate_child(curr_block, layout_data->args, i, false); } } - return movePtr(scan_ptr, get_size(hdr, layoutInt), *alloc_ptr); + return move_ptr(scan_ptr, get_size(hdr, layout_int), *alloc_ptr); } // Contains the decision logic for collecting the old generation. // For now, we collect the old generation every 50 young generation collections. -static bool shouldCollectOldGen() { +static bool should_collect_old_gen() { #ifdef GC_DBG return true; #else @@ -247,18 +247,18 @@ static bool shouldCollectOldGen() { #endif } -void migrateRoots(); +void migrate_roots(); -void initStaticObjects(void) { +void init_static_objects(void) { map m = map(); list l = list(); set s = set(); - setKoreMemoryFunctionsForGMP(); + set_kore_memory_functions_for_gmp(); } -void koreCollect(void **roots, uint8_t nroots, layoutitem *typeInfo) { +void kore_collect(void **roots, uint8_t nroots, layoutitem *type_info) { is_gc = true; - collect_old = shouldCollectOldGen(); + collect_old = should_collect_old_gen(); MEM_LOG("Starting garbage collection\n"); #ifdef GC_DBG if (!last_alloc_ptr) { @@ -266,7 +266,7 @@ void koreCollect(void **roots, uint8_t nroots, layoutitem *typeInfo) { } char *current_alloc_ptr = *young_alloc_ptr(); #endif - koreAllocSwap(collect_old); + kore_alloc_swap(collect_old); #ifdef GC_DBG for (int i = 0; i < 2048; i++) { numBytesLiveAtCollection[i] = 0; @@ -274,9 +274,9 @@ void koreCollect(void **roots, uint8_t nroots, layoutitem *typeInfo) { #endif char *previous_oldspace_alloc_ptr = *old_alloc_ptr(); for (int i = 0; i < nroots; i++) { - migrate_child(roots, typeInfo, i, true); + migrate_child(roots, type_info, i, true); } - migrateRoots(); + migrate_roots(); char *scan_ptr = youngspace_ptr(); if (scan_ptr != *young_alloc_ptr()) { MEM_LOG("Evacuating young generation\n"); @@ -295,10 +295,10 @@ void koreCollect(void **roots, uint8_t nroots, layoutitem *typeInfo) { // sequence at the start of the collection cycle. This means that the // allocation pointer is invalid and does not actually point to the next // address that would have been allocated at, according to the logic of - // koreArenaAlloc, which will have allocated a fresh memory block and put - // the allocation at the start of it. Thus, we use movePtr with a size + // kore_arena_alloc, which will have allocated a fresh memory block and put + // the allocation at the start of it. Thus, we use move_ptr with a size // of zero to adjust and get the true address of the allocation. - scan_ptr = movePtr(previous_oldspace_alloc_ptr, 0, *old_alloc_ptr()); + scan_ptr = move_ptr(previous_oldspace_alloc_ptr, 0, *old_alloc_ptr()); } else { scan_ptr = previous_oldspace_alloc_ptr; } @@ -311,7 +311,7 @@ void koreCollect(void **roots, uint8_t nroots, layoutitem *typeInfo) { } #ifdef GC_DBG ssize_t numBytesAllocedSinceLastCollection - = ptrDiff(current_alloc_ptr, last_alloc_ptr); + = ptr_diff(current_alloc_ptr, last_alloc_ptr); assert(numBytesAllocedSinceLastCollection >= 0); fwrite(&numBytesAllocedSinceLastCollection, sizeof(ssize_t), 1, stderr); last_alloc_ptr = *young_alloc_ptr(); @@ -325,12 +325,12 @@ void koreCollect(void **roots, uint8_t nroots, layoutitem *typeInfo) { set_gc_threshold(youngspace_size()); } -void freeAllKoreMem() { - koreCollect(nullptr, 0, nullptr); +void free_all_kore_mem() { + kore_collect(nullptr, 0, nullptr); } bool is_collection() { size_t threshold = get_gc_threshold(); - return youngspaceAlmostFull(threshold); + return youngspace_almost_full(threshold); } } diff --git a/runtime/collect/migrate_collection.cpp b/runtime/collect/migrate_collection.cpp index b8652f1bb..e2870de3e 100644 --- a/runtime/collect/migrate_collection.cpp +++ b/runtime/collect/migrate_collection.cpp @@ -4,33 +4,33 @@ #include -void migrate_collection_node(void **nodePtr) { - string *currBlock = STRUCT_BASE(string, data, *nodePtr); +void migrate_collection_node(void **node_ptr) { + string *curr_block = STRUCT_BASE(string, data, *node_ptr); if (youngspace_collection_id() - != getArenaSemispaceIDOfObject((void *)currBlock) + != get_arena_semispace_id_of_object((void *)curr_block) && oldspace_collection_id() - != getArenaSemispaceIDOfObject((void *)currBlock)) { + != get_arena_semispace_id_of_object((void *)curr_block)) { return; } - uint64_t const hdr = currBlock->h.hdr; + uint64_t const hdr = curr_block->h.hdr; INITIALIZE_MIGRATE(); - size_t lenInBytes = get_size(hdr, 0); + size_t len_in_bytes = get_size(hdr, 0); if (!hasForwardingAddress) { - string *newBlock = nullptr; + string *new_block = nullptr; if (shouldPromote || (isInOldGen && collect_old)) { - newBlock = (string *)koreAllocOld(lenInBytes); + new_block = (string *)kore_alloc_old(len_in_bytes); } else { - newBlock = (string *)koreAlloc(lenInBytes); + new_block = (string *)kore_alloc(len_in_bytes); } #ifdef GC_DBG - numBytesLiveAtCollection[oldAge] += lenInBytes; + numBytesLiveAtCollection[oldAge] += len_in_bytes; #endif - memcpy(newBlock, currBlock, lenInBytes); - MIGRATE_HEADER(newBlock); - *(void **)(currBlock + 1) = newBlock + 1; - currBlock->h.hdr |= FWD_PTR_BIT; + memcpy(new_block, curr_block, len_in_bytes); + MIGRATE_HEADER(new_block); + *(void **)(curr_block + 1) = new_block + 1; + curr_block->h.hdr |= FWD_PTR_BIT; } - *nodePtr = *(void **)(currBlock + 1); + *node_ptr = *(void **)(curr_block + 1); } struct migrate_visitor : immer::detail::rbts::visitor_base { @@ -92,14 +92,14 @@ void migrate_champ_traversal( } void migrate_map_leaf( - std::pair *start, std::pair *end) { + std::pair *start, std::pair *end) { for (auto *it = start; it != end; ++it) { migrate_once(&it->first.elem); migrate_once(&it->second.elem); } } -void migrate_set_leaf(KElem *start, KElem *end) { +void migrate_set_leaf(k_elem *start, k_elem *end) { for (auto *it = start; it != end; ++it) { migrate_once(&it->elem); } @@ -117,7 +117,7 @@ void migrate_map(void *m) { migrate_champ_traversal(impl.root, 0, migrate_map_leaf); } -using treemap = rb_tree::RBTree, KElem>; +using treemap = rb_tree::RBTree, k_elem>; void migrate_treemap(treemap t) { if (t.empty()) { return; diff --git a/runtime/collect/migrate_roots.cpp b/runtime/collect/migrate_roots.cpp index 10a64ad05..853b82b09 100644 --- a/runtime/collect/migrate_roots.cpp +++ b/runtime/collect/migrate_roots.cpp @@ -2,16 +2,16 @@ #include "runtime/collect.h" -extern std::vector blockEnumerators; +extern std::vector block_enumerators; -extern gmp_randstate_t kllvm_randState; -extern bool kllvm_randStateInitialized; +extern gmp_randstate_t kllvm_rand_state; +extern bool kllvm_rand_state_initialized; extern "C" { -void migrate(block **blockPtr); +void migrate(block **block_ptr); -void migrateRoots() { +void migrate_roots() { auto &l1 = list_impl::empty_root(); migrate_collection_node((void **)&l1); auto &l2 = list_impl::empty_tail(); @@ -20,22 +20,22 @@ void migrateRoots() { migrate_collection_node((void **)&s); auto &m = map_impl::empty(); migrate_collection_node((void **)&m); - if (kllvm_randStateInitialized) { - auto &rand = kllvm_randState->_mp_seed->_mp_d; + if (kllvm_rand_state_initialized) { + auto &rand = kllvm_rand_state->_mp_seed->_mp_d; string *limbs = STRUCT_BASE(string, data, rand); migrate((block **)&limbs); rand = (mp_limb_t *)limbs->data; } - if (blockEnumerators.empty()) { + if (block_enumerators.empty()) { return; } - for (auto &blockEnumerator : blockEnumerators) { - auto BlockIteratorPair = (*blockEnumerator)(); - auto BlockStartIt = BlockIteratorPair.first; - auto BlockEndIt = BlockIteratorPair.second; + for (auto &block_enumerator : block_enumerators) { + auto block_iterator_pair = (*block_enumerator)(); + auto block_start_it = block_iterator_pair.first; + auto block_end_it = block_iterator_pair.second; - for (auto it = BlockStartIt; it != BlockEndIt; ++it) { + for (auto it = block_start_it; it != block_end_it; ++it) { migrate(*it); } } diff --git a/runtime/collections/hash.cpp b/runtime/collections/hash.cpp index 51a266f44..6a90377f0 100644 --- a/runtime/collections/hash.cpp +++ b/runtime/collections/hash.cpp @@ -10,8 +10,8 @@ void float_hash(floating *, void *); static thread_local uint32_t hash_length; static thread_local uint32_t hash_depth; -static constexpr uint32_t HASH_THRESHOLD = 5; -static constexpr uint32_t HASH_LENGTH_THRESHOLD = 1024; +static constexpr uint32_t hash_threshold = 5; +static constexpr uint32_t hash_length_threshold = 1024; __attribute__((always_inline)) void add_hash8(void *h, uint8_t data) { auto *hash = (size_t *)h; @@ -33,8 +33,8 @@ __attribute__((always_inline)) void add_hash64(void *h, uint64_t data) { __attribute__((always_inline)) void add_hash_str(void *h, char *data, size_t len) { - if (len + hash_length > HASH_LENGTH_THRESHOLD) { - len = HASH_LENGTH_THRESHOLD - hash_length; + if (len + hash_length > hash_length_threshold) { + len = hash_length_threshold - hash_length; } for (size_t i = 0; i < len; i++) { add_hash8(h, data[i]); @@ -51,7 +51,7 @@ size_t hash_k(block *term) { bool hash_enter() { bool result - = hash_depth < HASH_THRESHOLD && hash_length < HASH_LENGTH_THRESHOLD; + = hash_depth < hash_threshold && hash_length < hash_length_threshold; hash_depth = hash_depth + 1; return result; } @@ -69,11 +69,11 @@ void k_hash(block *arg, void *h) { uint64_t arghdrcanon = arg->h.hdr & HDR_MASK; if (uint16_t arglayout = get_layout(arg)) { add_hash64(h, arghdrcanon); - layout *layoutPtr = getLayoutData(arglayout); - uint8_t length = layoutPtr->nargs; + layout *layout_ptr = get_layout_data(arglayout); + uint8_t length = layout_ptr->nargs; for (uint8_t i = 0; i < length; i++) { - uint64_t offset = layoutPtr->args[i].offset; - uint16_t cat = layoutPtr->args[i].cat; + uint64_t offset = layout_ptr->args[i].offset; + uint16_t cat = layout_ptr->args[i].cat; switch (cat) { case MAP_LAYOUT: { map *mapptr = (map *)(argintptr + offset); diff --git a/runtime/collections/kelemle.cpp b/runtime/collections/kelemle.cpp index 1f7d8a3e3..b6b77a61a 100644 --- a/runtime/collections/kelemle.cpp +++ b/runtime/collections/kelemle.cpp @@ -32,13 +32,13 @@ bool hook_KEQUAL_eq(block *arg1, block *arg2) { } // arglayout != 0 // Both arg1 and arg2 are blocks. auto arglayoutshort = (uint16_t)arglayout; - layout *layoutPtr = getLayoutData(arglayoutshort); - uint8_t length = layoutPtr->nargs; + layout *layout_ptr = get_layout_data(arglayoutshort); + uint8_t length = layout_ptr->nargs; for (uint8_t i = 0; i < length; i++) { - uint64_t offset = layoutPtr->args[i].offset; + uint64_t offset = layout_ptr->args[i].offset; uint64_t child1intptr = arg1intptr + offset; uint64_t child2intptr = arg2intptr + offset; - uint16_t cat = layoutPtr->args[i].cat; + uint16_t cat = layout_ptr->args[i].cat; switch (cat) { case MAP_LAYOUT: { map *map1ptr = (map *)(child1intptr); @@ -174,11 +174,11 @@ bool hook_KEQUAL_lt(block *arg1, block *arg2) { return arg1tag < arg2tag; } assert(arg1layout == arg2layout); - layout *layoutPtr = getLayoutData(arg1layout); - uint8_t length = layoutPtr->nargs; + layout *layout_ptr = get_layout_data(arg1layout); + uint8_t length = layout_ptr->nargs; for (uint8_t i = 0; i < length; i++) { - uint64_t offset = layoutPtr->args[i].offset; - uint16_t cat = layoutPtr->args[i].cat; + uint64_t offset = layout_ptr->args[i].offset; + uint16_t cat = layout_ptr->args[i].cat; switch (cat) { case INT_LAYOUT: { auto *int1ptrptr = (mpz_ptr *)(arg1intptr + offset); diff --git a/runtime/collections/lists.cpp b/runtime/collections/lists.cpp index fff474c54..633a3ac02 100644 --- a/runtime/collections/lists.cpp +++ b/runtime/collections/lists.cpp @@ -36,7 +36,7 @@ bool hook_LIST_in(SortKItem value, SortList list) { bool hook_LIST_in_keys(SortInt index, SortList list) { if (!mpz_fits_ulong_p(index)) { KLLVM_HOOK_INVALID_ARGUMENT( - "Index is too large for in_keys: {}", intToString(index)); + "Index is too large for in_keys: {}", int_to_string(index)); } size_t idx = mpz_get_ui(index); return idx < list->size(); @@ -51,7 +51,7 @@ SortKItem hook_LIST_get_long(SortList list, ssize_t idx) { SortKItem hook_LIST_get(SortList list, SortInt index) { if (!mpz_fits_slong_p(index)) { KLLVM_HOOK_INVALID_ARGUMENT( - "Index is too large for get: {}", intToString(index)); + "Index is too large for get: {}", int_to_string(index)); } ssize_t idx = mpz_get_si(index); return hook_LIST_get_long(list, idx); @@ -80,7 +80,7 @@ list hook_LIST_range(SortList list, SortInt from_front, SortInt from_back) { if (!mpz_fits_ulong_p(from_front) || !mpz_fits_ulong_p(from_back)) { KLLVM_HOOK_INVALID_ARGUMENT( "Range index too large for range: front={}, back={}", - intToString(from_front), intToString(from_back)); + int_to_string(from_front), int_to_string(from_back)); } size_t front = mpz_get_ui(from_front); @@ -102,7 +102,7 @@ SortInt hook_LIST_size(SortList list) { list hook_LIST_make(SortInt len, SortKItem value) { if (!mpz_fits_ulong_p(len)) { KLLVM_HOOK_INVALID_ARGUMENT( - "Length is too large for make: {}", intToString(len)); + "Length is too large for make: {}", int_to_string(len)); } size_t length = mpz_get_ui(len); @@ -112,7 +112,7 @@ list hook_LIST_make(SortInt len, SortKItem value) { list hook_LIST_update(SortList list, SortInt index, SortKItem value) { if (!mpz_fits_ulong_p(index)) { KLLVM_HOOK_INVALID_ARGUMENT( - "Length is too large for update: {}", intToString(index)); + "Length is too large for update: {}", int_to_string(index)); } size_t idx = mpz_get_ui(index); @@ -127,7 +127,7 @@ list hook_LIST_update(SortList list, SortInt index, SortKItem value) { list hook_LIST_updateAll(SortList l1, SortInt index, SortList l2) { if (!mpz_fits_ulong_p(index)) { KLLVM_HOOK_INVALID_ARGUMENT( - "Length is too large for updateAll: {}", intToString(index)); + "Length is too large for updateAll: {}", int_to_string(index)); } size_t idx = mpz_get_ui(index); @@ -163,12 +163,12 @@ list hook_LIST_updateAll(SortList l1, SortInt index, SortList l2) { list hook_LIST_fill(SortList l, SortInt index, SortInt len, SortKItem val) { if (!mpz_fits_ulong_p(index)) { KLLVM_HOOK_INVALID_ARGUMENT( - "Index is too large for fill: {}", intToString(index)); + "Index is too large for fill: {}", int_to_string(index)); } if (!mpz_fits_ulong_p(len)) { KLLVM_HOOK_INVALID_ARGUMENT( - "Length is too large for fill: {}", intToString(len)); + "Length is too large for fill: {}", int_to_string(len)); } size_t idx = mpz_get_ui(index); @@ -234,7 +234,7 @@ list list_push_back(list *list, block *value) { return list->push_back(value); } -void printList( +void print_list( writer *file, list *list, char const *unit, char const *element, char const *concat, void *state) { size_t size = list->size(); @@ -243,8 +243,8 @@ void printList( return; } - auto tag = getTagForSymbolName(element); - auto *arg_sorts = getArgumentSortsForTag(tag); + auto tag = get_tag_for_symbol_name(element); + auto *arg_sorts = get_argument_sorts_for_tag(tag); sfprintf(file, "\\left-assoc{}(%s(", concat); @@ -256,7 +256,7 @@ void printList( sfprintf(file, ","); } sfprintf(file, "%s(", element); - printConfigurationInternal(file, *iter, arg_sorts[0], false, state); + print_configuration_internal(file, *iter, arg_sorts[0], false, state); sfprintf(file, ")"); } sfprintf(file, "))"); diff --git a/runtime/collections/maps.cpp b/runtime/collections/maps.cpp index c4310efb5..98afcd0cf 100644 --- a/runtime/collections/maps.cpp +++ b/runtime/collections/maps.cpp @@ -50,11 +50,10 @@ SortKItem hook_MAP_lookup(SortMap m, SortKItem key) { return res; } -SortKItem -hook_MAP_lookupOrDefault(SortMap m, SortKItem key, SortKItem _default) { +SortKItem hook_MAP_lookupOrDefault(SortMap m, SortKItem key, SortKItem def) { auto *res = hook_MAP_lookup_null(m, key); if (!res) { - return _default; + return def; } return res; } @@ -191,7 +190,7 @@ map map_map(map *map, block *(process)(block *)) { return tmp; } -void printMap( +void print_map( writer *file, map *map, char const *unit, char const *element, char const *concat, void *state) { size_t size = map->size(); @@ -200,8 +199,8 @@ void printMap( return; } - auto tag = getTagForSymbolName(element); - auto *arg_sorts = getArgumentSortsForTag(tag); + auto tag = get_tag_for_symbol_name(element); + auto *arg_sorts = get_argument_sorts_for_tag(tag); sfprintf(file, "\\left-assoc{}(%s(", concat); @@ -215,9 +214,10 @@ void printMap( sfprintf(file, "%s(", element); auto entry = *iter; - printConfigurationInternal(file, entry.first, arg_sorts[0], false, state); + print_configuration_internal(file, entry.first, arg_sorts[0], false, state); sfprintf(file, ","); - printConfigurationInternal(file, entry.second, arg_sorts[1], false, state); + print_configuration_internal( + file, entry.second, arg_sorts[1], false, state); sfprintf(file, ")"); } sfprintf(file, "))"); diff --git a/runtime/collections/rangemaps.cpp b/runtime/collections/rangemaps.cpp index d13b12a2e..5e07dda5e 100644 --- a/runtime/collections/rangemaps.cpp +++ b/runtime/collections/rangemaps.cpp @@ -5,7 +5,7 @@ extern "C" { rangemap hook_RANGEMAP_element(SortKItem start, SortKItem end, SortKItem value) { - return rangemap().inserted(rng_map::Range(start, end), value); + return rangemap().inserted(rng_map::Range(start, end), value); } struct range { @@ -16,8 +16,8 @@ struct range { static struct blockheader range_header() { static struct blockheader hdr = {(uint64_t)-1}; if (hdr.hdr == -1) { - hdr = getBlockHeaderForSymbol( - (uint64_t)getTagForSymbolName("LblRangemap'Coln'Range{}")); + hdr = get_block_header_for_symbol( + (uint64_t)get_tag_for_symbol_name("LblRangemap'Coln'Range{}")); } return hdr; } @@ -52,11 +52,11 @@ SortKItem hook_RANGEMAP_lookup(SortRangeMap m, SortKItem key) { return res; } -SortKItem hook_RANGEMAP_lookupOrDefault( - SortRangeMap m, SortKItem key, SortKItem _default) { +SortKItem +hook_RANGEMAP_lookupOrDefault(SortRangeMap m, SortKItem key, SortKItem def) { auto *res = hook_RANGEMAP_lookup_null(m, key); if (!res) { - return _default; + return def; } return res; } @@ -64,7 +64,7 @@ SortKItem hook_RANGEMAP_lookupOrDefault( SortRange hook_RANGEMAP_find_range(SortRangeMap m, SortKItem key) { auto val = m->get_key_value(key); if (val.has_value()) { - auto *ptr = (range *)koreAlloc(sizeof(range)); + auto *ptr = (range *)kore_alloc(sizeof(range)); ptr->h = range_header(); ptr->start = val.value().first.start(); ptr->end = val.value().first.end(); @@ -75,7 +75,7 @@ SortRange hook_RANGEMAP_find_range(SortRangeMap m, SortKItem key) { rangemap hook_RANGEMAP_update( SortRangeMap m, SortKItem start, SortKItem end, SortKItem value) { - return m->inserted(rng_map::Range(start, end), value); + return m->inserted(rng_map::Range(start, end), value); } rangemap @@ -85,7 +85,7 @@ hook_RANGEMAP_updateRng(SortRangeMap m, SortRange rng, SortKItem value) { } rangemap hook_RANGEMAP_remove(SortRangeMap m, SortKItem start, SortKItem end) { - return m->deleted(rng_map::Range(start, end)); + return m->deleted(rng_map::Range(start, end)); } rangemap hook_RANGEMAP_removeRng(SortRangeMap m, SortRange rng) { @@ -108,20 +108,20 @@ struct inj_range2kitem { static struct blockheader inj_range2kitem_header() { static struct blockheader hdr = {(uint64_t)-1}; if (hdr.hdr == -1) { - hdr = getBlockHeaderForSymbol( - (uint64_t)getTagForSymbolName("inj{SortRange{}, SortKItem{}}")); + hdr = get_block_header_for_symbol( + (uint64_t)get_tag_for_symbol_name("inj{SortRange{}, SortKItem{}}")); } return hdr; } set hook_RANGEMAP_keys(SortRangeMap m) { auto tmp = hook_SET_unit(); - for (auto iter = rng_map::ConstRangeMapIterator(*m); + for (auto iter = rng_map::ConstRangeMapIterator(*m); iter.has_next(); ++iter) { - auto *ptr = (range *)koreAlloc(sizeof(range)); + auto *ptr = (range *)kore_alloc(sizeof(range)); ptr->h = range_header(); ptr->start = iter->first.start(); ptr->end = iter->first.end(); - auto *inj_ptr = (inj_range2kitem *)koreAlloc(sizeof(inj_range2kitem)); + auto *inj_ptr = (inj_range2kitem *)kore_alloc(sizeof(inj_range2kitem)); inj_ptr->h = inj_range2kitem_header(); inj_ptr->child = ptr; auto elem = hook_SET_element((SortKItem)inj_ptr); @@ -132,13 +132,13 @@ set hook_RANGEMAP_keys(SortRangeMap m) { list hook_RANGEMAP_keys_list(SortRangeMap m) { auto tmp = list().transient(); - for (auto iter = rng_map::ConstRangeMapIterator(*m); + for (auto iter = rng_map::ConstRangeMapIterator(*m); iter.has_next(); ++iter) { - auto *ptr = (range *)koreAlloc(sizeof(range)); + auto *ptr = (range *)kore_alloc(sizeof(range)); ptr->h = range_header(); ptr->start = iter->first.start(); ptr->end = iter->first.end(); - auto *inj_ptr = (inj_range2kitem *)koreAlloc(sizeof(inj_range2kitem)); + auto *inj_ptr = (inj_range2kitem *)kore_alloc(sizeof(inj_range2kitem)); inj_ptr->h = inj_range2kitem_header(); inj_ptr->child = ptr; tmp.push_back((SortKItem)inj_ptr); @@ -152,7 +152,7 @@ bool hook_RANGEMAP_in_keys(SortKItem key, SortRangeMap m) { list hook_RANGEMAP_values(SortRangeMap m) { auto tmp = list().transient(); - for (auto iter = rng_map::ConstRangeMapIterator(*m); + for (auto iter = rng_map::ConstRangeMapIterator(*m); iter.has_next(); ++iter) { tmp.push_back(iter->second); } @@ -172,7 +172,7 @@ SortRange hook_RANGEMAP_choiceRng(SortRangeMap m) { KLLVM_HOOK_INVALID_ARGUMENT("Cannot choose from an empty range map"); } auto pair = m->treemap().root_data(); - auto *ptr = (range *)koreAlloc(sizeof(range)); + auto *ptr = (range *)kore_alloc(sizeof(range)); ptr->h = range_header(); ptr->start = pair.first.start(); ptr->end = pair.first.end(); @@ -197,7 +197,7 @@ bool hook_RANGEMAP_inclusion(SortRangeMap m1, SortRangeMap m2) { rangemap hook_RANGEMAP_updateAll(SortRangeMap m1, SortRangeMap m2) { auto *from = m2; auto to = *m1; - for (auto iter = rng_map::ConstRangeMapIterator(*from); + for (auto iter = rng_map::ConstRangeMapIterator(*from); iter.has_next(); ++iter) { to = to.inserted(iter->first, iter->second); } @@ -209,17 +209,17 @@ rangemap hook_RANGEMAP_removeAll(SortRangeMap map, SortSet set) { for (auto iter = set->begin(); iter != set->end(); ++iter) { auto *b_ptr = (block *)iter->elem; auto *r_ptr = (range *)(b_ptr->children[0]); - tmp = tmp.deleted(rng_map::Range(r_ptr->start, r_ptr->end)); + tmp = tmp.deleted(rng_map::Range(r_ptr->start, r_ptr->end)); } return tmp; } bool hook_RANGEMAP_eq(SortRangeMap m1, SortRangeMap m2) { - auto it1 = rng_map::ConstRangeMapIterator(*m1); - auto it2 = rng_map::ConstRangeMapIterator(*m2); + auto it1 = rng_map::ConstRangeMapIterator(*m1); + auto it2 = rng_map::ConstRangeMapIterator(*m2); for (; it1.has_next() && it2.has_next(); ++it1, ++it2) { - std::pair, KElem> const &r1 = *it1; - std::pair, KElem> const &r2 = *it2; + std::pair, k_elem> const &r1 = *it1; + std::pair, k_elem> const &r2 = *it2; if (r1 != r2) { return false; } @@ -229,7 +229,7 @@ bool hook_RANGEMAP_eq(SortRangeMap m1, SortRangeMap m2) { void rangemap_hash(rangemap *m, void *hasher) { if (hash_enter()) { - for (auto iter = rng_map::ConstRangeMapIterator(*m); + for (auto iter = rng_map::ConstRangeMapIterator(*m); iter.has_next(); ++iter) { auto entry = *iter; k_hash(entry.first.start(), hasher); @@ -242,7 +242,7 @@ void rangemap_hash(rangemap *m, void *hasher) { rangemap rangemap_map(rangemap *map, block *(process)(block *)) { auto tmp = *map; - for (auto iter = rng_map::ConstRangeMapIterator(*map); + for (auto iter = rng_map::ConstRangeMapIterator(*map); iter.has_next(); ++iter) { auto entry = *iter; tmp = tmp.inserted(entry.first, process(entry.second)); @@ -250,7 +250,7 @@ rangemap rangemap_map(rangemap *map, block *(process)(block *)) { return tmp; } -void printRangeMap( +void print_range_map( writer *file, rangemap *map, char const *unit, char const *element, char const *concat, void *state) { size_t size = map->size(); @@ -259,13 +259,13 @@ void printRangeMap( return; } - auto tag = getTagForSymbolName(element); - auto *arg_sorts = getArgumentSortsForTag(tag); + auto tag = get_tag_for_symbol_name(element); + auto *arg_sorts = get_argument_sorts_for_tag(tag); sfprintf(file, "\\left-assoc{}(%s(", concat); bool once = true; - for (auto iter = rng_map::ConstRangeMapIterator(*map); + for (auto iter = rng_map::ConstRangeMapIterator(*map); iter.has_next(); ++iter) { if (once) { once = false; @@ -276,13 +276,14 @@ void printRangeMap( sfprintf(file, "%s(", element); auto entry = *iter; sfprintf(file, "LblRangemap'Coln'Range{}("); - printConfigurationInternal( + print_configuration_internal( file, entry.first.start(), "SortKItem{}", false, state); sfprintf(file, ","); - printConfigurationInternal( + print_configuration_internal( file, entry.first.end(), "SortKItem{}", false, state); sfprintf(file, "),"); - printConfigurationInternal(file, entry.second, arg_sorts[1], false, state); + print_configuration_internal( + file, entry.second, arg_sorts[1], false, state); sfprintf(file, ")"); } sfprintf(file, "))"); diff --git a/runtime/collections/sets.cpp b/runtime/collections/sets.cpp index db71a4061..56720a197 100644 --- a/runtime/collections/sets.cpp +++ b/runtime/collections/sets.cpp @@ -137,7 +137,7 @@ set set_map(set *s, block *(process)(block *)) { return tmp; } -void printSet( +void print_set( writer *file, set *set, char const *unit, char const *element, char const *concat, void *state) { size_t size = set->size(); @@ -146,8 +146,8 @@ void printSet( return; } - auto tag = getTagForSymbolName(element); - auto *arg_sorts = getArgumentSortsForTag(tag); + auto tag = get_tag_for_symbol_name(element); + auto *arg_sorts = get_argument_sorts_for_tag(tag); sfprintf(file, "\\left-assoc{}(%s(", concat); @@ -160,7 +160,7 @@ void printSet( } sfprintf(file, "%s(", element); - printConfigurationInternal(file, *iter, arg_sorts[0], false, state); + print_configuration_internal(file, *iter, arg_sorts[0], false, state); sfprintf(file, ")"); } sfprintf(file, "))"); diff --git a/runtime/fresh.ll b/runtime/fresh.ll index 099e14700..0dc848cbe 100644 --- a/runtime/fresh.ll +++ b/runtime/fresh.ll @@ -13,10 +13,10 @@ define weak tailcc %block* @"eval_LblgetGeneratedCounterCell{SortGeneratedTopCel unreachable } -declare i32 @getTagForFreshSort(i8*) +declare i32 @get_tag_for_fresh_sort(i8*) declare %mpz* @hook_INT_add(%mpz*, %mpz*) -declare i8* @evaluateFunctionSymbol(i32, i8**) -declare i8* @getTerminatedString(%string*) +declare i8* @evaluate_function_symbol(i32, i8**) +declare i8* @get_terminated_string(%string*) @fresh_int_1 = global %mpz { i32 1, i32 1, i64* getelementptr inbounds ([1 x i64], [1 x i64]* @fresh_int_1_limbs, i32 0, i32 0) } @fresh_int_1_limbs = global [1 x i64] [i64 1] @@ -29,12 +29,12 @@ entry: %currCounter = load %mpz*, %mpz** %mpzPtrPtr %nextCounter = call %mpz* @hook_INT_add(%mpz* %currCounter, %mpz* @fresh_int_1) store %mpz* %nextCounter, %mpz** %mpzPtrPtr - %sortData = call i8* @getTerminatedString(%string* %sort) - %tag = call i32 @getTagForFreshSort(i8* %sortData) + %sortData = call i8* @get_terminated_string(%string* %sort) + %tag = call i32 @get_tag_for_fresh_sort(i8* %sortData) %args = alloca i8* %voidPtr = bitcast %mpz* %currCounter to i8* store i8* %voidPtr, i8** %args - %retval = call i8* @evaluateFunctionSymbol(i32 %tag, i8** %args) + %retval = call i8* @evaluate_function_symbol(i32 %tag, i8** %args) ret i8* %retval } diff --git a/runtime/getTag.ll b/runtime/getTag.ll index 65a783659..3baff80dc 100644 --- a/runtime/getTag.ll +++ b/runtime/getTag.ll @@ -4,7 +4,7 @@ target triple = "@BACKEND_TARGET_TRIPLE@" %blockheader = type { i64 } %block = type { %blockheader, [0 x i64 *] } ; 16-bit layout, 8-bit length, 32-bit tag, children -define i32 @getTag(%block* %arg) { +define i32 @get_tag(%block* %arg) { %intptr = ptrtoint %block* %arg to i64 %isConstant = trunc i64 %intptr to i1 br i1 %isConstant, label %constant, label %block diff --git a/runtime/io/io.cpp b/runtime/io/io.cpp index 8224f2903..ddc2837dd 100644 --- a/runtime/io/io.cpp +++ b/runtime/io/io.cpp @@ -26,109 +26,108 @@ extern "C" { extern char kompiled_directory; -char *getTerminatedString(string *str); +char *get_terminated_string(string *str); -static block *dotK = leaf_block(getTagForSymbolName("dotk{}")); -static blockheader kseqHeader - = {getBlockHeaderForSymbol((uint64_t)getTagForSymbolName("kseq{}"))}; +static blockheader kseq_header = { + get_block_header_for_symbol((uint64_t)get_tag_for_symbol_name("kseq{}"))}; -static std::map logFiles; +static std::map log_files; static block *block_errno() { - char const *errStr = nullptr; + char const *err_str = nullptr; switch (errno) { - case EOF: errStr = GETTAG(EOF); break; - case E2BIG: errStr = GETTAG(E2BIG); break; - case EACCES: errStr = GETTAG(EACCES); break; - case EAGAIN: errStr = GETTAG(EAGAIN); break; - case EBADF: errStr = GETTAG(EBADF); break; - case EBUSY: errStr = GETTAG(EBUSY); break; - case ECHILD: errStr = GETTAG(ECHILD); break; - case EDEADLK: errStr = GETTAG(EDEADLK); break; - case EDOM: errStr = GETTAG(EDOM); break; - case EEXIST: errStr = GETTAG(EEXIST); break; - case EFAULT: errStr = GETTAG(EFAULT); break; - case EFBIG: errStr = GETTAG(EFBIG); break; - case EINTR: errStr = GETTAG(EINTR); break; - case EINVAL: errStr = GETTAG(EINVAL); break; - case EIO: errStr = GETTAG(EIO); break; - case EISDIR: errStr = GETTAG(EISDIR); break; - case EMFILE: errStr = GETTAG(EMFILE); break; - case EMLINK: errStr = GETTAG(EMLINK); break; - case ENAMETOOLONG: errStr = GETTAG(ENAMETOOLONG); break; - case ENFILE: errStr = GETTAG(ENFILE); break; - case ENODEV: errStr = GETTAG(ENODEV); break; - case ENOENT: errStr = GETTAG(ENOENT); break; - case ENOEXEC: errStr = GETTAG(ENOEXEC); break; - case ENOLCK: errStr = GETTAG(ENOLCK); break; - case ENOMEM: errStr = GETTAG(ENOMEM); break; - case ENOSPC: errStr = GETTAG(ENOSPC); break; - case ENOSYS: errStr = GETTAG(ENOSYS); break; - case ENOTDIR: errStr = GETTAG(ENOTDIR); break; - case ENOTEMPTY: errStr = GETTAG(ENOTEMPTY); break; - case ENOTTY: errStr = GETTAG(ENOTTY); break; - case ENXIO: errStr = GETTAG(ENXIO); break; - case EPERM: errStr = GETTAG(EPERM); break; - case EPIPE: errStr = GETTAG(EPIPE); break; - case ERANGE: errStr = GETTAG(ERANGE); break; - case EROFS: errStr = GETTAG(EROFS); break; - case ESPIPE: errStr = GETTAG(ESPIPE); break; - case ESRCH: errStr = GETTAG(ESRCH); break; - case EXDEV: errStr = GETTAG(EXDEV); break; + case EOF: err_str = GETTAG(EOF); break; + case E2BIG: err_str = GETTAG(E2BIG); break; + case EACCES: err_str = GETTAG(EACCES); break; + case EAGAIN: err_str = GETTAG(EAGAIN); break; + case EBADF: err_str = GETTAG(EBADF); break; + case EBUSY: err_str = GETTAG(EBUSY); break; + case ECHILD: err_str = GETTAG(ECHILD); break; + case EDEADLK: err_str = GETTAG(EDEADLK); break; + case EDOM: err_str = GETTAG(EDOM); break; + case EEXIST: err_str = GETTAG(EEXIST); break; + case EFAULT: err_str = GETTAG(EFAULT); break; + case EFBIG: err_str = GETTAG(EFBIG); break; + case EINTR: err_str = GETTAG(EINTR); break; + case EINVAL: err_str = GETTAG(EINVAL); break; + case EIO: err_str = GETTAG(EIO); break; + case EISDIR: err_str = GETTAG(EISDIR); break; + case EMFILE: err_str = GETTAG(EMFILE); break; + case EMLINK: err_str = GETTAG(EMLINK); break; + case ENAMETOOLONG: err_str = GETTAG(ENAMETOOLONG); break; + case ENFILE: err_str = GETTAG(ENFILE); break; + case ENODEV: err_str = GETTAG(ENODEV); break; + case ENOENT: err_str = GETTAG(ENOENT); break; + case ENOEXEC: err_str = GETTAG(ENOEXEC); break; + case ENOLCK: err_str = GETTAG(ENOLCK); break; + case ENOMEM: err_str = GETTAG(ENOMEM); break; + case ENOSPC: err_str = GETTAG(ENOSPC); break; + case ENOSYS: err_str = GETTAG(ENOSYS); break; + case ENOTDIR: err_str = GETTAG(ENOTDIR); break; + case ENOTEMPTY: err_str = GETTAG(ENOTEMPTY); break; + case ENOTTY: err_str = GETTAG(ENOTTY); break; + case ENXIO: err_str = GETTAG(ENXIO); break; + case EPERM: err_str = GETTAG(EPERM); break; + case EPIPE: err_str = GETTAG(EPIPE); break; + case ERANGE: err_str = GETTAG(ERANGE); break; + case EROFS: err_str = GETTAG(EROFS); break; + case ESPIPE: err_str = GETTAG(ESPIPE); break; + case ESRCH: err_str = GETTAG(ESRCH); break; + case EXDEV: err_str = GETTAG(EXDEV); break; #if EWOULDBLOCK != EAGAIN case EWOULDBLOCK: errStr = GETTAG(EWOULDBLOCK); break; #endif - case EINPROGRESS: errStr = GETTAG(EINPROGRESS); break; - case EALREADY: errStr = GETTAG(EALREADY); break; - case ENOTSOCK: errStr = GETTAG(ENOTSOCK); break; - case EDESTADDRREQ: errStr = GETTAG(EDESTADDRREQ); break; - case EMSGSIZE: errStr = GETTAG(EMSGSIZE); break; - case EPROTOTYPE: errStr = GETTAG(EPROTOTYPE); break; - case ENOPROTOOPT: errStr = GETTAG(ENOPROTOOPT); break; - case EPROTONOSUPPORT: errStr = GETTAG(EPROTONOSUPPORT); break; - case ESOCKTNOSUPPORT: errStr = GETTAG(ESOCKTNOSUPPORT); break; - case EOPNOTSUPP: errStr = GETTAG(EOPNOTSUPP); break; - case EPFNOSUPPORT: errStr = GETTAG(EPFNOSUPPORT); break; - case EAFNOSUPPORT: errStr = GETTAG(EAFNOSUPPORT); break; - case EADDRINUSE: errStr = GETTAG(EADDRINUSE); break; - case EADDRNOTAVAIL: errStr = GETTAG(EADDRNOTAVAIL); break; - case ENETDOWN: errStr = GETTAG(ENETDOWN); break; - case ENETUNREACH: errStr = GETTAG(ENETUNREACH); break; - case ENETRESET: errStr = GETTAG(ENETRESET); break; - case ECONNABORTED: errStr = GETTAG(ECONNABORTED); break; - case ECONNRESET: errStr = GETTAG(ECONNRESET); break; - case ENOBUFS: errStr = GETTAG(ENOBUFS); break; - case EISCONN: errStr = GETTAG(EISCONN); break; - case ENOTCONN: errStr = GETTAG(ENOTCONN); break; - case ESHUTDOWN: errStr = GETTAG(ESHUTDOWN); break; - case ETOOMANYREFS: errStr = GETTAG(ETOOMANYREFS); break; - case ETIMEDOUT: errStr = GETTAG(ETIMEDOUT); break; - case ECONNREFUSED: errStr = GETTAG(ECONNREFUSED); break; - case EHOSTDOWN: errStr = GETTAG(EHOSTDOWN); break; - case EHOSTUNREACH: errStr = GETTAG(EHOSTUNREACH); break; - case ELOOP: errStr = GETTAG(ELOOP); break; - case EOVERFLOW: errStr = GETTAG(EOVERFLOW); break; + case EINPROGRESS: err_str = GETTAG(EINPROGRESS); break; + case EALREADY: err_str = GETTAG(EALREADY); break; + case ENOTSOCK: err_str = GETTAG(ENOTSOCK); break; + case EDESTADDRREQ: err_str = GETTAG(EDESTADDRREQ); break; + case EMSGSIZE: err_str = GETTAG(EMSGSIZE); break; + case EPROTOTYPE: err_str = GETTAG(EPROTOTYPE); break; + case ENOPROTOOPT: err_str = GETTAG(ENOPROTOOPT); break; + case EPROTONOSUPPORT: err_str = GETTAG(EPROTONOSUPPORT); break; + case ESOCKTNOSUPPORT: err_str = GETTAG(ESOCKTNOSUPPORT); break; + case EOPNOTSUPP: err_str = GETTAG(EOPNOTSUPP); break; + case EPFNOSUPPORT: err_str = GETTAG(EPFNOSUPPORT); break; + case EAFNOSUPPORT: err_str = GETTAG(EAFNOSUPPORT); break; + case EADDRINUSE: err_str = GETTAG(EADDRINUSE); break; + case EADDRNOTAVAIL: err_str = GETTAG(EADDRNOTAVAIL); break; + case ENETDOWN: err_str = GETTAG(ENETDOWN); break; + case ENETUNREACH: err_str = GETTAG(ENETUNREACH); break; + case ENETRESET: err_str = GETTAG(ENETRESET); break; + case ECONNABORTED: err_str = GETTAG(ECONNABORTED); break; + case ECONNRESET: err_str = GETTAG(ECONNRESET); break; + case ENOBUFS: err_str = GETTAG(ENOBUFS); break; + case EISCONN: err_str = GETTAG(EISCONN); break; + case ENOTCONN: err_str = GETTAG(ENOTCONN); break; + case ESHUTDOWN: err_str = GETTAG(ESHUTDOWN); break; + case ETOOMANYREFS: err_str = GETTAG(ETOOMANYREFS); break; + case ETIMEDOUT: err_str = GETTAG(ETIMEDOUT); break; + case ECONNREFUSED: err_str = GETTAG(ECONNREFUSED); break; + case EHOSTDOWN: err_str = GETTAG(EHOSTDOWN); break; + case EHOSTUNREACH: err_str = GETTAG(EHOSTUNREACH); break; + case ELOOP: err_str = GETTAG(ELOOP); break; + case EOVERFLOW: err_str = GETTAG(EOVERFLOW); break; default: - auto *retBlock - = static_cast(koreAlloc(sizeof(block) + sizeof(mpz_ptr))); - retBlock->h = getBlockHeaderForSymbol( - (uint64_t)getTagForSymbolName("Lbl'Hash'unknownIOError{}")); + auto *ret_block + = static_cast(kore_alloc(sizeof(block) + sizeof(mpz_ptr))); + ret_block->h = get_block_header_for_symbol( + (uint64_t)get_tag_for_symbol_name("Lbl'Hash'unknownIOError{}")); mpz_t err; mpz_init_set_si(err, errno); mpz_ptr p = move_int(err); - memcpy(retBlock->children, &p, sizeof(mpz_ptr)); - return retBlock; + memcpy(ret_block->children, &p, sizeof(mpz_ptr)); + return ret_block; } - return leaf_block(getTagForSymbolName(errStr)); + return leaf_block(get_tag_for_symbol_name(err_str)); } static blockheader header_int() { static blockheader header = {(uint64_t)-1}; if (header.hdr == -1) { - header = getBlockHeaderForSymbol( - (uint64_t)getTagForSymbolName("inj{SortInt{}, SortIOInt{}}")); + header = get_block_header_for_symbol( + (uint64_t)get_tag_for_symbol_name("inj{SortInt{}, SortIOInt{}}")); } return header; @@ -138,8 +137,8 @@ blockheader header_err() { static blockheader header = {(uint64_t)-1}; if (header.hdr == -1) { - header = getBlockHeaderForSymbol( - (uint64_t)getTagForSymbolName("inj{SortIOError{}, SortKItem{}}")); + header = get_block_header_for_symbol( + (uint64_t)get_tag_for_symbol_name("inj{SortIOError{}, SortKItem{}}")); } return header; @@ -149,33 +148,35 @@ static blockheader header_string() { static blockheader header = {(uint64_t)-1}; if (header.hdr == -1) { - header = getBlockHeaderForSymbol( - (uint64_t)getTagForSymbolName("inj{SortString{}, SortIOString{}}")); + header = get_block_header_for_symbol( + (uint64_t)get_tag_for_symbol_name("inj{SortString{}, SortIOString{}}")); } return header; } -static inline block *getKSeqErrorBlock() { +static inline block *get_k_seq_error_block() { block *err = block_errno(); - auto *retBlock - = static_cast(koreAlloc(sizeof(block) + 2 * sizeof(block *))); - auto *inj = static_cast(koreAlloc(sizeof(block) + sizeof(block *))); - retBlock->h = kseqHeader; + auto *ret_block + = static_cast(kore_alloc(sizeof(block) + 2 * sizeof(block *))); + auto *inj = static_cast(kore_alloc(sizeof(block) + sizeof(block *))); + ret_block->h = kseq_header; inj->h = header_err(); memcpy(inj->children, &err, sizeof(block *)); - memcpy(retBlock->children, &inj, sizeof(block *)); - memcpy(retBlock->children + 1, &dotK, sizeof(block *)); - return retBlock; + memcpy(ret_block->children, &inj, sizeof(block *)); + + auto *dot_k_block = dot_k(); + memcpy(ret_block->children + 1, &dot_k_block, sizeof(block *)); + return ret_block; } -static inline block *getInjErrorBlock() { +static inline block *get_inj_error_block() { block *p = block_errno(); - auto *retBlock - = static_cast(koreAlloc(sizeof(block) + sizeof(block *))); - retBlock->h = header_err(); - memcpy(retBlock->children, &p, sizeof(block *)); - return retBlock; + auto *ret_block + = static_cast(kore_alloc(sizeof(block) + sizeof(block *))); + ret_block->h = header_err(); + memcpy(ret_block->children, &p, sizeof(block *)); + return ret_block; } #define MODE_R 1 @@ -186,7 +187,7 @@ static inline block *getInjErrorBlock() { #define MODE_B 32 #define MODE_P 64 -static int getFileModes(string *modes) { +static int get_file_modes(string *modes) { int flags = 0; int length = len(modes); @@ -217,7 +218,7 @@ static int getFileModes(string *modes) { SortIOInt hook_IO_open(SortString filename, SortString control) { int flags = 0; int access = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; - int modes = getFileModes(control); + int modes = get_file_modes(control); int fd = 0; mpz_t result; @@ -245,7 +246,7 @@ SortIOInt hook_IO_open(SortString filename, SortString control) { if (modes & MODE_B) { } - char *f = getTerminatedString(filename); + char *f = get_terminated_string(filename); fd = open(f, flags, access); // NOLINT(*-vararg) } else { errno = EINVAL; @@ -253,43 +254,43 @@ SortIOInt hook_IO_open(SortString filename, SortString control) { } if (-1 == fd) { - return getInjErrorBlock(); + return get_inj_error_block(); } - auto *retBlock - = static_cast(koreAlloc(sizeof(block) + sizeof(mpz_ptr))); - retBlock->h = header_int(); + auto *ret_block + = static_cast(kore_alloc(sizeof(block) + sizeof(mpz_ptr))); + ret_block->h = header_int(); mpz_init_set_si(result, fd); mpz_ptr p = move_int(result); - memcpy(retBlock->children, &p, sizeof(mpz_ptr)); - return retBlock; + memcpy(ret_block->children, &p, sizeof(mpz_ptr)); + return ret_block; } SortIOInt hook_IO_tell(SortInt i) { if (!mpz_fits_sint_p(i)) { - KLLVM_HOOK_INVALID_ARGUMENT("Arg too large for int: {}", intToString(i)); + KLLVM_HOOK_INVALID_ARGUMENT("Arg too large for int: {}", int_to_string(i)); } int fd = mpz_get_si(i); off_t loc = lseek(fd, 0, SEEK_CUR); if (-1 == loc) { - return getInjErrorBlock(); + return get_inj_error_block(); } - auto *retBlock - = static_cast(koreAlloc(sizeof(block) + sizeof(mpz_ptr))); - retBlock->h = header_int(); + auto *ret_block + = static_cast(kore_alloc(sizeof(block) + sizeof(mpz_ptr))); + ret_block->h = header_int(); mpz_t result; mpz_init_set_si(result, (long)loc); mpz_ptr p = move_int(result); - memcpy(retBlock->children, &p, sizeof(mpz_ptr)); - return retBlock; + memcpy(ret_block->children, &p, sizeof(mpz_ptr)); + return ret_block; } SortIOInt hook_IO_getc(SortInt i) { if (!mpz_fits_sint_p(i)) { - KLLVM_HOOK_INVALID_ARGUMENT("Arg too large for int: {}", intToString(i)); + KLLVM_HOOK_INVALID_ARGUMENT("Arg too large for int: {}", int_to_string(i)); } int fd = mpz_get_si(i); @@ -297,73 +298,74 @@ SortIOInt hook_IO_getc(SortInt i) { ssize_t ret = read(fd, &c, sizeof(char)); if (ret == 0) { - block *p = leaf_block(getTagForSymbolName(GETTAG(EOF))); - auto *retBlock - = static_cast(koreAlloc(sizeof(block) + sizeof(block *))); - retBlock->h = header_err(); - memcpy(retBlock->children, &p, sizeof(block *)); - return retBlock; + block *p = leaf_block(get_tag_for_symbol_name(GETTAG(EOF))); + auto *ret_block + = static_cast(kore_alloc(sizeof(block) + sizeof(block *))); + ret_block->h = header_err(); + memcpy(ret_block->children, &p, sizeof(block *)); + return ret_block; } if (ret == -1) { - return getInjErrorBlock(); + return get_inj_error_block(); } - auto *retBlock - = static_cast(koreAlloc(sizeof(block) + sizeof(mpz_ptr))); - retBlock->h = header_int(); + auto *ret_block + = static_cast(kore_alloc(sizeof(block) + sizeof(mpz_ptr))); + ret_block->h = header_int(); mpz_t result; mpz_init_set_si(result, (int)c); mpz_ptr p = move_int(result); - memcpy(retBlock->children, &p, sizeof(mpz_ptr)); - return retBlock; + memcpy(ret_block->children, &p, sizeof(mpz_ptr)); + return ret_block; } SortIOString hook_IO_read(SortInt i, SortInt len) { if (!mpz_fits_sint_p(i) || !mpz_fits_ulong_p(len)) { KLLVM_HOOK_INVALID_ARGUMENT( - "Arg too large: i={}, len={}", intToString(i), intToString(len)); + "Arg too large: i={}, len={}", int_to_string(i), int_to_string(len)); } int fd = mpz_get_si(i); size_t length = mpz_get_ui(len); - auto *result = static_cast(koreAllocToken(sizeof(string) + length)); + auto *result + = static_cast(kore_alloc_token(sizeof(string) + length)); int bytes = read(fd, &(result->data), length); if (-1 == bytes) { - return getInjErrorBlock(); + return get_inj_error_block(); } - result = static_cast(koreResizeLastAlloc( + result = static_cast(kore_resize_last_alloc( result, sizeof(string) + bytes, sizeof(string) + length)); - auto *retBlock - = static_cast(koreAlloc(sizeof(block) + sizeof(string *))); - retBlock->h = header_string(); + auto *ret_block + = static_cast(kore_alloc(sizeof(block) + sizeof(string *))); + ret_block->h = header_string(); init_with_len(result, bytes); - memcpy(retBlock->children, &result, sizeof(string *)); - return retBlock; + memcpy(ret_block->children, &result, sizeof(string *)); + return ret_block; } SortK hook_IO_close(SortInt i) { if (!mpz_fits_sint_p(i)) { - KLLVM_HOOK_INVALID_ARGUMENT("Arg too large for int: {}", intToString(i)); + KLLVM_HOOK_INVALID_ARGUMENT("Arg too large for int: {}", int_to_string(i)); } int fd = mpz_get_si(i); int ret = close(fd); if (ret == -1) { - return getKSeqErrorBlock(); + return get_k_seq_error_block(); } - return dotK; + return dot_k(); } SortK hook_IO_seek(SortInt i, SortInt loc) { if (!mpz_fits_sint_p(i) || !mpz_fits_slong_p(loc)) { KLLVM_HOOK_INVALID_ARGUMENT( - "Arg too large: i={}, loc={}", intToString(i), intToString(loc)); + "Arg too large: i={}, loc={}", int_to_string(i), int_to_string(loc)); } int fd = mpz_get_si(i); @@ -371,16 +373,16 @@ SortK hook_IO_seek(SortInt i, SortInt loc) { int ret = lseek(fd, l, SEEK_SET); if (ret == -1) { - return getKSeqErrorBlock(); + return get_k_seq_error_block(); } - return dotK; + return dot_k(); } SortK hook_IO_seekEnd(SortInt i, SortInt loc) { if (!mpz_fits_sint_p(i) || !mpz_fits_slong_p(loc)) { KLLVM_HOOK_INVALID_ARGUMENT( - "Arg too large: i={}, loc={}", intToString(i), intToString(loc)); + "Arg too large: i={}, loc={}", int_to_string(i), int_to_string(loc)); } int fd = mpz_get_si(i); @@ -388,16 +390,16 @@ SortK hook_IO_seekEnd(SortInt i, SortInt loc) { int ret = lseek(fd, l, SEEK_END); if (ret == -1) { - return getKSeqErrorBlock(); + return get_k_seq_error_block(); } - return dotK; + return dot_k(); } SortK hook_IO_putc(SortInt i, SortInt c) { if (!mpz_fits_sint_p(i) || !mpz_fits_sint_p(c)) { KLLVM_HOOK_INVALID_ARGUMENT( - "Arg too large: i={}, c={}", intToString(i), intToString(c)); + "Arg too large: i={}, c={}", int_to_string(i), int_to_string(c)); } int fd = mpz_get_si(i); @@ -405,31 +407,31 @@ SortK hook_IO_putc(SortInt i, SortInt c) { int ret = write(fd, &ch, 1); if (ret == -1) { - return getKSeqErrorBlock(); + return get_k_seq_error_block(); } - return dotK; + return dot_k(); } SortK hook_IO_write(SortInt i, SortString str) { if (!mpz_fits_sint_p(i)) { - KLLVM_HOOK_INVALID_ARGUMENT("Arg too large for int: {}", intToString(i)); + KLLVM_HOOK_INVALID_ARGUMENT("Arg too large for int: {}", int_to_string(i)); } int fd = mpz_get_si(i); int ret = write(fd, str->data, len(str)); if (ret == -1) { - return getKSeqErrorBlock(); + return get_k_seq_error_block(); } - return dotK; + return dot_k(); } SortK hook_IO_lock(SortInt i, SortInt len) { if (!mpz_fits_sint_p(i) || !mpz_fits_slong_p(len)) { KLLVM_HOOK_INVALID_ARGUMENT( - "Arg too large: i={}, len={}", intToString(i), intToString(len)); + "Arg too large: i={}, len={}", int_to_string(i), int_to_string(len)); } int fd = mpz_get_si(i); @@ -443,16 +445,16 @@ SortK hook_IO_lock(SortInt i, SortInt len) { int ret = fcntl(fd, F_SETLKW, &lockp); // NOLINT(*-vararg) if (ret == -1) { - return getKSeqErrorBlock(); + return get_k_seq_error_block(); } - return dotK; + return dot_k(); } SortK hook_IO_unlock(SortInt i, SortInt len) { if (!mpz_fits_sint_p(i) || !mpz_fits_slong_p(len)) { KLLVM_HOOK_INVALID_ARGUMENT( - "Arg too large: i={}, len={}", intToString(i), intToString(len)); + "Arg too large: i={}, len={}", int_to_string(i), int_to_string(len)); } int fd = mpz_get_si(i); @@ -466,72 +468,72 @@ SortK hook_IO_unlock(SortInt i, SortInt len) { int ret = fcntl(fd, F_SETLKW, &lockp); // NOLINT(*-vararg) if (ret == -1) { - return getKSeqErrorBlock(); + return get_k_seq_error_block(); } - return dotK; + return dot_k(); } SortK hook_IO_remove(SortString path) { - char *p = getTerminatedString(path); + char *p = get_terminated_string(path); int ret = unlink(p); if (ret == -1) { - return getKSeqErrorBlock(); + return get_k_seq_error_block(); } - return dotK; + return dot_k(); } SortIOInt hook_IO_accept(SortInt sock) { if (!mpz_fits_sint_p(sock)) { - KLLVM_HOOK_INVALID_ARGUMENT("Arg too large: {}", intToString(sock)); + KLLVM_HOOK_INVALID_ARGUMENT("Arg too large: {}", int_to_string(sock)); } int fd = mpz_get_si(sock); int clientsock = accept(fd, nullptr, nullptr); if (clientsock == -1) { - return getInjErrorBlock(); + return get_inj_error_block(); } - auto *retBlock - = static_cast(koreAlloc(sizeof(block) + sizeof(mpz_ptr))); - retBlock->h = header_int(); + auto *ret_block + = static_cast(kore_alloc(sizeof(block) + sizeof(mpz_ptr))); + ret_block->h = header_int(); mpz_t result; mpz_init_set_si(result, clientsock); mpz_ptr p = move_int(result); - memcpy(retBlock->children, &p, sizeof(mpz_ptr)); - return retBlock; + memcpy(ret_block->children, &p, sizeof(mpz_ptr)); + return ret_block; } SortK hook_IO_shutdownWrite(SortInt sock) { if (!mpz_fits_sint_p(sock)) { - KLLVM_HOOK_INVALID_ARGUMENT("Arg too large: {}", intToString(sock)); + KLLVM_HOOK_INVALID_ARGUMENT("Arg too large: {}", int_to_string(sock)); } int fd = mpz_get_si(sock); int ret = shutdown(fd, SHUT_WR); if (ret == -1) { - return getKSeqErrorBlock(); + return get_k_seq_error_block(); } - return dotK; + return dot_k(); } -void flush_IO_logs() { +void flush_io_logs() { std::string pid = std::to_string(getpid()); - for (auto const &log : logFiles) { - std::string pathStr = log.first; + for (auto const &log : log_files) { + std::string path_str = log.first; std::string msg = log.second; - size_t length = pathStr.length(); + size_t length = path_str.length(); char *path1 = (char *)malloc(sizeof(char) * (length + 1)); - strncpy(path1, pathStr.c_str(), length + 1); + strncpy(path1, path_str.c_str(), length + 1); path1[length] = '\0'; char *path2 = (char *)malloc(sizeof(char) * (length + 1)); - strncpy(path2, pathStr.c_str(), length + 1); + strncpy(path2, path_str.c_str(), length + 1); path2[length] = '\0'; char *dir = dirname(path1); if (getenv("K_LOG_DIR")) { @@ -546,8 +548,8 @@ void flush_IO_logs() { if (getenv("K_LOG_PREFIX")) { prefix = getenv("K_LOG_PREFIX"); } - auto fullPath = fmt::format("{}/{}{}_{}", fulldir, prefix, pid, base); - FILE *f = fopen(fullPath.c_str(), "a+"); + auto full_path = fmt::format("{}/{}{}_{}", fulldir, prefix, pid, base); + FILE *f = fopen(full_path.c_str(), "a+"); fwrite(msg.c_str(), sizeof(char), msg.length(), f); fclose(f); free(path1); @@ -556,24 +558,24 @@ void flush_IO_logs() { } SortK hook_IO_log(SortString path, SortString msg) { - char *p = getTerminatedString(path); - char *m = getTerminatedString(msg); + char *p = get_terminated_string(path); + char *m = get_terminated_string(msg); - static bool flushRegistered = false; - if (!flushRegistered) { - atexit(&flush_IO_logs); - flushRegistered = true; + static bool flush_registered = false; + if (!flush_registered) { + atexit(&flush_io_logs); + flush_registered = true; } - logFiles[p].append(m); + log_files[p].append(m); - return dotK; + return dot_k(); } SortK hook_IO_logString(SortString msg) { - char *m = getTerminatedString(msg); + char *m = get_terminated_string(msg); std::cerr << m << std::endl; - return dotK; + return dot_k(); } block *hook_KREFLECTION_parseKAST(string *kast) { @@ -588,11 +590,11 @@ string *hook_KREFLECTION_getenv(string *str) { KLLVM_HOOK_INVALID_ARGUMENT("not implemented: KREFLECTION.getenv"); } -string *hook_KREFLECTION_sort(block *K) { +string *hook_KREFLECTION_sort(block *k) { KLLVM_HOOK_INVALID_ARGUMENT("not implemented: KREFLECTION.sort"); } -block *hook_KREFLECTION_getKLabel(block *K) { +block *hook_KREFLECTION_getKLabel(block *k) { KLLVM_HOOK_INVALID_ARGUMENT("not implemented: KREFLECTION.getKLabel"); } @@ -603,7 +605,7 @@ block *hook_KREFLECTION_fresh(string *str) { string *hook_KREFLECTION_kompiledDir(void) { auto *str_ptr = &kompiled_directory; auto len = strlen(str_ptr); - auto *ret = static_cast(koreAllocToken(sizeof(string) + len)); + auto *ret = static_cast(kore_alloc_token(sizeof(string) + len)); memcpy(ret->data, str_ptr, len); init_with_len(ret, len); return ret; @@ -625,41 +627,41 @@ list hook_KREFLECTION_argv() { buf, llvm_backend_argv[i], strlen(llvm_backend_argv[i])); SortString str = hook_BUFFER_toString(buf); auto *b - = static_cast(koreAlloc(sizeof(block) + sizeof(SortString))); - b->h = getBlockHeaderForSymbol( - (uint64_t)getTagForSymbolName("inj{SortString{}, SortKItem{}}")); + = static_cast(kore_alloc(sizeof(block) + sizeof(SortString))); + b->h = get_block_header_for_symbol( + (uint64_t)get_tag_for_symbol_name("inj{SortString{}, SortKItem{}}")); memcpy(b->children, &str, sizeof(SortString)); - l = l.push_back(KElem(b)); + l = l.push_back(k_elem(b)); } return l; } SortIOFile hook_IO_mkstemp(SortString filename) { - char *temp = getTerminatedString(filename); + char *temp = get_terminated_string(filename); int ret = mkstemp(temp); if (ret == -1) { - return getInjErrorBlock(); + return get_inj_error_block(); } - auto *retBlock = static_cast( - koreAlloc(sizeof(block) + sizeof(string *) + sizeof(mpz_ptr))); + auto *ret_block = static_cast( + kore_alloc(sizeof(block) + sizeof(string *) + sizeof(mpz_ptr))); mpz_t result; mpz_init_set_si(result, ret); mpz_ptr p = move_int(result); size_t length = len(filename); - auto *retString = static_cast( - koreAllocToken(sizeof(string) + sizeof(char) * length)); - memcpy(retString->data, temp, sizeof(char) * length); - init_with_len(retString, length); - memcpy(retBlock->children, &retString, sizeof(string *)); - memcpy(retBlock->children + 1, &p, sizeof(mpz_ptr)); - retBlock->h = getBlockHeaderForSymbol( - (uint64_t)getTagForSymbolName(GETTAG(tempFile))); + auto *ret_string = static_cast( + kore_alloc_token(sizeof(string) + sizeof(char) * length)); + memcpy(ret_string->data, temp, sizeof(char) * length); + init_with_len(ret_string, length); + memcpy(ret_block->children, &ret_string, sizeof(string *)); + memcpy(ret_block->children + 1, &p, sizeof(mpz_ptr)); + ret_block->h = get_block_header_for_symbol( + (uint64_t)get_tag_for_symbol_name(GETTAG(tempFile))); - return retBlock; + return ret_block; } // NOLINTNEXTLINE(*-cognitive-complexity) @@ -668,13 +670,13 @@ SortKItem hook_IO_system(SortString cmd) { int ret = 0; int out[2]; int err[2]; - stringbuffer *outBuffer = hook_BUFFER_empty(); - stringbuffer *errBuffer = hook_BUFFER_empty(); + stringbuffer *out_buffer = hook_BUFFER_empty(); + stringbuffer *err_buffer = hook_BUFFER_empty(); char buf[IOBUFSIZE]; // NOLINTNEXTLINE(*-assignment-in-if-condition) if (pipe(out) == -1 || pipe(err) == -1 || (pid = fork()) == -1) { - return getKSeqErrorBlock(); + return get_k_seq_error_block(); } if (pid == 0) { @@ -686,7 +688,7 @@ SortKItem hook_IO_system(SortString cmd) { close(err[1]); if (len(cmd) > 0) { - char *command = getTerminatedString(cmd); + char *command = get_terminated_string(cmd); // NOLINTNEXTLINE(*-vararg) ret = execl("/bin/sh", "/bin/sh", "-c", command, nullptr); @@ -711,32 +713,32 @@ SortKItem hook_IO_system(SortString cmd) { while (done < 2) { ready_fds = read_fds; if (select(FD_SETSIZE, &ready_fds, nullptr, nullptr, nullptr) == -1) { - return getKSeqErrorBlock(); + return get_k_seq_error_block(); } if (FD_ISSET(out[0], &ready_fds)) { int nread = read(out[0], buf, IOBUFSIZE); if (nread == -1) { - return getKSeqErrorBlock(); + return get_k_seq_error_block(); } if (nread == 0) { FD_CLR(out[0], &read_fds); done++; } else { - hook_BUFFER_concat_raw(outBuffer, buf, nread); + hook_BUFFER_concat_raw(out_buffer, buf, nread); } } if (FD_ISSET(err[0], &ready_fds)) { int nread = read(err[0], buf, IOBUFSIZE); if (nread == -1) { - return getKSeqErrorBlock(); + return get_k_seq_error_block(); } if (nread == 0) { FD_CLR(err[0], &read_fds); done++; } else { - hook_BUFFER_concat_raw(errBuffer, buf, nread); + hook_BUFFER_concat_raw(err_buffer, buf, nread); } } } @@ -744,24 +746,24 @@ SortKItem hook_IO_system(SortString cmd) { waitpid(pid, &ret, 0); ret = WEXITSTATUS(ret); - auto *retBlock = static_cast(koreAlloc( + auto *ret_block = static_cast(kore_alloc( sizeof(block) + sizeof(mpz_ptr) + sizeof(string *) + sizeof(string *))); mpz_t result; mpz_init_set_si(result, ret); mpz_ptr p = move_int(result); - memcpy(retBlock->children, &p, sizeof(mpz_ptr)); - - retBlock->h = getBlockHeaderForSymbol( - (uint64_t)getTagForSymbolName(GETTAG(systemResult))); - string *outStr = nullptr; - string *errStr = nullptr; - outStr = hook_BUFFER_toString(outBuffer); - errStr = hook_BUFFER_toString(errBuffer); - memcpy(retBlock->children + 1, &outStr, sizeof(string *)); - memcpy(retBlock->children + 2, &errStr, sizeof(string *)); - - return retBlock; + memcpy(ret_block->children, &p, sizeof(mpz_ptr)); + + ret_block->h = get_block_header_for_symbol( + (uint64_t)get_tag_for_symbol_name(GETTAG(systemResult))); + string *out_str = nullptr; + string *err_str = nullptr; + out_str = hook_BUFFER_toString(out_buffer); + err_str = hook_BUFFER_toString(err_buffer); + memcpy(ret_block->children + 1, &out_str, sizeof(string *)); + memcpy(ret_block->children + 2, &err_str, sizeof(string *)); + + return ret_block; } block *hook_IO_stat(string *path) { diff --git a/runtime/io/logTerm.cpp b/runtime/io/logTerm.cpp index 2f36acf1c..242aa720b 100644 --- a/runtime/io/logTerm.cpp +++ b/runtime/io/logTerm.cpp @@ -7,17 +7,15 @@ #include "kllvm/util/temporary_file.h" #include "runtime/header.h" -static block *dotK = leaf_block(getTagForSymbolName("dotk{}")); - extern "C" { extern char kompiled_directory; block *hook_IO_log(string *path, string *msg); -int getTag(block *term); +int get_tag(block *term); SortKItem hook_IO_logTerm(SortString path, SortKItem term) { - string *msg = printConfigurationToString(term); + string *msg = print_configuration_to_string(term); hook_IO_log(path, msg); return term; } @@ -29,12 +27,12 @@ SortK hook_IO_traceTerm(block *term) { // Ensure that the term is injected into KItem correctly; if we don't do this // then the unparsed KORE ends up with a (null) in it which breaks the // printing below. - printSortedConfigurationToFile(fp, term, "SortKItem{}"); + print_sorted_configuration_to_file(fp, term, "SortKItem{}"); fflush(fp); - kllvm::printKORE( + kllvm::print_kore( std::cerr, &kompiled_directory, temp_file.filename(), false, true); - return dotK; + return dot_k(); } } diff --git a/runtime/io/parseKORE.cpp b/runtime/io/parseKORE.cpp index 11feb36bc..ce362f643 100644 --- a/runtime/io/parseKORE.cpp +++ b/runtime/io/parseKORE.cpp @@ -5,9 +5,8 @@ #include "runtime/header.h" extern "C" { -static block *dotK = leaf_block(getTagForSymbolName("dotk{}")); SortString hook_KREFLECTION_printKORE(block *subject) { - return printConfigurationToString(subject); + return print_configuration_to_string(subject); } } diff --git a/runtime/json/json.cpp b/runtime/json/json.cpp index 528be1385..29c7d03cd 100644 --- a/runtime/json/json.cpp +++ b/runtime/json/json.cpp @@ -12,11 +12,11 @@ using namespace rapidjson; extern "C" { floating *move_float(floating *); string *hook_STRING_int2string(mpz_t); -string *makeString(char const *input, ssize_t len = -1); -char *getTerminatedString(string *); +string *make_string(char const *input, ssize_t len = -1); +char *get_terminated_string(string *); } -std::string floatToString(floating const *f, char const *suffix); +std::string float_to_string(floating const *f, char const *suffix); struct zinj { blockheader h; @@ -55,15 +55,15 @@ struct jsonmember { block *val; }; -static block *dotK = leaf_block(getTagForSymbolName("dotk{}")); -static blockheader kseqHeader - = {getBlockHeaderForSymbol((uint64_t)getTagForSymbolName("kseq{}"))}; +static blockheader kseq_header = { + get_block_header_for_symbol((uint64_t)get_tag_for_symbol_name("kseq{}"))}; #define GET_HEADER(name, symbol) \ static struct blockheader name() { \ static struct blockheader hdr = {(uint64_t)-1}; \ if (hdr.hdr == -1) { \ - hdr = getBlockHeaderForSymbol((uint64_t)getTagForSymbolName(symbol)); \ + hdr = get_block_header_for_symbol( \ + (uint64_t)get_tag_for_symbol_name(symbol)); \ } \ return hdr; \ } @@ -81,7 +81,7 @@ GET_HEADER(listWrapHdr, "LblJSONList{}"); static block *name() { \ static uint64_t tag = (uint64_t)-1; \ if (tag == -1) { \ - tag = (uint64_t)leaf_block(getTagForSymbolName(symbol)); \ + tag = (uint64_t)leaf_block(get_tag_for_symbol_name(symbol)); \ } \ return (block *)tag; \ } @@ -89,7 +89,7 @@ GET_HEADER(listWrapHdr, "LblJSONList{}"); GET_BLOCK(dotList, "Lbl'Stop'List'LBraQuot'JSONs'QuotRBra'{}"); GET_BLOCK(null, "LblJSONnull{}"); -struct KoreHandler : BaseReaderHandler, KoreHandler> { +struct kore_handler : BaseReaderHandler, kore_handler> { block *result = nullptr; std::vector stack; @@ -98,7 +98,7 @@ struct KoreHandler : BaseReaderHandler, KoreHandler> { return true; } bool Bool(bool b) { - auto *inj = (boolinj *)koreAlloc(sizeof(boolinj)); + auto *inj = (boolinj *)kore_alloc(sizeof(boolinj)); inj->h = boolHdr(); inj->data = b; result = (block *)inj; @@ -110,7 +110,7 @@ struct KoreHandler : BaseReaderHandler, KoreHandler> { mpz_t z; int status = mpz_init_set_str(z, str, 10); if (status == 0) { - zinj *inj = (zinj *)koreAlloc(sizeof(zinj)); + zinj *inj = (zinj *)kore_alloc(sizeof(zinj)); inj->h = intHdr(); inj->data = move_int(z); result = (block *)inj; @@ -123,7 +123,7 @@ struct KoreHandler : BaseReaderHandler, KoreHandler> { mpfr_init2(f->f, 53); f->exp = 11; mpfr_set_str(f->f, str, 9, MPFR_RNDN); - auto *inj = (floatinj *)koreAlloc(sizeof(floatinj)); + auto *inj = (floatinj *)kore_alloc(sizeof(floatinj)); inj->h = floatHdr(); inj->data = move_float(f); result = (block *)inj; @@ -132,9 +132,9 @@ struct KoreHandler : BaseReaderHandler, KoreHandler> { } bool String(char const *str, SizeType len, bool copy) { - auto *inj = (stringinj *)koreAlloc(sizeof(stringinj)); + auto *inj = (stringinj *)kore_alloc(sizeof(stringinj)); inj->h = strHdr(); - auto *token = (string *)koreAllocToken(sizeof(string) + len); + auto *token = (string *)kore_alloc_token(sizeof(string) + len); init_with_len(token, len); memcpy(token->data, str, len); inj->data = token; @@ -149,22 +149,22 @@ struct KoreHandler : BaseReaderHandler, KoreHandler> { return String(str, len, copy); } - bool EndObject(SizeType memberCount) { + bool EndObject(SizeType member_count) { result = dotList(); - for (int i = 0; i < memberCount; i++) { - auto *member = (jsonmember *)koreAlloc(sizeof(jsonmember)); + for (int i = 0; i < member_count; i++) { + auto *member = (jsonmember *)kore_alloc(sizeof(jsonmember)); member->h = membHdr(); member->val = stack.back(); stack.pop_back(); member->key = stack.back(); stack.pop_back(); - auto *list = (jsonlist *)koreAlloc(sizeof(jsonlist)); + auto *list = (jsonlist *)kore_alloc(sizeof(jsonlist)); list->h = listHdr(); list->hd = (block *)member; list->tl = (jsonlist *)result; result = (block *)list; } - json *wrap = (json *)koreAlloc(sizeof(json)); + json *wrap = (json *)kore_alloc(sizeof(json)); wrap->h = objHdr(); wrap->data = (jsonlist *)result; stack.push_back((block *)wrap); @@ -173,17 +173,17 @@ struct KoreHandler : BaseReaderHandler, KoreHandler> { static bool StartArray() { return true; } - bool EndArray(SizeType elementCount) { + bool EndArray(SizeType element_count) { result = dotList(); - for (int i = 0; i < elementCount; i++) { - auto *list = (jsonlist *)koreAlloc(sizeof(jsonlist)); + for (int i = 0; i < element_count; i++) { + auto *list = (jsonlist *)kore_alloc(sizeof(jsonlist)); list->h = listHdr(); list->hd = stack.back(); stack.pop_back(); list->tl = (jsonlist *)result; result = (block *)list; } - json *wrap = (json *)koreAlloc(sizeof(json)); + json *wrap = (json *)kore_alloc(sizeof(json)); wrap->h = listWrapHdr(); wrap->data = (jsonlist *)result; stack.push_back((block *)wrap); @@ -192,8 +192,8 @@ struct KoreHandler : BaseReaderHandler, KoreHandler> { }; template -struct KoreWriter : Writer { - bool RawNumber( +struct kore_writer : Writer { + bool raw_number( typename Writer::Ch const *str, rapidjson::SizeType length, bool copy = false) { (void)copy; @@ -201,12 +201,12 @@ struct KoreWriter : Writer { return Writer::EndValue(Writer::WriteRawValue(str, length)); } - KoreWriter(Stream &os) + kore_writer(Stream &os) : Writer(os) { } }; template -static bool write_json(KoreWriter &writer, block *data) { +static bool write_json(kore_writer &writer, block *data) { bool return_value = true; if (data != dotList()) { if (data == null()) { @@ -217,11 +217,11 @@ static bool write_json(KoreWriter &writer, block *data) { } else if (tag_hdr(data->h.hdr) == tag_hdr(intHdr().hdr)) { zinj *inj = (zinj *)data; string *str = hook_STRING_int2string(inj->data); - writer.RawNumber(str->data, len(str), false); + writer.raw_number(str->data, len(str), false); } else if (tag_hdr(data->h.hdr) == tag_hdr(floatHdr().hdr)) { auto *inj = (floatinj *)data; - std::string str = floatToString(inj->data, ""); - writer.RawNumber(str.c_str(), str.length(), false); + std::string str = float_to_string(inj->data, ""); + writer.raw_number(str.c_str(), str.length(), false); } else if (tag_hdr(data->h.hdr) == tag_hdr(strHdr().hdr)) { auto *inj = (stringinj *)data; writer.String(inj->data->data, len(inj->data), false); @@ -255,17 +255,17 @@ extern "C" { SortString hook_JSON_json2string(SortJSON json) { StringBuffer buffer; - KoreWriter writer(buffer); + kore_writer writer(buffer); if (!write_json(writer, json)) { abort(); } - return makeString(buffer.GetString()); + return make_string(buffer.GetString()); } SortJSON hook_JSON_string2json(SortString str) { - char *cstr = getTerminatedString(str); + char *cstr = get_terminated_string(str); StringStream s(cstr); - KoreHandler handler; + kore_handler handler; Reader reader; bool result = reader.Parse(s, handler); if (result) { diff --git a/runtime/main/main.ll b/runtime/main/main.ll index 3209c28d3..df83bd116 100644 --- a/runtime/main/main.ll +++ b/runtime/main/main.ll @@ -4,16 +4,16 @@ target triple = "@BACKEND_TARGET_TRIPLE@" %blockheader = type { i64 } %block = type { %blockheader, [0 x i64 *] } ; 16-bit layout, 8-bit length, 32-bit tag, children -declare %block* @parseConfiguration(i8*) +declare %block* @parse_configuration(i8*) declare i64 @atol(i8*) declare i8* @fopen(i8*, i8*) declare %block* @take_steps(i64, %block*) declare void @finish_rewriting(%block*, i1) #0 -declare void @initStaticObjects() +declare void @init_static_objects() -declare void @printProofHintHeader(i8*) +declare void @print_proof_hint_header(i8*) @statistics.flag = private constant [13 x i8] c"--statistics\00" @binary_out.flag = private constant [16 x i8] c"--binary-output\00" @@ -94,15 +94,15 @@ entry: call void @parse_flags(i32 %argc, i8** %argv) - call void @initStaticObjects() + call void @init_static_objects() %proof_output = load i1, i1* @proof_output br i1 %proof_output, label %if, label %else if: - call void @printProofHintHeader(i8* %output_file) + call void @print_proof_hint_header(i8* %output_file) br label %else else: - %ret = call %block* @parseConfiguration(i8* %filename) + %ret = call %block* @parse_configuration(i8* %filename) %result = call %block* @take_steps(i64 %depth, %block* %ret) call void @finish_rewriting(%block* %result, i1 0) unreachable diff --git a/runtime/main/search.cpp b/runtime/main/search.cpp index 69071746d..9152cfc9f 100644 --- a/runtime/main/search.cpp +++ b/runtime/main/search.cpp @@ -4,17 +4,17 @@ #include "runtime/header.h" extern "C" { -void initStaticObjects(void); +void init_static_objects(void); uint64_t get_steps(void); } -std::unordered_set take_search_steps( +std::unordered_set take_search_steps( bool executeToBranch, int64_t depth, int64_t bound, block *subject); -void printConfigurations( - FILE *file, std::unordered_set results); +void print_configurations( + FILE *file, std::unordered_set results); -void serializeConfigurations( - FILE *file, std::unordered_set results); +void serialize_configurations( + FILE *file, std::unordered_set results); static bool hasStatistics = false; static bool binaryOutput = false; @@ -46,19 +46,19 @@ int main(int argc, char **argv) { parse_flags(argc, argv); - initStaticObjects(); + init_static_objects(); - block *input = parseConfiguration(filename); - std::unordered_set results + block *input = parse_configuration(filename); + std::unordered_set results = take_search_steps(executeToBranch, depth, bound, input); FILE *file = fopen(output, "w"); if (hasStatistics) { - printStatistics(file, get_steps()); + print_statistics(file, get_steps()); } if (binaryOutput) { - serializeConfigurations(file, results); + serialize_configurations(file, results); } else { - printConfigurations(file, results); + print_configurations(file, results); } fclose(file); return 0; diff --git a/runtime/meta/ffi.cpp b/runtime/meta/ffi.cpp index 9f3fd52d4..384c29716 100644 --- a/runtime/meta/ffi.cpp +++ b/runtime/meta/ffi.cpp @@ -23,17 +23,16 @@ extern "C" { static uint64_t tag_type_##NAME() { \ static uint64_t tag = -1; \ if (tag == -1) { \ - tag = (uint64_t)leaf_block(getTagForSymbolName(TYPETAG(NAME))); \ + tag = (uint64_t)leaf_block(get_tag_for_symbol_name(TYPETAG(NAME))); \ } \ return tag; \ } -static block *dotK = leaf_block(getTagForSymbolName("dotk{}")); +thread_local static std::vector struct_types; -thread_local static std::vector structTypes; - -static std::unordered_map allocatedKItemPtrs; -static std::map allocatedBytesRefs; +static std::unordered_map + allocated_k_item_ptrs; +static std::map allocated_bytes_refs; TAG_TYPE(void) TAG_TYPE(uint8) @@ -62,7 +61,7 @@ TAG_TYPE(complexdouble) TAG_TYPE(complexlongdouble) #endif -char *getTerminatedString(string *str); +char *get_terminated_string(string *str); size_t hook_LIST_size_long(list *l); block *hook_LIST_get_long(list *l, ssize_t idx); @@ -82,7 +81,7 @@ static void *so_lib_handle() { } // NOLINTBEGIN(*-else-after-return,*-cognitive-complexity) -static ffi_type *getTypeFromBlock(block *elem) { +static ffi_type *get_type_from_block(block *elem) { if (is_leaf_block(elem)) { auto symbol = (uint64_t)elem; @@ -142,35 +141,37 @@ static ffi_type *getTypeFromBlock(block *elem) { } #endif } else if ( - tag_hdr(elem->h.hdr) == (uint64_t)getTagForSymbolName(TYPETAG(struct))) { + tag_hdr(elem->h.hdr) + == (uint64_t)get_tag_for_symbol_name(TYPETAG(struct))) { list *elements = (list *)*elem->children; - size_t numFields = hook_LIST_size_long(elements); - block *structField = nullptr; - - auto *structType = (ffi_type *)malloc(sizeof(ffi_type)); - structType->size = 0; - structType->alignment = 0; - structType->type = FFI_TYPE_STRUCT; - structType->elements - = (ffi_type **)malloc(sizeof(ffi_type *) * (numFields + 1)); - - for (int j = 0; j < numFields; j++) { - structField = hook_LIST_get_long(elements, j); - - if (tag_hdr(structField->h.hdr) - != (uint64_t)getTagForSymbolName("inj{SortFFIType{}, SortKItem{}}")) { + size_t num_fields = hook_LIST_size_long(elements); + block *struct_field = nullptr; + + auto *struct_type = (ffi_type *)malloc(sizeof(ffi_type)); + struct_type->size = 0; + struct_type->alignment = 0; + struct_type->type = FFI_TYPE_STRUCT; + struct_type->elements + = (ffi_type **)malloc(sizeof(ffi_type *) * (num_fields + 1)); + + for (int j = 0; j < num_fields; j++) { + struct_field = hook_LIST_get_long(elements, j); + + if (tag_hdr(struct_field->h.hdr) + != (uint64_t)get_tag_for_symbol_name( + "inj{SortFFIType{}, SortKItem{}}")) { KLLVM_HOOK_INVALID_ARGUMENT("Struct list contains invalid FFI type"); } - structType->elements[j] - = getTypeFromBlock((block *)*(structField->children)); + struct_type->elements[j] + = get_type_from_block((block *)*(struct_field->children)); } - structType->elements[numFields] = nullptr; + struct_type->elements[num_fields] = nullptr; - structTypes.push_back(structType); + struct_types.push_back(struct_type); - return structType; + return struct_type; } // NOLINTEND(*-branch-clone) @@ -179,8 +180,8 @@ static ffi_type *getTypeFromBlock(block *elem) { // NOLINTEND(*-else-after-return,*-cognitive-complexity) // NOLINTNEXTLINE(*-cognitive-complexity) -string *ffiCall( - bool isVariadic, mpz_t addr, list *args, list *fixtypes, list *vartypes, +string *k_ffi_call( + bool is_variadic, mpz_t addr, list *args, list *fixtypes, list *vartypes, block *ret) { ffi_cif cif; ffi_type **argtypes = nullptr; @@ -188,7 +189,7 @@ string *ffiCall( void (*address)() = nullptr; if (!mpz_fits_ulong_p(addr)) { - KLLVM_HOOK_INVALID_ARGUMENT("Addr is too large: {}", intToString(addr)); + KLLVM_HOOK_INVALID_ARGUMENT("Addr is too large: {}", int_to_string(addr)); } address = (void (*)())mpz_get_ui(addr); @@ -197,7 +198,7 @@ string *ffiCall( size_t nfixtypes = hook_LIST_size_long(fixtypes); size_t nvartypes = 0; - if (isVariadic) { + if (is_variadic) { nvartypes = hook_LIST_size_long(vartypes); } @@ -213,37 +214,39 @@ string *ffiCall( for (int i = 0; i < nfixtypes; i++) { elem = hook_LIST_get_long(fixtypes, i); if (tag_hdr(elem->h.hdr) - != (uint64_t)getTagForSymbolName("inj{SortFFIType{}, SortKItem{}}")) { + != (uint64_t)get_tag_for_symbol_name( + "inj{SortFFIType{}, SortKItem{}}")) { KLLVM_HOOK_INVALID_ARGUMENT("Fix types list contains invalid FFI type"); } - argtypes[i] = getTypeFromBlock((block *)*elem->children); + argtypes[i] = get_type_from_block((block *)*elem->children); } for (int i = 0; i < nvartypes; i++) { elem = hook_LIST_get_long(vartypes, i); if (tag_hdr(elem->h.hdr) - != (uint64_t)getTagForSymbolName("inj{SortFFIType{}, SortKItem{}}")) { + != (uint64_t)get_tag_for_symbol_name( + "inj{SortFFIType{}, SortKItem{}}")) { KLLVM_HOOK_INVALID_ARGUMENT("Var types list contains invalid FFI type"); } - argtypes[i + nfixtypes] = getTypeFromBlock((block *)*elem->children); + argtypes[i + nfixtypes] = get_type_from_block((block *)*elem->children); } void **avalues = (void **)malloc(sizeof(void *) * nargs); for (int i = 0; i < nargs; i++) { elem = hook_LIST_get_long(args, i); if (tag_hdr(elem->h.hdr) - != (uint64_t)getTagForSymbolName("inj{SortBytes{}, SortKItem{}}")) { + != (uint64_t)get_tag_for_symbol_name("inj{SortBytes{}, SortKItem{}}")) { KLLVM_HOOK_INVALID_ARGUMENT("Args list contains non-bytes type"); } avalues[i] = ((string *)*elem->children)->data; } - rtype = getTypeFromBlock(ret); + rtype = get_type_from_block(ret); ffi_status status = FFI_OK; - if (isVariadic) { + if (is_variadic) { status = ffi_prep_cif_var( &cif, FFI_DEFAULT_ABI, nfixtypes, nargs, rtype, argtypes); } else { @@ -267,35 +270,35 @@ string *ffiCall( } auto *rvalue - = static_cast(koreAllocToken(sizeof(string) + rtype->size)); + = static_cast(kore_alloc_token(sizeof(string) + rtype->size)); ffi_call(&cif, address, (void *)(rvalue->data), avalues); free(argtypes); init_with_len(rvalue, rtype->size); free(avalues); - for (auto &s : structTypes) { + for (auto &s : struct_types) { free(s->elements); free(s); } - structTypes.clear(); + struct_types.clear(); return rvalue; } SortBytes hook_FFI_call(SortInt addr, SortList args, SortList types, SortFFIType ret) { - return ffiCall(false, addr, args, types, nullptr, ret); + return k_ffi_call(false, addr, args, types, nullptr, ret); } SortBytes hook_FFI_call_variadic( SortInt addr, SortList args, SortList fixtypes, SortList vartypes, SortFFIType ret) { - return ffiCall(true, addr, args, fixtypes, vartypes, ret); + return k_ffi_call(true, addr, args, fixtypes, vartypes, ret); } -static std::map getPrivateSymbols() { +static std::map get_private_symbols() { std::map m; m["atexit"] = (void *)atexit; #ifndef __APPLE__ @@ -318,14 +321,14 @@ static std::map getPrivateSymbols() { } SortInt hook_FFI_address(SortString fn) { - char *func = getTerminatedString(fn); + char *func = get_terminated_string(fn); - std::string funcStr = func; - static std::map const privateSymbols - = getPrivateSymbols(); + std::string func_str = func; + static std::map const private_symbols + = get_private_symbols(); void *address = nullptr; - if (auto it = privateSymbols.find(funcStr); it != privateSymbols.end()) { + if (auto it = private_symbols.find(func_str); it != private_symbols.end()) { address = it->second; } else { void *handle = so_lib_handle(); @@ -339,14 +342,14 @@ SortInt hook_FFI_address(SortString fn) { static std::pair< std::vector::iterator, std::vector::iterator> -firstBlockEnumerator() { +first_block_enumerator() { // NOLINTBEGIN(*-const-cast) static std::vector blocks; blocks.clear(); - for (auto &keyVal : allocatedKItemPtrs) { - blocks.push_back(const_cast(&(keyVal.first))); + for (auto &key_val : allocated_k_item_ptrs) { + blocks.push_back(const_cast(&(key_val.first))); } return std::make_pair(blocks.begin(), blocks.end()); @@ -355,14 +358,14 @@ firstBlockEnumerator() { static std::pair< std::vector::iterator, std::vector::iterator> -secondBlockEnumerator() { +second_block_enumerator() { // NOLINTBEGIN(*-const-cast) static std::vector blocks; blocks.clear(); - for (auto &keyVal : allocatedBytesRefs) { - blocks.push_back(const_cast(&(keyVal.second))); + for (auto &key_val : allocated_bytes_refs) { + blocks.push_back(const_cast(&(key_val.second))); } return std::make_pair(blocks.begin(), blocks.end()); @@ -373,27 +376,27 @@ string *hook_FFI_alloc(block *kitem, mpz_t size, mpz_t align) { static int registered = -1; if (registered == -1) { - registerGCRootsEnumerator(firstBlockEnumerator); - registerGCRootsEnumerator(secondBlockEnumerator); + register_gc_roots_enumerator(first_block_enumerator); + register_gc_roots_enumerator(second_block_enumerator); registered = 0; } if (!mpz_fits_ulong_p(size)) { - KLLVM_HOOK_INVALID_ARGUMENT("Size is too large: {}", intToString(size)); + KLLVM_HOOK_INVALID_ARGUMENT("Size is too large: {}", int_to_string(size)); } if (!mpz_fits_ulong_p(align)) { KLLVM_HOOK_INVALID_ARGUMENT( - "Alignment is too large: {}", intToString(align)); + "Alignment is too large: {}", int_to_string(align)); } size_t a = mpz_get_ui(align); - if (allocatedKItemPtrs.find(kitem) != allocatedKItemPtrs.end()) { - string *result = allocatedKItemPtrs[kitem]; + if (allocated_k_item_ptrs.find(kitem) != allocated_k_item_ptrs.end()) { + string *result = allocated_k_item_ptrs[kitem]; if ((((uintptr_t)result) & (a - 1)) != 0) { KLLVM_HOOK_INVALID_ARGUMENT("Memory is not aligned"); } - return allocatedKItemPtrs[kitem]; + return allocated_k_item_ptrs[kitem]; } size_t s = mpz_get_ui(size); @@ -409,46 +412,46 @@ string *hook_FFI_alloc(block *kitem, mpz_t size, mpz_t align) { init_with_len(ret, s); ret->h.hdr |= NOT_YOUNG_OBJECT_BIT; - allocatedKItemPtrs[kitem] = ret; - allocatedBytesRefs[ret] = kitem; + allocated_k_item_ptrs[kitem] = ret; + allocated_bytes_refs[ret] = kitem; return ret; } block *hook_FFI_free(block *kitem) { - auto ptrIter = allocatedKItemPtrs.find(kitem); - auto refIter = allocatedBytesRefs.find(ptrIter->second); + auto ptr_iter = allocated_k_item_ptrs.find(kitem); + auto ref_iter = allocated_bytes_refs.find(ptr_iter->second); - if (ptrIter != allocatedKItemPtrs.end()) { - free(allocatedKItemPtrs[kitem]); - allocatedKItemPtrs.erase(ptrIter); + if (ptr_iter != allocated_k_item_ptrs.end()) { + free(allocated_k_item_ptrs[kitem]); + allocated_k_item_ptrs.erase(ptr_iter); - if (refIter != allocatedBytesRefs.end()) { - allocatedBytesRefs.erase(refIter); + if (ref_iter != allocated_bytes_refs.end()) { + allocated_bytes_refs.erase(ref_iter); } else { throw std::runtime_error("Internal memory map is out of sync"); } } - return dotK; + return dot_k(); } block *hook_FFI_freeAll(void) { - for (auto &allocatedKItemPtr : allocatedKItemPtrs) { - hook_FFI_free(allocatedKItemPtr.first); + for (auto &allocated_k_item_ptr : allocated_k_item_ptrs) { + hook_FFI_free(allocated_k_item_ptr.first); } - return dotK; + return dot_k(); } block *hook_FFI_bytes_ref(string *bytes) { - auto refIter = allocatedBytesRefs.find(bytes); + auto ref_iter = allocated_bytes_refs.find(bytes); - if (refIter == allocatedBytesRefs.end()) { + if (ref_iter == allocated_bytes_refs.end()) { KLLVM_HOOK_INVALID_ARGUMENT("Bytes have no reference"); } - return allocatedBytesRefs[bytes]; + return allocated_bytes_refs[bytes]; } mpz_ptr hook_FFI_bytes_address(string *bytes) { @@ -458,7 +461,7 @@ mpz_ptr hook_FFI_bytes_address(string *bytes) { } bool hook_FFI_allocated(block *kitem) { - return allocatedKItemPtrs.find(kitem) != allocatedKItemPtrs.end(); + return allocated_k_item_ptrs.find(kitem) != allocated_k_item_ptrs.end(); } SortK hook_FFI_read(SortInt addr, SortBytes mem) { @@ -466,7 +469,7 @@ SortK hook_FFI_read(SortInt addr, SortBytes mem) { auto intptr = (uintptr_t)l; char *ptr = (char *)intptr; memcpy(mem->data, ptr, len(mem)); - return dotK; + return dot_k(); } SortK hook_FFI_write(SortInt addr, SortBytes mem) { @@ -478,6 +481,6 @@ SortK hook_FFI_write(SortInt addr, SortBytes mem) { ptr[i] = mem->data[i]; } } - return dotK; + return dot_k(); } } diff --git a/runtime/meta/substitution.cpp b/runtime/meta/substitution.cpp index 1a51e2330..40161e147 100644 --- a/runtime/meta/substitution.cpp +++ b/runtime/meta/substitution.cpp @@ -7,7 +7,7 @@ static thread_local string *var; static thread_local block *to_replace; static thread_local block *replacement; -static thread_local block *replacementInj; +static thread_local block *replacement_inj; static thread_local uint64_t idx; static thread_local uint64_t idx2; @@ -20,70 +20,70 @@ set set_map(void *, block *(block *)); } template -void makeDirty(bool &dirty, uint64_t offset, New newArg, block *&newBlock) { +void make_dirty(bool &dirty, uint64_t offset, New new_arg, block *&new_block) { if (!dirty) { dirty = true; - auto *alloc = (block *)koreAlloc(size_hdr(newBlock->h.hdr)); - alloc->h = newBlock->h; + auto *alloc = (block *)kore_alloc(size_hdr(new_block->h.hdr)); + alloc->h = new_block->h; reset_gc(alloc); - memcpy(alloc->children, newBlock->children, offset - 8); - newBlock = alloc; + memcpy(alloc->children, new_block->children, offset - 8); + new_block = alloc; } - New *newPtr = (New *)(((char *)newBlock) + offset); - *newPtr = newArg; + New *new_ptr = (New *)(((char *)new_block) + offset); + *new_ptr = new_arg; } -block *debruijnizeInternal(block *currBlock) { - if (is_leaf_block(currBlock)) { - return currBlock; +block *debruijnize_internal(block *curr_block) { + if (is_leaf_block(curr_block)) { + return curr_block; } - uint64_t const hdr = currBlock->h.hdr; - uint16_t layoutInt = layout_hdr(hdr); - if (layoutInt) { + uint64_t const hdr = curr_block->h.hdr; + uint16_t layout_int = layout_hdr(hdr); + if (layout_int) { uint32_t tag = tag_hdr(hdr); - bool isBinder = isSymbolABinder(tag); - if (isBinder) { + bool is_binder = is_symbol_a_binder(tag); + if (is_binder) { idx++; } - layout *layoutData = getLayoutData(layoutInt); + layout *layout_data = get_layout_data(layout_int); bool dirty = false; - block *newBlock = currBlock; - for (unsigned i = 0; i < layoutData->nargs; i++) { - layoutitem *argData = layoutData->args + i; - void *arg = ((char *)currBlock) + argData->offset; - switch (argData->cat) { + block *new_block = curr_block; + for (unsigned i = 0; i < layout_data->nargs; i++) { + layoutitem *arg_data = layout_data->args + i; + void *arg = ((char *)curr_block) + arg_data->offset; + switch (arg_data->cat) { case MAP_LAYOUT: { - map newArg = map_map(arg, debruijnizeInternal); - makeDirty(dirty, argData->offset, newArg, newBlock); + map new_arg = map_map(arg, debruijnize_internal); + make_dirty(dirty, arg_data->offset, new_arg, new_block); break; } case RANGEMAP_LAYOUT: { - rangemap newArg = rangemap_map(arg, debruijnizeInternal); - makeDirty(dirty, argData->offset, newArg, newBlock); + rangemap new_arg = rangemap_map(arg, debruijnize_internal); + make_dirty(dirty, arg_data->offset, new_arg, new_block); break; } case LIST_LAYOUT: { - list newArg = list_map(arg, debruijnizeInternal); - makeDirty(dirty, argData->offset, newArg, newBlock); + list new_arg = list_map(arg, debruijnize_internal); + make_dirty(dirty, arg_data->offset, new_arg, new_block); break; } case SET_LAYOUT: { - set newArg = set_map(arg, debruijnizeInternal); - makeDirty(dirty, argData->offset, newArg, newBlock); + set new_arg = set_map(arg, debruijnize_internal); + make_dirty(dirty, arg_data->offset, new_arg, new_block); break; } case SYMBOL_LAYOUT: { - block *oldArg = *(block **)arg; - block *newArg = debruijnizeInternal(oldArg); - if (oldArg != newArg || dirty) { - makeDirty(dirty, argData->offset, newArg, newBlock); + block *old_arg = *(block **)arg; + block *new_arg = debruijnize_internal(old_arg); + if (old_arg != new_arg || dirty) { + make_dirty(dirty, arg_data->offset, new_arg, new_block); } break; } case VARIABLE_LAYOUT: { - if ((i != 0 || !isBinder) && hook_STRING_eq(var, *(string **)arg)) { - block *newArg = variable_block(idx); - makeDirty(dirty, argData->offset, newArg, newBlock); + if ((i != 0 || !is_binder) && hook_STRING_eq(var, *(string **)arg)) { + block *new_arg = variable_block(idx); + make_dirty(dirty, arg_data->offset, new_arg, new_block); } break; } @@ -95,70 +95,70 @@ block *debruijnizeInternal(block *currBlock) { break; } } - if (isBinder) { + if (is_binder) { idx--; } - return newBlock; + return new_block; } - return currBlock; + return curr_block; } -block *replaceBinderInternal(block *currBlock) { - if (is_variable_block(currBlock)) { - uint64_t varIdx = ((uintptr_t)currBlock) >> 32; - if (idx == varIdx) { +block *replace_binder_internal(block *curr_block) { + if (is_variable_block(curr_block)) { + uint64_t var_idx = ((uintptr_t)curr_block) >> 32; + if (idx == var_idx) { return (block *)var; } - if (idx < varIdx) { - varIdx--; - return variable_block(varIdx); + if (idx < var_idx) { + var_idx--; + return variable_block(var_idx); } - return currBlock; + return curr_block; } - if (is_leaf_block(currBlock)) { - return currBlock; + if (is_leaf_block(curr_block)) { + return curr_block; } - uint64_t const hdr = currBlock->h.hdr; - uint16_t layoutInt = layout_hdr(hdr); - if (layoutInt) { + uint64_t const hdr = curr_block->h.hdr; + uint16_t layout_int = layout_hdr(hdr); + if (layout_int) { uint32_t tag = tag_hdr(hdr); - bool isBinder = isSymbolABinder(tag); - if (isBinder) { + bool is_binder = is_symbol_a_binder(tag); + if (is_binder) { idx++; } - layout *layoutData = getLayoutData(layoutInt); + layout *layout_data = get_layout_data(layout_int); bool dirty = false; - block *newBlock = currBlock; - for (unsigned i = 0; i < layoutData->nargs; i++) { - layoutitem *argData = layoutData->args + i; - void *arg = ((char *)currBlock) + argData->offset; - switch (argData->cat) { + block *new_block = curr_block; + for (unsigned i = 0; i < layout_data->nargs; i++) { + layoutitem *arg_data = layout_data->args + i; + void *arg = ((char *)curr_block) + arg_data->offset; + switch (arg_data->cat) { case MAP_LAYOUT: { - map newArg = map_map(arg, replaceBinderInternal); - makeDirty(dirty, argData->offset, newArg, newBlock); + map new_arg = map_map(arg, replace_binder_internal); + make_dirty(dirty, arg_data->offset, new_arg, new_block); break; } case RANGEMAP_LAYOUT: { - rangemap newArg = rangemap_map(arg, replaceBinderInternal); - makeDirty(dirty, argData->offset, newArg, newBlock); + rangemap new_arg = rangemap_map(arg, replace_binder_internal); + make_dirty(dirty, arg_data->offset, new_arg, new_block); break; } case LIST_LAYOUT: { - list newArg = list_map(arg, replaceBinderInternal); - makeDirty(dirty, argData->offset, newArg, newBlock); + list new_arg = list_map(arg, replace_binder_internal); + make_dirty(dirty, arg_data->offset, new_arg, new_block); break; } case SET_LAYOUT: { - set newArg = set_map(arg, replaceBinderInternal); - makeDirty(dirty, argData->offset, newArg, newBlock); + set new_arg = set_map(arg, replace_binder_internal); + make_dirty(dirty, arg_data->offset, new_arg, new_block); break; } case VARIABLE_LAYOUT: case SYMBOL_LAYOUT: { - block *oldArg = *(block **)arg; - block *newArg = replaceBinderInternal(oldArg); - if (oldArg != newArg || dirty) { - makeDirty(dirty, argData->offset, newArg, newBlock); + block *old_arg = *(block **)arg; + block *new_arg = replace_binder_internal(old_arg); + if (old_arg != new_arg || dirty) { + make_dirty(dirty, arg_data->offset, new_arg, new_block); } break; } @@ -170,77 +170,77 @@ block *replaceBinderInternal(block *currBlock) { break; } } - if (isBinder) { + if (is_binder) { idx--; } - return newBlock; + return new_block; } - return currBlock; + return curr_block; } -block *substituteInternal(block *currBlock) { - if (is_leaf_block(currBlock)) { - return currBlock; +block *substitute_internal(block *curr_block) { + if (is_leaf_block(curr_block)) { + return curr_block; } - uint64_t const hdr = currBlock->h.hdr; - uint16_t layoutInt = layout_hdr(hdr); - if (hook_KEQUAL_eq(currBlock, to_replace)) { + uint64_t const hdr = curr_block->h.hdr; + uint16_t layout_int = layout_hdr(hdr); + if (hook_KEQUAL_eq(curr_block, to_replace)) { idx2 = 0; - if (layoutInt) { + if (layout_int) { uint32_t tag = tag_hdr(hdr); - uint32_t injTag = getInjectionForSortOfTag(tag); - if (tag_hdr(replacementInj->h.hdr) != injTag) { - return incrementDebruijn(replacementInj); + uint32_t inj_tag = get_injection_for_sort_of_tag(tag); + if (tag_hdr(replacement_inj->h.hdr) != inj_tag) { + return increment_debruijn(replacement_inj); } } - return incrementDebruijn(replacement); + return increment_debruijn(replacement); } - if (layoutInt) { - layout *layoutData = getLayoutData(layoutInt); + if (layout_int) { + layout *layout_data = get_layout_data(layout_int); bool dirty = false; - block *newBlock = currBlock; + block *new_block = curr_block; uint32_t tag = tag_hdr(hdr); std::vector arguments; - bool isBinder = isSymbolABinder(tag); - if (isBinder) { + bool is_binder = is_symbol_a_binder(tag); + if (is_binder) { idx++; } - for (unsigned i = 0; i < layoutData->nargs; i++) { - layoutitem *argData = layoutData->args + i; - void *arg = ((char *)currBlock) + argData->offset; - switch (argData->cat) { + for (unsigned i = 0; i < layout_data->nargs; i++) { + layoutitem *arg_data = layout_data->args + i; + void *arg = ((char *)curr_block) + arg_data->offset; + switch (arg_data->cat) { case MAP_LAYOUT: { - map newArg = map_map(arg, substituteInternal); - makeDirty(dirty, argData->offset, newArg, newBlock); - arguments.push_back(((char *)newBlock) + argData->offset); + map new_arg = map_map(arg, substitute_internal); + make_dirty(dirty, arg_data->offset, new_arg, new_block); + arguments.push_back(((char *)new_block) + arg_data->offset); break; } case RANGEMAP_LAYOUT: { - rangemap newArg = rangemap_map(arg, substituteInternal); - makeDirty(dirty, argData->offset, newArg, newBlock); - arguments.push_back(((char *)newBlock) + argData->offset); + rangemap new_arg = rangemap_map(arg, substitute_internal); + make_dirty(dirty, arg_data->offset, new_arg, new_block); + arguments.push_back(((char *)new_block) + arg_data->offset); break; } case LIST_LAYOUT: { - list newArg = list_map(arg, substituteInternal); - makeDirty(dirty, argData->offset, newArg, newBlock); - arguments.push_back(((char *)newBlock) + argData->offset); + list new_arg = list_map(arg, substitute_internal); + make_dirty(dirty, arg_data->offset, new_arg, new_block); + arguments.push_back(((char *)new_block) + arg_data->offset); break; } case SET_LAYOUT: { - set newArg = set_map(arg, substituteInternal); - makeDirty(dirty, argData->offset, newArg, newBlock); - arguments.push_back(((char *)newBlock) + argData->offset); + set new_arg = set_map(arg, substitute_internal); + make_dirty(dirty, arg_data->offset, new_arg, new_block); + arguments.push_back(((char *)new_block) + arg_data->offset); break; } case VARIABLE_LAYOUT: case SYMBOL_LAYOUT: { - block *oldArg = *(block **)arg; - block *newArg = substituteInternal(oldArg); - if (oldArg != newArg || dirty) { - makeDirty(dirty, argData->offset, newArg, newBlock); + block *old_arg = *(block **)arg; + block *new_arg = substitute_internal(old_arg); + if (old_arg != new_arg || dirty) { + make_dirty(dirty, arg_data->offset, new_arg, new_block); } - arguments.push_back(newArg); + arguments.push_back(new_arg); break; } case STRINGBUFFER_LAYOUT: @@ -252,104 +252,104 @@ block *substituteInternal(block *currBlock) { break; } } - if (isBinder) { + if (is_binder) { idx--; } - if (isSymbolAFunction(tag)) { + if (is_symbol_a_function(tag)) { uint64_t idx_stack = idx; block *to_replace_stack = to_replace; block *replacement_stack = replacement; - block *replacementInj_stack = replacementInj; - auto *result = (block *)evaluateFunctionSymbol(tag, arguments.data()); + block *replacement_inj_stack = replacement_inj; + auto *result = (block *)evaluate_function_symbol(tag, arguments.data()); to_replace = to_replace_stack; replacement = replacement_stack; - replacementInj = replacementInj_stack; + replacement_inj = replacement_inj_stack; idx = idx_stack; return result; } - return newBlock; + return new_block; } - return currBlock; + return curr_block; } extern "C" { block *debruijnize(block *term) { - auto *layoutData = getLayoutData(get_layout(term)); - auto layoutVar = layoutData->args[0]; - auto layoutBody = layoutData->args[layoutData->nargs - 1]; - var = *(string **)(((char *)term) + layoutVar.offset); + auto *layout_data = get_layout_data(get_layout(term)); + auto layout_var = layout_data->args[0]; + auto layout_body = layout_data->args[layout_data->nargs - 1]; + var = *(string **)(((char *)term) + layout_var.offset); idx = 0; - auto *bodyPtr = *(block **)(((char *)term) + layoutBody.offset); - auto *newBody = debruijnizeInternal(bodyPtr); - auto *newBlock = term; - if (newBody != bodyPtr) { + auto *body_ptr = *(block **)(((char *)term) + layout_body.offset); + auto *new_body = debruijnize_internal(body_ptr); + auto *new_block = term; + if (new_body != body_ptr) { bool dirty = false; - makeDirty(dirty, layoutBody.offset, newBody, newBlock); + make_dirty(dirty, layout_body.offset, new_body, new_block); } - auto *newVar = *(string **)(((char *)newBlock) + layoutVar.offset); - newVar->h.hdr |= VARIABLE_BIT; - return newBlock; + auto *new_var = *(string **)(((char *)new_block) + layout_var.offset); + new_var->h.hdr |= VARIABLE_BIT; + return new_block; } -block *incrementDebruijn(block *currBlock) { - if (is_variable_block(currBlock)) { - uint64_t varIdx = ((uintptr_t)currBlock) >> 32; - if (varIdx >= idx2) { - varIdx += idx; - return variable_block(varIdx); +block *increment_debruijn(block *curr_block) { + if (is_variable_block(curr_block)) { + uint64_t var_idx = ((uintptr_t)curr_block) >> 32; + if (var_idx >= idx2) { + var_idx += idx; + return variable_block(var_idx); } - return currBlock; + return curr_block; } - if (is_leaf_block(currBlock)) { - return currBlock; + if (is_leaf_block(curr_block)) { + return curr_block; } - uint64_t const hdr = currBlock->h.hdr; - uint16_t layoutInt = layout_hdr(hdr); - if (layoutInt) { - layout *layoutData = getLayoutData(layoutInt); + uint64_t const hdr = curr_block->h.hdr; + uint16_t layout_int = layout_hdr(hdr); + if (layout_int) { + layout *layout_data = get_layout_data(layout_int); bool dirty = false; - block *newBlock = currBlock; + block *new_block = curr_block; uint32_t tag = tag_hdr(hdr); - bool isBinder = isSymbolABinder(tag); - if (isBinder) { + bool is_binder = is_symbol_a_binder(tag); + if (is_binder) { idx2++; } - for (unsigned i = 0; i < layoutData->nargs; i++) { - layoutitem *argData = layoutData->args + i; - void *arg = ((char *)currBlock) + argData->offset; - switch (argData->cat) { + for (unsigned i = 0; i < layout_data->nargs; i++) { + layoutitem *arg_data = layout_data->args + i; + void *arg = ((char *)curr_block) + arg_data->offset; + switch (arg_data->cat) { case MAP_LAYOUT: { - map newArg = map_map(arg, incrementDebruijn); - makeDirty(dirty, argData->offset, newArg, newBlock); + map new_arg = map_map(arg, increment_debruijn); + make_dirty(dirty, arg_data->offset, new_arg, new_block); break; } case RANGEMAP_LAYOUT: { - rangemap newArg = rangemap_map(arg, incrementDebruijn); - makeDirty(dirty, argData->offset, newArg, newBlock); + rangemap new_arg = rangemap_map(arg, increment_debruijn); + make_dirty(dirty, arg_data->offset, new_arg, new_block); break; } case LIST_LAYOUT: { - list newArg = list_map(arg, incrementDebruijn); - makeDirty(dirty, argData->offset, newArg, newBlock); + list new_arg = list_map(arg, increment_debruijn); + make_dirty(dirty, arg_data->offset, new_arg, new_block); break; } case SET_LAYOUT: { - set newArg = set_map(arg, incrementDebruijn); - makeDirty(dirty, argData->offset, newArg, newBlock); + set new_arg = set_map(arg, increment_debruijn); + make_dirty(dirty, arg_data->offset, new_arg, new_block); break; } case VARIABLE_LAYOUT: case SYMBOL_LAYOUT: { - block *oldArg = *(block **)arg; - block *newArg = nullptr; - if (i == 0 && isBinder) { - newArg = alphaRename(oldArg); + block *old_arg = *(block **)arg; + block *new_arg = nullptr; + if (i == 0 && is_binder) { + new_arg = alpha_rename(old_arg); } else { - newArg = incrementDebruijn(oldArg); + new_arg = increment_debruijn(old_arg); } - if (oldArg != newArg || dirty) { - makeDirty(dirty, argData->offset, newArg, newBlock); + if (old_arg != new_arg || dirty) { + make_dirty(dirty, arg_data->offset, new_arg, new_block); } break; } @@ -361,42 +361,42 @@ block *incrementDebruijn(block *currBlock) { break; } } - if (isBinder) { + if (is_binder) { idx2--; } - return newBlock; + return new_block; } - return currBlock; + return curr_block; } -block *alphaRename(block *term) { +block *alpha_rename(block *term) { auto *var = (string *)term; size_t var_len = len(var); - auto *newToken = (string *)koreAllocToken(sizeof(string) + var_len); - memcpy(newToken->data, var->data, var_len); - init_with_len(newToken, var_len); - newToken->h.hdr |= VARIABLE_BIT; - return (block *)newToken; + auto *new_token = (string *)kore_alloc_token(sizeof(string) + var_len); + memcpy(new_token->data, var->data, var_len); + init_with_len(new_token, var_len); + new_token->h.hdr |= VARIABLE_BIT; + return (block *)new_token; } -block *replaceBinderIndex(block *term, block *variable) { +block *replace_binder_index(block *term, block *variable) { idx = 0; var = (string *)variable; - return replaceBinderInternal(term); + return replace_binder_internal(term); } block * -hook_SUBSTITUTION_substOne(block *body, SortKItem newVal, SortKItem varInj) { - bool isSameSort = tag_hdr(newVal->h.hdr) == tag_hdr(varInj->h.hdr); +hook_SUBSTITUTION_substOne(block *body, SortKItem new_val, SortKItem var_inj) { + bool is_same_sort = tag_hdr(new_val->h.hdr) == tag_hdr(var_inj->h.hdr); idx = 0; - replacement = *(block **)(((char *)newVal) + sizeof(blockheader)); - if (isSameSort) { - to_replace = *(block **)(((char *)varInj) + sizeof(blockheader)); - replacementInj = replacement; + replacement = *(block **)(((char *)new_val) + sizeof(blockheader)); + if (is_same_sort) { + to_replace = *(block **)(((char *)var_inj) + sizeof(blockheader)); + replacement_inj = replacement; } else { - to_replace = varInj; - replacementInj = newVal; + to_replace = var_inj; + replacement_inj = new_val; } - return substituteInternal(body); + return substitute_internal(body); } } diff --git a/runtime/move_float.ll b/runtime/move_float.ll index e7c0c9197..2c4b6e46d 100644 --- a/runtime/move_float.ll +++ b/runtime/move_float.ll @@ -7,12 +7,12 @@ target triple = "@BACKEND_TARGET_TRIPLE@" ; helper function for float hooks define %floating* @move_float(%floating* %val) { %loaded = load %floating, %floating* %val - %malloccall = tail call i8* @koreAllocFloating(i64 0) + %malloccall = tail call i8* @kore_alloc_floating(i64 0) %ptr = bitcast i8* %malloccall to %floating* store %floating %loaded, %floating* %ptr ret %floating* %ptr } -declare noalias i8* @koreAllocFloating(i64) +declare noalias i8* @kore_alloc_floating(i64) diff --git a/runtime/move_int.ll b/runtime/move_int.ll index e891e22ed..d0849ef66 100644 --- a/runtime/move_int.ll +++ b/runtime/move_int.ll @@ -6,11 +6,11 @@ target triple = "@BACKEND_TARGET_TRIPLE@" ; helper function for int hooks define %mpz* @move_int(%mpz* %val) { %loaded = load %mpz, %mpz* %val - %malloccall = tail call i8* @koreAllocInteger(i64 0) + %malloccall = tail call i8* @kore_alloc_integer(i64 0) %ptr = bitcast i8* %malloccall to %mpz* store %mpz %loaded, %mpz* %ptr ret %mpz* %ptr } -declare noalias i8* @koreAllocInteger(i64) +declare noalias i8* @kore_alloc_integer(i64) diff --git a/runtime/strings/bytes.cpp b/runtime/strings/bytes.cpp index 92fb37223..74cc5ffdc 100644 --- a/runtime/strings/bytes.cpp +++ b/runtime/strings/bytes.cpp @@ -28,7 +28,7 @@ SortBytes hook_BYTES_empty() { uint64_t tag_big_endian() { static auto tag = (uint64_t)-1; if (tag == -1) { - tag = (uint64_t)leaf_block(getTagForSymbolName("LblbigEndianBytes{}")); + tag = (uint64_t)leaf_block(get_tag_for_symbol_name("LblbigEndianBytes{}")); } return tag; } @@ -38,7 +38,7 @@ uint64_t tag_big_endian() { uint64_t tag_unsigned() { static auto tag = (uint64_t)-1; if (tag == -1) { - tag = (uint64_t)leaf_block(getTagForSymbolName("LblunsignedBytes{}")); + tag = (uint64_t)leaf_block(get_tag_for_symbol_name("LblunsignedBytes{}")); } return tag; } @@ -73,7 +73,7 @@ SortInt hook_BYTES_bytes2int( unsigned long get_ui_named(mpz_t i, std::string const &caller) { if (!mpz_fits_ulong_p(i)) { KLLVM_HOOK_INVALID_ARGUMENT( - "Integer overflow from {}: {}", caller, intToString(i)); + "Integer overflow from {}: {}", caller, int_to_string(i)); } return mpz_get_ui(i); } @@ -90,23 +90,24 @@ hook_BYTES_int2bytes(SortInt len, SortInt i, SortEndianness endianness_ptr) { } bool neg = mpz_sgn(i) < 0; auto *result - = static_cast(koreAllocToken(sizeof(string) + len_long)); + = static_cast(kore_alloc_token(sizeof(string) + len_long)); init_with_len(result, len_long); memset(result->data, neg ? 0xff : 0x00, len_long); int order = endianness == tag_big_endian() ? 1 : -1; mpz_t twos; mpz_init(twos); extract(twos, i, 0, len_long * 8); - size_t sizeInBytes = (mpz_sizeinbase(twos, 2) + 7) / 8; - void *start = result->data - + (endianness == tag_big_endian() ? len_long - sizeInBytes : 0); + size_t size_in_bytes = (mpz_sizeinbase(twos, 2) + 7) / 8; + void *start + = result->data + + (endianness == tag_big_endian() ? len_long - size_in_bytes : 0); mpz_export(start, nullptr, order, 1, 0, 0, twos); mpz_clear(twos); return result; } string *bytes2string(string *b, size_t len) { - auto *result = static_cast(koreAllocToken(sizeof(string) + len)); + auto *result = static_cast(kore_alloc_token(sizeof(string) + len)); memcpy(result->data, b->data, len); init_with_len(result, len); return result; @@ -138,7 +139,7 @@ SortBytes hook_BYTES_substr(SortBytes input, SortInt start, SortInt end) { } uint64_t len = uend - ustart; auto *ret = static_cast( - koreAllocToken(sizeof(string) + sizeof(KCHAR) * len)); + kore_alloc_token(sizeof(string) + sizeof(KCHAR) * len)); init_with_len(ret, len); memcpy(&(ret->data), &(input->data[ustart]), len * sizeof(KCHAR)); return ret; @@ -229,7 +230,7 @@ SortBytes hook_BYTES_padRight(SortBytes b, SortInt length, SortInt v) { if (uv > 255) { KLLVM_HOOK_INVALID_ARGUMENT("Integer overflow on value: {}", uv); } - auto *result = static_cast(koreAllocToken(sizeof(string) + ulen)); + auto *result = static_cast(kore_alloc_token(sizeof(string) + ulen)); init_with_len(result, ulen); memcpy(result->data, b->data, len(b)); memset(result->data + len(b), uv, ulen - len(b)); @@ -245,7 +246,7 @@ SortBytes hook_BYTES_padLeft(SortBytes b, SortInt length, SortInt v) { if (uv > 255) { KLLVM_HOOK_INVALID_ARGUMENT("Integer overflow on value: {}", uv); } - auto *result = static_cast(koreAllocToken(sizeof(string) + ulen)); + auto *result = static_cast(kore_alloc_token(sizeof(string) + ulen)); init_with_len(result, ulen); memset(result->data, uv, ulen - len(b)); memcpy(result->data + ulen - len(b), b->data, len(b)); @@ -262,7 +263,7 @@ SortBytes hook_BYTES_concat(SortBytes a, SortBytes b) { auto len_a = len(a); auto len_b = len(b); auto newlen = len_a + len_b; - auto *ret = static_cast(koreAllocToken(sizeof(string) + newlen)); + auto *ret = static_cast(kore_alloc_token(sizeof(string) + newlen)); init_with_len(ret, newlen); memcpy(&(ret->data), &(a->data), len(a) * sizeof(KCHAR)); memcpy(&(ret->data[len(a)]), &(b->data), len(b) * sizeof(KCHAR)); diff --git a/runtime/strings/copy_on_write.cpp b/runtime/strings/copy_on_write.cpp index f87f07b53..4e750a203 100644 --- a/runtime/strings/copy_on_write.cpp +++ b/runtime/strings/copy_on_write.cpp @@ -6,7 +6,7 @@ namespace { SortBytes copy_bytes(SortBytes b) { auto new_len = len(b); - auto *ret = static_cast(koreAllocToken(sizeof(string) + new_len)); + auto *ret = static_cast(kore_alloc_token(sizeof(string) + new_len)); init_with_len(ret, new_len); memcpy(&(ret->data), &(b->data), new_len * sizeof(char)); return ret; diff --git a/runtime/strings/numeric.cpp b/runtime/strings/numeric.cpp index 3bb43b6e8..a9ec0fb33 100644 --- a/runtime/strings/numeric.cpp +++ b/runtime/strings/numeric.cpp @@ -7,7 +7,7 @@ #include "runtime/alloc.h" #include "runtime/header.h" -std::string floatToString(floating const *f, char const *suffix) { +std::string float_to_string(floating const *f, char const *suffix) { if (mpfr_nan_p(f->f)) { return "NaN" + std::string(suffix); } @@ -20,7 +20,7 @@ std::string floatToString(floating const *f, char const *suffix) { mpfr_exp_t printed_exp = 0; char *str = mpfr_get_str(nullptr, &printed_exp, 10, 0, f->f, MPFR_RNDN); size_t len = strlen(str); - auto *newstr = (string *)koreAllocToken(sizeof(string) + len + 2); + auto *newstr = (string *)kore_alloc_token(sizeof(string) + len + 2); init_with_len(newstr, len + 2); size_t idx = 0; if (str[0] == '-') { @@ -34,7 +34,7 @@ std::string floatToString(floating const *f, char const *suffix) { return std::string(newstr->data) + "e" + std::to_string(printed_exp) + suffix; } -std::string floatToString(floating const *f) { +std::string float_to_string(floating const *f) { uint64_t prec = mpfr_get_prec(f->f); uint64_t exp = f->exp; @@ -50,10 +50,10 @@ std::string floatToString(floating const *f) { return fmt::sprintf("p%" PRIu64 "x%" PRIu64, prec, exp); }(); - return floatToString(f, suffix.c_str()); + return float_to_string(f, suffix.c_str()); } -std::string intToStringInBase(mpz_t i, uint64_t base) { +std::string int_to_string_in_base(mpz_t i, uint64_t base) { char *tmp = mpz_get_str(nullptr, base, i); auto ret = std::string(tmp); @@ -64,6 +64,6 @@ std::string intToStringInBase(mpz_t i, uint64_t base) { return ret; } -std::string intToString(mpz_t i) { - return intToStringInBase(i, 10); +std::string int_to_string(mpz_t i) { + return int_to_string_in_base(i, 10); } diff --git a/runtime/strings/strings.cpp b/runtime/strings/strings.cpp index a443f0804..5c142c408 100644 --- a/runtime/strings/strings.cpp +++ b/runtime/strings/strings.cpp @@ -23,7 +23,7 @@ string *bytes2string(string *, size_t); string *hook_BYTES_concat(string *a, string *b); mpz_ptr hook_BYTES_length(string *a); string *hook_BYTES_substr(string *a, mpz_t start, mpz_t end); -char *getTerminatedString(string *str); +char *get_terminated_string(string *str); bool hook_STRING_gt(SortString a, SortString b) { auto res = memcmp(a->data, b->data, std::min(len(a), len(b))); @@ -82,7 +82,7 @@ SortString hook_STRING_chr(SortInt ord) { KLLVM_HOOK_INVALID_ARGUMENT("Ord must be <= 255: {}", uord); } auto *ret - = static_cast(koreAllocToken(sizeof(string) + sizeof(char))); + = static_cast(kore_alloc_token(sizeof(string) + sizeof(char))); init_with_len(ret, 1); ret->data[0] = static_cast(uord); return ret; @@ -175,20 +175,20 @@ hook_STRING_rfindChar(SortString haystack, SortString needle, SortInt pos) { return move_int(result); } -string *makeString(char const *input, ssize_t len = -1) { +string *make_string(char const *input, ssize_t len = -1) { if (len == -1) { len = strlen(input); } - auto *ret = static_cast(koreAllocToken(sizeof(string) + len)); + auto *ret = static_cast(kore_alloc_token(sizeof(string) + len)); memcpy(ret->data, input, len); init_with_len(ret, len); return ret; } -char *getTerminatedString(string *str) { +char *get_terminated_string(string *str) { int length = len(str); auto *buf - = static_cast(koreAllocToken(sizeof(string) + (length + 1))); + = static_cast(kore_alloc_token(sizeof(string) + (length + 1))); memcpy(buf->data, str->data, length); init_with_len(buf, length + 1); buf->data[length] = '\0'; @@ -196,36 +196,36 @@ char *getTerminatedString(string *str) { } SortString hook_STRING_base2string_long(SortInt input, uint64_t base) { - auto str = intToStringInBase(input, base); + auto str = int_to_string_in_base(input, base); // Include the null terminator in size calculations relating to allocation, // but not when setting the length of the string object itself. Any minus // signs will have been accounted for already by the intToString call. auto str_len = str.size() + 1; auto *result - = static_cast(koreAllocToken(sizeof(string) + str_len)); + = static_cast(kore_alloc_token(sizeof(string) + str_len)); strncpy(result->data, str.c_str(), str_len); init_with_len(result, str.size()); - return static_cast(koreResizeLastAlloc( + return static_cast(kore_resize_last_alloc( result, sizeof(string) + len(result), sizeof(string) + str_len)); } SortInt hook_STRING_string2base_long(SortString input, uint64_t base) { mpz_t result; size_t length = 0; - char const *dataStart = nullptr; + char const *data_start = nullptr; if (*(input->data) == '+') { length = len(input) - 1; - dataStart = input->data + 1; + data_start = input->data + 1; } else { length = len(input); - dataStart = input->data; + data_start = input->data; } - auto *copy = static_cast(koreAllocToken(length + 1)); - memcpy(copy, dataStart, length); + auto *copy = static_cast(kore_alloc_token(length + 1)); + memcpy(copy, data_start, length); copy[length] = 0; if (mpz_init_set_str(result, copy, base)) { KLLVM_HOOK_INVALID_ARGUMENT( @@ -253,8 +253,8 @@ SortString hook_STRING_base2string(SortInt input, SortInt base) { } SortString hook_STRING_float2string(SortFloat input) { - std::string result = floatToString(input); - return makeString(result.c_str()); + std::string result = float_to_string(input); + return make_string(result.c_str()); } SortFloat hook_STRING_string2float(SortString input) { @@ -304,7 +304,7 @@ inline SortString hook_STRING_replace( } auto diff = len(needle) - len(replacer); size_t new_len = len(haystack) - i * diff; - auto *ret = static_cast(koreAllocToken(sizeof(string) + new_len)); + auto *ret = static_cast(kore_alloc_token(sizeof(string) + new_len)); init_with_len(ret, new_len); int m = 0; for (size_t r = 0, h = 0; r < new_len;) { @@ -362,9 +362,10 @@ hook_STRING_countAllOccurrences(SortString haystack, SortString needle) { } SortString hook_STRING_transcode( - SortString input, SortString inputCharset, SortString outputCharset) { + SortString input, SortString input_charset, SortString output_charset) { iconv_t converter = iconv_open( - getTerminatedString(outputCharset), getTerminatedString(inputCharset)); + get_terminated_string(output_charset), + get_terminated_string(input_charset)); char *inbuf = input->data; size_t inbytesleft = len(input); size_t outbytesleft = inbytesleft * 4; @@ -376,7 +377,7 @@ SortString hook_STRING_transcode( KLLVM_HOOK_INVALID_ARGUMENT("transcoding failed: STRING.transcode"); } *outbuf = 0; - return makeString(buf, len(input) * 4 - outbytesleft); + return make_string(buf, len(input) * 4 - outbytesleft); } string *hook_STRING_uuid() { @@ -396,10 +397,10 @@ string *hook_STRING_floatFormat(string *str, string *fmt) { } SortStringBuffer hook_BUFFER_empty() { - auto *result = static_cast(koreAlloc(sizeof(stringbuffer))); + auto *result = static_cast(kore_alloc(sizeof(stringbuffer))); init_with_len(result, sizeof(stringbuffer) - sizeof(blockheader)); result->strlen = 0; - auto *str = static_cast(koreAllocToken(sizeof(string) + 16)); + auto *str = static_cast(kore_alloc_token(sizeof(string) + 16)); init_with_len(str, 16); result->contents = str; return result; @@ -411,29 +412,29 @@ SortStringBuffer hook_BUFFER_concat(SortStringBuffer buf, SortString s) { stringbuffer * hook_BUFFER_concat_raw(stringbuffer *buf, char const *data, uint64_t n) { - uint64_t newCapacity = len(buf->contents); - uint64_t minCapacity = buf->strlen + n; - uint64_t notYoungObjectBit = buf->h.hdr & NOT_YOUNG_OBJECT_BIT; - if (newCapacity < minCapacity) { - newCapacity = len(buf->contents) * 2 + 2; - if (newCapacity < minCapacity) { - newCapacity = minCapacity; + uint64_t new_capacity = len(buf->contents); + uint64_t min_capacity = buf->strlen + n; + uint64_t not_young_object_bit = buf->h.hdr & NOT_YOUNG_OBJECT_BIT; + if (new_capacity < min_capacity) { + new_capacity = len(buf->contents) * 2 + 2; + if (new_capacity < min_capacity) { + new_capacity = min_capacity; } string *new_contents = nullptr; - if (notYoungObjectBit) { + if (not_young_object_bit) { assert(buf->h.hdr & AGE_MASK); new_contents = static_cast( - koreAllocTokenOld(sizeof(string) + newCapacity)); + kore_alloc_token_old(sizeof(string) + new_capacity)); } else { - new_contents - = static_cast(koreAllocToken(sizeof(string) + newCapacity)); + new_contents = static_cast( + kore_alloc_token(sizeof(string) + new_capacity)); } memcpy(new_contents->data, buf->contents->data, buf->strlen); buf->contents = new_contents; } memcpy(buf->contents->data + buf->strlen, data, n); buf->strlen += n; - init_with_len(buf->contents, newCapacity); + init_with_len(buf->contents, new_capacity); return buf; } @@ -464,16 +465,16 @@ void init_float2(floating *result, std::string contents) { } result->exp = exp; mpfr_init2(result->f, prec); - int retValue = 0; + int ret_value = 0; if (contents == "+Infinity" || contents == "-Infinity" || contents == "Infinity") { - retValue = mpfr_set_str(result->f, contents.c_str(), 10, MPFR_RNDN); + ret_value = mpfr_set_str(result->f, contents.c_str(), 10, MPFR_RNDN); } else { size_t last = contents.find_last_of("fFdDpP"); std::string str_value = contents.substr(0, last); - retValue = mpfr_set_str(result->f, str_value.c_str(), 10, MPFR_RNDN); + ret_value = mpfr_set_str(result->f, str_value.c_str(), 10, MPFR_RNDN); } - if (retValue != 0) { + if (ret_value != 0) { KLLVM_HOOK_INVALID_ARGUMENT("Can't convert to float: {}", contents); } } diff --git a/runtime/take_steps.ll b/runtime/take_steps.ll index 8be31d750..17619a193 100644 --- a/runtime/take_steps.ll +++ b/runtime/take_steps.ll @@ -5,9 +5,9 @@ target triple = "@BACKEND_TARGET_TRIPLE@" %block = type { %blockheader, [0 x i64 *] } ; 16-bit layout, 8-bit length, 32-bit tag, children declare tailcc %block* @k_step(%block*) -declare tailcc %block** @stepAll(%block*, i64*) -declare void @serializeConfigurationToFile(i8*, %block*, i1, i1) -declare void @writeUInt64ToFile(i8*, i64) +declare tailcc %block** @step_all(%block*, i64*) +declare void @serialize_configuration_to_file(i8*, %block*, i1, i1) +declare void @write_uint64_to_file(i8*, i64) @proof_output = external global i1 @output_file = external global i8* @@ -50,9 +50,9 @@ define %block* @take_steps(i64 %depth, %block* %subject) { br i1 %proof_output, label %if, label %merge if: %output_file = load i8*, i8** @output_file - call void @writeUInt64ToFile(i8* %output_file, i64 18446744073709551615) - call void @serializeConfigurationToFile(i8* %output_file, %block* %subject, i1 1, i1 1) - call void @writeUInt64ToFile(i8* %output_file, i64 14757395258967641292) + call void @write_uint64_to_file(i8* %output_file, i64 18446744073709551615) + call void @serialize_configuration_to_file(i8* %output_file, %block* %subject, i1 1, i1 1) + call void @write_uint64_to_file(i8* %output_file, i64 14757395258967641292) br label %merge merge: store i64 %depth, i64* @depth @@ -62,7 +62,7 @@ merge: define %block** @take_search_step(%block* %subject, i64* %count) { store i64 -1, i64* @depth - %result = call tailcc %block** @stepAll(%block* %subject, i64* %count) + %result = call tailcc %block** @step_all(%block* %subject, i64* %count) ret %block** %result } diff --git a/runtime/util/ConfigurationParser.cpp b/runtime/util/ConfigurationParser.cpp index bcfdd04f5..2f74372e2 100644 --- a/runtime/util/ConfigurationParser.cpp +++ b/runtime/util/ConfigurationParser.cpp @@ -20,14 +20,14 @@ static thread_local Cache cache; extern "C" { -uint32_t getTagForSymbolNameInternal(char const *); +uint32_t get_tag_for_symbol_name_internal(char const *); void init_float(floating *result, char const *c_str) { std::string contents = std::string(c_str); init_float2(result, contents); } -uint32_t getTagForSymbolName(char const *name) { +uint32_t get_tag_for_symbol_name(char const *name) { std::string s = name; // https://stackoverflow.com/a/101980/6209703 auto lb = cache.lower_bound(s); @@ -36,7 +36,7 @@ uint32_t getTagForSymbolName(char const *name) { return lb->second; } - uint32_t const tag = getTagForSymbolNameInternal(s.c_str()); + uint32_t const tag = get_tag_for_symbol_name_internal(s.c_str()); if (tag == ERROR_TAG) { auto error_message = fmt::format( @@ -52,42 +52,43 @@ uint32_t getTagForSymbolName(char const *name) { } } -static uint32_t getTagForSymbol(KORESymbol const &symbol) { +static uint32_t get_tag_for_symbol(kore_symbol const &symbol) { auto name = ast_to_string(symbol); - return getTagForSymbolName(name.c_str()); + return get_tag_for_symbol_name(name.c_str()); } -void *constructCompositePattern(uint32_t tag, std::vector &arguments) { - if (isSymbolAFunction(tag)) { - return evaluateFunctionSymbol(tag, arguments.data()); +void * +construct_composite_pattern(uint32_t tag, std::vector &arguments) { + if (is_symbol_a_function(tag)) { + return evaluate_function_symbol(tag, arguments.data()); } - struct blockheader headerVal = getBlockHeaderForSymbol(tag); - size_t size = size_hdr(headerVal.hdr); + struct blockheader header_val = get_block_header_for_symbol(tag); + size_t size = size_hdr(header_val.hdr); - if (tag >= first_inj_tag && tag <= last_inj_tag) { - uint16_t layout_code = layout_hdr(headerVal.hdr); - layout *data = getLayoutData(layout_code); + if (tag >= FIRST_INJ_TAG && tag <= LAST_INJ_TAG) { + uint16_t layout_code = layout_hdr(header_val.hdr); + layout *data = get_layout_data(layout_code); if (data->args[0].cat == SYMBOL_LAYOUT) { auto *child = (block *)arguments[0]; if (!is_leaf_block(child) && get_layout(child) != 0) { uint32_t tag = tag_hdr(child->h.hdr); - if (tag >= first_inj_tag && tag <= last_inj_tag) { + if (tag >= FIRST_INJ_TAG && tag <= LAST_INJ_TAG) { return child; } } } } - auto *Block = (block *)koreAlloc(size); - Block->h = headerVal; + auto *new_block = (block *)kore_alloc(size); + new_block->h = header_val; - storeSymbolChildren(Block, arguments.data()); - if (isSymbolABinder(tag)) { - Block = debruijnize(Block); + store_symbol_children(new_block, arguments.data()); + if (is_symbol_a_binder(tag)) { + new_block = debruijnize(new_block); } - return Block; + return new_block; } struct construction { @@ -96,50 +97,50 @@ struct construction { }; // NOLINTNEXTLINE(*-cognitive-complexity) -extern "C" void *constructInitialConfiguration(KOREPattern const *initial) { - std::vector> workList{ +extern "C" void *construct_initial_configuration(kore_pattern const *initial) { + std::vector> work_list{ initial}; std::vector output; - while (!workList.empty()) { - std::variant current = workList.back(); - workList.pop_back(); + while (!work_list.empty()) { + std::variant current = work_list.back(); + work_list.pop_back(); - if (std::holds_alternative(current)) { - auto const *constructor = dynamic_cast( - *std::get_if(¤t)); + if (std::holds_alternative(current)) { + auto const *constructor = dynamic_cast( + *std::get_if(¤t)); assert(constructor && "Pattern in worklist is not composite"); - KORESymbol const *symbol = constructor->getConstructor(); + kore_symbol const *symbol = constructor->get_constructor(); assert( - symbol->isConcrete() + symbol->is_concrete() && "found sort variable in initial configuration"); - if (symbol->getName() == "\\dv") { - auto *const sort = dynamic_cast( - symbol->getFormalArguments()[0].get()); - auto *const strPattern = dynamic_cast( - constructor->getArguments()[0].get()); - std::string contents = strPattern->getContents(); - output.push_back(getToken( - sort->getName().c_str(), contents.size(), contents.c_str())); + if (symbol->get_name() == "\\dv") { + auto *const sort = dynamic_cast( + symbol->get_formal_arguments()[0].get()); + auto *const str_pattern = dynamic_cast( + constructor->get_arguments()[0].get()); + std::string contents = str_pattern->get_contents(); + output.push_back(get_token( + sort->get_name().c_str(), contents.size(), contents.c_str())); continue; } - uint32_t tag = getTagForSymbol(*symbol); + uint32_t tag = get_tag_for_symbol(*symbol); - if (isSymbolAFunction(tag) && constructor->getArguments().empty()) { - output.push_back(evaluateFunctionSymbol(tag, nullptr)); + if (is_symbol_a_function(tag) && constructor->get_arguments().empty()) { + output.push_back(evaluate_function_symbol(tag, nullptr)); continue; } - if (constructor->getArguments().empty()) { + if (constructor->get_arguments().empty()) { output.push_back(leaf_block(tag)); continue; } - construction term{tag, constructor->getArguments().size()}; - workList.emplace_back(term); - for (auto const &child : constructor->getArguments()) { - workList.emplace_back(child.get()); + construction term{tag, constructor->get_arguments().size()}; + work_list.emplace_back(term); + for (auto const &child : constructor->get_arguments()) { + work_list.emplace_back(child.get()); } } else { uint32_t tag = std::get_if(¤t)->tag; @@ -151,7 +152,7 @@ extern "C" void *constructInitialConfiguration(KOREPattern const *initial) { output.pop_back(); } - output.push_back(constructCompositePattern(tag, arguments)); + output.push_back(construct_composite_pattern(tag, arguments)); } } @@ -161,46 +162,46 @@ extern "C" void *constructInitialConfiguration(KOREPattern const *initial) { // NOLINTBEGIN(*-cognitive-complexity) template static void * -deserializeInitialConfiguration(It ptr, It end, binary_version version) { +deserialize_initial_configuration(It ptr, It end, binary_version version) { using namespace kllvm::detail; auto begin = ptr; auto output = std::vector{}; auto token_stack = std::vector{}; - auto sort_stack = std::vector>{}; - auto symbol = kllvm::ptr{}; + auto sort_stack = std::vector>{}; + auto symbol = kllvm::ptr{}; while (ptr < end) { switch (peek(ptr)) { - case header_byte: { + case header_byte: { ++ptr; auto arity = read_length(ptr, end, version, 2); assert(symbol && "No symbol set when reaching composite pattern"); assert( - symbol->isConcrete() + symbol->is_concrete() && "found sort variable in initial configuration"); - if (symbol->getName() == "\\dv") { - auto *sort = dynamic_cast( - symbol->getFormalArguments()[0].get()); + if (symbol->get_name() == "\\dv") { + auto *sort = dynamic_cast( + symbol->get_formal_arguments()[0].get()); assert(sort && "Not a composite sort"); auto const &token = token_stack.back(); output.push_back( - getToken(sort->getName().c_str(), token.size(), token.c_str())); + get_token(sort->get_name().c_str(), token.size(), token.c_str())); token_stack.pop_back(); break; } - uint32_t tag = getTagForSymbol(*symbol); + uint32_t tag = get_tag_for_symbol(*symbol); symbol = nullptr; - if (isSymbolAFunction(tag) && arity == 0) { - output.push_back(evaluateFunctionSymbol(tag, nullptr)); + if (is_symbol_a_function(tag) && arity == 0) { + output.push_back(evaluate_function_symbol(tag, nullptr)); break; } if (arity == 0) { @@ -217,29 +218,29 @@ deserializeInitialConfiguration(It ptr, It end, binary_version version) { } std::reverse(arguments.begin(), arguments.end()); - output.push_back(constructCompositePattern(tag, arguments)); + output.push_back(construct_composite_pattern(tag, arguments)); break; } - case header_byte: + case header_byte: ++ptr; token_stack.push_back(read_string(ptr, end, version)); break; - case header_byte: { + case header_byte: { ++ptr; symbol = read_symbol(ptr, end, sort_stack, version); break; } - case header_byte: { + case header_byte: { ++ptr; sort_stack.push_back( - KORESortVariable::Create(read_string(ptr, end, version))); + kore_sort_variable::create(read_string(ptr, end, version))); break; } - case header_byte: { + case header_byte: { ++ptr; sort_stack.push_back(read_composite_sort(ptr, end, sort_stack, version)); break; @@ -257,21 +258,22 @@ deserializeInitialConfiguration(It ptr, It end, binary_version version) { } // NOLINTEND(*-cognitive-complexity) -block *parseConfiguration(char const *filename) { +block *parse_configuration(char const *filename) { if (has_binary_kore_header(filename)) { auto data = file_contents(filename); - return deserializeConfiguration(data.data(), data.size()); + return deserialize_configuration(data.data(), data.size()); } - auto InitialConfiguration = parser::KOREParser(filename).pattern(); + auto initial_configuration = parser::kore_parser(filename).pattern(); // InitialConfiguration->print(std::cout); // Allocate the llvm KORE datastructures for the configuration - auto *b = (block *)constructInitialConfiguration(InitialConfiguration.get()); - deallocateSPtrKorePattern(std::move(InitialConfiguration)); + auto *b + = (block *)construct_initial_configuration(initial_configuration.get()); + deallocate_s_ptr_kore_pattern(std::move(initial_configuration)); return b; } -block *deserializeConfiguration(char *data, size_t size) { +block *deserialize_configuration(char *data, size_t size) { auto *ptr = data; auto *end = data + size; @@ -287,5 +289,5 @@ block *deserializeConfiguration(char *data, size_t size) { } return static_cast( - deserializeInitialConfiguration(ptr, end, version)); + deserialize_initial_configuration(ptr, end, version)); } diff --git a/runtime/util/ConfigurationPrinter.cpp b/runtime/util/ConfigurationPrinter.cpp index 4b3f3ff1e..437534569 100644 --- a/runtime/util/ConfigurationPrinter.cpp +++ b/runtime/util/ConfigurationPrinter.cpp @@ -21,13 +21,13 @@ #include "runtime/alloc.h" #include "runtime/header.h" -struct StringHash { +struct string_hash { size_t operator()(string *const &k) const { return std::hash{}(std::string(k->data, len(k))); } }; -struct StringEq { +struct string_eq { bool operator()(string *const &lhs, string *const &rhs) const { return hook_STRING_eq(lhs, rhs); } @@ -46,65 +46,65 @@ struct print_state { ~print_state() = default; - std::vector boundVariables; - std::unordered_map varNames; - std::set usedVarNames; - uint64_t varCounter{0}; + std::vector bound_variables; + std::unordered_map var_names; + std::set used_var_names; + uint64_t var_counter{0}; }; -void printInt(writer *file, mpz_t i, char const *sort, void *state) { - auto str = intToString(i); +void print_int(writer *file, mpz_t i, char const *sort, void *state) { + auto str = int_to_string(i); sfprintf(file, R"(\dv{%s}("%s"))", sort, str.c_str()); } -void printFloat(writer *file, floating *f, char const *sort, void *state) { - std::string str = floatToString(f); +void print_float(writer *file, floating *f, char const *sort, void *state) { + std::string str = float_to_string(f); sfprintf(file, R"(\dv{%s}("%s"))", sort, str.c_str()); } -void printBool(writer *file, bool b, char const *sort, void *state) { +void print_bool(writer *file, bool b, char const *sort, void *state) { char const *str = b ? "true" : "false"; sfprintf(file, R"(\dv{%s}("%s"))", sort, str); } -void printStringBuffer( +void print_string_buffer( writer *file, stringbuffer *b, char const *sort, void *state) { std::string str(b->contents->data, b->strlen); sfprintf(file, R"(\dv{%s}("%s"))", sort, str.c_str()); } -void printMInt( +void print_m_int( writer *file, size_t *i, size_t bits, char const *sort, void *state) { if (i == nullptr) { sfprintf(file, R"(\dv{%s}("0p%zd"))", sort, bits); } else { mpz_ptr z = hook_MINT_import(i, bits, false); - auto str = intToString(z); + auto str = int_to_string(z); sfprintf(file, R"(\dv{%s}("%sp%zd"))", sort, str.c_str(), bits); } } -void printComma(writer *file, void *state) { +void print_comma(writer *file, void *state) { sfprintf(file, ","); } // NOLINTNEXTLINE(*-cognitive-complexity) -void printConfigurationInternal( - writer *file, block *subject, char const *sort, bool isVar, +void print_configuration_internal( + writer *file, block *subject, char const *sort, bool is_var, void *state_ptr) { auto &state = *static_cast(state_ptr); - uint8_t isConstant = ((uintptr_t)subject) & 3; - if (isConstant) { + uint8_t is_constant = ((uintptr_t)subject) & 3; + if (is_constant) { uint32_t tag = ((uintptr_t)subject) >> 32; - if (isConstant == 3) { + if (is_constant == 3) { // bound variable - printConfigurationInternal( - file, state.boundVariables[state.boundVariables.size() - 1 - tag], + print_configuration_internal( + file, state.bound_variables[state.bound_variables.size() - 1 - tag], sort, true, state_ptr); return; } - char const *symbol = getSymbolNameForTag(tag); + char const *symbol = get_symbol_name_for_tag(tag); sfprintf(file, "%s()", symbol); return; } @@ -131,67 +131,67 @@ void printConfigurationInternal( break; } } - if (isVar && !state.varNames.contains(str)) { - std::string stdStr = std::string(str->data, len(str)); + if (is_var && !state.var_names.contains(str)) { + std::string std_str = std::string(str->data, len(str)); std::string suffix; - while (state.usedVarNames.contains(stdStr + suffix)) { - suffix = std::to_string(state.varCounter++); + while (state.used_var_names.contains(std_str + suffix)) { + suffix = std::to_string(state.var_counter++); } - stdStr = stdStr + suffix; + std_str = std_str + suffix; sfprintf(file, "%s", suffix.c_str()); - state.usedVarNames.insert(stdStr); - state.varNames[str] = suffix; - } else if (isVar) { - sfprintf(file, "%s", state.varNames[str].c_str()); + state.used_var_names.insert(std_str); + state.var_names[str] = suffix; + } else if (is_var) { + sfprintf(file, "%s", state.var_names[str].c_str()); } sfprintf(file, "\")"); return; } uint32_t tag = tag_hdr(subject->h.hdr); - bool isBinder = isSymbolABinder(tag); - if (isBinder) { - state.boundVariables.push_back( + bool is_binder = is_symbol_a_binder(tag); + if (is_binder) { + state.bound_variables.push_back( *(block **)(((char *)subject) + sizeof(blockheader))); } - char const *symbol = getSymbolNameForTag(tag); - std::string symbolStr(symbol); - if (symbolStr.rfind("inj{", 0) == 0) { - std::string prefix = symbolStr.substr(0, symbolStr.find_first_of(',')); + char const *symbol = get_symbol_name_for_tag(tag); + std::string symbol_str(symbol); + if (symbol_str.rfind("inj{", 0) == 0) { + std::string prefix = symbol_str.substr(0, symbol_str.find_first_of(',')); sfprintf(file, "%s, %s}(", prefix.c_str(), sort); } else { sfprintf(file, "%s(", symbol); } visitor callbacks - = {printConfigurationInternal, - printMap, - printList, - printSet, - printInt, - printFloat, - printBool, - printStringBuffer, - printMInt, - printComma, - printRangeMap}; - - visitChildren(subject, file, &callbacks, state_ptr); - - if (isBinder) { - state.boundVariables.pop_back(); + = {print_configuration_internal, + print_map, + print_list, + print_set, + print_int, + print_float, + print_bool, + print_string_buffer, + print_m_int, + print_comma, + print_range_map}; + + visit_children(subject, file, &callbacks, state_ptr); + + if (is_binder) { + state.bound_variables.pop_back(); } sfprintf(file, ")"); } -void printStatistics(FILE *file, uint64_t steps) { +void print_statistics(FILE *file, uint64_t steps) { fmt::print(file, "{}\n", steps - 1); // off by one adjustment } -void printConfiguration(FILE *file, block *subject) { +void print_configuration(FILE *file, block *subject) { auto state = print_state(); writer w = {file, nullptr}; - printConfigurationInternal(&w, subject, nullptr, false, &state); + print_configuration_internal(&w, subject, nullptr, false, &state); } // If the parameter `results` is passed by reference, the ordering induced by @@ -199,8 +199,8 @@ void printConfiguration(FILE *file, block *subject) { // expected output. We therefore just pass the results by value for now as this // code is not on a hot path. // NOLINTBEGIN(performance-unnecessary-value-param) -void printConfigurations( - FILE *file, std::unordered_set results) { +void print_configurations( + FILE *file, std::unordered_set results) { auto state = print_state(); writer w = {file, nullptr}; @@ -211,7 +211,7 @@ void printConfigurations( sfprintf(&w, "\\or{SortGeneratedTopCell{}}("); size_t j = 0; for (auto const &subject : results) { - printConfigurationInternal(&w, subject, nullptr, false, &state); + print_configuration_internal(&w, subject, nullptr, false, &state); if (++j != results.size()) { sfprintf(&w, ","); } @@ -229,82 +229,84 @@ string *debug_print_term(block *subject, char const *sort) { char const *print_sort = nullptr; if (sort) { - subject = constructKItemInj(subject, sort, false); + subject = construct_k_item_inj(subject, sort, false); print_sort = "SortKItem{}"; } - printConfigurationInternal(&w, subject, print_sort, false, &state); + print_configuration_internal(&w, subject, print_sort, false, &state); return hook_BUFFER_toString(buf); } -string *printConfigurationToString(block *subject) { +string *print_configuration_to_string(block *subject) { auto state = print_state(); stringbuffer *buf = hook_BUFFER_empty(); writer w = {nullptr, buf}; - printConfigurationInternal(&w, subject, nullptr, false, &state); + print_configuration_internal(&w, subject, nullptr, false, &state); return hook_BUFFER_toString(buf); } -void printSortedConfigurationToFile( +void print_sorted_configuration_to_file( FILE *file, block *subject, char const *sort) { auto state = print_state(); writer w = {file, nullptr}; - printConfigurationInternal(&w, subject, sort, false, &state); + print_configuration_internal(&w, subject, sort, false, &state); } -extern "C" void printMatchResult( - std::ostream &os, MatchLog *matchLog, size_t logSize, - std::string const &definitionPath) { +extern "C" void print_match_result( + std::ostream &os, match_log *match_log, size_t log_size, + std::string const &definition_path) { auto subject_file = temporary_file("subject_XXXXXX"); auto *subject = subject_file.file_pointer("w"); auto pattern_file = temporary_file("pattern_XXXXXX"); - for (int i = 0; i < logSize; i++) { - if (matchLog[i].kind == MatchLog::SUCCESS) { + for (int i = 0; i < log_size; i++) { + if (match_log[i].kind == match_log::Success) { os << "Match succeeds\n"; - } else if (matchLog[i].kind == MatchLog::FAIL) { + } else if (match_log[i].kind == match_log::Fail) { os << "Subject:\n"; if (i == 0) { - printSortedConfigurationToFile( - subject, (block *)matchLog[i].subject, matchLog[i].sort); + print_sorted_configuration_to_file( + subject, (block *)match_log[i].subject, match_log[i].sort); } else { - auto *subjectSort - = debug_print_term((block *)matchLog[i].subject, matchLog[i].sort); - auto strSubjectSort = std::string(subjectSort->data, len(subjectSort)); - subject_file.ofstream() << strSubjectSort << std::endl; + auto *subject_sort = debug_print_term( + (block *)match_log[i].subject, match_log[i].sort); + auto str_subject_sort + = std::string(subject_sort->data, len(subject_sort)); + subject_file.ofstream() << str_subject_sort << std::endl; } - kllvm::printKORE( - os, definitionPath, subject_file.filename(), false, true); + kllvm::print_kore( + os, definition_path, subject_file.filename(), false, true); os << "does not match pattern: \n"; - pattern_file.ofstream() << matchLog[i].pattern << std::endl; - kllvm::printKORE( - os, definitionPath, pattern_file.filename(), false, true); - } else if (matchLog[i].kind == MatchLog::FUNCTION) { - os << matchLog[i].debugName << "("; - - for (int j = 0; j < matchLog[i].args.size(); j += 2) { - auto *typeName = static_cast(matchLog[i].args[j + 1]); - printValueOfType(os, definitionPath, matchLog[i].args[j], typeName); - if (j + 2 != matchLog[i].args.size()) { + pattern_file.ofstream() << match_log[i].pattern << std::endl; + kllvm::print_kore( + os, definition_path, pattern_file.filename(), false, true); + } else if (match_log[i].kind == match_log::Function) { + os << match_log[i].debug_name << "("; + + for (int j = 0; j < match_log[i].args.size(); j += 2) { + auto *type_name = static_cast(match_log[i].args[j + 1]); + print_value_of_type( + os, definition_path, match_log[i].args[j], type_name); + if (j + 2 != match_log[i].args.size()) { os << ", "; } } - os << ") => " << *static_cast(matchLog[i].result) << "\n"; + os << ") => " << *static_cast(match_log[i].result) << "\n"; } } } -void printValueOfType( - std::ostream &os, std::string const &definitionPath, void *value, +void print_value_of_type( + std::ostream &os, std::string const &definition_path, void *value, std::string const &type) { if (type == "%mpz*") { os << static_cast(value); } else if (type == "%block*") { if ((((uintptr_t)value) & 3) == 1) { auto f = temporary_file("subject_XXXXXX"); - string *s = printConfigurationToString(static_cast(value)); + string *s = print_configuration_to_string(static_cast(value)); f.ofstream() << std::string(s->data, len(s)) << std::endl; - kllvm::printKORE(os, definitionPath, f.filename(), false, true); + kllvm::print_kore(os, definition_path, f.filename(), false, true); } else if ((((uintptr_t)value) & 1) == 0) { auto *s = static_cast(value); os << std::string(s->data, len(s)); @@ -312,7 +314,7 @@ void printValueOfType( os << "Error: " << type << " not implemented!"; } } else if (type == "%floating*") { - os << floatToString(static_cast(value)); + os << float_to_string(static_cast(value)); } else if (type == "i1") { os << *static_cast(value); } else { @@ -320,7 +322,7 @@ void printValueOfType( } } -void printVariableToFile(FILE *file, char const *varname) { +void print_variable_to_file(FILE *file, char const *varname) { fmt::print(file, "{}", varname); char n = 0; fwrite(&n, 1, 1, file); diff --git a/runtime/util/ConfigurationSerializer.cpp b/runtime/util/ConfigurationSerializer.cpp index 8e90e4788..8b2b47077 100644 --- a/runtime/util/ConfigurationSerializer.cpp +++ b/runtime/util/ConfigurationSerializer.cpp @@ -16,13 +16,13 @@ using namespace kllvm; using namespace kllvm::parser; -struct StringHash { +struct string_hash { size_t operator()(string *const &k) const { return std::hash{}(std::string(k->data, len(k))); } }; -struct StringEq { +struct string_eq { bool operator()(string *const &lhs, string *const &rhs) const { return hook_STRING_eq(lhs, rhs); } @@ -44,39 +44,39 @@ struct serialization_state { ~serialization_state() = default; serializer instance; - std::vector boundVariables; - std::unordered_map varNames; - std::set usedVarNames; - uint64_t varCounter{0}; + std::vector bound_variables; + std::unordered_map var_names; + std::set used_var_names; + uint64_t var_counter{0}; }; static std::string drop_back(std::string const &s, int n) { return s.substr(0, s.size() - n); } -void serializeConfigurationInternal( - writer *file, block *subject, char const *sort, bool isVar, void *state); +void serialize_configuration_internal( + writer *file, block *subject, char const *sort, bool is_var, void *state); /** * Emit a symbol of the form ctor{...}(...); this should be preceded by the * appropriate pattern arguments in the buffer. */ -static void emitSymbol( +static void emit_symbol( serializer &instance, char const *name, uint64_t arity = 0, uint64_t symbol_arity = 0) { - instance.emit(header_byte); + instance.emit(header_byte); instance.emit_length(symbol_arity); instance.emit_string(drop_back(name, 2)); - instance.emit(header_byte); + instance.emit(header_byte); instance.emit_length(arity); } /** * Emit a 0-argument sort of the form Sort{} */ -static void emitConstantSort(serializer &instance, char const *name) { - instance.emit(header_byte); +static void emit_constant_sort(serializer &instance, char const *name) { + instance.emit(header_byte); instance.emit_length(0); instance.emit_string(name); } @@ -84,9 +84,9 @@ static void emitConstantSort(serializer &instance, char const *name) { /** * Emit a symbol of the form \dv{Sort}("string") */ -static void emitToken( +static void emit_token( serializer &instance, char const *sort, char const *string, int len = -1) { - instance.emit(header_byte); + instance.emit(header_byte); // Allow the length of the token to be passed in explicitly to handle the // Bytes sort, which can include null characters in the middle of a string. @@ -98,173 +98,173 @@ static void emitToken( instance.emit_string(std::string(string, len)); } - emitConstantSort(instance, drop_back(sort, 2).c_str()); + emit_constant_sort(instance, drop_back(sort, 2).c_str()); - instance.emit(header_byte); + instance.emit(header_byte); instance.emit_length(1); instance.emit_string("\\dv"); - instance.emit(header_byte); + instance.emit(header_byte); instance.emit_length(1); } -void serializeMap( +void serialize_map( writer *file, map *map, char const *unit, char const *element, char const *concat, void *state) { auto &instance = static_cast(state)->instance; size_t size = map->size(); if (size == 0) { - emitSymbol(instance, unit); + emit_symbol(instance, unit); return; } - auto tag = getTagForSymbolName(element); - auto *arg_sorts = getArgumentSortsForTag(tag); + auto tag = get_tag_for_symbol_name(element); + auto *arg_sorts = get_argument_sorts_for_tag(tag); for (auto iter = map->begin(); iter != map->end(); ++iter) { - serializeConfigurationInternal( + serialize_configuration_internal( file, iter->first, arg_sorts[0], false, state); - serializeConfigurationInternal( + serialize_configuration_internal( file, iter->second, arg_sorts[1], false, state); - emitSymbol(instance, element, 2); + emit_symbol(instance, element, 2); if (iter != map->begin()) { - emitSymbol(instance, concat, 2); + emit_symbol(instance, concat, 2); } } } -void serializeRangeMap( +void serialize_range_map( writer *file, rangemap *map, char const *unit, char const *element, char const *concat, void *state) { auto &instance = static_cast(state)->instance; size_t size = map->size(); if (size == 0) { - emitSymbol(instance, unit); + emit_symbol(instance, unit); return; } - auto tag = getTagForSymbolName(element); - auto *arg_sorts = getArgumentSortsForTag(tag); + auto tag = get_tag_for_symbol_name(element); + auto *arg_sorts = get_argument_sorts_for_tag(tag); bool once = true; - for (auto iter = rng_map::ConstRangeMapIterator(*map); + for (auto iter = rng_map::ConstRangeMapIterator(*map); iter.has_next(); ++iter) { - serializeConfigurationInternal( + serialize_configuration_internal( file, iter->first.start(), "SortKItem{}", false, state); - serializeConfigurationInternal( + serialize_configuration_internal( file, iter->first.end(), "SortKItem{}", false, state); - emitSymbol(instance, "LblRangemap'Coln'Range{}", 2); - serializeConfigurationInternal( + emit_symbol(instance, "LblRangemap'Coln'Range{}", 2); + serialize_configuration_internal( file, iter->second, arg_sorts[1], false, state); - emitSymbol(instance, element, 2); + emit_symbol(instance, element, 2); if (once) { once = false; } else { - emitSymbol(instance, concat, 2); + emit_symbol(instance, concat, 2); } } } -void serializeList( +void serialize_list( writer *file, list *list, char const *unit, char const *element, char const *concat, void *state) { auto &instance = static_cast(state)->instance; size_t size = list->size(); if (size == 0) { - emitSymbol(instance, unit); + emit_symbol(instance, unit); return; } - auto tag = getTagForSymbolName(element); - auto *arg_sorts = getArgumentSortsForTag(tag); + auto tag = get_tag_for_symbol_name(element); + auto *arg_sorts = get_argument_sorts_for_tag(tag); for (auto iter = list->begin(); iter != list->end(); ++iter) { - serializeConfigurationInternal(file, *iter, arg_sorts[0], false, state); - emitSymbol(instance, element, 1); + serialize_configuration_internal(file, *iter, arg_sorts[0], false, state); + emit_symbol(instance, element, 1); if (iter != list->begin()) { - emitSymbol(instance, concat, 2); + emit_symbol(instance, concat, 2); } } } -void serializeSet( +void serialize_set( writer *file, set *set, char const *unit, char const *element, char const *concat, void *state) { auto &instance = static_cast(state)->instance; size_t size = set->size(); if (size == 0) { - emitSymbol(instance, unit); + emit_symbol(instance, unit); return; } - auto tag = getTagForSymbolName(element); - auto *arg_sorts = getArgumentSortsForTag(tag); + auto tag = get_tag_for_symbol_name(element); + auto *arg_sorts = get_argument_sorts_for_tag(tag); for (auto iter = set->begin(); iter != set->end(); ++iter) { - serializeConfigurationInternal(file, *iter, arg_sorts[0], false, state); - emitSymbol(instance, element, 1); + serialize_configuration_internal(file, *iter, arg_sorts[0], false, state); + emit_symbol(instance, element, 1); if (iter != set->begin()) { - emitSymbol(instance, concat, 2); + emit_symbol(instance, concat, 2); } } } -void serializeInt(writer *file, mpz_t i, char const *sort, void *state) { +void serialize_int(writer *file, mpz_t i, char const *sort, void *state) { auto &instance = static_cast(state)->instance; - auto str = intToString(i); - emitToken(instance, sort, str.c_str()); + auto str = int_to_string(i); + emit_token(instance, sort, str.c_str()); } -void serializeFloat(writer *file, floating *f, char const *sort, void *state) { +void serialize_float(writer *file, floating *f, char const *sort, void *state) { auto &instance = static_cast(state)->instance; - std::string str = floatToString(f); - emitToken(instance, sort, str.c_str()); + std::string str = float_to_string(f); + emit_token(instance, sort, str.c_str()); } -void serializeBool(writer *file, bool b, char const *sort, void *state) { +void serialize_bool(writer *file, bool b, char const *sort, void *state) { auto &instance = static_cast(state)->instance; char const *str = b ? "true" : "false"; - emitToken(instance, sort, str); + emit_token(instance, sort, str); } -void serializeStringBuffer( +void serialize_string_buffer( writer *file, stringbuffer *b, char const *sort, void *state) { auto &instance = static_cast(state)->instance; - emitToken(instance, sort, b->contents->data, b->strlen); + emit_token(instance, sort, b->contents->data, b->strlen); } -void serializeMInt( +void serialize_m_int( writer *file, size_t *i, size_t bits, char const *sort, void *state) { auto &instance = static_cast(state)->instance; auto str = (i == nullptr) ? std::string("0") - : intToString(hook_MINT_import(i, bits, false)); + : int_to_string(hook_MINT_import(i, bits, false)); auto buffer = fmt::format("{}p{}", str, bits); - emitToken(instance, sort, buffer.c_str()); + emit_token(instance, sort, buffer.c_str()); } -void serializeComma(writer *file, void *state) { } +void serialize_comma(writer *file, void *state) { } -static std::pair>> +static std::pair>> cached_symbol_sort_list(std::string const &symbol) { static auto cache = std::unordered_map< - std::string, std::pair>>>{}; + std::string, std::pair>>>{}; if (cache.find(symbol) == cache.end()) { - auto [id, sorts] = KOREParser::from_string(symbol)->symbol_sort_list(); + auto [id, sorts] = kore_parser::from_string(symbol)->symbol_sort_list(); // The parser returns the actual name of the symbol separately to its formal // sort parameters. However, the interface of emitSymbol is compatible with @@ -279,25 +279,25 @@ cached_symbol_sort_list(std::string const &symbol) { return cache.at(symbol); } -void serializeConfigurationInternal( - writer *file, block *subject, char const *sort, bool isVar, +void serialize_configuration_internal( + writer *file, block *subject, char const *sort, bool is_var, void *state_ptr) { auto &state = *static_cast(state_ptr); - uint8_t isConstant = ((uintptr_t)subject) & 3; + uint8_t is_constant = ((uintptr_t)subject) & 3; - if (isConstant) { + if (is_constant) { uint32_t tag = ((uintptr_t)subject) >> 32; - if (isConstant == 3) { + if (is_constant == 3) { // bound variable - serializeConfigurationInternal( - file, state.boundVariables[state.boundVariables.size() - 1 - tag], + serialize_configuration_internal( + file, state.bound_variables[state.bound_variables.size() - 1 - tag], sort, true, state_ptr); return; } - emitSymbol(state.instance, getSymbolNameForTag(tag)); + emit_symbol(state.instance, get_symbol_name_for_tag(tag)); return; } @@ -306,50 +306,50 @@ void serializeConfigurationInternal( auto *str = (string *)subject; size_t subject_len = len(subject); - if (isVar && !state.varNames.contains(str)) { - std::string stdStr = std::string(str->data, len(str)); + if (is_var && !state.var_names.contains(str)) { + std::string std_str = std::string(str->data, len(str)); std::string suffix; - while (state.usedVarNames.contains(stdStr + suffix)) { - suffix = std::to_string(state.varCounter++); + while (state.used_var_names.contains(std_str + suffix)) { + suffix = std::to_string(state.var_counter++); } - stdStr = stdStr + suffix; - emitToken(state.instance, sort, suffix.c_str()); - state.usedVarNames.insert(stdStr); - state.varNames[str] = suffix; - } else if (isVar) { - emitToken(state.instance, sort, state.varNames[str].c_str()); + std_str = std_str + suffix; + emit_token(state.instance, sort, suffix.c_str()); + state.used_var_names.insert(std_str); + state.var_names[str] = suffix; + } else if (is_var) { + emit_token(state.instance, sort, state.var_names[str].c_str()); } else { - emitToken(state.instance, sort, str->data, subject_len); + emit_token(state.instance, sort, str->data, subject_len); } return; } uint32_t tag = tag_hdr(subject->h.hdr); - bool isBinder = isSymbolABinder(tag); - if (isBinder) { - state.boundVariables.push_back( + bool is_binder = is_symbol_a_binder(tag); + if (is_binder) { + state.bound_variables.push_back( *(block **)(((char *)subject) + sizeof(blockheader))); } visitor callbacks - = {serializeConfigurationInternal, - serializeMap, - serializeList, - serializeSet, - serializeInt, - serializeFloat, - serializeBool, - serializeStringBuffer, - serializeMInt, - serializeComma, - serializeRangeMap}; - - visitChildren(subject, file, &callbacks, state_ptr); - - auto const *symbol = getSymbolNameForTag(tag); - - if (symbolIsInstantiation(tag)) { + = {serialize_configuration_internal, + serialize_map, + serialize_list, + serialize_set, + serialize_int, + serialize_float, + serialize_bool, + serialize_string_buffer, + serialize_m_int, + serialize_comma, + serialize_range_map}; + + visit_children(subject, file, &callbacks, state_ptr); + + auto const *symbol = get_symbol_name_for_tag(tag); + + if (symbol_is_instantiation(tag)) { auto [name, sorts] = cached_symbol_sort_list(symbol); if (name == "inj{}") { @@ -360,42 +360,43 @@ void serializeConfigurationInternal( assert(sorts.size() == 2 && "Malformed injection when serializing"); sorts[0]->serialize_to(state.instance); - emitConstantSort(state.instance, drop_back(sort, 2).c_str()); + emit_constant_sort(state.instance, drop_back(sort, 2).c_str()); } else { for (auto const &s : sorts) { s->serialize_to(state.instance); } } - emitSymbol(state.instance, name.c_str(), getSymbolArity(tag), sorts.size()); + emit_symbol( + state.instance, name.c_str(), get_symbol_arity(tag), sorts.size()); } else { - emitSymbol(state.instance, symbol, getSymbolArity(tag)); + emit_symbol(state.instance, symbol, get_symbol_arity(tag)); } - if (isBinder) { - state.boundVariables.pop_back(); + if (is_binder) { + state.bound_variables.pop_back(); } } -void serializeConfigurations( - FILE *file, std::unordered_set results) { +void serialize_configurations( + FILE *file, std::unordered_set results) { auto state = serialization_state(); auto w = writer{file, nullptr}; auto size = results.size(); if (size == 0) { - emitConstantSort(state.instance, "SortGeneratedTopCell"); - emitSymbol(state.instance, "\\bottom{}", size, 1); + emit_constant_sort(state.instance, "SortGeneratedTopCell"); + emit_symbol(state.instance, "\\bottom{}", size, 1); } else if (size == 1) { auto *result = *results.begin(); - serializeConfigurationInternal(&w, result, nullptr, false, &state); + serialize_configuration_internal(&w, result, nullptr, false, &state); } else { for (auto const &subject : results) { - serializeConfigurationInternal(&w, subject, nullptr, false, &state); + serialize_configuration_internal(&w, subject, nullptr, false, &state); } - emitConstantSort(state.instance, "SortGeneratedTopCell"); - emitSymbol(state.instance, "\\or{}", size, 1); + emit_constant_sort(state.instance, "SortGeneratedTopCell"); + emit_symbol(state.instance, "\\or{}", size, 1); } auto buf_size = state.instance.data().size(); @@ -406,25 +407,26 @@ void serializeConfigurations( free(buf); } -void serializeConfigurationToFile( +void serialize_configuration_to_file( FILE *file, block *subject, bool emit_size, bool use_intern) { char *data = nullptr; size_t size = 0; - serializeConfiguration(subject, nullptr, &data, &size, emit_size, use_intern); + serialize_configuration( + subject, nullptr, &data, &size, emit_size, use_intern); fwrite(data, 1, size, file); free(data); } -void serializeConfiguration( +void serialize_configuration( block *subject, char const *sort, char **data_out, size_t *size_out, bool emit_size, bool use_intern) { auto state = serialization_state( - use_intern ? serializer::flags::NONE : serializer::flags::NO_INTERN); + use_intern ? serializer::flags::NONE : serializer::flags::NoIntern); writer w = {nullptr, nullptr}; - serializeConfigurationInternal(&w, subject, sort, false, &state); + serialize_configuration_internal(&w, subject, sort, false, &state); if (emit_size) { state.instance.correct_emitted_size(); @@ -438,49 +440,50 @@ void serializeConfiguration( *size_out = size; } -void writeUInt64ToFile(FILE *file, uint64_t i) { +void write_uint64_to_file(FILE *file, uint64_t i) { fwrite(&i, 8, 1, file); } -void serializeTermToFile( +void serialize_term_to_file( FILE *file, block *subject, char const *sort, bool use_intern) { char *data = nullptr; size_t size = 0; - serializeConfiguration(subject, sort, &data, &size, true, use_intern); + serialize_configuration(subject, sort, &data, &size, true, use_intern); fwrite(data, 1, size, file); free(data); } -void serializeRawTermToFile( +void serialize_raw_term_to_file( FILE *file, void *subject, char const *sort, bool use_intern) { - block *term = constructRawTerm(subject, sort, true); + block *term = construct_raw_term(subject, sort, true); char *data = nullptr; size_t size = 0; - serializeConfiguration(term, "SortKItem{}", &data, &size, true, use_intern); + serialize_configuration(term, "SortKItem{}", &data, &size, true, use_intern); fwrite(data, 1, size, file); free(data); } -std::shared_ptr -sortedTermToKorePattern(block *subject, char const *sort) { +std::shared_ptr +sorted_term_to_kore_pattern(block *subject, char const *sort) { auto is_kitem = (std::string(sort) == "SortKItem{}"); - block *term = is_kitem ? subject : constructRawTerm(subject, sort, false); + block *term = is_kitem ? subject : construct_raw_term(subject, sort, false); char *data_out = nullptr; size_t size_out = 0; - serializeConfiguration(term, "SortKItem{}", &data_out, &size_out, true, true); + serialize_configuration( + term, "SortKItem{}", &data_out, &size_out, true, true); auto result = deserialize_pattern(data_out, data_out + size_out); free(data_out); return result; } -std::shared_ptr termToKorePattern(block *subject) { - return sortedTermToKorePattern(subject, "SortKItem{}"); +std::shared_ptr term_to_kore_pattern(block *subject) { + return sorted_term_to_kore_pattern(subject, "SortKItem{}"); } diff --git a/runtime/util/finish_rewriting.cpp b/runtime/util/finish_rewriting.cpp index cc256dca5..97b425fdf 100644 --- a/runtime/util/finish_rewriting.cpp +++ b/runtime/util/finish_rewriting.cpp @@ -35,14 +35,14 @@ int32_t get_exit_code(block *); } if (statistics) { - printStatistics(output_file, steps); + print_statistics(output_file, steps); } if (!proof_output) { if (binary_output) { - serializeConfigurationToFile(output_file, subject, true, true); + serialize_configuration_to_file(output_file, subject, true, true); } else { - printConfiguration(output_file, subject); + print_configuration(output_file, subject); } } diff --git a/runtime/util/match_log.cpp b/runtime/util/match_log.cpp index 2e5abe1f2..dd153b1ed 100644 --- a/runtime/util/match_log.cpp +++ b/runtime/util/match_log.cpp @@ -5,32 +5,32 @@ #include #include -extern "C" void *getStderr(void) { +extern "C" void *get_stderr(void) { return stderr; } -static std::vector matchLog; +static std::vector match_logs; -void **getMatchFnArgs(MatchLog *log) { +void **get_match_fn_args(match_log *log) { return log->args.data(); } extern "C" { -void resetMatchReason(void) { - matchLog.clear(); +void reset_match_reason(void) { + match_logs.clear(); } -MatchLog *getMatchLog(void) { - return matchLog.data(); +match_log *getmatch_log(void) { + return match_logs.data(); } -size_t getMatchLogSize(void) { - return matchLog.size(); +size_t getmatch_log_size(void) { + return match_logs.size(); } -void addMatchSuccess(void) { - matchLog.push_back( - {MatchLog::SUCCESS, +void add_match_success(void) { + match_logs.push_back( + {match_log::Success, nullptr, nullptr, nullptr, @@ -40,13 +40,14 @@ void addMatchSuccess(void) { nullptr}); } -void addMatchFailReason(void *subject, char const *pattern, char const *sort) { - matchLog.push_back( - {MatchLog::FAIL, nullptr, nullptr, nullptr, {}, pattern, subject, sort}); +void add_match_fail_reason( + void *subject, char const *pattern, char const *sort) { + match_logs.push_back( + {match_log::Fail, nullptr, nullptr, nullptr, {}, pattern, subject, sort}); } -void addMatchFunction( - char const *debugName, char const *function, void *result, ...) { +void add_match_function( + char const *debug_name, char const *function, void *result, ...) { // This function needs to use C variadic arguments because it's called from // generated LLVM IR. // NOLINTBEGIN(*-vararg) @@ -62,9 +63,9 @@ void addMatchFunction( args.push_back(arg); } - matchLog.push_back( - {MatchLog::FUNCTION, function, debugName, result, args, nullptr, nullptr, - nullptr}); + match_logs.push_back( + {match_log::Function, function, debug_name, result, args, nullptr, + nullptr, nullptr}); va_end(ap); // NOLINTEND(*-vararg) diff --git a/runtime/util/search.cpp b/runtime/util/search.cpp index b1a5c288e..4c52f5abf 100644 --- a/runtime/util/search.cpp +++ b/runtime/util/search.cpp @@ -6,12 +6,12 @@ #include "runtime/collect.h" #include "runtime/header.h" -static std::vector stepResults; +static std::vector step_results; extern "C" { -void addSearchResult(block *result) { - stepResults.push_back(result); +void add_search_result(block *result) { + step_results.push_back(result); } void take_search_step(block *); @@ -19,31 +19,31 @@ void take_search_step(block *); static std::list states; static block *state; -static std::unordered_set states_set; -static std::unordered_set results; +static std::unordered_set states_set; +static std::unordered_set results; static std::pair< std::vector::iterator, std::vector::iterator> -blockEnumerator() { +block_enumerator() { // NOLINTBEGIN(*-const-cast) static std::vector blocks; blocks.clear(); - for (auto &keyVal : states) { - blocks.push_back(const_cast(&(keyVal))); + for (auto &key_val : states) { + blocks.push_back(const_cast(&(key_val))); } blocks.push_back(&state); - for (auto &keyVal : stepResults) { - blocks.push_back(const_cast(&(keyVal))); + for (auto &key_val : step_results) { + blocks.push_back(const_cast(&(key_val))); } - for (auto const &keyVal : states_set) { - blocks.push_back(const_cast(&(keyVal))); + for (auto const &key_val : states_set) { + blocks.push_back(const_cast(&(key_val))); } - for (auto const &keyVal : results) { - blocks.push_back(const_cast(&(keyVal))); + for (auto const &key_val : results) { + blocks.push_back(const_cast(&(key_val))); } return std::make_pair(blocks.begin(), blocks.end()); @@ -51,11 +51,11 @@ blockEnumerator() { } // NOLINTNEXTLINE(*-cognitive-complexity) -std::unordered_set take_search_steps( - bool executeToBranch, int64_t depth, int64_t bound, block *subject) { +std::unordered_set take_search_steps( + bool execute_to_branch, int64_t depth, int64_t bound, block *subject) { static int registered = -1; if (registered == -1) { - registerGCRootsEnumerator(blockEnumerator); + register_gc_roots_enumerator(block_enumerator); } states.clear(); @@ -78,20 +78,20 @@ std::unordered_set take_search_steps( depth--; } - stepResults.clear(); + step_results.clear(); take_search_step(state); - if (executeToBranch && stepResults.size() > 1) { + if (execute_to_branch && step_results.size() > 1) { results.insert(state); return results; } - if (stepResults.empty()) { + if (step_results.empty()) { results.insert(state); if (results.size() == bound) { return results; } } else { - for (block *result : stepResults) { + for (block *result : step_results) { auto dirty = states_set.insert(result); if (dirty.second) { states.push_back(result); diff --git a/runtime/util/util.cpp b/runtime/util/util.cpp index 3da47e6c8..e1671513d 100644 --- a/runtime/util/util.cpp +++ b/runtime/util/util.cpp @@ -4,13 +4,9 @@ extern "C" { -block *dot_k() { - return leaf_block(getTagForSymbolName("dotk{}")); -} - bool is_injection(block *term) { auto tag = tag_hdr(term->h.hdr); - return tag >= first_inj_tag && tag <= last_inj_tag; + return tag >= FIRST_INJ_TAG && tag <= LAST_INJ_TAG; } block *strip_injection(block *term) { @@ -21,24 +17,24 @@ block *strip_injection(block *term) { return term; } -block *constructKItemInj(void *subject, char const *sort, bool raw_value) { +block *construct_k_item_inj(void *subject, char const *sort, bool raw_value) { auto inj_sym = "inj{" + std::string(sort) + ", SortKItem{}}"; - auto tag = getTagForSymbolName(inj_sym.c_str()); + auto tag = get_tag_for_symbol_name(inj_sym.c_str()); auto sort_prefix = std::string(sort).substr(0, 8); auto integral_sort = sort_prefix == "SortBool" || sort_prefix == "SortMInt"; auto add_indirection = raw_value && integral_sort; auto args = std::vector{add_indirection ? (void *)&subject : subject}; - return static_cast(constructCompositePattern(tag, args)); + return static_cast(construct_composite_pattern(tag, args)); } -block *constructRawTerm(void *subject, char const *sort, bool raw_value) { - auto tag = getTagForSymbolName("rawTerm{}"); +block *construct_raw_term(void *subject, char const *sort, bool raw_value) { + auto tag = get_tag_for_symbol_name("rawTerm{}"); auto args = std::vector{ - static_cast(constructKItemInj(subject, sort, raw_value))}; - return static_cast(constructCompositePattern(tag, args)); + static_cast(construct_k_item_inj(subject, sort, raw_value))}; + return static_cast(construct_composite_pattern(tag, args)); } -void printProofHintHeader(FILE *file) { +void print_proof_hint_header(FILE *file) { uint32_t version = 5; fmt::print(file, "HINT"); fwrite(&version, sizeof(version), 1, file); diff --git a/scripts/clang-tidy.sh b/scripts/clang-tidy.sh index 367aed953..e477d1c9a 100755 --- a/scripts/clang-tidy.sh +++ b/scripts/clang-tidy.sh @@ -21,11 +21,11 @@ source_dirs=( tools ) -mapfile -t inputs < <(find "${source_dirs[@]}" -name '*.cpp' -or -name '*.h') +mapfile -t inputs < <(find "${source_dirs[@]}" -name '*.cpp') "${driver}" \ "${inputs[@]}" \ - -header-filter 'include/(kllvm|runtime)/' \ + -header-filter '(include/kllvm/)|(include/runtime/*.h)' \ -clang-tidy-binary "${clang_tidy}" \ -j "$(nproc)" \ -p "${BUILD_DIR}" "$@" \ diff --git a/test/python/test_proof_trace.py b/test/python/test_proof_trace.py index 67d8e90c8..7aff383c5 100644 --- a/test/python/test_proof_trace.py +++ b/test/python/test_proof_trace.py @@ -21,7 +21,7 @@ def test_file(self): "Output", "test_proof_trace.py.tmp", "proof_trace.bin") with open(binary_proof_trace, 'rb') as f: data = f.read() - trace = kllvm.prooftrace.LLVMRewriteTrace.parse(data) + trace = kllvm.prooftrace.llvm_rewrite_trace.parse(data) self.assertFalse(trace is None) # check that there is a initial configuration diff --git a/tools/k-rule-apply/auxiliar.h b/tools/k-rule-apply/auxiliar.h index 2d7416140..36311ab90 100644 --- a/tools/k-rule-apply/auxiliar.h +++ b/tools/k-rule-apply/auxiliar.h @@ -14,25 +14,27 @@ using namespace kllvm; extern "C" { -void *constructInitialConfiguration(KOREPattern const *); -void resetMatchReason(); -MatchLog *getMatchLog(); -size_t getMatchLogSize(); -void printMatchResult(std::ostream &, MatchLog *, size_t, std::string const &); -void initStaticObjects(); +void *construct_initial_configuration(kore_pattern const *); +void reset_match_reason(); +match_log *getmatch_log(); +size_t getmatch_log_size(); +void print_match_result( + std::ostream &, match_log *, size_t, std::string const &); +void init_static_objects(); } -void *constructInitialConfiguration(KOREPattern const *pattern, void *handle) { - void *funcPtr = dlsym(handle, "constructInitialConfiguration"); +void * +construct_initial_configuration(kore_pattern const *pattern, void *handle) { + void *funcPtr = dlsym(handle, "construct_initial_configuration"); if (funcPtr == NULL) { return NULL; } - auto f = reinterpret_cast(funcPtr); + auto f = reinterpret_cast(funcPtr); return f(pattern); } -void *resetMatchReason(void *handle) { - void *funcPtr = dlsym(handle, "resetMatchReason"); +void *reset_match_reason(void *handle) { + void *funcPtr = dlsym(handle, "reset_match_reason"); if (funcPtr == NULL) { return NULL; } @@ -40,17 +42,17 @@ void *resetMatchReason(void *handle) { return f(); } -MatchLog *getMatchLog(void *handle) { - void *funcPtr = dlsym(handle, "getMatchLog"); +match_log *getmatch_log(void *handle) { + void *funcPtr = dlsym(handle, "getmatch_log"); if (funcPtr == NULL) { return NULL; } - auto f = reinterpret_cast(funcPtr); + auto f = reinterpret_cast(funcPtr); return f(); } -size_t getMatchLogSize(void *handle) { - void *funcPtr = dlsym(handle, "getMatchLogSize"); +size_t getmatch_log_size(void *handle) { + void *funcPtr = dlsym(handle, "getmatch_log_size"); if (funcPtr == NULL) { return -1; } @@ -58,21 +60,21 @@ size_t getMatchLogSize(void *handle) { return f(); } -void *printMatchResult( - std::ostream &os, MatchLog *log, size_t logSize, std::string const &dir, +void *print_match_result( + std::ostream &os, match_log *log, size_t logSize, std::string const &dir, void *handle) { - void *funcPtr = dlsym(handle, "printMatchResult"); + void *funcPtr = dlsym(handle, "print_match_result"); if (funcPtr == NULL) { return NULL; } auto f = reinterpret_cast< - void *(*)(std::ostream &, MatchLog *, size_t, std::string const &)>( + void *(*)(std::ostream &, match_log *, size_t, std::string const &)>( funcPtr); return f(os, log, logSize, dir); } -void *initStaticObjects(void *handle) { - void *funcPtr = dlsym(handle, "initStaticObjects"); +void *init_static_objects(void *handle) { + void *funcPtr = dlsym(handle, "init_static_objects"); if (funcPtr == NULL) { return NULL; } diff --git a/tools/k-rule-apply/main.cpp b/tools/k-rule-apply/main.cpp index 407076570..2afbc456d 100644 --- a/tools/k-rule-apply/main.cpp +++ b/tools/k-rule-apply/main.cpp @@ -3,62 +3,62 @@ using namespace llvm; using namespace kllvm; -cl::OptionCategory KRuleCat("k-rule-apply options"); +cl::OptionCategory k_rule_cat("k-rule-apply options"); -cl::opt KompiledDir( +cl::opt kompiled_dir( cl::Positional, cl::desc(""), cl::Required, - cl::cat(KRuleCat)); + cl::cat(k_rule_cat)); -cl::opt RuleLabel( +cl::opt rule_label( cl::Positional, cl::desc(""), cl::Required, - cl::cat(KRuleCat)); + cl::cat(k_rule_cat)); -cl::opt KOREPatternFilename( +cl::opt kore_pattern_filename( cl::Positional, cl::desc(""), cl::Required, - cl::cat(KRuleCat)); + cl::cat(k_rule_cat)); -cl::opt SharedLibPath( - cl::Positional, cl::desc(""), cl::cat(KRuleCat)); +cl::opt shared_lib_path( + cl::Positional, cl::desc(""), cl::cat(k_rule_cat)); -std::optional getMatchFunctionName() { - auto definition = KompiledDir + "/definition.kore"; +std::optional get_match_function_name() { + auto definition = kompiled_dir + "/definition.kore"; // Parse the definition.kore to get the AST. - parser::KOREParser parser(definition); + parser::kore_parser parser(definition); auto kore_ast = parser.definition(); kore_ast->preprocess(); // Iterate through axioms and return the one with the give rulen label if exits. - for (auto *axiom : kore_ast.get()->getAxioms()) { + for (auto *axiom : kore_ast.get()->get_axioms()) { // Check if the current axiom has the attribute label. - if (axiom->attributes().contains(attribute_set::key::label)) { + if (axiom->attributes().contains(attribute_set::key::Label)) { // Compare the axiom's label with the given rule label. - if (RuleLabel - == axiom->attributes().get_string(attribute_set::key::label)) { - return "intern_match_" + std::to_string(axiom->getOrdinal()); + if (rule_label + == axiom->attributes().get_string(attribute_set::key::Label)) { + return "intern_match_" + std::to_string(axiom->get_ordinal()); } } } - std::cerr << RuleLabel << "\n"; + std::cerr << rule_label << "\n"; return std::nullopt; } int main(int argc, char **argv) { - cl::HideUnrelatedOptions({&KRuleCat}); + cl::HideUnrelatedOptions({&k_rule_cat}); cl::ParseCommandLineOptions(argc, argv); // Parse the given KORE Pattern and get the block* to use as input for the // match function. - parser::KOREParser parser(KOREPatternFilename.getValue()); - auto InitialConfiguration = parser.pattern(); + parser::kore_parser parser(kore_pattern_filename.getValue()); + auto initial_configuration = parser.pattern(); - auto match_function_name = getMatchFunctionName(); + auto match_function_name = get_match_function_name(); if (!match_function_name.has_value()) { - std::cerr << "Rule with label " << RuleLabel << " does not exist.\n"; + std::cerr << "Rule with label " << rule_label << " does not exist.\n"; return EXIT_FAILURE; } // Open the shared library that contains the llvm match functions. - auto *handle = dlopen(SharedLibPath.c_str(), RTLD_LAZY); + auto *handle = dlopen(shared_lib_path.c_str(), RTLD_LAZY); // Check if the shared library exits in the given location. if (!handle) { @@ -78,28 +78,30 @@ int main(int argc, char **argv) { // NOLINTNEXTLINE(*-reinterpret-cast) auto match_function = reinterpret_cast(match_function_ptr); - resetMatchReason(handle); - initStaticObjects(handle); - auto *b = constructInitialConfiguration(InitialConfiguration.get(), handle); + reset_match_reason(handle); + init_static_objects(handle); + auto *b + = construct_initial_configuration(initial_configuration.get(), handle); if (b == nullptr) { std::cerr << "Error: " << dlerror() << "\n"; return EXIT_FAILURE; } match_function((block *)b); - auto *log = getMatchLog(handle); + auto *log = getmatch_log(handle); if (log == nullptr) { std::cerr << "Error: " << dlerror() << "\n"; return EXIT_FAILURE; } - size_t logSize = getMatchLogSize(handle); - if (logSize == -1) { + size_t log_size = getmatch_log_size(handle); + if (log_size == -1) { std::cerr << "Error: " << dlerror() << "\n"; return EXIT_FAILURE; } - printMatchResult(std::cout, (MatchLog *)log, logSize, KompiledDir, handle); + print_match_result( + std::cout, (match_log *)log, log_size, kompiled_dir, handle); dlclose(handle); return 0; diff --git a/tools/k-rule-find/main.cpp b/tools/k-rule-find/main.cpp index 5f02bda35..7c741fb14 100644 --- a/tools/k-rule-find/main.cpp +++ b/tools/k-rule-find/main.cpp @@ -10,7 +10,7 @@ using namespace llvm; using namespace kllvm; -struct Location { +struct location { std::string filename; int64_t start_line; int64_t end_line; @@ -18,33 +18,33 @@ struct Location { int64_t end_column; }; -cl::OptionCategory KRuleCat("k-rule-find options"); +cl::OptionCategory k_rule_cat("k-rule-find options"); -cl::opt KompiledDir( +cl::opt kompiled_dir( cl::Positional, cl::desc(""), cl::Required, - cl::cat(KRuleCat)); + cl::cat(k_rule_cat)); -cl::opt RuleLocation( +cl::opt rule_location( cl::Positional, cl::desc(""), cl::Required, - cl::cat(KRuleCat)); + cl::cat(k_rule_cat)); -std::string getSource(KOREAxiomDeclaration *axiom) { - auto *sourceAtt = axiom->attributes().get(attribute_set::key::source).get(); - assert(sourceAtt->getArguments().size() == 1); +std::string get_source(kore_axiom_declaration *axiom) { + auto *source_att = axiom->attributes().get(attribute_set::key::Source).get(); + assert(source_att->get_arguments().size() == 1); - auto *strPattern - = dynamic_cast(sourceAtt->getArguments()[0].get()); - return strPattern->getContents(); + auto *str_pattern = dynamic_cast( + source_att->get_arguments()[0].get()); + return str_pattern->get_contents(); } -Location getLocation(KOREAxiomDeclaration *axiom) { - auto *locationAtt - = axiom->attributes().get(attribute_set::key::location).get(); - assert(locationAtt->getArguments().size() == 1); +location get_location(kore_axiom_declaration *axiom) { + auto *location_att + = axiom->attributes().get(attribute_set::key::Location).get(); + assert(location_att->get_arguments().size() == 1); - auto *strPattern - = dynamic_cast(locationAtt->getArguments()[0].get()); - std::string location = strPattern->getContents(); + auto *str_pattern = dynamic_cast( + location_att->get_arguments()[0].get()); + std::string location = str_pattern->get_contents(); size_t l_paren = location.find_first_of('('); size_t first_comma = location.find_first_of(','); @@ -65,7 +65,7 @@ Location getLocation(KOREAxiomDeclaration *axiom) { return {location, start_line, end_line, start_column, end_column}; } -Location parseLocation(std::string const &loc) { +location parse_location(std::string const &loc) { size_t pos = loc.find(':'); if (pos == std::string::npos) { std::cerr << "Rule's location must be in the format: " @@ -73,52 +73,52 @@ Location parseLocation(std::string const &loc) { exit(EXIT_FAILURE); } - std::string lineColumn = loc.substr(pos + 1); - size_t pos_lc = lineColumn.find(':'); + std::string line_column = loc.substr(pos + 1); + size_t pos_lc = line_column.find(':'); // If another “:” isn’t found, the tool assumes no column number was given. int64_t line = 0; int64_t column = -1; if (pos_lc == std::string::npos) { - line = stoi(lineColumn); + line = stoi(line_column); } else { - line = stoi(lineColumn.substr(0, pos_lc)); - column = stoi(lineColumn.substr(pos_lc + 1)); + line = stoi(line_column.substr(0, pos_lc)); + column = stoi(line_column.substr(pos_lc + 1)); } return {loc.substr(0, pos), line, line, column, column}; } -bool checkRanges( - Location const ¶m, Location const &file, bool checkColumn) { +bool check_ranges( + location const ¶m, location const &file, bool check_column) { auto line = param.start_line >= file.start_line && param.end_line <= file.end_line; auto column = param.start_column >= file.start_column && param.end_column <= file.end_column; - return checkColumn ? line && column : line; + return check_column ? line && column : line; } int main(int argc, char **argv) { - cl::HideUnrelatedOptions({&KRuleCat}); + cl::HideUnrelatedOptions({&k_rule_cat}); cl::ParseCommandLineOptions(argc, argv); - auto loc = parseLocation(RuleLocation); - auto definition = KompiledDir + "/definition.kore"; + auto loc = parse_location(rule_location); + auto definition = kompiled_dir + "/definition.kore"; std::vector rule_labels; // Parse the definition.kore to get the AST. - kllvm::parser::KOREParser parser(definition); + kllvm::parser::kore_parser parser(definition); auto kore_ast = parser.definition(); // Iterate through axioms. - for (auto *axiom : kore_ast.get()->getAxioms()) { - if (axiom->attributes().contains(attribute_set::key::source)) { - auto source = getSource(axiom); + for (auto *axiom : kore_ast.get()->get_axioms()) { + if (axiom->attributes().contains(attribute_set::key::Source)) { + auto source = get_source(axiom); if (source.find(loc.filename) != std::string::npos) { - auto source_loc = getLocation(axiom); - if (checkRanges(loc, source_loc, loc.start_column != -1)) { + auto source_loc = get_location(axiom); + if (check_ranges(loc, source_loc, loc.start_column != -1)) { rule_labels.push_back( - axiom->attributes().get_string(attribute_set::key::label)); + axiom->attributes().get_string(attribute_set::key::Label)); } } } diff --git a/tools/kore-arity/main.cpp b/tools/kore-arity/main.cpp index 3026b2f15..a55bd2898 100644 --- a/tools/kore-arity/main.cpp +++ b/tools/kore-arity/main.cpp @@ -10,17 +10,17 @@ using namespace llvm; -cl::OptionCategory KoreArityCat("kore-arity options"); +cl::OptionCategory kore_arity_cat("kore-arity options"); -cl::opt Arity( - cl::Positional, cl::desc(""), cl::Required, cl::cat(KoreArityCat)); +cl::opt arity( + cl::Positional, cl::desc(""), cl::Required, cl::cat(kore_arity_cat)); int main(int argc, char **argv) { - cl::HideUnrelatedOptions({&KoreArityCat}); + cl::HideUnrelatedOptions({&kore_arity_cat}); cl::ParseCommandLineOptions(argc, argv); - auto s = kllvm::serializer(kllvm::serializer::DROP_HEADER); - s.emit_length(Arity); + auto s = kllvm::serializer(kllvm::serializer::DropHeader); + s.emit_length(arity); for (auto b : s.data()) { std::cout << static_cast(b); diff --git a/tools/kore-convert/main.cpp b/tools/kore-convert/main.cpp index ec12d0c20..069474690 100644 --- a/tools/kore-convert/main.cpp +++ b/tools/kore-convert/main.cpp @@ -21,72 +21,74 @@ using namespace kllvm; using namespace kllvm::parser; enum kore_file_format { - detect, - text, - binary, + Detect, + Text, + Binary, }; -cl::OptionCategory KoreConvertCat("kore-convert options"); +cl::OptionCategory kore_convert_cat("kore-convert options"); -cl::opt InputFilename( +cl::opt input_filename( cl::Positional, cl::desc(""), cl::Required, - cl::cat(KoreConvertCat)); + cl::cat(kore_convert_cat)); -cl::opt InputFormat( +cl::opt input_format( "from", cl::desc("Specify input file format"), cl::values( - clEnumVal(detect, "Detect input format automatically"), - clEnumVal(text, "Textual KORE"), clEnumVal(binary, "Binary KORE")), - cl::init(detect), cl::cat(KoreConvertCat)); + clEnumValN(Detect, "detect", "Detect input format automatically"), + clEnumValN(Text, "text", "Textual KORE"), + clEnumValN(Binary, "binary", "Binary KORE")), + cl::init(Detect), cl::cat(kore_convert_cat)); -cl::opt OutputFilename( +cl::opt output_filename( "o", cl::desc("Specify output filename"), cl::value_desc("filename"), - cl::init("-"), cl::cat(KoreConvertCat)); + cl::init("-"), cl::cat(kore_convert_cat)); -cl::opt OutputFormat( +cl::opt output_format( "to", cl::desc("Specify output file format"), cl::values( - clEnumVal(detect, "Convert binary <=> text"), - clEnumVal(text, "Textual KORE"), clEnumVal(binary, "Binary KORE")), - cl::init(detect), cl::cat(KoreConvertCat)); + clEnumValN(Detect, "detect", "Convert binary <=> text"), + clEnumValN(Text, "text", "Textual KORE"), + clEnumValN(Binary, "binary", "Binary KORE")), + cl::init(Detect), cl::cat(kore_convert_cat)); -cl::opt ForceBinary( - "F", cl::desc("Force binary output on stdout"), cl::cat(KoreConvertCat)); +cl::opt force_binary( + "F", cl::desc("Force binary output on stdout"), cl::cat(kore_convert_cat)); -cl::opt NoHeader( +cl::opt no_header( "k", cl::desc( "Don't add the KORE header and version at the start of binary output"), - cl::cat(KoreConvertCat)); + cl::cat(kore_convert_cat)); -cl::opt NoArity( +cl::opt no_arity( "a", cl::desc( "Don't add the topmost constructor arity at the end of binary output"), - cl::cat(KoreConvertCat)); + cl::cat(kore_convert_cat)); -cl::opt UseSize( +cl::opt use_size( "s", cl::desc("Emit size bytes for this pattern (useful if the resulting file " "will be embedded in a larger format, but will prohibit " "concatenation of terms)"), - cl::cat(KoreConvertCat)); + cl::cat(kore_convert_cat)); -sptr get_input_pattern() { +sptr get_input_pattern() { auto get_text - = [&]() { return KOREParser(InputFilename.getValue()).pattern(); }; - auto get_binary = [&]() { return deserialize_pattern(InputFilename); }; + = [&]() { return kore_parser(input_filename.getValue()).pattern(); }; + auto get_binary = [&]() { return deserialize_pattern(input_filename); }; - switch (InputFormat) { - case text: return get_text(); - case binary: return get_binary(); + switch (input_format) { + case Text: return get_text(); + case Binary: return get_binary(); - case detect: { - if (has_binary_kore_header(InputFilename)) { - InputFormat = binary; + case Detect: { + if (has_binary_kore_header(input_filename)) { + input_format = Binary; return get_binary(); } - InputFormat = text; + input_format = Text; return get_text(); break; @@ -94,12 +96,12 @@ sptr get_input_pattern() { } } -void dump_text(sptr const &pat) { - if (OutputFilename == "-") { +void dump_text(sptr const &pat) { + if (output_filename == "-") { pat->print(std::cout); std::cout << '\n'; } else { - auto os = std::ofstream(OutputFilename); + auto os = std::ofstream(output_filename); pat->print(os); os << '\n'; } @@ -108,19 +110,19 @@ void dump_text(sptr const &pat) { serializer::flags get_flags() { auto ret = serializer::NONE; - if (NoHeader) { - ret = static_cast(ret | serializer::DROP_HEADER); + if (no_header) { + ret = static_cast(ret | serializer::DropHeader); } - if (NoArity) { - ret = static_cast(ret | serializer::DROP_ARITY); + if (no_arity) { + ret = static_cast(ret | serializer::DropArity); } return ret; } int main(int argc, char **argv) { - cl::HideUnrelatedOptions({&KoreConvertCat}); + cl::HideUnrelatedOptions({&kore_convert_cat}); cl::ParseCommandLineOptions(argc, argv); auto input = get_input_pattern(); @@ -129,38 +131,38 @@ int main(int argc, char **argv) { return 1; } - if (OutputFormat == detect) { - OutputFormat = InputFormat == text ? binary : text; + if (output_format == Detect) { + output_format = input_format == Text ? Binary : Text; } - if (OutputFormat == text && NoHeader) { + if (output_format == Text && no_header) { std::cerr << "-k only applies to binary output\n" << "use --to=binary for binary input\n"; return 2; } - if (OutputFormat == text && NoArity) { + if (output_format == Text && no_arity) { std::cerr << "-a only applies to binary output\n" << "use --to=binary for binary input\n"; return 3; } - if (OutputFormat == binary && OutputFilename == "-" && !ForceBinary) { + if (output_format == Binary && output_filename == "-" && !force_binary) { std::cerr << "Not outputting binary KORE to stdout\n" << "use -o to specify output file, or -F to force stdout\n"; return 4; } - if (OutputFormat == text) { + if (output_format == Text) { dump_text(input); return 0; } - if (OutputFormat == binary) { + if (output_format == Binary) { auto s = serializer(get_flags()); input->serialize_to(s); - if (UseSize) { + if (use_size) { s.correct_emitted_size(); } @@ -170,10 +172,10 @@ int main(int argc, char **argv) { } }; - if (OutputFilename == "-") { + if (output_filename == "-") { output(std::cout); } else { - auto os = std::ofstream(OutputFilename, std::ios::binary); + auto os = std::ofstream(output_filename, std::ios::binary); output(os); } diff --git a/tools/kore-expand-macros/main.cpp b/tools/kore-expand-macros/main.cpp index c98313a20..2dc6e9191 100644 --- a/tools/kore-expand-macros/main.cpp +++ b/tools/kore-expand-macros/main.cpp @@ -23,45 +23,45 @@ int main(int argc, char **argv) { return 1; } - KOREParser parser(argv[1] + std::string("/syntaxDefinition.kore")); - ptr def = parser.definition(); + kore_parser parser(argv[1] + std::string("/syntaxDefinition.kore")); + ptr def = parser.definition(); - auto subsorts = def->getSubsorts(); - auto overloads = def->getOverloads(); + auto subsorts = def->get_subsorts(); + auto overloads = def->get_overloads(); - KOREParser parser2(argv[1] + std::string("/macros.kore")); - std::vector> axioms = parser2.declarations(); + kore_parser parser2(argv[1] + std::string("/macros.kore")); + std::vector> axioms = parser2.declarations(); std::sort( axioms.begin(), axioms.end(), - [](ptr const &l, ptr const &r) { - std::string lStr - = l->attributes().get_string(attribute_set::key::priority); - std::string rStr - = r->attributes().get_string(attribute_set::key::priority); - int lInt = std::stoi(lStr); - int rInt = std::stoi(rStr); - return lInt < rInt; + [](ptr const &l, ptr const &r) { + std::string l_str + = l->attributes().get_string(attribute_set::key::Priority); + std::string r_str + = r->attributes().get_string(attribute_set::key::Priority); + int l_int = std::stoi(l_str); + int r_int = std::stoi(r_str); + return l_int < r_int; }); - auto config = KOREPattern::load(argv[2]); - std::map> symbols; - config->markSymbols(symbols); + auto config = kore_pattern::load(argv[2]); + std::map> symbols; + config->mark_symbols(symbols); for (auto &decl : axioms) { - auto *axiom = dynamic_cast(decl.get()); - axiom->getPattern()->markSymbols(symbols); + auto *axiom = dynamic_cast(decl.get()); + axiom->get_pattern()->mark_symbols(symbols); } for (auto &entry : symbols) { for (auto *symbol : entry.second) { - auto *decl = def->getSymbolDeclarations().at(symbol->getName()); - symbol->instantiateSymbol(decl); + auto *decl = def->get_symbol_declarations().at(symbol->get_name()); + symbol->instantiate_symbol(decl); } } auto expanded = axioms.empty() ? config - : config->expandMacros(subsorts, overloads, axioms, false); + : config->expand_macros(subsorts, overloads, axioms, false); expanded->print(std::cout); std::cout << std::endl; diff --git a/tools/kore-proof-trace-test/main.cpp b/tools/kore-proof-trace-test/main.cpp index 6ffa09c58..bdbb5408f 100644 --- a/tools/kore-proof-trace-test/main.cpp +++ b/tools/kore-proof-trace-test/main.cpp @@ -7,62 +7,62 @@ using namespace llvm; using namespace kllvm; -cl::OptionCategory KoreProofTraceTestCat("kore-proof-trace options"); +cl::OptionCategory kore_proof_trace_test_cat("kore-proof-trace options"); -cl::opt InputFilename( +cl::opt input_filename( cl::Positional, cl::desc(""), cl::Required, - cl::cat(KoreProofTraceTestCat)); + cl::cat(kore_proof_trace_test_cat)); int main(int argc, char **argv) { - cl::HideUnrelatedOptions({&KoreProofTraceTestCat}); + cl::HideUnrelatedOptions({&kore_proof_trace_test_cat}); cl::ParseCommandLineOptions(argc, argv); - ProofTraceParser Parser(false); - auto Trace = Parser.parse_proof_trace_from_file(InputFilename); - if (!Trace.has_value()) { + proof_trace_parser parser(false); + auto trace = parser.parse_proof_trace_from_file(input_filename); + if (!trace.has_value()) { return 1; } // check that there is a initial configuration - if (!(Trace->getInitialConfig().isPattern() - && Trace->getInitialConfig().getKOREPattern())) { + if (!(trace->get_initial_config().is_pattern() + && trace->get_initial_config().getkore_pattern())) { return 1; } // check that the trace after the initial configuration is 4 events long - if (Trace->getTrace().size() != 4U) { + if (trace->get_trace().size() != 4U) { return 1; } // check that the first event is the rewrite a() => b() - auto const Rule1 = std::dynamic_pointer_cast( - Trace->getTrace()[0].getStepEvent()); - if (!Rule1) { + auto const rule1 = std::dynamic_pointer_cast( + trace->get_trace()[0].get_step_event()); + if (!rule1) { return 1; } - if (Rule1->getRuleOrdinal() != 95) { + if (rule1->get_rule_ordinal() != 95) { return 1; } // check that the second event is a configuration - if (!(Trace->getTrace()[1].isPattern() - && Trace->getTrace()[1].getKOREPattern())) { + if (!(trace->get_trace()[1].is_pattern() + && trace->get_trace()[1].getkore_pattern())) { return 1; } // check that the third event is the rewrite b() => c() - auto const Rule2 = std::dynamic_pointer_cast( - Trace->getTrace()[2].getStepEvent()); - if (!Rule2) { + auto const rule2 = std::dynamic_pointer_cast( + trace->get_trace()[2].get_step_event()); + if (!rule2) { return 1; } - if (Rule2->getRuleOrdinal() != 96) { + if (rule2->get_rule_ordinal() != 96) { return 1; } // check that the fourth event is a configuration - if (!(Trace->getTrace()[3].isPattern() - && Trace->getTrace()[3].getKOREPattern())) { + if (!(trace->get_trace()[3].is_pattern() + && trace->get_trace()[3].getkore_pattern())) { return 1; } diff --git a/tools/kore-proof-trace/main.cpp b/tools/kore-proof-trace/main.cpp index d63e1b627..917778021 100644 --- a/tools/kore-proof-trace/main.cpp +++ b/tools/kore-proof-trace/main.cpp @@ -7,24 +7,24 @@ using namespace llvm; using namespace kllvm; -cl::OptionCategory KoreProofTraceCat("kore-proof-trace options"); +cl::OptionCategory kore_proof_trace_cat("kore-proof-trace options"); -cl::opt InputFilename( +cl::opt input_filename( cl::Positional, cl::desc(""), cl::Required, - cl::cat(KoreProofTraceCat)); + cl::cat(kore_proof_trace_cat)); -cl::opt VerboseOutput( +cl::opt verbose_output( "verbose", llvm::cl::desc("Print verbose information about the input proof trace"), - llvm::cl::cat(KoreProofTraceCat)); + llvm::cl::cat(kore_proof_trace_cat)); int main(int argc, char **argv) { - cl::HideUnrelatedOptions({&KoreProofTraceCat}); + cl::HideUnrelatedOptions({&kore_proof_trace_cat}); cl::ParseCommandLineOptions(argc, argv); - ProofTraceParser Parser(VerboseOutput); - auto Trace = Parser.parse_proof_trace_from_file(InputFilename); - if (Trace.has_value()) { + proof_trace_parser parser(verbose_output); + auto trace = parser.parse_proof_trace_from_file(input_filename); + if (trace.has_value()) { return 0; } diff --git a/tools/kore-split/main.cpp b/tools/kore-split/main.cpp index 8e5cb0e59..d3bb2f01e 100644 --- a/tools/kore-split/main.cpp +++ b/tools/kore-split/main.cpp @@ -16,13 +16,13 @@ int main(int argc, char **argv) { return 1; } - auto config = KOREPattern::load(argv[1]); - if (auto *composite = dynamic_cast(config.get())) { - if (composite->getConstructor()->getName() != "\\or") { + auto config = kore_pattern::load(argv[1]); + if (auto *composite = dynamic_cast(config.get())) { + if (composite->get_constructor()->get_name() != "\\or") { std::cerr << "pattern must be an \\or" << std::endl; return 1; } - std::vector> args; + std::vector> args; flatten(composite, "\\or", args); for (unsigned i = 0; i < args.size(); i++) { diff --git a/tools/kore-strip/main.cpp b/tools/kore-strip/main.cpp index 3fe41189b..1bde0ee03 100644 --- a/tools/kore-strip/main.cpp +++ b/tools/kore-strip/main.cpp @@ -16,27 +16,27 @@ using namespace llvm; -cl::OptionCategory KoreStripCat("kore-strip options"); +cl::OptionCategory kore_strip_cat("kore-strip options"); -cl::opt StripArity( +cl::opt strip_arity( "a", cl::desc( "Strip a single sequence of arity bytes from the end of the input"), - cl::cat(KoreStripCat)); + cl::cat(kore_strip_cat)); -cl::opt StripHeader( +cl::opt strip_header( "k", cl::desc("Strip the leading bytes (header, version and size for version " "1.2.0 onwards) from the input file"), - cl::cat(KoreStripCat)); + cl::cat(kore_strip_cat)); -cl::opt InputFilename( +cl::opt input_filename( "i", cl::desc("Specify input filename"), cl::value_desc("filename"), - cl::Required, cl::cat(KoreStripCat)); + cl::Required, cl::cat(kore_strip_cat)); -cl::opt OutputFilename( +cl::opt output_filename( "o", cl::desc("Specify output filename"), cl::value_desc("filename"), - cl::init("-"), cl::cat(KoreStripCat)); + cl::init("-"), cl::cat(kore_strip_cat)); std::FILE *check_fopen(char const *name, char const *mode) { auto *f = std::fopen(name, mode); @@ -51,10 +51,10 @@ std::FILE *check_fopen(char const *name, char const *mode) { } int main(int argc, char **argv) { - cl::HideUnrelatedOptions({&KoreStripCat}); + cl::HideUnrelatedOptions({&kore_strip_cat}); cl::ParseCommandLineOptions(argc, argv); - auto *input = check_fopen(InputFilename.c_str(), "rb"); + auto *input = check_fopen(input_filename.c_str(), "rb"); std::fseek(input, 0, SEEK_END); auto file_size = std::ftell(input); @@ -62,7 +62,7 @@ int main(int argc, char **argv) { auto end_skip_length = 0; auto begin_skip_length = 0; - if (StripArity) { + if (strip_arity) { std::fseek(input, file_size - 9, SEEK_SET); auto buffer = std::vector(9); auto read @@ -97,7 +97,7 @@ int main(int argc, char **argv) { } } - if (StripHeader) { + if (strip_header) { std::fseek(input, 5, SEEK_SET); auto buffer = std::vector(6); auto read @@ -126,7 +126,7 @@ int main(int argc, char **argv) { return 1; } - if (OutputFilename == "-") { + if (output_filename == "-") { std::fwrite(buffer.data(), sizeof(uint8_t), result_size, stdout); std::fclose(input); } else { @@ -136,6 +136,6 @@ int main(int argc, char **argv) { std::fwrite(buffer.data(), sizeof(uint8_t), result_size, file_pointer); std::fflush(file_pointer); - tmp_file.rename(OutputFilename); + tmp_file.rename(output_filename); } } diff --git a/tools/kprint/main.cpp b/tools/kprint/main.cpp index 7e4036e0c..379d04b46 100644 --- a/tools/kprint/main.cpp +++ b/tools/kprint/main.cpp @@ -10,36 +10,36 @@ using namespace kllvm; using namespace llvm; -cl::OptionCategory KPrintCat("kprint options"); +cl::OptionCategory k_print_cat("kprint options"); -cl::opt DefinitionFilename( +cl::opt definition_filename( cl::Positional, cl::desc(""), cl::Required, - cl::cat(KPrintCat)); + cl::cat(k_print_cat)); -cl::opt PatternFilename( +cl::opt pattern_filename( cl::Positional, cl::desc(""), cl::Required, - cl::cat(KPrintCat)); + cl::cat(k_print_cat)); -cl::opt ArgColor( +cl::opt arg_color( cl::Positional, cl::desc("[true|false|auto]"), cl::init("auto"), - cl::cat(KPrintCat)); + cl::cat(k_print_cat)); -cl::opt FilterSubst( +cl::opt filter_subst( cl::Positional, cl::desc("[true|false]"), cl::init(true), - cl::cat(KPrintCat)); + cl::cat(k_print_cat)); -cl::opt PrintAsKore( +cl::opt print_as_kore( "kore", cl::desc("Perform unparsing, but print KORE rather than surface syntax"), - cl::cat(KPrintCat)); + cl::cat(k_print_cat)); int main(int argc, char **argv) { - cl::HideUnrelatedOptions({&KPrintCat}); + cl::HideUnrelatedOptions({&k_print_cat}); cl::ParseCommandLineOptions(argc, argv); - bool has_color = ArgColor == "true" || (ArgColor == "auto" && isatty(1)); + bool has_color = arg_color == "true" || (arg_color == "auto" && isatty(1)); - printKORE( - std::cout, DefinitionFilename, PatternFilename, has_color, FilterSubst, - !PrintAsKore); + print_kore( + std::cout, definition_filename, pattern_filename, has_color, filter_subst, + !print_as_kore); } diff --git a/tools/llvm-backend-version/version.cpp b/tools/llvm-backend-version/version.cpp index 582d0f694..adc30f7b8 100644 --- a/tools/llvm-backend-version/version.cpp +++ b/tools/llvm-backend-version/version.cpp @@ -5,17 +5,17 @@ using namespace llvm; -cl::OptionCategory VersionCat("kprint options"); +cl::OptionCategory version_cat("kprint options"); -cl::opt LLVMVersion( +cl::opt llvm_library_version( "llvm", cl::desc("Print LLVM version rather than backend version"), - cl::cat(VersionCat)); + cl::cat(version_cat)); int main(int argc, char **argv) { - cl::HideUnrelatedOptions({&VersionCat}); + cl::HideUnrelatedOptions({&version_cat}); cl::ParseCommandLineOptions(argc, argv); - if (LLVMVersion) { + if (llvm_library_version) { llvm::outs() << llvm_version << '\n'; } else { llvm::outs() << llvm_backend_version << '\n'; diff --git a/tools/llvm-kompile-codegen/main.cpp b/tools/llvm-kompile-codegen/main.cpp index ee2392a53..852210e29 100644 --- a/tools/llvm-kompile-codegen/main.cpp +++ b/tools/llvm-kompile-codegen/main.cpp @@ -40,49 +40,49 @@ using namespace kllvm::parser; namespace fs = std::filesystem; -cl::OptionCategory CodegenToolCat("llvm-kompile-codegen options"); +cl::OptionCategory codegen_tool_cat("llvm-kompile-codegen options"); -cl::opt Definition( +cl::opt definition_path( cl::Positional, cl::desc(""), cl::Required, - cl::cat(CodegenToolCat)); + cl::cat(codegen_tool_cat)); -cl::opt DecisionTree( +cl::opt decision_tree( cl::Positional, cl::desc(""), cl::Required, - cl::cat(CodegenToolCat)); + cl::cat(codegen_tool_cat)); -cl::opt Directory( - cl::Positional, cl::desc(""), cl::Required, cl::cat(CodegenToolCat)); +cl::opt directory( + cl::Positional, cl::desc(""), cl::Required, cl::cat(codegen_tool_cat)); -cl::opt OutputFile( +cl::opt output_file( "output", cl::desc("Output file path"), cl::init("-"), - cl::cat(CodegenToolCat)); + cl::cat(codegen_tool_cat)); -cl::alias OutputFileAlias( - "o", cl::desc("Alias for --output"), cl::aliasopt(OutputFile), - cl::cat(CodegenToolCat)); +cl::alias output_file_alias( + "o", cl::desc("Alias for --output"), cl::aliasopt(output_file), + cl::cat(codegen_tool_cat)); -cl::opt MutableBytes( +cl::opt mutable_bytes( "mutable-bytes", cl::desc("Enable unsound reference semantics for objects of sort Bytes"), - cl::init(false), cl::cat(CodegenToolCat)); + cl::init(false), cl::cat(codegen_tool_cat)); -cl::opt SafePartial( +cl::opt safe_partial( "safe-partial", cl::desc("Do not terminate the process when a partial function is " "evaluated at an undefined input; rather throw a recoverable " "exception."), - cl::init(false), cl::cat(CodegenToolCat)); + cl::init(false), cl::cat(codegen_tool_cat)); namespace { fs::path dt_dir() { - return Directory.getValue(); + return directory.getValue(); } fs::path get_indexed_filename( std::map const &index, - KORESymbolDeclaration *decl) { - return dt_dir() / index.at(decl->getSymbol()->getName()); + kore_symbol_declaration *decl) { + return dt_dir() / index.at(decl->get_symbol()->get_name()); } std::map read_index_file() { @@ -100,15 +100,15 @@ std::map read_index_file() { template void perform_output(F &&action) { - if (OutputFile == "-") { + if (output_file == "-") { std::invoke(std::forward(action), llvm::outs()); } else { auto err = std::error_code{}; - auto os = raw_fd_ostream(OutputFile, err, sys::fs::FA_Write); + auto os = raw_fd_ostream(output_file, err, sys::fs::FA_Write); if (err) { throw std::runtime_error( - fmt::format("Error opening file {}: {}", OutputFile, err.message())); + fmt::format("Error opening file {}: {}", output_file, err.message())); } std::invoke(std::forward(action), os); @@ -124,10 +124,10 @@ void initialize_llvm() { } void emit_metadata(llvm::Module &mod) { - auto kompiled_dir = fs::absolute(Definition.getValue()).parent_path(); - addKompiledDirSymbol(mod, kompiled_dir, Debug); - addMutableBytesFlag(mod, MutableBytes, Debug); - addSafePartialFlag(mod, SafePartial, Debug); + auto kompiled_dir = fs::absolute(definition_path.getValue()).parent_path(); + add_kompiled_dir_symbol(mod, kompiled_dir, debug); + add_mutable_bytes_flag(mod, mutable_bytes, debug); + add_safe_partial_flag(mod, safe_partial, debug); } } // namespace @@ -136,100 +136,101 @@ void emit_metadata(llvm::Module &mod) { int main(int argc, char **argv) { initialize_llvm(); - cl::HideUnrelatedOptions({&CodegenToolCat, &CodegenLibCat}); + cl::HideUnrelatedOptions({&codegen_tool_cat, &codegen_lib_cat}); cl::ParseCommandLineOptions(argc, argv); - validate_codegen_args(OutputFile == "-"); + validate_codegen_args(output_file == "-"); - KOREParser parser(Definition.getValue()); - ptr definition = parser.definition(); + kore_parser parser(definition_path.getValue()); + ptr definition = parser.definition(); definition->preprocess(); - llvm::LLVMContext Context; - std::unique_ptr mod = newModule("definition", Context); + llvm::LLVMContext context; + std::unique_ptr mod = new_module("definition", context); emit_metadata(*mod); - if (Debug) { - initDebugInfo(mod.get(), Definition); + if (debug) { + init_debug_info(mod.get(), definition_path); } - for (auto *axiom : definition->getAxioms()) { - makeSideConditionFunction(axiom, definition.get(), mod.get()); - if (!axiom->isTopAxiom()) { - makeApplyRuleFunction(axiom, definition.get(), mod.get()); + for (auto *axiom : definition->get_axioms()) { + make_side_condition_function(axiom, definition.get(), mod.get()); + if (!axiom->is_top_axiom()) { + make_apply_rule_function(axiom, definition.get(), mod.get()); } else { auto dt_filename - = dt_dir() / fmt::format("dt_{}.yaml", axiom->getOrdinal()); - if (fs::exists(dt_filename) && !ProofHintInstrumentation) { - auto residuals = parseYamlSpecialDecisionTree( - mod.get(), dt_filename, definition->getAllSymbols(), - definition->getHookedSorts()); - makeApplyRuleFunction( + = dt_dir() / fmt::format("dt_{}.yaml", axiom->get_ordinal()); + if (fs::exists(dt_filename) && !proof_hint_instrumentation) { + auto residuals = parse_yaml_specialdecision_tree( + mod.get(), dt_filename, definition->get_all_symbols(), + definition->get_hooked_sorts()); + make_apply_rule_function( axiom, definition.get(), mod.get(), residuals.residuals); - makeStepFunction(axiom, definition.get(), mod.get(), residuals); + make_step_function(axiom, definition.get(), mod.get(), residuals); } else { - makeApplyRuleFunction(axiom, definition.get(), mod.get(), true); + make_apply_rule_function(axiom, definition.get(), mod.get(), true); } auto match_filename - = dt_dir() / fmt::format("match_{}.yaml", axiom->getOrdinal()); + = dt_dir() / fmt::format("match_{}.yaml", axiom->get_ordinal()); if (fs::exists(match_filename)) { - auto *dt = parseYamlDecisionTree( - mod.get(), match_filename, definition->getAllSymbols(), - definition->getHookedSorts()); - makeMatchReasonFunction(definition.get(), mod.get(), axiom, dt); + auto *dt = parse_yamldecision_tree( + mod.get(), match_filename, definition->get_all_symbols(), + definition->get_hooked_sorts()); + make_match_reason_function(definition.get(), mod.get(), axiom, dt); } } } - emitConfigParserFunctions(definition.get(), mod.get()); + emit_config_parser_functions(definition.get(), mod.get()); - auto *dt = parseYamlDecisionTree( - mod.get(), DecisionTree, definition->getAllSymbols(), - definition->getHookedSorts()); - makeStepFunction(definition.get(), mod.get(), dt, false); - auto *dtSearch = parseYamlDecisionTree( - mod.get(), dt_dir() / "dt-search.yaml", definition->getAllSymbols(), - definition->getHookedSorts()); - makeStepFunction(definition.get(), mod.get(), dtSearch, true); + auto *dt = parse_yamldecision_tree( + mod.get(), decision_tree, definition->get_all_symbols(), + definition->get_hooked_sorts()); + make_step_function(definition.get(), mod.get(), dt, false); + auto *dt_search = parse_yamldecision_tree( + mod.get(), dt_dir() / "dt-search.yaml", definition->get_all_symbols(), + definition->get_hooked_sorts()); + make_step_function(definition.get(), mod.get(), dt_search, true); auto index = read_index_file(); - for (auto const &entry : definition->getSymbols()) { + for (auto const &entry : definition->get_symbols()) { auto *symbol = entry.second; - auto *decl = definition->getSymbolDeclarations().at(symbol->getName()); - if (decl->attributes().contains(attribute_set::key::function) - && !decl->isHooked()) { + auto *decl = definition->get_symbol_declarations().at(symbol->get_name()); + if (decl->attributes().contains(attribute_set::key::Function) + && !decl->is_hooked()) { auto filename = get_indexed_filename(index, decl); - auto *funcDt = parseYamlDecisionTree( - mod.get(), filename, definition->getAllSymbols(), - definition->getHookedSorts()); - makeEvalFunction(decl->getSymbol(), definition.get(), mod.get(), funcDt); - } else if (decl->isAnywhere()) { + auto *func_dt = parse_yamldecision_tree( + mod.get(), filename, definition->get_all_symbols(), + definition->get_hooked_sorts()); + make_eval_function( + decl->get_symbol(), definition.get(), mod.get(), func_dt); + } else if (decl->is_anywhere()) { auto filename = get_indexed_filename(index, decl); - auto *funcDt = parseYamlDecisionTree( - mod.get(), filename, definition->getAllSymbols(), - definition->getHookedSorts()); + auto *func_dt = parse_yamldecision_tree( + mod.get(), filename, definition->get_all_symbols(), + definition->get_hooked_sorts()); - makeAnywhereFunction( - definition->getAllSymbols().at(ast_to_string(*decl->getSymbol())), - definition.get(), mod.get(), funcDt); + make_anywhere_function( + definition->get_all_symbols().at(ast_to_string(*decl->get_symbol())), + definition.get(), mod.get(), func_dt); } } - if (Debug) { - finalizeDebugInfo(); + if (debug) { + finalize_debug_info(); } - if (!NoOptimize) { + if (!no_optimize) { apply_kllvm_opt_passes(*mod); } perform_output([&](auto &os) { - if (EmitObject) { + if (emit_object) { generate_object_file(*mod, os); } else { - if (BinaryIR) { + if (binary_ir) { WriteBitcodeToFile(*mod, os); } else { mod->print(os, nullptr); diff --git a/tools/llvm-kompile-gc-stats/main.cpp b/tools/llvm-kompile-gc-stats/main.cpp index 114ffbe62..84086cd96 100644 --- a/tools/llvm-kompile-gc-stats/main.cpp +++ b/tools/llvm-kompile-gc-stats/main.cpp @@ -43,12 +43,12 @@ int main(int argc, char **argv) { mpz_init(i); } } - int lowerBound = 0; - int upperBound = 0; + int lower_bound = 0; + int upper_bound = 0; mpz_t size; if (generation) { - lowerBound = atoi(argv[3]); - upperBound = atoi(argv[4]); + lower_bound = atoi(argv[3]); + upper_bound = atoi(argv[4]); mpz_init(size); } while (true) { @@ -83,7 +83,7 @@ int main(int argc, char **argv) { } } else if (generation) { mpz_set_ui(size, 0); - for (int i = lowerBound; i <= upperBound; i++) { + for (int i = lower_bound; i <= upper_bound; i++) { if (i == 0) { mpz_add_ui(size, size, frame[0]); mpz_sub_ui(size, size, frame[1]); diff --git a/unittests/compiler/asttest.cpp b/unittests/compiler/asttest.cpp index 19099b3fb..fd5df869b 100644 --- a/unittests/compiler/asttest.cpp +++ b/unittests/compiler/asttest.cpp @@ -7,38 +7,38 @@ using namespace kllvm; BOOST_AUTO_TEST_SUITE(ASTTest) BOOST_AUTO_TEST_CASE(substitute) { - KORESort::substitution subst; - auto var = KORESortVariable::Create("foo"); - auto composite = KORECompositeSort::Create("bar"); - auto poly = KORECompositeSort::Create("baz"); - poly->addArgument(var); + kore_sort::substitution subst; + auto var = kore_sort_variable::create("foo"); + auto composite = kore_composite_sort::create("bar"); + auto poly = kore_composite_sort::create("baz"); + poly->add_argument(var); subst[*var] = composite; BOOST_CHECK_EQUAL(var->substitute(subst), composite); BOOST_CHECK_EQUAL(composite->substitute(subst), composite); - auto expected = KORECompositeSort::Create("baz"); - expected->addArgument(composite); + auto expected = kore_composite_sort::create("baz"); + expected->add_argument(composite); BOOST_CHECK_EQUAL(*poly->substitute(subst), *expected); } BOOST_AUTO_TEST_CASE(instantiate) { - auto decl = KORESymbolDeclaration::Create("sym"); - auto var = KORESortVariable::Create("foo"); - decl->addObjectSortVariable(var); - auto poly = KORECompositeSort::Create("baz"); - auto composite = KORECompositeSort::Create("bar"); - poly->addArgument(var); - decl->getSymbol()->addArgument(poly); - decl->getSymbol()->addArgument(composite); - decl->getSymbol()->addSort(poly); - auto sym = KORESymbol::Create("sym"); - sym->addFormalArgument(composite); - sym->instantiateSymbol(decl.get()); - auto expected = KORECompositeSort::Create("baz"); - expected->addArgument(composite); - BOOST_CHECK_EQUAL(*sym->getSort(), *expected); - BOOST_CHECK_EQUAL(sym->getArguments().size(), 2); - BOOST_CHECK_EQUAL(*sym->getArguments()[0], *expected); - BOOST_CHECK_EQUAL(*sym->getArguments()[1], *composite); + auto decl = kore_symbol_declaration::create("sym"); + auto var = kore_sort_variable::create("foo"); + decl->add_object_sort_variable(var); + auto poly = kore_composite_sort::create("baz"); + auto composite = kore_composite_sort::create("bar"); + poly->add_argument(var); + decl->get_symbol()->add_argument(poly); + decl->get_symbol()->add_argument(composite); + decl->get_symbol()->add_sort(poly); + auto sym = kore_symbol::create("sym"); + sym->add_formal_argument(composite); + sym->instantiate_symbol(decl.get()); + auto expected = kore_composite_sort::create("baz"); + expected->add_argument(composite); + BOOST_CHECK_EQUAL(*sym->get_sort(), *expected); + BOOST_CHECK_EQUAL(sym->get_arguments().size(), 2); + BOOST_CHECK_EQUAL(*sym->get_arguments()[0], *expected); + BOOST_CHECK_EQUAL(*sym->get_arguments()[1], *composite); } BOOST_AUTO_TEST_SUITE_END() diff --git a/unittests/compiler/pattern_matching.cpp b/unittests/compiler/pattern_matching.cpp index 13c967566..fc8573086 100644 --- a/unittests/compiler/pattern_matching.cpp +++ b/unittests/compiler/pattern_matching.cpp @@ -6,10 +6,11 @@ using namespace kllvm; using namespace kllvm::pattern_matching; template -std::shared_ptr +std::shared_ptr term(std::string const &s, Args &&...args) { - std::shared_ptr ret = KORECompositePattern::Create(s); - (ret->addArgument(std::forward(args)), ...); + std::shared_ptr ret + = kore_composite_pattern::create(s); + (ret->add_argument(std::forward(args)), ...); return ret; } @@ -87,9 +88,9 @@ BOOST_AUTO_TEST_CASE(literals) { } static std::optional -get_name(std::shared_ptr const &term) { - if (auto comp = std::dynamic_pointer_cast(term)) { - return comp->getConstructor()->getName(); +get_name(std::shared_ptr const &term) { + if (auto comp = std::dynamic_pointer_cast(term)) { + return comp->get_constructor()->get_name(); } return std::nullopt; diff --git a/unittests/runtime-arithmetic/inttest.cpp b/unittests/runtime-arithmetic/inttest.cpp index b76b0233b..fc9022fa3 100644 --- a/unittests/runtime-arithmetic/inttest.cpp +++ b/unittests/runtime-arithmetic/inttest.cpp @@ -5,7 +5,7 @@ extern "C" { -void *koreAllocToken(size_t requested) { +void *kore_alloc_token(size_t requested) { return malloc(requested); } size_t const BLOCK_SIZE = -1; @@ -49,11 +49,11 @@ mpz_ptr move_int(mpz_t i) { void add_hash64(void *, uint64_t) { } -uint32_t getTagForSymbolName(char const *) { +uint32_t get_tag_for_symbol_name(char const *) { return 0; } -void *koreAllocAlwaysGC(size_t size) { +void *kore_alloc_always_gc(size_t size) { return malloc(size); } } diff --git a/unittests/runtime-collections/lists.cpp b/unittests/runtime-collections/lists.cpp index acd0cb2cc..ab9ea550e 100644 --- a/unittests/runtime-collections/lists.cpp +++ b/unittests/runtime-collections/lists.cpp @@ -28,16 +28,16 @@ bool during_gc() { return false; } -void *koreAllocToken(size_t requested) { +void *kore_alloc_token(size_t requested) { return malloc(requested); } size_t const BLOCK_SIZE = -1; -char const **getArgumentSortsForTag(uint32_t tag) { +char const **get_argument_sorts_for_tag(uint32_t tag) { return nullptr; } -void printConfigurationInternal( +void print_configuration_internal( writer *file, block *subject, char const *sort, bool, void *) { } SortStringBuffer diff --git a/unittests/runtime-collections/rangemap-hooks.cpp b/unittests/runtime-collections/rangemap-hooks.cpp index d8a90e69b..23a210588 100644 --- a/unittests/runtime-collections/rangemap-hooks.cpp +++ b/unittests/runtime-collections/rangemap-hooks.cpp @@ -47,15 +47,15 @@ bool hook_KEQUAL_lt(block *b1, block *b2) { return b1->h.hdr < b2->h.hdr; } -void *koreAlloc(size_t requested) { +void *kore_alloc(size_t requested) { return malloc(requested); } -uint32_t getTagForSymbolName(char const *symbolName) { +uint32_t get_tag_for_symbol_name(char const *symbolName) { return 0; } -struct blockheader getBlockHeaderForSymbol(uint32_t tag) { +struct blockheader get_block_header_for_symbol(uint32_t tag) { return {(uint64_t)tag}; } @@ -67,8 +67,8 @@ struct range { static struct blockheader range_header() { static struct blockheader hdr = {(uint64_t)-1}; if (hdr.hdr == -1) { - hdr = getBlockHeaderForSymbol( - (uint64_t)getTagForSymbolName("LblRangemap'Coln'Range{}")); + hdr = get_block_header_for_symbol( + (uint64_t)get_tag_for_symbol_name("LblRangemap'Coln'Range{}")); } return hdr; } @@ -79,8 +79,8 @@ struct inj_range2kitem { static struct blockheader inj_range2kitem_header() { static struct blockheader hdr = {(uint64_t)-1}; if (hdr.hdr == -1) { - hdr = getBlockHeaderForSymbol( - (uint64_t)getTagForSymbolName("inj{SortRange{}, SortKItem{}}")); + hdr = get_block_header_for_symbol( + (uint64_t)get_tag_for_symbol_name("inj{SortRange{}, SortKItem{}}")); } return hdr; } @@ -97,7 +97,7 @@ BOOST_AUTO_TEST_CASE(rangemap_hook_element) { } BOOST_AUTO_TEST_CASE(rangemap_hook_element_rng) { - range *ptr = (range *)koreAlloc(sizeof(range)); + range *ptr = (range *)kore_alloc(sizeof(range)); ptr->h = range_header(); ptr->start = RDUMMY0; ptr->end = RDUMMY1; @@ -162,7 +162,7 @@ BOOST_AUTO_TEST_CASE(rangemap_hook_update_rng) { BOOST_CHECK_EQUAL(result, RDUMMY0); auto result2 = hook_RANGEMAP_size_long(&map1); BOOST_CHECK_EQUAL(result2, 1); - range *ptr = (range *)koreAlloc(sizeof(range)); + range *ptr = (range *)kore_alloc(sizeof(range)); ptr->h = range_header(); ptr->start = RDUMMY0; ptr->end = RDUMMY1; @@ -187,7 +187,7 @@ BOOST_AUTO_TEST_CASE(rangemap_hook_remove_rng) { auto map1 = hook_RANGEMAP_update(&m1, RDUMMY0, RDUMMY1, RDUMMY1); auto result = hook_RANGEMAP_size_long(&map1); BOOST_CHECK_EQUAL(result, 2); - range *ptr = (range *)koreAlloc(sizeof(range)); + range *ptr = (range *)kore_alloc(sizeof(range)); ptr->h = range_header(); ptr->start = RDUMMY0; ptr->end = RDUMMY1; @@ -292,12 +292,12 @@ BOOST_AUTO_TEST_CASE(rangemap_hook_remove_all) { auto map2 = hook_RANGEMAP_removeAll(&map1, &set); auto result = hook_RANGEMAP_size_long(&map2); BOOST_CHECK_EQUAL(result, 1); - range *ptr = (range *)koreAlloc(sizeof(range)); + range *ptr = (range *)kore_alloc(sizeof(range)); ptr->h = range_header(); ptr->start = RDUMMY0; ptr->end = RDUMMY1; inj_range2kitem *inj_ptr - = (inj_range2kitem *)koreAlloc(sizeof(inj_range2kitem)); + = (inj_range2kitem *)kore_alloc(sizeof(inj_range2kitem)); inj_ptr->h = inj_range2kitem_header(); inj_ptr->child = ptr; auto elem = hook_SET_element((SortKItem)inj_ptr); diff --git a/unittests/runtime-collections/treemaps.cpp b/unittests/runtime-collections/treemaps.cpp index 1592afa5e..1da5c129f 100644 --- a/unittests/runtime-collections/treemaps.cpp +++ b/unittests/runtime-collections/treemaps.cpp @@ -6,7 +6,7 @@ #include #include -void hugeTest(std::vector &v) { +void huge_test(std::vector &v) { std::vector> trees; trees.push_back(rb_tree::RBTree()); for (int i : v) { @@ -47,7 +47,7 @@ void hugeTest(std::vector &v) { trees[0].assert_BST_invariant(); } -void makeTestVectors( +void make_test_vectors( int n, std::vector &asc, std::vector &desc, std::vector &rnd) { asc.clear(); @@ -65,10 +65,10 @@ BOOST_AUTO_TEST_SUITE(TreeMapTest) BOOST_AUTO_TEST_CASE(hugetest) { std::vector a, d, r; - makeTestVectors(500, a, d, r); - hugeTest(a); - hugeTest(d); - hugeTest(r); + make_test_vectors(500, a, d, r); + huge_test(a); + huge_test(d); + huge_test(r); } BOOST_AUTO_TEST_CASE(treemap_test_element) { diff --git a/unittests/runtime-ffi/ffi.cpp b/unittests/runtime-ffi/ffi.cpp index 2f4c0a7fb..5b6cbcf8f 100644 --- a/unittests/runtime-ffi/ffi.cpp +++ b/unittests/runtime-ffi/ffi.cpp @@ -14,7 +14,8 @@ #define KCHAR char #define TYPETAG(type) "Lbl'Hash'ffi'Unds'" #type "{}" -void *constructCompositePattern(uint32_t tag, std::vector &arguments) { +void * +construct_composite_pattern(uint32_t tag, std::vector &arguments) { return nullptr; } @@ -40,16 +41,16 @@ char const *symbols[NUM_SYMBOLS] "inj{SortBytes{}, SortKItem{}}", "inj{SortFFIType{}, SortKItem{}}"}; -char const **getArgumentSortsForTag(uint32_t tag) { +char const **get_argument_sorts_for_tag(uint32_t tag) { return nullptr; } -uint32_t const first_inj_tag = 4; -uint32_t const last_inj_tag = 5; +uint32_t const FIRST_INJ_TAG = 4; +uint32_t const LAST_INJ_TAG = 5; -char *getTerminatedString(string *str); +char *get_terminated_string(string *str); -uint32_t getTagForSymbolName(char const *s) { +uint32_t get_tag_for_symbol_name(char const *s) { for (int i = 0; i < NUM_SYMBOLS; i++) { if (0 == strcmp(symbols[i], s)) { return i + 1; @@ -59,7 +60,7 @@ uint32_t getTagForSymbolName(char const *s) { return 0; } -struct blockheader getBlockHeaderForSymbol(uint32_t tag) { +struct blockheader get_block_header_for_symbol(uint32_t tag) { return blockheader{tag}; } @@ -81,7 +82,7 @@ bool during_gc() { return false; } -void printConfigurationInternal( +void print_configuration_internal( writer *file, block *subject, char const *sort, bool, void *) { } void sfprintf(writer *, char const *, ...) { } @@ -101,7 +102,7 @@ block *hook_FFI_bytes_ref(string *bytes); string *hook_FFI_alloc(block *kitem, mpz_t size, mpz_t align); bool hook_FFI_allocated(block *kitem); -string *makeString(const KCHAR *, int64_t len = -1); +string *make_string(const KCHAR *, int64_t len = -1); list hook_LIST_element(block *value); list hook_LIST_concat(list *l1, list *l2); @@ -125,66 +126,66 @@ block D1 = {{1}}; block *DUMMY1 = &D1; } -struct FfiTestFixture { +struct ffi_test_fixture { - ~FfiTestFixture() { hook_FFI_freeAll(); } + ~ffi_test_fixture() { hook_FFI_freeAll(); } }; -BOOST_FIXTURE_TEST_SUITE(FfiTest, FfiTestFixture) +BOOST_FIXTURE_TEST_SUITE(FfiTest, ffi_test_fixture) BOOST_AUTO_TEST_CASE(address) { - string *fn = makeString("timesTwo"); + string *fn = make_string("times_two"); mpz_ptr addr = hook_FFI_address(fn); BOOST_CHECK(0 < mpz_cmp_ui(addr, 0)); - fn = makeString("utimesTwo"); + fn = make_string("utimes_two"); addr = hook_FFI_address(fn); BOOST_CHECK(0 < mpz_cmp_ui(addr, 0)); - fn = makeString("times"); + fn = make_string("times"); addr = hook_FFI_address(fn); BOOST_CHECK(0 < mpz_cmp_ui(addr, 0)); - fn = makeString("getX"); + fn = make_string("get_x"); addr = hook_FFI_address(fn); BOOST_CHECK(0 < mpz_cmp_ui(addr, 0)); - fn = makeString("increaseX"); + fn = make_string("increase_x"); addr = hook_FFI_address(fn); BOOST_CHECK(0 < mpz_cmp_ui(addr, 0)); - fn = makeString("timesPoint"); + fn = make_string("times_point"); addr = hook_FFI_address(fn); BOOST_CHECK(0 < mpz_cmp_ui(addr, 0)); - fn = makeString("fakeFunction"); + fn = make_string("fake_function"); addr = hook_FFI_address(fn); BOOST_CHECK_EQUAL(0, mpz_cmp_ui(addr, 0)); } BOOST_AUTO_TEST_CASE(call) { - /* int timesTwo(int x) */ + /* int times_two(int x) */ int x = -3; - string *xargstr = makeString((char *)&x, sizeof(int)); + string *xargstr = make_string((char *)&x, sizeof(int)); block *xarg - = static_cast(koreAlloc(sizeof(block) + sizeof(string *))); - xarg->h = getBlockHeaderForSymbol( - (uint64_t)getTagForSymbolName("inj{SortBytes{}, SortKItem{}}")); + = static_cast(kore_alloc(sizeof(block) + sizeof(string *))); + xarg->h = get_block_header_for_symbol( + (uint64_t)get_tag_for_symbol_name("inj{SortBytes{}, SortKItem{}}")); memcpy(xarg->children, &xargstr, sizeof(string *)); list args = hook_LIST_element(xarg); - block *type_sint = leaf_block(getTagForSymbolName(TYPETAG(sint))); + block *type_sint = leaf_block(get_tag_for_symbol_name(TYPETAG(sint))); block *argtype - = static_cast(koreAlloc(sizeof(block) + sizeof(block *))); - argtype->h = getBlockHeaderForSymbol( - (uint64_t)getTagForSymbolName("inj{SortFFIType{}, SortKItem{}}")); + = static_cast(kore_alloc(sizeof(block) + sizeof(block *))); + argtype->h = get_block_header_for_symbol( + (uint64_t)get_tag_for_symbol_name("inj{SortFFIType{}, SortKItem{}}")); memcpy(argtype->children, &type_sint, sizeof(block *)); list types = hook_LIST_element(argtype); - string *fn = makeString("timesTwo"); + string *fn = make_string("times_two"); mpz_ptr addr = hook_FFI_address(fn); string *bytes = hook_FFI_call(addr, &args, &types, type_sint); @@ -195,19 +196,19 @@ BOOST_AUTO_TEST_CASE(call) { BOOST_CHECK_EQUAL(ret, x * 2); - /* unsigned int utimesTwo(unsigned int x) */ + /* unsigned int utimes_two(unsigned int x) */ x = 4; - xargstr = makeString((char *)&x, sizeof(int)); + xargstr = make_string((char *)&x, sizeof(int)); memcpy(xarg->children, &xargstr, sizeof(string *)); args = hook_LIST_element(xarg); - block *type_uint = leaf_block(getTagForSymbolName(TYPETAG(uint))); + block *type_uint = leaf_block(get_tag_for_symbol_name(TYPETAG(uint))); memcpy(argtype->children, &type_uint, sizeof(block *)); types = hook_LIST_element(argtype); - fn = makeString("utimesTwo"); + fn = make_string("utimes_two"); addr = hook_FFI_address(fn); bytes = hook_FFI_call(addr, &args, &types, type_uint); @@ -220,14 +221,14 @@ BOOST_AUTO_TEST_CASE(call) { /* int times(int x, int y) */ int y = 4; - string *yargstr = makeString((char *)&y, sizeof(int)); + string *yargstr = make_string((char *)&y, sizeof(int)); memcpy(argtype->children, &type_sint, sizeof(block *)); block *yarg - = static_cast(koreAlloc(sizeof(block) + sizeof(string *))); - yarg->h = getBlockHeaderForSymbol( - (uint64_t)getTagForSymbolName("inj{SortBytes{}, SortKItem{}}")); + = static_cast(kore_alloc(sizeof(block) + sizeof(string *))); + yarg->h = get_block_header_for_symbol( + (uint64_t)get_tag_for_symbol_name("inj{SortBytes{}, SortKItem{}}")); memcpy(yarg->children, &yargstr, sizeof(string *)); list yargs = hook_LIST_element(yarg); @@ -235,27 +236,27 @@ BOOST_AUTO_TEST_CASE(call) { args = hook_LIST_concat(&args, &yargs); types = hook_LIST_concat(&types, &types); - fn = makeString("times"); + fn = make_string("times"); addr = hook_FFI_address(fn); bytes = hook_FFI_call(addr, &args, &types, type_sint); ret = *(int *)bytes->data; BOOST_CHECK_EQUAL(ret, x * y); - /* struct point constructPoint(int x, int y) */ + /* struct point construct_point(int x, int y) */ block *structType - = static_cast(koreAlloc(sizeof(block) + sizeof(block *))); - structType->h - = getBlockHeaderForSymbol((uint64_t)getTagForSymbolName(TYPETAG(struct))); + = static_cast(kore_alloc(sizeof(block) + sizeof(block *))); + structType->h = get_block_header_for_symbol( + (uint64_t)get_tag_for_symbol_name(TYPETAG(struct))); - list *structFields = static_cast(koreAlloc(sizeof(list))); + list *structFields = static_cast(kore_alloc(sizeof(list))); list tmp = hook_LIST_element(argtype); tmp = hook_LIST_concat(&tmp, &tmp); memcpy(structFields, &tmp, sizeof(list)); memcpy(structType->children, &structFields, sizeof(list *)); - fn = makeString("constructPoint"); + fn = make_string("construct_point"); addr = hook_FFI_address(fn); bytes = hook_FFI_call(addr, &args, &types, structType); @@ -263,21 +264,21 @@ BOOST_AUTO_TEST_CASE(call) { BOOST_CHECK_EQUAL(p.x, x); BOOST_CHECK_EQUAL(p.y, y); - /* int getX(void) */ - fn = makeString("getX"); + /* int get_x(void) */ + fn = make_string("get_x"); addr = hook_FFI_address(fn); bytes = hook_FFI_call(addr, &args, &types, type_sint); ret = *(int *)bytes->data; BOOST_CHECK_EQUAL(ret, 1); - /* void increaseX(void) */ - fn = makeString("increaseX"); + /* void increase_x(void) */ + fn = make_string("increase_x"); addr = hook_FFI_address(fn); bytes = hook_FFI_call(addr, &args, &types, type_sint); - /* int getX(void) */ - fn = makeString("getX"); + /* int get_x(void) */ + fn = make_string("get_x"); addr = hook_FFI_address(fn); bytes = hook_FFI_call(addr, &args, &types, type_sint); ret = *(int *)bytes->data; @@ -291,24 +292,24 @@ BOOST_AUTO_TEST_CASE(call) { * * int timesPoint(struct point p) */ p = {.x = 2, .y = 5}; - string *pargstr = makeString((char *)&p, sizeof(struct point)); + string *pargstr = make_string((char *)&p, sizeof(struct point)); block *parg - = static_cast(koreAlloc(sizeof(block) + sizeof(string *))); - parg->h = getBlockHeaderForSymbol( - (uint64_t)getTagForSymbolName("inj{SortBytes{}, SortKItem{}}")); + = static_cast(kore_alloc(sizeof(block) + sizeof(string *))); + parg->h = get_block_header_for_symbol( + (uint64_t)get_tag_for_symbol_name("inj{SortBytes{}, SortKItem{}}")); memcpy(parg->children, &pargstr, sizeof(string *)); args = hook_LIST_element(parg); block *new_argtype - = static_cast(koreAlloc(sizeof(block) + sizeof(block *))); - new_argtype->h = getBlockHeaderForSymbol( - (uint64_t)getTagForSymbolName("inj{SortFFIType{}, SortKItem{}}")); + = static_cast(kore_alloc(sizeof(block) + sizeof(block *))); + new_argtype->h = get_block_header_for_symbol( + (uint64_t)get_tag_for_symbol_name("inj{SortFFIType{}, SortKItem{}}")); memcpy(new_argtype->children, &structType, sizeof(block *)); types = hook_LIST_element(new_argtype); - fn = makeString("timesPoint"); + fn = make_string("times_point"); addr = hook_FFI_address(fn); bytes = hook_FFI_call(addr, &args, &types, type_sint); @@ -322,24 +323,24 @@ BOOST_AUTO_TEST_CASE(call) { * * int timesPoint2(struct point2 p) */ struct point2 p2 = {.p = p}; - string *pargstr2 = makeString((char *)&p2, sizeof(struct point2)); + string *pargstr2 = make_string((char *)&p2, sizeof(struct point2)); memcpy(parg->children, &pargstr2, sizeof(string *)); args = hook_LIST_element(parg); block *structType2 - = static_cast(koreAlloc(sizeof(block) + sizeof(block *))); - structType2->h - = getBlockHeaderForSymbol((uint64_t)getTagForSymbolName(TYPETAG(struct))); + = static_cast(kore_alloc(sizeof(block) + sizeof(block *))); + structType2->h = get_block_header_for_symbol( + (uint64_t)get_tag_for_symbol_name(TYPETAG(struct))); block *structArgType - = static_cast(koreAlloc(sizeof(block) + sizeof(block *))); - structArgType->h = getBlockHeaderForSymbol( - (uint64_t)getTagForSymbolName("inj{SortFFIType{}, SortKItem{}}")); + = static_cast(kore_alloc(sizeof(block) + sizeof(block *))); + structArgType->h = get_block_header_for_symbol( + (uint64_t)get_tag_for_symbol_name("inj{SortFFIType{}, SortKItem{}}")); memcpy(structArgType->children, &structType, sizeof(block *)); - list *structFields2 = static_cast(koreAlloc(sizeof(list))); + list *structFields2 = static_cast(kore_alloc(sizeof(list))); list tmp2 = hook_LIST_element(structArgType); memcpy(structFields2, &tmp2, sizeof(list)); @@ -348,7 +349,7 @@ BOOST_AUTO_TEST_CASE(call) { memcpy(new_argtype->children, &structType2, sizeof(block *)); types = hook_LIST_element(new_argtype); - fn = makeString("timesPoint2"); + fn = make_string("times_point2"); addr = hook_FFI_address(fn); bytes = hook_FFI_call(addr, &args, &types, type_sint); @@ -373,22 +374,22 @@ BOOST_AUTO_TEST_CASE(call) { mpz_ptr addr1 = hook_FFI_bytes_address(b1); uintptr_t address1 = mpz_get_ui(addr1); - string *ptrargstr = makeString((char *)&address1, sizeof(uintptr_t *)); + string *ptrargstr = make_string((char *)&address1, sizeof(uintptr_t *)); block *ptrarg - = static_cast(koreAlloc(sizeof(block) + sizeof(string *))); - ptrarg->h = getBlockHeaderForSymbol( - (uint64_t)getTagForSymbolName("inj{SortBytes{}, SortKItem{}}")); + = static_cast(kore_alloc(sizeof(block) + sizeof(string *))); + ptrarg->h = get_block_header_for_symbol( + (uint64_t)get_tag_for_symbol_name("inj{SortBytes{}, SortKItem{}}")); memcpy(ptrarg->children, &ptrargstr, sizeof(string *)); args = hook_LIST_element(ptrarg); - block *type_pointer = leaf_block(getTagForSymbolName(TYPETAG(pointer))); + block *type_pointer = leaf_block(get_tag_for_symbol_name(TYPETAG(pointer))); memcpy(argtype->children, &type_pointer, sizeof(block *)); types = hook_LIST_element(argtype); - fn = makeString("pointerTest"); + fn = make_string("pointer_test"); addr = hook_FFI_address(fn); bytes = hook_FFI_call(addr, &args, &types, type_sint); @@ -405,47 +406,47 @@ BOOST_AUTO_TEST_CASE(call) { BOOST_AUTO_TEST_CASE(call_variadic) { /* int addInts(int x, ...) */ int n = 1; - string *nargstr = makeString((char *)&n, sizeof(int)); + string *nargstr = make_string((char *)&n, sizeof(int)); block *narg - = static_cast(koreAlloc(sizeof(block) + sizeof(string *))); - narg->h = getBlockHeaderForSymbol( - (uint64_t)getTagForSymbolName("inj{SortBytes{}, SortKItem{}}")); + = static_cast(kore_alloc(sizeof(block) + sizeof(string *))); + narg->h = get_block_header_for_symbol( + (uint64_t)get_tag_for_symbol_name("inj{SortBytes{}, SortKItem{}}")); memcpy(narg->children, &nargstr, sizeof(string *)); list args = hook_LIST_element(narg); int arg1 = 1; - string *arg1str = makeString((char *)&arg1, sizeof(int)); + string *arg1str = make_string((char *)&arg1, sizeof(int)); block *arg1block - = static_cast(koreAlloc(sizeof(block) + sizeof(string *))); - arg1block->h = getBlockHeaderForSymbol( - (uint64_t)getTagForSymbolName("inj{SortBytes{}, SortKItem{}}")); + = static_cast(kore_alloc(sizeof(block) + sizeof(string *))); + arg1block->h = get_block_header_for_symbol( + (uint64_t)get_tag_for_symbol_name("inj{SortBytes{}, SortKItem{}}")); memcpy(arg1block->children, &arg1str, sizeof(string *)); list arg1list = hook_LIST_element(arg1block); args = hook_LIST_concat(&args, &arg1list); - block *type_sint = leaf_block(getTagForSymbolName(TYPETAG(sint))); + block *type_sint = leaf_block(get_tag_for_symbol_name(TYPETAG(sint))); block *fixargtype - = static_cast(koreAlloc(sizeof(block) + sizeof(block *))); - fixargtype->h = getBlockHeaderForSymbol( - (uint64_t)getTagForSymbolName("inj{SortFFIType{}, SortKItem{}}")); + = static_cast(kore_alloc(sizeof(block) + sizeof(block *))); + fixargtype->h = get_block_header_for_symbol( + (uint64_t)get_tag_for_symbol_name("inj{SortFFIType{}, SortKItem{}}")); memcpy(fixargtype->children, &type_sint, sizeof(block *)); block *varargtype - = static_cast(koreAlloc(sizeof(block) + sizeof(block *))); - varargtype->h = getBlockHeaderForSymbol( - (uint64_t)getTagForSymbolName("inj{SortFFIType{}, SortKItem{}}")); + = static_cast(kore_alloc(sizeof(block) + sizeof(block *))); + varargtype->h = get_block_header_for_symbol( + (uint64_t)get_tag_for_symbol_name("inj{SortFFIType{}, SortKItem{}}")); memcpy(varargtype->children, &type_sint, sizeof(block *)); list fixtypes = hook_LIST_element(fixargtype); list vartypes = hook_LIST_element(varargtype); - string *fn = makeString("addInts"); + string *fn = make_string("add_ints"); mpz_ptr addr = hook_FFI_address(fn); string *bytes @@ -459,23 +460,23 @@ BOOST_AUTO_TEST_CASE(call_variadic) { /* addInts with 2 var args */ n = 2; - nargstr = makeString((char *)&n, sizeof(int)); + nargstr = make_string((char *)&n, sizeof(int)); memcpy(narg->children, &nargstr, sizeof(string *)); args = hook_LIST_element(narg); arg1 = 20; - arg1str = makeString((char *)&arg1, sizeof(int)); + arg1str = make_string((char *)&arg1, sizeof(int)); memcpy(arg1block->children, &arg1str, sizeof(string *)); arg1list = hook_LIST_element(arg1block); args = hook_LIST_concat(&args, &arg1list); int arg2 = 15; - string *arg2str = makeString((char *)&arg2, sizeof(int)); + string *arg2str = make_string((char *)&arg2, sizeof(int)); block *arg2block - = static_cast(koreAlloc(sizeof(block) + sizeof(string *))); - arg2block->h = getBlockHeaderForSymbol( - (uint64_t)getTagForSymbolName("inj{SortBytes{}, SortKItem{}}")); + = static_cast(kore_alloc(sizeof(block) + sizeof(string *))); + arg2block->h = get_block_header_for_symbol( + (uint64_t)get_tag_for_symbol_name("inj{SortBytes{}, SortKItem{}}")); memcpy(arg2block->children, &arg2str, sizeof(string *)); list arg2list = hook_LIST_element(arg2block); @@ -495,7 +496,7 @@ BOOST_AUTO_TEST_CASE(call_variadic) { /* addInts with 0 var args */ n = 0; - nargstr = makeString((char *)&n, sizeof(int)); + nargstr = make_string((char *)&n, sizeof(int)); memcpy(narg->children, &nargstr, sizeof(string *)); args = hook_LIST_element(narg); diff --git a/unittests/runtime-ffi/lib/foreign.cpp b/unittests/runtime-ffi/lib/foreign.cpp index 1ed99d402..35e4f90e4 100644 --- a/unittests/runtime-ffi/lib/foreign.cpp +++ b/unittests/runtime-ffi/lib/foreign.cpp @@ -12,11 +12,11 @@ struct point2 { int x = 1; -int timesTwo(int x) { +int times_two(int x) { return x * 2; } -unsigned int utimesTwo(unsigned int x) { +unsigned int utimes_two(unsigned int x) { return x * 2; } @@ -24,27 +24,27 @@ int times(int x, int y) { return x * y; } -int getX(void) { +int get_x(void) { return x; } -void increaseX(void) { +void increase_x(void) { x++; } -int timesPoint(struct point p) { +int times_point(struct point p) { return p.x * p.y; } -int timesPoint2(struct point2 p) { +int times_point2(struct point2 p) { return p.p.x * p.p.y; } -struct point constructPoint(int x, int y) { +struct point construct_point(int x, int y) { return {.x = x, .y = y}; } -int addInts(int n, ...) { +int add_ints(int n, ...) { int sum = 0; va_list vl; va_start(vl, n); @@ -58,7 +58,7 @@ int addInts(int n, ...) { return sum; } -int pointerTest(int *x) { +int pointer_test(int *x) { return x == 0 ? 0 : *x; } } diff --git a/unittests/runtime-io/io.cpp b/unittests/runtime-io/io.cpp index 2051c14d0..a04a9682e 100644 --- a/unittests/runtime-io/io.cpp +++ b/unittests/runtime-io/io.cpp @@ -14,7 +14,8 @@ #define KCHAR char -void *constructCompositePattern(uint32_t tag, std::vector &arguments) { +void * +construct_composite_pattern(uint32_t tag, std::vector &arguments) { return nullptr; } @@ -36,10 +37,10 @@ char const *symbols[NUM_SYMBOLS] "kseq{}", GETTAG(systemResult)}; -uint32_t const first_inj_tag = 3; -uint32_t const last_inj_tag = 5; +uint32_t const FIRST_INJ_TAG = 3; +uint32_t const LAST_INJ_TAG = 5; -uint32_t getTagForSymbolName(char const *s) { +uint32_t get_tag_for_symbol_name(char const *s) { for (int i = 0; i < NUM_SYMBOLS; i++) { if (0 == strcmp(symbols[i], s)) { return i; @@ -49,7 +50,7 @@ uint32_t getTagForSymbolName(char const *s) { return 0; } -struct blockheader getBlockHeaderForSymbol(uint32_t tag) { +struct blockheader get_block_header_for_symbol(uint32_t tag) { return blockheader{tag}; } @@ -59,8 +60,8 @@ bool during_gc() { void add_hash64(void *, uint64_t) { } -void flush_IO_logs(); -string *makeString(const KCHAR *, int64_t len = -1); +void flush_io_logs(); +string *make_string(const KCHAR *, int64_t len = -1); blockheader header_err(); block *hook_IO_open(string *filename, string *control); block *hook_IO_tell(mpz_t i); @@ -95,7 +96,7 @@ floating *move_float(floating *i) { } } -int overwriteTestFile() { +int overwrite_test_file() { int fd = ::open( "test.txt", O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH); @@ -107,39 +108,39 @@ int overwriteTestFile() { BOOST_AUTO_TEST_SUITE(IoTest) BOOST_AUTO_TEST_CASE(open) { - int fd = overwriteTestFile(); + int fd = overwrite_test_file(); ::close(fd); - auto realFilename = makeString("test.txt"); - auto fakeFilename = makeString("testFake.txt"); - auto control = makeString("r"); + auto realFilename = make_string("test.txt"); + auto fakeFilename = make_string("testFake.txt"); + auto control = make_string("r"); block *b1 = hook_IO_open(realFilename, control); BOOST_CHECK_EQUAL( - b1->h.hdr, getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortInt{}, SortIOInt{}}")) + b1->h.hdr, get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortInt{}, SortIOInt{}}")) .hdr); BOOST_CHECK(0 < mpz_cmp_si((mpz_ptr) * (b1->children), 0)); block *b2 = hook_IO_open(fakeFilename, control); BOOST_CHECK_EQUAL( - b2->h.hdr, getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortIOError{}, SortKItem{}}")) + b2->h.hdr, get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortIOError{}, SortKItem{}}")) .hdr); BOOST_CHECK_EQUAL( (uint64_t) * (b2->children), - ERRBLOCK(getTagForSymbolName(GETTAG(ENOENT)))); + ERRBLOCK(get_tag_for_symbol_name(GETTAG(ENOENT)))); } BOOST_AUTO_TEST_CASE(tell) { mpz_t f; - int fd = overwriteTestFile(); + int fd = overwrite_test_file(); mpz_init_set_si(f, fd); block *b = hook_IO_tell(f); BOOST_CHECK_EQUAL( - b->h.hdr, getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortInt{}, SortIOInt{}}")) + b->h.hdr, get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortInt{}, SortIOInt{}}")) .hdr); BOOST_CHECK_EQUAL( 0, @@ -149,15 +150,15 @@ BOOST_AUTO_TEST_CASE(tell) { b = hook_IO_tell(f); BOOST_CHECK_EQUAL( - b->h.hdr, getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortInt{}, SortIOInt{}}")) + b->h.hdr, get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortInt{}, SortIOInt{}}")) .hdr); BOOST_CHECK_EQUAL(0, mpz_cmp_si((mpz_ptr) * (b->children), 5)); b = hook_IO_tell(f); BOOST_CHECK_EQUAL( - b->h.hdr, getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortInt{}, SortIOInt{}}")) + b->h.hdr, get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortInt{}, SortIOInt{}}")) .hdr); BOOST_CHECK_EQUAL( 0, @@ -167,15 +168,15 @@ BOOST_AUTO_TEST_CASE(tell) { b = hook_IO_tell(f); BOOST_CHECK_EQUAL( - b->h.hdr, getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortInt{}, SortIOInt{}}")) + b->h.hdr, get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortInt{}, SortIOInt{}}")) .hdr); BOOST_CHECK_EQUAL(0, mpz_cmp_si((mpz_ptr) * (b->children), 1)); b = hook_IO_tell(f); BOOST_CHECK_EQUAL( - b->h.hdr, getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortInt{}, SortIOInt{}}")) + b->h.hdr, get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortInt{}, SortIOInt{}}")) .hdr); BOOST_CHECK_EQUAL( 0, @@ -186,97 +187,102 @@ BOOST_AUTO_TEST_CASE(tell) { mpz_set_si(f, -1); b = hook_IO_tell(f); BOOST_CHECK_EQUAL( - b->h.hdr, getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortIOError{}, SortKItem{}}")) + b->h.hdr, get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortIOError{}, SortKItem{}}")) .hdr); BOOST_CHECK_EQUAL( - (uint64_t) * (b->children), ERRBLOCK(getTagForSymbolName(GETTAG(EBADF)))); + (uint64_t) * (b->children), + ERRBLOCK(get_tag_for_symbol_name(GETTAG(EBADF)))); } BOOST_AUTO_TEST_CASE(getc) { mpz_t f; - int fd = overwriteTestFile(); + int fd = overwrite_test_file(); mpz_init_set_si(f, fd); block *b = hook_IO_getc(f); BOOST_CHECK_EQUAL( - b->h.hdr, getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortInt{}, SortIOInt{}}")) + b->h.hdr, get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortInt{}, SortIOInt{}}")) .hdr); BOOST_CHECK_EQUAL(0, mpz_cmp_si((mpz_ptr) * (b->children), int('h'))); b = hook_IO_getc(f); BOOST_CHECK_EQUAL( - b->h.hdr, getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortInt{}, SortIOInt{}}")) + b->h.hdr, get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortInt{}, SortIOInt{}}")) .hdr); BOOST_CHECK_EQUAL(0, mpz_cmp_si((mpz_ptr) * (b->children), int('e'))); b = hook_IO_getc(f); BOOST_CHECK_EQUAL( - b->h.hdr, getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortInt{}, SortIOInt{}}")) + b->h.hdr, get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortInt{}, SortIOInt{}}")) .hdr); BOOST_CHECK_EQUAL(0, mpz_cmp_si((mpz_ptr) * (b->children), int('l'))); b = hook_IO_getc(f); BOOST_CHECK_EQUAL( - b->h.hdr, getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortInt{}, SortIOInt{}}")) + b->h.hdr, get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortInt{}, SortIOInt{}}")) .hdr); BOOST_CHECK_EQUAL(0, mpz_cmp_si((mpz_ptr) * (b->children), int('l'))); b = hook_IO_getc(f); BOOST_CHECK_EQUAL( - b->h.hdr, getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortInt{}, SortIOInt{}}")) + b->h.hdr, get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortInt{}, SortIOInt{}}")) .hdr); BOOST_CHECK_EQUAL(0, mpz_cmp_si((mpz_ptr) * (b->children), int('o'))); ::lseek(fd, 0, SEEK_END); b = hook_IO_getc(f); BOOST_CHECK_EQUAL( - b->h.hdr, getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortIOError{}, SortKItem{}}")) + b->h.hdr, get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortIOError{}, SortKItem{}}")) .hdr); char const *temp = GETTAG(EOF); BOOST_CHECK(std::string(temp) != ""); BOOST_CHECK_EQUAL( - (uint64_t) * (b->children), ERRBLOCK(getTagForSymbolName(GETTAG(EOF)))); + (uint64_t) * (b->children), + ERRBLOCK(get_tag_for_symbol_name(GETTAG(EOF)))); ::close(fd); mpz_set_si(f, -1); b = hook_IO_getc(f); BOOST_CHECK_EQUAL( - b->h.hdr, getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortIOError{}, SortKItem{}}")) + b->h.hdr, get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortIOError{}, SortKItem{}}")) .hdr); BOOST_CHECK_EQUAL( - (uint64_t) * (b->children), ERRBLOCK(getTagForSymbolName(GETTAG(EBADF)))); + (uint64_t) * (b->children), + ERRBLOCK(get_tag_for_symbol_name(GETTAG(EBADF)))); } BOOST_AUTO_TEST_CASE(read) { mpz_t f; mpz_t length; - int fd = overwriteTestFile(); + int fd = overwrite_test_file(); mpz_init_set_si(f, fd); mpz_init_set_si(length, 6); block *b = hook_IO_read(f, length); BOOST_CHECK_EQUAL( - b->h.hdr, getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortString{}, SortIOString{}}")) - .hdr); + b->h.hdr, + get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortString{}, SortIOString{}}")) + .hdr); string *str = (string *)*(b->children); BOOST_CHECK_EQUAL(0, strncmp(str->data, "hello ", 6)); b = hook_IO_read(f, length); BOOST_CHECK_EQUAL( - b->h.hdr, getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortString{}, SortIOString{}}")) - .hdr); + b->h.hdr, + get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortString{}, SortIOString{}}")) + .hdr); str = (string *)*(b->children); BOOST_CHECK_EQUAL(0, strncmp(str->data, "world!", 6)); @@ -284,9 +290,10 @@ BOOST_AUTO_TEST_CASE(read) { b = hook_IO_read(f, length); BOOST_CHECK_EQUAL( - b->h.hdr, getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortString{}, SortIOString{}}")) - .hdr); + b->h.hdr, + get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortString{}, SortIOString{}}")) + .hdr); str = (string *)*(b->children); BOOST_CHECK_EQUAL(0, len(str)); @@ -294,19 +301,20 @@ BOOST_AUTO_TEST_CASE(read) { b = hook_IO_read(f, length); BOOST_CHECK_EQUAL( - b->h.hdr, getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortIOError{}, SortKItem{}}")) + b->h.hdr, get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortIOError{}, SortKItem{}}")) .hdr); BOOST_CHECK_EQUAL( - (uint64_t) * (b->children), ERRBLOCK(getTagForSymbolName(GETTAG(EBADF)))); + (uint64_t) * (b->children), + ERRBLOCK(get_tag_for_symbol_name(GETTAG(EBADF)))); } BOOST_AUTO_TEST_CASE(close) { mpz_t f1; mpz_t f2; - int fd1 = overwriteTestFile(); + int fd1 = overwrite_test_file(); mpz_init_set_si(f1, fd1); - int fd2 = overwriteTestFile(); + int fd2 = overwrite_test_file(); mpz_init_set_si(f2, fd2); hook_IO_close(f1); @@ -319,33 +327,35 @@ BOOST_AUTO_TEST_CASE(close) { block *b = hook_IO_close(f1); BOOST_CHECK_EQUAL( - b->h.hdr, getBlockHeaderForSymbol(getTagForSymbolName("kseq{}")).hdr); + b->h.hdr, + get_block_header_for_symbol(get_tag_for_symbol_name("kseq{}")).hdr); BOOST_CHECK_EQUAL( ((block *)*(b->children))->h.hdr, - getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortIOError{}, SortKItem{}}")) + get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortIOError{}, SortKItem{}}")) .hdr); BOOST_CHECK_EQUAL( (uint64_t) * (((block *)*(b->children))->children), - ERRBLOCK(getTagForSymbolName(GETTAG(EBADF)))); + ERRBLOCK(get_tag_for_symbol_name(GETTAG(EBADF)))); b = hook_IO_close(f2); BOOST_CHECK_EQUAL( - b->h.hdr, getBlockHeaderForSymbol(getTagForSymbolName("kseq{}")).hdr); + b->h.hdr, + get_block_header_for_symbol(get_tag_for_symbol_name("kseq{}")).hdr); BOOST_CHECK_EQUAL( ((block *)*(b->children))->h.hdr, - getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortIOError{}, SortKItem{}}")) + get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortIOError{}, SortKItem{}}")) .hdr); BOOST_CHECK_EQUAL( (uint64_t) * (((block *)*(b->children))->children), - ERRBLOCK(getTagForSymbolName(GETTAG(EBADF)))); + ERRBLOCK(get_tag_for_symbol_name(GETTAG(EBADF)))); } BOOST_AUTO_TEST_CASE(putc) { mpz_t f; mpz_t c; - int fd = overwriteTestFile(); + int fd = overwrite_test_file(); mpz_init_set_si(f, fd); lseek(fd, 0, SEEK_SET); @@ -372,15 +382,16 @@ BOOST_AUTO_TEST_CASE(putc) { block *b = hook_IO_putc(f, c); BOOST_CHECK_EQUAL( - b->h.hdr, getBlockHeaderForSymbol(getTagForSymbolName("kseq{}")).hdr); + b->h.hdr, + get_block_header_for_symbol(get_tag_for_symbol_name("kseq{}")).hdr); BOOST_CHECK_EQUAL( ((block *)*(b->children))->h.hdr, - getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortIOError{}, SortKItem{}}")) + get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortIOError{}, SortKItem{}}")) .hdr); BOOST_CHECK_EQUAL( (uint64_t) * (((block *)*(b->children))->children), - ERRBLOCK(getTagForSymbolName(GETTAG(EBADF)))); + ERRBLOCK(get_tag_for_symbol_name(GETTAG(EBADF)))); } BOOST_AUTO_TEST_CASE(seek) { @@ -388,7 +399,7 @@ BOOST_AUTO_TEST_CASE(seek) { mpz_t loc; mpz_init(loc); - int fd = overwriteTestFile(); + int fd = overwrite_test_file(); mpz_init_set_si(f, fd); int deltas[5] = {3, 0, 2, 5, 1}; @@ -402,21 +413,22 @@ BOOST_AUTO_TEST_CASE(seek) { mpz_set_si(f, -1); block *b = hook_IO_seek(f, loc); BOOST_CHECK_EQUAL( - b->h.hdr, getBlockHeaderForSymbol(getTagForSymbolName("kseq{}")).hdr); + b->h.hdr, + get_block_header_for_symbol(get_tag_for_symbol_name("kseq{}")).hdr); BOOST_CHECK_EQUAL( ((block *)*(b->children))->h.hdr, - getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortIOError{}, SortKItem{}}")) + get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortIOError{}, SortKItem{}}")) .hdr); BOOST_CHECK_EQUAL( (uint64_t) * (((block *)*(b->children))->children), - ERRBLOCK(getTagForSymbolName(GETTAG(EBADF)))); + ERRBLOCK(get_tag_for_symbol_name(GETTAG(EBADF)))); } BOOST_AUTO_TEST_CASE(seekEnd) { mpz_t f; mpz_t loc; - int fd = overwriteTestFile(); + int fd = overwrite_test_file(); mpz_init_set_si(f, fd); mpz_init(loc); @@ -434,21 +446,22 @@ BOOST_AUTO_TEST_CASE(seekEnd) { mpz_set_si(f, -1); block *b = hook_IO_seekEnd(f, loc); BOOST_CHECK_EQUAL( - b->h.hdr, getBlockHeaderForSymbol(getTagForSymbolName("kseq{}")).hdr); + b->h.hdr, + get_block_header_for_symbol(get_tag_for_symbol_name("kseq{}")).hdr); BOOST_CHECK_EQUAL( ((block *)*(b->children))->h.hdr, - getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortIOError{}, SortKItem{}}")) + get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortIOError{}, SortKItem{}}")) .hdr); BOOST_CHECK_EQUAL( (uint64_t) * (((block *)*(b->children))->children), - ERRBLOCK(getTagForSymbolName(GETTAG(EBADF)))); + ERRBLOCK(get_tag_for_symbol_name(GETTAG(EBADF)))); } BOOST_AUTO_TEST_CASE(write) { mpz_t f; - string *msg = makeString("This is a test message\n"); - int fd = overwriteTestFile(); + string *msg = make_string("This is a test message\n"); + int fd = overwrite_test_file(); mpz_init_set_si(f, fd); hook_IO_write(f, msg); @@ -463,20 +476,21 @@ BOOST_AUTO_TEST_CASE(write) { mpz_set_si(f, -1); block *b = hook_IO_write(f, msg); BOOST_CHECK_EQUAL( - b->h.hdr, getBlockHeaderForSymbol(getTagForSymbolName("kseq{}")).hdr); + b->h.hdr, + get_block_header_for_symbol(get_tag_for_symbol_name("kseq{}")).hdr); BOOST_CHECK_EQUAL( ((block *)*(b->children))->h.hdr, - getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortIOError{}, SortKItem{}}")) + get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortIOError{}, SortKItem{}}")) .hdr); BOOST_CHECK_EQUAL( (uint64_t) * (((block *)*(b->children))->children), - ERRBLOCK(getTagForSymbolName(GETTAG(EBADF)))); + ERRBLOCK(get_tag_for_symbol_name(GETTAG(EBADF)))); } BOOST_AUTO_TEST_CASE(lock) { mpz_t f, len; - int fd = overwriteTestFile(); + int fd = overwrite_test_file(); mpz_init_set_si(f, fd); mpz_init_set_si(len, 12); @@ -494,20 +508,21 @@ BOOST_AUTO_TEST_CASE(lock) { mpz_set_si(f, -1); b = hook_IO_lock(f, len); BOOST_CHECK_EQUAL( - b->h.hdr, getBlockHeaderForSymbol(getTagForSymbolName("kseq{}")).hdr); + b->h.hdr, + get_block_header_for_symbol(get_tag_for_symbol_name("kseq{}")).hdr); BOOST_CHECK_EQUAL( ((block *)*(b->children))->h.hdr, - getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortIOError{}, SortKItem{}}")) + get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortIOError{}, SortKItem{}}")) .hdr); BOOST_CHECK_EQUAL( (uint64_t) * (((block *)*(b->children))->children), - ERRBLOCK(getTagForSymbolName(GETTAG(EBADF)))); + ERRBLOCK(get_tag_for_symbol_name(GETTAG(EBADF)))); } BOOST_AUTO_TEST_CASE(unlock) { mpz_t f, len; - int fd = overwriteTestFile(); + int fd = overwrite_test_file(); mpz_init_set_si(f, fd); mpz_init_set_si(len, 12); @@ -525,27 +540,28 @@ BOOST_AUTO_TEST_CASE(unlock) { mpz_set_si(f, -1); b = hook_IO_unlock(f, len); BOOST_CHECK_EQUAL( - b->h.hdr, getBlockHeaderForSymbol(getTagForSymbolName("kseq{}")).hdr); + b->h.hdr, + get_block_header_for_symbol(get_tag_for_symbol_name("kseq{}")).hdr); BOOST_CHECK_EQUAL( ((block *)*(b->children))->h.hdr, - getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortIOError{}, SortKItem{}}")) + get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortIOError{}, SortKItem{}}")) .hdr); BOOST_CHECK_EQUAL( (uint64_t) * (((block *)*(b->children))->children), - ERRBLOCK(getTagForSymbolName(GETTAG(EBADF)))); + ERRBLOCK(get_tag_for_symbol_name(GETTAG(EBADF)))); } BOOST_AUTO_TEST_CASE(log) { std::string strPath = "logFile"; std::string strMsg = "Log1\nLog2\n"; - string *path = makeString(strPath.c_str()); - string *msg = makeString(strMsg.c_str()); + string *path = make_string(strPath.c_str()); + string *msg = make_string(strMsg.c_str()); hook_IO_log(path, msg); - msg = makeString("Log3\n"); + msg = make_string("Log3\n"); hook_IO_log(path, msg); - flush_IO_logs(); + flush_io_logs(); std::string PID = std::to_string(getpid()); FILE *f = fopen((PID + "_" + strPath).c_str(), "r"); @@ -558,7 +574,7 @@ BOOST_AUTO_TEST_CASE(log) { BOOST_AUTO_TEST_CASE(system) { std::string command = "echo \"hello\""; - string *cmd = makeString(command.c_str()); + string *cmd = make_string(command.c_str()); block *ret = hook_IO_system(cmd); @@ -569,7 +585,8 @@ BOOST_AUTO_TEST_CASE(system) { BOOST_CHECK_EQUAL( ret->h.hdr, - getBlockHeaderForSymbol(getTagForSymbolName(GETTAG(systemResult))).hdr); + get_block_header_for_symbol(get_tag_for_symbol_name(GETTAG(systemResult))) + .hdr); BOOST_CHECK_EQUAL(0, mpz_cmp_si((mpz_ptr) * (ret->children), 0)); string *out = (string *)*(ret->children + 1); @@ -578,7 +595,7 @@ BOOST_AUTO_TEST_CASE(system) { /* Check if shell is available */ command = ""; - cmd = makeString(command.c_str()); + cmd = make_string(command.c_str()); ret = hook_IO_system(cmd); BOOST_CHECK(ret != NULL); @@ -587,12 +604,13 @@ BOOST_AUTO_TEST_CASE(system) { BOOST_CHECK((ret->children + 2) != NULL); BOOST_CHECK_EQUAL( ret->h.hdr, - getBlockHeaderForSymbol(getTagForSymbolName(GETTAG(systemResult))).hdr); + get_block_header_for_symbol(get_tag_for_symbol_name(GETTAG(systemResult))) + .hdr); BOOST_CHECK(mpz_cmp_si((mpz_ptr) * (ret->children), 0) > 0); /* Execute program that segfaults */ command = "./IOTest 1"; - cmd = makeString(command.c_str()); + cmd = make_string(command.c_str()); ret = hook_IO_system(cmd); out = (string *)*(ret->children + 1); BOOST_CHECK(ret != NULL); @@ -601,13 +619,14 @@ BOOST_AUTO_TEST_CASE(system) { BOOST_CHECK((ret->children + 2) != NULL); BOOST_CHECK_EQUAL( ret->h.hdr, - getBlockHeaderForSymbol(getTagForSymbolName(GETTAG(systemResult))).hdr); + get_block_header_for_symbol(get_tag_for_symbol_name(GETTAG(systemResult))) + .hdr); // this assertion fails on some platforms // BOOST_CHECK_EQUAL(0, mpz_cmp_si((mpz_ptr) *(ret->children), 139)); /* Execute program that prints to stderr */ command = "./IOTest"; - cmd = makeString(command.c_str()); + cmd = make_string(command.c_str()); ret = hook_IO_system(cmd); out = (string *)*(ret->children + 1); BOOST_CHECK(ret != NULL); @@ -616,7 +635,8 @@ BOOST_AUTO_TEST_CASE(system) { BOOST_CHECK((ret->children + 2) != NULL); BOOST_CHECK_EQUAL( ret->h.hdr, - getBlockHeaderForSymbol(getTagForSymbolName(GETTAG(systemResult))).hdr); + get_block_header_for_symbol(get_tag_for_symbol_name(GETTAG(systemResult))) + .hdr); BOOST_CHECK_EQUAL(0, mpz_cmp_si((mpz_ptr) * (ret->children), 0)); string *err = (string *)*(ret->children + 2); @@ -652,8 +672,8 @@ BOOST_AUTO_TEST_CASE(argv) { BOOST_CHECK(ret[0].elem != nullptr); BOOST_CHECK_EQUAL( ret[0].elem->h.hdr, - getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortString{}, SortKItem{}}")) + get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortString{}, SortKItem{}}")) .hdr); string *arg0 = (string *)*(ret[0].elem->children); BOOST_CHECK_EQUAL(0, strncmp(arg0->data, argv[0], strlen(argv[0]))); @@ -662,8 +682,8 @@ BOOST_AUTO_TEST_CASE(argv) { BOOST_CHECK(ret[1].elem != nullptr); BOOST_CHECK_EQUAL( ret[1].elem->h.hdr, - getBlockHeaderForSymbol( - getTagForSymbolName("inj{SortString{}, SortKItem{}}")) + get_block_header_for_symbol( + get_tag_for_symbol_name("inj{SortString{}, SortKItem{}}")) .hdr); string *arg1 = (string *)*(ret[1].elem->children); BOOST_CHECK_EQUAL(0, strncmp(arg1->data, argv[1], strlen(argv[1]))); diff --git a/unittests/runtime-strings/bytestest.cpp b/unittests/runtime-strings/bytestest.cpp index 50cbd3a6b..42ecaa216 100644 --- a/unittests/runtime-strings/bytestest.cpp +++ b/unittests/runtime-strings/bytestest.cpp @@ -9,7 +9,7 @@ #define KCHAR char extern "C" { -uint32_t getTagForSymbolName(char const *s) { +uint32_t get_tag_for_symbol_name(char const *s) { return 0; } @@ -31,13 +31,13 @@ string *hook_BYTES_padRight(string *b, mpz_t len, mpz_t v); string *hook_BYTES_padLeft(string *b, mpz_t len, mpz_t v); string *hook_BYTES_reverse(string *b); string *hook_BYTES_concat(string *b1, string *); -string *makeString(const KCHAR *, int64_t len = -1); +string *make_string(const KCHAR *, int64_t len = -1); } BOOST_AUTO_TEST_SUITE(BytesTest) BOOST_AUTO_TEST_CASE(bytes2int) { - auto empty = makeString(""); + auto empty = make_string(""); BOOST_CHECK_EQUAL( 0, mpz_cmp_si( hook_BYTES_bytes2int(empty, tag_big_endian(), tag_unsigned()), 0)); @@ -47,7 +47,7 @@ BOOST_AUTO_TEST_CASE(bytes2int) { 0, mpz_cmp_si(hook_BYTES_bytes2int(empty, tag_big_endian(), 2), 0)); BOOST_CHECK_EQUAL(0, mpz_cmp_si(hook_BYTES_bytes2int(empty, 2, 2), 0)); - auto ff = makeString("\xff"); + auto ff = make_string("\xff"); BOOST_CHECK_EQUAL( 0, mpz_cmp_si( hook_BYTES_bytes2int(ff, tag_big_endian(), tag_unsigned()), 255)); @@ -57,7 +57,7 @@ BOOST_AUTO_TEST_CASE(bytes2int) { 0, mpz_cmp_si(hook_BYTES_bytes2int(ff, 2, tag_unsigned()), 255)); BOOST_CHECK_EQUAL(0, mpz_cmp_si(hook_BYTES_bytes2int(ff, 2, 2), -1)); - auto _00ff = makeString("\x00\xff", 2); + auto _00ff = make_string("\x00\xff", 2); BOOST_CHECK_EQUAL( 0, mpz_cmp_si( @@ -65,7 +65,7 @@ BOOST_AUTO_TEST_CASE(bytes2int) { BOOST_CHECK_EQUAL( 0, mpz_cmp_si(hook_BYTES_bytes2int(_00ff, tag_big_endian(), 2), 255)); - auto ff00 = makeString("\xff\x00", 2); + auto ff00 = make_string("\xff\x00", 2); BOOST_CHECK_EQUAL(0, mpz_cmp_si(hook_BYTES_bytes2int(ff00, 2, 2), 255)); BOOST_CHECK_EQUAL( 0, mpz_cmp_si(hook_BYTES_bytes2int(ff00, 2, tag_unsigned()), 255)); @@ -159,12 +159,12 @@ BOOST_AUTO_TEST_CASE(int2bytes) { } BOOST_AUTO_TEST_CASE(bytes2string) { - auto empty = makeString(""); + auto empty = make_string(""); auto res = hook_BYTES_bytes2string(empty); BOOST_CHECK(res != empty); BOOST_CHECK_EQUAL(len(empty), 0); - auto _1234 = makeString("1234"); + auto _1234 = make_string("1234"); res = hook_BYTES_bytes2string(_1234); BOOST_CHECK(res != _1234); BOOST_CHECK_EQUAL(len(_1234), 4); @@ -172,12 +172,12 @@ BOOST_AUTO_TEST_CASE(bytes2string) { } BOOST_AUTO_TEST_CASE(string2bytes) { - auto empty = makeString(""); + auto empty = make_string(""); auto res = hook_BYTES_string2bytes(empty); BOOST_CHECK(res != empty); BOOST_CHECK_EQUAL(len(empty), 0); - auto _1234 = makeString("1234"); + auto _1234 = make_string("1234"); res = hook_BYTES_string2bytes(_1234); BOOST_CHECK(res != _1234); BOOST_CHECK_EQUAL(len(_1234), 4); @@ -185,7 +185,7 @@ BOOST_AUTO_TEST_CASE(string2bytes) { } BOOST_AUTO_TEST_CASE(substr) { - auto catAll = makeString("hellohehf"); + auto catAll = make_string("hellohehf"); mpz_t _2, _9, _6, _0, _4, _7, _40, _8, _10, _1024, _4096; mpz_init_set_si(_2, 2); @@ -218,7 +218,7 @@ BOOST_AUTO_TEST_CASE(substr) { } BOOST_AUTO_TEST_CASE(update) { - auto _1234 = makeString("1234"); + auto _1234 = make_string("1234"); mpz_t _0, _2; mpz_init_set_ui(_0, '0'); mpz_init_set_ui(_2, 2); @@ -230,7 +230,7 @@ BOOST_AUTO_TEST_CASE(update) { } BOOST_AUTO_TEST_CASE(memset) { - auto _12345 = makeString("12345"); + auto _12345 = make_string("12345"); mpz_t _0, _1, _3; mpz_init_set_si(_0, '0'); mpz_init_set_ui(_1, 1); @@ -258,7 +258,7 @@ BOOST_AUTO_TEST_CASE(memset) { } BOOST_AUTO_TEST_CASE(get) { - auto _1234 = makeString("1234"); + auto _1234 = make_string("1234"); mpz_t _0; mpz_init_set_ui(_0, 0); @@ -267,8 +267,8 @@ BOOST_AUTO_TEST_CASE(get) { } BOOST_AUTO_TEST_CASE(replaceAt) { - auto _1234 = makeString("1234"); - auto _2 = makeString("2"); + auto _1234 = make_string("1234"); + auto _2 = make_string("2"); mpz_t _0; mpz_init_set_ui(_0, 0); @@ -277,16 +277,16 @@ BOOST_AUTO_TEST_CASE(replaceAt) { BOOST_CHECK_EQUAL(4, len(res)); BOOST_CHECK_EQUAL(0, memcmp(res->data, "2234", 4)); - auto _23 = makeString("23"); - _1234 = makeString("1234"); + auto _23 = make_string("23"); + _1234 = make_string("1234"); res = hook_BYTES_replaceAt(_1234, _0, _23); BOOST_CHECK_EQUAL(_1234, res); BOOST_CHECK_EQUAL(4, len(res)); BOOST_CHECK_EQUAL(0, memcmp(res->data, "2334", 4)); - auto empty = makeString(""); - _1234 = makeString("1234"); + auto empty = make_string(""); + _1234 = make_string("1234"); res = hook_BYTES_replaceAt(_1234, _0, empty); BOOST_CHECK_EQUAL(_1234, res); @@ -295,7 +295,7 @@ BOOST_AUTO_TEST_CASE(replaceAt) { mpz_t _1; mpz_init_set_ui(_1, 1); - auto _12 = makeString("12"); + auto _12 = make_string("12"); res = hook_BYTES_replaceAt(_1234, _1, _12); BOOST_CHECK_EQUAL(_1234, res); @@ -304,15 +304,15 @@ BOOST_AUTO_TEST_CASE(replaceAt) { } BOOST_AUTO_TEST_CASE(length) { - auto empty = makeString(""); + auto empty = make_string(""); BOOST_CHECK_EQUAL(0, mpz_get_ui(hook_BYTES_length(empty))); - auto _1234 = makeString("1234"); + auto _1234 = make_string("1234"); BOOST_CHECK_EQUAL(4, mpz_get_ui(hook_BYTES_length(_1234))); } BOOST_AUTO_TEST_CASE(padRight) { - auto empty = makeString(""); + auto empty = make_string(""); mpz_t _0; mpz_init_set_ui(_0, 0); @@ -328,7 +328,7 @@ BOOST_AUTO_TEST_CASE(padRight) { BOOST_CHECK_EQUAL(4, len(res)); BOOST_CHECK_EQUAL(0, memcmp(res->data, "aaaa", 4)); - auto _1234 = makeString("1234"); + auto _1234 = make_string("1234"); mpz_t _8; mpz_init_set_ui(_8, 8); @@ -338,7 +338,7 @@ BOOST_AUTO_TEST_CASE(padRight) { } BOOST_AUTO_TEST_CASE(padLeft) { - auto empty = makeString(""); + auto empty = make_string(""); mpz_t _0; mpz_init_set_ui(_0, 0); @@ -354,7 +354,7 @@ BOOST_AUTO_TEST_CASE(padLeft) { BOOST_CHECK_EQUAL(4, len(res)); BOOST_CHECK_EQUAL(0, memcmp(res->data, "aaaa", 4)); - auto _1234 = makeString("1234"); + auto _1234 = make_string("1234"); mpz_t _8; mpz_init_set_ui(_8, 8); @@ -364,12 +364,12 @@ BOOST_AUTO_TEST_CASE(padLeft) { } BOOST_AUTO_TEST_CASE(reverse) { - auto empty = makeString(""); + auto empty = make_string(""); auto res = hook_BYTES_reverse(empty); BOOST_CHECK_EQUAL(empty, res); BOOST_CHECK_EQUAL(len(empty), 0); - auto _1234 = makeString("1234"); + auto _1234 = make_string("1234"); res = hook_BYTES_reverse(_1234); BOOST_CHECK_EQUAL(_1234, res); BOOST_CHECK_EQUAL(len(_1234), 4); @@ -377,10 +377,10 @@ BOOST_AUTO_TEST_CASE(reverse) { } BOOST_AUTO_TEST_CASE(concat) { - auto a = makeString("hello"); - auto b = makeString("he"); - auto c = makeString("hf"); - auto d = makeString(""); + auto a = make_string("hello"); + auto b = make_string("he"); + auto c = make_string("hf"); + auto d = make_string(""); auto emptyCatR = hook_BYTES_concat(a, d); BOOST_CHECK_EQUAL(0, memcmp(emptyCatR->data, a->data, len(emptyCatR))); @@ -391,7 +391,7 @@ BOOST_AUTO_TEST_CASE(concat) { BOOST_CHECK_EQUAL(len(emptyCatL), len(a)); auto catAll = hook_BYTES_concat(hook_BYTES_concat(a, b), c); - auto expected = makeString("hellohehf"); + auto expected = make_string("hellohehf"); BOOST_CHECK_EQUAL(0, memcmp(catAll->data, expected->data, len(catAll))); BOOST_CHECK_EQUAL(len(catAll), len(expected)); } diff --git a/unittests/runtime-strings/stringtest.cpp b/unittests/runtime-strings/stringtest.cpp index e7f84d5b4..83c226928 100644 --- a/unittests/runtime-strings/stringtest.cpp +++ b/unittests/runtime-strings/stringtest.cpp @@ -12,7 +12,8 @@ #define KCHAR char -void *constructCompositePattern(uint32_t tag, std::vector &arguments) { +void * +construct_composite_pattern(uint32_t tag, std::vector &arguments) { return nullptr; } @@ -45,13 +46,13 @@ string *hook_STRING_replace(string *, string *, string *, mpz_t); string *hook_STRING_replaceFirst(string *, string *, string *); mpz_ptr hook_STRING_countAllOccurrences(string *, string *); string *hook_STRING_transcode(string *, string *, string *); -string *makeString(const KCHAR *, int64_t len = -1); +string *make_string(const KCHAR *, int64_t len = -1); stringbuffer *hook_BUFFER_empty(); stringbuffer *hook_BUFFER_concat(stringbuffer *, string *); string *hook_BUFFER_toString(stringbuffer *); -uint32_t const first_inj_tag = std::numeric_limits::max(); -uint32_t const last_inj_tag = std::numeric_limits::min(); +uint32_t const FIRST_INJ_TAG = std::numeric_limits::max(); +uint32_t const LAST_INJ_TAG = std::numeric_limits::min(); mpz_ptr move_int(mpz_t i) { mpz_ptr result = (mpz_ptr)malloc(sizeof(__mpz_struct)); @@ -71,10 +72,10 @@ void add_hash64(void *, uint64_t) { } BOOST_AUTO_TEST_SUITE(StringTest) BOOST_AUTO_TEST_CASE(gt) { - auto a = makeString("hello"); - auto b = makeString("he"); - auto c = makeString("hf"); - auto d = makeString(""); + auto a = make_string("hello"); + auto b = make_string("he"); + auto c = make_string("hf"); + auto d = make_string(""); BOOST_CHECK_EQUAL(false, hook_STRING_gt(a, a)); BOOST_CHECK_EQUAL(true, hook_STRING_gt(a, b)); @@ -95,10 +96,10 @@ BOOST_AUTO_TEST_CASE(gt) { } BOOST_AUTO_TEST_CASE(ge) { - auto a = makeString("hello"); - auto b = makeString("he"); - auto c = makeString("hf"); - auto d = makeString(""); + auto a = make_string("hello"); + auto b = make_string("he"); + auto c = make_string("hf"); + auto d = make_string(""); BOOST_CHECK_EQUAL(true, hook_STRING_ge(a, a)); BOOST_CHECK_EQUAL(true, hook_STRING_ge(a, b)); @@ -119,10 +120,10 @@ BOOST_AUTO_TEST_CASE(ge) { } BOOST_AUTO_TEST_CASE(lt) { - auto a = makeString("hello"); - auto b = makeString("he"); - auto c = makeString("hf"); - auto d = makeString(""); + auto a = make_string("hello"); + auto b = make_string("he"); + auto c = make_string("hf"); + auto d = make_string(""); BOOST_CHECK_EQUAL(false, hook_STRING_lt(a, a)); BOOST_CHECK_EQUAL(false, hook_STRING_lt(a, b)); @@ -143,10 +144,10 @@ BOOST_AUTO_TEST_CASE(lt) { } BOOST_AUTO_TEST_CASE(le) { - auto a = makeString("hello"); - auto b = makeString("he"); - auto c = makeString("hf"); - auto d = makeString(""); + auto a = make_string("hello"); + auto b = make_string("he"); + auto c = make_string("hf"); + auto d = make_string(""); BOOST_CHECK_EQUAL(true, hook_STRING_le(a, a)); BOOST_CHECK_EQUAL(false, hook_STRING_le(a, b)); @@ -167,10 +168,10 @@ BOOST_AUTO_TEST_CASE(le) { } BOOST_AUTO_TEST_CASE(eq) { - auto a = makeString("hello"); - auto b = makeString("he"); - auto c = makeString("hf"); - auto d = makeString(""); + auto a = make_string("hello"); + auto b = make_string("he"); + auto c = make_string("hf"); + auto d = make_string(""); BOOST_CHECK_EQUAL(true, hook_STRING_eq(a, a)); BOOST_CHECK_EQUAL(false, hook_STRING_eq(a, b)); @@ -191,10 +192,10 @@ BOOST_AUTO_TEST_CASE(eq) { } BOOST_AUTO_TEST_CASE(ne) { - auto a = makeString("hello"); - auto b = makeString("he"); - auto c = makeString("hf"); - auto d = makeString(""); + auto a = make_string("hello"); + auto b = make_string("he"); + auto c = make_string("hf"); + auto d = make_string(""); BOOST_CHECK_EQUAL(false, hook_STRING_ne(a, a)); BOOST_CHECK_EQUAL(true, hook_STRING_ne(a, b)); @@ -215,10 +216,10 @@ BOOST_AUTO_TEST_CASE(ne) { } BOOST_AUTO_TEST_CASE(concat) { - auto a = makeString("hello"); - auto b = makeString("he"); - auto c = makeString("hf"); - auto d = makeString(""); + auto a = make_string("hello"); + auto b = make_string("he"); + auto c = make_string("hf"); + auto d = make_string(""); auto emptyCatR = hook_STRING_concat(a, d); BOOST_CHECK_EQUAL(0, memcmp(emptyCatR->data, a->data, len(emptyCatR))); @@ -229,7 +230,7 @@ BOOST_AUTO_TEST_CASE(concat) { BOOST_CHECK_EQUAL(len(emptyCatL), len(a)); auto catAll = hook_STRING_concat(hook_STRING_concat(a, b), c); - auto expected = makeString("hellohehf"); + auto expected = make_string("hellohehf"); BOOST_CHECK_EQUAL(0, memcmp(catAll->data, expected->data, len(catAll))); BOOST_CHECK_EQUAL(len(catAll), len(expected)); } @@ -249,24 +250,24 @@ BOOST_AUTO_TEST_CASE(chr) { } BOOST_AUTO_TEST_CASE(length) { - BOOST_CHECK_EQUAL(mpz_cmp_ui(hook_STRING_length(makeString("hello")), 5), 0); - BOOST_CHECK_EQUAL(mpz_cmp_ui(hook_STRING_length(makeString("")), 0), 0); - BOOST_CHECK_EQUAL(mpz_cmp_ui(hook_STRING_length(makeString("worl")), 4), 0); + BOOST_CHECK_EQUAL(mpz_cmp_ui(hook_STRING_length(make_string("hello")), 5), 0); + BOOST_CHECK_EQUAL(mpz_cmp_ui(hook_STRING_length(make_string("")), 0), 0); + BOOST_CHECK_EQUAL(mpz_cmp_ui(hook_STRING_length(make_string("worl")), 4), 0); } BOOST_AUTO_TEST_CASE(ord) { - mpz_ptr result = hook_STRING_ord(makeString("A")); + mpz_ptr result = hook_STRING_ord(make_string("A")); BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 65), 0); - result = hook_STRING_ord(makeString(" ")); + result = hook_STRING_ord(make_string(" ")); BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 32), 0); - result = hook_STRING_ord(makeString("\xff")); + result = hook_STRING_ord(make_string("\xff")); BOOST_CHECK_EQUAL(mpz_cmp_ui(result, 255), 0); - BOOST_CHECK_THROW(hook_STRING_ord(makeString("")), std::invalid_argument); - BOOST_CHECK_THROW(hook_STRING_ord(makeString("AA")), std::invalid_argument); + BOOST_CHECK_THROW(hook_STRING_ord(make_string("")), std::invalid_argument); + BOOST_CHECK_THROW(hook_STRING_ord(make_string("AA")), std::invalid_argument); } BOOST_AUTO_TEST_CASE(substr) { - auto catAll = makeString("hellohehf"); + auto catAll = make_string("hellohehf"); mpz_t _2, _9, _6, _0, _4, _7, _40, _8, _10, _1024, _4096; mpz_init_set_si(_2, 2); @@ -300,9 +301,9 @@ BOOST_AUTO_TEST_CASE(substr) { } BOOST_AUTO_TEST_CASE(find) { - auto haystack = makeString("hellollo"); - auto needle = makeString("llo"); - auto needle2 = makeString("hf"); + auto haystack = make_string("hellollo"); + auto needle = make_string("llo"); + auto needle2 = make_string("hf"); mpz_t a, b, c, d, e, f, g; mpz_init_set_si(a, 0); @@ -324,8 +325,8 @@ BOOST_AUTO_TEST_CASE(find) { } BOOST_AUTO_TEST_CASE(findChar) { - auto haystack = makeString("Hello world"); - auto needle = makeString("Hd"); + auto haystack = make_string("Hello world"); + auto needle = make_string("Hd"); mpz_t a, b; mpz_init_set_si(a, 0); @@ -338,11 +339,11 @@ BOOST_AUTO_TEST_CASE(findChar) { } BOOST_AUTO_TEST_CASE(rfind) { - auto haystack = makeString("hellollo"); - auto needle = makeString("llo"); - auto needle2 = makeString("hf"); - auto needle3 = makeString("hello"); - auto needle4 = makeString("lol"); + auto haystack = make_string("hellollo"); + auto needle = make_string("llo"); + auto needle2 = make_string("hf"); + auto needle3 = make_string("hello"); + auto needle4 = make_string("lol"); mpz_t a, b, c, d, e, f, g; mpz_init_set_si(a, 0); @@ -366,8 +367,8 @@ BOOST_AUTO_TEST_CASE(rfind) { } BOOST_AUTO_TEST_CASE(rfindChar) { - auto haystack = makeString("Hello world"); - auto needle = makeString("Hd"); + auto haystack = make_string("Hello world"); + auto needle = make_string("Hd"); mpz_t a, b; mpz_init_set_si(a, 10); @@ -404,11 +405,11 @@ BOOST_AUTO_TEST_CASE(int2string) { } BOOST_AUTO_TEST_CASE(string2int) { - auto _0 = makeString("0"); - auto _10 = makeString("10"); - auto neg10 = makeString("-10"); - auto neg10000 = makeString("-10000"); - auto plus1000 = makeString("+1000"); + auto _0 = make_string("0"); + auto _10 = make_string("10"); + auto neg10 = make_string("-10"); + auto neg10000 = make_string("-10000"); + auto plus1000 = make_string("+1000"); BOOST_CHECK_EQUAL(mpz_cmp_si(hook_STRING_string2int(_0), 0), 0); BOOST_CHECK_EQUAL(mpz_cmp_si(hook_STRING_string2int(_10), 10), 0); @@ -418,10 +419,10 @@ BOOST_AUTO_TEST_CASE(string2int) { } BOOST_AUTO_TEST_CASE(string2base) { - auto _0 = makeString("0"); - auto _10 = makeString("10"); - auto neg10 = makeString("-10"); - auto ff = makeString("ff"); + auto _0 = make_string("0"); + auto _10 = make_string("10"); + auto neg10 = make_string("-10"); + auto ff = make_string("ff"); mpz_t int10; mpz_init_set_ui(int10, 10); @@ -440,7 +441,7 @@ BOOST_AUTO_TEST_CASE(string2base) { } BOOST_AUTO_TEST_CASE(string2float) { - auto _float = makeString("8.0f"); + auto _float = make_string("8.0f"); floating *result; result = hook_STRING_string2float(_float); @@ -452,28 +453,28 @@ BOOST_AUTO_TEST_CASE(string2float) { std::string resultSTL = std::string(result2->data, len(result2)); BOOST_CHECK_EQUAL(resultSTL, "0.800000000e1f"); - _float = makeString("+Infinity"); + _float = make_string("+Infinity"); result = hook_STRING_string2float(_float); BOOST_CHECK_EQUAL(53, mpfr_get_prec(result->f)); BOOST_CHECK_EQUAL(11, result->exp); BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, INFINITY), 0); - _float = makeString("-Infinity"); + _float = make_string("-Infinity"); result = hook_STRING_string2float(_float); BOOST_CHECK_EQUAL(53, mpfr_get_prec(result->f)); BOOST_CHECK_EQUAL(11, result->exp); BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, -INFINITY), 0); - _float = makeString("Infinityf"); + _float = make_string("Infinityf"); result = hook_STRING_string2float(_float); BOOST_CHECK_EQUAL(24, mpfr_get_prec(result->f)); BOOST_CHECK_EQUAL(8, result->exp); BOOST_CHECK_EQUAL(mpfr_cmp_d(result->f, INFINITY), 0); - _float = makeString("Infinityp50x10"); + _float = make_string("Infinityp50x10"); result = hook_STRING_string2float(_float); BOOST_CHECK_EQUAL(50, mpfr_get_prec(result->f)); @@ -482,9 +483,9 @@ BOOST_AUTO_TEST_CASE(string2float) { } BOOST_AUTO_TEST_CASE(replace) { - auto replacee = makeString("hello world hello world hello world he worl"); - auto matcher = makeString("hello"); - auto replacer = makeString("goodbye"); + auto replacee = make_string("hello world hello world hello world he worl"); + auto matcher = make_string("hello"); + auto replacer = make_string("goodbye"); mpz_t a, b, c, d, e; mpz_init_set_si(a, 0); @@ -497,48 +498,49 @@ BOOST_AUTO_TEST_CASE(replace) { true, hook_STRING_eq( hook_STRING_replaceAll(replacee, matcher, replacer), - makeString("goodbye world goodbye world goodbye world he worl"))); + make_string("goodbye world goodbye world goodbye world he worl"))); BOOST_CHECK_EQUAL( true, hook_STRING_eq( hook_STRING_replace(replacee, matcher, replacer, a), - makeString("hello world hello world hello world he worl"))); + make_string("hello world hello world hello world he worl"))); BOOST_CHECK_EQUAL( true, hook_STRING_eq( hook_STRING_replace(replacee, matcher, replacer, b), - makeString("goodbye world hello world hello world he worl"))); + make_string("goodbye world hello world hello world he worl"))); BOOST_CHECK_EQUAL( - true, hook_STRING_eq( - hook_STRING_replace(replacee, matcher, replacer, c), - makeString("goodbye world goodbye world hello world he worl"))); + true, + hook_STRING_eq( + hook_STRING_replace(replacee, matcher, replacer, c), + make_string("goodbye world goodbye world hello world he worl"))); BOOST_CHECK_EQUAL( true, hook_STRING_eq( hook_STRING_replace(replacee, matcher, replacer, d), - makeString("goodbye world goodbye world goodbye world he worl"))); + make_string("goodbye world goodbye world goodbye world he worl"))); BOOST_CHECK_EQUAL( true, hook_STRING_eq( hook_STRING_replace(replacee, matcher, replacer, e), - makeString("goodbye world goodbye world goodbye world he worl"))); + make_string("goodbye world goodbye world goodbye world he worl"))); BOOST_CHECK_EQUAL( true, hook_STRING_eq( hook_STRING_replaceFirst(replacee, matcher, replacer), - makeString("goodbye world hello world hello world he worl"))); + make_string("goodbye world hello world hello world he worl"))); } BOOST_AUTO_TEST_CASE(countAllOccurrences) { - auto replacee = makeString("hello world hello world hello world he worl"); - auto matcher = makeString("hello"); + auto replacee = make_string("hello world hello world hello world he worl"); + auto matcher = make_string("hello"); BOOST_CHECK_EQUAL( mpz_cmp_ui(hook_STRING_countAllOccurrences(replacee, matcher), 3), 0); - replacee = makeString("hel world hel world heo world he worl"); - matcher = makeString("hello"); + replacee = make_string("hel world hel world heo world he worl"); + matcher = make_string("hello"); BOOST_CHECK_EQUAL( mpz_cmp_ui(hook_STRING_countAllOccurrences(replacee, matcher), 0), 0); - replacee = makeString("hel world hel world hello world he worl"); - matcher = makeString("hello"); + replacee = make_string("hel world hel world hello world he worl"); + matcher = make_string("hello"); BOOST_CHECK_EQUAL( mpz_cmp_ui(hook_STRING_countAllOccurrences(replacee, matcher), 1), 0); } @@ -569,16 +571,16 @@ BOOST_AUTO_TEST_CASE(buffer_concat) { } BOOST_AUTO_TEST_CASE(transcode) { - auto foo = makeString("foo"); - auto fooUTF16LE = makeString("f\0o\0o\0", 6); - auto fooUTF16BE = makeString("\0f\0o\0o", 6); - auto fooUTF32LE = makeString("f\0\0\0o\0\0\0o\0\0\0", 12); - auto fooUTF32BE = makeString("\0\0\0f\0\0\0o\0\0\0o", 12); - auto UTF8 = makeString("UTF-8"); - auto UTF16LE = makeString("UTF-16LE"); - auto UTF16BE = makeString("UTF-16BE"); - auto UTF32LE = makeString("UTF-32LE"); - auto UTF32BE = makeString("UTF-32BE"); + auto foo = make_string("foo"); + auto fooUTF16LE = make_string("f\0o\0o\0", 6); + auto fooUTF16BE = make_string("\0f\0o\0o", 6); + auto fooUTF32LE = make_string("f\0\0\0o\0\0\0o\0\0\0", 12); + auto fooUTF32BE = make_string("\0\0\0f\0\0\0o\0\0\0o", 12); + auto UTF8 = make_string("UTF-8"); + auto UTF16LE = make_string("UTF-16LE"); + auto UTF16BE = make_string("UTF-16BE"); + auto UTF32LE = make_string("UTF-32LE"); + auto UTF32BE = make_string("UTF-32BE"); auto result = hook_STRING_transcode(foo, UTF8, UTF16LE); BOOST_CHECK_EQUAL(1, hook_STRING_eq(result, fooUTF16LE)); result = hook_STRING_transcode(foo, UTF8, UTF16BE);