sim-lib-lang-prolog 0.1.0-rc.1

Prolog surface profile for the SIM 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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
use std::{
    fs,
    path::Path,
    sync::{Arc, Mutex},
};

use sim_codec::{Input, decode_with_codec};
use sim_kernel::{
    AbiVersion, Args, Callable, ClassRef, Cx, Error, Expr, Lib, LibManifest, LibTarget, Linker,
    LoadCx, Object, QuoteMode, RawArgs, ReadPolicy, Result, Symbol, Value, Version,
    logic_consult_file_capability, logic_db_write_capability,
};
use sim_lib_logic::{LogicConfig, LogicDb, LogicPolicy, SearchStrategy, query};

use crate::exports::prolog_export_declarations;

const PROLOG_LIB_ID: &str = "prolog";
const DB_SYMBOL: &str = "db";
const CONFIG_SYMBOL: &str = "config-state";

/// The loadable Prolog surface organ.
///
/// Loading the organ registers `prolog/*` functions plus the state handles used
/// by [`install_prolog_lib`] to point the active logic eval policy at the same
/// clause database.
pub struct PrologLib;

impl Lib for PrologLib {
    fn manifest(&self) -> LibManifest {
        LibManifest {
            id: Symbol::new(PROLOG_LIB_ID),
            version: Version(env!("CARGO_PKG_VERSION").to_owned()),
            abi: AbiVersion { major: 0, minor: 1 },
            target: LibTarget::HostRegistered,
            requires: Vec::new(),
            capabilities: Vec::new(),
            exports: prolog_export_declarations(),
        }
    }

    fn load(&self, cx: &mut LoadCx, linker: &mut Linker<'_>) -> Result<()> {
        register_prolog_functions(cx, linker)?;
        linker.value(
            Symbol::qualified("prolog", DB_SYMBOL),
            cx.factory().opaque(Arc::new(PrologDbState::default()))?,
        )?;
        linker.value(
            Symbol::qualified("prolog", CONFIG_SYMBOL),
            cx.factory()
                .opaque(Arc::new(PrologConfigState::default()))?,
        )?;
        Ok(())
    }
}

/// Installs the Prolog surface into `cx` and makes its logic policy active.
///
/// Repeated calls keep the installed database and reset the active eval policy
/// to the installed Prolog database, so direct expression evaluation and
/// `prolog/*` calls see the same asserted clauses.
pub fn install_prolog_lib(cx: &mut Cx) -> Result<()> {
    let _ = sim_lib_core::install_once(cx, &PrologLib)?;
    let db = prolog_db_state(cx)?.handle();
    let config = prolog_config_state(cx)?.lock()?.clone();
    cx.set_eval_policy(Arc::new(LogicPolicy::from_shared(db, config)));
    Ok(())
}

#[derive(Clone, Default)]
struct PrologDbState {
    inner: Arc<Mutex<LogicDb>>,
}

impl PrologDbState {
    fn handle(&self) -> Arc<Mutex<LogicDb>> {
        Arc::clone(&self.inner)
    }

    fn lock(&self) -> Result<std::sync::MutexGuard<'_, LogicDb>> {
        self.inner
            .lock()
            .map_err(|_| Error::PoisonedLock("prolog db"))
    }
}

impl Object for PrologDbState {
    fn display(&self, _cx: &mut Cx) -> Result<String> {
        Ok("#<prolog-db>".to_owned())
    }

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

impl sim_kernel::ObjectCompat for PrologDbState {
    fn class(&self, cx: &mut Cx) -> Result<ClassRef> {
        cx.factory().class_stub(
            sim_kernel::ClassId(0),
            Symbol::qualified("prolog", "DbState"),
        )
    }
}

#[derive(Clone, Default)]
struct PrologConfigState {
    inner: Arc<Mutex<LogicConfig>>,
}

impl PrologConfigState {
    fn lock(&self) -> Result<std::sync::MutexGuard<'_, LogicConfig>> {
        self.inner
            .lock()
            .map_err(|_| Error::PoisonedLock("prolog config"))
    }
}

impl Object for PrologConfigState {
    fn display(&self, _cx: &mut Cx) -> Result<String> {
        Ok("#<prolog-config>".to_owned())
    }

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

impl sim_kernel::ObjectCompat for PrologConfigState {
    fn class(&self, cx: &mut Cx) -> Result<ClassRef> {
        cx.factory().class_stub(
            sim_kernel::ClassId(0),
            Symbol::qualified("prolog", "ConfigState"),
        )
    }
}

struct PrologFunction {
    symbol: Symbol,
    implementation: fn(&mut Cx, &[Expr]) -> Result<Value>,
}

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

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

impl sim_kernel::ObjectCompat for PrologFunction {
    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 PrologFunction {
    fn call(&self, _cx: &mut Cx, _args: Args) -> Result<Value> {
        Err(prolog_eval_error(format!(
            "{} must be called from source expressions",
            self.symbol
        )))
    }

    fn call_exprs(&self, cx: &mut Cx, args: RawArgs) -> Result<Value> {
        (self.implementation)(cx, args.exprs())
    }
}

fn register_prolog_functions(cx: &mut LoadCx, linker: &mut Linker<'_>) -> Result<()> {
    for (symbol, implementation) in [
        (
            Symbol::qualified("prolog", "assert!"),
            prolog_assert_fn as fn(&mut Cx, &[Expr]) -> Result<Value>,
        ),
        (Symbol::qualified("prolog", "retract!"), prolog_retract_fn),
        (Symbol::qualified("prolog", "query"), prolog_query_fn),
        (
            Symbol::qualified("prolog", "query/all"),
            prolog_query_all_fn,
        ),
        (
            Symbol::qualified("prolog", "query-seq"),
            prolog_query_seq_fn,
        ),
        (Symbol::qualified("prolog", "consult"), prolog_consult_fn),
    ] {
        linker.function_value(
            symbol.clone(),
            cx.factory().opaque(Arc::new(PrologFunction {
                symbol,
                implementation,
            }))?,
        )?;
    }
    Ok(())
}

fn prolog_assert_fn(cx: &mut Cx, args: &[Expr]) -> Result<Value> {
    cx.require(&logic_db_write_capability())?;
    let [expr] = args else {
        return Err(prolog_eval_error(
            "prolog/assert! expects one quoted clause",
        ));
    };
    prolog_db_state(cx)?
        .lock()?
        .assert_clause_expr(unquote(expr))?;
    cx.factory().bool(true)
}

fn prolog_retract_fn(cx: &mut Cx, args: &[Expr]) -> Result<Value> {
    cx.require(&logic_db_write_capability())?;
    let [expr] = args else {
        return Err(prolog_eval_error(
            "prolog/retract! expects one quoted clause",
        ));
    };
    let removed = prolog_db_state(cx)?
        .lock()?
        .retract_clause_expr(&unquote(expr))?;
    cx.factory().bool(removed)
}

fn prolog_query_fn(cx: &mut Cx, args: &[Expr]) -> Result<Value> {
    let [goal, rest @ ..] = args else {
        return Err(prolog_eval_error("prolog/query expects a goal"));
    };
    let config = prolog_query_config(cx, rest)?;
    let db = prolog_db_state(cx)?.lock()?.clone();
    let stream = query(cx, &db, &config, unquote(goal))?;
    match stream.collect(cx, Some(1))?.into_iter().next() {
        Some(answer) => Ok(answer),
        None => cx.factory().nil(),
    }
}

fn prolog_query_all_fn(cx: &mut Cx, args: &[Expr]) -> Result<Value> {
    let [goal, rest @ ..] = args else {
        return Err(prolog_eval_error("prolog/query/all expects a goal"));
    };
    let config = prolog_query_config(cx, rest)?;
    let db = prolog_db_state(cx)?.lock()?.clone();
    let stream = query(cx, &db, &config, unquote(goal))?;
    let answers = stream.collect(cx, config.limits.max_answers)?;
    cx.factory().list(answers)
}

fn prolog_query_seq_fn(cx: &mut Cx, args: &[Expr]) -> Result<Value> {
    let [goal, rest @ ..] = args else {
        return Err(prolog_eval_error("prolog/query-seq expects a goal"));
    };
    let config = prolog_query_config(cx, rest)?;
    let db = prolog_db_state(cx)?.lock()?.clone();
    let stream = query(cx, &db, &config, unquote(goal))?;
    cx.factory().opaque(Arc::new(stream))
}

fn prolog_consult_fn(cx: &mut Cx, args: &[Expr]) -> Result<Value> {
    cx.require(&logic_db_write_capability())?;
    let [expr] = args else {
        return Err(prolog_eval_error(
            "prolog/consult expects one path or quoted program",
        ));
    };
    let program = unquote(expr);
    let count = match program {
        Expr::String(path) => {
            let state = prolog_db_state(cx)?;
            let mut db = state.lock()?;
            prolog_consult_path(cx, &mut db, &path)?
        }
        Expr::Symbol(path) => {
            let state = prolog_db_state(cx)?;
            let mut db = state.lock()?;
            prolog_consult_path(cx, &mut db, &path.to_string())?
        }
        other => {
            let state = prolog_db_state(cx)?;
            let mut db = state.lock()?;
            prolog_consult_expr(&mut db, other)?
        }
    };
    cx.factory().string(count.to_string())
}

fn prolog_db_state(cx: &mut Cx) -> Result<PrologDbState> {
    cx.resolve_value(&Symbol::qualified("prolog", DB_SYMBOL))?
        .object()
        .downcast_ref::<PrologDbState>()
        .cloned()
        .ok_or(Error::TypeMismatch {
            expected: "prolog db state",
            found: "non-prolog-db",
        })
}

fn prolog_config_state(cx: &mut Cx) -> Result<PrologConfigState> {
    cx.resolve_value(&Symbol::qualified("prolog", CONFIG_SYMBOL))?
        .object()
        .downcast_ref::<PrologConfigState>()
        .cloned()
        .ok_or(Error::TypeMismatch {
            expected: "prolog config state",
            found: "non-prolog-config",
        })
}

fn prolog_query_config(cx: &mut Cx, options: &[Expr]) -> Result<LogicConfig> {
    let mut config = prolog_config_state(cx)?.lock()?.clone();
    if !options.len().is_multiple_of(2) {
        return Err(prolog_eval_error(
            "prolog query options must be key/value pairs",
        ));
    }
    for pair in options.chunks(2) {
        let key = keyword(&pair[0])?;
        match key.as_str() {
            "limit" | "answer-limit" | "max-answers" => {
                config.limits.max_answers = Some(usize_from_expr(cx, &pair[1])?)
            }
            "buffer" | "stream-buffer" => config.stream_buffer = usize_from_expr(cx, &pair[1])?,
            "strategy" => {
                let symbol = symbol_expr(cx, &pair[1])?;
                config.strategy = SearchStrategy::from_symbol(&symbol)
                    .ok_or_else(|| prolog_eval_error(format!("unsupported strategy {symbol}")))?;
            }
            other => {
                return Err(prolog_eval_error(format!(
                    "prolog query does not support :{other}"
                )));
            }
        }
    }
    Ok(config)
}

fn keyword(expr: &Expr) -> Result<String> {
    let Expr::Symbol(symbol) = expr else {
        return Err(prolog_eval_error("expected keyword symbol"));
    };
    Ok(symbol.name.trim_start_matches(':').to_owned())
}

fn symbol_expr(cx: &mut Cx, expr: &Expr) -> Result<Symbol> {
    match unquote(expr) {
        Expr::Symbol(symbol) => Ok(symbol),
        other => match cx.eval_expr(other)?.object().as_expr(cx)? {
            Expr::Symbol(symbol) => Ok(symbol),
            _ => Err(prolog_eval_error("expected symbol")),
        },
    }
}

fn usize_from_expr(cx: &mut Cx, expr: &Expr) -> Result<usize> {
    match unquote(expr) {
        Expr::Number(number) => number
            .canonical
            .parse::<usize>()
            .map_err(|_| prolog_eval_error(format!("expected usize, found {}", number.canonical))),
        Expr::String(text) => text
            .parse::<usize>()
            .map_err(|_| prolog_eval_error(format!("expected usize, found {text}"))),
        Expr::Symbol(symbol) => symbol
            .name
            .parse::<usize>()
            .map_err(|_| prolog_eval_error(format!("expected usize, found {symbol}"))),
        other => match cx.eval_expr(other)?.object().as_expr(cx)? {
            Expr::Number(number) => number.canonical.parse::<usize>().map_err(|_| {
                prolog_eval_error(format!("expected usize, found {}", number.canonical))
            }),
            Expr::String(text) => text
                .parse::<usize>()
                .map_err(|_| prolog_eval_error(format!("expected usize, found {text}"))),
            _ => Err(prolog_eval_error("expected usize value")),
        },
    }
}

fn unquote(expr: &Expr) -> Expr {
    match expr {
        Expr::Quote {
            mode: QuoteMode::Quote,
            expr,
        } => (**expr).clone(),
        other => other.clone(),
    }
}

fn prolog_consult_path(cx: &mut Cx, db: &mut LogicDb, path: &str) -> Result<usize> {
    cx.require(&logic_consult_file_capability())?;
    let bytes = fs::read(path).map_err(|err| prolog_eval_error(err.to_string()))?;
    let codec = codec_for_path(path);
    let expr = decode_with_codec(
        cx,
        &codec,
        match codec.name.as_ref() {
            "binary" | "binary-base64" => Input::Bytes(bytes),
            _ => Input::Text(
                String::from_utf8(bytes).map_err(|err| prolog_eval_error(err.to_string()))?,
            ),
        },
        ReadPolicy::default(),
    )?;
    prolog_consult_expr(db, expr)
}

fn prolog_consult_expr(db: &mut LogicDb, expr: Expr) -> Result<usize> {
    match expr {
        Expr::List(items) => {
            let mut count = 0usize;
            for item in items {
                db.assert_clause_expr(item)?;
                count += 1;
            }
            Ok(count)
        }
        other => {
            db.assert_clause_expr(other)?;
            Ok(1)
        }
    }
}

fn codec_for_path(path: &str) -> Symbol {
    match Path::new(path)
        .extension()
        .and_then(|extension| extension.to_str())
        .unwrap_or_default()
    {
        "simlogicb64" | "simb64" => Symbol::qualified("codec", "binary-base64"),
        "json" => Symbol::qualified("codec", "json"),
        "alg" => Symbol::qualified("codec", "algol"),
        "slb8" => Symbol::qualified("codec", "binary"),
        _ => Symbol::qualified("codec", "lisp"),
    }
}

fn prolog_eval_error(message: impl Into<String>) -> Error {
    Error::Eval(message.into())
}