Refactor executable library handbooks and improve document reading
This commit is contained in:
1 parent
16c44588d5
commit
c50c515c4a
191 files changed
+29572
-7816
No files matched your search
@@ -0,0 +1,803 @@
|
||||
//! Audit library source with the real parser, and compare executable ASTs across prose refactors.
|
||||
use anyhow::{Context, Result};
|
||||
use marqdo::{ast::*, diagnostics::Span};
|
||||
use serde_json::{json, Value};
|
||||
use std::{
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
fn files(dir: &Path, out: &mut Vec<PathBuf>) -> Result<()> {
|
||||
for entry in fs::read_dir(dir)? {
|
||||
let p = entry?.path();
|
||||
if p.is_dir() {
|
||||
files(&p, out)?
|
||||
} else if p.to_string_lossy().ends_with(".mq.md") {
|
||||
out.push(p)
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn expr(e: Expr) -> Expr {
|
||||
match e {
|
||||
Expr::Occluded { payload, .. } => payload
|
||||
.map(|p| expr(*p))
|
||||
.unwrap_or(Expr::Literal(Literal::None)),
|
||||
Expr::Unary { op, expr: e } => Expr::Unary {
|
||||
op,
|
||||
expr: Box::new(expr(*e)),
|
||||
},
|
||||
Expr::Binary { op, left, right } => Expr::Binary {
|
||||
op,
|
||||
left: Box::new(expr(*left)),
|
||||
right: Box::new(expr(*right)),
|
||||
},
|
||||
Expr::Call(c) => {
|
||||
let c = call(c);
|
||||
pure_literal_call(&c).unwrap_or(Expr::Call(c))
|
||||
}
|
||||
Expr::List(xs) => Expr::List(xs.into_iter().map(expr).collect()),
|
||||
Expr::Map(xs) => Expr::Map(xs.into_iter().map(|(k, v)| (k, expr(v))).collect()),
|
||||
Expr::Index { base, label } => Expr::Index {
|
||||
base: Box::new(expr(*base)),
|
||||
label,
|
||||
},
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
fn call(mut c: CallExpr) -> CallExpr {
|
||||
for a in &mut c.args {
|
||||
match a {
|
||||
Arg::Positional(e) | Arg::Named { value: e, .. } => *e = expr(e.clone()),
|
||||
}
|
||||
}
|
||||
c
|
||||
}
|
||||
// Only the explicitly supported pure literal-building cases are folded. This is
|
||||
// a refactor audit, not an evaluator: unknown calls and nonconstant data remain.
|
||||
fn literal_json_value(v: serde_json::Value) -> Option<Expr> {
|
||||
use serde_json::Value as J;
|
||||
Some(Expr::Literal(match v {
|
||||
J::Null => Literal::None,
|
||||
J::Bool(b) => Literal::Bool(b),
|
||||
J::String(s) => Literal::Text(s),
|
||||
J::Number(n) => {
|
||||
if let Some(i) = n.as_i64() {
|
||||
if i.unsigned_abs() > 9_007_199_254_740_991 {
|
||||
return None;
|
||||
}
|
||||
Literal::Int(i)
|
||||
} else {
|
||||
let n = n.as_f64()?;
|
||||
if !n.is_finite() || (n.fract() == 0.0 && n.abs() > 9_007_199_254_740_991.0) {
|
||||
return None;
|
||||
}
|
||||
Literal::Num(n)
|
||||
}
|
||||
}
|
||||
_ => return None,
|
||||
}))
|
||||
}
|
||||
// Read JSON literals without accepting duplicate keys or unsafe numeric coercions.
|
||||
fn flat_json_record(text: &str) -> Option<Expr> {
|
||||
struct Constant;
|
||||
impl<'de> serde::Deserialize<'de> for ConstantExpr {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
|
||||
de.deserialize_any(Constant).map(ConstantExpr)
|
||||
}
|
||||
}
|
||||
struct ConstantExpr(Expr);
|
||||
impl<'de> serde::de::Visitor<'de> for Constant {
|
||||
type Value = Expr;
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
f.write_str("constant JSON in the exact audit numeric domain")
|
||||
}
|
||||
fn visit_unit<E: serde::de::Error>(self) -> Result<Expr, E> {
|
||||
Ok(Expr::Literal(Literal::None))
|
||||
}
|
||||
fn visit_bool<E: serde::de::Error>(self, b: bool) -> Result<Expr, E> {
|
||||
Ok(Expr::Literal(Literal::Bool(b)))
|
||||
}
|
||||
fn visit_str<E: serde::de::Error>(self, s: &str) -> Result<Expr, E> {
|
||||
Ok(Expr::Literal(Literal::Text(s.into())))
|
||||
}
|
||||
fn visit_i64<E: serde::de::Error>(self, n: i64) -> Result<Expr, E> {
|
||||
literal_json_value(n.into()).ok_or_else(|| E::custom("unsafe integer"))
|
||||
}
|
||||
fn visit_u64<E: serde::de::Error>(self, n: u64) -> Result<Expr, E> {
|
||||
literal_json_value(n.into()).ok_or_else(|| E::custom("unsafe integer"))
|
||||
}
|
||||
fn visit_f64<E: serde::de::Error>(self, n: f64) -> Result<Expr, E> {
|
||||
let n = serde_json::Number::from_f64(n).ok_or_else(|| E::custom("nonfinite number"))?;
|
||||
literal_json_value(n.into()).ok_or_else(|| E::custom("unsafe number"))
|
||||
}
|
||||
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Expr, A::Error> {
|
||||
let mut values = Vec::new();
|
||||
while let Some(ConstantExpr(v)) = seq.next_element()? {
|
||||
values.push(v);
|
||||
}
|
||||
Ok(Expr::List(values))
|
||||
}
|
||||
fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Expr, A::Error> {
|
||||
use serde::de::Error;
|
||||
let mut fields = std::collections::BTreeMap::new();
|
||||
while let Some((key, ConstantExpr(value))) = map.next_entry::<String, ConstantExpr>()? {
|
||||
if fields.insert(key, value).is_some() {
|
||||
return Err(A::Error::custom("duplicate key"));
|
||||
}
|
||||
}
|
||||
Ok(Expr::Map(fields.into_iter().collect()))
|
||||
}
|
||||
}
|
||||
let ConstantExpr(value) = serde_json::from_str::<ConstantExpr>(text).ok()?;
|
||||
Some(value)
|
||||
}
|
||||
fn pure_literal_call(c: &CallExpr) -> Option<Expr> {
|
||||
let name = c
|
||||
.path
|
||||
.as_ref()
|
||||
.map(|p| p.join("."))
|
||||
.unwrap_or_else(|| c.callee.clone());
|
||||
let get = |key: &str| {
|
||||
c.args.iter().find_map(|a| match a {
|
||||
Arg::Named { name, value } if name == key => Some(value),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
match name.as_str() {
|
||||
"json.parse" => {
|
||||
if let Expr::Literal(Literal::Text(text)) = get("text")? {
|
||||
flat_json_record(text)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
"table.put" if matches!(get("in")?, Expr::Literal(Literal::None)) => {
|
||||
if let Expr::Literal(Literal::Text(key)) = get("at")? {
|
||||
let value = get("value")?;
|
||||
if matches!(value, Expr::Literal(_)) {
|
||||
Some(Expr::Map(vec![(key.clone(), value.clone())]))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
"table.empty_list" => Some(Expr::List(Vec::new())),
|
||||
"table.from_pairs" => {
|
||||
let Expr::List(rows) = get("pairs")? else {
|
||||
return None;
|
||||
};
|
||||
let mut fields = Vec::new();
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
for row in rows {
|
||||
let Expr::Map(pairs) = row else {
|
||||
return None;
|
||||
};
|
||||
let Some((_, Expr::Literal(Literal::Text(key)))) =
|
||||
pairs.iter().find(|(k, _)| k == "key")
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let Some((_, value)) = pairs.iter().find(|(k, _)| k == "value") else {
|
||||
return None;
|
||||
};
|
||||
if !constant(value) || !seen.insert(key.clone()) {
|
||||
return None;
|
||||
}
|
||||
fields.push((key.clone(), value.clone()));
|
||||
}
|
||||
Some(Expr::Map(fields))
|
||||
}
|
||||
"text.str_join" => {
|
||||
let Expr::List(rows) = get("xs")? else {
|
||||
return None;
|
||||
};
|
||||
let Expr::Literal(Literal::Text(separator)) = get("sep")? else {
|
||||
return None;
|
||||
};
|
||||
let rows = rows
|
||||
.iter()
|
||||
.map(|e| {
|
||||
if let Expr::Literal(Literal::Text(s)) = e {
|
||||
Some(s.as_str())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect::<Option<Vec<_>>>()?;
|
||||
Some(Expr::Literal(Literal::Text(rows.join(separator))))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn constant(e: &Expr) -> bool {
|
||||
match e {
|
||||
Expr::Literal(_) => true,
|
||||
Expr::List(xs) => xs.iter().all(constant),
|
||||
Expr::Map(xs) => xs.iter().all(|(_, v)| constant(v)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
fn substitute(e: Expr, temps: &std::collections::BTreeMap<String, Expr>) -> Expr {
|
||||
let e = match e {
|
||||
Expr::Var(name) if temps.contains_key(&name) => temps[&name].clone(),
|
||||
Expr::Call(mut c) => {
|
||||
for a in &mut c.args {
|
||||
match a {
|
||||
Arg::Named { value, .. } | Arg::Positional(value) => {
|
||||
*value = substitute(value.clone(), temps)
|
||||
}
|
||||
}
|
||||
}
|
||||
Expr::Call(c)
|
||||
}
|
||||
Expr::Map(xs) => Expr::Map(
|
||||
xs.into_iter()
|
||||
.map(|(k, v)| (k, substitute(v, temps)))
|
||||
.collect(),
|
||||
),
|
||||
Expr::List(xs) => Expr::List(xs.into_iter().map(|v| substitute(v, temps)).collect()),
|
||||
Expr::Occluded {
|
||||
payload: Some(v), ..
|
||||
} => substitute(*v, temps),
|
||||
Expr::Unary { op, expr: v } => Expr::Unary {
|
||||
op,
|
||||
expr: Box::new(substitute(*v, temps)),
|
||||
},
|
||||
Expr::Binary { op, left, right } => Expr::Binary {
|
||||
op,
|
||||
left: Box::new(substitute(*left, temps)),
|
||||
right: Box::new(substitute(*right, temps)),
|
||||
},
|
||||
other => other,
|
||||
};
|
||||
expr(e)
|
||||
}
|
||||
fn canonical_statements(statements: Vec<Stmt>) -> Vec<Stmt> {
|
||||
fn block(
|
||||
statements: Vec<Stmt>,
|
||||
mut temps: std::collections::BTreeMap<String, Expr>,
|
||||
) -> Vec<Stmt> {
|
||||
let mut out = Vec::new();
|
||||
for s in statements {
|
||||
let s = statement(s);
|
||||
let s = match s {
|
||||
Stmt::Assign {
|
||||
name,
|
||||
value,
|
||||
span,
|
||||
end_line,
|
||||
} => {
|
||||
let value = substitute(value, &temps);
|
||||
if name.starts_with("_literal_") && constant(&value) {
|
||||
temps.insert(name, value);
|
||||
continue;
|
||||
}
|
||||
Stmt::Assign {
|
||||
name,
|
||||
value,
|
||||
span,
|
||||
end_line,
|
||||
}
|
||||
}
|
||||
Stmt::Return { value, span } => Stmt::Return {
|
||||
value: substitute(value, &temps),
|
||||
span,
|
||||
},
|
||||
Stmt::Expr { value, span } => Stmt::Expr {
|
||||
value: substitute(value, &temps),
|
||||
span,
|
||||
},
|
||||
Stmt::Branch { arms, span } => Stmt::Branch {
|
||||
arms: arms
|
||||
.into_iter()
|
||||
.map(|a| BranchArm {
|
||||
condition: a.condition.map(|e| substitute(e, &temps)),
|
||||
body: block(a.body, temps.clone()),
|
||||
})
|
||||
.collect(),
|
||||
span,
|
||||
},
|
||||
Stmt::ForEach {
|
||||
item,
|
||||
collection,
|
||||
label,
|
||||
body,
|
||||
span,
|
||||
} => Stmt::ForEach {
|
||||
item,
|
||||
collection,
|
||||
label,
|
||||
body: block(body, temps.clone()),
|
||||
span,
|
||||
},
|
||||
Stmt::While {
|
||||
condition,
|
||||
body,
|
||||
span,
|
||||
} => Stmt::While {
|
||||
condition: substitute(condition, &temps),
|
||||
body: block(body, temps.clone()),
|
||||
span,
|
||||
},
|
||||
other => other,
|
||||
};
|
||||
out.push(s);
|
||||
}
|
||||
out
|
||||
}
|
||||
block(statements, std::collections::BTreeMap::new())
|
||||
}
|
||||
|
||||
fn statement(s: Stmt) -> Stmt {
|
||||
let span = Span::new(0, 0);
|
||||
match s {
|
||||
Stmt::Assign { name, value, .. } => Stmt::Assign {
|
||||
name,
|
||||
value: expr(value),
|
||||
span,
|
||||
end_line: 0,
|
||||
},
|
||||
Stmt::Return { value, .. } => Stmt::Return {
|
||||
value: expr(value),
|
||||
span,
|
||||
},
|
||||
Stmt::Call { call: c, .. } => Stmt::Expr {
|
||||
value: Expr::Call(call(c)),
|
||||
span,
|
||||
},
|
||||
Stmt::Expr { value, .. } => Stmt::Expr {
|
||||
value: expr(value),
|
||||
span,
|
||||
},
|
||||
Stmt::Branch { arms, .. } => Stmt::Branch {
|
||||
arms: arms
|
||||
.into_iter()
|
||||
.map(|a| BranchArm {
|
||||
condition: a.condition.map(expr),
|
||||
body: a.body.into_iter().map(statement).collect(),
|
||||
})
|
||||
.collect(),
|
||||
span,
|
||||
},
|
||||
Stmt::While {
|
||||
condition, body, ..
|
||||
} => Stmt::While {
|
||||
condition: expr(condition),
|
||||
body: body.into_iter().map(statement).collect(),
|
||||
span,
|
||||
},
|
||||
Stmt::ForEach {
|
||||
item,
|
||||
collection,
|
||||
body,
|
||||
..
|
||||
} => Stmt::ForEach {
|
||||
item,
|
||||
collection,
|
||||
body: body.into_iter().map(statement).collect(),
|
||||
span,
|
||||
label: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
fn quote(s: &str) -> String {
|
||||
serde_json::to_string(s).unwrap().replace('`', "\\`")
|
||||
}
|
||||
fn render(e: &Expr) -> Result<String> {
|
||||
Ok(match e {
|
||||
Expr::Literal(l) => match l {
|
||||
Literal::None => "None".into(),
|
||||
Literal::Bool(b) => if *b { "True" } else { "False" }.into(),
|
||||
Literal::Int(n) => n.to_string(),
|
||||
Literal::Num(n) => {
|
||||
let text = n.to_string();
|
||||
if text.contains('.') || text.contains(['e', 'E']) {
|
||||
text
|
||||
} else {
|
||||
format!("{text}.0")
|
||||
}
|
||||
}
|
||||
Literal::Text(s) => quote(s),
|
||||
},
|
||||
Expr::Var(n) => format!("`{n}`"),
|
||||
Expr::Interp(parts) => {
|
||||
let mut s = String::new();
|
||||
for p in parts {
|
||||
match p {
|
||||
InterpPart::Lit(t) => s.push_str(&t.replace('`', "\\`")),
|
||||
InterpPart::Var(v) => s.push_str(&format!("`{v}`")),
|
||||
InterpPart::Index { .. } => {
|
||||
anyhow::bail!("legacy interpolated index needs review")
|
||||
}
|
||||
}
|
||||
}
|
||||
serde_json::to_string(&s)?.replace("\\\\`", "\\`")
|
||||
}
|
||||
Expr::Call(c) => render_call(c)?,
|
||||
Expr::Unary { op, expr: e } => format!(
|
||||
"({}{})",
|
||||
match op {
|
||||
UnaryOp::Not => "not ",
|
||||
UnaryOp::Neg => "-",
|
||||
},
|
||||
render(e)?
|
||||
),
|
||||
Expr::Binary { op, left, right } => format!(
|
||||
"({} {} {})",
|
||||
render(left)?,
|
||||
match op {
|
||||
BinaryOp::Add => "+",
|
||||
BinaryOp::Sub => "-",
|
||||
BinaryOp::Mul => "*",
|
||||
BinaryOp::Div => "/",
|
||||
BinaryOp::Eq => "==",
|
||||
BinaryOp::Ne => "!=",
|
||||
BinaryOp::Lt => "<",
|
||||
BinaryOp::Le => "<=",
|
||||
BinaryOp::Gt => ">",
|
||||
BinaryOp::Ge => ">=",
|
||||
BinaryOp::And => "and",
|
||||
BinaryOp::Or => "or",
|
||||
},
|
||||
render(right)?
|
||||
),
|
||||
Expr::List(xs) => format!(
|
||||
"[{}]",
|
||||
xs.iter()
|
||||
.map(render)
|
||||
.collect::<Result<Vec<_>>>()?
|
||||
.join(", ")
|
||||
),
|
||||
Expr::Map(xs) => format!(
|
||||
"{{{}}}",
|
||||
xs.iter()
|
||||
.map(|(k, v)| Ok(format!("{}: {}", quote(k), render(v)?)))
|
||||
.collect::<Result<Vec<_>>>()?
|
||||
.join(", ")
|
||||
),
|
||||
Expr::Occluded {
|
||||
label,
|
||||
payload: Some(p),
|
||||
} => format!("[{}]({})", label.replace(']', "\\]"), render(p)?),
|
||||
Expr::Occluded { payload: None, .. } => "None".into(),
|
||||
_ => anyhow::bail!("expression needs manual rendering: {e:?}"),
|
||||
})
|
||||
}
|
||||
fn render_call(c: &CallExpr) -> Result<String> {
|
||||
let target = if let Some(r) = &c.receiver {
|
||||
format!("`{r}`.{}", c.callee)
|
||||
} else if let Some(p) = &c.path {
|
||||
p.join(".")
|
||||
} else {
|
||||
c.callee.clone()
|
||||
};
|
||||
let c = c.with_modifiers_expanded().map_err(anyhow::Error::msg)?;
|
||||
let args = c
|
||||
.args
|
||||
.iter()
|
||||
.map(|a| {
|
||||
Ok(match a {
|
||||
Arg::Positional(e) => render(e)?,
|
||||
Arg::Named { name, value } => format!("{name}={}", render(value)?),
|
||||
})
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
if c.receiver.is_some() {
|
||||
Ok(format!("> {target} {} ", args.join(" ")))
|
||||
} else {
|
||||
Ok(format!("{target}({})", args.join(", ")))
|
||||
}
|
||||
}
|
||||
fn receiver_call(c: &CallExpr, f: &Function, imports: &[String]) -> CallExpr {
|
||||
let mut c = c.clone();
|
||||
if let Some(path) = &c.path {
|
||||
if path.len() == 2
|
||||
&& f.params.iter().any(|p| p.name == path[0])
|
||||
&& !imports.contains(&path[0])
|
||||
{
|
||||
c.receiver = Some(path[0].clone());
|
||||
c.path = None;
|
||||
}
|
||||
}
|
||||
c
|
||||
}
|
||||
fn render_value(v: &Expr, f: &Function, imports: &[String]) -> Result<String> {
|
||||
match v {
|
||||
Expr::Call(c) => render_call(&receiver_call(c, f, imports)),
|
||||
Expr::Occluded {
|
||||
label,
|
||||
payload: Some(v),
|
||||
} => Ok(format!(
|
||||
"[{}]({})",
|
||||
label.replace(']', "\\]"),
|
||||
render_value(v, f, imports)?
|
||||
)),
|
||||
other => render(other),
|
||||
}
|
||||
}
|
||||
// A qualified call through a parameter and its explicit receiver form resolve
|
||||
// the same object when that name is not an imported module binding.
|
||||
fn normalize_receiver_text(mut body: String, params: &Value, imports: &[String]) -> String {
|
||||
for p in params.as_array().unwrap() {
|
||||
let name = p["name"].as_str().unwrap();
|
||||
if imports.iter().any(|i| i == name) {
|
||||
continue;
|
||||
}
|
||||
let quoted = serde_json::to_string(name).unwrap();
|
||||
let pattern = format!(
|
||||
r#"path: Some\(\[{}, "[^"\n]+"\]\), receiver: None"#,
|
||||
regex::escape("ed)
|
||||
);
|
||||
let re = regex::Regex::new(&pattern).unwrap();
|
||||
body = re
|
||||
.replace_all(&body, format!("path: None, receiver: Some({quoted})"))
|
||||
.into_owned();
|
||||
}
|
||||
body
|
||||
}
|
||||
fn collect(fs: &[Function], prefix: &str, source: &str, imports: &[String], out: &mut Vec<Value>) {
|
||||
for f in fs {
|
||||
let name = if prefix.is_empty() {
|
||||
f.name.clone()
|
||||
} else {
|
||||
format!("{prefix}.{}", f.name)
|
||||
};
|
||||
let mut calls = Vec::new();
|
||||
marqdo::ast::walk_stmts(f, &mut |s| {
|
||||
if let Stmt::Call { call, span } = s {
|
||||
calls.push(json!({"line":span.line,"rendered":render_call(&receiver_call(call, f, imports)).ok(),"call":format!("{call:?}")}))
|
||||
}
|
||||
});
|
||||
let mut statements = Vec::new();
|
||||
marqdo::ast::walk_stmts(f, &mut |s| {
|
||||
let (kind, name, value, line, end) = match s {
|
||||
Stmt::Assign {
|
||||
name,
|
||||
value,
|
||||
span,
|
||||
end_line,
|
||||
} => (
|
||||
"assign",
|
||||
Some(name.as_str()),
|
||||
Some(value),
|
||||
span.line,
|
||||
*end_line,
|
||||
),
|
||||
Stmt::Return { value, span } => ("return", None, Some(value), span.line, span.line),
|
||||
Stmt::Expr { value, span } => ("expr", None, Some(value), span.line, span.line),
|
||||
Stmt::Call { call, span } => {
|
||||
statements.push(json!({"kind":"call", "line":span.line, "rendered":render_call(&receiver_call(call, f, imports)).ok(), "callee":call.callee, "path":call.path, "receiver":call.receiver}));
|
||||
return;
|
||||
}
|
||||
_ => return,
|
||||
};
|
||||
let mut inner = value;
|
||||
while let Some(Expr::Occluded {
|
||||
payload: Some(p), ..
|
||||
}) = inner
|
||||
{
|
||||
inner = Some(p);
|
||||
}
|
||||
let target = match inner {
|
||||
Some(Expr::Call(c)) => {
|
||||
Some(json!({"callee":c.callee,"path":c.path,"receiver":c.receiver}))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
statements.push(json!({"kind":kind,"name":name,"line":line,"end":end,"rendered":value.and_then(|v|render_value(v, f, imports).ok()),"target":target,"value":value.map(|v|format!("{v:?}"))}));
|
||||
});
|
||||
out.push(json!({"name":name,"short_name":f.name,"line":f.span.line,"level":f.level,"base":f.base,"receiver":function_uses_receiver(f),"params":f.params.iter().map(|p|json!({"name":p.name,"line":p.span.line,"default":p.default.as_ref().map(|e|format!("{:?}",expr(e.clone()))),"default_source":p.default.as_ref().and_then(|e|render(e).ok()),"type":f.contract.as_ref().and_then(|c|c.params.iter().find(|x|x.name==p.name)).map(|p|p.ty.name()).unwrap_or("any".into())})).collect::<Vec<_>>(),"returns":f.contract.as_ref().and_then(|c|c.returns.as_ref()).map(|r|r.ty.name()).unwrap_or("any".into()),"contract":f.contract.as_ref().map(|c|format!("{c:?}")),"body":format!("{:?}",canonical_statements(f.body.clone())),"calls":calls,"statements":statements,"narrative":marqdo::narrative_ratio::measure_source_units(source,std::slice::from_ref(f)).first().map(|r|r.ratio)}));
|
||||
collect(&f.children, &name, source, imports, out);
|
||||
}
|
||||
}
|
||||
fn difference(description: String, before: Value, after: Value) -> Value {
|
||||
use sha2::Digest;
|
||||
let digest = |value: Value| {
|
||||
format!(
|
||||
"{:x}",
|
||||
sha2::Sha256::digest(serde_json::to_vec(&value).unwrap())
|
||||
)
|
||||
};
|
||||
json!({"difference":description,"before":digest(before),"after":digest(after)})
|
||||
}
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<_> = std::env::args().collect();
|
||||
let baseline = args
|
||||
.iter()
|
||||
.position(|x| x == "--compare")
|
||||
.map(|i| fs::read_to_string(&args[i + 1]))
|
||||
.transpose()?
|
||||
.map(|s| serde_json::from_str::<Value>(&s))
|
||||
.transpose()?;
|
||||
let original = args
|
||||
.iter()
|
||||
.position(|x| x == "--from")
|
||||
.map(|i| fs::read_to_string(&args[i + 1]))
|
||||
.transpose()?
|
||||
.map(|s| serde_json::from_str::<Value>(&s))
|
||||
.transpose()?;
|
||||
let mut paths = Vec::new();
|
||||
files(Path::new("lib"), &mut paths)?;
|
||||
files(Path::new("ext"), &mut paths)?;
|
||||
paths.sort();
|
||||
if let Some(input) = &original {
|
||||
paths.retain(|p| input.get(p.to_str().unwrap()).is_some());
|
||||
}
|
||||
let mut result = serde_json::Map::new();
|
||||
let mut differences = Vec::new();
|
||||
for path in paths {
|
||||
let key = path.to_str().context("UTF-8 library path")?;
|
||||
let source = if let Some(s) = original
|
||||
.as_ref()
|
||||
.and_then(|m| m.get(key))
|
||||
.and_then(|m| m["source"].as_str())
|
||||
{
|
||||
s.to_owned()
|
||||
} else {
|
||||
fs::read_to_string(&path)?
|
||||
};
|
||||
let module = marqdo::parse::parse_source(&source).with_context(|| key.to_owned())?;
|
||||
let mut functions = Vec::new();
|
||||
let imports: Vec<_> = module
|
||||
.imports
|
||||
.iter()
|
||||
.map(|i| i.bind.clone())
|
||||
.chain(module.uses.iter().map(|i| i.bind.clone()))
|
||||
.collect();
|
||||
collect(&module.functions, "", &source, &imports, &mut functions);
|
||||
let reports = marqdo::narrative_ratio::measure_source_units(&source, &module.functions);
|
||||
for f in &mut functions {
|
||||
let report = reports.iter().find(|r| json!(r.line) == f["line"]).unwrap();
|
||||
f["narrative_chars"] = json!(report.narrative);
|
||||
f["code_chars"] = json!(report.total - report.narrative);
|
||||
f["narrative"] = json!(
|
||||
reports
|
||||
.iter()
|
||||
.find(|r| json!(r.line) == f["line"])
|
||||
.unwrap()
|
||||
.ratio
|
||||
);
|
||||
}
|
||||
if let Some(old) = baseline.as_ref().and_then(|b| b.get(key)) {
|
||||
for o in old["functions"].as_array().unwrap() {
|
||||
match functions.iter().find(|f| f["name"] == o["name"]) {
|
||||
None => differences.push(difference(
|
||||
format!("removed {key} {}", o["name"]),
|
||||
json!({"level":o["level"],"base":o["base"],"receiver":o["receiver"],"params":o["params"].as_array().unwrap().iter().map(|p|json!([p["name"],p["default"]])).collect::<Vec<_>>(),"body":o["body"]}),
|
||||
Value::Null,
|
||||
)),
|
||||
Some(n) => {
|
||||
for field in ["level", "base", "receiver", "body"] {
|
||||
let same = if field == "body" {
|
||||
normalize_receiver_text(
|
||||
n[field].as_str().unwrap().to_owned(),
|
||||
&o["params"],
|
||||
&imports,
|
||||
) == normalize_receiver_text(
|
||||
o[field].as_str().unwrap().to_owned(),
|
||||
&o["params"],
|
||||
&imports,
|
||||
)
|
||||
} else {
|
||||
n[field] == o[field]
|
||||
};
|
||||
if !same {
|
||||
differences.push(difference(format!("{key} {} changed {field}", o["name"]), o[field].clone(), n[field].clone()));
|
||||
}
|
||||
}
|
||||
let sig = |f: &Value| {
|
||||
f["params"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|p| json!([p["name"], p["default"]]))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
if sig(n) != sig(o) {
|
||||
differences.push(difference(format!("{key} {} changed parameters", o["name"]),json!(sig(o)),json!(sig(n))));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
result.insert(
|
||||
key.to_owned(),
|
||||
json!({"source": source, "functions": functions}),
|
||||
);
|
||||
}
|
||||
if let Some(i) = args.iter().position(|x| x == "--snapshot") {
|
||||
fs::write(&args[i + 1], serde_json::to_vec_pretty(&result)?)?;
|
||||
}
|
||||
println!(
|
||||
"{} library files, {} functions",
|
||||
result.len(),
|
||||
result
|
||||
.values()
|
||||
.map(|f| f["functions"].as_array().unwrap().len())
|
||||
.sum::<usize>()
|
||||
);
|
||||
if let Some(i) = args.iter().position(|x| x == "--differences") {
|
||||
fs::write(&args[i + 1], serde_json::to_vec_pretty(&differences)?)?;
|
||||
}
|
||||
if baseline.is_some() {
|
||||
let reviewed = args
|
||||
.iter()
|
||||
.position(|x| x == "--reviewed-fixes")
|
||||
.map(|i| fs::read_to_string(&args[i + 1]))
|
||||
.transpose()?
|
||||
.map(|text| serde_json::from_str::<Vec<Value>>(&text))
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
let matches = |d: &Value, r: &Value| {
|
||||
["difference", "before", "after"]
|
||||
.iter()
|
||||
.all(|k| d[*k] == r[*k])
|
||||
&& r["reason"].as_str().is_some_and(|s| !s.trim().is_empty())
|
||||
};
|
||||
let unreviewed: Vec<_> = differences
|
||||
.iter()
|
||||
.filter(|d| !reviewed.iter().any(|r| matches(d, r)))
|
||||
.collect();
|
||||
let stale: Vec<_> = reviewed
|
||||
.iter()
|
||||
.filter(|r| !differences.iter().any(|d| matches(d, r)))
|
||||
.collect();
|
||||
println!("{} executable differences, {} exact reviewed fixes, {} unreviewed, {} stale review records",
|
||||
differences.len(),differences.len()-unreviewed.len(),unreviewed.len(),stale.len());
|
||||
for d in &unreviewed {
|
||||
println!("{}", d["difference"]);
|
||||
}
|
||||
if !unreviewed.is_empty() || !stale.is_empty() {
|
||||
anyhow::bail!(
|
||||
"review executable differences; only exact before/after digests are accepted"
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn json_literal_audit_rejects_duplicates_unsafe_numbers_and_trailing_data() {
|
||||
for text in [
|
||||
r#"{"x":1,"x":2}"#,
|
||||
r#"{"nested":{"x":1,"x":2}}"#,
|
||||
r#"{"x":9007199254740992}"#,
|
||||
r#"{} false"#,
|
||||
r#"{"x":NaN}"#,
|
||||
] {
|
||||
assert!(flat_json_record(text).is_none(), "{text}");
|
||||
}
|
||||
let value = flat_json_record(r#"{"z":[null,true,"a\nb"],"a":1}"#).unwrap();
|
||||
assert!(constant(&value));
|
||||
let Expr::Map(fields) = value else {
|
||||
panic!("map expected");
|
||||
};
|
||||
assert_eq!(fields[0].0, "a");
|
||||
assert_eq!(fields[1].0, "z");
|
||||
}
|
||||
#[test]
|
||||
fn only_supported_constant_builders_are_folded() {
|
||||
for code in [
|
||||
"unknown(text=\"{}\")",
|
||||
"json.parse(text=`input`)",
|
||||
"table.put(in=`input`, at=\"key\", value=1)",
|
||||
"text.str_join(xs=`rows`, sep=\"\\n\")",
|
||||
] {
|
||||
let Expr::Call(call) = marqdo::parse::expr::parse_expr(code).unwrap() else {
|
||||
panic!("call expected");
|
||||
};
|
||||
assert!(pure_literal_call(&call).is_none(), "{code}");
|
||||
}
|
||||
let Expr::Call(call) =
|
||||
marqdo::parse::expr::parse_expr("json.parse(text=\"{\\\"key\\\":null}\")").unwrap()
|
||||
else {
|
||||
panic!("call expected");
|
||||
};
|
||||
assert!(pure_literal_call(&call).is_some());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: Standard library engineering practice
|
||||
import:
|
||||
fs: lib/fs.mq.md
|
||||
path: lib/path.mq.md
|
||||
table: lib/table.mq.md
|
||||
csv: lib/csv.mq.md
|
||||
document: lib/document.mq.md
|
||||
hash: lib/hash.mq.md
|
||||
bytes: lib/bytes.mq.md
|
||||
---
|
||||
|
||||
This project demonstrates file inventory, typed CSV aggregation and controlled
|
||||
Markdown maintenance using the public standard library. No foreign program,
|
||||
plugin or alternate data syntax is involved. Each operation below is callable.
|
||||
The demo creates its own directory under the filesystem root and removes it
|
||||
when successful; it returns the real inventory, report and update outcome.
|
||||
|
||||
Create a disposable directory and set MQ_WORK to its absolute path before the
|
||||
following command. All relative IO is confined to that directory. The Rust
|
||||
acceptance test prepares this directory and runs the same source on both runtimes.
|
||||
|
||||
```sh
|
||||
marqdo call examples/stdlib-handbook/index.mq.md demo --fs-root "$MQ_WORK" --effects fs.write --json
|
||||
```
|
||||
|
||||
For production, call inventory on your source directory, summarize_csv on text
|
||||
from fs.read_text, or update_section with an explicit title and replacement body.
|
||||
Inspect each operation Result before using its value. File inventory keeps one
|
||||
unreadable file from aborting other records. Directory cleanup and the update are
|
||||
separate operations, not a transaction. For high-volume inputs use the batched
|
||||
collection transforms; this report uses batch transforms, including grouping and aggregation.
|
||||
|
||||
## inventory
|
||||
+ `root`
|
||||
|
||||
| 参数 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| root | text | Directory relative to the granted filesystem root |
|
||||
|
||||
| 返回 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| result | list | One path/ok/characters/error record per Markdown file |
|
||||
|
||||
Discover Markdown files, then retain each read outcome. A bad UTF-8 document
|
||||
is represented as an error record; valid documents still contribute counts.
|
||||
|
||||
**names = fs.find path=`root` pattern="**/*.md"**
|
||||
**out = table.empty_list**
|
||||
- [inspect each discovered file](遍历 names 为 name)
|
||||
**file = path.join a=`root` b=`name`**
|
||||
**read = fs.try_read_text path=`file`**
|
||||
**characters = None**
|
||||
1. [read succeeded](access(`read`, "ok"))
|
||||
**body = access(read, "value")**
|
||||
**characters = len `body`**
|
||||
2. *
|
||||
**characters = None**
|
||||
**success = access(read, "ok")**
|
||||
**error = access(read, "error")**
|
||||
`record` =
|
||||
|
||||
| path | ok | characters | error |
|
||||
|---|---|---|---|
|
||||
| `name` | `success` | `characters` | `error` |
|
||||
|
||||
**out = table.append list=`out` item=`record`**
|
||||
*out*
|
||||
|
||||
## summarize_csv
|
||||
+ `text`
|
||||
|
||||
| 参数 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| text | text | Header-based CSV: team, amount and active fields |
|
||||
|
||||
| 返回 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| result | text | CSV with team/total/count for active rows |
|
||||
|
||||
CSV cells start as text. Convert them deliberately, select active rows, group
|
||||
by team, and sum integer amounts with overflow checks. Nothing passes through SQL.
|
||||
|
||||
**rows = csv.parse text=`text`**
|
||||
`schema` =
|
||||
|
||||
| amount | active |
|
||||
|---|---|
|
||||
| int | bool |
|
||||
|
||||
**typed = table.cast rows=`rows` schema=`schema`**
|
||||
**selected = table.where list=`typed` key="active" value=True**
|
||||
**summary = table.summarize list=`selected` key="team" field="amount"**
|
||||
`names` =
|
||||
|
||||
| key | value |
|
||||
|---|---|
|
||||
| team | total |
|
||||
|
||||
**renamed = table.rename list=`summary` fields=`names`**
|
||||
`fields` =
|
||||
|
||||
| field |
|
||||
|---|
|
||||
| team |
|
||||
| total |
|
||||
| count |
|
||||
|
||||
**report = table.project list=`renamed` keys=`fields`**
|
||||
*> csv.stringify rows=`report`*
|
||||
|
||||
## update_section
|
||||
+ `path`
|
||||
+ `title`
|
||||
+ `body`
|
||||
|
||||
| 参数 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| path | text | Existing Markdown file under the granted root |
|
||||
| title | text | Exact, unique heading title |
|
||||
| body | text | Replacement section body, without its heading |
|
||||
|
||||
| 返回 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| result | map | Recoverable replacement/write outcome |
|
||||
|
||||
Compute the expected digest from the exact source that was read. Transform
|
||||
only the selected body; fs.write_checked detects stale content before replacing.
|
||||
Concurrent writers still need coordination: this is not a kernel CAS primitive.
|
||||
|
||||
**source = fs.read_text path=`path`**
|
||||
**expected = hash.sha256 text=`source`**
|
||||
**changed = document.replace_section text=`source` title=`title` body=`body`**
|
||||
1. [section replacement succeeded](access(`changed`, "ok"))
|
||||
**next = access(changed, "value")**
|
||||
*> fs.write_checked path=`path` text=`next` expected_sha256=`expected`*
|
||||
2. *
|
||||
*changed*
|
||||
|
||||
## demo
|
||||
|
||||
| 返回 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| result | map | Actual file inventory, CSV report and document update |
|
||||
|
||||
Prepare a small valid corpus and an invalid UTF-8 file, then run all three
|
||||
operations. Validate the returned data; this function never fabricates a pass flag.
|
||||
|
||||
**work = fs.temp_dir prefix="stdlib-demo"**
|
||||
**note = path.join a=`work` b="notes.md"**
|
||||
**bad = path.join a=`work` b="invalid.md"**
|
||||
**corpus = "# Notes\n\n## Status\n\nOld status.\n\n# Appendix\n\nKeep this paragraph.\n"**
|
||||
> fs.atomic_write path=`note` text=`corpus`
|
||||
**binary = bytes.from_base64 text="/w=="**
|
||||
> fs.write_bytes path=`bad` data=`binary`
|
||||
**files = inventory root=`work`**
|
||||
**data = "team,amount,active\na,10,true\nb,4,false\na,20,true\n"**
|
||||
**report = summarize_csv text=`data`**
|
||||
**update = update_section path=`note` title="Status" body="Updated through public standard libraries."**
|
||||
**after = fs.read_text path=`note`**
|
||||
> fs.remove_tree path=`work`
|
||||
`out` =
|
||||
|
||||
| inventory | csv | update | document |
|
||||
|---|---|---|---|
|
||||
| `files` | `report` | `update` | `after` |
|
||||
|
||||
*out*
|
||||
@@ -0,0 +1,9 @@
|
||||
---
|
||||
markup: occlusion
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
A file task returns its answer; stdout is not the answer channel.
|
||||
|
||||
*17*
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: 标准库工程实践
|
||||
import:
|
||||
practice: index.mq.md
|
||||
---
|
||||
|
||||
本工程把文件整理、CSV 数据处理和文档维护连为真实工作流。
|
||||
中文入口复用同一份实现,避免双语版本逐渐分叉。准备一个可丢弃目录,
|
||||
把其绝对路径设为 MQ_WORK,再执行下面的工具;成功后会清理自己的临时子目录。
|
||||
返回值包含真实的文件结果、CSV 报表及修改后文档,不以一个通过标志代替验收。
|
||||
|
||||
```sh
|
||||
marqdo call examples/stdlib-handbook/索引.mq.md 演示 --fs-root "$MQ_WORK" --effects fs.write --json
|
||||
```
|
||||
|
||||
生产使用时先阅读[同源实现](index.mq.md),选择文件清单、汇总报表或更新章节。
|
||||
读取失败以每文件错误记录保留;CSV 字段先显式转换类型;章节替换保留周围叙述,
|
||||
写入前检查来源摘要。根目录、失败结果和并发写入限制都在真实函数旁说明。
|
||||
|
||||
## 演示
|
||||
|
||||
| 返回 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| result | map | 三项真实工作流的结果 |
|
||||
|
||||
执行同源工程,保留所有实际返回数据和失败行为。
|
||||
|
||||
*> practice.demo*
|
||||
@@ -0,0 +1,123 @@
|
||||
//! Inspect real single-file standard library signatures; no index module is required.
|
||||
//! --json emits compiler metadata; --check validates source effect notes;
|
||||
//! --write refreshes only effect notes, preserving authored prose and examples.
|
||||
use anyhow::{bail, Context, Result};
|
||||
use std::{
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<_> = std::env::args().collect();
|
||||
let write = args.iter().any(|arg| arg == "--write");
|
||||
let json = args.iter().any(|arg| arg == "--json");
|
||||
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
let mut sources: Vec<_> = fs::read_dir(root.join("lib"))?
|
||||
.map(|entry| entry.map(|e| e.path()))
|
||||
.collect::<std::io::Result<_>>()?;
|
||||
sources.retain(|p| p.is_file() && p.to_string_lossy().ends_with(".mq.md"));
|
||||
sources.sort();
|
||||
let mut changed = 0;
|
||||
let mut tools = Vec::new();
|
||||
for source in sources {
|
||||
let module = marqdo::load::load_module(&source)?;
|
||||
let compilation = marqdo::sema::compile_file_closure(&source)?;
|
||||
let content = fs::read_to_string(&source)?;
|
||||
let mut lines: Vec<_> = content.lines().map(str::to_owned).collect();
|
||||
let mut edits = Vec::new();
|
||||
let zh = source
|
||||
.file_name()
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.chars()
|
||||
.any(|c| !c.is_ascii());
|
||||
for (index, function) in module.functions.iter().enumerate() {
|
||||
let artifact = compilation
|
||||
.semantics
|
||||
.artifacts
|
||||
.iter()
|
||||
.find(|a| {
|
||||
a.kind == "function"
|
||||
&& a.source.line == function.span.line
|
||||
&& same_source(&compilation.semantics.root, &a.source.file, &source)
|
||||
})
|
||||
.context("missing compiler function artifact")?;
|
||||
let signature = artifact
|
||||
.signature
|
||||
.as_ref()
|
||||
.context("missing compiler signature")?;
|
||||
let effects: Vec<_> = artifact
|
||||
.effects
|
||||
.values()
|
||||
.into_iter()
|
||||
.filter(|e| *e != "pure")
|
||||
.collect();
|
||||
let effects = if effects.is_empty() {
|
||||
"pure".to_owned()
|
||||
} else {
|
||||
effects.join(",")
|
||||
};
|
||||
let expected = if zh {
|
||||
format!("调用效应:{effects}。")
|
||||
} else {
|
||||
format!("Effects: {effects}.")
|
||||
};
|
||||
let start = function.span.line as usize;
|
||||
let end = module
|
||||
.functions
|
||||
.get(index + 1)
|
||||
.map(|f| (f.span.line as usize).saturating_sub(1))
|
||||
.unwrap_or(lines.len());
|
||||
let notes: Vec<_> = (start..end)
|
||||
.filter(|i| {
|
||||
lines[*i].starts_with("Effects: ") || lines[*i].starts_with("调用效应:")
|
||||
})
|
||||
.collect();
|
||||
if notes.len() != 1 {
|
||||
bail!(
|
||||
"{} {} needs one effect note in its source",
|
||||
source.display(),
|
||||
function.name
|
||||
);
|
||||
}
|
||||
if lines[notes[0]] != expected {
|
||||
changed += 1;
|
||||
if write {
|
||||
edits.push((notes[0], expected));
|
||||
} else if !json {
|
||||
eprintln!("stale effect note: {} {}", source.display(), function.name);
|
||||
}
|
||||
}
|
||||
tools.push(serde_json::json!({
|
||||
"name": function.name,
|
||||
"parameters": signature.params.iter().map(|p| serde_json::json!({"name":p.name,"type":p.ty,"required":p.required,"default_digest":p.default_digest.as_ref().map(|d| &d.0),"unit":p.unit})).collect::<Vec<_>>(),
|
||||
"returns": signature.returns,
|
||||
"effects": artifact.effects.values(),
|
||||
"source": source.strip_prefix(&root)?,
|
||||
"line": function.span.line
|
||||
}));
|
||||
}
|
||||
if !edits.is_empty() {
|
||||
for (line, text) in edits {
|
||||
lines[line] = text;
|
||||
}
|
||||
fs::write(&source, lines.join("\n") + "\n")?;
|
||||
}
|
||||
}
|
||||
if json {
|
||||
println!("{}", serde_json::to_string_pretty(&tools)?);
|
||||
} else if changed > 0 && !write {
|
||||
bail!("{changed} effect notes differ from compiler metadata; run with --write");
|
||||
} else {
|
||||
println!(
|
||||
"{} source effect notes {}; {} public functions",
|
||||
changed,
|
||||
if write { "updated" } else { "need updating" },
|
||||
tools.len()
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn same_source(root: &Path, relative: &str, source: &Path) -> bool {
|
||||
root.join(relative).canonicalize().ok() == source.canonicalize().ok()
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: 在正文里读懂一段程序
|
||||
description: 用同一份源码演示动作遮蔽、输入输出、数据表、条件、循环和待补逻辑。
|
||||
---
|
||||
|
||||
这份示例把计算留在文章里。动作说明可以直接阅读,展开侧注才看到实际表达式。
|
||||
侧注说明“准备怎样计算”,运行标注说明“这一次得到什么”;两种信息有不同的来源。
|
||||
|
||||
用 marqdo view examples/view-reading.mq.md 打开实时阅读,或执行下面的离线导出命令。
|
||||
导出时的 --no-exec 只分析和排版,不运行示例,也不触发任何动作。
|
||||
|
||||
```sh
|
||||
marqdo view output examples/view-reading.mq.md --no-exec --out /tmp/marqdo-reading
|
||||
```
|
||||
|
||||
## 计算小计
|
||||
|
||||
| 参数 | 类型 | 默认 | 说明 |
|
||||
|---|---|---|---|
|
||||
| 单价 | number | 必填 | 每件商品的价格,使用调用方选定的同一种货币单位 |
|
||||
| 数量 | number | 1 | 购买的件数;本例由调用方保证非负 |
|
||||
|
||||
| 返回 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| 小计 | number | 单价乘以数量得到的金额,不包含额外税费或优惠 |
|
||||
|
||||
已知商品的`单价`,未指定时购买`数量`=1。这里没有网络请求或文件写入;
|
||||
价格与数量由调用者提供,不会从屏幕上的说明自动推测。
|
||||
完成乘法后,我们返回*[按件数计算金额](单价 * 数量)*,让后面的步骤继续使用。
|
||||
|
||||
## 预留逻辑
|
||||
|
||||
| 返回 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| 结果 | any | 当前返回 None;尚未接入实际业务实现 |
|
||||
|
||||
此函数演示空遮蔽的显示。它没有实现业务行为,不能作为“功能已完成”的证据。
|
||||
目前返回*[由作者补充具体业务]()*;阅读器会明确标出待补逻辑,而不会假装已有结果。
|
||||
|
||||
# main
|
||||
|
||||
| 返回 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| 结果 | map | 两笔金额与遍历计算的总数,均来自这一次实际执行 |
|
||||
|
||||
先**第一笔 = [购买两件商品](计算小计(单价=12, 数量=2))**,再**第二笔 = [使用默认件数](计算小计(单价=8))**。
|
||||
两个动作可以在同一句话里出现,各自关联自己的逻辑侧注。金额的实际数值只在运行后产生。
|
||||
|
||||
下面的单列表是三个数量组成的列表;绑定名让它成为数据,和上面的参数契约表不同。
|
||||
|
||||
`数量列表` =
|
||||
|
||||
| 数量 |
|
||||
|---|
|
||||
| 1 |
|
||||
| 2 |
|
||||
| 3 |
|
||||
|
||||
从**总数 = 0**开始累计,每次迭代读取一个值。切换迭代记录只是在查看既有结果,不会重跑循环。
|
||||
|
||||
- [依次累计数量](遍历 数量列表 为 项)
|
||||
把当前项加入已有累计,得到**总数 = 总数 + 项**。
|
||||
|
||||
下面按计算结果选择分支;未进入的分支仍然属于源码,不会因为查看运行记录而消失。
|
||||
|
||||
1. `总数` > 0
|
||||
确认这次遍历已有数据后,执行**[输出累计值](print(text=`总数`))**。
|
||||
2. *
|
||||
没有数量时,执行**[说明输入为空](print(text="没有数量"))**。
|
||||
|
||||
把已经计算的值整理成一行记录,字段名称说明每一项的来源。
|
||||
|
||||
`摘要` =
|
||||
|
||||
| 第一笔 | 第二笔 | 总数 |
|
||||
|---|---|---|
|
||||
| `第一笔` | `第二笔` | `总数` |
|
||||
|
||||
最后返回*摘要*,调用者得到的是结构化记录;上面的预留函数并未在本流程中调用。
|
||||
Reference in new issue
Block a user