feat(stdlib): Mid M5 list algorithms and cli.parse
Thicken table with sort/unique/chunk/zip/flatten and add lib/cli flag parsing, with golds and public demos. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
506de65dae
commit
7d86ed1d9c
20 files changed
+608
-14
No files matched your search
+122
@@ -0,0 +1,122 @@
|
||||
//! CLI arg parsing for Mid M5 (`lib/cli`).
|
||||
|
||||
use crate::host::HostContext;
|
||||
use crate::value::Value;
|
||||
|
||||
fn as_text_list(v: &Value) -> Result<Vec<String>, String> {
|
||||
match v {
|
||||
Value::List(xs) => {
|
||||
let mut out = Vec::new();
|
||||
for x in xs {
|
||||
match x {
|
||||
Value::Text(s) => out.push(s.clone()),
|
||||
_ => return Err("cli.parse: args must be list of text".into()),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
Value::None => Ok(vec![]),
|
||||
_ => Err("cli.parse: args needs list".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse `--key value` / `--key=value` / `--flag` / positionals into a map.
|
||||
/// Positionals are stored under key `_` as a list.
|
||||
pub fn parse(ctx: &HostContext, args: Option<&Value>) -> Result<Value, String> {
|
||||
let argv = match args {
|
||||
None | Some(Value::None) => ctx.argv.clone(),
|
||||
Some(v) => as_text_list(v)?,
|
||||
};
|
||||
let mut map: Vec<(String, Value)> = Vec::new();
|
||||
let mut positionals: Vec<Value> = Vec::new();
|
||||
let mut i = 0usize;
|
||||
while i < argv.len() {
|
||||
let a = &argv[i];
|
||||
if let Some(rest) = a.strip_prefix("--") {
|
||||
if rest.is_empty() {
|
||||
// bare `--` — remaining are positionals
|
||||
i += 1;
|
||||
while i < argv.len() {
|
||||
positionals.push(Value::Text(argv[i].clone()));
|
||||
i += 1;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if let Some((k, v)) = rest.split_once('=') {
|
||||
upsert(&mut map, k.to_string(), Value::Text(v.to_string()));
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let key = rest.to_string();
|
||||
if i + 1 < argv.len() && !argv[i + 1].starts_with('-') {
|
||||
upsert(&mut map, key, Value::Text(argv[i + 1].clone()));
|
||||
i += 2;
|
||||
} else {
|
||||
upsert(&mut map, key, Value::Bool(true));
|
||||
i += 1;
|
||||
}
|
||||
} else if let Some(rest) = a.strip_prefix('-') {
|
||||
// short flags: -abc → a/b/c True; -k val not special-cased beyond single letter groups
|
||||
if rest.is_empty() {
|
||||
positionals.push(Value::Text(a.clone()));
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if rest.len() == 1 && i + 1 < argv.len() && !argv[i + 1].starts_with('-') {
|
||||
upsert(&mut map, rest.to_string(), Value::Text(argv[i + 1].clone()));
|
||||
i += 2;
|
||||
} else {
|
||||
for ch in rest.chars() {
|
||||
upsert(&mut map, ch.to_string(), Value::Bool(true));
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
} else {
|
||||
positionals.push(Value::Text(a.clone()));
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
if !positionals.is_empty() {
|
||||
upsert(&mut map, "_".into(), Value::List(positionals));
|
||||
}
|
||||
Ok(Value::Map(map))
|
||||
}
|
||||
|
||||
fn upsert(map: &mut Vec<(String, Value)>, key: String, value: Value) {
|
||||
if let Some((_, slot)) = map.iter_mut().find(|(k, _)| *k == key) {
|
||||
*slot = value;
|
||||
} else {
|
||||
map.push((key, value));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_flags() {
|
||||
let ctx = HostContext::default();
|
||||
let args = Value::List(vec![
|
||||
Value::Text("--input".into()),
|
||||
Value::Text("a.csv".into()),
|
||||
Value::Text("x".into()),
|
||||
Value::Text("--verbose".into()),
|
||||
]);
|
||||
let m = parse(&ctx, Some(&args)).unwrap();
|
||||
match m {
|
||||
Value::Map(entries) => {
|
||||
assert!(entries
|
||||
.iter()
|
||||
.any(|(k, v)| k == "input" && *v == Value::Text("a.csv".into())));
|
||||
assert!(entries
|
||||
.iter()
|
||||
.any(|(k, v)| k == "verbose" && *v == Value::Bool(true)));
|
||||
assert!(entries
|
||||
.iter()
|
||||
.any(|(k, v)| k == "_" && matches!(v, Value::List(_))));
|
||||
}
|
||||
_ => panic!("map"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -385,6 +385,136 @@ pub fn list_last(list: &Value) -> Result<Value, String> {
|
||||
}
|
||||
}
|
||||
|
||||
fn cmp_value(a: &Value, b: &Value) -> std::cmp::Ordering {
|
||||
use std::cmp::Ordering;
|
||||
match (a, b) {
|
||||
(Value::Int(x), Value::Int(y)) => x.cmp(y),
|
||||
(Value::Num(x), Value::Num(y)) => x.partial_cmp(y).unwrap_or(Ordering::Equal),
|
||||
(Value::Int(x), Value::Num(y)) => (*x as f64).partial_cmp(y).unwrap_or(Ordering::Equal),
|
||||
(Value::Num(x), Value::Int(y)) => x.partial_cmp(&(*y as f64)).unwrap_or(Ordering::Equal),
|
||||
(Value::Text(x), Value::Text(y)) => x.cmp(y),
|
||||
(Value::Bool(x), Value::Bool(y)) => x.cmp(y),
|
||||
_ => a.as_display().cmp(&b.as_display()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_sort(list: &Value) -> Result<Value, String> {
|
||||
match list {
|
||||
Value::List(xs) => {
|
||||
let mut out = xs.clone();
|
||||
out.sort_by(cmp_value);
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
Value::None => Ok(Value::List(vec![])),
|
||||
_ => Err("list_sort needs list".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_sort_by(list: &Value, key: &Value) -> Result<Value, String> {
|
||||
let key = match key {
|
||||
Value::Text(s) => s.as_str(),
|
||||
_ => return Err("sort_by key needs text".into()),
|
||||
};
|
||||
match list {
|
||||
Value::List(xs) => {
|
||||
let mut out = xs.clone();
|
||||
out.sort_by(|a, b| {
|
||||
let ka = match a {
|
||||
Value::Map(m) => m
|
||||
.iter()
|
||||
.find(|(k, _)| k == key)
|
||||
.map(|(_, v)| v)
|
||||
.unwrap_or(&Value::None),
|
||||
_ => &Value::None,
|
||||
};
|
||||
let kb = match b {
|
||||
Value::Map(m) => m
|
||||
.iter()
|
||||
.find(|(k, _)| k == key)
|
||||
.map(|(_, v)| v)
|
||||
.unwrap_or(&Value::None),
|
||||
_ => &Value::None,
|
||||
};
|
||||
cmp_value(ka, kb)
|
||||
});
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
Value::None => Ok(Value::List(vec![])),
|
||||
_ => Err("list_sort_by needs list".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_unique(list: &Value) -> Result<Value, String> {
|
||||
match list {
|
||||
Value::List(xs) => {
|
||||
let mut out = Vec::new();
|
||||
for x in xs {
|
||||
if !out.iter().any(|y| y == x) {
|
||||
out.push(x.clone());
|
||||
}
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
Value::None => Ok(Value::List(vec![])),
|
||||
_ => Err("list_unique needs list".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_chunk(list: &Value, size: &Value) -> Result<Value, String> {
|
||||
let n = match size {
|
||||
Value::Int(i) if *i > 0 => *i as usize,
|
||||
Value::Int(_) => return Err("chunk size must be positive".into()),
|
||||
_ => return Err("chunk size needs int".into()),
|
||||
};
|
||||
match list {
|
||||
Value::List(xs) => {
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < xs.len() {
|
||||
let end = (i + n).min(xs.len());
|
||||
out.push(Value::List(xs[i..end].to_vec()));
|
||||
i = end;
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
Value::None => Ok(Value::List(vec![])),
|
||||
_ => Err("list_chunk needs list".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_zip(a: &Value, b: &Value) -> Result<Value, String> {
|
||||
let (aa, bb) = match (a, b) {
|
||||
(Value::List(x), Value::List(y)) => (x, y),
|
||||
(Value::None, Value::List(y)) => (&Vec::new(), y),
|
||||
(Value::List(x), Value::None) => (x, &Vec::new()),
|
||||
(Value::None, Value::None) => return Ok(Value::List(vec![])),
|
||||
_ => return Err("list_zip needs two lists".into()),
|
||||
};
|
||||
let n = aa.len().min(bb.len());
|
||||
let mut out = Vec::with_capacity(n);
|
||||
for i in 0..n {
|
||||
out.push(Value::List(vec![aa[i].clone(), bb[i].clone()]));
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
|
||||
pub fn list_flatten(list: &Value) -> Result<Value, String> {
|
||||
match list {
|
||||
Value::List(xs) => {
|
||||
let mut out = Vec::new();
|
||||
for x in xs {
|
||||
match x {
|
||||
Value::List(inner) => out.extend(inner.iter().cloned()),
|
||||
other => out.push(other.clone()),
|
||||
}
|
||||
}
|
||||
Ok(Value::List(out))
|
||||
}
|
||||
Value::None => Ok(Value::List(vec![])),
|
||||
_ => Err("list_flatten needs list".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn collection_clear(value: &Value) -> Result<Value, String> {
|
||||
match value {
|
||||
Value::List(_) | Value::None => Ok(Value::List(vec![])),
|
||||
|
||||
+49
-2
@@ -3,8 +3,8 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::host::{
|
||||
csv, encoding, fs, hash, json, math, net, path, re, secrets, sys, text_ops, time, writeback,
|
||||
HostContext,
|
||||
cli, csv, encoding, fs, hash, json, math, net, path, re, secrets, sys, text_ops, time,
|
||||
writeback, HostContext,
|
||||
};
|
||||
#[cfg(feature = "exec-host")]
|
||||
use crate::host::{foreign, subtask};
|
||||
@@ -166,6 +166,13 @@ pub enum HostFn {
|
||||
TextPad = 157,
|
||||
CsvParse = 158,
|
||||
CsvStringify = 159,
|
||||
ListSort = 160,
|
||||
ListSortBy = 161,
|
||||
ListUnique = 162,
|
||||
ListChunk = 163,
|
||||
ListZip = 164,
|
||||
ListFlatten = 165,
|
||||
CliParse = 166,
|
||||
}
|
||||
|
||||
|
||||
@@ -322,6 +329,13 @@ impl HostFn {
|
||||
157 => Self::TextPad,
|
||||
158 => Self::CsvParse,
|
||||
159 => Self::CsvStringify,
|
||||
160 => Self::ListSort,
|
||||
161 => Self::ListSortBy,
|
||||
162 => Self::ListUnique,
|
||||
163 => Self::ListChunk,
|
||||
164 => Self::ListZip,
|
||||
165 => Self::ListFlatten,
|
||||
166 => Self::CliParse,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -481,6 +495,13 @@ impl HostFn {
|
||||
"host_text_pad" | "text_pad" => Self::TextPad,
|
||||
"host_csv_parse" | "csv_parse" => Self::CsvParse,
|
||||
"host_csv_stringify" | "csv_stringify" => Self::CsvStringify,
|
||||
"host_list_sort" | "list_sort" => Self::ListSort,
|
||||
"host_list_sort_by" | "list_sort_by" => Self::ListSortBy,
|
||||
"host_list_unique" | "list_unique" => Self::ListUnique,
|
||||
"host_list_chunk" | "list_chunk" => Self::ListChunk,
|
||||
"host_list_zip" | "list_zip" => Self::ListZip,
|
||||
"host_list_flatten" | "list_flatten" => Self::ListFlatten,
|
||||
"host_cli_parse" | "cli_parse" => Self::CliParse,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -627,6 +648,13 @@ impl HostFn {
|
||||
Self::TextPad => "host_text_pad",
|
||||
Self::CsvParse => "host_csv_parse",
|
||||
Self::CsvStringify => "host_csv_stringify",
|
||||
Self::ListSort => "host_list_sort",
|
||||
Self::ListSortBy => "host_list_sort_by",
|
||||
Self::ListUnique => "host_list_unique",
|
||||
Self::ListChunk => "host_list_chunk",
|
||||
Self::ListZip => "host_list_zip",
|
||||
Self::ListFlatten => "host_list_flatten",
|
||||
Self::CliParse => "host_cli_parse",
|
||||
Self::WritebackRecord => "host_writeback_record",
|
||||
Self::WritebackGet => "host_writeback_get",
|
||||
Self::WritebackClear => "host_writeback_clear",
|
||||
@@ -741,6 +769,11 @@ impl HostFn {
|
||||
Self::TextPad => &["text", "width"],
|
||||
Self::CsvParse => &["text"],
|
||||
Self::CsvStringify => &["rows"],
|
||||
Self::ListSort | Self::ListUnique | Self::ListFlatten => &["list"],
|
||||
Self::ListSortBy => &["list", "key"],
|
||||
Self::ListChunk => &["list", "size"],
|
||||
Self::ListZip => &["a", "b"],
|
||||
Self::CliParse => &[],
|
||||
Self::WritebackRecord => &["value"],
|
||||
Self::WritebackGet | Self::WritebackClear => &[],
|
||||
Self::WritebackList => &[],
|
||||
@@ -778,6 +811,7 @@ impl HostFn {
|
||||
Self::SecretsTokenHex | Self::SecretsTokenUrlsafe => &["n"],
|
||||
Self::TextReplace => &["count"],
|
||||
Self::TextPad => &["fill", "align"],
|
||||
Self::CliParse => &["args"],
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
@@ -1207,6 +1241,19 @@ pub fn call_host(
|
||||
),
|
||||
HostFn::CsvParse => csv::parse(require(bound, "text")?),
|
||||
HostFn::CsvStringify => csv::stringify(require(bound, "rows")?),
|
||||
HostFn::ListSort => super::collection::list_sort(require(bound, "list")?),
|
||||
HostFn::ListSortBy => {
|
||||
super::collection::list_sort_by(require(bound, "list")?, require(bound, "key")?)
|
||||
}
|
||||
HostFn::ListUnique => super::collection::list_unique(require(bound, "list")?),
|
||||
HostFn::ListChunk => {
|
||||
super::collection::list_chunk(require(bound, "list")?, require(bound, "size")?)
|
||||
}
|
||||
HostFn::ListZip => {
|
||||
super::collection::list_zip(require(bound, "a")?, require(bound, "b")?)
|
||||
}
|
||||
HostFn::ListFlatten => super::collection::list_flatten(require(bound, "list")?),
|
||||
HostFn::CliParse => cli::parse(ctx, bound.get("args")),
|
||||
HostFn::OuterCallLine => Ok(Value::Int(
|
||||
ctx.call_site_lines
|
||||
.first()
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
pub mod agent_rt;
|
||||
pub mod collection;
|
||||
mod dispatch;
|
||||
mod cli;
|
||||
mod csv;
|
||||
mod encoding;
|
||||
pub mod event_bus;
|
||||
|
||||
Reference in new issue
Block a user