feat(frontend): heading scopes, semantic mapping, inference and call validation

Implement the P0/P1 frontend from spec/mapping.md, spec/evaluation.md:

- units: heading scope index (level-1 namespace, level-2 function, level>=3
  section), range computation, duplicate/empty-name diagnostics, GitHub anchor
  table kept separate from canonical ids, and warnings for would-be execution
  nodes outside function bodies.
- map: AST-to-IR mapping where role comes from node kind + position. Strong is
  an execution statement, Emph a return, ordered list a branch, bullet list a
  loop sequence, block quote a call; invalid shapes are hard
  markdown.invalid_construct errors, never prose fallback. Payload parsing
  errors are mapped from payload-relative to file-relative spans.
- payload: strict text/code payload concatenation with exact span mapping
  (including code-span delimiter handling) used to rewrite expression spans
  onto the source file.
- signature: optional `(name: Type = const)` paragraph declaration; defaults
  must be compile-time constants; duplicates and malformed declarations are
  errors.
- infer: definite-assignment data-flow parameter inference (must/may/ambiguous
  states, loop first-iteration handling, branch joins) per blueprint S-04.
- calls: static call validation of arity/named arguments/builtin signatures
  after all signatures are known; inferred signatures accept named args only.
- resources: inert Formula/Code resources with owning units and SHA-256
  content hashes.
- analyze: pipeline (parse -> units -> frontmatter imports -> map -> signature/
  inference -> module -> call checks) that never executes anything.

Tests include factorial recursion, loop counter, prose-invariance (IR equal
modulo spans), and hard-error cases.
This commit is contained in:
cflmy committed 2026-11-20 10:36:12 +08:00
1 parent 62a9af05fd
commit 8003907f4e
10 files changed
+2763 -3

No files matched your search

+404
View File
@@ -0,0 +1,404 @@
//! Static call validation.
//!
//! Calls are resolved after all functions have signatures (including inferred
//! ones), so arity/name mistakes are compile errors with source spans instead
//! of surprises at runtime. Type errors stay runtime concerns: v1 has no static
//! type inference beyond literal checks.
use std::collections::{BTreeMap, BTreeSet};
use marqdo_expression::{Arg, Expr, Ident};
use marqdo_ir::{builtins, Module, Param, SignatureKind, Stmt};
use marqdo_span::Span;
use marqdo_value::{codes, Diagnostic};
/// Signature information needed to validate a call.
#[derive(Debug, Clone)]
pub struct CallableSignature {
/// Parameter list.
pub params: Vec<Param>,
/// Explicit signatures allow positional arguments; inferred do not.
pub kind: SignatureKind,
}
/// Build the callable signature table for a module.
pub fn signature_table(module: &Module) -> BTreeMap<String, CallableSignature> {
let mut table = BTreeMap::new();
for function in &module.functions {
table.insert(
function.id.name.clone(),
CallableSignature {
params: function.params.clone(),
kind: function.signature,
},
);
}
table
}
/// Validate every call in every function body of the module.
pub fn validate_module(module: &Module) -> Vec<Diagnostic> {
let table = signature_table(module);
let mut diagnostics = Vec::new();
for function in &module.functions {
let mut locals: BTreeSet<String> = function
.params
.iter()
.map(|param| param.name.clone())
.collect();
collect_assigned(&function.body, &mut locals);
let mut check = CallChecker {
current_namespace: function.namespace.clone(),
locals: &locals,
table: &table,
imports: module
.imports
.iter()
.map(|import| import.alias.clone())
.collect(),
diagnostics: Vec::new(),
};
check.stmts(&function.body);
diagnostics.extend(check.diagnostics);
}
diagnostics
}
fn collect_assigned(stmts: &[Stmt], out: &mut BTreeSet<String>) {
for stmt in stmts {
match stmt {
Stmt::Assign { name, .. } => {
out.insert(name.clone());
}
Stmt::Branch { arms, .. } => {
for arm in arms {
collect_assigned(&arm.body, out);
}
}
Stmt::Loop { body, .. } => collect_assigned(body, out),
_ => {}
}
}
}
struct CallChecker<'a> {
current_namespace: Option<String>,
locals: &'a BTreeSet<String>,
table: &'a BTreeMap<String, CallableSignature>,
imports: BTreeSet<String>,
diagnostics: Vec<Diagnostic>,
}
impl<'a> CallChecker<'a> {
fn stmts(&mut self, stmts: &[Stmt]) {
for stmt in stmts {
match stmt {
Stmt::Assign { value, .. }
| Stmt::Eval { expr: value, .. }
| Stmt::Return { value, .. } => {
self.expr(value);
}
Stmt::Call { call, .. } => {
for Arg { value, .. } in &call.args {
self.expr(value);
}
}
Stmt::Branch { arms, .. } => {
for arm in arms {
self.expr(&arm.condition);
self.stmts(&arm.body);
}
}
Stmt::Loop {
condition, body, ..
} => {
self.expr(condition);
self.stmts(body);
}
}
}
}
fn expr(&mut self, expr: &Expr) {
match expr {
Expr::Int(_) | Expr::Float(_) | Expr::Text(_) | Expr::Bool(_) | Expr::None => {}
Expr::Ident(_) => {}
Expr::List(items) => items.iter().for_each(|item| self.expr(item)),
Expr::Record(entries) => entries.iter().for_each(|entry| self.expr(&entry.value)),
Expr::Unary { operand, .. } => self.expr(operand),
Expr::Binary { left, right, .. } => {
self.expr(left);
self.expr(right);
}
Expr::Member { base, .. } => self.expr(base),
Expr::Index { base, index, .. } => {
self.expr(base);
self.expr(index);
}
Expr::Call { callee, args, span } => {
self.call(callee, args, *span);
for arg in args {
self.expr(&arg.value);
}
}
}
}
fn call(&mut self, callee: &Expr, args: &[Arg], span: Span) {
match callee {
Expr::Ident(Ident { name, .. }) => {
if let Some(builtin) = builtins::find(name) {
if let Err(message) = builtins::validate_args(builtin, args) {
self.diagnostics.push(
Diagnostic::error(codes::CALL_ARITY, Some(span), message)
.with_hint("check the builtin parameter list"),
);
}
return;
}
let name_span = match callee {
Expr::Ident(Ident { span, .. }) => *span,
_ => span,
};
if let Some(signature) = self.resolve(name) {
self.validate_against(name, signature, args, span, name_span);
return;
}
if self.locals.contains(name) || self.imports.contains(name) {
// A local may hold a FunctionRef value; resolved at runtime.
return;
}
self.diagnostics.push(
Diagnostic::error(
codes::SYMBOL_UNKNOWN,
Some(name_span),
format!("unknown function `{name}`"),
)
.with_hint("define it as a level-2 heading or call a builtin"),
);
}
// Qualified calls are validated once the imported module has been
// analysed by the loader; argument expressions are still checked.
Expr::Member { base, .. } => self.expr(base),
other => self.expr(other),
}
}
fn resolve(&self, name: &str) -> Option<&'a CallableSignature> {
if let Some(namespace) = &self.current_namespace {
if let Some(found) = self.table.get(&format!("{namespace}.{name}")) {
return Some(found);
}
}
if let Some(found) = self.table.get(name) {
return Some(found);
}
// Unique local name across namespaces.
let mut matches = self
.table
.iter()
.filter(|(key, _)| key.ends_with(&format!(".{name}")))
.map(|(_, signature)| signature);
let first = matches.next()?;
if matches.next().is_some() {
None
} else {
Some(first)
}
}
fn validate_against(
&mut self,
name: &str,
signature: &CallableSignature,
args: &[Arg],
call_span: Span,
name_span: Span,
) {
if signature.kind == SignatureKind::Inferred {
if let Some(positional) = args.iter().find(|arg| arg.name.is_none()) {
self.diagnostics.push(
Diagnostic::error(
codes::CALL_ARITY,
Some(positional.span),
format!(
"`{name}` has an inferred signature and only accepts named arguments"
),
)
.with_hint("pass arguments as `name = value`"),
);
}
}
let mut supplied: BTreeSet<&str> = BTreeSet::new();
let mut positional = 0usize;
for arg in args {
match &arg.name {
Some(argument_name) => {
if !signature
.params
.iter()
.any(|param| param.name == *argument_name)
{
self.diagnostics.push(
Diagnostic::error(
codes::CALL_ARITY,
Some(arg.span),
format!("`{name}` has no parameter named `{argument_name}`"),
)
.with_hint("check `inspect --signature`"),
);
}
supplied.insert(argument_name.as_str());
}
None => {
if let Some(param) = signature.params.get(positional) {
supplied.insert(param.name.as_str());
positional += 1;
} else {
self.diagnostics.push(Diagnostic::error(
codes::CALL_ARITY,
Some(call_span),
format!(
"`{name}` accepts at most {} positional argument(s)",
signature.params.len()
),
));
}
}
}
}
for param in &signature.params {
if param.default.is_none() && !supplied.contains(param.name.as_str()) {
self.diagnostics.push(
Diagnostic::error(
codes::CALL_ARITY,
Some(name_span),
format!("`{name}` is missing required argument `{}`", param.name),
)
.with_hint("pass it by name, e.g. `x = value`"),
);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use marqdo_expression::parse_expression;
use marqdo_ir::{Function, FunctionId, ModuleId, Param, UnitId};
fn function(name: &str, params: &[&str], kind: SignatureKind, body: Vec<Stmt>) -> Function {
Function {
id: FunctionId {
module: ModuleId::from("index.mq.md"),
name: name.to_string(),
},
local_name: name.to_string(),
namespace: None,
unit: UnitId {
module: ModuleId::from("index.mq.md"),
path: vec![name.to_string()],
},
heading_span: Span::new(0, 0),
span: Span::new(0, 0),
params: params
.iter()
.map(|name| Param {
name: name.to_string(),
span: Span::new(0, 0),
type_annotation: None,
default: None,
})
.collect(),
signature: kind,
body,
}
}
fn make_module(functions: Vec<Function>) -> Module {
Module {
id: ModuleId::from("index.mq.md"),
units: vec![],
functions,
imports: vec![],
resources: vec![],
anchors: std::collections::BTreeMap::new(),
}
}
fn return_call(code: &str) -> Stmt {
Stmt::Return {
value: parse_expression(code).unwrap(),
span: Span::new(0, 0),
}
}
#[test]
fn unknown_function_is_an_error() {
let module = make_module(vec![function(
"main",
&[],
SignatureKind::Explicit,
vec![return_call("nope(1)")],
)]);
let diagnostics = validate_module(&module);
assert!(diagnostics.iter().any(|d| d.code == codes::SYMBOL_UNKNOWN));
}
#[test]
fn inferred_signature_requires_named_arguments() {
let callee = function("f", &["n"], SignatureKind::Inferred, vec![]);
let module = make_module(vec![
function(
"main",
&[],
SignatureKind::Explicit,
vec![return_call("f(1)")],
),
callee,
]);
let diagnostics = validate_module(&module);
assert!(diagnostics.iter().any(|d| d.code == codes::CALL_ARITY));
}
#[test]
fn explicit_signature_allows_positional_and_checks_arity() {
let callee = function("f", &["a", "b"], SignatureKind::Explicit, vec![]);
let module = make_module(vec![
function(
"main",
&[],
SignatureKind::Explicit,
vec![return_call("f(1, 2)")],
),
callee,
]);
assert!(validate_module(&module).is_empty());
let module = make_module(vec![
function(
"main",
&[],
SignatureKind::Explicit,
vec![return_call("f(1)")],
),
function("f", &["a", "b"], SignatureKind::Explicit, vec![]),
]);
assert!(validate_module(&module)
.iter()
.any(|d| d.code == codes::CALL_ARITY));
}
#[test]
fn builtin_arity_is_checked() {
let module = make_module(vec![function(
"main",
&[],
SignatureKind::Explicit,
vec![return_call("打印()")],
)]);
assert!(validate_module(&module)
.iter()
.any(|d| d.code == codes::CALL_ARITY));
}
}