1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
| #include <QtCore> #include "booleanparser.h" #include "node.h" BooleanParser::BooleanParser() { } Node *BooleanParser::parse(const QString &expr) { in = expr; in.replace(" ", ""); pos = 0; Node *node = new Node(Node::Root); addChild(node, parseOrExpression()); return node; } /** 解析或表达式 */ Node *BooleanParser::parseOrExpression() { Node *childNode = parseAndExpression(); if (matchToken("||")) { Node *node = new Node(Node::OrExpression); addChild(node,childNode); while (matchToken("||")) { addToken(node,"||", Node::Operator); addChild(node, parseAndExpression()); } return node; } else { return childNode; } } /** 解析与表达式 */ Node *BooleanParser::parseAndExpression() { Node *childNode = parseNotExpression(); if (matchToken("&&")) { Node *node = new Node(Node::AndExpression); addChild(node, childNode); while (matchToken("&&")) { addToken(node, "&&", Node::Operator); addChild(node, parseNotExpression()); } return node; } else { return childNode; } } /** 解析非表达式 */ Node *BooleanParser::parseNotExpression() { if (matchToken("!")) { Node *node = new Node(Node::NotExpression); while (matchToken("!")) addToken(node, "!", Node::Operator); addChild(node, parseAtom()); return node; } else { return parseAtom(); } } /** 解析一个项 */ Node *BooleanParser::parseAtom() { if (matchToken("(")) { Node *node = new Node(Node::Atom); addToken(node, "(", Node::Punctuator); addChild(node, parseOrExpression()); addToken(node, ")", Node::Punctuator); return node; } else { return parseIdentifier(); } } /** 解析标识符 */ Node *BooleanParser::parseIdentifier() { int startPos = pos; while (pos < in.length() && in[pos].isLetterOrNumber()) ++pos; if (pos > startPos) { return new Node(Node::Identifier, in.mid(startPos, pos - startPos)); } else { return 0; } } /** 添加子结点 */ void BooleanParser::addChild(Node *parent, Node *child) { if (child) { parent->children += child; parent->str += child->str; child->parent = parent; } } /** 添加token */ void BooleanParser::addToken(Node *parent, const QString &str, Node::Type type) { if (in.mid(pos, str.length()) == str) { addChild(parent, new Node(type, str)); pos += str.length(); } } /** token匹配 */ bool BooleanParser::matchToken(const QString &str) const { return in.mid(pos, str.length()) == str; }
|