fix(frontend): recognize signatures only from Exec payloads
signature::detect() scanned the function body independently of heading
modes, skipping only level>=3 headings. A 'params(...)' code span in an
### @knowledge section was therefore taken as the function signature
('inspect --signature' reported it as explicit), even though that span is
inert documentation and is never executed.
Unify recognition with the executable traversal:
- MappedBody now reports the params(...) payload the mapper accepted; the
mapper already enforces Exec mode, directness, first-function-wide
position and single declaration
- signature::from_payload validates that text and rewrites default-value
spans; signature::detect is removed along with its mode-blind heuristic
- analyze uses the mapper result, so Knowledge sections cannot declare a
signature and prose/Knowledge subsections may still precede the first
Exec declaration
- tests: Knowledge params ignored; Exec params after prose/Knowledge is the
signature; spec/mapping.md states the recognition rule
Verified: clippy -D warnings clean; cargo test --workspace --locked green
(62 targets).
This commit is contained in:
1 parent
d5002ac826
commit
9fb97bc2df
4 files changed
+83
-57
No files matched your search
@@ -105,15 +105,14 @@ pub fn analyze_source(module_id: &str, source: &str) -> AnalysisResult {
|
||||
|
||||
let mut functions: Vec<Function> = Vec::new();
|
||||
for scope in &units.functions {
|
||||
let blocks: Vec<&marqdo_markdown::MdNode> = document.root.children
|
||||
[scope.body_start..scope.body_end]
|
||||
.iter()
|
||||
.collect();
|
||||
let signature = signature::detect(&document, &blocks);
|
||||
let explicit = signature.as_ref().map(|(_, sig)| sig);
|
||||
|
||||
let mut mapped = map::map_function(&document, &units, scope);
|
||||
diagnostics.append(&mut mapped.diagnostics);
|
||||
// The mapper already proved that this payload is the function's first
|
||||
// direct executable payload; a Knowledge section can never supply one.
|
||||
let signature = mapped.params.as_ref().map(|declaration| {
|
||||
signature::from_payload(&declaration.text, declaration.span, &declaration.segments)
|
||||
});
|
||||
let explicit = signature.as_ref();
|
||||
|
||||
let mut params: Vec<Param> = Vec::new();
|
||||
let mut kind = SignatureKind::Inferred;
|
||||
@@ -238,6 +237,39 @@ mod tests {
|
||||
assert!(matches!(function.body[1], marqdo_ir::Stmt::Loop { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn knowledge_section_cannot_declare_a_signature() {
|
||||
// The `params(...)` payload sits in a Knowledge section, so it is inert
|
||||
// documentation and must not become the function's signature.
|
||||
let source = "## @exec f\n\n### @knowledge 说明\n\n`params(x: Int)`\n\n### @exec 计算\n\n`return 1`\n";
|
||||
let result = analyze(source);
|
||||
assert!(
|
||||
!result.has_errors(),
|
||||
"unexpected diagnostics: {:#?}",
|
||||
result.diagnostics
|
||||
);
|
||||
let function = result.module.function("f").expect("f");
|
||||
assert_eq!(function.signature, SignatureKind::Inferred);
|
||||
assert!(function.params.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_section_params_after_prose_is_the_signature() {
|
||||
// Prose and a Knowledge subsection may precede the declaration, so a
|
||||
// later Exec section can still declare the first executable payload.
|
||||
let source = "## @exec f\n\n说明文字。\n\n### @knowledge 原理\n\n`params(ignored: Int)`\n\n### @exec 计算\n\n`params(x: Int)`\n\n`return x`\n";
|
||||
let result = analyze(source);
|
||||
assert!(
|
||||
!result.has_errors(),
|
||||
"unexpected diagnostics: {:#?}",
|
||||
result.diagnostics
|
||||
);
|
||||
let function = result.module.function("f").expect("f");
|
||||
assert_eq!(function.signature, SignatureKind::Explicit);
|
||||
assert_eq!(function.params.len(), 1);
|
||||
assert_eq!(function.params[0].name, "x");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_strong_payload_is_a_hard_error() {
|
||||
let result = analyze("## @exec f\n\n**a *b* c**\n");
|
||||
|
||||
@@ -16,6 +16,22 @@ use marqdo_value::{codes, Diagnostic};
|
||||
use crate::payload::PayloadSegments;
|
||||
use crate::units::{FunctionScope, UnitIndex};
|
||||
|
||||
/// The `params(...)` payload accepted for one function.
|
||||
///
|
||||
/// Only the first function-wide direct payload qualifies; the signature parser
|
||||
/// validates the interior. Keeping the carrier text and span map here means the
|
||||
/// declaration is recognized by the same traversal and mode rules that decide
|
||||
/// what executes, so a Knowledge section can never declare a signature.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ParamsDeclaration {
|
||||
/// Payload text, e.g. `params(n: Int)`.
|
||||
pub text: String,
|
||||
/// Span of the carrier node.
|
||||
pub span: Span,
|
||||
/// Payload-offset → file-span map for default expressions.
|
||||
pub segments: PayloadSegments,
|
||||
}
|
||||
|
||||
/// A mapped function body plus diagnostics.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct MappedBody {
|
||||
@@ -23,6 +39,8 @@ pub struct MappedBody {
|
||||
pub stmts: Vec<Stmt>,
|
||||
/// Diagnostics produced while mapping.
|
||||
pub diagnostics: Vec<Diagnostic>,
|
||||
/// The accepted `params(...)` declaration, if the function has one.
|
||||
pub params: Option<ParamsDeclaration>,
|
||||
}
|
||||
|
||||
/// Map one function scope to executable statements.
|
||||
@@ -33,6 +51,7 @@ pub fn map_function(
|
||||
) -> MappedBody {
|
||||
let mut mapper = Mapper {
|
||||
diagnostics: Vec::new(),
|
||||
params: None,
|
||||
saw_params: None,
|
||||
executed: false,
|
||||
};
|
||||
@@ -63,11 +82,14 @@ pub fn map_function(
|
||||
MappedBody {
|
||||
stmts,
|
||||
diagnostics: mapper.diagnostics,
|
||||
params: mapper.params,
|
||||
}
|
||||
}
|
||||
|
||||
struct Mapper {
|
||||
diagnostics: Vec<Diagnostic>,
|
||||
/// Accepted `params(...)` payload for the function being mapped.
|
||||
params: Option<ParamsDeclaration>,
|
||||
/// First direct `params(...)` payload of the **function** (not just the
|
||||
/// current heading segment), used to reject duplicate declarations.
|
||||
saw_params: Option<Span>,
|
||||
@@ -86,6 +108,7 @@ enum Stop {
|
||||
|
||||
struct RawPayload {
|
||||
payload: Payload,
|
||||
text: String,
|
||||
span: Span,
|
||||
segments: PayloadSegments,
|
||||
/// True only for a carrier in the heading's direct body, not inside a
|
||||
@@ -194,6 +217,7 @@ impl Mapper {
|
||||
}
|
||||
out.push(RawPayload {
|
||||
payload,
|
||||
text,
|
||||
span,
|
||||
segments,
|
||||
direct,
|
||||
@@ -341,6 +365,11 @@ impl Mapper {
|
||||
);
|
||||
} else {
|
||||
self.saw_params = Some(raw.span);
|
||||
self.params = Some(ParamsDeclaration {
|
||||
text: raw.text.clone(),
|
||||
span: raw.span,
|
||||
segments: raw.segments.clone(),
|
||||
});
|
||||
}
|
||||
*position += 1;
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
|
||||
use marqdo_expression::{parse_expression, Expr, Statement, StatementKind};
|
||||
use marqdo_ir::{Param, SignatureKind};
|
||||
use marqdo_markdown::{MarkdownDocument, MdKind, MdNode};
|
||||
use marqdo_span::Span;
|
||||
use marqdo_value::{codes, Diagnostic};
|
||||
use unicode_ident::{is_xid_continue, is_xid_start};
|
||||
@@ -20,7 +19,7 @@ use crate::payload::PayloadSegments;
|
||||
pub struct Signature {
|
||||
/// Parameters in declaration order.
|
||||
pub params: Vec<Param>,
|
||||
/// Span of the declaration code span.
|
||||
/// Span of the declaration payload carrier.
|
||||
pub span: Span,
|
||||
/// Diagnostics raised while parsing the declaration.
|
||||
pub diagnostics: Vec<Diagnostic>,
|
||||
@@ -33,56 +32,20 @@ impl Signature {
|
||||
}
|
||||
}
|
||||
|
||||
/// Detect and parse a signature paragraph.
|
||||
/// Parse the `params(...)` payload the mapper accepted for a function.
|
||||
///
|
||||
/// A paragraph qualifies only when it is the first block in the function body
|
||||
/// (ignoring inert level>=3 section headings) and consists of exactly one
|
||||
/// inline code span whose payload starts with `(`. Any other first paragraph is
|
||||
/// prose and inference is used instead.
|
||||
pub fn detect(_doc: &MarkdownDocument, blocks: &[&MdNode]) -> Option<(usize, Signature)> {
|
||||
for (index, block) in blocks.iter().enumerate() {
|
||||
match &block.kind {
|
||||
MdKind::Heading { level, .. } if *level >= 3 => continue,
|
||||
MdKind::Paragraph => {
|
||||
if block.children.len() != 1 {
|
||||
continue;
|
||||
}
|
||||
let carrier = &block.children[0];
|
||||
let (source, span, segments) = match &carrier.kind {
|
||||
MdKind::Code { ticks } => {
|
||||
let literal = carrier.literal.clone().unwrap_or_default();
|
||||
let inner = Span::new(
|
||||
carrier.span.start.saturating_add(*ticks),
|
||||
carrier.span.end.saturating_sub(*ticks),
|
||||
);
|
||||
(
|
||||
literal.clone(),
|
||||
carrier.span,
|
||||
PayloadSegments::single(&literal, inner),
|
||||
)
|
||||
}
|
||||
MdKind::Strong | MdKind::Emph => match PayloadSegments::of(carrier) {
|
||||
Ok((source, segments)) => (source, carrier.span, segments),
|
||||
Err(_) => continue,
|
||||
},
|
||||
_ => continue,
|
||||
};
|
||||
if !source.trim_start().starts_with("params(") {
|
||||
return None;
|
||||
}
|
||||
let mut signature = parse(&source, span);
|
||||
for param in &mut signature.params {
|
||||
if let Some(default) = &mut param.default {
|
||||
segments.rewrite_expr(default);
|
||||
}
|
||||
}
|
||||
return Some((index, signature));
|
||||
}
|
||||
MdKind::List { .. } | MdKind::BlockQuote | MdKind::Item { .. } => continue,
|
||||
_ => return None,
|
||||
/// The mapper owns recognition: only the first function-wide direct payload of
|
||||
/// an Exec H2 can be a declaration, and Knowledge sections never produce
|
||||
/// payloads. This function only validates the declaration text and rewrites
|
||||
/// default-value spans onto the file.
|
||||
pub fn from_payload(text: &str, span: Span, segments: &PayloadSegments) -> Signature {
|
||||
let mut signature = parse(text, span);
|
||||
for param in &mut signature.params {
|
||||
if let Some(default) = &mut param.default {
|
||||
segments.rewrite_expr(default);
|
||||
}
|
||||
}
|
||||
None
|
||||
signature
|
||||
}
|
||||
|
||||
/// Parse signature payload text (without the code span delimiters).
|
||||
|
||||
+3
-1
@@ -277,7 +277,9 @@ Rules:
|
||||
segment are visible in later segments. They do not create new functions.
|
||||
* `params(name: Type, ...)` is legal only as the **first direct execution
|
||||
payload of an Exec H2 function**, at most once, and not inside a list or
|
||||
block quote. The position is function-wide: it may be preceded by prose or a
|
||||
block quote. Recognition happens in the same Exec-mode traversal that finds
|
||||
statements, so a `params(...)` code span in a Knowledge section is inert
|
||||
documentation and is never a signature. The position is function-wide: it may be preceded by prose or a
|
||||
Knowledge subsection, but not by an executing statement in **any** heading
|
||||
segment of that function (a later `### @exec` section may not add a
|
||||
signature after earlier code ran). Violations are `sem.signature_position`;
|
||||
|
||||
Reference in new issue
Block a user