expr_node.dart 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. /// 结构化表达式模型 —— 计算器的输入不再是字符串,而是一棵树。
  2. ///
  3. /// 为什么值得单独做一套:纯文本光标表达不了多参数结构。用户按了 `∫` 之后
  4. /// 光标该放哪?按 `^` 之后指数该往哪写?用字符串只能靠"插入 `Integrate[, x]`
  5. /// 再把光标往回退 4 位"这种把戏,模板一复杂就散架,分数、上下标更是没法表达。
  6. /// 树 + 槽就没有这个问题。
  7. ///
  8. /// 分工:**计算器用这套结构化输入,控制台继续用纯文本**(长表达式、粘贴、
  9. /// 脚本式输入还是文本方便)。两者序列化后交给同一个求值内核。
  10. library;
  11. import 'package:meta/meta.dart';
  12. /// 表达式节点。
  13. sealed class ExprNode {
  14. const ExprNode();
  15. }
  16. /// 字面量:数字、变量名、常量。用字符串存,因为 `3.14`、`x`、`Pi` 都是文本。
  17. class LitNode extends ExprNode {
  18. /// 真正送进 Symja 的文本。
  19. final String text;
  20. /// **显示**用的名字。为 null 就显示 [text]。
  21. ///
  22. /// 用在"界面上该写人话、但引擎只认符号"的地方 —— 比如 `%`(Symja 的上一次
  23. /// 结果)在编辑框里显示成 `ANS` 更好认,但送进去必须是 `%`。
  24. final String? display;
  25. const LitNode(this.text, {this.display});
  26. }
  27. /// 函数调用:`name[arg0, arg1, …]`。每个参数是一个槽。
  28. class FuncNode extends ExprNode {
  29. final String name;
  30. final List<SeqNode> args;
  31. FuncNode(this.name, this.args);
  32. }
  33. /// 分式:分子 / 分母。
  34. class FracNode extends ExprNode {
  35. SeqNode num;
  36. SeqNode den;
  37. FracNode({required this.num, required this.den});
  38. }
  39. /// 幂:底 ^ 指数。
  40. class PowNode extends ExprNode {
  41. SeqNode base;
  42. SeqNode exp;
  43. PowNode({required this.base, required this.exp});
  44. }
  45. /// 括号分组 `( … )`。
  46. ///
  47. /// 用独立节点而不是把括号当字面量:括号必须成对且包住一整段,
  48. /// 当字面量的话用户能删掉半个括号,表达式就废了。
  49. class GroupNode extends ExprNode {
  50. SeqNode inner;
  51. GroupNode(this.inner);
  52. }
  53. /// 花括号列表 `{ … }`。
  54. ///
  55. /// 计算器自己不用它(Sum 的迭代范围是一个字面量),但**粘贴**进来的表达式
  56. /// 可能带花括号(`Sum[f, {n, 1, Infinity}]`),没有这个节点就解析不了。
  57. class BraceNode extends ExprNode {
  58. SeqNode inner;
  59. BraceNode(this.inner);
  60. }
  61. /// 大运算符:∫ / ∑ / ∏ / lim。
  62. ///
  63. /// 为什么要单独一个节点,而不是复用 `FuncNode` + `{x,a,b}` 那种写法:
  64. /// 上下限得单独成槽才画得到**习惯位置**(积分号的上方/下方、Σ 的上下、
  65. /// lim 的下方)。塞在一个花括号字面量里就只能顺着排,画不出来。
  66. ///
  67. /// 和 Symja 的对应关系(序列化时还原):
  68. /// Integrate[body, {variable, lower, upper}] 定积分;上下限都空时退化成不定积分
  69. /// Sum[body, {variable, lower, upper}] 求和
  70. /// Product[body, {variable, lower, upper}] 连乘
  71. /// Limit[body, variable -> lower] 极限(upper 不用)
  72. class BigOpNode extends ExprNode {
  73. /// 'Integrate' | 'Sum' | 'Product' | 'Limit'
  74. final String kind;
  75. /// 被积函数 / 求和项 / 取极限的表达式。
  76. SeqNode body;
  77. /// 积分变量 / 求和指标 / 趋近的变量。
  78. SeqNode variable;
  79. /// 下限:积分下限、求和起点、Limit 的趋近值。
  80. SeqNode lower;
  81. /// 上限。Limit 不用,留空槽且不显示。
  82. SeqNode upper;
  83. BigOpNode({
  84. required this.kind,
  85. required this.body,
  86. required this.variable,
  87. required this.lower,
  88. required this.upper,
  89. });
  90. bool get needsUpper => kind != 'Limit';
  91. bool get isDefinite => !lower.isEmpty || (needsUpper && !upper.isEmpty);
  92. }
  93. /// 后缀运算符,目前只有阶乘 `!`。
  94. class PostfixNode extends ExprNode {
  95. SeqNode operand;
  96. final String op;
  97. PostfixNode({required this.operand, this.op = '!'});
  98. }
  99. /// 一个槽 = 一串节点。分式的分子分母、函数的参数、幂的指数都是槽。
  100. class SeqNode {
  101. final List<ExprNode> children;
  102. SeqNode([List<ExprNode>? children]) : children = children ?? <ExprNode>[];
  103. bool get isEmpty => children.isEmpty;
  104. }
  105. /// 光标路径里的一跳:进入第 [child] 个孩子的第 [slot] 个槽。
  106. class SlotStep {
  107. final int child;
  108. final int slot;
  109. const SlotStep(this.child, this.slot);
  110. }
  111. /// 光标位置。空路径 = 根槽;[offset] 是在最终那个槽里的插入位置。
  112. class SlotPath {
  113. final List<SlotStep> steps;
  114. final int offset;
  115. const SlotPath(this.steps, this.offset);
  116. static const root = SlotPath(<SlotStep>[], 0);
  117. SlotPath push(int child, int slot) =>
  118. SlotPath([...steps, SlotStep(child, slot)], 0);
  119. /// 是否落在**同一个槽**里(只比路径,不比槽内位置)。
  120. ///
  121. /// 这个方法和 [operator ==] 的区别很关键:`offset` 是**槽内的插入位置**,
  122. /// 不属于"槽的身份"。渲染时判断"这个槽是不是光标所在的槽"必须用它 ——
  123. /// 早先用 `==` 比整个 SlotPath,而路径自带的 offset 恒为 0,
  124. /// 结果只有光标停在槽首时才认为聚焦,**打第一个字符光标就消失了**。
  125. bool sameSlotAs(SlotPath other) {
  126. if (other.steps.length != steps.length) return false;
  127. for (var i = 0; i < steps.length; i++) {
  128. if (steps[i].child != other.steps[i].child) return false;
  129. if (steps[i].slot != other.steps[i].slot) return false;
  130. }
  131. return true;
  132. }
  133. /// 回到父槽,并把光标停在刚才那个孩子之后。
  134. SlotPath? get parent {
  135. if (steps.isEmpty) return null;
  136. final last = steps.last;
  137. return SlotPath(steps.sublist(0, steps.length - 1), last.child + 1);
  138. }
  139. @override
  140. bool operator ==(Object other) {
  141. if (other is! SlotPath || other.offset != offset) return false;
  142. if (other.steps.length != steps.length) return false;
  143. for (var i = 0; i < steps.length; i++) {
  144. if (steps[i].child != other.steps[i].child) return false;
  145. if (steps[i].slot != other.steps[i].slot) return false;
  146. }
  147. return true;
  148. }
  149. @override
  150. int get hashCode =>
  151. Object.hash(offset, Object.hashAll(steps.map((s) => Object.hash(s.child, s.slot))));
  152. }
  153. /// 把一个槽序列化成 Symja 表达式。
  154. ///
  155. /// 序列化不依赖任何文档状态,所以给出这个顶层入口,
  156. /// 免得为了转个字符串还要 new 一个 ExprDoc。
  157. String symjaOf(SeqNode seq) => ExprDoc().serializeSeq(seq);
  158. /// 选区:**同一个槽里**一段连续的子节点。
  159. ///
  160. /// 不做跨槽的任意范围 —— 那要处理"从分子选到分母"这种语义模糊的情况,
  161. /// 而实际用起来,想剪切的东西几乎总在同一层(`2x+1` 就是根槽里连续的四个节点)。
  162. @immutable
  163. class SlotRange {
  164. final SlotPath path;
  165. final int start; // 含
  166. final int end; // 不含
  167. const SlotRange(this.path, this.start, this.end);
  168. bool get isEmpty => end <= start;
  169. @override
  170. bool operator ==(Object other) =>
  171. other is SlotRange && other.path == path && other.start == start && other.end == end;
  172. @override
  173. int get hashCode => Object.hash(path, start, end);
  174. }
  175. /// 编辑器文档:持有一棵树和一个光标,并实现所有编辑操作。
  176. ///
  177. /// 可变对象,调用方自己 setState。刻意不做成 ChangeNotifier —— 操作很密集
  178. /// (每敲一个键一次),让页面统一刷新比分发通知更简单也更快。
  179. class ExprDoc {
  180. final SeqNode root = SeqNode();
  181. SlotPath cursor = SlotPath.root;
  182. /// 当前选区。null = 没选中(此时操作都作用在光标处)。
  183. SlotRange? selection;
  184. // ------------------------------------------------------------------ 选区
  185. void selectNodeAt(SlotPath path, int index) {
  186. selection = SlotRange(path, index, index + 1);
  187. }
  188. /// 把选区扩展到包含第 [index] 个节点(按住不放再点另一个节点的语义)。
  189. /// 只支持同一个槽内,跨槽忽略。
  190. void extendSelectionTo(SlotPath path, int index) {
  191. final s = selection;
  192. if (s == null || !s.path.sameSlotAs(path)) return;
  193. selection = SlotRange(
  194. s.path,
  195. index < s.start ? index : s.start,
  196. index + 1 > s.end ? index + 1 : s.end,
  197. );
  198. }
  199. void clearSelection() => selection = null;
  200. /// 选中的节点(按原位序)。
  201. List<ExprNode> get selectedNodes {
  202. final s = selection;
  203. if (s == null || s.isEmpty) return const <ExprNode>[];
  204. final children = slotAt(s.path).children;
  205. final from = s.start.clamp(0, children.length);
  206. final to = s.end.clamp(0, children.length);
  207. return children.sublist(from, to);
  208. }
  209. /// 选区的 Symja 文本(复制到剪贴板的内容)。
  210. String get selectionText => symjaOf(SeqNode(selectedNodes));
  211. /// 删掉选区,光标落到选区起点。
  212. void deleteSelection() {
  213. final s = selection;
  214. if (s == null || s.isEmpty) return;
  215. final children = slotAt(s.path).children;
  216. final from = s.start.clamp(0, children.length);
  217. final to = s.end.clamp(0, children.length);
  218. children.removeRange(from, to);
  219. cursor = SlotPath(s.path.steps, from);
  220. selection = null;
  221. }
  222. /// 在光标处插入一串节点(粘贴用),插完光标落在它们之后。
  223. void insertNodesAtCursor(List<ExprNode> nodes) {
  224. if (nodes.isEmpty) return;
  225. final seq = current;
  226. final at = cursor.offset.clamp(0, seq.children.length);
  227. seq.children.insertAll(at, nodes);
  228. cursor = SlotPath(cursor.steps, at + nodes.length);
  229. selection = null;
  230. }
  231. // ------------------------------------------------------------------ 取槽
  232. /// 按路径找到对应的槽。路径失效时返回根槽。
  233. SeqNode slotAt(SlotPath path) {
  234. var seq = root;
  235. for (final step in path.steps) {
  236. if (step.child < 0 || step.child >= seq.children.length) return root;
  237. final node = seq.children[step.child];
  238. final slots = _slotsOf(node);
  239. if (step.slot < 0 || step.slot >= slots.length) return seq;
  240. seq = slots[step.slot];
  241. }
  242. return seq;
  243. }
  244. static List<SeqNode> _slotsOf(ExprNode node) => switch (node) {
  245. FuncNode f => f.args,
  246. FracNode f => [f.num, f.den], // 0=分子 1=分母
  247. PowNode p => [p.base, p.exp], // 0=底 1=指数
  248. GroupNode g => [g.inner],
  249. BraceNode b => [b.inner],
  250. BigOpNode b => [b.body, b.variable, b.lower, b.upper],
  251. PostfixNode p => [p.operand],
  252. LitNode _ => const <SeqNode>[],
  253. };
  254. SeqNode get current => slotAt(cursor);
  255. // ------------------------------------------------------------------ 插入
  256. /// 在当前光标处插入一个节点;[enterSlot] 不为空则顺便把光标移进它的某个槽。
  257. void insert(ExprNode node, {int? enterSlot}) {
  258. final seq = current;
  259. final at = cursor.offset.clamp(0, seq.children.length);
  260. seq.children.insert(at, node);
  261. cursor = enterSlot == null
  262. ? SlotPath(cursor.steps, at + 1)
  263. : _descend(cursor, at, enterSlot);
  264. }
  265. SlotPath _descend(SlotPath from, int child, int slot) =>
  266. from.push(child, slot);
  267. /// 插入一个字符。
  268. ///
  269. /// 数字和小数点会**并进左边那个数字字面量**,而不是各建一个节点 ——
  270. /// 否则 `42` 是两个节点,退格只删最后一位、显示上还分不出是一个数还是两个。
  271. void insertChar(String ch) {
  272. final seq = current;
  273. if (cursor.offset > 0 && seq.children.isNotEmpty) {
  274. final left = seq.children[cursor.offset - 1];
  275. if (left is LitNode && _isNumberText(left.text) && _isNumberChar(ch)) {
  276. seq.children[cursor.offset - 1] = LitNode(left.text + ch);
  277. return;
  278. }
  279. }
  280. insert(LitNode(ch));
  281. }
  282. static bool _isNumberText(String s) =>
  283. s.isNotEmpty && RegExp(r'^[0-9.]+$').hasMatch(s);
  284. static bool _isNumberChar(String c) => RegExp(r'^[0-9.]$').hasMatch(c);
  285. /// 造一个大运算符。光标落在 body 槽(要填的那个)。
  286. void makeBigOp(String kind, {String variable = 'x', String lower = '',
  287. String upper = ''}) {
  288. SeqNode lit(String t) => t.isEmpty ? SeqNode() : SeqNode([LitNode(t)]);
  289. insert(
  290. BigOpNode(
  291. kind: kind,
  292. body: SeqNode(),
  293. variable: lit(variable),
  294. lower: lit(lower),
  295. upper: lit(upper),
  296. ),
  297. enterSlot: 0,
  298. );
  299. }
  300. /// 插入一对括号(光标停在里面)。
  301. void makeGroup() => insert(GroupNode(SeqNode()), enterSlot: 0);
  302. /// 把当前槽里光标左边那个节点取出来(没有则返回 null),并把它从槽里摘掉。
  303. ///
  304. /// `^`、`/`、`√` 这些"把前面那个东西变成结构的一部分"的操作靠它实现 ——
  305. /// 这是结构化编辑器和纯文本手感最接近的地方:先打 `x` 再按 `^`,就成了 x 的幂。
  306. ExprNode? takeLeft() {
  307. final seq = current;
  308. if (cursor.offset <= 0 || cursor.offset > seq.children.length) return null;
  309. cursor = SlotPath(cursor.steps, cursor.offset - 1);
  310. return seq.children.removeAt(cursor.offset);
  311. }
  312. /// 制造一个幂:底 = 光标左边那个节点(没有就用空底),光标落到指数上。
  313. void makePower() {
  314. final base = takeLeft();
  315. final node = PowNode(base: SeqNode(base == null ? null : [base]), exp: SeqNode());
  316. insert(node, enterSlot: 1);
  317. }
  318. /// 制造一个分式:分子 = 光标左边那个节点(没有就空着),光标落到分母上。
  319. void makeFraction() {
  320. final num = takeLeft();
  321. final node = FracNode(num: SeqNode(num == null ? null : [num]), den: SeqNode());
  322. insert(node, enterSlot: 1);
  323. }
  324. /// 制造一个函数调用,光标落在第一个参数槽。
  325. ///
  326. /// [prefill] 每一项对应一个参数:[String] 为空表示**留一个空槽给用户填**,
  327. /// 非空则预置成字面量(例如 `Sum` 的 `{n, 1, Infinity}`)。
  328. void makeFunction(String name, {List<String> prefill = const []}) {
  329. insert(
  330. FuncNode(name, [
  331. for (final p in prefill)
  332. p.isEmpty ? SeqNode() : SeqNode([LitNode(p)]),
  333. if (prefill.isEmpty) SeqNode(),
  334. ]),
  335. enterSlot: 0,
  336. );
  337. }
  338. /// 切到当前函数调用的下一个参数;已经是最后一个就新建一个参数槽。
  339. ///
  340. /// 只能用在函数参数里(光标路径的最后一跳指向某个 FuncNode 的参数槽时)。
  341. void nextArgument() {
  342. if (cursor.steps.isEmpty) return;
  343. final here = cursor.steps.last;
  344. final parent = SlotPath(cursor.steps.sublist(0, cursor.steps.length - 1), 0);
  345. final siblings = slotAt(parent);
  346. if (here.child >= siblings.children.length) return;
  347. final node = siblings.children[here.child];
  348. if (node is! FuncNode) return;
  349. var target = here.slot + 1;
  350. if (target >= node.args.length) {
  351. node.args.add(SeqNode());
  352. target = node.args.length - 1;
  353. }
  354. cursor = parent.push(here.child, target);
  355. }
  356. // ------------------------------------------------------------------ 删除
  357. /// 槽里还有没填的空位("还没填完的模板")。
  358. static bool _incomplete(ExprNode n) => _slotsOf(n).any((s) => s.isEmpty);
  359. /// 退格。
  360. ///
  361. /// 三条规则,都是为了"手感":
  362. /// 1. 数字字面量**逐位删** —— 计算器按退格是删一位,不是把整个数清掉。
  363. /// 2. 左边是**还没填完的模板**(还有空槽)就钻进去删,而不是整个删掉 ——
  364. /// 用户按了 `∫` 后悔,一按退格整块模板没了会很难受。
  365. /// 3. 左边是**已经填完的模板**就整个删掉 —— 否则光标会永远在模板内部打转,
  366. /// 根本删不掉它。
  367. void backspace() {
  368. // 有选区就是"删掉选中的那段",这是谁都会先试的直觉
  369. if (selection != null && !selection!.isEmpty) {
  370. deleteSelection();
  371. return;
  372. }
  373. final seq = current;
  374. if (cursor.offset > 0 && seq.children.isNotEmpty) {
  375. final node = seq.children[cursor.offset - 1];
  376. // 规则 1
  377. if (node is LitNode && _isNumberText(node.text) && node.text.length > 1) {
  378. seq.children[cursor.offset - 1] =
  379. LitNode(node.text.substring(0, node.text.length - 1));
  380. return;
  381. }
  382. final slots = _slotsOf(node);
  383. if (slots.isEmpty) {
  384. seq.children.removeAt(cursor.offset - 1);
  385. cursor = SlotPath(cursor.steps, cursor.offset - 1);
  386. return;
  387. }
  388. if (_incomplete(node)) {
  389. // 规则 2:钻进最后一个空槽
  390. final i = slots.lastIndexWhere((s) => s.isEmpty);
  391. cursor = cursor.push(cursor.offset - 1, i);
  392. return;
  393. }
  394. // 规则 3
  395. seq.children.removeAt(cursor.offset - 1);
  396. cursor = SlotPath(cursor.steps, cursor.offset - 1);
  397. return;
  398. }
  399. // 已经在槽的最左边:退回父槽
  400. final up = cursor.parent;
  401. if (up == null) return; // 根槽最左边,没得删
  402. final parentSeq = slotAt(SlotPath(up.steps, up.offset));
  403. final idx = up.offset - 1;
  404. if (idx >= 0 && idx < parentSeq.children.length) {
  405. final child = parentSeq.children[idx];
  406. // 从"还没填完的模板"里退出来时,顺手把它也删掉
  407. if (_incomplete(child)) {
  408. parentSeq.children.removeAt(idx);
  409. cursor = SlotPath(up.steps, idx);
  410. return;
  411. }
  412. }
  413. cursor = up;
  414. }
  415. /// 用另一个槽的内容整体替换(粘贴用)。光标落到末尾 —— 粘完接着打最自然。
  416. void replaceWith(SeqNode other) {
  417. root.children
  418. ..clear()
  419. ..addAll(other.children);
  420. cursor = SlotPath(const <SlotStep>[], root.children.length);
  421. }
  422. void clear() {
  423. root.children.clear();
  424. cursor = SlotPath.root;
  425. }
  426. // ------------------------------------------------------------------ 序列化成 Symja
  427. /// 整棵树 → 一条 Symja 表达式。
  428. String toSymja() => serializeSeq(root);
  429. /// 槽 → 表达式。空槽在 Symja 里写成 `Null`,求值时会明确报错而不是静默算错。
  430. String serializeSeq(SeqNode seq) {
  431. if (seq.isEmpty) return 'Null';
  432. return seq.children.map(serialize).join();
  433. }
  434. String serialize(ExprNode node) => switch (node) {
  435. LitNode l => l.text,
  436. FuncNode f => '${f.name}[${f.args.map(serializeSeq).join(', ')}]',
  437. FracNode f => '${_grouped(serializeSeq(f.num))}/${_grouped(serializeSeq(f.den))}',
  438. PowNode p => '${_grouped(serializeSeq(p.base))}^${_grouped(serializeSeq(p.exp))}',
  439. GroupNode g => '(${serializeSeq(g.inner)})',
  440. BraceNode b => '{${serializeSeq(b.inner)}}',
  441. BigOpNode b => _serializeBigOp(b),
  442. PostfixNode p => '${_grouped(serializeSeq(p.operand))}${p.op}',
  443. };
  444. /// 大运算符还原成 Symja 写法。
  445. static String _serializeBigOp(BigOpNode b) {
  446. final body = ExprDoc().serializeSeq(b.body);
  447. final v = ExprDoc().serializeSeq(b.variable);
  448. if (b.kind == 'Limit') {
  449. // Limit[f, x -> 0]
  450. final to = ExprDoc().serializeSeq(b.lower);
  451. return 'Limit[$body, $v -> $to]';
  452. }
  453. // 上下限都空 → 不定积分这种,只给变量
  454. if (b.lower.isEmpty && b.upper.isEmpty) {
  455. return '${b.kind}[$body, $v]';
  456. }
  457. final lo = ExprDoc().serializeSeq(b.lower);
  458. final hi = ExprDoc().serializeSeq(b.upper);
  459. return '${b.kind}[$body, {$v, $lo, $hi}]';
  460. }
  461. /// 复合结构当操作数时要加括号,否则 `x+1` 当分母会算错优先级。
  462. ///
  463. /// 但**不多加**:整体已经被一对括号包住的(`(x+1)`)不再套一层成 `((x+1))`;
  464. /// 单个项(字面量、函数调用)本来就不需要括号。
  465. String _grouped(String s) {
  466. if (s.isEmpty) return s;
  467. if (_isFullyParenthesized(s)) return s;
  468. if (_isSimpleTerm(s)) return s;
  469. return '($s)';
  470. }
  471. /// 整个串恰好被一对括号包住(括号配平、且中间没有提前闭合)。
  472. static bool _isFullyParenthesized(String s) {
  473. if (!s.startsWith('(') || !s.endsWith(')')) return false;
  474. var depth = 0;
  475. for (var i = 0; i < s.length; i++) {
  476. if (s[i] == '(') {
  477. depth++;
  478. } else if (s[i] == ')') {
  479. depth--;
  480. if (depth == 0) return i == s.length - 1;
  481. }
  482. }
  483. return false;
  484. }
  485. /// 顶层没有运算符 —— 单个字面量、函数调用或括号组,当操作数不需要括号。
  486. ///
  487. /// `[` `]` `{` `}` 也算一层,所以 `Sin[x+1]` 里的 `+` 不算顶层运算符 ——
  488. /// 它本来就不用括号。开头的正负号是正负号不是运算符,跳过。
  489. static bool _isSimpleTerm(String s) {
  490. var depth = 0;
  491. for (var i = 0; i < s.length; i++) {
  492. final c = s[i];
  493. if (c == '(' || c == '[' || c == '{') {
  494. depth++;
  495. } else if (c == ')' || c == ']' || c == '}') {
  496. depth--;
  497. } else if (depth == 0 && '+-*/^'.contains(c)) {
  498. if (i == 0 && (c == '-' || c == '+')) continue;
  499. return false;
  500. }
  501. }
  502. return true;
  503. }
  504. }