Implement object inheritance: # Child = > Parent (I0-I2)
- Parse `# Child = > Parent` object decls (base must be a simple name after `>`; dotted bases and `# Foo = 1` are diagnostics). - Validate in load: unknown base types and cyclic inheritance (A → B → A) fail with line/col. - Method resolution walks the base chain (most specific first) on both tree and bytecode backends; `_type` stays the child name; same-name child ## overrides the parent. - Add inherit.rs, wire Program.object_bases, gold fixtures (inherit-parent-method / inherit-override + cycle/unknown-base/bad-rhs) and public 09-inherit demo pages. Docs: objects.md, markdown-mapping, roadmap, skill. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
a23fdedfa2
commit
5456d9ff83
25 files changed
+590
-41
No files matched your search
@@ -30,7 +30,7 @@ Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords.
|
||||
|
||||
| Marker | Meaning |
|
||||
|--------|---------|
|
||||
| `#` | **Object / type** (constructor body). `# main` = entry object. |
|
||||
| `#` | **Object / type** (constructor body). `# main` = entry object. `# Child = > Parent` = inherit. |
|
||||
| `##` … `######` | **Function / method** (nesting by heading depth). |
|
||||
| `` + `name` `` under heading | Parameter (optional `` `name`=default ``) |
|
||||
| `1.` `2.` … in body | Branch arm (condition or `N. *` else). **Same-indent restart at `1.` = new branch statement** (not more arms of the previous list). |
|
||||
|
||||
@@ -155,6 +155,28 @@ description: loads math
|
||||
|
||||
See `tests/structure/object-handle.mq.md` and `ext/llm.mq.md`: `# Type` constructs a map with `_type`; methods use `` > `obj`.method `` and read `self` / `自`.
|
||||
|
||||
## 10b. Object inheritance
|
||||
|
||||
```markdown
|
||||
# Greeter
|
||||
|
||||
## hello
|
||||
+ `who`
|
||||
|
||||
*`msg` = "Hello, `who`!" *
|
||||
**`msg`**
|
||||
|
||||
# Loud = > Greeter
|
||||
|
||||
## hello
|
||||
+ `who`
|
||||
|
||||
*`msg` = "HELLO, `who`!" *
|
||||
**`msg`**
|
||||
```
|
||||
|
||||
`_type` stays the most specific name (`Loud`). Methods walk the base chain; same-name `##` on the child overrides. No implicit super in v1.
|
||||
|
||||
## 11. Agent layout (ABI)
|
||||
|
||||
```markdown
|
||||
|
||||
+1
-1
@@ -53,7 +53,7 @@
|
||||
| [roadmap/next-phase.md](roadmap/next-phase.md) | **下一阶段:input / 诊断 / 标准库 / view 调试** |
|
||||
| [roadmap/okf-near-match.md](roadmap/okf-near-match.md) | **规划:OKF 相近任务命中**(精确 sig 之外的可选软复用) |
|
||||
| [roadmap/agent-streaming.md](roadmap/agent-streaming.md) | **规划:智能体 / LLM 流式输出**(事件模型 + step/plan 透传) |
|
||||
| [roadmap/object-inheritance.md](roadmap/object-inheritance.md) | **规划:对象继承**(`# 子类 = > 父类`) |
|
||||
| [roadmap/object-inheritance.md](roadmap/object-inheritance.md) | **对象继承**(`# 子类 = > 父类`;I0–I2 已落地) |
|
||||
| [roadmap/tables-maps-footnotes.md](roadmap/tables-maps-footnotes.md) | **表格语义**(竖表 / 横表字典 / 脚注取元 / 行向记录;T0–T4 已落地) |
|
||||
| [roadmap/ext-web.md](roadmap/ext-web.md) | **规划:`ext/web` 动态网页**(env/DB init·迁移·样式脚手架·ABI) |
|
||||
| [roadmap/ext-quantum.md](roadmap/ext-quantum.md) | **规划:`ext/quantum` 量子模拟**(基础门·电路·ABI·`ext add`) |
|
||||
|
||||
@@ -40,7 +40,7 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置
|
||||
|
||||
| 标记 | 语义 |
|
||||
|------|------|
|
||||
| `#` … `######` | **`#` = 对象/类型**;**`##`+ = 函数/方法**(层差=嵌套)。见 [objects.md](objects.md) |
|
||||
| `#` … `######` | **`#` = 对象/类型**(可 `# Child = > Parent`);**`##`+ = 函数/方法**(层差=嵌套)。见 [objects.md](objects.md) |
|
||||
| 函数头下 `+ `` `名` `` ` | 形参 / 构造参数(可选 `` `名`=默认值 ``) |
|
||||
| 体内 `1.` `2.` … | **分支**(有序列表臂;条件行或 else) |
|
||||
| 体内 `-` | **循环**(`while` 条件,或 `` [`项`](`集合`) `` 遍历) |
|
||||
@@ -129,6 +129,7 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置
|
||||
## 6. 对象、函数、形参
|
||||
|
||||
- `# Name`:对象(构造体);`# main` 为入口对象。
|
||||
- `# Child = > Parent`:单继承(基类须为已定义对象名;方法沿链查找,子类可覆盖)。见 [objects.md](objects.md) §5。
|
||||
- `##` / `###` …:函数或方法;挂在对象下则为方法。
|
||||
- 标准库顶层 API 使用自由函数 `## name`(见 [objects.md](objects.md))。
|
||||
|
||||
|
||||
+35
-4
@@ -58,13 +58,44 @@
|
||||
官方 `lib/*.mq.md` 以**顶层自由函数**为主:全部为 `##`(不再使用 `#` 冒充类型)。
|
||||
真正的类型化扩展(如 `ext/llm`)使用 `# 类型` + `##` 方法。
|
||||
|
||||
## 5. 非目标(本波)
|
||||
## 5. 继承(`# 子类 = > 父类`)
|
||||
|
||||
- 继承 / 接口 / 可见性 — **继承语法已单独立项规划**,见 [object-inheritance.md](../roadmap/object-inheritance.md)(提案:`# 子类 = > 父类`)
|
||||
```markdown
|
||||
# Greeter
|
||||
|
||||
## hello
|
||||
+ `who`
|
||||
|
||||
*`msg` = "Hello, `who`!" *
|
||||
**`msg`**
|
||||
|
||||
# Loud = > Greeter
|
||||
|
||||
## hello
|
||||
+ `who`
|
||||
|
||||
*`msg` = "HELLO, `who`!" *
|
||||
**`msg`**
|
||||
```
|
||||
|
||||
| 规则 | 说明 |
|
||||
|------|------|
|
||||
| 语法 | `# Child = > Parent`(右侧必须是 `>` + 简单类型名;无路径) |
|
||||
| `_type` | 构造后仍为**最具体子类名** |
|
||||
| 方法查找 | 先子类 `##`,未命中再沿基类链;同名则子类覆盖 |
|
||||
| 构造 | v1 **不**隐式调用父构造;需要时在子类正文显式 `` `self` = > Parent … `` |
|
||||
| 多继承 | 不支持 |
|
||||
| 诊断 | 未知基类、循环继承、非法 RHS(如 `# Foo = 1`) |
|
||||
|
||||
详见 [object-inheritance.md](../roadmap/object-inheritance.md)。
|
||||
|
||||
## 6. 非目标(本波)
|
||||
|
||||
- 接口 / 可见性 / 多继承
|
||||
- 无 `_type` 的「鸭子」方法分发
|
||||
- 用表格声明字段 schema(表格仍表示数据集合;几何语义打磨见 [tables-maps-footnotes.md](../roadmap/tables-maps-footnotes.md))
|
||||
- 用表格声明字段 schema(表格仍表示数据集合;见 [tables-maps-footnotes.md](../roadmap/tables-maps-footnotes.md))
|
||||
|
||||
## 6. 迁移摘要
|
||||
## 7. 迁移摘要
|
||||
|
||||
| 旧 | 新 |
|
||||
|----|----|
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **规划 / 未开工** |
|
||||
| 日期 | 2026-08-09 |
|
||||
| 状态 | **I0–I2 已落地**(I3 隐式 super 仍可选) |
|
||||
| 日期 | 2026-08-10 |
|
||||
| 相关 | [objects.md](../design/objects.md) · [markdown-mapping.md](../design/markdown-mapping.md) · [keywords.md](../design/keywords.md) |
|
||||
| 提案语法 | `# 子类 = > 父类` |
|
||||
|
||||
@@ -136,9 +136,9 @@
|
||||
## 6. 推荐落地顺序
|
||||
|
||||
```text
|
||||
I0 语法 + AST + 金样(解析/循环继承错误)
|
||||
I1 方法解析沿基类链;构造 _type=子类
|
||||
I2 覆盖方法;文档更新 objects.md(移出「非目标」)
|
||||
I0 语法 + AST + 金样(解析/循环继承错误) ✅
|
||||
I1 方法解析沿基类链;构造 _type=子类 ✅
|
||||
I2 覆盖方法;文档更新 objects.md ✅
|
||||
I3 (可选)子构造约定:显式 > 父类 … 或隐式 super
|
||||
```
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
title: Object inheritance
|
||||
description: "# Child = > Parent; methods walk the base chain"
|
||||
---
|
||||
|
||||
# Greeter
|
||||
|
||||
## hello
|
||||
+ `who`
|
||||
|
||||
*`msg` = "Hello, `who`!" *
|
||||
**`msg`**
|
||||
|
||||
# Loud = > Greeter
|
||||
|
||||
## hello
|
||||
+ `who`
|
||||
|
||||
*`msg` = "HELLO, `who`!" *
|
||||
**`msg`**
|
||||
|
||||
# main
|
||||
|
||||
*`g` = > Greeter *
|
||||
*`m` = > `g`.hello who=world *
|
||||
> print text=`m`
|
||||
*`l` = > Loud *
|
||||
*`m2` = > `l`.hello who=world *
|
||||
> print text=`m2`
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
title: 对象继承
|
||||
description: "# 子类 = > 父类;方法沿基类链查找"
|
||||
---
|
||||
|
||||
# 问候者
|
||||
|
||||
## 你好
|
||||
+ `谁`
|
||||
|
||||
*`msg` = "你好,`谁`!" *
|
||||
**`msg`**
|
||||
|
||||
# 大声 = > 问候者
|
||||
|
||||
## 你好
|
||||
+ `谁`
|
||||
|
||||
*`msg` = "你好,`谁`!!!" *
|
||||
**`msg`**
|
||||
|
||||
# main
|
||||
|
||||
*`g` = > 问候者 *
|
||||
*`m` = > `g`.你好 谁=世界 *
|
||||
> 打印 内容=`m`
|
||||
*`l` = > 大声 *
|
||||
*`m2` = > `l`.你好 谁=世界 *
|
||||
> 打印 内容=`m2`
|
||||
@@ -29,7 +29,7 @@ Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords.
|
||||
|
||||
| Marker | Meaning |
|
||||
|--------|---------|
|
||||
| `#` | **Object / type** (constructor body). `# main` = entry object. |
|
||||
| `#` | **Object / type** (constructor body). `# main` = entry object. `# Child = > Parent` = inherit. |
|
||||
| `##` … `######` | **Function / method** (nesting by heading depth). |
|
||||
| `` + `name` `` under heading | Parameter (optional `` `name`=default ``) |
|
||||
| `1.` `2.` … in body | Branch arm (condition or `N. *` else). **Same-indent restart at `1.` = new branch statement** (not more arms of the previous list). |
|
||||
|
||||
@@ -155,6 +155,28 @@ description: loads math
|
||||
|
||||
See `tests/structure/object-handle.mq.md` and `ext/llm.mq.md`: `# Type` constructs a map with `_type`; methods use `` > `obj`.method `` and read `self` / `自`.
|
||||
|
||||
## 10b. Object inheritance
|
||||
|
||||
```markdown
|
||||
# Greeter
|
||||
|
||||
## hello
|
||||
+ `who`
|
||||
|
||||
*`msg` = "Hello, `who`!" *
|
||||
**`msg`**
|
||||
|
||||
# Loud = > Greeter
|
||||
|
||||
## hello
|
||||
+ `who`
|
||||
|
||||
*`msg` = "HELLO, `who`!" *
|
||||
**`msg`**
|
||||
```
|
||||
|
||||
`_type` stays the most specific name (`Loud`). Methods walk the base chain; same-name `##` on the child overrides. No implicit super in v1.
|
||||
|
||||
## 11. Agent layout (ABI)
|
||||
|
||||
```markdown
|
||||
|
||||
+12
-4
@@ -55,6 +55,8 @@ pub struct Function {
|
||||
pub params: Vec<Param>,
|
||||
pub body: Vec<Stmt>,
|
||||
pub children: Vec<Function>,
|
||||
/// Base type name for `# Child = > Parent` (objects only).
|
||||
pub base: Option<String>,
|
||||
}
|
||||
|
||||
impl Function {
|
||||
@@ -211,10 +213,16 @@ pub fn format_ast_dump(path: &str, module: &Module) -> String {
|
||||
fn dump_fun(out: &mut String, fun: &Function, depth: usize) {
|
||||
let pad = " ".repeat(depth);
|
||||
let kind = if fun.is_object() { "object" } else { "fun" };
|
||||
out.push_str(&format!(
|
||||
"{pad}({kind} level={} {:?} params={:?} @{}\n",
|
||||
fun.level, fun.name, fun.params, fun.span
|
||||
));
|
||||
match &fun.base {
|
||||
Some(base) => out.push_str(&format!(
|
||||
"{pad}({kind} level={} {:?} extends={base:?} params={:?} @{}\n",
|
||||
fun.level, fun.name, fun.params, fun.span
|
||||
)),
|
||||
None => out.push_str(&format!(
|
||||
"{pad}({kind} level={} {:?} params={:?} @{}\n",
|
||||
fun.level, fun.name, fun.params, fun.span
|
||||
)),
|
||||
}
|
||||
for stmt in &fun.body {
|
||||
dump_stmt(out, stmt, depth + 1);
|
||||
}
|
||||
|
||||
@@ -15,6 +15,8 @@ struct FlatFun {
|
||||
name: String,
|
||||
level: u8,
|
||||
parent: Option<usize>,
|
||||
/// Inheritance base type name (`# Child = > Parent`), objects only.
|
||||
base: Option<String>,
|
||||
params: Vec<Param>,
|
||||
body: Vec<Stmt>,
|
||||
children: Vec<usize>,
|
||||
@@ -60,6 +62,19 @@ pub fn compile_module(path: Option<&Path>, module: &Module) -> Result<Program> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let name_to_flat: HashMap<&str, usize> = objects
|
||||
.iter()
|
||||
.map(|(n, i)| (n.as_str(), *i))
|
||||
.collect();
|
||||
let mut object_bases = Vec::with_capacity(objects.len());
|
||||
for (name, _) in &objects {
|
||||
let flat_i = name_to_flat[name.as_str()];
|
||||
let base = flat[flat_i]
|
||||
.base
|
||||
.as_deref()
|
||||
.and_then(|b| name_to_flat.get(b).copied());
|
||||
object_bases.push(base);
|
||||
}
|
||||
|
||||
let path_buf = path.map(|p| p.to_path_buf());
|
||||
let mut functions = Vec::new();
|
||||
@@ -74,6 +89,7 @@ pub fn compile_module(path: Option<&Path>, module: &Module) -> Result<Program> {
|
||||
functions,
|
||||
entry,
|
||||
objects,
|
||||
object_bases,
|
||||
methods,
|
||||
parents,
|
||||
children,
|
||||
@@ -134,6 +150,7 @@ fn collect_fun(
|
||||
name: fun.name.clone(),
|
||||
level: fun.level,
|
||||
parent,
|
||||
base: fun.base.clone(),
|
||||
params: fun.params.clone(),
|
||||
body: fun.body.clone(),
|
||||
children: Vec::new(),
|
||||
|
||||
@@ -92,6 +92,8 @@ pub struct Program {
|
||||
pub entry: usize,
|
||||
/// Top-level object name → function index (level-1).
|
||||
pub objects: Vec<(String, usize)>,
|
||||
/// Parallel to `objects`: base object flat index (`# Child = > Parent`).
|
||||
pub object_bases: Vec<Option<usize>>,
|
||||
/// (object_fn_idx, method_name) → method fn idx
|
||||
pub methods: Vec<(usize, String, usize)>,
|
||||
/// Parallel to `functions`: parent fn index for dynamic `call_fn` lookup.
|
||||
|
||||
+46
-11
@@ -402,25 +402,38 @@ impl Vm {
|
||||
}
|
||||
vals.reverse();
|
||||
let type_name = instance_type_name_bc(&recv).map_err(|m| self.err_at(span, m))?;
|
||||
let obj_idx = program
|
||||
let start_oi = program
|
||||
.objects
|
||||
.iter()
|
||||
.find(|(n, _)| n == &type_name)
|
||||
.map(|(_, i)| *i)
|
||||
.position(|(n, _)| n == &type_name)
|
||||
.ok_or_else(|| {
|
||||
self.err_at(span, format!("unknown object type `{type_name}`"))
|
||||
})?;
|
||||
let method_fid = program
|
||||
.methods
|
||||
.iter()
|
||||
.find(|(o, m, _)| *o == obj_idx && m == &method_name)
|
||||
.map(|(_, _, i)| *i)
|
||||
.ok_or_else(|| {
|
||||
let method_fid = resolve_method_fid(program, start_oi, &method_name).ok_or_else(
|
||||
|| {
|
||||
let mut chain = Vec::new();
|
||||
let mut oi = Some(start_oi);
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
while let Some(i) = oi {
|
||||
if !seen.insert(i) {
|
||||
break;
|
||||
}
|
||||
chain.push(program.objects[i].0.as_str());
|
||||
oi = program.object_bases.get(i).copied().flatten().and_then(
|
||||
|base_flat| {
|
||||
program.objects.iter().position(|(_, f)| *f == base_flat)
|
||||
},
|
||||
);
|
||||
}
|
||||
self.err_at(
|
||||
span,
|
||||
format!("unknown method `{type_name}.{method_name}`"),
|
||||
format!(
|
||||
"unknown method `{type_name}.{method_name}` (searched {})",
|
||||
chain.join(" → ")
|
||||
),
|
||||
)
|
||||
})?;
|
||||
},
|
||||
)?;
|
||||
let callee = &program.functions[method_fid];
|
||||
if callee.params.len() != argc {
|
||||
return Err(self.err_at(span, "method argument count mismatch"));
|
||||
@@ -546,6 +559,28 @@ impl Vm {
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_method_fid(program: &Program, start_oi: usize, method_name: &str) -> Option<usize> {
|
||||
let mut oi = Some(start_oi);
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
while let Some(i) = oi {
|
||||
if !seen.insert(i) {
|
||||
break;
|
||||
}
|
||||
let obj_flat = program.objects[i].1;
|
||||
if let Some((_, _, fid)) = program
|
||||
.methods
|
||||
.iter()
|
||||
.find(|(o, m, _)| *o == obj_flat && m == method_name)
|
||||
{
|
||||
return Some(*fid);
|
||||
}
|
||||
oi = program.object_bases.get(i).copied().flatten().and_then(|base_flat| {
|
||||
program.objects.iter().position(|(_, f)| *f == base_flat)
|
||||
});
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn pop(stack: &mut Vec<Value>) -> Result<Value, String> {
|
||||
stack
|
||||
.pop()
|
||||
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
//! Object inheritance: `# Child = > Parent` validation and helpers.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use anyhow::Result;
|
||||
|
||||
use crate::ast::{Function, Module};
|
||||
use crate::diagnostics::{Diagnostic, Span};
|
||||
|
||||
/// Validate that every object's `base` resolves and that the inheritance graph is acyclic.
|
||||
pub fn validate_inheritance(module: &Module) -> Result<()> {
|
||||
let mut by_name: HashMap<String, (Span, Option<String>)> = HashMap::new();
|
||||
collect_objects(module, &mut by_name);
|
||||
// Deterministic order: source line, then name (stable gold diagnostics).
|
||||
let mut names: Vec<String> = by_name.keys().cloned().collect();
|
||||
names.sort_by(|a, b| {
|
||||
let (sa, _) = &by_name[a];
|
||||
let (sb, _) = &by_name[b];
|
||||
sa.line.cmp(&sb.line).then_with(|| a.cmp(b))
|
||||
});
|
||||
|
||||
for name in &names {
|
||||
let (span, base) = &by_name[name];
|
||||
let Some(base) = base else { continue };
|
||||
if !by_name.contains_key(base) {
|
||||
return Err(Diagnostic::new(
|
||||
None,
|
||||
*span,
|
||||
format!("unknown base type `{base}` for object `{name}`"),
|
||||
)
|
||||
.into());
|
||||
}
|
||||
}
|
||||
|
||||
for name in &names {
|
||||
let (span, base) = &by_name[name];
|
||||
if base.is_none() {
|
||||
continue;
|
||||
}
|
||||
let mut path = Vec::new();
|
||||
let mut cur = name.clone();
|
||||
loop {
|
||||
if path.iter().any(|p| p == &cur) {
|
||||
path.push(cur);
|
||||
return Err(Diagnostic::new(
|
||||
None,
|
||||
*span,
|
||||
format!(
|
||||
"cyclic inheritance involving `{name}` ({})",
|
||||
path.join(" → ")
|
||||
),
|
||||
)
|
||||
.into());
|
||||
}
|
||||
path.push(cur.clone());
|
||||
let Some((_, Some(next))) = by_name.get(&cur) else {
|
||||
break;
|
||||
};
|
||||
cur = next.clone();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn collect_objects(module: &Module, out: &mut HashMap<String, (Span, Option<String>)>) {
|
||||
for fun in &module.functions {
|
||||
if fun.is_object() {
|
||||
out.entry(fun.name.clone())
|
||||
.or_insert((fun.span, fun.base.clone()));
|
||||
}
|
||||
}
|
||||
for lib in module.import_modules.values() {
|
||||
collect_objects(lib, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// Walk the base chain starting at `type_name` (inclusive).
|
||||
pub fn inheritance_chain<'a>(module: &'a Module, type_name: &str) -> Vec<&'a Function> {
|
||||
let mut out = Vec::new();
|
||||
let mut cur = type_name.to_string();
|
||||
let mut seen = HashSet::new();
|
||||
while seen.insert(cur.clone()) {
|
||||
let Some(obj) = find_object(module, &cur) else {
|
||||
break;
|
||||
};
|
||||
out.push(obj);
|
||||
match &obj.base {
|
||||
Some(b) => cur = b.clone(),
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn find_object<'a>(module: &'a Module, name: &str) -> Option<&'a Function> {
|
||||
module
|
||||
.functions
|
||||
.iter()
|
||||
.find(|f| f.name == name && f.is_object())
|
||||
.or_else(|| {
|
||||
module.import_modules.values().find_map(|lib| {
|
||||
lib.functions
|
||||
.iter()
|
||||
.find(|f| f.name == name && f.is_object())
|
||||
})
|
||||
})
|
||||
}
|
||||
+35
-7
@@ -732,13 +732,20 @@ impl Interpreter {
|
||||
.cloned()
|
||||
.ok_or_else(|| self.err(format!("undefined variable `{recv_name}`")))?;
|
||||
let type_name = instance_type_name(&recv).map_err(|m| self.err(m))?;
|
||||
let (owner, obj) = find_object_type(module, &type_name)
|
||||
.ok_or_else(|| self.err(format!("unknown object type `{type_name}`")))?;
|
||||
let target = obj
|
||||
.children
|
||||
.iter()
|
||||
.find(|c| c.name == method)
|
||||
.ok_or_else(|| self.err(format!("unknown method `{type_name}.{method}`")))?;
|
||||
if find_object_type(module, &type_name).is_none() {
|
||||
return Err(self.err(format!("unknown object type `{type_name}`")));
|
||||
}
|
||||
let (owner, _obj, target) = find_method_along_bases(module, &type_name, method)
|
||||
.ok_or_else(|| {
|
||||
let chain = crate::inherit::inheritance_chain(module, &type_name)
|
||||
.into_iter()
|
||||
.map(|o| o.name.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join(" → ");
|
||||
self.err(format!(
|
||||
"unknown method `{type_name}.{method}` (searched {chain})"
|
||||
))
|
||||
})?;
|
||||
let bound = bind_function_args(self, module, fun, env, &target.params, ev_args, false)
|
||||
.map_err(|m| self.err(m))?;
|
||||
let mut call_env = Env::new();
|
||||
@@ -918,6 +925,27 @@ fn find_object_type<'a>(module: &'a Module, name: &str) -> Option<(&'a Module, &
|
||||
})
|
||||
}
|
||||
|
||||
/// Resolve `` `obj`.method `` along the inheritance chain (`_type` first, then bases).
|
||||
fn find_method_along_bases<'a>(
|
||||
module: &'a Module,
|
||||
type_name: &str,
|
||||
method: &str,
|
||||
) -> Option<(&'a Module, &'a Function, &'a Function)> {
|
||||
let mut cur = type_name.to_string();
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
while seen.insert(cur.clone()) {
|
||||
let (owner, obj) = find_object_type(module, &cur)?;
|
||||
if let Some(target) = obj.children.iter().find(|c| c.name == method) {
|
||||
return Some((owner, obj, target));
|
||||
}
|
||||
match &obj.base {
|
||||
Some(b) => cur = b.clone(),
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn find_function_anywhere<'a>(module: &'a Module, name: &str) -> Option<&'a Function> {
|
||||
for f in &module.functions {
|
||||
if f.name == name {
|
||||
|
||||
@@ -16,6 +16,7 @@ pub mod ext_cli;
|
||||
pub mod foreign;
|
||||
pub mod formula;
|
||||
pub mod host;
|
||||
pub mod inherit;
|
||||
pub mod input_feed;
|
||||
pub mod interp;
|
||||
pub mod lex;
|
||||
|
||||
@@ -46,6 +46,7 @@ fn load_module_inner(path: &Path, visited: &mut HashSet<PathBuf>) -> Result<Modu
|
||||
import_modules.insert(imp.bind, dep);
|
||||
}
|
||||
module.import_modules = import_modules;
|
||||
crate::inherit::validate_inheritance(&module).map_err(|e| attach_path(path, e))?;
|
||||
|
||||
Ok(module)
|
||||
})();
|
||||
|
||||
+78
-6
@@ -129,22 +129,25 @@ impl<'a> Cursor<'a> {
|
||||
|
||||
fn parse_function(&mut self, min_level: u8) -> Result<Function> {
|
||||
let line = self.bump().unwrap();
|
||||
let (level, name) = parse_heading(line.text.trim())
|
||||
let (level, raw_name) = parse_heading(line.text.trim())
|
||||
.ok_or_else(|| anyhow::anyhow!("{}:1: expected heading", line.line_no))?;
|
||||
if level < min_level {
|
||||
bail!("{}:1: heading level {level} < expected {min_level}", line.line_no);
|
||||
}
|
||||
let span = Span {
|
||||
line: line.line_no,
|
||||
col: 1,
|
||||
};
|
||||
let (name, base) = parse_object_decl(level, raw_name, span)?;
|
||||
|
||||
let mut fun = Function {
|
||||
name: name.to_string(),
|
||||
name,
|
||||
level,
|
||||
span: Span {
|
||||
line: line.line_no,
|
||||
col: 1,
|
||||
},
|
||||
span,
|
||||
params: Vec::new(),
|
||||
body: Vec::new(),
|
||||
children: Vec::new(),
|
||||
base,
|
||||
};
|
||||
|
||||
// Parameter zone: indented `- name` pure identifiers.
|
||||
@@ -766,6 +769,75 @@ fn parse_heading(trimmed: &str) -> Option<(u8, &str)> {
|
||||
Some((level, name))
|
||||
}
|
||||
|
||||
/// `# Child = > Parent` → `(Child, Some(Parent))`; plain `# Child` → `(Child, None)`.
|
||||
fn parse_object_decl(level: u8, raw: &str, span: Span) -> Result<(String, Option<String>)> {
|
||||
let raw = raw.trim();
|
||||
if let Some(eq) = raw.find('=') {
|
||||
if level != 1 {
|
||||
return Err(Diagnostic::new(
|
||||
None,
|
||||
span,
|
||||
"inheritance (`= > Base`) is only allowed on `#` object headings",
|
||||
)
|
||||
.into());
|
||||
}
|
||||
let name = raw[..eq].trim();
|
||||
let rhs = raw[eq + 1..].trim();
|
||||
if name.is_empty() {
|
||||
return Err(Diagnostic::new(None, span, "object name missing before `=`").into());
|
||||
}
|
||||
if !is_simple_type_name(name) {
|
||||
return Err(Diagnostic::new(
|
||||
None,
|
||||
span,
|
||||
format!("invalid object name `{name}`"),
|
||||
)
|
||||
.into());
|
||||
}
|
||||
let Some(after_gt) = rhs.strip_prefix('>') else {
|
||||
return Err(Diagnostic::new(
|
||||
None,
|
||||
span,
|
||||
"object inheritance requires `# Name = > Base` (base must follow `>`)",
|
||||
)
|
||||
.into());
|
||||
};
|
||||
let base = after_gt.trim();
|
||||
if base.is_empty() {
|
||||
return Err(Diagnostic::new(None, span, "missing base type after `>`").into());
|
||||
}
|
||||
if base.contains('.') {
|
||||
return Err(Diagnostic::new(
|
||||
None,
|
||||
span,
|
||||
format!("base type must be a simple name, not a path (`{base}`)"),
|
||||
)
|
||||
.into());
|
||||
}
|
||||
if !is_simple_type_name(base) {
|
||||
return Err(Diagnostic::new(
|
||||
None,
|
||||
span,
|
||||
format!("invalid base type name `{base}`"),
|
||||
)
|
||||
.into());
|
||||
}
|
||||
return Ok((name.to_string(), Some(base.to_string())));
|
||||
}
|
||||
Ok((raw.to_string(), None))
|
||||
}
|
||||
|
||||
fn is_simple_type_name(s: &str) -> bool {
|
||||
let mut chars = s.chars();
|
||||
let Some(first) = chars.next() else {
|
||||
return false;
|
||||
};
|
||||
if !(first.is_alphabetic() || first == '_' || !first.is_ascii()) {
|
||||
return false;
|
||||
}
|
||||
chars.all(|c| c.is_alphanumeric() || c == '_' || !c.is_ascii())
|
||||
}
|
||||
|
||||
/// Parse `lib/time.mq.md` / `lib/time.mq.md as time` / `lib/时间.mq.md 作为 时间`.
|
||||
pub fn parse_import_spec(rest: &str) -> Option<Import> {
|
||||
let rest = rest.trim();
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
---
|
||||
title: inheritance rhs must be > Base
|
||||
---
|
||||
|
||||
# Foo = 1
|
||||
|
||||
# main
|
||||
|
||||
> print text=nope
|
||||
@@ -0,0 +1,11 @@
|
||||
---
|
||||
title: cyclic inheritance
|
||||
---
|
||||
|
||||
# A = > B
|
||||
|
||||
# B = > A
|
||||
|
||||
# main
|
||||
|
||||
> print text=nope
|
||||
@@ -0,0 +1,9 @@
|
||||
---
|
||||
title: unknown base type
|
||||
---
|
||||
|
||||
# Child = > MissingParent
|
||||
|
||||
# main
|
||||
|
||||
> print text=nope
|
||||
@@ -67,6 +67,24 @@ fn structure_object_handle() {
|
||||
assert_out("tests/structure/object-handle.mq.md", "counter\n3\n4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structure_inherit_parent_method() {
|
||||
assert_out(
|
||||
"tests/structure/inherit-parent-method.mq.md",
|
||||
"Loud
|
||||
Hello, world!",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structure_inherit_override() {
|
||||
assert_out(
|
||||
"tests/structure/inherit-override.mq.md",
|
||||
"Hello, world!
|
||||
HELLO, world!",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structure_nested_call() {
|
||||
assert_out("tests/structure/nested-call.mq.md", "Hello World!");
|
||||
@@ -457,6 +475,33 @@ fn error_table_row_marker_only() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_inherit_cycle() {
|
||||
assert_err(
|
||||
"tests/errors/inherit-cycle.mq.md",
|
||||
"5:1",
|
||||
"cyclic inheritance",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_inherit_unknown_base() {
|
||||
assert_err(
|
||||
"tests/errors/inherit-unknown-base.mq.md",
|
||||
"5:1",
|
||||
"unknown base type",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_inherit_bad_rhs() {
|
||||
assert_err(
|
||||
"tests/errors/inherit-bad-rhs.mq.md",
|
||||
"5:1",
|
||||
"object inheritance requires",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_bad_int() {
|
||||
assert_err(
|
||||
@@ -554,6 +599,26 @@ fn bytecode_hello() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bytecode_inherit_parent_method() {
|
||||
assert_out_backend(
|
||||
"tests/structure/inherit-parent-method.mq.md",
|
||||
"bytecode",
|
||||
"Loud
|
||||
Hello, world!",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bytecode_inherit_override() {
|
||||
assert_out_backend(
|
||||
"tests/structure/inherit-override.mq.md",
|
||||
"bytecode",
|
||||
"Hello, world!
|
||||
HELLO, world!",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bytecode_branch() {
|
||||
assert_out_backend("tests/structure/branch.mq.md", "bytecode", "零");
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
---
|
||||
title: inherit method override
|
||||
---
|
||||
|
||||
# Greeter
|
||||
|
||||
## hello
|
||||
+ `who`
|
||||
|
||||
*`msg` = "Hello, `who`!" *
|
||||
**`msg`**
|
||||
|
||||
# Loud = > Greeter
|
||||
|
||||
## hello
|
||||
+ `who`
|
||||
|
||||
*`msg` = "HELLO, `who`!" *
|
||||
**`msg`**
|
||||
|
||||
# main
|
||||
|
||||
*`g` = > Greeter *
|
||||
*`m` = > `g`.hello who=world *
|
||||
> print text=`m`
|
||||
*`l` = > Loud *
|
||||
*`m2` = > `l`.hello who=world *
|
||||
> print text=`m2`
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
title: inherit parent method
|
||||
> lib/json.mq.md
|
||||
---
|
||||
|
||||
# Greeter
|
||||
|
||||
## hello
|
||||
+ `who`
|
||||
|
||||
*`msg` = "Hello, `who`!" *
|
||||
**`msg`**
|
||||
|
||||
# Loud = > Greeter
|
||||
|
||||
# main
|
||||
|
||||
*`l` = > Loud *
|
||||
*`ty` = > json.get value=`l` key=_type *
|
||||
> print text=`ty`
|
||||
*`m` = > `l`.hello who=world *
|
||||
> print text=`m`
|
||||
Reference in new issue
Block a user