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
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::collections::HashMap;

use bumpalo::Bump;

// Immutable representation of syntax.
// We use references instead of a smart pointer,
// relying on an arena that holds everything.
// This way we can use pattern matching.

// Unit is a source unit.
// It consists of declarations and clauses.
// After parsing, all source units for a Mangle package
// are merged into one, so unit can also be seen
// as translation unit.
#[derive(Debug)]
pub struct Unit<'a> {
    pub decls: &'a [&'a Decl<'a>],
    pub clauses: &'a [&'a Clause<'a>],
}

// Predicate, package and use declarations.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Decl<'a> {
    pub atom: &'a Atom<'a>,
    pub descr: &'a [&'a Atom<'a>],
    pub bounds: Option<&'a [&'a BoundDecl<'a>]>,
    pub constraints: Option<&'a Constraints<'a>>,
}

#[derive(Debug, PartialEq)]
pub struct BoundDecl<'a> {
    pub base_terms: &'a [&'a BaseTerm<'a>],
}

//
#[derive(Debug, Clone, PartialEq)]
pub struct Constraints<'a> {
    // All of these must hold.
    pub consequences: &'a [&'a Atom<'a>],
    // In addition to consequences, at least one of these must hold.
    pub alternatives: &'a [&'a [&'a Atom<'a>]],
}

#[derive(Debug)]
pub struct Clause<'a> {
    pub head: &'a Atom<'a>,
    pub premises: &'a [&'a Term<'a>],
    pub transform: &'a [&'a TransformStmt<'a>],
}

#[derive(Debug)]
pub struct TransformStmt<'a> {
    pub var: Option<&'a str>,
    pub app: &'a BaseTerm<'a>,
}

// Term that may appear on righthand-side of a clause.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Term<'a> {
    Atom(&'a Atom<'a>),
    NegAtom(&'a Atom<'a>),
    Eq(&'a BaseTerm<'a>, &'a BaseTerm<'a>),
    Ineq(&'a BaseTerm<'a>, &'a BaseTerm<'a>),
}

impl<'a> Term<'a> {
    pub fn apply_subst<'b>(
        &'a self,
        bump: &'b Bump,
        subst: &HashMap<&'a str, &'a BaseTerm<'a>>,
    ) -> &'b Term<'b> {
        &*bump.alloc(match self {
            Term::Atom(atom) => Term::Atom(atom.apply_subst(bump, subst)),
            Term::NegAtom(atom) => Term::NegAtom(atom.apply_subst(bump, subst)),
            Term::Eq(left, right) => Term::Eq(
                left.apply_subst(bump, subst),
                right.apply_subst(bump, subst),
            ),
            Term::Ineq(left, right) => Term::Ineq(
                left.apply_subst(bump, subst),
                right.apply_subst(bump, subst),
            ),
        })
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BaseTerm<'a> {
    Const(Const<'a>),
    Variable(&'a str),
    ApplyFn(FunctionSym<'a>, &'a [&'a BaseTerm<'a>]),
}

impl<'a> BaseTerm<'a> {
    pub fn apply_subst<'b>(
        &'a self,
        bump: &'b Bump,
        subst: &HashMap<&'a str, &'a BaseTerm<'a>>,
    ) -> &'b BaseTerm<'b> {
        match self {
            BaseTerm::Const(_) => copy_base_term(bump, self),
            BaseTerm::Variable(v) => subst
                .get(v)
                .map_or(copy_base_term(bump, self), |b| copy_base_term(bump, b)),
            BaseTerm::ApplyFn(fun, args) => {
                let args: Vec<&'b BaseTerm<'b>> = args
                    .iter()
                    .map(|arg| arg.apply_subst(bump, subst))
                    .collect();
                copy_base_term(bump, &BaseTerm::ApplyFn(*fun, &args))
            }
        }
    }
}

impl<'a> std::fmt::Display for BaseTerm<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BaseTerm::Const(c) => write!(f, "{c}"),
            BaseTerm::Variable(v) => write!(f, "{v}"),
            BaseTerm::ApplyFn(FunctionSym { name: n, .. }, args) => write!(
                f,
                "{n}({})",
                args.iter()
                    .map(|x| x.to_string())
                    .collect::<Vec<_>>()
                    .join(",")
            ),
        }
    }
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Const<'a> {
    Name(&'a str),
    Bool(bool),
    Number(i64),
    Float(f64),
    String(&'a str),
    Bytes(&'a [u8]),
    List(&'a [&'a Const<'a>]),
    Map {
        keys: &'a [&'a Const<'a>],
        values: &'a [&'a Const<'a>],
    },
    Struct {
        fields: &'a [&'a str],
        values: &'a [&'a Const<'a>],
    },
}

impl<'a> Eq for Const<'a> {}

impl<'a> std::fmt::Display for Const<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match *self {
            Const::Name(v) => write!(f, "{v}"),
            Const::Bool(v) => write!(f, "{v}"),
            Const::Number(v) => write!(f, "{v}"),
            Const::Float(v) => write!(f, "{v}"),
            Const::String(v) => write!(f, "{v}"),
            Const::Bytes(v) => write!(f, "{:?}", v),
            Const::List(v) => write!(
                f,
                "[{}]",
                v.iter()
                    .map(|x| x.to_string())
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
            Const::Map { keys: _, values: _ } => write!(f, "{{...}}"),
            Const::Struct {
                fields: _,
                values: _,
            } => write!(f, "{{...}}"),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PredicateSym<'a> {
    pub name: &'a str,
    pub arity: Option<u8>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct FunctionSym<'a> {
    pub name: &'a str,
    pub arity: Option<u8>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Atom<'a> {
    pub sym: PredicateSym<'a>,

    pub args: &'a [&'a BaseTerm<'a>],
}

impl<'a> Atom<'a> {
    // A fact matches a query if there is a substitution s.t. subst(query) = fact.
    // We assume that self is a fact and query_args are the arguments of a query,
    // i.e. only variables and constants.
    pub fn matches(&'a self, query_args: &[&BaseTerm]) -> bool {
        for (fact_arg, query_arg) in self.args.iter().zip(query_args.iter()) {
            if let BaseTerm::Const(_) = query_arg {
                if fact_arg != query_arg {
                    return false;
                }
            }
        }
        true
    }

    pub fn apply_subst<'b>(
        &'a self,
        bump: &'b Bump,
        subst: &HashMap<&'a str, &'a BaseTerm<'a>>,
    ) -> &'b Atom<'b> {
        let args: Vec<&'b BaseTerm<'b>> = self
            .args
            .iter()
            .map(|arg| arg.apply_subst(bump, subst))
            .collect();
        let args = &*bump.alloc_slice_copy(&args);
        bump.alloc(Atom {
            sym: copy_predicate_sym(bump, self.sym),
            args,
        })
    }
}

impl<'a> std::fmt::Display for Atom<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}(", self.sym.name)?;
        for arg in self.args {
            write!(f, "{arg}")?;
        }
        write!(f, ")")
    }
}

pub fn copy_predicate_sym<'dest>(bump: &'dest Bump, p: PredicateSym) -> PredicateSym<'dest> {
    PredicateSym {
        name: bump.alloc_str(p.name),
        arity: p.arity,
    }
}

// Copies BaseTerm to another Bump
pub fn copy_atom<'dest, 'src>(bump: &'dest Bump, atom: &'src Atom<'src>) -> &'dest Atom<'dest> {
    let args: Vec<_> = atom
        .args
        .iter()
        .map(|arg| copy_base_term(bump, arg))
        .collect();
    let args = &*bump.alloc_slice_copy(&args);
    bump.alloc(Atom {
        sym: copy_predicate_sym(bump, atom.sym),
        args,
    })
}

// Copies BaseTerm to another Bump
pub fn copy_base_term<'dest, 'src>(
    bump: &'dest Bump,
    b: &'src BaseTerm<'src>,
) -> &'dest BaseTerm<'dest> {
    match b {
        BaseTerm::Const(c) =>
        // Should it be a reference?
        {
            bump.alloc(BaseTerm::Const(*copy_const(bump, c)))
        }
        BaseTerm::Variable(s) => bump.alloc(BaseTerm::Variable(bump.alloc_str(s))),
        BaseTerm::ApplyFn(fun, args) => {
            let fun = FunctionSym {
                name: bump.alloc_str(fun.name),
                arity: fun.arity,
            };
            let args: Vec<_> = args.iter().map(|a| copy_base_term(bump, a)).collect();
            let args = bump.alloc_slice_copy(&args);
            bump.alloc(BaseTerm::ApplyFn(fun, args))
        }
    }
}

// Copies Const to another Bump
pub fn copy_const<'dest, 'src>(bump: &'dest Bump, c: &'src Const<'src>) -> &'dest Const<'dest> {
    match c {
        Const::Name(name) => {
            let name = &*bump.alloc_str(name);
            bump.alloc(Const::Name(name))
        }
        Const::Bool(b) => bump.alloc(Const::Bool(*b)),
        Const::Number(n) => bump.alloc(Const::Number(*n)),
        Const::Float(f) => bump.alloc(Const::Float(*f)),
        Const::String(s) => {
            let s = &*bump.alloc_str(s);
            bump.alloc(Const::String(s))
        }
        Const::Bytes(b) => {
            let b = &*bump.alloc_slice_copy(b);
            bump.alloc(Const::Bytes(b))
        }
        Const::List(cs) => {
            let cs: Vec<_> = cs.iter().map(|c| copy_const(bump, c)).collect();
            let cs = &*bump.alloc_slice_copy(&cs);
            bump.alloc(Const::List(cs))
        }
        Const::Map { keys, values } => {
            let keys: Vec<_> = keys.iter().map(|c| copy_const(bump, c)).collect();
            let keys = &*bump.alloc_slice_copy(&keys);

            let values: Vec<_> = values.iter().map(|c| copy_const(bump, c)).collect();
            let values = &*bump.alloc_slice_copy(&values);

            bump.alloc(Const::Map { keys, values })
        }
        Const::Struct { fields, values } => {
            let fields: Vec<_> = fields.iter().map(|s| &*bump.alloc_str(s)).collect();
            let fields = &*bump.alloc_slice_copy(&fields);

            let values: Vec<_> = values.iter().map(|c| copy_const(bump, c)).collect();
            let values = &*bump.alloc_slice_copy(&values);

            bump.alloc(Const::Struct { fields, values })
        }
    }
}

pub fn copy_transform<'dest, 'src>(
    bump: &'dest Bump,
    stmt: &'src TransformStmt<'src>,
) -> &'dest TransformStmt<'dest> {
    let TransformStmt { var, app } = stmt;
    let var = var.map(|s| &*bump.alloc_str(s));
    let app = copy_base_term(bump, app);
    bump.alloc(TransformStmt { var, app })
}

pub fn copy_clause<'dest, 'src>(
    bump: &'dest Bump,
    clause: &'src Clause<'src>,
) -> &'dest Clause<'dest> {
    let Clause {
        head,
        premises,
        transform,
    } = clause;
    let premises: Vec<_> = premises.iter().map(|x| copy_term(bump, x)).collect();
    let transform: Vec<_> = transform.iter().map(|x| copy_transform(bump, x)).collect();
    bump.alloc(Clause {
        head: copy_atom(bump, head),
        premises: &*bump.alloc_slice_copy(&premises),
        transform: &*bump.alloc_slice_copy(&transform),
    })
}

fn copy_term<'dest, 'src>(bump: &'dest Bump, term: &'src Term<'src>) -> &'dest Term<'dest> {
    match term {
        Term::Atom(atom) => {
            let atom = copy_atom(bump, atom);
            bump.alloc(Term::Atom(atom))
        }
        Term::NegAtom(atom) => {
            let atom = copy_atom(bump, atom);
            bump.alloc(Term::NegAtom(atom))
        }
        Term::Eq(left, right) => {
            let left = copy_base_term(bump, left);
            let right = copy_base_term(bump, right);
            bump.alloc(Term::Eq(left, right))
        }
        Term::Ineq(left, right) => {
            let left = copy_base_term(bump, left);
            let right = copy_base_term(bump, right);
            bump.alloc(Term::Ineq(left, right))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bumpalo::Bump;

    #[test]
    fn it_works() {
        let bump = Bump::new();
        let foo = &*bump.alloc(BaseTerm::Const(Const::Name("/foo")));
        let bar = bump.alloc(PredicateSym {
            name: "bar",
            arity: Some(1),
        });
        let bar_args = bump.alloc_slice_copy(&[foo]);
        let head = bump.alloc(Atom {
            sym: *bar,
            args: &*bar_args,
        });
        assert_eq!("bar(/foo)", head.to_string());
    }
}