expr_node.dart 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. /// 结构化表达式模型 —— 计算器的输入不再是字符串,而是一棵树。
  2. ///
  3. /// 为什么值得单独做一套:纯文本光标表达不了多参数结构。用户按了 `∫` 之后
  4. /// 光标该放哪?按 `^` 之后指数该往哪写?用字符串只能靠"插入 `Integrate[, x]`
  5. /// 再把光标往回退 4 位"这种把戏,模板一复杂就散架,分数、上下标更是没法表达。
  6. /// 树 + 槽就没有这个问题。
  7. ///
  8. /// 分工:**计算器用这套结构化输入,控制台继续用纯文本**(长表达式、粘贴、
  9. /// 脚本式输入还是文本方便)。两者序列化后交给同一个求值内核。
  10. library;
  11. /// 表达式节点。
  12. sealed class ExprNode {
  13. const ExprNode();
  14. }
  15. /// 字面量:数字、变量名、常量。用字符串存,因为 `3.14`、`x`、`Pi` 都是文本。
  16. class LitNode extends ExprNode {
  17. final String text;
  18. const LitNode(this.text);
  19. }
  20. /// 函数调用:`name[arg0, arg1, …]`。每个参数是一个槽。
  21. class FuncNode extends ExprNode {
  22. final String name;
  23. final List<SeqNode> args;
  24. FuncNode(this.name, this.args);
  25. }
  26. /// 分式:分子 / 分母。
  27. class FracNode extends ExprNode {
  28. SeqNode num;
  29. SeqNode den;
  30. FracNode({required this.num, required this.den});
  31. }
  32. /// 幂:底 ^ 指数。
  33. class PowNode extends ExprNode {
  34. SeqNode base;
  35. SeqNode exp;
  36. PowNode({required this.base, required this.exp});
  37. }
  38. /// 括号分组 `( … )`。
  39. ///
  40. /// 用独立节点而不是把括号当字面量:括号必须成对且包住一整段,
  41. /// 当字面量的话用户能删掉半个括号,表达式就废了。
  42. class GroupNode extends ExprNode {
  43. SeqNode inner;
  44. GroupNode(this.inner);
  45. }
  46. /// 后缀运算符,目前只有阶乘 `!`。
  47. class PostfixNode extends ExprNode {
  48. SeqNode operand;
  49. final String op;
  50. PostfixNode({required this.operand, this.op = '!'});
  51. }
  52. /// 一个槽 = 一串节点。分式的分子分母、函数的参数、幂的指数都是槽。
  53. class SeqNode {
  54. final List<ExprNode> children;
  55. SeqNode([List<ExprNode>? children]) : children = children ?? <ExprNode>[];
  56. bool get isEmpty => children.isEmpty;
  57. }
  58. /// 光标路径里的一跳:进入第 [child] 个孩子的第 [slot] 个槽。
  59. class SlotStep {
  60. final int child;
  61. final int slot;
  62. const SlotStep(this.child, this.slot);
  63. }
  64. /// 光标位置。空路径 = 根槽;[offset] 是在最终那个槽里的插入位置。
  65. class SlotPath {
  66. final List<SlotStep> steps;
  67. final int offset;
  68. const SlotPath(this.steps, this.offset);
  69. static const root = SlotPath(<SlotStep>[], 0);
  70. SlotPath push(int child, int slot) =>
  71. SlotPath([...steps, SlotStep(child, slot)], 0);
  72. /// 是否落在**同一个槽**里(只比路径,不比槽内位置)。
  73. ///
  74. /// 这个方法和 [operator ==] 的区别很关键:`offset` 是**槽内的插入位置**,
  75. /// 不属于"槽的身份"。渲染时判断"这个槽是不是光标所在的槽"必须用它 ——
  76. /// 早先用 `==` 比整个 SlotPath,而路径自带的 offset 恒为 0,
  77. /// 结果只有光标停在槽首时才认为聚焦,**打第一个字符光标就消失了**。
  78. bool sameSlotAs(SlotPath other) {
  79. if (other.steps.length != steps.length) return false;
  80. for (var i = 0; i < steps.length; i++) {
  81. if (steps[i].child != other.steps[i].child) return false;
  82. if (steps[i].slot != other.steps[i].slot) return false;
  83. }
  84. return true;
  85. }
  86. /// 回到父槽,并把光标停在刚才那个孩子之后。
  87. SlotPath? get parent {
  88. if (steps.isEmpty) return null;
  89. final last = steps.last;
  90. return SlotPath(steps.sublist(0, steps.length - 1), last.child + 1);
  91. }
  92. @override
  93. bool operator ==(Object other) {
  94. if (other is! SlotPath || other.offset != offset) return false;
  95. if (other.steps.length != steps.length) return false;
  96. for (var i = 0; i < steps.length; i++) {
  97. if (steps[i].child != other.steps[i].child) return false;
  98. if (steps[i].slot != other.steps[i].slot) return false;
  99. }
  100. return true;
  101. }
  102. @override
  103. int get hashCode =>
  104. Object.hash(offset, Object.hashAll(steps.map((s) => Object.hash(s.child, s.slot))));
  105. }
  106. /// 编辑器文档:持有一棵树和一个光标,并实现所有编辑操作。
  107. ///
  108. /// 可变对象,调用方自己 setState。刻意不做成 ChangeNotifier —— 操作很密集
  109. /// (每敲一个键一次),让页面统一刷新比分发通知更简单也更快。
  110. class ExprDoc {
  111. final SeqNode root = SeqNode();
  112. SlotPath cursor = SlotPath.root;
  113. // ------------------------------------------------------------------ 取槽
  114. /// 按路径找到对应的槽。路径失效时返回根槽。
  115. SeqNode slotAt(SlotPath path) {
  116. var seq = root;
  117. for (final step in path.steps) {
  118. if (step.child < 0 || step.child >= seq.children.length) return root;
  119. final node = seq.children[step.child];
  120. final slots = _slotsOf(node);
  121. if (step.slot < 0 || step.slot >= slots.length) return seq;
  122. seq = slots[step.slot];
  123. }
  124. return seq;
  125. }
  126. static List<SeqNode> _slotsOf(ExprNode node) => switch (node) {
  127. FuncNode f => f.args,
  128. FracNode f => [f.num, f.den], // 0=分子 1=分母
  129. PowNode p => [p.base, p.exp], // 0=底 1=指数
  130. GroupNode g => [g.inner],
  131. PostfixNode p => [p.operand],
  132. LitNode _ => const <SeqNode>[],
  133. };
  134. SeqNode get current => slotAt(cursor);
  135. // ------------------------------------------------------------------ 插入
  136. /// 在当前光标处插入一个节点;[enterSlot] 不为空则顺便把光标移进它的某个槽。
  137. void insert(ExprNode node, {int? enterSlot}) {
  138. final seq = current;
  139. final at = cursor.offset.clamp(0, seq.children.length);
  140. seq.children.insert(at, node);
  141. cursor = enterSlot == null
  142. ? SlotPath(cursor.steps, at + 1)
  143. : _descend(cursor, at, enterSlot);
  144. }
  145. SlotPath _descend(SlotPath from, int child, int slot) =>
  146. from.push(child, slot);
  147. /// 插入一个字符。
  148. ///
  149. /// 数字和小数点会**并进左边那个数字字面量**,而不是各建一个节点 ——
  150. /// 否则 `42` 是两个节点,退格只删最后一位、显示上还分不出是一个数还是两个。
  151. void insertChar(String ch) {
  152. final seq = current;
  153. if (cursor.offset > 0 && seq.children.isNotEmpty) {
  154. final left = seq.children[cursor.offset - 1];
  155. if (left is LitNode && _isNumberText(left.text) && _isNumberChar(ch)) {
  156. seq.children[cursor.offset - 1] = LitNode(left.text + ch);
  157. return;
  158. }
  159. }
  160. insert(LitNode(ch));
  161. }
  162. static bool _isNumberText(String s) =>
  163. s.isNotEmpty && RegExp(r'^[0-9.]+$').hasMatch(s);
  164. static bool _isNumberChar(String c) => RegExp(r'^[0-9.]$').hasMatch(c);
  165. /// 插入一对括号(光标停在里面)。
  166. void makeGroup() => insert(GroupNode(SeqNode()), enterSlot: 0);
  167. /// 把当前槽里光标左边那个节点取出来(没有则返回 null),并把它从槽里摘掉。
  168. ///
  169. /// `^`、`/`、`√` 这些"把前面那个东西变成结构的一部分"的操作靠它实现 ——
  170. /// 这是结构化编辑器和纯文本手感最接近的地方:先打 `x` 再按 `^`,就成了 x 的幂。
  171. ExprNode? takeLeft() {
  172. final seq = current;
  173. if (cursor.offset <= 0 || cursor.offset > seq.children.length) return null;
  174. cursor = SlotPath(cursor.steps, cursor.offset - 1);
  175. return seq.children.removeAt(cursor.offset);
  176. }
  177. /// 制造一个幂:底 = 光标左边那个节点(没有就用空底),光标落到指数上。
  178. void makePower() {
  179. final base = takeLeft();
  180. final node = PowNode(base: SeqNode(base == null ? null : [base]), exp: SeqNode());
  181. insert(node, enterSlot: 1);
  182. }
  183. /// 制造一个分式:分子 = 光标左边那个节点(没有就空着),光标落到分母上。
  184. void makeFraction() {
  185. final num = takeLeft();
  186. final node = FracNode(num: SeqNode(num == null ? null : [num]), den: SeqNode());
  187. insert(node, enterSlot: 1);
  188. }
  189. /// 制造一个函数调用,光标落在第一个参数槽。
  190. ///
  191. /// [prefill] 每一项对应一个参数:[String] 为空表示**留一个空槽给用户填**,
  192. /// 非空则预置成字面量(例如 `Sum` 的 `{n, 1, Infinity}`)。
  193. void makeFunction(String name, {List<String> prefill = const []}) {
  194. insert(
  195. FuncNode(name, [
  196. for (final p in prefill)
  197. p.isEmpty ? SeqNode() : SeqNode([LitNode(p)]),
  198. if (prefill.isEmpty) SeqNode(),
  199. ]),
  200. enterSlot: 0,
  201. );
  202. }
  203. /// 槽尾是不是运算符 —— 说明用户这句还没写完。
  204. static const _operators = {'+', '-', '*', '/', '^', ','};
  205. static bool _endsWithOperator(SeqNode seq) {
  206. if (seq.children.isEmpty) return false;
  207. final last = seq.children.last;
  208. return last is LitNode && _operators.contains(last.text);
  209. }
  210. /// 单参数(或多参数带预置)函数键的行为。
  211. ///
  212. /// 两种情况,按"用户此刻想干什么"分:
  213. ///
  214. /// 1. **光标在槽尾、槽里有内容、且最后不是运算符** → 把**整槽内容**包进函数。
  215. /// 用户打完 `2x+1` 按 `ln`,要的是 `Log[2x+1]`,不是 `Log[]` 再让他重打。
  216. /// (注意是**整槽**不是"左边那个节点" —— `2x+1` 是四个节点,
  217. /// 只包最后一个会变成 `2x+Log[1]`。)
  218. ///
  219. /// 2. **其余情况** → 插一个空模板,光标进括号里。
  220. /// 空槽时按 `ln` 就是这种情况;光标停在中间时也是。
  221. ///
  222. /// 一个刻意的例外:槽尾是运算符(用户刚打完 `1+`)**不包**。
  223. /// 那时他想要的是 `1+Log[...]`,包起来会变成 `Log[1+]`。
  224. ///
  225. /// [prefill] 里的第一项留空表示"由上面两种情况决定",其余项原样预置。
  226. void applyFunction(String name, {List<String> prefill = const []}) {
  227. final seq = current;
  228. final atEnd = cursor.offset >= seq.children.length;
  229. final shouldWrap =
  230. atEnd && seq.children.isNotEmpty && !_endsWithOperator(seq);
  231. // prefill 的第一项是"要填的那个参数",包裹时被整槽内容顶替;
  232. // 没有 prefill 的函数(Sin、Log…)就只有一个参数。
  233. final rest = prefill.isEmpty ? const <String>[] : prefill.sublist(1);
  234. if (!shouldWrap) {
  235. makeFunction(name, prefill: prefill);
  236. return;
  237. }
  238. final inner = SeqNode(List<ExprNode>.from(seq.children));
  239. seq.children.clear();
  240. seq.children.add(FuncNode(name, [
  241. inner,
  242. for (final p in rest) p.isEmpty ? SeqNode() : SeqNode([LitNode(p)]),
  243. ]));
  244. cursor = SlotPath(cursor.steps, 1);
  245. }
  246. /// 切到当前函数调用的下一个参数;已经是最后一个就新建一个参数槽。
  247. ///
  248. /// 只能用在函数参数里(光标路径的最后一跳指向某个 FuncNode 的参数槽时)。
  249. void nextArgument() {
  250. if (cursor.steps.isEmpty) return;
  251. final here = cursor.steps.last;
  252. final parent = SlotPath(cursor.steps.sublist(0, cursor.steps.length - 1), 0);
  253. final siblings = slotAt(parent);
  254. if (here.child >= siblings.children.length) return;
  255. final node = siblings.children[here.child];
  256. if (node is! FuncNode) return;
  257. var target = here.slot + 1;
  258. if (target >= node.args.length) {
  259. node.args.add(SeqNode());
  260. target = node.args.length - 1;
  261. }
  262. cursor = parent.push(here.child, target);
  263. }
  264. // ------------------------------------------------------------------ 删除
  265. /// 槽里还有没填的空位("还没填完的模板")。
  266. static bool _incomplete(ExprNode n) => _slotsOf(n).any((s) => s.isEmpty);
  267. /// 退格。
  268. ///
  269. /// 三条规则,都是为了"手感":
  270. /// 1. 数字字面量**逐位删** —— 计算器按退格是删一位,不是把整个数清掉。
  271. /// 2. 左边是**还没填完的模板**(还有空槽)就钻进去删,而不是整个删掉 ——
  272. /// 用户按了 `∫` 后悔,一按退格整块模板没了会很难受。
  273. /// 3. 左边是**已经填完的模板**就整个删掉 —— 否则光标会永远在模板内部打转,
  274. /// 根本删不掉它。
  275. void backspace() {
  276. final seq = current;
  277. if (cursor.offset > 0 && seq.children.isNotEmpty) {
  278. final node = seq.children[cursor.offset - 1];
  279. // 规则 1
  280. if (node is LitNode && _isNumberText(node.text) && node.text.length > 1) {
  281. seq.children[cursor.offset - 1] =
  282. LitNode(node.text.substring(0, node.text.length - 1));
  283. return;
  284. }
  285. final slots = _slotsOf(node);
  286. if (slots.isEmpty) {
  287. seq.children.removeAt(cursor.offset - 1);
  288. cursor = SlotPath(cursor.steps, cursor.offset - 1);
  289. return;
  290. }
  291. if (_incomplete(node)) {
  292. // 规则 2:钻进最后一个空槽
  293. final i = slots.lastIndexWhere((s) => s.isEmpty);
  294. cursor = cursor.push(cursor.offset - 1, i);
  295. return;
  296. }
  297. // 规则 3
  298. seq.children.removeAt(cursor.offset - 1);
  299. cursor = SlotPath(cursor.steps, cursor.offset - 1);
  300. return;
  301. }
  302. // 已经在槽的最左边:退回父槽
  303. final up = cursor.parent;
  304. if (up == null) return; // 根槽最左边,没得删
  305. final parentSeq = slotAt(SlotPath(up.steps, up.offset));
  306. final idx = up.offset - 1;
  307. if (idx >= 0 && idx < parentSeq.children.length) {
  308. final child = parentSeq.children[idx];
  309. // 从"还没填完的模板"里退出来时,顺手把它也删掉
  310. if (_incomplete(child)) {
  311. parentSeq.children.removeAt(idx);
  312. cursor = SlotPath(up.steps, idx);
  313. return;
  314. }
  315. }
  316. cursor = up;
  317. }
  318. void clear() {
  319. root.children.clear();
  320. cursor = SlotPath.root;
  321. }
  322. // ------------------------------------------------------------------ 序列化成 Symja
  323. /// 整棵树 → 一条 Symja 表达式。
  324. String toSymja() => serializeSeq(root);
  325. /// 槽 → 表达式。空槽在 Symja 里写成 `Null`,求值时会明确报错而不是静默算错。
  326. String serializeSeq(SeqNode seq) {
  327. if (seq.isEmpty) return 'Null';
  328. return seq.children.map(serialize).join();
  329. }
  330. String serialize(ExprNode node) => switch (node) {
  331. LitNode l => l.text,
  332. FuncNode f =>
  333. '${f.name}[${f.args.map(serializeSeq).join(', ')}]',
  334. FracNode f => '${_grouped(serializeSeq(f.num))}/${_grouped(serializeSeq(f.den))}',
  335. PowNode p => '${_grouped(serializeSeq(p.base))}^${_grouped(serializeSeq(p.exp))}',
  336. GroupNode g => '(${serializeSeq(g.inner)})',
  337. PostfixNode p => '${_grouped(serializeSeq(p.operand))}${p.op}',
  338. };
  339. /// 复合结构当操作数时要加括号,否则 `x+1` 当分母会算错优先级。
  340. String _grouped(String s) {
  341. if (s.isEmpty) return s;
  342. final needsParens = s.contains(RegExp(r'[+\-*/^]')) ||
  343. (s.contains(' ') && s.contains(','));
  344. return needsParens ? '($s)' : s;
  345. }
  346. }