Support calculate ^0.5

This commit is contained in:
2025-09-14 13:42:14 +08:00
parent c9190d05a1
commit e6a52b8b74
4 changed files with 149 additions and 16 deletions

View File

@@ -33,12 +33,12 @@ class Parser {
}
Expr parseMul() {
var expr = parseAtom();
var expr = parsePow();
skipSpaces();
while (!isEnd && (current == '*' || current == '/')) {
var op = current;
eat();
var right = parseAtom();
var right = parsePow();
if (op == '*') {
expr = MulExpr(expr, right);
} else {
@@ -49,6 +49,17 @@ class Parser {
return expr;
}
Expr parsePow() {
var expr = parseAtom();
skipSpaces();
if (!isEnd && current == '^') {
eat();
var right = parsePow(); // right associative
return PowExpr(expr, right);
}
return expr;
}
Expr parseAtom() {
skipSpaces();
if (current == '(') {
@@ -106,13 +117,20 @@ class Parser {
return VarExpr(varName);
}
// 解析
// 解析数字 (整数或小数)
var buf = '';
while (!isEnd && RegExp(r'\d').hasMatch(current)) {
bool hasDot = false;
while (!isEnd &&
(RegExp(r'\d').hasMatch(current) || (!hasDot && current == '.'))) {
if (current == '.') hasDot = true;
buf += current;
eat();
}
if (buf.isEmpty) throw Exception("无法解析: $current");
return IntExpr(int.parse(buf));
if (hasDot) {
return DoubleExpr(double.parse(buf));
} else {
return IntExpr(int.parse(buf));
}
}
}