use crate::pipeline::*;
use crate::syntax::ast::IndexSpec;
pub const MAX_FORK: usize = 10_000_000;
fn product_past_bound(left: usize, right: usize) -> Option<String> {
match left.checked_mul(right) {
Some(n) if n <= MAX_FORK => None,
_ => Some(format!(
"the product of {left} and {right} values is past the {MAX_FORK} one expression may fork"
)),
}
}
pub(crate) fn eval_operand<H: Host>(
host: &H,
ext: &H::Ext,
operand: &Operand,
trace: &H::Trace,
scope: Scope<'_, H::Ext>,
) -> Vec<Value> {
stacker::maybe_grow(1024 * 1024, 16 * 1024 * 1024, || {
eval_operand_in(host, ext, operand, trace, scope)
})
}
fn eval_operand_in<H: Host>(
host: &H,
ext: &H::Ext,
operand: &Operand,
trace: &H::Trace,
scope: Scope<'_, H::Ext>,
) -> Vec<Value> {
match operand {
Operand::Lit(Value::Quarq(q)) if q.projector.is_some() => {
vec![q.projector.as_deref().cloned().expect("checked")]
}
Operand::Lit(Value::Quarq(q)) if q.is_template() => {
vec![crate::pipeline::template::fill_template(
host, ext, q, trace, scope,
)]
}
Operand::Lit(v) => vec![v.clone()],
Operand::Hole(h) => {
record_refusal(format!(
"expansion '${{{}}}' stands outside a quarq template",
h.text
));
vec![Value::Null]
}
Operand::Pattern(_) => Vec::new(),
Operand::Match {
scrutinee,
arms,
other,
} => {
let subject = discard(|| operand_scalar(host, ext, scrutinee, trace, scope));
if matches!(subject, Value::Bool(_)) {
record_refusal(
"the switch compares a VALUE, and its scrutinee is a boolean: \
the plain conditional is '(cond ? a : b)'"
.to_string(),
);
return vec![Value::Null];
}
for (test, regex, result) in arms {
let mut groups: Option<Captured> = None;
let hit = discard(|| {
if *regex {
let pat = operand_scalar(host, ext, test, trace, scope);
let hit = regex_test(&subject, &pat, true);
if hit {
groups = compiled_regex(&pat.to_string())
.filter(|re| re.captures_len() > 1)
.and_then(|re| {
let text = subject.to_string();
re.captures(&text).map(|caps| {
let numbered = caps
.iter()
.skip(1)
.map(|g| {
g.map_or(String::new(), |m| m.as_str().to_string())
})
.collect();
let named = re
.capture_names()
.enumerate()
.filter_map(|(i, n)| {
n.map(|n| {
let text =
caps.get(i).map_or(String::new(), |m| {
m.as_str().to_string()
});
(n.to_string(), text)
})
})
.collect();
(numbered, named)
})
});
}
hit
} else {
let t = operand_scalar(host, ext, test, trace, scope);
value_eq(&subject, &t, &|e| host.scale_of(e))
}
});
if hit {
return match &groups {
Some((numbered, named)) => {
let arm = Scope {
captures: numbered,
named,
..scope
};
eval_operand(host, ext, result, trace, arm)
}
None => eval_operand(host, ext, result, trace, scope),
};
}
}
eval_operand(host, ext, other, trace, scope)
}
Operand::Now => vec![
run_option(|o| o.now)
.map(|(secs, nanos)| Value::Instant {
secs,
nanos,
offset_min: Some(0),
calendar: Default::default(),
})
.unwrap_or(Value::Null),
],
Operand::Recall(r) => {
note_all(&recall_origins(scope.register, r));
vec![recall(scope.register, r)]
}
Operand::Topic | Operand::Seed => {
if let Some(p) = scope.prov {
note_all(&p.origins);
}
vec![
scope
.topic
.cloned()
.or_else(|| with_run(|s| s.enclosing_topic.last().cloned()))
.or_else(|| host.node_form(ext).map(Value::quarq_form))
.unwrap_or(Value::Null),
]
}
Operand::Field { base, name, .. } if matches!(base.as_ref(), Operand::Recall(_)) => {
let Operand::Recall(r) = base.as_ref() else {
unreachable!()
};
note_all(&recall_field_origins(scope.register, r, name));
vec![match recall(scope.register, r) {
Value::Record(fields) => crate::value::ambient::read_field(&fields, name)
.cloned()
.unwrap_or(Value::Null),
t @ (Value::Table(_) | Value::Quarq(_)) => {
crate::pipeline::commands::record_field(t, name)
}
_ => Value::Null,
}]
}
Operand::ValueMeta { base, key } => {
let (_, o) = capture(|| eval_operand(host, ext, base, trace, scope));
note_all(&o);
vec![host.origins_meta(&o, key).unwrap_or(Value::Null)]
}
Operand::Field {
base,
name,
bare: true,
} if matches!(**base, Operand::Topic)
&& !matches!(scope.topic, Some(Value::Record(_) | Value::List(_)))
&& let Some(read) = row_field(name) =>
{
vec![match read {
Ok(v) => v,
Err(columns) => {
record_refusal(format!(
"no column '{name}' (the columns: {})",
columns.join(", ")
));
Value::Null
}
}]
}
Operand::Field { base, name, .. }
if matches!(**base, Operand::Topic)
&& let Some(Value::Record(r)) = scope.topic
&& r.get(name).is_none()
&& let Some(why) = crate::pipeline::run::missing_row_column(r, name) =>
{
record_refusal(why);
vec![Value::Null]
}
Operand::Field { base, name, .. }
if matches!(**base, Operand::Topic)
&& scope.topic.is_some_and(|t| matches!(t, Value::Node(_))) =>
{
let topic = scope.topic.cloned().unwrap_or(Value::Null);
vec![through(host, &topic, &Projection::CoreMeta(name.clone()))]
}
Operand::Field { base, name, .. }
if matches!(**base, Operand::Topic) && scope.topic.is_none() =>
{
note(host.origin_at(ext).position);
vec![host.project(ext, &Projection::CoreMeta(name.clone()))]
}
Operand::Field { base, name, .. }
if matches!(**base, Operand::Topic)
&& !matches!(
scope.topic,
Some(Value::Record(_) | Value::List(_) | Value::Table(_))
) =>
{
let own = scope.topic.and_then(|t| match t {
Value::Quarq(q) => q.core_field(name),
_ => None,
});
if let Some(v) = own {
vec![v]
} else if crate::graph::navigate::CORE_FIELDS.contains(&name.as_str()) {
note(host.origin_at(ext).position);
vec![host.project(ext, &Projection::CoreMeta(name.clone()))]
} else {
vec![Value::Null]
}
}
Operand::Field { base, name, .. } => eval_operand(host, ext, base, trace, scope)
.into_iter()
.map(|v| match &v {
Value::Node(_) | Value::List(_)
if !crate::graph::navigate::ref_nodes(&v).is_empty() =>
{
through(host, &v, &Projection::CoreMeta(name.clone()))
}
_ => record_field(v, name),
})
.collect(),
Operand::Through { base, projection } => eval_operand(host, ext, base, trace, scope)
.into_iter()
.map(|v| through(host, &v, projection))
.collect(),
Operand::LabelIndex { base, labels } => {
let specs: Vec<LabelSpec> = labels
.iter()
.flat_map(|l| match l {
Operand::Range {
from,
to,
step: None,
} => vec![LabelSpec::Range(
operand_value(host, ext, from, trace, scope),
operand_value(host, ext, to, trace, scope),
)],
other => match operand_value(host, ext, other, trace, scope) {
Value::List(items) => vec![LabelSpec::Many(items.to_vec())],
v => vec![LabelSpec::One(v)],
},
})
.collect();
eval_operand(host, ext, base, trace, scope)
.into_iter()
.map(|v| match label_lookup(v, &specs, &|e| host.scale_of(e)) {
Ok(v) => v,
Err(why) => {
crate::pipeline::record_refusal(why);
Value::Null
}
})
.collect()
}
Operand::Apply { base, reg, shot } => {
let command = match shot {
Some(shot) => Command::SpliceAs {
reg: reg.clone(),
shot: *shot,
},
None => Command::Splice(reg.clone()),
};
let piped = Operand::Piped {
expr: base.clone(),
commands: vec![command],
};
eval_operand(host, ext, &piped, trace, scope)
}
Operand::Projected { base, shape } => {
use crate::syntax::ast::ProjShape;
let probes: Vec<(H::Ext, Option<Value>)> = match base.as_ref() {
Operand::Rel {
steps,
projection,
anchor,
} => crate::pipeline::run::out_of_row_reach(|| {
host.rel_threads(ext, steps, anchor, projection.as_ref(), trace, scope)
})
.into_iter()
.map(|(x, topic, _)| (x, topic))
.collect(),
other => {
let at_node = matches!(other, Operand::Topic) && scope.topic.is_none();
eval_operand(host, ext, other, trace, scope)
.into_iter()
.map(|v| match v {
Value::Null if at_node => (ext.clone(), None),
v => (ext.clone(), Some(v)),
})
.collect()
}
};
let mut out = Vec::new();
for (x, topic) in &probes {
let pscope = Scope {
topic: topic.as_ref(),
prov: None,
members: &[],
..scope
};
let read =
|ladder: u8, key: &str| read_projection(host, x, ladder, key, trace, pscope);
match shape {
ProjShape::Value(v) => {
let values = match v.as_ref() {
Operand::Piped { expr, commands }
if matches!(**expr, Operand::Topic)
&& let [Command::Func(call)] = commands.as_slice()
&& matches!(call.name.as_str(), "rec" | "record") =>
{
let build = |pscope: Scope<'_, H::Ext>| match record_build(
&call.args, host, x, trace, pscope,
) {
Ok((r, _)) => Value::Record(r),
Err(why) => {
crate::pipeline::record_refusal(why);
Value::Null
}
};
match topic {
Some(Value::List(items))
if !items.is_empty()
&& items
.iter()
.all(|i| matches!(i, Value::Record(_))) =>
{
vec![Value::list(
items
.iter()
.map(|item| {
build(Scope {
topic: Some(item),
..pscope
})
})
.collect(),
)]
}
_ => vec![build(pscope)],
}
}
other => eval_operand(host, x, other, trace, pscope),
};
let held = matches!(v.as_ref(), Operand::Recall(_));
for value in values {
out.push(match value {
Value::Quarq(q) if held => match &q.projector {
Some(p) => walk_projections((**p).clone(), &read),
None => {
crate::pipeline::record_refusal(
"the colon projects; to run the quarq write v | &$.f (or v&$.f)"
.into(),
);
Value::Null
}
},
v @ (Value::Str(_) | Value::Int(_) | Value::Float(_) | Value::Bool(_) | Value::Null) if held => {
crate::pipeline::record_refusal(format!(
"the colon projects, and the regula holds {} with no projector in it; to run a quarq write v | &$.f",
crate::stdlib::kind_of(&v)
));
Value::Null
}
Value::Quarq(q) => run_quarq(host, x, &q, trace, pscope),
v => walk_projections(v, &read),
});
}
}
ProjShape::Columns {
items,
index,
autoindex,
casts,
} => {
let mut header: Vec<(String, Option<crate::ColumnType>)> =
Vec::with_capacity(items.len());
let mut columns = Vec::with_capacity(items.len());
let mut refused = false;
let named = |items: &[(Option<String>, Operand)], k: &str| {
items.iter().any(|(n, o)| {
n.as_deref() == Some(k)
|| crate::syntax::ast::auto_field_name(o) == Some(k)
})
};
let new_index: Option<
Result<Vec<(String, Option<crate::ColumnType>)>, String>,
> = index.as_ref().map(|op| {
match operand_value(host, x, op, trace, pscope) {
v @ (Value::Projection { .. } | Value::List(_) | Value::Str(_)) => {
Ok(crate::stdlib::index_levels(&v))
}
other => Err(format!(
"--index names a column with a projector (-i=:col), not {}",
crate::stdlib::kind_of(&other)
)),
}
});
if let Some(Value::Table(t)) = topic
&& t.index > 0
{
for j in 0..t.index {
let k = t.column_name(j);
let wanted = match &new_index {
None => true,
Some(Ok(levels)) => levels.iter().any(|(n, _)| *n == k),
Some(Err(_)) => false,
};
if wanted && !named(items, &k) {
header.push((k.clone(), t.declaration(j)));
columns.push(t.column(&k).unwrap_or(Value::Null));
}
}
}
let taken: Vec<String> = items
.iter()
.flat_map(|(n, o)| {
let o = match o {
Operand::Typed { inner, .. } => inner.as_ref(),
other => other,
};
let mut v = Vec::new();
if let Some(k) = n {
v.push(k.clone());
}
if let Operand::Field { base, name, .. } = o
&& matches!(**base, Operand::Topic)
&& name != "*"
{
v.push(name.clone());
}
v
})
.collect();
let is_rest = |o: &Operand| matches!(o, Operand::Field { base, name, .. } if matches!(**base, Operand::Topic) && name == "*");
for (name, item) in items {
if let Operand::Spread(inner) = item {
let held = operand_value(host, x, inner, trace, pscope);
let projectors = match held {
Value::List(l) => l.to_vec(),
p @ Value::Projection { .. } => vec![p],
other => {
crate::pipeline::record_refusal(format!(
"the spread in a table shape takes a list of projectors, not {}",
crate::stdlib::kind_of(&other)
));
refused = true;
break;
}
};
for p in projectors {
let Value::Projection {
ladder,
key,
typing,
} = p
else {
crate::pipeline::record_refusal(format!(
"the spread in a table shape takes projectors; {} is none",
p.display_form()
));
refused = true;
break;
};
header.push((
key.clone(),
typing.as_ref().and_then(crate::Typing::declared),
));
columns.push(read(ladder, &key));
}
if refused {
break;
}
continue;
}
if name.is_none() && is_rest(item) {
match topic {
Some(Value::Table(t)) => {
for j in t.index..t.width() {
let k = t.column_name(j);
if !taken.contains(&k) {
header.push((k.clone(), t.declaration(j)));
columns.push(t.column(&k).unwrap_or(Value::Null));
}
}
}
_ => {
crate::pipeline::record_refusal(
"':*' stands in a projector over a table (t:#(:*; …)) or a record (r:%(:*; …)): the rest of its columns or fields".into(),
);
refused = true;
break;
}
}
continue;
}
let (item, declared) = match item {
Operand::Typed { inner, typing } => {
(inner.as_ref(), typing.declared())
}
other => (other, None),
};
let key = name.clone().or_else(|| {
crate::syntax::ast::auto_field_name(item).map(str::to_string)
});
let Some(key) = key else {
crate::pipeline::record_refusal(
"the table shape names its columns: a bare projection (:A) or 'name = expr'".into(),
);
refused = true;
break;
};
header.push((key, declared));
let column = match (topic, item) {
(Some(Value::Table(t)), Operand::Field { base, name, .. })
if matches!(**base, Operand::Topic) =>
{
match t.column(name) {
Some(c) => c,
None => {
crate::pipeline::record_refusal(format!(
"no column '{name}' (the columns: {})",
(0..t.width())
.map(|j| t.column_name(j))
.collect::<Vec<_>>()
.join(", ")
));
refused = true;
break;
}
}
}
(Some(Value::Table(t)), item) => Value::list(
(1..=t.n_rows())
.map(|i| {
let row = t.row(i).unwrap_or(Value::Null);
with_row_in_reach(row, || {
walk_projections(
operand_value(host, x, item, trace, pscope),
&read,
)
})
})
.collect(),
),
_ => walk_projections(
operand_value(host, x, item, trace, pscope),
&read,
),
};
columns.push(column);
}
if !refused
&& let Some((k, _)) = header
.iter()
.enumerate()
.find(|(i, (k, _))| header[..*i].iter().any(|(h, _)| h == k))
.map(|(_, h)| h)
{
crate::pipeline::record_refusal(format!(
"'{k}' is already a column of the projector; a name stands once in a header"
));
refused = true;
}
if refused {
out.push(Value::Null);
continue;
}
let all_lists = !columns.is_empty()
&& columns.iter().all(|c| matches!(c, Value::List(_)));
let rows: Vec<Vec<Value>> = if all_lists {
let lists: Vec<Vec<Value>> = columns
.iter()
.map(|c| c.clone().into_items().unwrap_or_default())
.collect();
let n = lists.iter().map(Vec::len).max().unwrap_or(0);
(0..n)
.map(|i| {
lists
.iter()
.map(|l| l.get(i).cloned().unwrap_or(Value::Null))
.collect()
})
.collect()
} else {
vec![columns]
};
let kept = matches!(topic, Some(Value::Table(t)) if t.index > 0)
&& index.is_none();
let levels = matches!(topic, Some(Value::Table(t)) if t.levels);
let built = crate::Table::declared(header, rows)
.map(|t| t.with_levels(levels))
.and_then(|t| match new_index {
Some(Ok(levels)) => t.indexed_by_levels(&levels),
Some(Err(why)) => Err(why),
None => Ok(match topic {
Some(Value::Table(base)) if kept => t.with_index(base.index),
_ => t,
}),
});
let built = built.and_then(|t| {
if !*autoindex {
return Ok(t);
}
if index.is_some() {
return Err("#(…; -a -i=:col) names two indexes, and a table has one: -a prepends the positions as the index, -i=:col makes a column the index".into());
}
crate::stdlib::autoindex_bare(&t)
});
let built = built.and_then(|t| {
if casts.is_empty() {
return Ok(t);
}
let mut list: Vec<(String, crate::ColumnType)> = Vec::new();
for c in casts {
match operand_value(host, x, c, trace, pscope) {
v @ (Value::Projection { .. } | Value::List(_)) => {
for (name, ty) in crate::stdlib::index_levels(&v) {
match ty {
Some(ty) => list.push((name, ty)),
None => return Err(format!("-c=:{name} names no type: -c=:{name}<int>")),
}
}
}
other => return Err(format!("--cast names a column with a typed projector (-c=:col<int>), not {}", crate::stdlib::kind_of(&other))),
}
}
t.cast_columns(&list)
});
out.push(match built {
Ok(t) => Value::table(t),
Err(why) => {
crate::pipeline::record_refusal(why);
Value::Null
}
});
}
}
}
out
}
Operand::Spread(inner) => eval_operand(host, ext, inner, trace, scope),
Operand::List(items) => vec![Value::list(
items
.iter()
.flat_map(|item| match item {
Operand::Typed { inner, typing } => {
let key = crate::syntax::ast::auto_field_name(inner)
.unwrap_or_default()
.to_string();
eval_operand(host, ext, inner, trace, scope)
.into_iter()
.map(|v| cast_reading(v, &key, Some(typing.clone())))
.collect::<Vec<_>>()
}
other => eval_operand(host, ext, other, trace, scope),
})
.collect(),
)],
Operand::Coalesce { left, right } => {
let v = operand_value(host, ext, left, trace, scope);
let fill = |v: &Value| -> Value {
if matches!(v, Value::Null) {
operand_value(host, ext, right, trace, scope)
} else {
v.clone()
}
};
match v {
Value::Null => eval_operand(host, ext, right, trace, scope),
Value::Table(t)
if t.rows()
.flat_map(|r| r.iter())
.any(|c| matches!(c, Value::Null)) =>
{
let rows = t
.rows()
.map(|r| r.iter().map(|v| fill(&v)).collect())
.collect();
vec![match t.rebuild(rows) {
Ok(t) => Value::table(t),
Err(why) => {
crate::pipeline::record_refusal(format!("??: {why}"));
Value::Null
}
}]
}
Value::List(items) if items.iter().any(|c| matches!(c, Value::Null)) => {
vec![Value::list(items.iter().map(fill).collect())]
}
Value::Record(fields) if fields.iter().any(|(_, c)| matches!(c, Value::Null)) => {
vec![Value::Record(
fields.iter().map(|(k, c)| (k.clone(), fill(c))).collect(),
)]
}
other => vec![other],
}
}
Operand::Index { base, rows, cols } => {
let v = operand_value(host, ext, base, trace, scope);
let condition: Option<Result<bool, &PredExpr>> = match rows {
IndexSpec::Cond(e) if cols.is_none() => Some(Err(e)),
IndexSpec::Expr(e) if cols.is_none() => {
let read = operand_value(host, ext, e, trace, scope);
match crate::pipeline::positions_of(&read) {
Some(_) => None,
None => Some(Ok(read.is_truthy())),
}
}
_ => None,
};
if let (IndexSpec::Unit(unit), None) = (rows, cols.as_ref()) {
let Some((_, base, _, _)) =
crate::value::quantity::parse_unit_text(&format!("1 {unit}"))
else {
crate::pipeline::record_refusal(format!("'[<_{unit}>]': '{unit}' is no unit"));
return vec![Value::Null];
};
return vec![match v {
Value::List(items) => Value::list(
items
.iter()
.filter(
|i| matches!(i, Value::Quantity { base: held, .. } if *held == base),
)
.cloned()
.collect(),
),
other => {
crate::pipeline::record_refusal(format!(
"'[<_{unit}>]' keeps the items of a list that measure {base}, and \
this is {}: a column converts under the trait (':col<_{unit}>'), \
a table's rows take a condition ('t[:col > 0]')",
crate::stdlib::kind_of(&other)
));
Value::Null
}
}];
}
if let Some(cond) = condition {
let holds = |topic: &Value| -> bool {
match cond {
Ok(constant) => constant,
Err(e) => {
let mut s = scope;
s.topic = Some(topic);
eval_pred_expr(host, ext, e, trace, s)
}
}
};
return vec![match v {
Value::Table(t) => match cond {
Err(e) => {
crate::pipeline::commands::rows_that_hold(&t, e, host, ext, holds)
.unwrap_or(Value::Null)
}
Ok(constant) => match constant {
true => Value::Table(t),
false => Value::table(t.keep_rows(Vec::new())),
},
},
Value::List(items) => {
Value::list(items.iter().filter(|i| holds(i)).cloned().collect())
}
Value::Record(_) => {
crate::pipeline::record_refusal(
"a record takes no condition in its brackets (it has no rows): index a field by name, '[\"age\"]', or by position".into(),
);
Value::Null
}
other => {
let piped = match cond {
Err(e) => format!(
": a condition on the value itself filters the thread, \
'@| [{}]'",
crate::syntax::unparse::pred_expr(e)
),
Ok(_) => String::new(),
};
crate::pipeline::record_refusal(format!(
"a condition in brackets reads the rows of a table or the items of a list, not {}{piped}",
crate::stdlib::kind_of(&other)
));
Value::Null
}
}];
}
let resolve = |s: &IndexSpec| resolve_index_spec(host, ext, s, trace, scope);
let (rows, cols) = match (resolve(rows), cols.as_ref().map(|c| resolve(c)).transpose())
{
(Ok(r), Ok(c)) => (r, c),
(Err(why), _) | (_, Err(why)) => {
crate::pipeline::record_refusal(why);
return vec![Value::Null];
}
};
match crate::stdlib::index_value(v, &rows, cols.as_ref()) {
Ok(v) => vec![v],
Err(why) => {
crate::pipeline::record_refusal(why);
vec![Value::Null]
}
}
}
Operand::Range { from, to, step } => {
let int = |e: &Operand, what: &str| -> Result<i64, String> {
let v = operand_value(host, ext, e, trace, scope);
match v.numeric_reading() {
Some(Value::Int(n)) => Ok(n),
_ => Err(format!(
"a range's {what} is an integer, not {}",
crate::stdlib::kind_of(&v)
)),
}
};
let bounds = (|| -> Result<Vec<Value>, String> {
let a = int(from, "start")?;
let b = int(to, "end")?;
let s = match step {
Some(s) => int(s, "stride")?,
None => 1,
};
if s == 0 {
return Err("a range's stride is not zero".into());
}
let s = match step {
Some(_) => s,
None if b < a => -1,
None => 1,
};
let count = ((b as i128 - a as i128) / s as i128).max(-1) + 1;
if count > MAX_FORK as i128 {
return Err(format!(
"the range {a}..{b} holds {count} values, past the {MAX_FORK} one expression may fork"
));
}
let mut out = Vec::new();
let mut i = a;
while if s > 0 { i <= b } else { i >= b } {
out.push(Value::Int(i));
i = match i.checked_add(s) {
Some(n) => n,
None => break,
};
}
Ok(out)
})();
match bounds {
Ok(vs) => vs,
Err(why) => {
crate::pipeline::record_refusal(why);
vec![Value::Null]
}
}
}
Operand::RecordArray { header, rows } => {
let cell = |e: &Operand| operand_value(host, ext, e, trace, scope);
match record_array(header, rows, cell) {
Ok(v) => vec![v],
Err(why) => {
crate::pipeline::record_refusal(why);
vec![Value::Null]
}
}
}
Operand::Table {
header,
declared,
rows,
levels,
} => {
let cell = |e: &Operand| match e {
Operand::Lit(v @ Value::Projection { .. }) => v.clone(),
_ => operand_value(host, ext, e, trace, scope),
};
let by_columns = if scope.whole && rows.len() == 1 {
match member_columns(&rows[0], cell) {
Ok(rows) => rows,
Err(why) => {
crate::pipeline::record_refusal(why);
return vec![Value::Null];
}
}
} else {
None
};
let rows = by_columns.as_deref().unwrap_or(rows);
match table_literal(header.clone(), declared, rows, cell) {
Ok(t) => vec![Value::table(t.with_levels(*levels))],
Err(why) => {
crate::pipeline::record_refusal(why);
vec![Value::Null]
}
}
}
Operand::NamedCaptures => {
let record = |named: &[(String, String)]| {
Value::Record(
named
.iter()
.map(|(k, v)| (k.clone(), Value::Str(v.clone())))
.collect(),
)
};
vec![if scope.captures.is_empty() && scope.named.is_empty() {
crate::pipeline::run::enclosing_captures(|c| {
record(c.map_or(&[][..], |(_, named)| named))
})
} else {
record(scope.named)
}]
}
Operand::Ordinal => vec![
scope
.ordinal
.map(|i| Value::Int(i as i64))
.unwrap_or(Value::Null),
],
Operand::StepsTaken => {
let (Some(own), Some(thread)) = (ext.steps_taken(), scope.ext.steps_taken()) else {
crate::pipeline::record_refusal(
"'$STEPS' after an aggregation: the thread stands for many paths and \
has no count of steps of its own"
.to_string(),
);
return vec![Value::Null];
};
let mut n = own.max(thread);
let mut around = scope.outer;
while let Some(s) = around {
if let Some(k) = s.ext.steps_taken() {
n = n.max(k);
}
around = s.outer;
}
vec![Value::Int(n as i64)]
}
Operand::WalkFact { fact, level } => vec![walk_fact(scope, *fact, *level)],
Operand::Cond { cond, then, other } => {
let taken = if discard(|| eval_pred_expr(host, ext, cond, trace, scope)) {
then
} else {
other
};
eval_operand(host, ext, taken, trace, scope)
}
Operand::PeerReg { at, reg } => {
let keys = match at {
Some(at) => discard(|| host.operand_keys(ext, at, trace, scope)),
None => vec![ext.key()],
};
let mut out = Vec::new();
for k in keys {
match reg {
RegRef::Record => {
let all = attached_all(&k);
for r in &all {
note_all(&r.prov.origins);
}
out.push(Value::record(
all.into_iter().map(|r| (r.name, r.value)).collect(),
));
}
RegRef::Named(name) => {
if let Some((v, prov)) = attached(&k, name) {
note_all(&prov.origins);
out.push(v);
}
}
_ => {}
}
}
out
}
Operand::Topics => host.capsae(scope, None),
Operand::Positions { projection } => host.positions(scope, projection.as_ref()),
Operand::Matrix { node, full } => matrix(scope, *node, *full),
Operand::CtxTable => ctx_table(host, scope),
Operand::Piped { expr, commands }
if matches!(**expr, Operand::Topic)
&& let [Command::Func(call)] = commands.as_slice()
&& matches!(call.name.as_str(), "rec" | "record") =>
{
match record_build(&call.args, host, ext, trace, scope) {
Ok((r, _)) => vec![Value::Record(r)],
Err(why) => {
crate::pipeline::record_refusal(why);
vec![Value::Null]
}
}
}
Operand::Piped { expr, commands } => {
let _own_cells = crate::value::ambient::cells_ground();
let _position = scope
.ordinal
.map(|at| crate::pipeline::random_position(at as u64));
let capsa = |x: H::Ext, topic: Option<Value>, prov: Prov| Thread::<H::Ext> {
prov,
register: scope.register.to_vec(),
topic,
members: Vec::new(),
captures: scope.captures.to_vec(),
named: scope.named.to_vec(),
ext: x,
};
let mut caps: Vec<Thread<H::Ext>> = match expr.as_ref() {
Operand::Rel {
steps,
projection,
anchor,
} => crate::pipeline::run::out_of_row_reach(|| {
host.rel_threads(ext, steps, anchor, projection.as_ref(), trace, scope)
})
.into_iter()
.map(|(x, topic, prov)| capsa(x, topic, prov))
.collect(),
Operand::Seed
if scope.members.is_empty()
|| (scope.whole && !reads_each_member(commands.first())) =>
{
let topic = scope
.topic
.cloned()
.or_else(|| with_run(|s| s.enclosing_topic.last().cloned()));
vec![capsa(
host.restate(&scope, ext),
topic,
scope.prov.cloned().unwrap_or_else(|| host.prov_at(ext)),
)]
}
Operand::Topic | Operand::Seed
if !scope.members.is_empty()
&& if scope.whole {
reads_each_member(commands.first())
} else {
matches!(commands.first(), Some(Command::Func(c)) if crate::syntax::registry::takes_of(&c.name))
} =>
{
let topics: Vec<Value> = scope
.members
.iter()
.map(|m| crate::pipeline::effective_topic(m, host))
.collect();
vec![Thread::<H::Ext> {
prov: scope.prov.cloned().unwrap_or_else(|| host.prov_at(ext)),
register: scope.register.to_vec(),
topic: Some(Value::list(topics)),
members: scope.members.to_vec(),
captures: scope.captures.to_vec(),
named: scope.named.to_vec(),
ext: host.restate(&scope, ext),
}]
}
Operand::Topic | Operand::Seed if !scope.members.is_empty() && !scope.whole => {
scope
.members
.iter()
.map(|m| match &m.topic {
Some(t) => capsa(
host.restate(&scope, &m.ext),
Some(t.clone()),
m.prov.clone(),
),
None => capsa(
host.restate(&scope, &m.ext),
Some(crate::pipeline::effective_topic(m, host)),
host.prov_at(&m.ext),
),
})
.collect()
}
_ => {
let (values, o) = capture(|| eval_operand(host, ext, expr, trace, scope));
let prov = Prov::leaf(o);
values
.into_iter()
.map(|v| capsa(host.restate(&scope, ext), Some(v), prov.clone()))
.collect()
}
};
let mut mode = crate::pipeline::commands::start_mode(&caps);
let _own_ground = crate::pipeline::run::fresh_group();
for command in commands.iter() {
crate::pipeline::commands::accepted_spelling(command);
if caps.is_empty() && matches!(command, Command::Func(c) if c.name == "default") {
caps.push(capsa(
host.restate(&scope, ext),
Some(Value::Null),
Prov::default(),
));
}
if matches!(command, Command::Agg(_) | Command::Select(_))
&& caps.len() == 1
&& let Some(Value::List(items)) = &caps[0].topic
{
crate::value::ambient::record_lone_list(
|| crate::syntax::unparse::command(command),
matches!(command, Command::Select(_)),
items,
);
}
let outer_expr = |a: &Arg| {
matches!(a, Arg::Expr(_))
|| matches!(a, Arg::Opt { value: Some(v), .. } if !matches!(v, Operand::Lit(_)))
};
let selecting;
let command = match command {
Command::Func(call)
if call.name == "[]"
&& caps.len() > 1
&& caps.iter().all(|c| {
!matches!(
c.topic,
None | Some(
Value::List(_) | Value::Table(_) | Value::Record(_)
)
)
})
&& let Some(pred) = match call.args.as_slice() {
[Arg::Lit(Value::Int(n))] => {
Some(crate::syntax::ast::Predicate::Index(*n))
}
[Arg::Range(a, b)] => {
Some(crate::syntax::ast::Predicate::Range(*a, *b))
}
_ => None,
} =>
{
selecting = Command::Select(pred);
&selecting
}
other => other,
};
let resolved;
let command = match command {
Command::Func(call)
if stdlib::known_scalar(&call.name)
&& !matches!(call.name.as_str(), "rec" | "record" | "map")
&& call.args.iter().any(|a| {
outer_expr(a) && !stdlib::names_columns(&call.name, a)
}) =>
{
resolved = Command::Func(FnCall {
headless: false,
name: call.name.clone(),
args: call
.args
.iter()
.map(|a| match a {
a if stdlib::names_columns(&call.name, a) => a.clone(),
Arg::Expr(e) => {
Arg::Lit(operand_scalar(host, ext, e, trace, scope))
}
Arg::Opt {
name,
value: Some(e),
} if !matches!(e, Operand::Lit(_)) => Arg::Opt {
name: name.clone(),
value: Some(Operand::Lit(operand_scalar(
host, ext, e, trace, scope,
))),
},
other => other.clone(),
})
.collect(),
});
&resolved
}
other => other,
};
let had_nodes = caps.iter().any(|c| c.topic.is_none());
caps = crate::pipeline::commands::apply_command_in(
command,
mode,
caps,
host,
trace,
Some(&scope),
);
mode = crate::syntax::parser::command_mode_out(command, mode);
if !had_nodes {
for c in &mut caps {
if c.topic.is_none() {
c.topic = Some(Value::Null);
}
}
}
}
for c in &caps {
note_all(&c.prov.origins);
}
caps.into_iter()
.map(|c| c.topic.unwrap_or(Value::Bool(true)))
.collect()
}
Operand::Edges { projection } => host.edges(scope, projection.as_ref()),
Operand::Edge { projection } => host.edge(scope, projection.as_ref()),
Operand::Param(_) => vec![Value::Null],
Operand::Invoking(inner) => match scope.outer {
Some(o) if bare_cursor(inner) => host.node_ref(o.ext).into_iter().collect(),
Some(o) => eval_operand(
host,
if H::Ext::standing(&o.view) {
o.ext
} else {
ext
},
inner,
trace,
*o,
),
None => vec![Value::Null],
},
Operand::Position(inner) if bare_cursor(inner) => host.node_ref(ext).into_iter().collect(),
Operand::Cursor => {
let topic = operand_value(host, ext, &Operand::Topic, trace, scope);
let position = host.node_ref(ext).unwrap_or(Value::Null);
vec![Value::record(vec![
("topic".to_string(), topic),
("position".to_string(), position),
])]
}
Operand::Position(inner) if !host.placed(ext) => Vec::new(),
Operand::Position(inner) => eval_operand(host, ext, inner, trace, scope),
Operand::Driver(inner) => match scope.driver {
Some(d) if bare_cursor(inner) => host.node_ref(d.ext).into_iter().collect(),
Some(d) => eval_operand(
host,
if H::Ext::standing(&d.view) {
d.ext
} else {
ext
},
inner,
trace,
*d,
),
None if bare_cursor(inner) => host.node_ref(ext).into_iter().collect(),
None => eval_operand(host, ext, inner, trace, scope),
},
Operand::Interp(segs) => {
let mut out = String::new();
for seg in segs {
match seg {
InterpSeg::Text(t) => out.push_str(t),
InterpSeg::Expr(e) => {
let vs = eval_operand(host, ext, e, trace, scope);
if vs.len() > 1 {
record_refusal(format!(
"'${{…}}' takes one value, and the expression forks into {}: write \
'${{… @| join(\", \")}}' for one string, or interpolate per thread",
vs.len()
));
return vec![Value::Null];
}
let v = vs.into_iter().next().unwrap_or(Value::Null);
out.push_str(&v.to_string());
}
InterpSeg::Strict(e, msg) => {
let v = operand_scalar(host, ext, e, trace, scope);
if matches!(v, Value::Null) {
record_refusal(match msg {
Some(m) => m.clone(),
None => format!(
"the strict expansion '${{{}:?}}' is null",
crate::syntax::unparse::operand_text(e)
),
});
} else {
out.push_str(&v.to_string());
}
}
InterpSeg::Default(e, f) => {
let v = operand_scalar(host, ext, e, trace, scope);
let v = if matches!(v, Value::Null) {
operand_scalar(host, ext, f, trace, scope)
} else {
v
};
out.push_str(&v.to_string());
}
}
}
vec![Value::Str(out)]
}
Operand::Capture(n) => {
let own = |captures: &[String]| {
captures
.get(n - 1)
.map(|s| Value::Str(s.clone()))
.unwrap_or(Value::Null)
};
vec![if scope.captures.is_empty() && scope.named.is_empty() {
crate::pipeline::run::enclosing_captures(|c| {
own(c.map_or(&[][..], |(numbered, _)| numbered))
})
} else {
own(scope.captures)
}]
}
Operand::Rel {
steps,
projection: Some(projection @ (Projection::Property(_) | Projection::CoreMeta(_))),
anchor: Anchor::Current,
} if steps.is_empty() && scope.topic.is_some_and(|t| matches!(t, Value::Node(_))) => {
let topic = scope.topic.cloned().unwrap_or(Value::Null);
vec![through(host, &topic, projection)]
}
Operand::Rel {
steps,
projection: Some(Projection::AdapterMeta(key)),
anchor: Anchor::Current,
} if steps.is_empty()
&& (matches!(
scope.topic,
Some(Value::Record(_) | Value::Table(_) | Value::Projection { .. })
) || matches!(scope.topic, Some(Value::List(l)) if !l.is_empty() && l.iter().all(|x| matches!(x, Value::Record(_))))) =>
{
let topic = scope.topic.cloned().unwrap_or(Value::Null);
if let Some(prov) = scope.prov {
note_all(&prov.origins);
}
use crate::stdlib as sl;
if let Value::Projection { .. } = &topic {
return vec![match key.as_str() {
"type" => topic
.declared_type()
.map_or(Value::Null, |t| Value::Str(t.word().to_string())),
_ => Value::Null,
}];
}
vec![match key.as_str() {
"fields" => sl::fields_reading(topic).unwrap_or(Value::Null),
"keys" => sl::keys_reading(topic).unwrap_or(Value::Null),
"header" => sl::table_meta(topic, "header").unwrap_or(Value::Null),
"index" => match &topic {
Value::Table(t) => t.labels().map_or(Value::Null, Value::list),
_ => Value::Null,
},
"name" => match &topic {
Value::Table(t) => t.name.clone().map_or(Value::Null, Value::Str),
_ => Value::Null,
},
"type" => sl::type_of(&topic),
"dim" => sl::table_meta(topic, "dim").unwrap_or(Value::Null),
"nrows" | "ncols" => match sl::table_meta(topic, "dim") {
Ok(Value::List(d)) => d
.get(usize::from(key == "ncols"))
.cloned()
.unwrap_or(Value::Null),
_ => Value::Null,
},
_ => Value::Null,
}]
}
Operand::Rel {
steps,
projection: projection @ Some(Projection::Property(Some(name))),
anchor: anchor @ Anchor::Current,
} if steps.is_empty() && crate::pipeline::run::row_column(scope.topic, name) => {
let read = crate::pipeline::run::out_of_row_reach(|| {
host.rel(ext, steps, anchor, projection.as_ref(), trace, scope)
});
if read.iter().all(|v| matches!(v, Value::Null)) {
crate::pipeline::record_refusal(crate::pipeline::run::property_read_on_a_row(name));
}
read
}
Operand::Rel {
steps,
projection,
anchor,
} => crate::pipeline::run::out_of_row_reach(|| {
host.rel(ext, steps, anchor, projection.as_ref(), trace, scope)
}),
Operand::Arith { op, left, right } => {
let scale = |e: &str| host.scale_of(e);
let ls = forking(eval_operand(host, ext, left, trace, scope));
let rs = forking(eval_operand(host, ext, right, trace, scope));
if let Some(refusal) = product_past_bound(ls.len(), rs.len()) {
crate::pipeline::record_refusal(refusal);
return vec![Value::Null];
}
let mut out = Vec::with_capacity(ls.len() * rs.len());
for l in &ls {
let l = retype_shaped_lit(left, l.clone(), &scale);
for r in &rs {
let r = retype_shaped_lit(right, r.clone(), &scale);
out.push(match crate::stdlib::arith::broadcast(*op, &l, &r, &scale) {
Ok(v) => v,
Err(why) => {
crate::pipeline::record_refusal(why);
Value::Null
}
});
}
}
out
}
Operand::Concat { mode, left, right } => {
let row_of = |items: &[(Option<String>, Operand)]| -> Result<Vec<(Option<String>, Value)>, String> {
let mut row: Vec<(Option<String>, Value)> = Vec::with_capacity(items.len());
let mut node_items = false;
for (name, e) in items {
match e {
Operand::Typed { inner, typing } => {
let v = gathered(eval_operand(host, ext, inner, trace, scope));
let key = name.clone().unwrap_or_default();
row.push((name.clone(), cast_reading(v, &key, Some(typing.clone()))));
}
e if name.is_none() && crate::syntax::ast::node_item(e) => {
let exts = node_item_exts(host, ext, e, trace, scope)?;
for (k, v) in node_item_fields(host, &exts) {
row.push((Some(format!("\u{0}{k}")), v));
}
node_items = true;
}
e => row.push((
name.clone(),
gathered(eval_operand(host, ext, e, trace, scope)),
)),
}
}
if node_items && row.iter().any(|(name, _)| name.is_none()) {
return Err(
"a positional item beside a node in the row: the node brings its \
properties as named cells, so an item beside it takes a name too, \
%(node; name = value)"
.to_string(),
);
}
if node_items {
let key = |n: &Option<String>| {
n.as_deref().map(|k| crate::syntax::ast::row_key(k).0.to_string())
};
for (i, (name, _)) in row.iter().enumerate() {
if let Some(k) = key(name)
&& row[..i].iter().any(|(m, _)| key(m).as_deref() == Some(k.as_str()))
{
return Err(format!(
"'{k}' is named twice in the row, and the node brings a property \
of that name: give one of the two another key"
));
}
}
}
Ok(row)
};
if matches!(left.as_ref(), Operand::Cursor | Operand::Topic)
&& let Operand::Row(items) = right.as_ref()
&& let Some(form) = host.node_form(ext)
{
let row = match row_of(items) {
Ok(row) => row,
Err(why) => {
crate::pipeline::record_refusal(format!("{}: {why}", mode.symbol()));
return vec![Value::Null];
}
};
return vec![match form.rewrite(*mode, &row) {
Ok(f) => Value::quarq_form(f),
Err(why) => {
crate::pipeline::record_refusal(format!("{}: {why}", mode.symbol()));
Value::Null
}
}];
}
let ls = forking(eval_operand(host, ext, left, trace, scope));
let rs: Vec<Result<Value, String>> = match right.as_ref() {
Operand::Row(items) => {
let row = match row_of(items) {
Ok(row) => row,
Err(why) => {
crate::pipeline::record_refusal(format!("{}: {why}", mode.symbol()));
return vec![Value::Null];
}
};
ls.iter()
.map(|l| crate::stdlib::concat_row(*mode, l.clone(), row.clone()))
.collect()
}
_ => {
let rs = forking(eval_operand(host, ext, right, trace, scope));
if let Some(refusal) = product_past_bound(ls.len(), rs.len()) {
crate::pipeline::record_refusal(refusal);
return vec![Value::Null];
}
let mut out = Vec::with_capacity(ls.len() * rs.len());
for l in &ls {
for r in &rs {
out.push(crate::stdlib::concat(*mode, l.clone(), r.clone()));
}
}
out
}
};
rs.into_iter()
.map(|out| match out {
Ok(v) => v,
Err(why) => {
crate::pipeline::record_refusal(format!("{}: {why}", mode.symbol()));
Value::Null
}
})
.collect()
}
Operand::Row(_) => vec![Value::Null],
Operand::Typed {
inner,
typing: crate::Typing::Declared(crate::ColumnType::Unit(unit)),
} => under_unit(
inner,
unit,
forking(eval_operand(host, ext, inner, trace, scope)),
),
Operand::InUnit { inner, unit } => under_unit(
inner,
unit,
forking(eval_operand(host, ext, inner, trace, scope)),
),
Operand::InOffset { inner, minutes } => {
forking(eval_operand(host, ext, inner, trace, scope))
.into_iter()
.map(|v| crate::value::offset_reading_at(v, *minutes))
.collect()
}
Operand::Typed {
inner,
typing: crate::Typing::Declared(crate::ColumnType::Offset(minutes)),
} => forking(eval_operand(host, ext, inner, trace, scope))
.into_iter()
.map(|v| crate::value::offset_reading_at(v, *minutes))
.collect(),
Operand::Typed { inner, typing } => {
let spelled = crate::syntax::unparse::operand(operand);
let cast = match typing.declared() {
Some(t) => format!(
"; cast a value with {}({})",
t.word(),
crate::syntax::unparse::operand(inner)
),
None => String::new(),
};
crate::pipeline::record_refusal(format!(
"'{spelled}' declares a field, and stands where a value does: a trait describes a field, never a value{cast}"
));
vec![Value::Null]
}
Operand::Neg(inner) | Operand::Desc(inner) => {
forking(eval_operand(host, ext, inner, trace, scope))
.into_iter()
.map(crate::stdlib::functions::negated)
.collect()
}
Operand::Gathered(inner) => vec![gathered(eval_operand(host, ext, inner, trace, scope))],
Operand::Group(e) => {
if let PredExpr::Compare(l, op, r) = e.as_ref()
&& !matches!(r, Operand::Pattern(_))
{
let lhs = discard(|| eval_operand(host, ext, l, trace, scope));
let rhs = discard(|| eval_operand(host, ext, r, trace, scope));
if lhs.len() == 1
&& rhs.len() == 1
&& (matches!(lhs[0], Value::List(_)) || matches!(rhs[0], Value::List(_)))
{
return vec![match crate::stdlib::compare::compare_value(
&lhs[0],
*op,
&rhs[0],
&|e| host.scale_of(e),
) {
Ok(v) => v,
Err(why) => {
record_refusal(why);
Value::Null
}
}];
}
}
vec![Value::Bool(discard(|| {
eval_pred_expr(host, ext, e, trace, scope)
}))]
}
Operand::Ctx {
index,
steps,
projection,
} => host.ctx(ext, *index, steps, projection.as_ref(), trace, scope),
}
}
pub(crate) fn bare_cursor(inner: &Operand) -> bool {
matches!(
inner,
Operand::Rel {
steps,
projection: None,
anchor: Anchor::Current,
} if steps.is_empty()
)
}
fn under_unit(inner: &Operand, unit: &str, values: Vec<Value>) -> Vec<Value> {
let held = matches!(
inner,
Operand::Recall(_)
| Operand::WalkFact { .. }
| Operand::PeerReg { .. }
| Operand::ValueMeta { .. }
);
values
.into_iter()
.map(|v| match held {
true => crate::value::unit_conversion(&v, unit, &mut |other, listed| {
not_a_quantity(inner, unit, other, listed)
}),
false => crate::value::unit_reading(v, unit),
})
.collect()
}
fn not_a_quantity(inner: &Operand, unit: &str, other: &Value, _listed: bool) {
use crate::syntax::ast::WalkFact;
let counter = match inner {
Operand::WalkFact {
fact: WalkFact::Total | WalkFact::Totals,
..
} => return,
Operand::WalkFact { .. } => true,
_ => false,
};
let held = crate::syntax::unparse::operand(inner);
crate::value::ambient::record_unconverted(
&format!("{held}<_{unit}>"),
unit,
|| {
if counter {
return None;
}
let read = match inner {
Operand::Recall(RegRef::Named(name)) => {
format!("write the unit where the value is pushed ('.{name}(::prop<_{unit}>)')")
}
_ => "write the unit where the value is read".to_string(),
};
Some(format!(
"{read} or apply it to the held value ('{held} | unit({unit})')"
))
},
|| crate::stdlib::functions::shown(other),
);
}
fn forking(values: Vec<Value>) -> Vec<Value> {
if values.is_empty() {
vec![Value::Null]
} else {
values
}
}
fn gathered(mut values: Vec<Value>) -> Value {
if values.len() == 1 {
values.pop().expect("one")
} else {
Value::list(values)
}
}
pub(crate) fn read_projection<H: Host>(
host: &H,
ext: &H::Ext,
ladder: u8,
key: &str,
trace: &H::Trace,
scope: Scope<'_, H::Ext>,
) -> Value {
use crate::syntax::ast::{Anchor, Projection};
let op = match ladder {
1 => Operand::Field {
base: Box::new(Operand::Topic),
name: key.to_string(),
bare: true,
},
_ => Operand::Rel {
steps: Vec::new(),
projection: Some(match ladder {
2 => Projection::Property(Some(key.to_string())),
_ => Projection::AdapterMeta(key.to_string()),
}),
anchor: Anchor::Current,
},
};
group_value(host, ext, &op, trace, scope)
}
pub(crate) fn walk_projections(v: Value, read: &dyn Fn(u8, &str) -> Value) -> Value {
match v {
Value::Projection {
ladder,
key,
typing: Some(crate::Typing::Levels(below)),
} => {
let base = read(ladder, &key);
let under = |l: u8, k: &str| match l {
1 => crate::pipeline::commands::record_field(base.clone(), k),
_ => Value::Null,
};
Value::list(
below
.into_iter()
.map(|x| walk_projections(x, &under))
.collect(),
)
}
Value::Projection {
ladder,
key,
typing,
} => cast_reading(read(ladder, &key), &key, typing),
Value::List(items) => Value::list(
items
.iter()
.cloned()
.map(|x| walk_projections(x, read))
.collect(),
),
Value::Record(fields) => Value::Record(
fields
.into_iter()
.map(|(k, x)| (k, walk_projections(x, read)))
.collect(),
),
Value::Table(t) => {
let rows = t
.rows()
.map(|r| r.iter().map(|x| walk_projections(x, read)).collect())
.collect();
Value::table(t.with_rows(rows))
}
other => other,
}
}
pub(crate) enum LabelSpec {
One(Value),
Many(Vec<Value>),
Range(Value, Value),
}
pub(crate) fn label_lookup(
v: Value,
specs: &[LabelSpec],
scale: crate::stdlib::arith::UnitScale,
) -> Result<Value, String> {
use crate::stdlib::compare::value_cmp;
use std::cmp::Ordering;
let within = |x: &Value, a: &Value, b: &Value| {
matches!(
value_cmp(a, x, scale),
Some(Ordering::Less | Ordering::Equal)
) && matches!(
value_cmp(x, b, scale),
Some(Ordering::Less | Ordering::Equal)
)
};
match v {
Value::Record(r) => {
let find = |k: &Value| r.find_key(k);
let mut hits: Vec<usize> = Vec::new();
for s in specs {
match s {
LabelSpec::One(k) => {
let hit = find(k);
if specs.len() == 1 {
crate::value::ambient::field_read(
&r,
&crate::value::Record::key_text(k),
hit.is_some(),
);
}
if let Some(i) = hit {
hits.push(i);
} else if specs.len() == 1 {
return Ok(Value::Null);
}
}
LabelSpec::Many(ks) => hits.extend(ks.iter().filter_map(find)),
LabelSpec::Range(a, b) => {
hits.extend((0..r.len()).filter(|&i| within(&r.key(i), a, b)));
}
}
}
if let [LabelSpec::One(_)] = specs {
return Ok(hits.first().map(|&i| r[i].1.clone()).unwrap_or(Value::Null));
}
Ok(Value::Record(r.filter_fields(|i, _| hits.contains(&i))))
}
Value::Table(t) if t.index > 1 => {
if let [LabelSpec::Many(many)] = specs {
let rows: Vec<usize> = many.iter().flat_map(|l| t.rows_at_levels(std::slice::from_ref(l))).collect();
return Ok(Value::table(t.take_rows(&rows)));
}
let levels: Vec<Value> = specs
.iter()
.map(|s| match s {
LabelSpec::One(v) => Ok(v.clone()),
LabelSpec::Many(_) => Err("a list of labels stands alone in the double bracket: t[[@(x; y)]]".to_string()),
LabelSpec::Range(_, _) => Err("a range reads one level of a composite index at a time: t[[a..b]] on the outer level alone is not yet a form".to_string()),
})
.collect::<Result<_, _>>()?;
if levels.len() > t.index {
return Err(format!(
"the index has {} levels ({}), and {} labels were given",
t.index,
t.level_names().join(", "),
levels.len()
));
}
let rows = t.rows_at_levels(&levels);
if levels.len() == t.index {
return Ok(if rows.len() == 1 {
t.row(rows[0] + 1).unwrap_or(Value::Null)
} else if rows.is_empty() {
Value::Null
} else {
Value::table(t.take_rows(&rows))
});
}
Ok(Value::table(t.sub_table(&rows, levels.len())))
}
Value::Table(t) => {
if t.index == 0 {
return Err(
"the table has no index to look a label up in: name one with #(-i=:col), or read a row by position, t[n]"
.into(),
);
}
let labels = t.labels().unwrap_or_default();
let ty = t.types().first().cloned();
let cast = |x: &Value| match &ty {
Some(ty) => crate::value::cast_cell(x, ty).unwrap_or_else(|| x.clone()),
None => x.clone(),
};
let tuple_index = matches!(ty, Some(crate::ColumnType::Tuple(_)));
let specs: Vec<LabelSpec> = specs
.iter()
.map(|s| match s {
LabelSpec::Many(ks) if tuple_index => LabelSpec::One(Value::list(ks.clone())),
LabelSpec::One(v) => LabelSpec::One(v.clone()),
LabelSpec::Many(ks) => LabelSpec::Many(ks.clone()),
LabelSpec::Range(a, b) => LabelSpec::Range(a.clone(), b.clone()),
})
.collect();
let specs = specs.as_slice();
let mut rows: Vec<usize> = Vec::new();
for s in specs {
match s {
LabelSpec::One(k) => {
let k = cast(k);
rows.extend(labels.iter().enumerate().filter(|(_, l)| l.same_key(&k)).map(|(i, _)| i));
}
LabelSpec::Many(ks) => {
for k in ks {
let k = cast(k);
rows.extend(labels.iter().enumerate().filter(|(_, l)| l.same_key(&k)).map(|(i, _)| i));
}
}
LabelSpec::Range(a, b) => {
let (a, b) = (cast(a), cast(b));
rows.extend(labels.iter().enumerate().filter(|(_, l)| within(l, &a, &b)).map(|(i, _)| i));
}
}
}
if let [LabelSpec::One(_)] = specs
&& rows.len() <= 1
{
return Ok(rows.first().and_then(|&i| t.row(i + 1)).unwrap_or(Value::Null));
}
Ok(Value::table(t.take_rows(&rows)))
}
Value::List(_) => Err(
"a list is indexed by position, [n]; the double bracket looks a label up on an indexed table, or a key on a record"
.into(),
),
other => Err(format!(
"the double bracket looks a label up on an indexed table or a key on a record, not {}",
crate::stdlib::kind_of(&other)
)),
}
}
pub(crate) fn cast_reading(v: Value, key: &str, typing: Option<crate::Typing>) -> Value {
let Some(ty) = typing.as_ref().and_then(crate::Typing::declared) else {
return v;
};
let cast_one = |c: &Value| crate::value::cast_cell(c, &ty);
match &v {
Value::List(items) => {
let mut out = Vec::with_capacity(items.len());
for (i, c) in items.iter().enumerate() {
match cast_one(c) {
Some(x) => out.push(x),
None => {
crate::pipeline::record_refusal(format!(
"'{key}' is declared {}, and item {} holds {}, which does not cast to it",
ty.word(),
i + 1,
crate::value::held_text(c)
));
return Value::Null;
}
}
}
Value::list(out)
}
Value::Record(_) | Value::Table(_) | Value::Foreign(_) => v,
c => match cast_one(c) {
Some(x) => x,
None => {
crate::pipeline::record_refusal(format!(
"'{key}' is declared {}, and holds {}, which does not cast to it",
ty.word(),
crate::value::held_text(c)
));
Value::Null
}
},
}
}
pub(crate) fn run_quarq<H: Host>(
host: &H,
ext: &H::Ext,
q: &crate::value::Quarq,
trace: &H::Trace,
scope: Scope<'_, H::Ext>,
) -> Value {
let piped = Operand::Piped {
expr: Box::new(Operand::Seed),
commands: (*q.body).clone(),
};
operand_scalar(host, ext, &piped, trace, scope)
}
pub(crate) fn apply_held<H: Host>(
host: &H,
ext: &H::Ext,
v: Value,
trace: &H::Trace,
scope: Scope<'_, H::Ext>,
) -> Value {
match v {
Value::Quarq(q) => run_quarq(host, ext, &q, trace, scope),
v if v.holds_projector() => {
let read =
|ladder: u8, key: &str| read_projection(host, ext, ladder, key, trace, scope);
walk_projections(v, &read)
}
v => v,
}
}
pub(crate) fn resolve_index_spec<H: Host>(
host: &H,
ext: &H::Ext,
spec: &IndexSpec,
trace: &H::Trace,
scope: Scope<'_, H::Ext>,
) -> Result<IndexSpec, String> {
match spec {
IndexSpec::Expr(e) => {
match crate::pipeline::positions_of(&operand_value(host, ext, e, trace, scope)) {
Some(crate::syntax::ast::Predicate::Index(n)) => Ok(IndexSpec::At(n)),
Some(crate::syntax::ast::Predicate::Positions(parts)) => Ok(IndexSpec::List(
parts
.iter()
.map(|p| match p {
crate::syntax::ast::Predicate::Index(n) => IndexSpec::At(*n),
_ => IndexSpec::At(0),
})
.collect(),
)),
_ => Err(
"an index read from an expression is an integer or a list of integers".into(),
),
}
}
other => Ok(other.clone()),
}
}
fn walk_fact<X: Attachment>(
scope: Scope<'_, X>,
fact: crate::syntax::ast::WalkFact,
level: usize,
) -> Value {
use crate::pipeline::run::QFrame;
use crate::syntax::ast::WalkFact;
use crate::thread::WalkLevels;
enum Level<'a, W> {
Push(usize),
Step(usize, usize),
Walk(&'a W, usize),
}
let mut in_scope: Vec<Level<'_, X::Walk>> = Vec::new();
for w in scope.walks() {
for i in (0..w.rounds().len()).rev() {
in_scope.push(Level::Walk(w, i));
}
}
let n = in_scope.len();
let mut in_scope = in_scope.into_iter();
let mut taken = 0usize;
let mut levels: Vec<Level<'_, X::Walk>> = Vec::new();
for frame in crate::pipeline::run::quantifiers() {
let enclosing = match &frame {
QFrame::Push { enclosing, .. } | QFrame::Step { enclosing, .. } => *enclosing,
};
for _ in 0..n.saturating_sub(enclosing).saturating_sub(taken) {
if let Some(l) = in_scope.next() {
levels.push(l);
taken += 1;
}
}
match frame {
QFrame::Push { round, .. } => levels.push(Level::Push(round)),
QFrame::Step { rounds, steps, .. } => {
levels.extend(
rounds
.iter()
.zip(steps.iter())
.rev()
.map(|(r, s)| Level::Step(*r, *s)),
);
}
}
}
levels.extend(in_scope);
let name = fact.spelling(level);
let refuse = |why: String| {
crate::pipeline::record_refusal(why);
Value::Null
};
match levels.get(level.saturating_sub(1)) {
None => refuse(match levels.len() {
0 => format!("'{name}' reads a quantifier around it, and none encloses it here"),
1 => format!(
"'{name}' counts {level} quantifiers outward, and one encloses it here: '{}'",
fact.spelling(1)
),
k => format!(
"'{name}' counts {level} quantifiers outward, and {k} enclose it here: the \
outermost is '{}'",
fact.spelling(k)
),
}),
Some(Level::Push(round)) => match fact {
WalkFact::Iter => Value::Int(*round as i64),
_ => refuse(format!(
"'{name}' reads a walk, and the quantifier it names here is a quantified \
push, which takes no steps: its rounds are '{}'",
WalkFact::Iter.spelling(level)
)),
},
Some(Level::Step(round, steps)) => match fact {
WalkFact::Iter => Value::Int(*round as i64),
WalkFact::Steps => Value::Int(*steps as i64),
_ => refuse(format!(
"'{name}' in a step's own predicate: the weight of the edge being tried is \
not folded yet; test it in the group's guard, after the braces"
)),
},
Some(Level::Walk(w, i)) => match fact {
WalkFact::Iter => Value::Int(w.rounds()[*i] as i64),
WalkFact::Steps => Value::Int(w.steps_at(*i) as i64),
_ if *i + 1 == w.rounds().len() => w.fact(fact),
_ => refuse(format!(
"'{name}' reads a group that holds another quantified group: its weight \
is not kept apart from the inner walk's, which '{}' reads",
fact.spelling(1)
)),
},
}
}
pub(crate) fn operand_scalar<H: Host>(
host: &H,
ext: &H::Ext,
expr: &Operand,
trace: &H::Trace,
scope: Scope<'_, H::Ext>,
) -> Value {
eval_operand(host, ext, expr, trace, scope)
.into_iter()
.next()
.unwrap_or(Value::Null)
}
pub(crate) fn record_fields_prov<H: Host>(
args: &[Arg],
host: &H,
ext: &H::Ext,
trace: &H::Trace,
scope: Scope<'_, H::Ext>,
) -> Result<Vec<(String, Value, Prov)>, String> {
let (record, provs) = record_build(args, host, ext, trace, scope)?;
Ok(record
.into_fields()
.into_iter()
.zip(provs)
.map(|((k, v), p)| (k, v, p))
.collect())
}
fn node_item_exts<H: Host>(
host: &H,
ext: &H::Ext,
e: &Operand,
trace: &H::Trace,
scope: Scope<'_, H::Ext>,
) -> Result<Vec<H::Ext>, String> {
if let Operand::Rel {
steps,
projection: None,
anchor,
} = e
{
return Ok(crate::pipeline::run::out_of_row_reach(|| {
host.rel_threads(ext, steps, anchor, None, trace, scope)
})
.into_iter()
.map(|(x, _, _)| x)
.collect());
}
let mut exts = Vec::new();
for v in eval_operand(host, ext, e, trace, scope)
.iter()
.flat_map(|v| match v {
Value::List(items) => items.to_vec(),
one => vec![one.clone()],
})
{
match v {
Value::Node(n) => exts.push(host.ext_at(crate::NodeId(n.id))),
other => {
return Err(format!(
"a record field needs a name: the item answers {}, which is no node; give \
it a key, %(name = …)",
crate::stdlib::kind_of(&other)
));
}
}
}
Ok(exts)
}
fn node_item_fields<H: Host>(host: &H, exts: &[H::Ext]) -> Vec<(String, Value)> {
let mut names: Vec<String> = Vec::new();
for x in exts {
for n in host.property_names_of(x) {
if !names.contains(&n) {
names.push(n);
}
}
}
names
.into_iter()
.map(|name| {
let read = |x: &H::Ext| host.property_of(x, &name).unwrap_or(Value::Null);
let value = match exts {
[one] => read(one),
many => Value::list(many.iter().map(read).collect()),
};
(name, value)
})
.collect()
}
pub(crate) fn record_build<H: Host>(
args: &[Arg],
host: &H,
ext: &H::Ext,
trace: &H::Trace,
scope: Scope<'_, H::Ext>,
) -> Result<(crate::value::Record, Vec<Prov>), String> {
use crate::value::{ColumnType, Record};
let mut fields: Vec<(String, Value, Prov)> = Vec::new();
let mut keys: Vec<Option<Value>> = Vec::new();
let mut declared: Vec<Option<ColumnType>> = Vec::new();
let mut keys_type: Option<ColumnType> = None;
let mut values_type: Option<ColumnType> = None;
let mut node_items = false;
let taken: Vec<String> = {
let mut v = Vec::new();
let mut it = args.iter().peekable();
while let Some(a) = it.next() {
let produced = match a {
Arg::Lit(Value::Str(name)) => Some(name.clone()),
Arg::Key(k) => Some(Record::key_text(k)),
_ => None,
};
if let Some(name) = produced {
v.push(name);
if let Some(Arg::Expr(Operand::Field {
base, name: old, ..
})) = it.peek()
&& matches!(**base, Operand::Topic)
&& old != "*"
{
v.push(old.clone());
}
continue;
}
match a {
Arg::Expr(Operand::Field { base, name, .. })
if matches!(**base, Operand::Topic) && name != "*" =>
{
v.push(name.clone());
}
Arg::Expr(Operand::Typed { inner, .. }) => {
if let Some(k) = crate::syntax::ast::auto_field_name(inner) {
v.push(k.to_string());
}
}
_ => {}
}
}
v
};
let mut args = args.iter().peekable();
while let Some(arg) = args.next() {
let before = fields.len();
match arg {
Arg::Hole(_) => {}
Arg::Lit(Value::Str(_)) | Arg::Key(_) => {
let (name, key) = match arg {
Arg::Lit(Value::Str(name)) => (name.clone(), None),
Arg::Key(k) => (Record::key_text(k), Some(k.clone())),
_ => unreachable!(),
};
let mut decl = None;
let (value, prov) = match args.next() {
Some(Arg::Expr(Operand::Typed { inner, typing })) => {
let (v, o) = capture(|| operand_value(host, ext, inner, trace, scope));
decl = typing.declared();
(cast_reading(v, &name, Some(typing.clone())), Prov::leaf(o))
}
Some(Arg::Expr(e)) => {
let (v, o) = capture(|| operand_value(host, ext, e, trace, scope));
(v, Prov::leaf(o))
}
Some(Arg::Lit(v)) => (v.clone(), Prov::default()),
Some(Arg::Range(_, _))
| Some(Arg::Key(_))
| Some(Arg::Named { .. })
| Some(Arg::Opt { .. })
| Some(Arg::Pairs { .. })
| Some(Arg::Hole(_))
| None => (Value::Null, Prov::default()),
};
fields.push((name, value, prov));
keys.push(key);
declared.push(decl);
}
Arg::Opt {
name,
value: Some(Operand::Lit(Value::Str(word))),
} if matches!(name.as_str(), "--keys" | "--values") => {
let ty = ColumnType::from_word(word);
if name == "--keys" {
keys_type = ty;
} else {
values_type = ty;
}
}
Arg::Expr(Operand::Spread(inner)) => {
let (v, o) = capture(|| operand_value(host, ext, inner, trace, scope));
let items = match v {
Value::List(items) => items.to_vec(),
one @ Value::Projection { .. } => vec![one],
other => {
return Err(format!(
"the spread takes a list of projections, not {}",
crate::stdlib::kind_of(&other)
));
}
};
for item in items {
let Value::Projection {
ladder,
key,
typing,
} = item
else {
return Err(format!(
"the spread takes projections; {} is none",
item.display_form()
));
};
if let Some(first) = fields.iter().find(|(f, _, _)| *f == key) {
let _ = first;
return Err(format!(
"two projections share the bare key '{key}' ({}); the record keys by it",
Value::projection_spelling(ladder, &key)
));
}
let value = read_projection(host, ext, ladder, &key, trace, scope);
let value = cast_reading(value, &key, typing);
fields.push((key, value, Prov::leaf(o.clone())));
}
}
Arg::Expr(Operand::Typed { inner, typing }) => {
let name = crate::syntax::ast::auto_field_name(inner)
.unwrap_or_default()
.to_string();
let (v, o) = capture(|| operand_value(host, ext, inner, trace, scope));
fields.push((
name.clone(),
cast_reading(v, &name, Some(typing.clone())),
Prov::leaf(o),
));
keys.push(None);
declared.push(typing.declared());
}
Arg::Expr(Operand::Field { base, name, .. })
if matches!(**base, Operand::Topic) && name == "*" =>
{
let Some(Value::Record(r)) = scope.topic else {
return Err(
"':*' stands in a projector over a record (r:%(:*; …)) or a table (t:#(:*; …)): the rest of its fields or columns".into(),
);
};
for (k, v) in r.iter() {
if !taken.iter().any(|t| t == k) {
if fields.iter().any(|(f, _, _)| f == k) {
return Err(format!("'{k}' is already a field of the record"));
}
fields.push((
k.clone(),
v.clone(),
scope.prov.cloned().unwrap_or_default(),
));
}
}
}
Arg::Expr(e)
if crate::syntax::ast::auto_field_name(e).is_none()
&& crate::syntax::ast::node_item(e) =>
{
let (exts, o) = capture(|| node_item_exts(host, ext, e, trace, scope));
for (name, value) in node_item_fields(host, &exts?) {
if fields.iter().any(|(f, _, _)| *f == name) {
return Err(format!(
"'{name}' is already a field of the record, and the node brings a \
property of that name: give one of the two a key"
));
}
fields.push((name, value, Prov::leaf(o.clone())));
}
node_items = true;
}
Arg::Expr(e) => {
let name = crate::syntax::ast::auto_field_name(e)
.unwrap_or_default()
.to_string();
let (v, o) = capture(|| operand_value(host, ext, e, trace, scope));
fields.push((name, v, Prov::leaf(o)));
}
Arg::Lit(v) => fields.push((String::new(), v.clone(), Prov::default())),
Arg::Pairs {
keys: key_list,
values,
} => {
let k = operand_value(host, ext, key_list, trace, scope);
let (v, o) = capture(|| operand_value(host, ext, values, trace, scope));
let names: Vec<String> = match &k {
Value::List(l) => l
.iter()
.map(|n| match n {
Value::Str(s) => s.clone(),
other => other.to_string(),
})
.collect(),
other => {
return Err(format!(
"the pairwise field takes a list of names on the left of '=', not {}",
crate::stdlib::kind_of(other)
));
}
};
let items: Vec<Value> = match &v {
Value::List(l) => l.to_vec(),
other => {
return Err(format!(
"the pairwise field takes a list of values on the right of '=', not {}",
crate::stdlib::kind_of(other)
));
}
};
if names.len() != items.len() {
return Err(format!(
"the pairwise field's names and values differ in number, {} and {}",
names.len(),
items.len()
));
}
let typed_keys: Vec<Option<Value>> = match &k {
Value::List(l) => l
.iter()
.map(|n| (!matches!(n, Value::Str(_))).then(|| n.clone()))
.collect(),
_ => Vec::new(),
};
for ((name, value), key) in names.into_iter().zip(items).zip(typed_keys) {
if fields.iter().any(|(n, _, _)| *n == name) {
return Err(format!("'{name}' is already a field of the record"));
}
fields.push((name, value, Prov::leaf(o.clone())));
keys.push(key);
declared.push(None);
}
}
Arg::Range(_, _) | Arg::Named { .. } | Arg::Opt { .. } => {}
}
let _ = before;
keys.resize(fields.len(), None);
declared.resize(fields.len(), None);
}
if node_items {
for (i, (name, _, _)) in fields.iter().enumerate() {
if fields[..i].iter().any(|(f, _, _)| f == name) {
return Err(format!(
"'{name}' is already a field of the record, and the node brings a property \
of that name: give one of the two a key"
));
}
}
}
if let Some(ty) = keys_type {
for (i, (name, _, _)) in fields.iter().enumerate() {
let k = keys[i].clone().unwrap_or_else(|| Value::Str(name.clone()));
match crate::value::cast_cell(&k, &ty) {
Some(cast) => keys[i] = Some(cast),
None => {
return Err(format!(
"--keys={}: the key {} does not cast to it",
ty.word(),
crate::value::held_text(&k)
));
}
}
}
}
if let Some(ty) = values_type {
for (i, (name, v, _)) in fields.iter_mut().enumerate() {
match crate::value::cast_cell(v, &ty) {
Some(cast) => *v = cast,
None => {
return Err(format!(
"--values={}: field '{name}' holds {}, which does not cast to it",
ty.word(),
crate::value::held_text(v)
));
}
}
declared[i] = Some(ty.clone());
}
}
let provs: Vec<Prov> = fields.iter().map(|(_, _, p)| p.clone()).collect();
let mut record = if keys.iter().any(Option::is_some) {
Record::keyed(
fields
.iter()
.zip(&keys)
.map(|((name, v, _), k)| {
(
k.clone().unwrap_or_else(|| Value::Str(name.clone())),
v.clone(),
)
})
.collect(),
)
} else {
Record::new(fields.into_iter().map(|(k, v, _)| (k, v)).collect())
};
for (i, d) in declared.into_iter().enumerate() {
if d.is_some() {
record.declare(i, d);
}
}
Ok((record, provs))
}
pub(crate) fn extract_captures<H: Host>(
e: &PredExpr,
host: &H,
ext: &H::Ext,
trace: &H::Trace,
scope: Scope<'_, H::Ext>,
) -> Option<Captured> {
match e {
PredExpr::Or(a, b) | PredExpr::And(a, b) => {
let first = extract_captures(a, host, ext, trace, scope);
extract_captures(b, host, ext, trace, scope).or(first)
}
PredExpr::Not(a) => extract_captures(a, host, ext, trace, scope),
PredExpr::Compare(l, CmpOp::Match, r) => {
let pattern = operand_scalar(host, ext, r, trace, scope);
let re = compiled_regex(&pattern.to_string())?;
if re.captures_len() <= 1 {
return None;
}
eval_operand(host, ext, l, trace, scope)
.iter()
.find_map(|v| {
let text = v.to_string();
re.captures(&text).map(|caps| {
let numbered = caps
.iter()
.skip(1)
.map(|g| g.map_or(String::new(), |m| m.as_str().to_string()))
.collect();
let named = re
.capture_names()
.enumerate()
.filter_map(|(i, n)| {
n.map(|n| {
let text = caps
.get(i)
.map_or(String::new(), |m| m.as_str().to_string());
(n.to_string(), text)
})
})
.collect();
(numbered, named)
})
})
}
PredExpr::Compare(..) | PredExpr::Chain(..) | PredExpr::Truthy(_) => None,
}
}
pub(crate) fn eval_pred_expr<H: Host>(
host: &H,
ext: &H::Ext,
e: &PredExpr,
trace: &H::Trace,
scope: Scope<'_, H::Ext>,
) -> bool {
stacker::maybe_grow(512 * 1024, 8 * 1024 * 1024, || {
eval_pred_expr_in(host, ext, e, trace, scope)
})
}
fn eval_pred_expr_in<H: Host>(
host: &H,
ext: &H::Ext,
e: &PredExpr,
trace: &H::Trace,
scope: Scope<'_, H::Ext>,
) -> bool {
match e {
PredExpr::Or(a, b) => {
eval_pred_expr(host, ext, a, trace, scope) || eval_pred_expr(host, ext, b, trace, scope)
}
PredExpr::And(a, b) => {
eval_pred_expr(host, ext, a, trace, scope) && eval_pred_expr(host, ext, b, trace, scope)
}
PredExpr::Not(a) => !eval_pred_expr(host, ext, a, trace, scope),
PredExpr::Compare(l, op, r) => {
if let Operand::Pattern(segs) = r {
let lhs = eval_operand(host, ext, l, trace, scope);
return match op {
CmpOp::Ne => lhs.iter().any(|a| !pattern_test(segs, a)),
_ => lhs.iter().any(|a| pattern_test(segs, a)),
};
}
let lhs = eval_operand(host, ext, l, trace, scope);
let rhs = eval_operand(host, ext, r, trace, scope);
holds(l, &lhs, *op, r, &rhs, &|e| host.scale_of(e))
}
PredExpr::Chain(operands, ops) => {
let values: Vec<Vec<Value>> = operands
.iter()
.map(|o| eval_operand(host, ext, o, trace, scope))
.collect();
ops.iter().enumerate().all(|(i, op)| {
holds(
&operands[i],
&values[i],
*op,
&operands[i + 1],
&values[i + 1],
&|e| host.scale_of(e),
)
})
}
PredExpr::Truthy(Operand::Rel {
steps,
projection,
anchor,
}) if !steps.is_empty() => {
host.rel_exists(ext, steps, anchor, projection.as_ref(), trace, scope)
}
PredExpr::Truthy(o) => {
let read = || eval_operand(host, ext, o, trace, scope);
let values = match o {
Operand::Rel {
projection: Some(Projection::Property(Some(name))),
..
} => {
let values = crate::value::ambient::with_presence(read);
if values.iter().any(|v| !matches!(v, Value::Null)) {
crate::value::ambient::presence_found(name);
}
values
}
_ => read(),
};
values.iter().any(|v| match v {
Value::List(l)
if !l.is_empty()
&& l.iter().all(|x| matches!(x, Value::Bool(_) | Value::Null)) =>
{
l.iter().any(|x| matches!(x, Value::Bool(true)))
}
v => v.is_truthy(),
})
}
}
}
fn is_null_literal(o: &Operand) -> bool {
matches!(o, Operand::Lit(Value::Null))
}
pub(crate) fn eval_join_condition<H: Host>(
host: &H,
ext: &H::Ext,
e: &PredExpr,
trace: &H::Trace,
scope: Scope<'_, H::Ext>,
) -> Option<bool> {
use crate::syntax::parser::operand_is_correlated as keyed;
let known = |o: &Operand| -> Vec<Value> {
eval_operand(host, ext, o, trace, scope)
.into_iter()
.filter(|v| !matches!(v, Value::Null))
.collect()
};
match e {
PredExpr::Or(a, b) => match eval_join_condition(host, ext, a, trace, scope) {
Some(true) => Some(true),
left => match (left, eval_join_condition(host, ext, b, trace, scope)) {
(_, Some(true)) => Some(true),
(Some(false), Some(false)) => Some(false),
_ => None,
},
},
PredExpr::And(a, b) => match eval_join_condition(host, ext, a, trace, scope) {
Some(false) => Some(false),
left => match (left, eval_join_condition(host, ext, b, trace, scope)) {
(_, Some(false)) => Some(false),
(Some(true), Some(true)) => Some(true),
_ => None,
},
},
PredExpr::Not(a) => eval_join_condition(host, ext, a, trace, scope).map(|b| !b),
PredExpr::Truthy(Operand::Group(inner)) => {
eval_join_condition(host, ext, inner, trace, scope)
}
PredExpr::Compare(l, _, r) if is_null_literal(l) || is_null_literal(r) => {
Some(eval_pred_expr(host, ext, e, trace, scope))
}
PredExpr::Compare(l, op, r) if keyed(l) || keyed(r) => {
let lhs = known(l);
if lhs.is_empty() {
return None;
}
if let Operand::Pattern(segs) = r {
return Some(match op {
CmpOp::Ne => lhs.iter().any(|a| !pattern_test(segs, a)),
_ => lhs.iter().any(|a| pattern_test(segs, a)),
});
}
let rhs = known(r);
if rhs.is_empty() {
return None;
}
Some(holds(l, &lhs, *op, r, &rhs, &|e| host.scale_of(e)))
}
PredExpr::Chain(operands, ops) if operands.iter().any(keyed) => {
let values: Vec<Vec<Value>> = operands.iter().map(known).collect();
if values.iter().any(Vec::is_empty) {
return None;
}
Some(ops.iter().enumerate().all(|(i, op)| {
holds(
&operands[i],
&values[i],
*op,
&operands[i + 1],
&values[i + 1],
&|e| host.scale_of(e),
)
}))
}
other => Some(eval_pred_expr(host, ext, other, trace, scope)),
}
}
pub(crate) fn record_array(
header: &[String],
rows: &[Vec<(Option<String>, Operand)>],
mut cell: impl FnMut(&Operand) -> Value,
) -> Result<Value, String> {
let mut names: Vec<String> = header.to_vec();
let mut records: Vec<Vec<(String, Value)>> = Vec::with_capacity(rows.len());
for (i, row) in rows.iter().enumerate() {
let n = i + 1;
let mut fields: Vec<(String, Value)> = Vec::with_capacity(row.len());
let mut next = 0;
for (name, e) in row {
let v = cell(e);
let name = match name {
Some(name) => {
if !names.contains(name) {
names.push(name.clone());
}
name.clone()
}
None => {
if next >= header.len() {
return Err(format!(
"row {n} has more positional values than the header has names ({}); name the rest",
header.len()
));
}
next += 1;
header[next - 1].clone()
}
};
match fields.iter_mut().find(|(k, _)| *k == name) {
Some((_, slot)) => *slot = v,
None => fields.push((name, v)),
}
}
records.push(fields);
}
Ok(Value::list(
records
.into_iter()
.map(|fields| {
Value::Record(
names
.iter()
.map(|k| {
(
k.clone(),
fields
.iter()
.find(|(n, _)| n == k)
.map(|(_, v)| v.clone())
.unwrap_or(Value::Null),
)
})
.collect(),
)
})
.collect(),
))
}
fn member_columns(
row: &crate::syntax::ast::TableRow,
mut cell: impl FnMut(&Operand) -> Value,
) -> Result<Option<Vec<crate::syntax::ast::TableRow>>, String> {
use crate::syntax::ast::TableRow;
let items: Vec<(Option<String>, Value)> = match row {
TableRow::List(items) => items.iter().map(|e| (None, cell(e))).collect(),
TableRow::Record(items) => items.iter().map(|(n, e)| (n.clone(), cell(e))).collect(),
};
let mut height: Option<(usize, usize)> = None;
for (j, (_, v)) in items.iter().enumerate() {
let Value::List(l) = v else { continue };
match height {
None => height = Some((j, l.len())),
Some((first, n)) if n != l.len() => {
return Err(format!(
"#: the columns differ in length: item {} reads {} values, item {} reads \
{}; the items of a table built from a context are its columns",
first + 1,
n,
j + 1,
l.len()
));
}
Some(_) => {}
}
}
let lit = |v: &Value| Operand::Lit(v.clone());
let height = match height {
Some((_, n)) => n,
None => {
return Ok(Some(vec![match row {
TableRow::List(_) => TableRow::List(items.iter().map(|(_, v)| lit(v)).collect()),
TableRow::Record(_) => {
TableRow::Record(items.iter().map(|(n, v)| (n.clone(), lit(v))).collect())
}
}]));
}
};
let at = |v: &Value, i: usize| match v {
Value::List(l) => lit(&l[i]),
one => lit(one),
};
Ok(Some(
(0..height)
.map(|i| match row {
TableRow::List(_) => TableRow::List(items.iter().map(|(_, v)| at(v, i)).collect()),
TableRow::Record(_) => {
TableRow::Record(items.iter().map(|(n, v)| (n.clone(), at(v, i))).collect())
}
})
.collect(),
))
}
pub(crate) fn table_literal(
mut header: Option<Vec<String>>,
declared: &[Option<crate::ColumnType>],
rows: &[crate::syntax::ast::TableRow],
mut cell: impl FnMut(&Operand) -> Value,
) -> Result<crate::Table, String> {
use crate::syntax::ast::TableRow;
let mut out: Vec<Vec<Value>> = Vec::with_capacity(rows.len());
let mut width: Option<usize> = header.as_ref().map(Vec::len);
for (i, row) in rows.iter().enumerate() {
let n = i + 1;
let unmarked: Vec<(Option<String>, Operand)>;
let row = match row {
TableRow::Record(items)
if items
.iter()
.any(|(n, _)| n.as_deref().is_some_and(|n| n.starts_with('\u{0}'))) =>
{
unmarked = items
.iter()
.map(|(n, e)| {
(
n.as_deref()
.map(|n| crate::syntax::ast::row_key(n).0.to_string()),
e.clone(),
)
})
.collect();
&TableRow::Record(unmarked)
}
other => other,
};
let mut values: Vec<Value> = match row {
TableRow::List(items) => items.iter().map(&mut cell).collect(),
TableRow::Record(items) => {
if header.is_none()
&& out.is_empty()
&& items.iter().any(|(name, _)| name.is_some())
{
let names: Vec<String> = items
.iter()
.enumerate()
.map(|(j, (name, _))| {
name.clone().ok_or_else(|| {
format!("row {n}: item {} has no name while the others name their columns", j + 1)
})
})
.collect::<Result<_, _>>()?;
width = Some(names.len());
header = Some(names);
}
let Some(h) = header.as_ref() else {
if let Some((name, _)) = items.iter().find(|(name, _)| name.is_some()) {
return Err(format!(
"row {n}: '{}' names no column of an array (its columns are positions); write the header first",
name.as_deref().unwrap_or("")
));
}
let values: Vec<Value> = items.iter().map(|(_, e)| cell(e)).collect();
let w = *width.get_or_insert(values.len());
if values.len() > w {
return Err(format!(
"row {n} has {} values, the table {w} columns",
values.len()
));
}
let mut values = values;
values.resize(w, Value::Null);
out.push(values);
continue;
};
let mut values = vec![Value::Null; h.len()];
let mut taken = vec![false; h.len()];
let mut next = 0;
for (name, e) in items {
let v = cell(e);
match name {
Some(name) => match h.iter().position(|c| c == name) {
Some(p) => {
values[p] = v;
taken[p] = true;
}
None => {
return Err(format!(
"row {n}: '{name}' is not a column of the table (the header: {})",
h.join(", ")
));
}
},
None => {
while next < h.len() && taken[next] {
next += 1;
}
if next >= h.len() {
return Err(format!(
"row {n} has {} values, the header {} columns",
items.len(),
h.len()
));
}
values[next] = v;
taken[next] = true;
next += 1;
}
}
}
values
}
};
let w = *width.get_or_insert(values.len());
if values.len() > w {
return Err(format!(
"row {n} has {} values, the table {w} columns",
values.len()
));
}
values.resize(w, Value::Null);
if let Some((j, v)) = values.iter().enumerate().find(|(_, v)| !flat_cell(v)) {
return Err(format!(
"row {n}, column {}: a table is flat, its cell a scalar or null, not {}",
j + 1,
crate::stdlib::kind_of(v)
));
}
out.push(values);
}
Ok(crate::Table::typed(header, out, declared.to_vec())?)
}
pub(crate) fn operand_value<H: Host>(
host: &H,
ext: &H::Ext,
expr: &Operand,
trace: &H::Trace,
scope: Scope<'_, H::Ext>,
) -> Value {
let values = eval_operand(host, ext, expr, trace, scope);
match values.len() {
0 => Value::Null,
1 => values.into_iter().next().unwrap(),
_ => Value::list(values),
}
}
fn reads_each_member(first: Option<&Command>) -> bool {
matches!(first, Some(Command::Func(c) | Command::Agg(c))
if (crate::syntax::registry::takes_of(&c.name) && c.of_expr().is_some())
|| crate::stdlib::known_keyed(&c.name)
|| crate::stdlib::association(&c.name))
}
pub(crate) fn group_value<H: Host>(
host: &H,
ext: &H::Ext,
expr: &Operand,
trace: &H::Trace,
scope: Scope<'_, H::Ext>,
) -> Value {
if scope.members.is_empty() {
return operand_scalar(host, ext, expr, trace, scope);
}
let values = eval_operand(host, ext, expr, trace, scope);
match values.len() {
0 => Value::Null,
1 => values.into_iter().next().unwrap(),
_ => Value::list(values),
}
}
fn holds(
l: &Operand,
lhs: &[Value],
op: CmpOp,
r: &Operand,
rhs: &[Value],
scale: crate::stdlib::arith::UnitScale,
) -> bool {
let spread = |o: &Operand, vs: &[Value]| -> Vec<Value> {
if matches!(o, Operand::Range { .. }) {
vec![Value::list(vs.to_vec())]
} else {
vs.to_vec()
}
};
match op {
CmpOp::Within => {
let rs = spread(r, rhs);
lhs.iter()
.any(|a| rs.iter().any(|b| compare(a, op, b, scale)))
}
CmpOp::Encloses => {
let ls = spread(l, lhs);
ls.iter()
.any(|a| rhs.iter().any(|b| compare(a, op, b, scale)))
}
CmpOp::NotWithin => !holds(l, lhs, CmpOp::Within, r, rhs, scale),
CmpOp::NotEncloses => !holds(l, lhs, CmpOp::Encloses, r, rhs, scale),
_ => lhs
.iter()
.any(|a| rhs.iter().any(|b| compare(a, op, b, scale))),
}
}
pub(crate) fn ctx_table<H: Host>(host: &H, scope: Scope<'_, H::Ext>) -> Vec<Value> {
if scope.peers.is_none() {
return vec![Value::Null];
}
let items = |vs: Vec<Value>| match vs.into_iter().next() {
Some(v @ Value::List(_)) => v.into_items().unwrap_or_default(),
_ => Vec::new(),
};
let topics = items(host.capsae(scope, None));
let positions = items(host.positions(scope, None));
let rows: Vec<Vec<Value>> = topics
.into_iter()
.zip(positions)
.map(|(t, p)| vec![t, p])
.collect();
vec![Value::table(crate::value::Table::new(
Some(vec!["topic".to_string(), "position".to_string()]),
rows,
))]
}
pub(crate) fn matrix<X: crate::thread::Attachment>(
scope: Scope<'_, X>,
node: bool,
full: bool,
) -> Vec<Value> {
let Some(peers) = scope.peers else {
return vec![Value::Null];
};
let part = match (node, full) {
(false, false) => RegRef::Record,
(false, true) => RegRef::FullRecord,
(true, false) => RegRef::NodeRecord,
(true, true) => RegRef::NodeFullRecord,
};
let spelled = match (node, full) {
(false, false) => "#.",
(false, true) => "#.*",
(true, false) => "##.",
(true, true) => "##.*",
};
let mut header: Vec<String> = Vec::new();
let mut records: Vec<Vec<(String, Value)>> = Vec::new();
for p in &peers.caps {
let fields = match recall(&p.register, &part) {
Value::Record(f) => f,
_ => Vec::new().into(),
};
for (k, _) in &fields {
if !header.iter().any(|h| h == k) {
header.push(k.clone());
}
}
records.push(fields.to_vec());
}
let mut rows = Vec::with_capacity(records.len());
for fields in records {
let mut row = Vec::with_capacity(header.len());
for h in &header {
let v = fields
.iter()
.find(|(k, _)| k == h)
.map(|(_, v)| v.clone())
.unwrap_or(Value::Null);
if matches!(
v,
Value::List(_) | Value::Record(_) | Value::Table(_) | Value::Foreign(_)
) {
record_refusal(format!(
"'{spelled}' holds {} under '{h}': a table cell is flat (read the regula with '$.{h}' instead)",
crate::stdlib::kind_of(&v)
));
return vec![Value::Null];
}
row.push(v);
}
rows.push(row);
}
vec![Value::table(crate::value::Table::new(Some(header), rows))]
}
pub(crate) fn through<H: Host>(host: &H, v: &Value, projection: &Projection) -> Value {
match v {
Value::Node(n) => host.project(&host.ext_at(crate::NodeId(n.id)), projection),
Value::List(items) => {
Value::list(items.iter().map(|x| through(host, x, projection)).collect())
}
Value::Quarq(q) => match projection {
Projection::CoreMeta(key) => q.core_field(key).unwrap_or(Value::Null),
_ => Value::Null,
},
_ => Value::Null,
}
}