feat: add List.findIndex, List.zip, List.flatten, List.contains
Add missing List operations requested by ergon game engine project: - findIndex(list, predicate) -> Option<Int> - zip(list1, list2) -> List<(A, B)> - flatten(listOfLists) -> List<A> - contains(list, element) -> Bool Resolves ergon porting blocker #4. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -4942,6 +4942,108 @@ impl CBackend {
|
|||||||
self.register_rc_var(&result_var, "LuxList*");
|
self.register_rc_var(&result_var, "LuxList*");
|
||||||
Ok(result_var)
|
Ok(result_var)
|
||||||
}
|
}
|
||||||
|
"findIndex" => {
|
||||||
|
if args.len() != 2 {
|
||||||
|
return Err(CGenError { message: "List.findIndex takes 2 arguments".to_string(), span: None });
|
||||||
|
}
|
||||||
|
let elem_type = self.infer_callback_param_type(&args[1], 0);
|
||||||
|
let elem_is_prim = Self::is_primitive_c_type(&elem_type);
|
||||||
|
|
||||||
|
let list = self.emit_expr(&args[0])?;
|
||||||
|
let closure = self.emit_expr(&args[1])?;
|
||||||
|
let id = self.fresh_name();
|
||||||
|
let result_var = format!("_findidx_{}", id);
|
||||||
|
let i_var = format!("_i_{}", id);
|
||||||
|
let elem_var = format!("_elem_{}", id);
|
||||||
|
let fn_var = format!("_fn_{}", id);
|
||||||
|
let matches_var = format!("_matches_{}", id);
|
||||||
|
|
||||||
|
let arg_pass = if elem_is_prim {
|
||||||
|
format!("{}({})", Self::unbox_fn_for_type(&elem_type), elem_var)
|
||||||
|
} else {
|
||||||
|
elem_var.clone()
|
||||||
|
};
|
||||||
|
let fn_cast = if elem_is_prim {
|
||||||
|
format!("(LuxBool(*)(void*, {}))", elem_type)
|
||||||
|
} else {
|
||||||
|
"(LuxBool(*)(void*, void*))".to_string()
|
||||||
|
};
|
||||||
|
|
||||||
|
self.writeln(&format!("Option {} = lux_option_none();", result_var));
|
||||||
|
self.writeln(&format!("for (int64_t {} = 0; {} < {}->length; {}++) {{", i_var, i_var, list, i_var));
|
||||||
|
self.indent += 1;
|
||||||
|
self.writeln(&format!("void* {} = {}->elements[{}];", elem_var, list, i_var));
|
||||||
|
self.writeln(&format!("LuxClosure* {} = (LuxClosure*){};", fn_var, closure));
|
||||||
|
self.writeln(&format!("LuxBool {} = ({}{}->fn_ptr)({}->env, {});", matches_var, fn_cast, fn_var, fn_var, arg_pass));
|
||||||
|
self.writeln(&format!("if ({}) {{", matches_var));
|
||||||
|
self.indent += 1;
|
||||||
|
self.writeln(&format!("{} = lux_option_some((void*)(intptr_t){});", result_var, i_var));
|
||||||
|
self.writeln("break;");
|
||||||
|
self.indent -= 1;
|
||||||
|
self.writeln("}");
|
||||||
|
self.indent -= 1;
|
||||||
|
self.writeln("}");
|
||||||
|
if closure.starts_with("_closure_") || closure.starts_with("_fn_ref_") {
|
||||||
|
self.writeln(&format!("lux_decref_closure({});", closure));
|
||||||
|
}
|
||||||
|
Ok(result_var)
|
||||||
|
}
|
||||||
|
|
||||||
|
"zip" => {
|
||||||
|
if args.len() != 2 {
|
||||||
|
return Err(CGenError { message: "List.zip takes 2 arguments".to_string(), span: None });
|
||||||
|
}
|
||||||
|
let list1 = self.emit_expr(&args[0])?;
|
||||||
|
let list2 = self.emit_expr(&args[1])?;
|
||||||
|
let id = self.fresh_name();
|
||||||
|
let result_var = format!("_zip_{}", id);
|
||||||
|
let len_var = format!("_ziplen_{}", id);
|
||||||
|
let i_var = format!("_i_{}", id);
|
||||||
|
|
||||||
|
self.writeln(&format!("int64_t {} = {}->length < {}->length ? {}->length : {}->length;", len_var, list1, list2, list1, list2));
|
||||||
|
self.writeln(&format!("LuxList* {} = lux_list_new({});", result_var, len_var));
|
||||||
|
self.writeln(&format!("for (int64_t {} = 0; {} < {}; {}++) {{", i_var, i_var, len_var, i_var));
|
||||||
|
self.indent += 1;
|
||||||
|
self.writeln(&format!("LuxTuple* _tup = (LuxTuple*)lux_rc_alloc(sizeof(LuxTuple) + 2 * sizeof(void*), LUX_TAG_TUPLE);"));
|
||||||
|
self.writeln("_tup->length = 2;");
|
||||||
|
self.writeln(&format!("_tup->elements[0] = {}->elements[{}];", list1, i_var));
|
||||||
|
self.writeln(&format!("_tup->elements[1] = {}->elements[{}];", list2, i_var));
|
||||||
|
self.writeln(&format!("lux_incref({}->elements[{}]);", list1, i_var));
|
||||||
|
self.writeln(&format!("lux_incref({}->elements[{}]);", list2, i_var));
|
||||||
|
self.writeln(&format!("lux_list_push({}, (void*)_tup);", result_var));
|
||||||
|
self.indent -= 1;
|
||||||
|
self.writeln("}");
|
||||||
|
self.register_rc_var(&result_var, "LuxList*");
|
||||||
|
Ok(result_var)
|
||||||
|
}
|
||||||
|
|
||||||
|
"flatten" => {
|
||||||
|
if args.len() != 1 {
|
||||||
|
return Err(CGenError { message: "List.flatten takes 1 argument".to_string(), span: None });
|
||||||
|
}
|
||||||
|
let list = self.emit_expr(&args[0])?;
|
||||||
|
let id = self.fresh_name();
|
||||||
|
let result_var = format!("_flat_{}", id);
|
||||||
|
let i_var = format!("_i_{}", id);
|
||||||
|
let j_var = format!("_j_{}", id);
|
||||||
|
let inner_var = format!("_inner_{}", id);
|
||||||
|
|
||||||
|
self.writeln(&format!("LuxList* {} = lux_list_new(16);", result_var));
|
||||||
|
self.writeln(&format!("for (int64_t {} = 0; {} < {}->length; {}++) {{", i_var, i_var, list, i_var));
|
||||||
|
self.indent += 1;
|
||||||
|
self.writeln(&format!("LuxList* {} = (LuxList*){}->elements[{}];", inner_var, list, i_var));
|
||||||
|
self.writeln(&format!("for (int64_t {} = 0; {} < {}->length; {}++) {{", j_var, j_var, inner_var, j_var));
|
||||||
|
self.indent += 1;
|
||||||
|
self.writeln(&format!("lux_incref({}->elements[{}]);", inner_var, j_var));
|
||||||
|
self.writeln(&format!("lux_list_push({}, {}->elements[{}]);", result_var, inner_var, j_var));
|
||||||
|
self.indent -= 1;
|
||||||
|
self.writeln("}");
|
||||||
|
self.indent -= 1;
|
||||||
|
self.writeln("}");
|
||||||
|
self.register_rc_var(&result_var, "LuxList*");
|
||||||
|
Ok(result_var)
|
||||||
|
}
|
||||||
|
|
||||||
_ => Err(CGenError {
|
_ => Err(CGenError {
|
||||||
message: format!("Unsupported List operation: {}", op),
|
message: format!("Unsupported List operation: {}", op),
|
||||||
span: None,
|
span: None,
|
||||||
@@ -5374,8 +5476,8 @@ impl CBackend {
|
|||||||
},
|
},
|
||||||
"List" => match field.name.as_str() {
|
"List" => match field.name.as_str() {
|
||||||
"map" | "filter" | "concat" | "reverse" | "take" | "drop"
|
"map" | "filter" | "concat" | "reverse" | "take" | "drop"
|
||||||
| "range" | "sort" | "sortBy" | "flatten" | "intersperse" => return Some("LuxList*".to_string()),
|
| "range" | "sort" | "sortBy" | "flatten" | "intersperse" | "zip" => return Some("LuxList*".to_string()),
|
||||||
"head" | "tail" | "get" | "find" | "last" => return Some("Option".to_string()),
|
"head" | "tail" | "get" | "find" | "findIndex" | "last" => return Some("Option".to_string()),
|
||||||
"length" => return Some("LuxInt".to_string()),
|
"length" => return Some("LuxInt".to_string()),
|
||||||
"fold" | "foldLeft" => {
|
"fold" | "foldLeft" => {
|
||||||
// Fold return type is the type of the init value (2nd arg)
|
// Fold return type is the type of the init value (2nd arg)
|
||||||
@@ -5469,9 +5571,9 @@ impl CBackend {
|
|||||||
if effect.name == "List" {
|
if effect.name == "List" {
|
||||||
match operation.name.as_str() {
|
match operation.name.as_str() {
|
||||||
// Operations returning lists
|
// Operations returning lists
|
||||||
"map" | "filter" | "concat" | "reverse" | "take" | "drop" | "range" | "sort" | "sortBy" => Some("LuxList*".to_string()),
|
"map" | "filter" | "concat" | "reverse" | "take" | "drop" | "range" | "sort" | "sortBy" | "zip" | "flatten" => Some("LuxList*".to_string()),
|
||||||
// Operations returning Option
|
// Operations returning Option
|
||||||
"head" | "tail" | "get" | "find" => Some("Option".to_string()),
|
"head" | "tail" | "get" | "find" | "findIndex" => Some("Option".to_string()),
|
||||||
// Operations returning Int
|
// Operations returning Int
|
||||||
"length" => Some("LuxInt".to_string()),
|
"length" => Some("LuxInt".to_string()),
|
||||||
// Fold returns the type of the init value
|
// Fold returns the type of the init value
|
||||||
@@ -5483,7 +5585,7 @@ impl CBackend {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Operations returning Bool
|
// Operations returning Bool
|
||||||
"isEmpty" | "any" | "all" => Some("LuxBool".to_string()),
|
"isEmpty" | "any" | "all" | "contains" => Some("LuxBool".to_string()),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
} else if effect.name == "Random" {
|
} else if effect.name == "Random" {
|
||||||
@@ -6382,7 +6484,8 @@ impl CBackend {
|
|||||||
// These List operations return new lists
|
// These List operations return new lists
|
||||||
return matches!(field.name.as_str(),
|
return matches!(field.name.as_str(),
|
||||||
"map" | "filter" | "concat" | "reverse" |
|
"map" | "filter" | "concat" | "reverse" |
|
||||||
"take" | "drop" | "range"
|
"take" | "drop" | "range" | "zip" | "flatten" |
|
||||||
|
"sort" | "sortBy"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if module.name == "String" {
|
if module.name == "String" {
|
||||||
@@ -6408,7 +6511,8 @@ impl CBackend {
|
|||||||
if effect.name == "List" {
|
if effect.name == "List" {
|
||||||
matches!(operation.name.as_str(),
|
matches!(operation.name.as_str(),
|
||||||
"map" | "filter" | "concat" | "reverse" |
|
"map" | "filter" | "concat" | "reverse" |
|
||||||
"take" | "drop" | "range"
|
"take" | "drop" | "range" | "zip" | "flatten" |
|
||||||
|
"sort" | "sortBy"
|
||||||
)
|
)
|
||||||
} else if effect.name == "Process" {
|
} else if effect.name == "Process" {
|
||||||
// Process.exec returns RC-managed string
|
// Process.exec returns RC-managed string
|
||||||
|
|||||||
@@ -83,10 +83,14 @@ pub enum BuiltinFn {
|
|||||||
// Additional List operations
|
// Additional List operations
|
||||||
ListIsEmpty,
|
ListIsEmpty,
|
||||||
ListFind,
|
ListFind,
|
||||||
|
ListFindIndex,
|
||||||
ListAny,
|
ListAny,
|
||||||
ListAll,
|
ListAll,
|
||||||
ListTake,
|
ListTake,
|
||||||
ListDrop,
|
ListDrop,
|
||||||
|
ListZip,
|
||||||
|
ListFlatten,
|
||||||
|
ListContains,
|
||||||
|
|
||||||
// Additional String operations
|
// Additional String operations
|
||||||
StringStartsWith,
|
StringStartsWith,
|
||||||
@@ -974,10 +978,14 @@ impl Interpreter {
|
|||||||
Value::Builtin(BuiltinFn::ListIsEmpty),
|
Value::Builtin(BuiltinFn::ListIsEmpty),
|
||||||
),
|
),
|
||||||
("find".to_string(), Value::Builtin(BuiltinFn::ListFind)),
|
("find".to_string(), Value::Builtin(BuiltinFn::ListFind)),
|
||||||
|
("findIndex".to_string(), Value::Builtin(BuiltinFn::ListFindIndex)),
|
||||||
("any".to_string(), Value::Builtin(BuiltinFn::ListAny)),
|
("any".to_string(), Value::Builtin(BuiltinFn::ListAny)),
|
||||||
("all".to_string(), Value::Builtin(BuiltinFn::ListAll)),
|
("all".to_string(), Value::Builtin(BuiltinFn::ListAll)),
|
||||||
("take".to_string(), Value::Builtin(BuiltinFn::ListTake)),
|
("take".to_string(), Value::Builtin(BuiltinFn::ListTake)),
|
||||||
("drop".to_string(), Value::Builtin(BuiltinFn::ListDrop)),
|
("drop".to_string(), Value::Builtin(BuiltinFn::ListDrop)),
|
||||||
|
("zip".to_string(), Value::Builtin(BuiltinFn::ListZip)),
|
||||||
|
("flatten".to_string(), Value::Builtin(BuiltinFn::ListFlatten)),
|
||||||
|
("contains".to_string(), Value::Builtin(BuiltinFn::ListContains)),
|
||||||
(
|
(
|
||||||
"forEach".to_string(),
|
"forEach".to_string(),
|
||||||
Value::Builtin(BuiltinFn::ListForEach),
|
Value::Builtin(BuiltinFn::ListForEach),
|
||||||
@@ -2723,6 +2731,55 @@ impl Interpreter {
|
|||||||
Ok(EvalResult::Value(Value::Bool(true)))
|
Ok(EvalResult::Value(Value::Bool(true)))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
BuiltinFn::ListFindIndex => {
|
||||||
|
let (list, func) = Self::expect_args_2::<Vec<Value>, Value>(&args, "List.findIndex", span)?;
|
||||||
|
for (i, item) in list.iter().enumerate() {
|
||||||
|
let v = self.eval_call_to_value(func.clone(), vec![item.clone()], span)?;
|
||||||
|
match v {
|
||||||
|
Value::Bool(true) => {
|
||||||
|
return Ok(EvalResult::Value(Value::Constructor {
|
||||||
|
name: "Some".to_string(),
|
||||||
|
fields: vec![Value::Int(i as i64)],
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
Value::Bool(false) => {}
|
||||||
|
_ => return Err(err("List.findIndex predicate must return Bool")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(EvalResult::Value(Value::Constructor {
|
||||||
|
name: "None".to_string(),
|
||||||
|
fields: vec![],
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
BuiltinFn::ListZip => {
|
||||||
|
let (list1, list2) = Self::expect_args_2::<Vec<Value>, Vec<Value>>(&args, "List.zip", span)?;
|
||||||
|
let result: Vec<Value> = list1
|
||||||
|
.into_iter()
|
||||||
|
.zip(list2.into_iter())
|
||||||
|
.map(|(a, b)| Value::Tuple(vec![a, b]))
|
||||||
|
.collect();
|
||||||
|
Ok(EvalResult::Value(Value::List(result)))
|
||||||
|
}
|
||||||
|
|
||||||
|
BuiltinFn::ListFlatten => {
|
||||||
|
let list = Self::expect_arg_1::<Vec<Value>>(&args, "List.flatten", span)?;
|
||||||
|
let mut result = Vec::new();
|
||||||
|
for item in list {
|
||||||
|
match item {
|
||||||
|
Value::List(inner) => result.extend(inner),
|
||||||
|
other => result.push(other),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(EvalResult::Value(Value::List(result)))
|
||||||
|
}
|
||||||
|
|
||||||
|
BuiltinFn::ListContains => {
|
||||||
|
let (list, target) = Self::expect_args_2::<Vec<Value>, Value>(&args, "List.contains", span)?;
|
||||||
|
let found = list.iter().any(|item| Value::values_equal(item, &target));
|
||||||
|
Ok(EvalResult::Value(Value::Bool(found)))
|
||||||
|
}
|
||||||
|
|
||||||
BuiltinFn::ListTake => {
|
BuiltinFn::ListTake => {
|
||||||
let (list, n) = Self::expect_args_2::<Vec<Value>, i64>(&args, "List.take", span)?;
|
let (list, n) = Self::expect_args_2::<Vec<Value>, i64>(&args, "List.take", span)?;
|
||||||
let n = n.max(0) as usize;
|
let n = n.max(0) as usize;
|
||||||
|
|||||||
34
src/types.rs
34
src/types.rs
@@ -1539,6 +1539,16 @@ impl TypeEnv {
|
|||||||
Type::Option(Box::new(Type::var())),
|
Type::Option(Box::new(Type::var())),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
(
|
||||||
|
"findIndex".to_string(),
|
||||||
|
Type::function(
|
||||||
|
vec![
|
||||||
|
Type::List(Box::new(Type::var())),
|
||||||
|
Type::function(vec![Type::var()], Type::Bool),
|
||||||
|
],
|
||||||
|
Type::Option(Box::new(Type::Int)),
|
||||||
|
),
|
||||||
|
),
|
||||||
(
|
(
|
||||||
"any".to_string(),
|
"any".to_string(),
|
||||||
Type::function(
|
Type::function(
|
||||||
@@ -1603,6 +1613,30 @@ impl TypeEnv {
|
|||||||
)
|
)
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
|
(
|
||||||
|
"zip".to_string(),
|
||||||
|
Type::function(
|
||||||
|
vec![
|
||||||
|
Type::List(Box::new(Type::var())),
|
||||||
|
Type::List(Box::new(Type::var())),
|
||||||
|
],
|
||||||
|
Type::List(Box::new(Type::Tuple(vec![Type::var(), Type::var()]))),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"flatten".to_string(),
|
||||||
|
Type::function(
|
||||||
|
vec![Type::List(Box::new(Type::List(Box::new(Type::var()))))],
|
||||||
|
Type::List(Box::new(Type::var())),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"contains".to_string(),
|
||||||
|
Type::function(
|
||||||
|
vec![Type::List(Box::new(Type::var())), Type::var()],
|
||||||
|
Type::Bool,
|
||||||
|
),
|
||||||
|
),
|
||||||
]);
|
]);
|
||||||
env.bind("List", TypeScheme::mono(list_module_type));
|
env.bind("List", TypeScheme::mono(list_module_type));
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user