sim-lib-lang-lua 0.1.4

Lua-style surface profile for the SIM expression runtime.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
use std::sync::Arc;

use sim_kernel::{
    Args, Callable, ClassRef, Cx, Error, Expr, Object, ObjectCompat, Result, Symbol, Value,
};
use sim_lib_standard_core::{Arity, SharedOrganRuntime};

use crate::{
    LuaEvalPolicy, LuaNumber, call::call_lua_value, lua_core_profile, lua_integer_value,
    lua_number_from_value, lua_rawdel, lua_rawget, lua_rawset, lua_table_from_values,
    lua_table_value,
};

#[derive(Clone, Copy)]
pub(crate) enum LuaTableKind {
    Insert,
    Remove,
    Move,
    Concat,
    Sort,
    Pack,
    Unpack,
}

impl LuaTableKind {
    const ALL: [Self; 7] = [
        Self::Insert,
        Self::Remove,
        Self::Move,
        Self::Concat,
        Self::Sort,
        Self::Pack,
        Self::Unpack,
    ];

    fn env_name(self) -> &'static str {
        match self {
            Self::Insert => "insert",
            Self::Remove => "remove",
            Self::Move => "move",
            Self::Concat => "concat",
            Self::Sort => "sort",
            Self::Pack => "pack",
            Self::Unpack => "unpack",
        }
    }

    fn function_symbol(self) -> Symbol {
        Symbol::qualified("lua/table", self.env_name())
    }

    fn organ(self) -> Symbol {
        match self {
            Self::Concat | Self::Pack | Self::Unpack => sim_lib_sequence::sequence_organ_symbol(),
            Self::Insert | Self::Remove | Self::Move | Self::Sort => {
                sim_lib_mutation::mutation_organ_symbol()
            }
        }
    }
}

#[derive(Clone)]
pub(crate) struct LuaTableFunction {
    kind: LuaTableKind,
}

impl LuaTableFunction {
    fn new(kind: LuaTableKind) -> Self {
        Self { kind }
    }

    pub(crate) fn kind(&self) -> LuaTableKind {
        self.kind
    }
}

impl Object for LuaTableFunction {
    fn display(&self, _cx: &mut Cx) -> Result<String> {
        Ok(format!("#<lua-table-function {}>", self.kind.env_name()))
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl ObjectCompat for LuaTableFunction {
    fn class(&self, cx: &mut Cx) -> Result<ClassRef> {
        cx.resolve_class(&Symbol::qualified("core", "Function"))
    }

    fn as_callable(&self) -> Option<&dyn Callable> {
        Some(self)
    }
}

impl Callable for LuaTableFunction {
    fn call(&self, cx: &mut Cx, args: Args) -> Result<Value> {
        let policy = LuaEvalPolicy::new(cx)?;
        let values = run_lua_table_function(cx, &policy, self.kind, args.into_vec())?;
        Ok(policy
            .kit()
            .adjust_values(values, Arity::AtLeastOne)
            .into_iter()
            .next()
            .unwrap_or_else(|| policy.kit().nil.clone()))
    }
}

pub(crate) fn install_lua_table_stdlib(
    cx: &mut Cx,
    policy: &LuaEvalPolicy,
    env: &mut crate::LuaEnv,
) -> Result<()> {
    let mut runtime = SharedOrganRuntime::new();
    let profile = lua_core_profile();
    let profile_symbol = profile.symbol.clone();
    runtime.register_profile(profile)?;
    runtime.register_kit(&profile_symbol, policy.kit().clone())?;

    let mut table_entries = Vec::new();
    for kind in LuaTableKind::ALL {
        let function = cx.factory().opaque(Arc::new(LuaTableFunction::new(kind)))?;
        runtime.define_function(
            &profile_symbol,
            kind.organ(),
            kind.function_symbol(),
            function.clone(),
        )?;
        table_entries.push((
            cx.factory().string(kind.env_name().to_owned())?,
            function.clone(),
        ));
        define_or_assign(
            env,
            Symbol::new(format!("table.{}", kind.env_name())),
            function,
        )?;
    }
    let table = lua_table_from_values(cx, table_entries)?;
    define_or_assign(env, Symbol::new("table"), table)
}

pub(crate) fn run_lua_table_function(
    cx: &mut Cx,
    policy: &LuaEvalPolicy,
    kind: LuaTableKind,
    args: Vec<Value>,
) -> Result<Vec<Value>> {
    match kind {
        LuaTableKind::Insert => lua_table_insert(cx, policy, args),
        LuaTableKind::Remove => lua_table_remove(cx, policy, args),
        LuaTableKind::Move => lua_table_move(cx, args),
        LuaTableKind::Concat => lua_table_concat(cx, args),
        LuaTableKind::Sort => lua_table_sort(cx, policy, args),
        LuaTableKind::Pack => lua_table_pack(cx, args),
        LuaTableKind::Unpack => lua_table_unpack(cx, policy, args),
    }
}

fn lua_table_insert(cx: &mut Cx, policy: &LuaEvalPolicy, args: Vec<Value>) -> Result<Vec<Value>> {
    let (table, pos, value) = match args.as_slice() {
        [table, value] => {
            let len = lua_table_value(table)?.len_border(cx)?;
            (table.clone(), len + 1, value.clone())
        }
        [table, pos, value] => (
            table.clone(),
            integer_arg(cx, pos, "table.insert position")?,
            value.clone(),
        ),
        _ => {
            return Err(Error::Eval(
                "table.insert requires table, optional position, and value".to_owned(),
            ));
        }
    };
    let len = lua_table_value(&table)?.len_border(cx)?;
    if pos < 1 || pos > len + 1 {
        return Err(Error::Eval("table.insert position out of range".to_owned()));
    }
    for index in (pos..=len).rev() {
        move_slot(cx, policy, &table, index, index + 1)?;
    }
    raw_set_index(cx, &table, pos, value)?;
    Ok(Vec::new())
}

fn lua_table_remove(cx: &mut Cx, policy: &LuaEvalPolicy, args: Vec<Value>) -> Result<Vec<Value>> {
    let table = first_arg(&args, "table.remove")?.clone();
    let len = lua_table_value(&table)?.len_border(cx)?;
    let pos = match args.get(1) {
        Some(value) => integer_arg(cx, value, "table.remove position")?,
        None => len,
    };
    if len == 0 || pos < 1 || pos > len {
        return Ok(vec![policy.kit().nil.clone()]);
    }
    let removed = raw_get_index(cx, &table, pos)?.unwrap_or_else(|| policy.kit().nil.clone());
    for index in pos + 1..=len {
        move_slot(cx, policy, &table, index, index - 1)?;
    }
    raw_del_index(cx, &table, len)?;
    Ok(vec![removed])
}

fn lua_table_move(cx: &mut Cx, args: Vec<Value>) -> Result<Vec<Value>> {
    let [source, first, last, target, rest @ ..] = args.as_slice() else {
        return Err(Error::Eval(
            "table.move requires source, first, last, and target".to_owned(),
        ));
    };
    let first = integer_arg(cx, first, "table.move first")?;
    let last = integer_arg(cx, last, "table.move last")?;
    let target_start = integer_arg(cx, target, "table.move target")?;
    let destination = rest.first().cloned().unwrap_or_else(|| source.clone());
    if first <= last {
        let mut values = Vec::new();
        for index in first..=last {
            values.push(
                raw_get_index(cx, source, index)?.unwrap_or_else(|| cx.factory().nil().unwrap()),
            );
        }
        for (offset, value) in values.into_iter().enumerate() {
            raw_set_index(cx, &destination, target_start + offset as i64, value)?;
        }
    }
    Ok(vec![destination])
}

fn lua_table_concat(cx: &mut Cx, args: Vec<Value>) -> Result<Vec<Value>> {
    let table = first_arg(&args, "table.concat")?;
    let sep = args
        .get(1)
        .map(|value| string_arg(cx, value, "table.concat separator"))
        .transpose()?
        .unwrap_or_default();
    let len = lua_table_value(table)?.len_border(cx)?;
    let first = match args.get(2) {
        Some(value) => integer_arg(cx, value, "table.concat first")?,
        None => 1,
    };
    let last = match args.get(3) {
        Some(value) => integer_arg(cx, value, "table.concat last")?,
        None => len,
    };
    let mut parts = Vec::new();
    if first <= last {
        for index in first..=last {
            let value = raw_get_index(cx, table, index)?
                .ok_or_else(|| Error::Eval("table.concat found nil array slot".to_owned()))?;
            parts.push(lua_string_coercion(cx, &value, "table.concat value")?);
        }
    }
    cx.factory()
        .string(parts.join(&sep))
        .map(|value| vec![value])
}

fn lua_table_sort(cx: &mut Cx, policy: &LuaEvalPolicy, args: Vec<Value>) -> Result<Vec<Value>> {
    let table = first_arg(&args, "table.sort")?.clone();
    let comparator = args.get(1).cloned();
    let len = lua_table_value(&table)?.len_border(cx)?;
    let mut values = Vec::new();
    for index in 1..=len {
        values.push(
            raw_get_index(cx, &table, index)?
                .ok_or_else(|| Error::Eval("table.sort found nil array slot".to_owned()))?,
        );
    }
    for index in 1..values.len() {
        let mut cursor = index;
        while cursor > 0
            && lua_less_than(
                cx,
                policy,
                &values[cursor],
                &values[cursor - 1],
                comparator.as_ref(),
            )?
        {
            values.swap(cursor, cursor - 1);
            cursor -= 1;
        }
    }
    for (index, value) in values.into_iter().enumerate() {
        raw_set_index(cx, &table, index as i64 + 1, value)?;
    }
    Ok(Vec::new())
}

fn lua_table_pack(cx: &mut Cx, args: Vec<Value>) -> Result<Vec<Value>> {
    let mut entries = Vec::with_capacity(args.len() + 1);
    for (index, value) in args.iter().cloned().enumerate() {
        entries.push((lua_integer_value(cx, index as i64 + 1)?, value));
    }
    entries.push((
        cx.factory().string("n".to_owned())?,
        lua_integer_value(cx, args.len() as i64)?,
    ));
    lua_table_from_values(cx, entries).map(|value| vec![value])
}

fn lua_table_unpack(cx: &mut Cx, policy: &LuaEvalPolicy, args: Vec<Value>) -> Result<Vec<Value>> {
    let table = first_arg(&args, "table.unpack")?;
    let len = lua_table_value(table)?.len_border(cx)?;
    let first = match args.get(1) {
        Some(value) => integer_arg(cx, value, "table.unpack first")?,
        None => 1,
    };
    let last = match args.get(2) {
        Some(value) => integer_arg(cx, value, "table.unpack last")?,
        None => len,
    };
    let mut values = Vec::new();
    if first <= last {
        for index in first..=last {
            values
                .push(raw_get_index(cx, table, index)?.unwrap_or_else(|| policy.kit().nil.clone()));
        }
    }
    Ok(values)
}

fn move_slot(cx: &mut Cx, policy: &LuaEvalPolicy, table: &Value, from: i64, to: i64) -> Result<()> {
    match raw_get_index(cx, table, from)? {
        Some(value) => raw_set_index(cx, table, to, value),
        None => raw_set_index(cx, table, to, policy.kit().nil.clone()),
    }
}

fn lua_less_than(
    cx: &mut Cx,
    policy: &LuaEvalPolicy,
    left: &Value,
    right: &Value,
    comparator: Option<&Value>,
) -> Result<bool> {
    if let Some(comparator) = comparator {
        let result = call_lua_value(
            cx,
            policy,
            comparator.clone(),
            vec![left.clone(), right.clone()],
        )?;
        let value = policy
            .kit()
            .adjust_values(result, Arity::AtLeastOne)
            .into_iter()
            .next()
            .unwrap_or_else(|| policy.kit().nil.clone());
        return policy.kit().is_truthy(cx, &value);
    }
    if let (Some(left), Some(right)) = (
        lua_number_from_value(cx, left)?,
        lua_number_from_value(cx, right)?,
    ) {
        return Ok(number_as_f64(left) < number_as_f64(right));
    }
    Ok(string_arg(cx, left, "table.sort value")? < string_arg(cx, right, "table.sort value")?)
}

fn raw_get_index(cx: &mut Cx, table: &Value, index: i64) -> Result<Option<Value>> {
    let key = lua_integer_value(cx, index)?;
    lua_rawget(cx, table, &key)
}

fn raw_set_index(cx: &mut Cx, table: &Value, index: i64, value: Value) -> Result<()> {
    let key = lua_integer_value(cx, index)?;
    lua_rawset(cx, table, key, value)
}

fn raw_del_index(cx: &mut Cx, table: &Value, index: i64) -> Result<()> {
    let key = lua_integer_value(cx, index)?;
    lua_rawdel(cx, table, &key)?;
    Ok(())
}

fn first_arg<'a>(args: &'a [Value], context: &str) -> Result<&'a Value> {
    args.first()
        .ok_or_else(|| Error::Eval(format!("{context} requires a table")))
}

fn integer_arg(cx: &mut Cx, value: &Value, context: &str) -> Result<i64> {
    match lua_number_from_value(cx, value)? {
        Some(LuaNumber::Integer(value)) => Ok(value),
        Some(LuaNumber::Float(value)) if value.fract() == 0.0 => Ok(value as i64),
        _ => Err(Error::Eval(format!("{context} must be an integer"))),
    }
}

fn string_arg(cx: &mut Cx, value: &Value, context: &str) -> Result<String> {
    match value.object().as_expr(cx)? {
        Expr::String(value) => Ok(value),
        _ => Err(Error::Eval(format!("{context} must be a string"))),
    }
}

fn lua_string_coercion(cx: &mut Cx, value: &Value, context: &str) -> Result<String> {
    match value.object().as_expr(cx)? {
        Expr::String(value) => Ok(value),
        Expr::Number(number) => Ok(number.canonical),
        _ => Err(Error::Eval(format!("{context} must be a string or number"))),
    }
}

fn number_as_f64(value: LuaNumber) -> f64 {
    match value {
        LuaNumber::Integer(value) => value as f64,
        LuaNumber::Float(value) => value,
    }
}

fn define_or_assign(env: &mut crate::LuaEnv, name: Symbol, value: Value) -> Result<()> {
    if env.contains(&name) {
        env.assign(&name, value)?;
    } else {
        env.define(name, value)?;
    }
    Ok(())
}