简单的命题逻辑表达式解析与范式生成(C++实现)

命题逻辑表达式解析与范式生成

命题逻辑公式的自动求值可以被视为一个受限的表达式语言处理问题。输入是一组命题变量、逻辑联结词和括号组成的字符串,输出则是公式在所有赋值下的真值、主析取范式和主合取范式。本文将该问题形式化为“词法结构识别、语法结构构造和语义求值”三个层次,比较字符串重写与语法树求值两类方法,并给出一个基于递归下降分析器和抽象语法树的完整 C++17 实现。该实现支持多字符变量、括号、常量以及非、合取、析取、蕴含和等价运算,并通过统一的语义函数生成真值表和标准范式。

1. 问题形式化

设命题变量集合为

\[V=\{x_1,x_2,\ldots,x_n\}, \]

每个变量的取值属于布尔集合 \(\mathbb{B}=\{0,1\}\)。一个赋值是函数

\[\nu:V\rightarrow\mathbb{B} \]

给定命题公式 \(\varphi\),求值过程的目标是计算语义函数

\[\llbracket\varphi\rrbracket_\nu\in\mathbb{B} \]

当公式包含 \(n\) 个不同变量时,所有可能赋值共有 \(2^n\) 个。枚举这些赋值并计算公式结果,就得到真值表。进一步地,结果为 1 的行可构造主析取范式,结果为 0 的行可构造主合取范式。因此,真值表和两类标准范式并不是三个相互独立的功能,而是同一个语义求值过程的不同输出视图。

2. 语法与运算语义

为了使输入字符串具有唯一解释,需要先定义形式语法。本文使用如下优先级,从高到低排列:

优先级 产生式或运算符 含义
最高 ! 否定
* 合取
+ 或 | 析取
> 蕴含
最低 = 或 <-> 等价

相应的文法可以写成:

equivalence  := implication (('=' | '<->') implication)*
implication  := disjunction ('>' implication)?
disjunction  := conjunction (('+' | '|') conjunction)*
conjunction  := unary ('*' unary)*
unary        := '!' unary | '(' equivalence ')' | variable | constant

这里将蕴含定义为右结合。例如,p>q>r 被解释为 p>(q>r)。合取和析取采用左结合,p*q*r 被解释为 (p*q)*r。括号可以递归嵌套,因此文法能够表达任意深度的复合公式。

各联结词的语义定义如下:

\[\begin{aligned} \llbracket !p\rrbracket_\nu &= \neg\llbracket p\rrbracket_\nu\\ \llbracket p*q\rrbracket_\nu &= \llbracket p\rrbracket_\nu\land\llbracket q\rrbracket_\nu\\ \llbracket p+q\rrbracket_\nu &= \llbracket p\rrbracket_\nu\lor\llbracket q\rrbracket_\nu\\ \llbracket p>q\rrbracket_\nu &= \neg\llbracket p\rrbracket_\nu\lor\llbracket q\rrbracket_\nu\\ \llbracket p=q\rrbracket_\nu &= (\llbracket p\rrbracket_\nu=\llbracket q\rrbracket_\nu) \end{aligned} \]

这种“先定义语言,再定义语义”的顺序非常重要。若直接在字符串上添加替换规则,运算符优先级和结合性会隐含在函数调用顺序中,容易导致同一字符串在不同代码路径下得到不同解释。

3. 从字符串到抽象语法树

3.1 字符串重写的局限

最直接的方法是将变量替换为 0 或 1,然后反复寻找 !0、0*1、(1) 等局部模式并进行化简。这种方案对于格式严格、运算符数量有限的输入比较直观,但它实际上把词法分析、语法分析和求值混在了一起。

其主要问题包括:

  • 优先级由多个化简函数的调用顺序间接表示;
  • 对括号嵌套和一元运算的处理依赖大量边界判断;
  • 每一次局部替换都可能导致字符串移动,重复扫描成本较高;
  • 非法表达式通常无法在准确位置报告原因;
  • 变量、常量和运算符没有独立的数据类型。

字符串重写可以作为原型验证手段,但不适合作为表达式引擎的长期结构。

3.2 递归下降分析

递归下降分析器为每一层优先级设置一个解析函数。以 parseConjunction 为例,它首先读取一个一元表达式,然后只要继续遇到 *,就读取下一个一元表达式并构造二叉节点。由于析取层调用合取层、蕴含层调用析取层,优先级自然由函数调用层级体现。

下面是完整实现中的核心结构:

enum class NodeKind {
    Variable, Constant, Not, And, Or, Implication, Equivalence
};

struct Node {
    NodeKind kind;
    std::string name;
    bool value = false;
    std::unique_ptr<Node> left;
    std::unique_ptr<Node> right;
};

抽象语法树(Abstract Syntax Tree,AST)只保留公式的结构信息,不再保留无语义的括号。例如,公式 (!p+q)*r 的根节点是合取,左子树是析取,析取节点的左子树是 !p。这种结构一旦构建完成,后续求值不需要再次理解原始字符串。

3.3 递归下降的关键实现

完整代码位于同目录下的 logic_truth_table.cpp。解析器的入口为 parse:

std::unique_ptr<Node> parse() {
    auto root = parseEquivalence();
    skipSpaces();
    if (pos_ != text_.size()) {
        throw error("unexpected character");
    }
    return root;
}

解析成功后,输入必须完全消耗。如果表达式尾部存在多余字符,程序不会静默忽略,而是抛出带位置的信息。这一约束可以避免诸如 p*q abc 被错误地当成合法公式。

一元运算的递归处理体现了否定的高优先级:

std::unique_ptr<Node> parseUnary() {
    if (accept('!')) {
        return makeUnary(NodeKind::Not, parseUnary());
    }
    if (accept('(')) {
        auto expression = parseEquivalence();
        if (!accept(')')) throw error("missing ')' ");
        return expression;
    }
    // 后续识别常量和变量
}

! 后面再次调用 parseUnary,因此 !!p、!(p+q) 等形式都能自然处理。变量采用字母开头、字母数字或下划线继续的规则,从而同时支持 p、flag1 和 user_enabled 等名称。

4. 语义求值与真值表生成

AST 求值函数直接按照节点类型递归实现语义定义:

bool evaluate(const Node& node, const Assignment& assignment) {
    switch (node.kind) {
    case NodeKind::Constant:
        return node.value;
    case NodeKind::Variable:
        return assignment.at(node.name);
    case NodeKind::Not:
        return !evaluate(*node.left, assignment);
    case NodeKind::And:
        return evaluate(*node.left, assignment) && evaluate(*node.right, assignment);
    case NodeKind::Or:
        return evaluate(*node.left, assignment) || evaluate(*node.right, assignment);
    case NodeKind::Implication:
        return !evaluate(*node.left, assignment) || evaluate(*node.right, assignment);
    case NodeKind::Equivalence:
        return evaluate(*node.left, assignment) == evaluate(*node.right, assignment);
    }
    throw std::logic_error("unknown node kind");
}

变量集合从 AST 中收集,并排序后作为真值表列顺序。令变量数组为 x[0..n-1],整数 mask 的二进制位可以直接生成一行赋值:

for (std::size_t i = 0; i < variables.size(); ++i) {
    bool value = (mask >> (variables.size() - i - 1)) & 1U;
    assignment[variables[i]] = value;
}

最高位对应第一列变量,因而真值表按字典序从全 0 行递增到全 1 行。每一行完成赋值后,只需要调用同一个 evaluate 函数,即可同时得到表格结果和范式所需的行信息。

5. 主析取范式与主合取范式

设某一行赋值为 \(\nu\)。当公式在该行的值为 1 时,构造一个最小项:变量取 1 时写变量本身,变量取 0 时写变量否定,变量之间用合取连接。例如对变量顺序 p,q,r,赋值 1,0,1 得到

\[p\land\neg q\land r \]

所有结果为 1 的最小项进行析取,得到主析取范式:

\[\mathrm{PDNF}(\varphi)=\bigvee_{\nu(\varphi)=1}m_\nu \]

当公式在某一行的值为 0 时,构造一个最大项:变量取 0 时写变量本身,变量取 1 时写变量否定,变量之间用析取连接。例如同一赋值得到

\[\neg p\lor q\lor\neg r \]

所有结果为 0 的最大项进行合取,得到主合取范式:

\[\mathrm{PCNF}(\varphi)=\bigwedge_{\nu(\varphi)=0}M_\nu \]

代码中分别由 minterm 和 maxterm 完成这一转换:

std::string minterm(const std::vector<std::string>& variables,
                    const Assignment& assignment);
std::string maxterm(const std::vector<std::string>& variables,
                    const Assignment& assignment);

如果没有结果为 1 的行,主析取范式应表示恒假式 0;如果没有结果为 0 的行,主合取范式应表示恒真式 1。这两个退化情形必须显式处理,否则恒真式和恒假式会产生空字符串,无法作为合法逻辑公式输出。

6. 正确性说明

可以用结构归纳法说明 evaluate 的正确性。

基例: 对变量节点,函数从赋值函数中取出对应值;对常量节点,函数直接返回其存储值,因此与语义定义一致。

归纳步骤: 假设左右子树的递归求值分别等于其语义值。对于否定节点,代码返回左子树结果的逻辑非;对于合取、析取、蕴含和等价节点,代码分别使用对应的布尔运算。因此复合节点的结果等于其语义定义。

由此,根节点的求值结果等于整个公式在当前赋值下的语义值。枚举算法又覆盖了全部 \(2^n\) 个赋值,所以输出的结果列完整地表示了公式的真值函数。主析取范式和主合取范式按照结果为 1 或 0 的行逐项构造,因此分别满足原公式的全部真值条件。

7. 复杂度分析

设公式的 AST 节点数量为 \(m\),不同变量数量为 \(n\)。

  • 词法扫描和递归下降解析的时间复杂度为 \(O(m)\);
  • AST 空间复杂度为 \(O(m)\);
  • 单行求值在朴素实现下为 \(O(m)\);
  • 真值表枚举共进行 \(2^n\) 行,因此总时间复杂度为 \(O(m2^n)\);
  • 若保存所有范式项,输出相关空间最多为 \(O(n2^n)\)。

指数项来自真值表定义本身,而不是某一种具体实现。变量达到 20 个时,行数已经超过一百万;当变量数量继续增加,完整真值表和标准范式通常不再是合适的表示方式。此时可以考虑二叉决策图、符号化布尔表达式、SAT 求解或基于位并行的批量求值。

8. 编译与使用

代码文件为 logic_truth_table.cpp,需要 C++17 或更高标准。完整源码如下:

#include <cctype>
#include <iostream>
#include <memory>
#include <set>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>

using Assignment = std::unordered_map<std::string, bool>;

enum class NodeKind {
    Variable,
    Constant,
    Not,
    And,
    Or,
    Implication,
    Equivalence
};

struct Node {
    NodeKind kind;
    std::string name;
    bool value = false;
    std::unique_ptr<Node> left;
    std::unique_ptr<Node> right;

    explicit Node(NodeKind kind) : kind(kind) {}
};

class Parser {
public:
    explicit Parser(std::string text) : text_(std::move(text)) {}

    std::unique_ptr<Node> parse() {
        auto root = parseEquivalence();
        skipSpaces();
        if (pos_ != text_.size()) {
            throw error("unexpected character");
        }
        return root;
    }

private:
    std::string text_;
    std::size_t pos_ = 0;

    std::runtime_error error(const std::string& message) const {
        return std::runtime_error(
            message + " at position " + std::to_string(pos_));
    }

    void skipSpaces() {
        while (pos_ < text_.size() &&
               std::isspace(static_cast<unsigned char>(text_[pos_]))) {
            ++pos_;
        }
    }

    bool accept(char token) {
        skipSpaces();
        if (pos_ < text_.size() && text_[pos_] == token) {
            ++pos_;
            return true;
        }
        return false;
    }

    std::unique_ptr<Node> makeUnary(NodeKind kind,
                                    std::unique_ptr<Node> child) {
        auto node = std::make_unique<Node>(kind);
        node->left = std::move(child);
        return node;
    }

    std::unique_ptr<Node> makeBinary(NodeKind kind,
                                     std::unique_ptr<Node> left,
                                     std::unique_ptr<Node> right) {
        auto node = std::make_unique<Node>(kind);
        node->left = std::move(left);
        node->right = std::move(right);
        return node;
    }

    // equivalence := implication (('=' | '<->') implication)*
    std::unique_ptr<Node> parseEquivalence() {
        auto left = parseImplication();
        while (true) {
            skipSpaces();
            if (accept('=')) {
                left = makeBinary(NodeKind::Equivalence,
                                  std::move(left), parseImplication());
            } else if (text_.compare(pos_, 3, "<->") == 0) {
                pos_ += 3;
                left = makeBinary(NodeKind::Equivalence,
                                  std::move(left), parseImplication());
            } else {
                return left;
            }
        }
    }

    // implication := disjunction ('>' implication)?
    std::unique_ptr<Node> parseImplication() {
        auto left = parseDisjunction();
        if (accept('>')) {
            return makeBinary(NodeKind::Implication,
                              std::move(left), parseImplication());
        }
        return left;
    }

    // disjunction := conjunction (('+' | '|') conjunction)*
    std::unique_ptr<Node> parseDisjunction() {
        auto left = parseConjunction();
        while (true) {
            if (accept('+') || accept('|')) {
                left = makeBinary(NodeKind::Or,
                                  std::move(left), parseConjunction());
            } else {
                return left;
            }
        }
    }

    // conjunction := unary ('*' unary)*
    std::unique_ptr<Node> parseConjunction() {
        auto left = parseUnary();
        while (accept('*')) {
            left = makeBinary(NodeKind::And,
                              std::move(left), parseUnary());
        }
        return left;
    }

    // unary := '!' unary | '(' equivalence ')' | variable | constant
    std::unique_ptr<Node> parseUnary() {
        if (accept('!')) {
            return makeUnary(NodeKind::Not, parseUnary());
        }

        if (accept('(')) {
            auto expression = parseEquivalence();
            if (!accept(')')) {
                throw error("missing ')'");
            }
            return expression;
        }

        skipSpaces();
        if (pos_ >= text_.size()) {
            throw error("expected operand");
        }

        if (text_[pos_] == '0' || text_[pos_] == '1') {
            auto node = std::make_unique<Node>(NodeKind::Constant);
            node->value = text_[pos_++] == '1';
            return node;
        }

        if (std::isalpha(static_cast<unsigned char>(text_[pos_]))) {
            std::string name;
            while (pos_ < text_.size() &&
                   (std::isalnum(static_cast<unsigned char>(text_[pos_])) ||
                    text_[pos_] == '_')) {
                name += text_[pos_++];
            }
            auto node = std::make_unique<Node>(NodeKind::Variable);
            node->name = std::move(name);
            return node;
        }

        throw error("expected operand");
    }
};

void collectVariables(const Node& node,
                      std::set<std::string>& variables) {
    if (node.kind == NodeKind::Variable) {
        variables.insert(node.name);
    }
    if (node.left) {
        collectVariables(*node.left, variables);
    }
    if (node.right) {
        collectVariables(*node.right, variables);
    }
}

bool evaluate(const Node& node, const Assignment& assignment) {
    switch (node.kind) {
    case NodeKind::Constant:
        return node.value;
    case NodeKind::Variable:
        return assignment.at(node.name);
    case NodeKind::Not:
        return !evaluate(*node.left, assignment);
    case NodeKind::And:
        return evaluate(*node.left, assignment) &&
               evaluate(*node.right, assignment);
    case NodeKind::Or:
        return evaluate(*node.left, assignment) ||
               evaluate(*node.right, assignment);
    case NodeKind::Implication:
        return !evaluate(*node.left, assignment) ||
               evaluate(*node.right, assignment);
    case NodeKind::Equivalence:
        return evaluate(*node.left, assignment) ==
               evaluate(*node.right, assignment);
    }
    throw std::logic_error("unknown node kind");
}

std::string minterm(const std::vector<std::string>& variables,
                    const Assignment& assignment) {
    if (variables.empty()) {
        return "1";
    }

    std::string result = "(";
    for (std::size_t i = 0; i < variables.size(); ++i) {
        if (i != 0) {
            result += "*";
        }
        if (!assignment.at(variables[i])) {
            result += "!";
        }
        result += variables[i];
    }
    return result + ")";
}

std::string maxterm(const std::vector<std::string>& variables,
                    const Assignment& assignment) {
    if (variables.empty()) {
        return "0";
    }

    std::string result = "(";
    for (std::size_t i = 0; i < variables.size(); ++i) {
        if (i != 0) {
            result += "+";
        }
        if (assignment.at(variables[i])) {
            result += "!";
        }
        result += variables[i];
    }
    return result + ")";
}

std::string join(const std::vector<std::string>& terms,
                 const std::string& separator) {
    if (terms.empty()) {
        return "";
    }

    std::string result = terms.front();
    for (std::size_t i = 1; i < terms.size(); ++i) {
        result += separator + terms[i];
    }
    return result;
}

int main() {
    std::cout << "Expression: ";
    std::string expression;
    std::getline(std::cin, expression);

    try {
        Parser parser(expression);
        auto syntaxTree = parser.parse();

        std::set<std::string> variableSet;
        collectVariables(*syntaxTree, variableSet);
        std::vector<std::string> variables(variableSet.begin(),
                                            variableSet.end());

        if (variables.size() >= sizeof(std::size_t) * 8) {
            throw std::runtime_error(
                "too many variables for exhaustive enumeration");
        }

        for (const auto& variable : variables) {
            std::cout << variable << "\t";
        }
        std::cout << "| F\n";

        std::vector<std::string> minterms;
        std::vector<std::string> maxterms;
        const std::size_t rowCount = std::size_t{1} << variables.size();

        for (std::size_t mask = 0; mask < rowCount; ++mask) {
            Assignment assignment;
            for (std::size_t i = 0; i < variables.size(); ++i) {
                bool value =
                    (mask >> (variables.size() - i - 1)) & 1U;
                assignment[variables[i]] = value;
                std::cout << (value ? 1 : 0) << "\t";
            }

            bool result = evaluate(*syntaxTree, assignment);
            std::cout << "| " << (result ? 1 : 0) << "\n";

            if (result) {
                minterms.push_back(minterm(variables, assignment));
            } else {
                maxterms.push_back(maxterm(variables, assignment));
            }
        }

        std::cout << "PDNF: "
                  << (minterms.empty() ? "0" : join(minterms, "+"))
                  << "\n";
        std::cout << "PCNF: "
                  << (maxterms.empty() ? "1" : join(maxterms, "*"))
                  << "\n";
    } catch (const std::exception& exception) {
        std::cerr << "Error: " << exception.what() << '\n';
        return 1;
    }
}

使用 GCC 或 Clang 时可以执行:

g++ -std=c++17 -O2 -Wall -Wextra logic_truth_table.cpp -o logic_truth_table

随后输入例如:

(!p+q)*(r>p)

程序会依次输出变量列、真值表、主析取范式和主合取范式。也支持带空格的输入,例如:

!(p * q) = (!p + !q)

其中 = 和 <-> 都表示等价,+ 和 | 都表示析取。若输入存在括号不匹配或运算符缺少操作数,程序会输出错误位置,而不是生成不确定结果。

posted @ 2026-10-20 16:02  YukiRinLL  阅读(25)  评论(0)    收藏  举报