diff options
| author | Richard Qin <richard.qin.x@gmail.com> | 2026-04-02 04:10:53 +0800 |
|---|---|---|
| committer | Richard Qin <richard.qin.x@gmail.com> | 2026-04-02 04:10:53 +0800 |
| commit | 26da267b732e28e4d9697278e735b410e50e5e08 (patch) | |
| tree | c084d333f50b94e1adee6f139d463bed14ced14f | |
| download | ratp-26da267b732e28e4d9697278e735b410e50e5e08.tar.gz ratp-26da267b732e28e4d9697278e735b410e50e5e08.tar.xz | |
Initial commit: Build project architecture, define interfaces, write documentation, with the help of Claude
74 files changed, 3476 insertions, 0 deletions
diff --git a/.cache/clangd/index/clausifier.cpp.9FD5A8E503FCC1D9.idx b/.cache/clangd/index/clausifier.cpp.9FD5A8E503FCC1D9.idx Binary files differnew file mode 100644 index 0000000..2e9fe48 --- /dev/null +++ b/.cache/clangd/index/clausifier.cpp.9FD5A8E503FCC1D9.idx diff --git a/.cache/clangd/index/discrim_tree.cpp.E42DE863D5277544.idx b/.cache/clangd/index/discrim_tree.cpp.E42DE863D5277544.idx Binary files differnew file mode 100644 index 0000000..8e446d8 --- /dev/null +++ b/.cache/clangd/index/discrim_tree.cpp.E42DE863D5277544.idx diff --git a/.cache/clangd/index/main.cpp.E859CA8999ADDE12.idx b/.cache/clangd/index/main.cpp.E859CA8999ADDE12.idx Binary files differnew file mode 100644 index 0000000..0b3849a --- /dev/null +++ b/.cache/clangd/index/main.cpp.E859CA8999ADDE12.idx diff --git a/.cache/clangd/index/proof_trace.cpp.1C59D7C4E2AA6F75.idx b/.cache/clangd/index/proof_trace.cpp.1C59D7C4E2AA6F75.idx Binary files differnew file mode 100644 index 0000000..6676913 --- /dev/null +++ b/.cache/clangd/index/proof_trace.cpp.1C59D7C4E2AA6F75.idx diff --git a/.cache/clangd/index/prover.cpp.3C0A611D8081F4D2.idx b/.cache/clangd/index/prover.cpp.3C0A611D8081F4D2.idx Binary files differnew file mode 100644 index 0000000..bbf1235 --- /dev/null +++ b/.cache/clangd/index/prover.cpp.3C0A611D8081F4D2.idx diff --git a/.cache/clangd/index/resolution.cpp.DB2A5A3C44A70C4B.idx b/.cache/clangd/index/resolution.cpp.DB2A5A3C44A70C4B.idx Binary files differnew file mode 100644 index 0000000..7d4a0b7 --- /dev/null +++ b/.cache/clangd/index/resolution.cpp.DB2A5A3C44A70C4B.idx diff --git a/.cache/clangd/index/subsumption.cpp.6D5F5B98AE9124E8.idx b/.cache/clangd/index/subsumption.cpp.6D5F5B98AE9124E8.idx Binary files differnew file mode 100644 index 0000000..e919d99 --- /dev/null +++ b/.cache/clangd/index/subsumption.cpp.6D5F5B98AE9124E8.idx diff --git a/.cache/clangd/index/symbol_table.cpp.685747B6B16C64EF.idx b/.cache/clangd/index/symbol_table.cpp.685747B6B16C64EF.idx Binary files differnew file mode 100644 index 0000000..8be6d25 --- /dev/null +++ b/.cache/clangd/index/symbol_table.cpp.685747B6B16C64EF.idx diff --git a/.cache/clangd/index/term_bank.cpp.943AA1306E763CC8.idx b/.cache/clangd/index/term_bank.cpp.943AA1306E763CC8.idx Binary files differnew file mode 100644 index 0000000..d452e77 --- /dev/null +++ b/.cache/clangd/index/term_bank.cpp.943AA1306E763CC8.idx diff --git a/.cache/clangd/index/test_clausifier.cpp.FF3EDB07B9DFBBC1.idx b/.cache/clangd/index/test_clausifier.cpp.FF3EDB07B9DFBBC1.idx Binary files differnew file mode 100644 index 0000000..34f30e6 --- /dev/null +++ b/.cache/clangd/index/test_clausifier.cpp.FF3EDB07B9DFBBC1.idx diff --git a/.cache/clangd/index/test_discrim_tree.cpp.9508FB8B5A477D10.idx b/.cache/clangd/index/test_discrim_tree.cpp.9508FB8B5A477D10.idx Binary files differnew file mode 100644 index 0000000..acdacd0 --- /dev/null +++ b/.cache/clangd/index/test_discrim_tree.cpp.9508FB8B5A477D10.idx diff --git a/.cache/clangd/index/test_prover.cpp.604919AAC374F32C.idx b/.cache/clangd/index/test_prover.cpp.604919AAC374F32C.idx Binary files differnew file mode 100644 index 0000000..f51c118 --- /dev/null +++ b/.cache/clangd/index/test_prover.cpp.604919AAC374F32C.idx diff --git a/.cache/clangd/index/test_resolution.cpp.E785AA54A14F55A5.idx b/.cache/clangd/index/test_resolution.cpp.E785AA54A14F55A5.idx Binary files differnew file mode 100644 index 0000000..4787177 --- /dev/null +++ b/.cache/clangd/index/test_resolution.cpp.E785AA54A14F55A5.idx diff --git a/.cache/clangd/index/test_term_bank.cpp.50AF7E4F3359B770.idx b/.cache/clangd/index/test_term_bank.cpp.50AF7E4F3359B770.idx Binary files differnew file mode 100644 index 0000000..a7b87e9 --- /dev/null +++ b/.cache/clangd/index/test_term_bank.cpp.50AF7E4F3359B770.idx diff --git a/.cache/clangd/index/test_unification.cpp.BA63AEE14AACBCCC.idx b/.cache/clangd/index/test_unification.cpp.BA63AEE14AACBCCC.idx Binary files differnew file mode 100644 index 0000000..17d690c --- /dev/null +++ b/.cache/clangd/index/test_unification.cpp.BA63AEE14AACBCCC.idx diff --git a/.cache/clangd/index/tptp_parser.cpp.50E69F3F47D54605.idx b/.cache/clangd/index/tptp_parser.cpp.50E69F3F47D54605.idx Binary files differnew file mode 100644 index 0000000..2c65a2f --- /dev/null +++ b/.cache/clangd/index/tptp_parser.cpp.50E69F3F47D54605.idx diff --git a/.cache/clangd/index/unification.cpp.FAE8F2832CAC7DB0.idx b/.cache/clangd/index/unification.cpp.FAE8F2832CAC7DB0.idx Binary files differnew file mode 100644 index 0000000..ed348bb --- /dev/null +++ b/.cache/clangd/index/unification.cpp.FAE8F2832CAC7DB0.idx diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..64f782a --- /dev/null +++ b/.clang-format @@ -0,0 +1,62 @@ +--- +Language: Cpp +BasedOnStyle: Google + +# Indentation +IndentWidth: 4 +TabWidth: 4 +UseTab: Never +AccessModifierOffset: -2 +NamespaceIndentation: None +IndentCaseLabels: true + +# Line width +ColumnLimit: 100 + +# Braces +BreakBeforeBraces: Attach +AllowShortFunctionsOnASingleLine: Inline +AllowShortIfStatementsOnASingleLine: Never +AllowShortLoopsOnASingleLine: false +AllowShortBlocksOnASingleLine: Empty + +# Includes +SortIncludes: CaseSensitive +IncludeBlocks: Regroup +IncludeCategories: + # Project headers + - Regex: '^"atp/' + Priority: 1 + # System / C++ standard headers + - Regex: '^<' + Priority: 2 + # Catch-all + - Regex: '.*' + Priority: 3 + +# Alignment +AlignAfterOpenBracket: Align +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +AlignOperands: Align +AlignTrailingComments: true + +# Spacing +SpaceAfterCStyleCast: false +SpaceAfterTemplateKeyword: true +SpaceBeforeAssignmentOperators: true +SpaceBeforeParens: ControlStatements +SpacesInAngles: Never + +# Pointer alignment +PointerAlignment: Left +ReferenceAlignment: Left +DerivePointerAlignment: false + +# Other +ReflowComments: true +FixNamespaceComments: true +CompactNamespaces: false +AllowAllParametersOfDeclarationOnNextLine: true +BinPackArguments: true +BinPackParameters: true diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 0000000..227c129 --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,68 @@ +--- +# ATP Engine clang-tidy configuration +# +# Enable categories incrementally — start strict on the code we write, +# avoid noise from auto-generated code (ANTLR4). + +Checks: > + -*, + bugprone-*, + -bugprone-easily-swappable-parameters, + clang-analyzer-*, + cppcoreguidelines-*, + -cppcoreguidelines-avoid-magic-numbers, + -cppcoreguidelines-pro-type-reinterpret-cast, + -cppcoreguidelines-pro-bounds-pointer-arithmetic, + -cppcoreguidelines-owning-memory, + misc-*, + -misc-non-private-member-variables-in-classes, + modernize-*, + -modernize-use-trailing-return-type, + performance-*, + readability-*, + -readability-magic-numbers, + -readability-identifier-length, + +WarningsAsErrors: '' + +HeaderFilterRegex: 'include/atp/.*\.h$' + +CheckOptions: + - key: readability-identifier-naming.NamespaceCase + value: lower_case + - key: readability-identifier-naming.ClassCase + value: CamelCase + - key: readability-identifier-naming.StructCase + value: CamelCase + - key: readability-identifier-naming.FunctionCase + value: camelBack + - key: readability-identifier-naming.VariableCase + value: lower_case + - key: readability-identifier-naming.MemberCase + value: lower_case + - key: readability-identifier-naming.MemberSuffix + value: '_' + - key: readability-identifier-naming.ConstantCase + value: CamelCase + - key: readability-identifier-naming.ConstantPrefix + value: k + - key: readability-identifier-naming.EnumConstantCase + value: CamelCase + - key: readability-identifier-naming.EnumConstantPrefix + value: k + - key: readability-identifier-naming.ConstexprVariableCase + value: CamelCase + - key: readability-identifier-naming.ConstexprVariablePrefix + value: k + - key: readability-identifier-naming.GlobalConstantCase + value: CamelCase + - key: readability-identifier-naming.GlobalConstantPrefix + value: k + - key: readability-identifier-naming.TemplateParameterCase + value: CamelCase + - key: performance-move-const-arg.CheckTriviallyCopyableMove + value: false + - key: cppcoreguidelines-special-member-functions.AllowSoleDefaultDtor + value: true + - key: readability-function-cognitive-complexity.Threshold + value: 25 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7242ee6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +# Build +build/ +cmake-build-*/ +compile_commands.json + +# IDE +.vscode/ +.idea/ +*.swp +*~ + +# OS +.DS_Store +Thumbs.db diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..2cf69db --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,102 @@ +cmake_minimum_required(VERSION 3.20) +project(atp_engine + VERSION 0.1.0 + LANGUAGES CXX +) + +# ─── C++ Standard ──────────────────────────────────────────────────────────── +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +# Export compile_commands.json for clang-tidy and IDE support +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) + +# ─── Compiler Warnings ────────────────────────────────────────────────────── +add_compile_options( + -Wall -Wextra -Wpedantic + -Wshadow -Wnon-virtual-dtor + -Wold-style-cast -Wcast-align -Wunused + -Woverloaded-virtual -Wconversion -Wsign-conversion + -Wnull-dereference -Wdouble-promotion + -Wformat=2 -Wimplicit-fallthrough +) + +# ─── Sanitizers (Debug builds) ─────────────────────────────────────────────── +option(ATP_ENABLE_SANITIZERS "Enable ASan + UBSan in Debug builds" ON) +if(ATP_ENABLE_SANITIZERS AND CMAKE_BUILD_TYPE STREQUAL "Debug") + add_compile_options(-fsanitize=address,undefined -fno-omit-frame-pointer) + add_link_options(-fsanitize=address,undefined) +endif() + +# ─── clang-tidy Integration ───────────────────────────────────────────────── +option(ATP_ENABLE_CLANG_TIDY "Enable clang-tidy static analysis" OFF) +if(ATP_ENABLE_CLANG_TIDY) + find_program(CLANG_TIDY_EXE NAMES clang-tidy) + if(CLANG_TIDY_EXE) + set(CMAKE_CXX_CLANG_TIDY "${CLANG_TIDY_EXE}") + message(STATUS "clang-tidy found: ${CLANG_TIDY_EXE}") + else() + message(WARNING "clang-tidy requested but not found") + endif() +endif() + +# ─── clang-format Custom Target ───────────────────────────────────────────── +find_program(CLANG_FORMAT_EXE NAMES clang-format) +if(CLANG_FORMAT_EXE) + file(GLOB_RECURSE ALL_CXX_SOURCES + ${PROJECT_SOURCE_DIR}/src/*.cc + ${PROJECT_SOURCE_DIR}/include/*.h + ${PROJECT_SOURCE_DIR}/tests/*.cc + ) + add_custom_target(format + COMMAND ${CLANG_FORMAT_EXE} -i ${ALL_CXX_SOURCES} + COMMENT "Running clang-format on all source files" + VERBATIM + ) + add_custom_target(format-check + COMMAND ${CLANG_FORMAT_EXE} --dry-run --Werror ${ALL_CXX_SOURCES} + COMMENT "Checking clang-format compliance" + VERBATIM + ) + message(STATUS "clang-format found: ${CLANG_FORMAT_EXE}") + message(STATUS " Use 'cmake --build . --target format' to auto-format") + message(STATUS " Use 'cmake --build . --target format-check' to check format") +else() + message(WARNING "clang-format not found, format targets disabled") +endif() + +# ─── Source Files ──────────────────────────────────────────────────────────── +set(ATP_SOURCES + src/core/symbol_table.cc + src/core/term_bank.cc + src/core/clause_store.cc + src/normalize/clausifier.cc + src/infer/unification.cc + src/infer/resolution.cc + src/index/discrim_tree.cc + src/simplify/subsumption.cc + src/search/prover.cc + src/proof/proof_trace.cc + src/rewrite/ordering.cc + src/rewrite/paramodulation.cc + src/strategy/problem_analyzer.cc + src/frontend/tptp_parser.cc +) + +# ─── Core Library ──────────────────────────────────────────────────────────── +add_library(atp_core STATIC ${ATP_SOURCES}) +target_include_directories(atp_core PUBLIC + ${PROJECT_SOURCE_DIR}/include +) + +# ─── Main Executable ──────────────────────────────────────────────────────── +add_executable(atp src/main.cc) +target_link_libraries(atp PRIVATE atp_core) + +# ─── Tests ─────────────────────────────────────────────────────────────────── +option(ATP_BUILD_TESTS "Build unit tests" ON) +if(ATP_BUILD_TESTS) + enable_testing() + add_subdirectory(tests) +endif() @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<https://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<https://www.gnu.org/licenses/why-not-lgpl.html>. diff --git a/README.md b/README.md new file mode 100644 index 0000000..ac0ccd6 --- /dev/null +++ b/README.md @@ -0,0 +1,49 @@ +# ATP Engine + +A saturation-based automated theorem prover for first-order logic, written in C++20. + +## Overview + +ATP Engine implements the **Given Clause Loop** (Otter/E-style) with hash-consed term sharing, discrimination tree indexing, and pluggable search heuristics. It reads problems in [TPTP](https://www.tptp.org/) format and produces human-readable proofs via resolution and factoring. + +The architecture is designed for extensibility toward equality reasoning (superposition), sorted logic, and theory integration. See [`docs/architecture.md`](docs/architecture.md) for full design documentation. + +## Build + +Requires CMake 3.20+ and a C++20 compiler (GCC 11+ / Clang 14+). + +```bash +cmake -B build -DCMAKE_BUILD_TYPE=Debug +cmake --build build -j$(nproc) +``` + +### Options + +| Flag | Default | Description | +|------|---------|-------------| +| `ATP_ENABLE_CLANG_TIDY` | `OFF` | Run clang-tidy during compilation | +| `ATP_ENABLE_SANITIZERS` | `ON` | ASan + UBSan in Debug builds | +| `ATP_BUILD_TESTS` | `ON` | Build GoogleTest unit tests | + +### Format & Lint + +```bash +cmake --build build --target format # auto-format all sources +cmake --build build --target format-check # check format compliance +``` + +## Run + +```bash +./build/atp data/monkey_banana.p +``` + +## Test + +```bash +cd build && ctest --output-on-failure +``` + +## License + +This project is licensed under the [GNU General Public License v3.0](https://www.gnu.org/licenses/gpl-3.0.html). Also see [LICENSE](LICENSE) diff --git a/data/monkey_banana.p b/data/monkey_banana.p new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/data/monkey_banana.p diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..333fa99 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,630 @@ +# ATP Engine — Architecture Design Document + +> **Version**: 1.0 +> **Target**: Extensible first-order logic theorem prover (saturation-based) +> **Language**: C++20 +> **Build**: CMake 3.20+, GoogleTest, ANTLR4 (C++ target) + +--- + +## Table of Contents + +1. [Design Philosophy](#1-design-philosophy) +2. [System Architecture](#2-system-architecture) +3. [Directory Structure](#3-directory-structure) +4. [Module Specifications](#4-module-specifications) +5. [Data Flow](#5-data-flow) +6. [Known Limitations & Future Work](#6-known-limitations--future-work) +7. [References](#7-references) + +--- + +## 1. Design Philosophy + +### 1.1 Core Principles + +| Principle | Rationale | +|-----------|-----------| +| **Bottom-up construction** | Build from the memory layer upward. A stable Term Bank is the foundation everything else rests on. | +| **Strict layered dependencies** | Dependencies flow in one direction only: `core → infer → index → simplify → search → proof`. No cycles. | +| **Interface-implementation separation** | Headers in `include/atp/` define interfaces; `src/` contains implementations. Modules communicate through stable APIs. | +| **Premature abstraction avoidance** | V1 hardcodes resolution + factoring. Abstract strategy selection (`strategy/`) is scaffolded but not wired in until V2. | +| **Parse once, reason forever** | Text parsing (ANTLR4) is a one-shot frontend concern. The core engine operates entirely on integer IDs, never on strings. | + +### 1.2 Design Influences + +This architecture draws from three production-grade theorem provers: + +- **E Prover** (Stephan Schulz) — Given Clause Loop, term sharing via hash consing, age-weight clause selection. +- **Vampire** (Andrei Voronkov et al.) — AVATAR splitting, superposition calculus, discrimination tree indexing. +- **Otter** (William McCune) — Original set-of-support strategy, subsumption, demodulation. + +### 1.3 Versioning Strategy + +``` +V1 → Pure first-order resolution (no equality). Solve the Monkey-Banana problem. +V2 → Pluggable inference rules (Calculus), age-weight scheduling, variable standardization. +V3 → Equality reasoning (paramodulation/superposition), term orderings (KBO/LPO). +V4 → AVATAR splitting, SAT solver integration, TPTP competition readiness. +``` + +--- + +## 2. System Architecture + +### 2.1 Layered Architecture Overview + +``` +┌──────────────────────────────────────────────────────────────────────┐ +│ Frontend Layer │ +│ TPTP File → ANTLR4 Lexer/Parser → AST Builder → tptp_parser.h │ +└────────────────────────────────┬─────────────────────────────────────┘ + │ Formula (internal AST) +┌────────────────────────────────▼─────────────────────────────────────┐ +│ Normalization Layer │ +│ formula.h → clausifier.h (NNF → Skolem → CNF) │ +└────────────────────────────────┬─────────────────────────────────────┘ + │ Clause set +┌────────────────────────────────▼─────────────────────────────────────┐ +│ Search Layer (Control) │ +│ │ +│ ┌──────────────┐ select ┌─────────────────┐ resolve with all │ +│ │ Unprocessed │─────────→ │ Given Clause │─────────────────→ │ +│ │ (pri queue) │ │ (selected) │ │ +│ └──────▲───────┘ └─────────────────┘ │ +│ │ enqueue survivors │ +│ ┌──────┴───────┐ ┌─────────────────┐ │ +│ │ Simplify & │←──────────│ New Clauses │ │ +│ │ Filter │ │ (resolvents) │ │ +│ └──────────────┘ └─────────────────┘ │ +│ │ if empty clause found │ +└──────────┼───────────────────────────────────────────────────────────┘ + ▼ +┌──────────────────────────────────────────────────────────────────────┐ +│ Output Layer │ +│ proof_trace.h → DFS backtrack → format & print action sequence │ +└──────────────────────────────────────────────────────────────────────┘ + +═══════════════════════ Shared Foundation ══════════════════════════════ +┌──────────────────────────────────────────────────────────────────────┐ +│ Core Layer (Data Plane) │ +│ Symbol Table │ Term Bank (hash consing) │ Clause Store │ Types │ +└──────────────────────────────────────────────────────────────────────┘ +``` + +### 2.2 Dependency Graph + +``` +frontend ──→ normalize ──→ core + ↑ +search ──→ simplify ──→ index ──→ infer ──→ core + ↑ + rewrite ─┘ + proof ──→ core/clause_store + + strategy/ ──→ (V2: wired into search) +``` + +All arrows point downward/inward. `proof` depends only on `clause_store`, not on `search` (no reverse dependency). + +--- + +## 3. Directory Structure + +``` +richard-atp-engine/ +├── CMakeLists.txt # Top-level build (C++20, clang-tidy, clang-format, sanitizers) +├── .clang-format # Google-based, 4-space indent, 100-col +├── .clang-tidy # Strict checks, filtered for generated code +├── .gitignore +│ +├── grammar/ +│ └── TPTP.g4 # ANTLR4 grammar for TPTP fof/cnf syntax +│ +├── docs/ +│ └── architecture.md # This document +│ +├── data/ +│ └── monkey_banana.p # First integration test (TPTP format) +│ +├── include/atp/ +│ ├── core/ # Data plane — memory foundation +│ │ ├── types.h # TermId, ClauseId, SymbolId, SortId, SymbolKind, InferenceRule +│ │ ├── symbol_table.h # String interning with kind/sort metadata +│ │ ├── term.h # Flat term struct (symbol_id + args) +│ │ ├── literal.h # Polarity + atom TermId +│ │ ├── clause.h # Literal vector + provenance (parents, rule, depth) +│ │ ├── clause_store.h # Central clause ownership, ClauseId allocation +│ │ └── term_bank.h # Hash-consing pool for structural sharing +│ │ +│ ├── normalize/ # Normalization — FOL formula to CNF +│ │ ├── formula.h # FOL AST nodes (And, Or, Not, Forall, Exists, ...) +│ │ └── clausifier.h # Eliminate →/↔ → NNF → Skolemize → distribute → flatten +│ │ +│ ├── infer/ # Compute plane — stateless inference operators +│ │ ├── substitution.h # Variable binding map (stack-lifetime) +│ │ ├── unification.h # MGU with optional occurs check +│ │ └── resolution.h # Binary resolution + factoring +│ │ +│ ├── index/ # Index plane — fast term retrieval +│ │ └── discrim_tree.h # Discrimination tree (unifiable / instance / generalization queries) +│ │ +│ ├── simplify/ # Redundancy elimination +│ │ ├── tautology.h # Complementary literal detection +│ │ └── subsumption.h # Forward/backward subsumption (backed by discrim tree) +│ │ +│ ├── search/ # Control plane — proof search scheduling +│ │ ├── clause_queue.h # Comparators (BFS, weight-based) +│ │ └── prover.h # Given Clause Loop (V1: hardcoded rules; V2: Calculus-driven) +│ │ +│ ├── proof/ # Output — proof reconstruction +│ │ └── proof_trace.h # DFS backtrack from empty clause, formatting +│ │ +│ ├── rewrite/ # Equality reasoning (V3 extension point) +│ │ ├── ordering.h # Abstract TermOrdering (KBO, LPO) +│ │ └── paramodulation.h # Paramodulation + demodulation +│ │ +│ ├── strategy/ # Dynamic algorithm selection (V2 extension point) +│ │ ├── inference_rule.h # GeneratingRule / SimplifyingRule interfaces +│ │ ├── calculus.h # Bundles rules + heuristics + ordering +│ │ └── problem_analyzer.h # Feature detection + calculus selection +│ │ +│ └── utils/ +│ ├── hash_utils.h # Hash combination (boost::hash_combine equivalent) +│ └── logger.h # Compile-time-filtered logging macros +│ +├── src/ # Implementation files (mirror include/ structure) +│ ├── core/ +│ ├── normalize/ +│ ├── infer/ +│ ├── index/ +│ ├── simplify/ +│ ├── search/ +│ ├── proof/ +│ ├── rewrite/ +│ ├── strategy/ +│ ├── frontend/ +│ └── main.cpp +│ +└── tests/ # GoogleTest unit tests + ├── CMakeLists.txt + ├── test_term_bank.cc + ├── test_unification.cc + ├── test_clausifier.cc + ├── test_resolution.cc + ├── test_discrim_tree.cc + └── test_prover.cc # End-to-end: Monkey-Banana problem +``` + +--- + +## 4. Module Specifications + +### 4.1 Core Layer (`core/`) + +The core layer owns all persistent data. Every other module receives `const&` or `&` references to core objects — never raw pointers, never ownership. + +#### `types.h` — Type System Foundation + +```cpp +using SymbolId = uint32_t; // Index into SymbolTable +using TermId = uint32_t; // Index into TermBank (hash-consed) +using ClauseId = uint32_t; // Index into ClauseStore +using SortId = uint16_t; // For sorted logic (V3+), default = kUnsorted + +enum class SymbolKind : uint8_t { + kVariable, kConstant, kFunction, kPredicate, kSkolem +}; + +enum class InferenceRule : uint16_t { + kInput = 0, kResolution = 1, kFactoring = 2, // Core + kParamodulation = 100, kDemodulation = 101, ... // Equality (V3) + kSubsumption = 200, kTautologyElim = 201, ... // Simplification + kTheoryResolution = 300, ... // Theory (V4) +}; +``` + +**Design decisions**: +- `uint32_t` IDs instead of pointers — enables flat array storage, trivial comparison, and cache-friendly iteration. +- `InferenceRule` uses `uint16_t` with reserved ranges (0-99 core, 100-199 equality, 200-299 simplification, 300+ theory) to avoid enum churn as the system grows. +- `SymbolKind` enables distinguishing variables from function symbols at the symbol level, critical for unification and sorted logic. +- `SortId` is present but unused in V1 (`kUnsorted`), ready for sorted unification in V3. + +#### `symbol_table.h` — String Interning + +```cpp +struct SymbolInfo { + std::string name; + SymbolKind kind; + uint16_t arity; + SortId sort; +}; + +class SymbolTable { + SymbolId intern(string_view name, SymbolKind kind, uint16_t arity, SortId sort); + string_view getName(SymbolId id) const; + const SymbolInfo& getInfo(SymbolId id) const; + bool isVariable(SymbolId id) const; +}; +``` + +Each unique symbol string is stored exactly once. All downstream modules work with `SymbolId` integers. The `SymbolInfo` metadata (kind, arity, sort) enables type-checking during unification without string inspection. + +#### `term_bank.h` — Hash Consing + +```cpp +class TermBank { + TermId makeTerm(SymbolId symbol, span<const TermId> args); + TermId makeVar(SymbolId var_symbol); + const Term& getTerm(TermId id) const; + bool isVariable(TermId id) const; +}; +``` + +**Hash consing guarantee**: If `makeTerm(f, {a, b})` is called twice with the same `f`, `a`, `b`, it returns the same `TermId`. This makes structural equality a single integer comparison (`O(1)`), which is the foundation for efficient indexing and subsumption. + +**Memory layout**: Terms are stored in a flat arena. Each `Term` header (`symbol_id` + `arity`) is followed by its argument `TermId` array in contiguous memory. No heap allocation per term. + +#### `clause_store.h` — Clause Ownership + +```cpp +class ClauseStore { + ClauseId addClause(Clause clause); + const Clause& getClause(ClauseId id) const; + Clause& getMutableClause(ClauseId id); + void forEach(const function<void(const Clause&)>& visitor) const; +}; +``` + +Separated from `Prover` so that proof extraction, simplification, and search all access clauses through the same stable interface. Changing the search strategy (OTTER loop → DISCOUNT loop) does not affect clause storage. + +--- + +### 4.2 Normalization Layer (`normalize/`) + +#### `formula.h` — First-Order Logic AST + +```cpp +enum class FormulaKind : uint8_t { + kAtom, kNot, kAnd, kOr, kImplies, kIff, kForall, kExists +}; + +struct Formula { + FormulaKind kind; + TermId atom; // for kAtom + string var_name; // for quantifiers + vector<unique_ptr<Formula>> children; // sub-formulas +}; +``` + +This is the **pre-clausification** representation. The parser builds `Formula` trees; the clausifier destroys them and produces `Clause` vectors. Formula nodes are short-lived — they exist only during the normalization phase. + +#### `clausifier.h` — CNF Conversion Pipeline + +``` +Input Formula + │ + ▼ eliminateImplication() — P → Q becomes ¬P ∨ Q + ▼ eliminateBiconditional() — P ↔ Q becomes (¬P ∨ Q) ∧ (P ∨ ¬Q) + ▼ pushNegation() — ¬(P ∧ Q) becomes ¬P ∨ ¬Q (NNF) + ▼ skolemize() — ∀x∃y.P(x,y) becomes ∀x.P(x, sk(x)) + ▼ dropUniversal() — All remaining vars are implicitly ∀ + ▼ distribute() — (P ∨ (Q ∧ R)) becomes (P ∨ Q) ∧ (P ∨ R) + ▼ flatten() — Nested ∧ at top level → separate clauses + │ + ▼ +Output: vector<Clause> +``` + +**Critical**: `skolemize()` must correctly handle nested quantifier scopes. Given `∀x ∃y ∀z ∃w. P(x,y,z,w)`, the Skolem functions are `y = sk1(x)` and `w = sk2(x, z)` — each existential variable becomes a function of all universally quantified variables in its scope. + +--- + +### 4.3 Inference Layer (`infer/`) + +#### `substitution.h` — Variable Bindings + +A substitution `σ = {X → f(a), Y → Z}` maps variables to terms. Key properties: + +- **Stack lifetime**: Created during unification, applied to build the resolvent, then discarded. Never stored long-term. +- **Chain resolution**: `resolve(X)` walks the binding chain (`X → Y → f(a)`) to the final value. +- **Idempotence**: After applying a substitution, no variables in the result have bindings in the same substitution. + +#### `unification.h` — Most General Unifier + +```cpp +bool unify(const TermBank& bank, TermId t1, TermId t2, Substitution& subst, + const UnificationConfig& config); +``` + +The Robinson unification algorithm, operating on `TermId` values via the `TermBank`. Returns the Most General Unifier (MGU) if one exists. + +**Occurs check**: Configurable via `UnificationConfig::enable_occurs_check`. Disabled for situation calculus planning (performance); enabled for general mathematical reasoning (soundness — prevents infinite terms like `X = f(X)`). + +#### `resolution.h` — Inference Rules + +```cpp +optional<Clause> resolve(bank, clause1, lit_idx1, clause2, lit_idx2); +vector<Clause> allResolvents(bank, clause1, clause2); +vector<Clause> factor(bank, clause); +``` + +**Binary resolution**: Given clauses `{P(x), Q(x)}` and `{¬P(a), R(a)}`, if `P(x)` and `P(a)` unify under `σ = {x→a}`, produce resolvent `{Q(a), R(a)}`. + +**Factoring**: Given clause `{P(x), P(a), Q(x)}`, if `P(x)` and `P(a)` unify, produce `{P(a), Q(a)}`. Factoring is necessary for completeness of binary resolution. + +--- + +### 4.4 Index Layer (`index/`) + +#### `discrim_tree.h` — Discrimination Tree + +A trie-based index over the flattened structure of terms. Supports three query types: + +| Query | Use Case | Direction | +|-------|----------|-----------| +| `queryUnifiable(t)` | Find resolution partners | Bidirectional matching | +| `queryInstances(t)` | Backward subsumption | Pattern more general than indexed | +| `queryGeneralizations(t)` | Forward subsumption | Indexed more general than query | + +The tree is built by linearizing terms in pre-order: `f(g(a), b)` becomes the key sequence `[f, g, a, *, b]` where `*` represents a variable (wildcard). Lookups traverse the trie, branching at decision points. + +--- + +### 4.5 Simplification Layer (`simplify/`) + +#### `tautology.h` + +Detects clauses containing both `P` and `¬P` for the same atom. These are logically true and can be safely discarded without affecting completeness. + +#### `subsumption.h` + +Backed by the discrimination tree. Two operations: + +- **Forward subsumption**: Before enqueuing a new clause `C`, check if any existing clause `D` subsumes it (`D ⊆ C` — every literal of `D` matches a literal of `C`). If yes, discard `C`. +- **Backward subsumption**: After adding `C`, check if `C` subsumes any existing clause `D`. If yes, remove `D`. + +Subsumption is the single most important simplification rule for keeping the clause set manageable. + +--- + +### 4.6 Search Layer (`search/`) + +#### `prover.h` — The Given Clause Loop + +The main proof search loop, following the OTTER/E paradigm: + +``` +procedure GivenClauseLoop(initial_clauses): + Unprocessed ← priority_queue(initial_clauses) + Processed ← empty_set + + while Unprocessed is not empty: + given ← Unprocessed.pop() // clause selection + + if given is tautology: continue + if given is forward-subsumed: continue + + // Backward simplification + remove from Processed all clauses subsumed by given + + // Inference + for each clause C in Processed: + for each resolvent R of (given, C): + if R is empty clause: RETURN PROOF FOUND + if R is not tautology and not forward-subsumed: + Unprocessed.push(R) + + // Generate factors of given + for each factor F of given: + if F is empty clause: RETURN PROOF FOUND + Unprocessed.push(F) + + Processed.add(given) + + RETURN SATURATED (no proof exists) +``` + +**V1 configuration**: +```cpp +struct ProverConfig { + ClauseComparator comparator = bfsCompare; // BFS for shortest proof + size_t max_clauses = 100000; + size_t max_iterations = 500000; + bool enable_occurs_check = false; +}; +``` + +--- + +### 4.7 Proof Layer (`proof/`) + +#### `proof_trace.h` + +When the empty clause `□` is derived, the prover halts. Proof extraction walks the `parent1`/`parent2` pointers stored in each `Clause` via DFS, reconstructing the derivation tree from `□` back to input axioms. + +The output is a sequence of `ProofStep` records, each containing the inference rule used and the parent clause IDs. This can be formatted as a human-readable proof or (future) TSTP-compliant output. + +--- + +### 4.8 Extension Point: Rewriting (`rewrite/`) + +Scaffolded for V3. Not compiled in V1. + +#### `ordering.h` — Abstract Term Ordering + +```cpp +class TermOrdering { + virtual OrderResult compare(const TermBank& bank, TermId t1, TermId t2) const = 0; +}; +``` + +Concrete implementations (future): Knuth-Bendix Ordering (KBO), Lexicographic Path Ordering (LPO). These are required for ordered resolution and superposition calculus — they ensure that rewriting always terminates. + +#### `paramodulation.h` — Equality Reasoning + +Paramodulation replaces a subterm in one clause with an equal term from another. Combined with a term ordering, this becomes the **superposition calculus** — the dominant approach for first-order logic with equality. + +--- + +### 4.9 Extension Point: Strategy (`strategy/`) + +Scaffolded for V2. Not compiled in V1. + +The strategy module will enable dynamic algorithm selection based on problem analysis: + +``` +Input clauses → ProblemAnalyzer → ProblemFeatures → selectCalculus() → Calculus + │ + ┌────────────────────────────────────────────────┘ + ▼ + Calculus = { generating_rules[], simplifying_rules[], + comparator, ordering, resource_limits } + │ + ▼ + Prover.prove(calculus) +``` + +This prevents search space explosion by loading only the inference rules relevant to the problem. A pure propositional problem would never load the paramodulation rule; an equality-heavy problem would skip pure resolution in favor of superposition. + +--- + +## 5. Data Flow + +### 5.1 End-to-End Pipeline + +``` +monkey_banana.p (TPTP text file) + │ + ▼ + [tptp_parser] ANTLR4 lexer/parser → parse tree → Formula AST + │ + ▼ + [clausifier] NNF → Skolemize → CNF → vector<Clause> + │ + ▼ + [prover] Given Clause Loop (resolution + factoring + subsumption) + │ + ├── Normal: derive new clauses, enqueue, repeat + │ + └── Empty clause found! + │ + ▼ + [proof_trace] DFS backtrack through parent pointers + │ + ▼ + Human-readable proof output +``` + +### 5.2 Term Lifecycle + +``` +String "do(walk, S0)" + │ + ▼ SymbolTable::intern() + SymbolIds: { do=0, walk=1, S0=2 } + │ + ▼ TermBank::makeTerm() + TermIds: S0_term=0, walk_term=1, do_walk_S0=2 + │ (hash-consed: calling makeTerm(do, [walk, S0]) again returns 2) + │ + ▼ Used everywhere as integer IDs + Clause { literals: [ Literal{atom=2, positive=true} ] } +``` + +### 5.3 Substitution Lifecycle + +``` +Unify( P(X, f(Y)), P(a, f(b)) ) + │ + ▼ unify() creates stack-local Substitution + σ = { X → a, Y → b } + │ + ▼ Apply σ to build resolvent clause + New terms created in TermBank (hash-consed) + │ + ▼ Substitution goes out of scope — destroyed + Only the new TermIds persist +``` + +--- + +## 6. Known Limitations & Future Work + +### 6.1 Critical Gaps (Ordered by Priority) + +#### Gap 1: No Variable Standardization Apart + +**Impact**: Correctness bug if not addressed before first real resolution. + +When resolving clause `{P(X)}` with clause `{¬P(X), Q(X)}`, variable `X` in the two clauses must be treated as distinct. Without renaming one clause's variables (e.g., `X → X'`), the unifier incorrectly constrains both clauses' variables. + +**Fix**: Add `renameVariables(Clause&, TermBank&, uint32_t& next_var_id)` to `infer/` before Phase 2 resolution implementation. + +#### Gap 2: No Literal Selection Function + +**Impact**: Search space is ~10x larger than necessary. + +Ordered resolution restricts inference to the **maximal literal** (under a term ordering) in each clause. Our `Prover` currently has no concept of selecting which literal to resolve on — it tries all pairs. + +**Fix**: V2 — add `LiteralSelector` interface, parameterized by `TermOrdering`. + +#### Gap 3: Single Clause Queue (No Age-Weight Interleaving) + +**Impact**: Incomplete or extremely slow on hard problems. + +A single `ClauseComparator` cannot implement the age-weight ratio that E Prover uses: "pick the lightest clause 5 times, then the oldest clause once." This interleaving is crucial for both performance and completeness. + +**Fix**: V2 — replace `ClauseComparator` with a `ClauseQueue` abstract class supporting multi-queue round-robin. + +#### Gap 4: Single Index Type + +**Impact**: Suboptimal retrieval performance. + +The discrimination tree handles forward matching well but is not ideal for all query patterns. Modern ATPs maintain multiple complementary indices: + +| Index Type | Best For | +|-----------|----------| +| Discrimination Tree | Forward matching (generalization queries) | +| Substitution Tree | Backward matching + unification candidates | +| Fingerprint Index | O(1) pre-filtering of non-unifiable pairs | +| Feature Vector Index | Clause-level subsumption checks | + +**Fix**: V3 — abstract `TermIndex` interface, multiple implementations. + +#### Gap 5: No Preprocessing Pipeline + +**Impact**: Missed optimization opportunities. + +Between clausification and the main loop, modern ATPs perform definition unfolding, pure literal elimination, equality axiom injection, and miniscoping. Our `normalize/` layer has only the clausifier. + +**Fix**: V2 — extend `normalize/` into a transform pipeline with pluggable passes. + +#### Gap 6: No AVATAR Splitting + +**Impact**: Cannot compete on structured problems. + +AVATAR splits clauses with independent variable sets into propositional components managed by an embedded SAT solver. This is the single largest performance innovation in ATP in the last decade (10-100x speedup on structured problems). + +**Fix**: V4 — add `sat/` module with MiniSat/CaDiCaL integration + splitting logic in `search/`. + +### 6.2 Non-Critical Gaps + +| Gap | Category | Target Version | +|-----|----------|----------------| +| TSTP proof output format | Interoperability | V2 | +| Watched literals for unit propagation | Performance | V3 | +| Clause arena (replace `vector<Literal>`) | Memory | V3 | +| ML-guided clause selection | Research | V5+ | +| Parallel portfolio mode | Performance | V5+ | + +--- + +## 7. References + +1. Schulz, S. (2013). *System Description: E 1.8*. CADE-24. +2. Kovács, L., Voronkov, A. (2013). *First-Order Theorem Proving and Vampire*. CAV 2013. +3. Voronkov, A. (2014). *AVATAR: The Architecture for First-Order Theorem Provers*. CAV 2014. +4. Nieuwenhuis, R., Rubio, A. (2001). *Paramodulation-Based Theorem Proving*. Handbook of Automated Reasoning. +5. Sutcliffe, G. (2009). *The TPTP Problem Library and Associated Infrastructure*. Journal of Automated Reasoning. +6. Robinson, J.A. (1965). *A Machine-Oriented Logic Based on the Resolution Principle*. JACM. diff --git a/grammar/TPTP.g4 b/grammar/TPTP.g4 new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/grammar/TPTP.g4 diff --git a/include/atp/core/clause.h b/include/atp/core/clause.h new file mode 100644 index 0000000..b4d3e68 --- /dev/null +++ b/include/atp/core/clause.h @@ -0,0 +1,53 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + +#pragma once + +/// @file clause.h +/// @brief A clause is a disjunction of literals, with provenance tracking. +/// +/// NOTE: V1 uses std::vector<Literal> for simplicity. +/// Future optimization: migrate to a Clause Arena with contiguous storage. + +#include <vector> + +#include "atp/core/literal.h" +#include "atp/core/types.h" + +namespace atp { + +/// A clause: a disjunction of literals plus provenance for proof reconstruction. +struct Clause { + ClauseId id = kInvalidId; + std::vector<Literal> literals; + + // Provenance (for proof trace) + InferenceRule rule = InferenceRule::kInput; + ClauseId parent1 = kInvalidId; + ClauseId parent2 = kInvalidId; + uint16_t depth = 0; ///< Derivation depth (for BFS scheduling) + + /// True if the clause has no literals (contradiction). + [[nodiscard]] bool isEmpty() const { return literals.empty(); } + + /// Number of literals. + [[nodiscard]] size_t size() const { return literals.size(); } +}; + +} // namespace atp diff --git a/include/atp/core/clause_store.h b/include/atp/core/clause_store.h new file mode 100644 index 0000000..6e220cc --- /dev/null +++ b/include/atp/core/clause_store.h @@ -0,0 +1,62 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + +#pragma once + +/// @file clause_store.h +/// @brief Central clause storage — owns all clauses, assigns ClauseIds. +/// +/// Extracted from Prover to separate storage responsibility from search logic. +/// This enables swapping search strategies (OTTER loop / DISCOUNT loop) +/// without touching clause lifecycle management. + +#include "atp/core/clause.h" +#include "atp/core/types.h" + +#include <functional> +#include <vector> + +namespace atp { + +/// Central clause store. Owns all clauses and assigns unique ClauseIds. +/// All modules access clauses through this store via ClauseId references. +class ClauseStore { + public: + ClauseStore() = default; + + /// Add a clause, assign it a ClauseId, and return the ID. + ClauseId addClause(Clause clause); + + /// Access a clause by its ID. UB if id is out of range. + [[nodiscard]] const Clause& getClause(ClauseId id) const; + + /// Mutable access (for marking clauses as deleted, etc.) + [[nodiscard]] Clause& getMutableClause(ClauseId id); + + /// Total number of stored clauses. + [[nodiscard]] size_t size() const; + + /// Iterate over all clauses with a visitor. + void forEach(const std::function<void(const Clause&)>& visitor) const; + + private: + std::vector<Clause> clauses_; +}; + +} // namespace atp diff --git a/include/atp/core/literal.h b/include/atp/core/literal.h new file mode 100644 index 0000000..1b4f65c --- /dev/null +++ b/include/atp/core/literal.h @@ -0,0 +1,40 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + +#pragma once + +/// @file literal.h +/// @brief A literal is a (possibly negated) atomic formula. + +#include "atp/core/types.h" + +namespace atp { + +/// A literal: a polarity flag plus the TermId of the atom. +struct Literal { + TermId atom; ///< TermId of the predicate application + bool is_positive; ///< true = positive, false = negated + + /// Complement: flip polarity, same atom. + [[nodiscard]] Literal complement() const { return {atom, !is_positive}; } + + bool operator==(const Literal& other) const = default; +}; + +} // namespace atp diff --git a/include/atp/core/symbol_table.h b/include/atp/core/symbol_table.h new file mode 100644 index 0000000..ed27a4d --- /dev/null +++ b/include/atp/core/symbol_table.h @@ -0,0 +1,68 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + +#pragma once + +/// @file symbol_table.h +/// @brief Bidirectional mapping between symbol names and SymbolIds, +/// with kind and sort metadata. + +#include <string> +#include <string_view> + +#include "atp/core/types.h" + +namespace atp { + +/// Metadata associated with an interned symbol. +struct SymbolInfo { + std::string name; + SymbolKind kind = SymbolKind::kFunction; + uint16_t arity = 0; + SortId sort = kUnsorted; ///< Result sort (for sorted logic) +}; + +/// Interns symbol names so that each unique string is stored exactly once. +/// Also tracks symbol metadata (kind, arity, sort). +/// Thread-safety: NOT thread-safe (single-threaded prover design). +class SymbolTable { + public: + SymbolTable() = default; + + /// Intern a symbol name with metadata. Returns existing ID if already present. + SymbolId intern(std::string_view name, SymbolKind kind, uint16_t arity = 0, + SortId sort = kUnsorted); + + /// Look up the name for a given SymbolId. UB if id is out of range. + [[nodiscard]] std::string_view getName(SymbolId id) const; + + /// Look up full metadata for a SymbolId. + [[nodiscard]] const SymbolInfo& getInfo(SymbolId id) const; + + /// Check if a symbol is a variable. + [[nodiscard]] bool isVariable(SymbolId id) const; + + /// Number of interned symbols. + [[nodiscard]] size_t size() const; + + private: + // TODO: Phase 1 implementation +}; + +} // namespace atp diff --git a/include/atp/core/term.h b/include/atp/core/term.h new file mode 100644 index 0000000..e1edfcf --- /dev/null +++ b/include/atp/core/term.h @@ -0,0 +1,43 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + +#pragma once + +/// @file term.h +/// @brief Core Term data structure — hash-consed, immutable. + +#include <span> + +#include "atp/core/types.h" + +namespace atp { + +/// A term is a function/predicate application: f(t1, t2, ..., tn). +/// Stored in a flat arena; args are contiguous TermIds following the header. +/// Variables are represented as terms with a special symbol range. +struct Term { + SymbolId symbol_id; ///< Index into the SymbolTable + uint16_t arity; ///< Number of arguments + + /// Access the argument TermIds (stored immediately after this struct in the arena). + [[nodiscard]] std::span<const TermId> args() const; + [[nodiscard]] std::span<TermId> mutableArgs(); +}; + +} // namespace atp diff --git a/include/atp/core/term_bank.h b/include/atp/core/term_bank.h new file mode 100644 index 0000000..a121f8a --- /dev/null +++ b/include/atp/core/term_bank.h @@ -0,0 +1,57 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + +#pragma once + +/// @file term_bank.h +/// @brief Hash-consing term pool — guarantees structural sharing. + +#include "atp/core/term.h" +#include "atp/core/types.h" + +#include <span> + +namespace atp { + +/// Global term pool with hash-consing. +/// Every structurally identical term maps to the same TermId. +class TermBank { + public: + TermBank() = default; + + /// Create or retrieve a term. Returns the canonical TermId. + TermId makeTerm(SymbolId symbol, std::span<const TermId> args); + + /// Create a variable term. + TermId makeVar(SymbolId var_symbol); + + /// Look up a term by its ID. + [[nodiscard]] const Term& getTerm(TermId id) const; + + /// Check if a TermId represents a variable. + [[nodiscard]] bool isVariable(TermId id) const; + + /// Total number of unique terms stored. + [[nodiscard]] size_t size() const; + + private: + // TODO: Phase 1 implementation — flat arena + hash index +}; + +} // namespace atp diff --git a/include/atp/core/types.h b/include/atp/core/types.h new file mode 100644 index 0000000..c68e716 --- /dev/null +++ b/include/atp/core/types.h @@ -0,0 +1,80 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + +#pragma once + +/// @file types.h +/// @brief Core type aliases for the ATP engine. + +#include <cstdint> + +namespace atp { + +/// Unique identifier for an interned symbol (predicate/function/constant name). +using SymbolId = uint32_t; + +/// Unique identifier for a term in the Term Bank (hash-consed). +using TermId = uint32_t; + +/// Unique identifier for a clause in the Clause Store. +using ClauseId = uint32_t; + +/// Unique identifier for a sort/type (for sorted logic). +using SortId = uint16_t; + +/// Sentinel value indicating an invalid / unassigned ID. +inline constexpr uint32_t kInvalidId = UINT32_MAX; + +/// Default sort (unsorted logic). +inline constexpr SortId kUnsorted = 0; + +/// Symbol kind — distinguishes variables from function/predicate symbols. +enum class SymbolKind : uint8_t { + kVariable, ///< Universally quantified variable + kConstant, ///< 0-arity function symbol (constant) + kFunction, ///< Function symbol (arity >= 1) + kPredicate, ///< Predicate symbol (returns bool) + kSkolem, ///< Skolem function/constant (introduced by Skolemization) +}; + +/// Inference rule that produced a clause. +/// Deliberately uses uint16_t for extensibility toward algebra/analysis rules. +enum class InferenceRule : uint16_t { + // ── Core resolution rules ── + kInput = 0, ///< Original input clause (axiom / negated conjecture) + kResolution = 1, ///< Binary resolution + kFactoring = 2, ///< Factoring + + // ── Equality rules (algebra) ── + kParamodulation = 100, ///< Paramodulation (equality resolution) + kDemodulation = 101, ///< Demodulation (simplification by rewriting) + kEqualityResolution = 102, ///< s != t resolved with unifier + kEqualityFactoring = 103, ///< Factoring with equality + + // ── Simplification rules ── + kSubsumption = 200, ///< Removed by subsumption + kTautologyElim = 201, ///< Removed as tautology + kPureLiteralElim = 202, ///< Pure literal elimination + + // ── Theory rules (analysis, arithmetic) ── + kTheoryResolution = 300, ///< Theory-specific resolution + kTheoryRewrite = 301, ///< Theory-driven rewriting +}; + +} // namespace atp diff --git a/include/atp/frontend/tptp_parser.h b/include/atp/frontend/tptp_parser.h new file mode 100644 index 0000000..f43f020 --- /dev/null +++ b/include/atp/frontend/tptp_parser.h @@ -0,0 +1,52 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + +#pragma once + +/// @file tptp_parser.h +/// @brief Bridge from ANTLR4-generated parse tree to internal Formula AST. + +#include "atp/core/clause.h" +#include "atp/core/term_bank.h" +#include "atp/normalize/formula.h" + +#include <string> +#include <vector> + +namespace atp { + +/// Role of a TPTP formula (axiom, hypothesis, conjecture, etc.) +enum class FormulaRole : uint8_t { + kAxiom, + kHypothesis, + kConjecture, + kNegatedConjecture, +}; + +/// A parsed TPTP formula with its name and role. +struct AnnotatedFormula { + std::string name; + FormulaRole role; + std::unique_ptr<Formula> formula; +}; + +/// Parse a TPTP file and return the annotated formulas. +std::vector<AnnotatedFormula> parseTptpFile(const std::string& filepath, TermBank& bank); + +} // namespace atp diff --git a/include/atp/index/discrim_tree.h b/include/atp/index/discrim_tree.h new file mode 100644 index 0000000..8cadaa6 --- /dev/null +++ b/include/atp/index/discrim_tree.h @@ -0,0 +1,77 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + +#pragma once + +/// @file discrim_tree.h +/// @brief Perfect Discrimination Tree for fast term indexing. +/// +/// Used by subsumption and resolution to quickly find candidate clauses +/// whose literals unify with a query term. Supports three query modes: +/// - Unifiable: find terms that can be unified with the query +/// - Instances: find terms that are instances of the query (more specific) +/// - Generalizations: find terms that are generalizations of the query (more general) + +#include "atp/core/clause.h" +#include "atp/core/term_bank.h" +#include "atp/core/types.h" + +#include <vector> + +namespace atp { + +/// A match result from the discrimination tree. +struct IndexMatch { + ClauseId clause_id; + size_t lit_index; +}; + +/// A discrimination tree index over terms. +/// Supports insertion and three types of retrieval queries. +class DiscrimTree { + public: + explicit DiscrimTree(const TermBank& bank); + + /// Insert a term (identified by its TermId) with an associated clause/literal ref. + void insert(TermId term, ClauseId clause_id, size_t lit_index); + + /// Retrieve all entries whose indexed term is unifiable with `query`. + [[nodiscard]] std::vector<IndexMatch> queryUnifiable(TermId query) const; + + /// Retrieve all entries whose indexed term is an instance of `query`. + /// (query is more general, indexed term is more specific) + [[nodiscard]] std::vector<IndexMatch> queryInstances(TermId query) const; + + /// Retrieve all entries whose indexed term is a generalization of `query`. + /// (indexed term is more general, query is more specific) + /// This is the key operation for forward subsumption. + [[nodiscard]] std::vector<IndexMatch> queryGeneralizations(TermId query) const; + + /// Remove all entries for a given clause. + void removeClause(ClauseId clause_id); + + /// Number of indexed entries. + [[nodiscard]] size_t size() const; + + private: + const TermBank& bank_; + // TODO: Phase 3 implementation — trie node arena +}; + +} // namespace atp diff --git a/include/atp/infer/resolution.h b/include/atp/infer/resolution.h new file mode 100644 index 0000000..2d73b06 --- /dev/null +++ b/include/atp/infer/resolution.h @@ -0,0 +1,44 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + +#pragma once + +/// @file resolution.h +/// @brief Binary resolution and factoring inference rules. + +#include "atp/core/clause.h" +#include "atp/core/term_bank.h" + +#include <optional> +#include <vector> + +namespace atp { + +/// Attempt binary resolution between two clauses on the specified literal indices. +/// @return The resolvent clause if resolution succeeds, std::nullopt otherwise. +std::optional<Clause> resolve(const TermBank& bank, const Clause& c1, size_t lit_idx1, + const Clause& c2, size_t lit_idx2); + +/// Generate all possible resolvents between two clauses. +std::vector<Clause> allResolvents(const TermBank& bank, const Clause& c1, const Clause& c2); + +/// Attempt factoring on a single clause (merge two unifiable literals). +std::vector<Clause> factor(const TermBank& bank, const Clause& c); + +} // namespace atp diff --git a/include/atp/infer/substitution.h b/include/atp/infer/substitution.h new file mode 100644 index 0000000..f9f562a --- /dev/null +++ b/include/atp/infer/substitution.h @@ -0,0 +1,54 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + +#pragma once + +/// @file substitution.h +/// @brief Variable binding map: Var -> Term. + +#include "atp/core/types.h" + +#include <vector> + +namespace atp { + +/// A substitution is a mapping from variable TermIds to their bound TermIds. +/// Designed as a short-lived, stack-allocated object during unification. +class Substitution { + public: + Substitution() = default; + + /// Bind a variable to a term. Returns false if already bound to something different. + bool bind(TermId var, TermId term); + + /// Look up what a variable is bound to. Returns kInvalidId if unbound. + [[nodiscard]] TermId lookup(TermId var) const; + + /// Walk the binding chain to the final bound value. + [[nodiscard]] TermId resolve(TermId id) const; + + /// Clear all bindings. + void clear(); + + private: + // TODO: Phase 2 implementation + std::vector<std::pair<TermId, TermId>> bindings_; +}; + +} // namespace atp diff --git a/include/atp/infer/unification.h b/include/atp/infer/unification.h new file mode 100644 index 0000000..7d91aaf --- /dev/null +++ b/include/atp/infer/unification.h @@ -0,0 +1,40 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + +#pragma once + +/// @file unification.h +/// @brief Most General Unifier (MGU) computation. + +#include "atp/core/term_bank.h" +#include "atp/infer/substitution.h" + +namespace atp { + +/// Configuration for the unification algorithm. +struct UnificationConfig { + bool enable_occurs_check = false; ///< Set true for sound but slower unification +}; + +/// Attempt to unify two terms, producing a most general unifier. +/// @return true if unification succeeds, with the MGU in `subst`. +bool unify(const TermBank& bank, TermId t1, TermId t2, Substitution& subst, + const UnificationConfig& config = {}); + +} // namespace atp diff --git a/include/atp/normalize/clausifier.h b/include/atp/normalize/clausifier.h new file mode 100644 index 0000000..1ff4d27 --- /dev/null +++ b/include/atp/normalize/clausifier.h @@ -0,0 +1,38 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + +#pragma once + +/// @file clausifier.h +/// @brief Converts FOL formulas to Clause Normal Form (CNF). +/// +/// Pipeline: eliminate ↔/→ → NNF → Skolemize → distribute ∨ over ∧ → flatten. + +#include "atp/core/clause.h" +#include "atp/core/term_bank.h" +#include "atp/normalize/formula.h" + +#include <vector> + +namespace atp { + +/// Convert a first-order formula into a set of clauses (CNF). +std::vector<Clause> clausify(const Formula& formula, TermBank& bank); + +} // namespace atp diff --git a/include/atp/normalize/formula.h b/include/atp/normalize/formula.h new file mode 100644 index 0000000..ccf1302 --- /dev/null +++ b/include/atp/normalize/formula.h @@ -0,0 +1,74 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + +#pragma once + +/// @file formula.h +/// @brief First-order logic formula AST (pre-clausification). + +#include "atp/core/types.h" + +#include <memory> +#include <string> +#include <vector> + +namespace atp { + +/// AST node types for first-order logic formulas. +enum class FormulaKind : uint8_t { + kAtom, ///< Predicate application: P(t1, ..., tn) + kNot, ///< Negation: ¬F + kAnd, ///< Conjunction: F ∧ G + kOr, ///< Disjunction: F ∨ G + kImplies, ///< Implication: F → G + kIff, ///< Biconditional: F ↔ G + kForall, ///< Universal: ∀x. F + kExists, ///< Existential: ∃x. F +}; + +/// A first-order logic formula node. +struct Formula { + FormulaKind kind; + + // For kAtom: the predicate term + TermId atom = kInvalidId; + + // For quantifiers: the bound variable name + std::string var_name; + + // Sub-formulas (1 for Not/Quantifiers, 2 for binary connectives) + std::vector<std::unique_ptr<Formula>> children; + + static std::unique_ptr<Formula> makeAtom(TermId atom); + static std::unique_ptr<Formula> makeNot(std::unique_ptr<Formula> child); + static std::unique_ptr<Formula> makeAnd(std::unique_ptr<Formula> lhs, + std::unique_ptr<Formula> rhs); + static std::unique_ptr<Formula> makeOr(std::unique_ptr<Formula> lhs, + std::unique_ptr<Formula> rhs); + static std::unique_ptr<Formula> makeImplies(std::unique_ptr<Formula> lhs, + std::unique_ptr<Formula> rhs); + static std::unique_ptr<Formula> makeIff(std::unique_ptr<Formula> lhs, + std::unique_ptr<Formula> rhs); + static std::unique_ptr<Formula> makeForall(std::string var, + std::unique_ptr<Formula> body); + static std::unique_ptr<Formula> makeExists(std::string var, + std::unique_ptr<Formula> body); +}; + +} // namespace atp diff --git a/include/atp/proof/proof_trace.h b/include/atp/proof/proof_trace.h new file mode 100644 index 0000000..cda6c5b --- /dev/null +++ b/include/atp/proof/proof_trace.h @@ -0,0 +1,54 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + +#pragma once + +/// @file proof_trace.h +/// @brief Proof reconstruction from the empty clause back to axioms. +/// +/// This module depends only on ClauseStore (not Prover), so it can be +/// reused with any search strategy. + +#include "atp/core/clause.h" +#include "atp/core/clause_store.h" +#include "atp/core/term_bank.h" + +#include <string> +#include <vector> + +namespace atp { + +/// A single step in a reconstructed proof. +struct ProofStep { + ClauseId clause_id; + InferenceRule rule; + ClauseId parent1; + ClauseId parent2; + std::string description; ///< Human-readable description +}; + +/// Reconstruct the proof trace from the empty clause. +/// Walks parent pointers via ClauseStore, independent of search strategy. +std::vector<ProofStep> extractProof(const ClauseStore& store, ClauseId empty_clause_id, + const TermBank& bank); + +/// Format a proof as a human-readable string. +std::string formatProof(const std::vector<ProofStep>& proof, const TermBank& bank); + +} // namespace atp diff --git a/include/atp/rewrite/ordering.h b/include/atp/rewrite/ordering.h new file mode 100644 index 0000000..5696766 --- /dev/null +++ b/include/atp/rewrite/ordering.h @@ -0,0 +1,54 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + +#pragma once + +/// @file ordering.h +/// @brief Term orderings for equality reasoning (KBO, LPO). +/// +/// Term orderings are the foundation of equality-based theorem proving. +/// They ensure that rewriting always terminates by enforcing a well-founded +/// ordering on terms. Required by paramodulation, demodulation, and +/// ordered resolution. + +#include "atp/core/term_bank.h" +#include "atp/core/types.h" + +namespace atp { + +/// Ordering comparison result. +enum class OrderResult : uint8_t { + kLessThan, ///< t1 < t2 + kEqual, ///< t1 = t2 + kGreaterThan, ///< t1 > t2 + kIncomparable, ///< t1 and t2 are incomparable +}; + +/// Abstract base for term orderings. +/// Concrete implementations: KBO (Knuth-Bendix), LPO (Lexicographic Path). +class TermOrdering { + public: + virtual ~TermOrdering() = default; + + /// Compare two terms under the ordering. + [[nodiscard]] virtual OrderResult compare(const TermBank& bank, TermId t1, + TermId t2) const = 0; +}; + +} // namespace atp diff --git a/include/atp/rewrite/paramodulation.h b/include/atp/rewrite/paramodulation.h new file mode 100644 index 0000000..f43cd7b --- /dev/null +++ b/include/atp/rewrite/paramodulation.h @@ -0,0 +1,48 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + +#pragma once + +/// @file paramodulation.h +/// @brief Paramodulation inference rule for equality reasoning. +/// +/// Paramodulation replaces a subterm in one clause with an equal term +/// from an equation in another clause. Combined with term orderings, +/// this gives a complete calculus for first-order logic with equality +/// (the Superposition calculus). + +#include "atp/core/clause.h" +#include "atp/core/term_bank.h" +#include "atp/rewrite/ordering.h" + +#include <vector> + +namespace atp { + +/// Generate all paramodulants between two clauses. +/// Uses the term ordering to restrict to ordered paramodulation (superposition). +std::vector<Clause> paramodulate(const TermBank& bank, const Clause& c1, const Clause& c2, + const TermOrdering& ordering); + +/// Simplify a clause by demodulation (rewriting with unit equalities). +/// Returns true if the clause was modified. +bool demodulate(TermBank& bank, Clause& clause, const Clause& unit_eq, + const TermOrdering& ordering); + +} // namespace atp diff --git a/include/atp/search/clause_queue.h b/include/atp/search/clause_queue.h new file mode 100644 index 0000000..828a725 --- /dev/null +++ b/include/atp/search/clause_queue.h @@ -0,0 +1,44 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + +#pragma once + +/// @file clause_queue.h +/// @brief Priority queue for the Given Clause Loop. + +#include "atp/core/clause.h" + +#include <functional> + +namespace atp { + +/// Comparison function type for clause ordering. +using ClauseComparator = std::function<bool(const Clause& a, const Clause& b)>; + +/// BFS comparator: prioritize shallower derivation depth. +inline bool bfsCompare(const Clause& a, const Clause& b) { + return a.depth > b.depth; // min-heap by depth +} + +/// Weight comparator: prioritize shorter (fewer literals) clauses. +inline bool weightCompare(const Clause& a, const Clause& b) { + return a.literals.size() > b.literals.size(); // min-heap by literal count +} + +} // namespace atp diff --git a/include/atp/search/prover.h b/include/atp/search/prover.h new file mode 100644 index 0000000..308e044 --- /dev/null +++ b/include/atp/search/prover.h @@ -0,0 +1,81 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + +#pragma once + +/// @file prover.h +/// @brief The Given Clause Loop — main saturation-based proof search. +/// +/// V1: Uses a simple ProverConfig with hardcoded resolution + factoring. +/// V2: Will be refactored to accept a Calculus object from strategy/ module +/// for dynamic algorithm loading per problem type. + +#include "atp/core/clause.h" +#include "atp/core/clause_store.h" +#include "atp/core/term_bank.h" +#include "atp/search/clause_queue.h" + +#include <optional> +#include <vector> + +namespace atp { + +/// Result of a proof attempt. +enum class ProverResult : uint8_t { + kTheorem, ///< Empty clause derived — conjecture is a theorem + kSaturation, ///< Search space saturated — cannot prove + kTimeout, ///< Resource limit exceeded +}; + +/// V1 configuration — simple and direct. +/// Future: replaced by strategy::Calculus for dynamic rule loading. +struct ProverConfig { + ClauseComparator comparator = bfsCompare; + size_t max_clauses = 100000; ///< Safety limit + size_t max_iterations = 500000; ///< Safety limit + bool enable_occurs_check = false; +}; + +/// Main prover class implementing the Given Clause Loop. +/// V1: hardcodes resolution + factoring + subsumption. +/// V2: will accept a Calculus object for pluggable inference rules. +class Prover { + public: + Prover(TermBank& bank, ClauseStore& store, ProverConfig config = {}); + + /// Add initial clauses (axioms + negated conjecture). + void addClauses(std::vector<Clause> clauses); + + /// Run the proof search. + ProverResult prove(); + + /// After a successful proof, retrieve the empty clause ID. + [[nodiscard]] std::optional<ClauseId> getEmptyClauseId() const; + + /// Access the underlying clause store. + [[nodiscard]] const ClauseStore& clauseStore() const { return store_; } + + private: + TermBank& bank_; + ClauseStore& store_; + ProverConfig config_; + // TODO: Phase 5 implementation — Unprocessed queue + Processed set +}; + +} // namespace atp diff --git a/include/atp/simplify/subsumption.h b/include/atp/simplify/subsumption.h new file mode 100644 index 0000000..ee7a83e --- /dev/null +++ b/include/atp/simplify/subsumption.h @@ -0,0 +1,55 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + +#pragma once + +/// @file subsumption.h +/// @brief Forward and backward subsumption checks (backed by discrimination tree). + +#include "atp/core/clause.h" +#include "atp/index/discrim_tree.h" + +#include <vector> + +namespace atp { + +/// Subsumption engine: checks if a new clause is subsumed by existing ones +/// (forward) or subsumes existing ones (backward). +class SubsumptionEngine { + public: + explicit SubsumptionEngine(const TermBank& bank); + + /// Returns true if `candidate` is subsumed by any existing clause. + [[nodiscard]] bool isForwardSubsumed(const Clause& candidate) const; + + /// Returns IDs of existing clauses that are subsumed by `new_clause`. + [[nodiscard]] std::vector<ClauseId> backwardSubsumed(const Clause& new_clause) const; + + /// Add a clause to the subsumption index. + void addClause(const Clause& clause); + + /// Remove a clause from the subsumption index. + void removeClause(ClauseId id); + + private: + DiscrimTree index_; + // TODO: Phase 5 implementation +}; + +} // namespace atp diff --git a/include/atp/simplify/tautology.h b/include/atp/simplify/tautology.h new file mode 100644 index 0000000..80aa1f9 --- /dev/null +++ b/include/atp/simplify/tautology.h @@ -0,0 +1,32 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + +#pragma once + +/// @file tautology.h +/// @brief Tautology detection for clauses. + +#include "atp/core/clause.h" + +namespace atp { + +/// Returns true if the clause is a tautology (contains complementary literals). +[[nodiscard]] bool isTautology(const Clause& clause); + +} // namespace atp diff --git a/include/atp/strategy/calculus.h b/include/atp/strategy/calculus.h new file mode 100644 index 0000000..ee8ee09 --- /dev/null +++ b/include/atp/strategy/calculus.h @@ -0,0 +1,68 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + +#pragma once + +/// @file calculus.h +/// @brief A Calculus bundles the exact set of inference rules + heuristics +/// to use for a specific problem class. +/// +/// Think of it as the "algorithm profile" that the Prover loads. +/// Different problems get different calculi: +/// - Pure propositional: resolution + factoring only +/// - FOL without equality: + full unification +/// - FOL with equality: + paramodulation + KBO ordering +/// - Arithmetic: + theory solver integration +/// +/// This is the single point where search space control happens. + +#include "atp/rewrite/ordering.h" +#include "atp/search/clause_queue.h" +#include "atp/strategy/inference_rule.h" + +#include <memory> +#include <string_view> +#include <vector> + +namespace atp { + +/// A Calculus = a complete specification of how to search for a proof. +/// The Prover is parameterized by this — it never hardcodes which rules to use. +struct Calculus { + /// Name for logging (e.g., "superposition", "pure_resolution"). + std::string name; + + /// Generating rules (executed in order during the main loop). + std::vector<std::unique_ptr<GeneratingRule>> generating_rules; + + /// Simplifying rules (applied to each new clause before enqueuing). + std::vector<std::unique_ptr<SimplifyingRule>> simplifying_rules; + + /// Clause selection heuristic. + ClauseComparator comparator = bfsCompare; + + /// Term ordering (nullptr if equality reasoning is disabled). + std::unique_ptr<TermOrdering> ordering = nullptr; + + /// Resource limits. + size_t max_clauses = 100000; + size_t max_iterations = 500000; +}; + +} // namespace atp diff --git a/include/atp/strategy/inference_rule.h b/include/atp/strategy/inference_rule.h new file mode 100644 index 0000000..1c7dbba --- /dev/null +++ b/include/atp/strategy/inference_rule.h @@ -0,0 +1,81 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + +#pragma once + +/// @file inference_rule.h +/// @brief Abstract interface for pluggable inference rules. +/// +/// Each inference rule (resolution, factoring, paramodulation, etc.) +/// is a self-contained object that the Prover can selectively load. +/// This prevents search space explosion by only enabling rules relevant +/// to the problem at hand. + +#include "atp/core/clause.h" +#include "atp/core/clause_store.h" +#include "atp/core/term_bank.h" + +#include <string_view> +#include <vector> + +namespace atp { + +/// Abstract base class for all inference rules. +/// The Prover invokes only the rules present in its active calculus. +class InferenceRuleBase { + public: + virtual ~InferenceRuleBase() = default; + + /// Human-readable name for logging and proof output. + [[nodiscard]] virtual std::string_view name() const = 0; + + /// Is this a generating rule (produces new clauses) or simplifying rule + /// (rewrites/deletes existing clauses)? + enum class Kind : uint8_t { kGenerating, kSimplifying }; + [[nodiscard]] virtual Kind kind() const = 0; +}; + +/// Generating inference rule: given a "given clause" and the set of processed +/// clauses, produce new clauses. +class GeneratingRule : public InferenceRuleBase { + public: + [[nodiscard]] Kind kind() const final { return Kind::kGenerating; } + + /// Generate new clauses from the given clause against all processed clauses. + /// @param given The selected clause from the Unprocessed queue. + /// @param processed All previously processed clauses (accessed via store). + /// @param bank The global term bank. + /// @return Newly generated clauses (not yet added to the store). + [[nodiscard]] virtual std::vector<Clause> generate( + const Clause& given, const std::vector<ClauseId>& processed, + const ClauseStore& store, TermBank& bank) const = 0; +}; + +/// Simplifying inference rule: rewrite or delete a clause in-place. +class SimplifyingRule : public InferenceRuleBase { + public: + [[nodiscard]] Kind kind() const final { return Kind::kSimplifying; } + + /// Attempt to simplify a clause. Returns true if the clause was modified. + /// If the clause should be deleted entirely, clear its literals. + virtual bool simplify(Clause& clause, const ClauseStore& store, + TermBank& bank) const = 0; +}; + +} // namespace atp diff --git a/include/atp/strategy/problem_analyzer.h b/include/atp/strategy/problem_analyzer.h new file mode 100644 index 0000000..b5fdef4 --- /dev/null +++ b/include/atp/strategy/problem_analyzer.h @@ -0,0 +1,62 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + +#pragma once + +/// @file problem_analyzer.h +/// @brief Analyzes input clauses and selects the optimal Calculus. +/// +/// Before the Prover starts its main loop, the ProblemAnalyzer inspects +/// the input clause set to determine problem characteristics: +/// - Contains equality? → enable paramodulation +/// - Pure Horn clauses? → use SLD resolution +/// - Contains arithmetic literals? → enable theory solver +/// - Problem size / clause density → tune resource limits +/// +/// This is the "auto mode" that mature ATPs use to avoid loading +/// unnecessary inference rules that would explode the search space. + +#include "atp/core/clause.h" +#include "atp/strategy/calculus.h" + +#include <vector> + +namespace atp { + +/// Features detected in the input problem. +struct ProblemFeatures { + bool has_equality = false; ///< Contains '=' predicate + bool is_purely_propositional = false; ///< No function symbols, no variables + bool is_horn = false; ///< All clauses are Horn clauses + bool has_existential = false; ///< Had existential quantifiers (Skolemized) + size_t num_clauses = 0; + size_t num_predicates = 0; + size_t num_functions = 0; + size_t max_clause_size = 0; + size_t max_term_depth = 0; +}; + +/// Analyze the input clauses and extract problem features. +ProblemFeatures analyzeFeatures(const std::vector<Clause>& clauses, const TermBank& bank); + +/// Select the optimal calculus based on detected features. +/// This is the core strategy dispatch logic. +std::unique_ptr<Calculus> selectCalculus(const ProblemFeatures& features); + +} // namespace atp diff --git a/include/atp/utils/hash_utils.h b/include/atp/utils/hash_utils.h new file mode 100644 index 0000000..4531fa6 --- /dev/null +++ b/include/atp/utils/hash_utils.h @@ -0,0 +1,47 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + +#pragma once + +/// @file hash_utils.h +/// @brief Hash combination utilities. + +#include <cstddef> +#include <cstdint> +#include <functional> + +namespace atp { + +/// Combine a hash with a new value (boost::hash_combine style). +inline void hashCombine(size_t& seed, size_t value) { + seed ^= value + 0x9e3779b9 + (seed << 6) + (seed >> 2); +} + +/// Hash a span of values. +template <typename T> +size_t hashRange(const T* data, size_t count) { + size_t seed = 0; + std::hash<T> hasher; + for (size_t i = 0; i < count; ++i) { + hashCombine(seed, hasher(data[i])); + } + return seed; +} + +} // namespace atp diff --git a/include/atp/utils/logger.h b/include/atp/utils/logger.h new file mode 100644 index 0000000..95d3dd2 --- /dev/null +++ b/include/atp/utils/logger.h @@ -0,0 +1,43 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + +#pragma once + +/// @file logger.h +/// @brief Minimal high-performance logging macros. + +#include <cstdio> + +#ifndef ATP_LOG_LEVEL +#define ATP_LOG_LEVEL 2 // 0=TRACE, 1=DEBUG, 2=INFO, 3=WARN, 4=ERROR +#endif + +#define ATP_LOG(level, level_str, fmt, ...) \ + do { \ + if constexpr (level >= ATP_LOG_LEVEL) { \ + std::fprintf(stderr, "[%s] " fmt "\n", level_str, \ + ##__VA_ARGS__); \ + } \ + } while (0) + +#define ATP_TRACE(fmt, ...) ATP_LOG(0, "TRACE", fmt, ##__VA_ARGS__) +#define ATP_DEBUG(fmt, ...) ATP_LOG(1, "DEBUG", fmt, ##__VA_ARGS__) +#define ATP_INFO(fmt, ...) ATP_LOG(2, "INFO", fmt, ##__VA_ARGS__) +#define ATP_WARN(fmt, ...) ATP_LOG(3, "WARN", fmt, ##__VA_ARGS__) +#define ATP_ERROR(fmt, ...) ATP_LOG(4, "ERROR", fmt, ##__VA_ARGS__) diff --git a/src/core/clause_store.cc b/src/core/clause_store.cc new file mode 100644 index 0000000..b62ffd0 --- /dev/null +++ b/src/core/clause_store.cc @@ -0,0 +1,19 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + diff --git a/src/core/symbol_table.cc b/src/core/symbol_table.cc new file mode 100644 index 0000000..b62ffd0 --- /dev/null +++ b/src/core/symbol_table.cc @@ -0,0 +1,19 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + diff --git a/src/core/term_bank.cc b/src/core/term_bank.cc new file mode 100644 index 0000000..b62ffd0 --- /dev/null +++ b/src/core/term_bank.cc @@ -0,0 +1,19 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + diff --git a/src/frontend/tptp_parser.cc b/src/frontend/tptp_parser.cc new file mode 100644 index 0000000..b62ffd0 --- /dev/null +++ b/src/frontend/tptp_parser.cc @@ -0,0 +1,19 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + diff --git a/src/index/discrim_tree.cc b/src/index/discrim_tree.cc new file mode 100644 index 0000000..b62ffd0 --- /dev/null +++ b/src/index/discrim_tree.cc @@ -0,0 +1,19 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + diff --git a/src/infer/resolution.cc b/src/infer/resolution.cc new file mode 100644 index 0000000..b62ffd0 --- /dev/null +++ b/src/infer/resolution.cc @@ -0,0 +1,19 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + diff --git a/src/infer/unification.cc b/src/infer/unification.cc new file mode 100644 index 0000000..b62ffd0 --- /dev/null +++ b/src/infer/unification.cc @@ -0,0 +1,19 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + diff --git a/src/main.cc b/src/main.cc new file mode 100644 index 0000000..b62ffd0 --- /dev/null +++ b/src/main.cc @@ -0,0 +1,19 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + diff --git a/src/normalize/clausifier.cc b/src/normalize/clausifier.cc new file mode 100644 index 0000000..b62ffd0 --- /dev/null +++ b/src/normalize/clausifier.cc @@ -0,0 +1,19 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + diff --git a/src/proof/proof_trace.cc b/src/proof/proof_trace.cc new file mode 100644 index 0000000..b62ffd0 --- /dev/null +++ b/src/proof/proof_trace.cc @@ -0,0 +1,19 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + diff --git a/src/rewrite/ordering.cc b/src/rewrite/ordering.cc new file mode 100644 index 0000000..b62ffd0 --- /dev/null +++ b/src/rewrite/ordering.cc @@ -0,0 +1,19 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + diff --git a/src/rewrite/paramodulation.cc b/src/rewrite/paramodulation.cc new file mode 100644 index 0000000..b62ffd0 --- /dev/null +++ b/src/rewrite/paramodulation.cc @@ -0,0 +1,19 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + diff --git a/src/search/prover.cc b/src/search/prover.cc new file mode 100644 index 0000000..b62ffd0 --- /dev/null +++ b/src/search/prover.cc @@ -0,0 +1,19 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + diff --git a/src/simplify/subsumption.cc b/src/simplify/subsumption.cc new file mode 100644 index 0000000..b62ffd0 --- /dev/null +++ b/src/simplify/subsumption.cc @@ -0,0 +1,19 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + diff --git a/src/strategy/problem_analyzer.cc b/src/strategy/problem_analyzer.cc new file mode 100644 index 0000000..b62ffd0 --- /dev/null +++ b/src/strategy/problem_analyzer.cc @@ -0,0 +1,19 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt new file mode 100644 index 0000000..d841595 --- /dev/null +++ b/tests/CMakeLists.txt @@ -0,0 +1,27 @@ +# ─── GoogleTest ─────────────────────────────────────────────────────────────── +include(FetchContent) +FetchContent_Declare( + googletest + GIT_REPOSITORY https://github.com/google/googletest.git + GIT_TAG v1.14.0 +) +# Prevent GoogleTest from overriding our compiler/linker options +set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) +FetchContent_MakeAvailable(googletest) + +include(GoogleTest) + +# ─── Helper: define a test target ──────────────────────────────────────────── +function(atp_add_test TEST_NAME TEST_SOURCE) + add_executable(${TEST_NAME} ${TEST_SOURCE}) + target_link_libraries(${TEST_NAME} PRIVATE atp_core GTest::gtest_main) + gtest_discover_tests(${TEST_NAME}) +endfunction() + +# ─── Test Targets ──────────────────────────────────────────────────────────── +atp_add_test(test_term_bank test_term_bank.cc) +atp_add_test(test_unification test_unification.cc) +atp_add_test(test_clausifier test_clausifier.cc) +atp_add_test(test_resolution test_resolution.cc) +atp_add_test(test_discrim_tree test_discrim_tree.cc) +atp_add_test(test_prover test_prover.cc) diff --git a/tests/test_clausifier.cc b/tests/test_clausifier.cc new file mode 100644 index 0000000..b62ffd0 --- /dev/null +++ b/tests/test_clausifier.cc @@ -0,0 +1,19 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + diff --git a/tests/test_discrim_tree.cc b/tests/test_discrim_tree.cc new file mode 100644 index 0000000..b62ffd0 --- /dev/null +++ b/tests/test_discrim_tree.cc @@ -0,0 +1,19 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + diff --git a/tests/test_prover.cc b/tests/test_prover.cc new file mode 100644 index 0000000..b62ffd0 --- /dev/null +++ b/tests/test_prover.cc @@ -0,0 +1,19 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + diff --git a/tests/test_resolution.cc b/tests/test_resolution.cc new file mode 100644 index 0000000..b62ffd0 --- /dev/null +++ b/tests/test_resolution.cc @@ -0,0 +1,19 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + diff --git a/tests/test_term_bank.cc b/tests/test_term_bank.cc new file mode 100644 index 0000000..b62ffd0 --- /dev/null +++ b/tests/test_term_bank.cc @@ -0,0 +1,19 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + diff --git a/tests/test_unification.cc b/tests/test_unification.cc new file mode 100644 index 0000000..b62ffd0 --- /dev/null +++ b/tests/test_unification.cc @@ -0,0 +1,19 @@ +/* + * richard-atp-engine: A saturation-based automated theorem prover for first-order logic. + * Copyright (C) 2026 Richard Qin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. + */ + + |
