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
//! This file contains the typed AST.

use crate::data_structures::OrderedMap;
use proc_macro2::Ident;
use quote::ToTokens;
use std::fmt;

/// The predicate kind regarding IO.
#[derive(Debug, PartialEq, Clone, Eq, Hash)]
pub enum PredicateKind {
    /// Instances of this predicate can be provided only as input facts.
    Input,
    /// Instances of this predicate can be used for computation but cannot be output.
    Internal,
    /// Instances of this predicate can be used for computation and also can be output.
    Output,
}

impl fmt::Display for PredicateKind {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            PredicateKind::Input => write!(f, "input"),
            PredicateKind::Internal => write!(f, "internal"),
            PredicateKind::Output => write!(f, "output"),
        }
    }
}

/// Parameter information of the predicate declaration.
#[derive(Clone)]
pub struct ParamDecl {
    pub name: Ident,
    pub typ: syn::Type,
}

impl fmt::Debug for ParamDecl {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}: {}", self.name, self.typ.to_token_stream())
    }
}

impl fmt::Display for ParamDecl {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}: {}", self.name, self.typ.to_token_stream())
    }
}

impl PartialEq for ParamDecl {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
    }
}

impl Eq for ParamDecl {}

impl ParamDecl {
    pub fn typ_as_string(&self) -> String {
        self.typ.to_token_stream().to_string()
    }
}

/// A declaration of the predicate.
///
/// ```plain
/// input Input(x: u32, y: u32)
/// internal Internal(x: u32, y: u32)
/// output Output(x: u32, y: u32)
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PredicateDecl {
    pub kind: PredicateKind,
    pub name: Ident,
    pub parameters: Vec<ParamDecl>,
}

impl fmt::Display for PredicateDecl {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} {}(", self.kind, self.name)?;
        let mut first = true;
        for parameter in &self.parameters {
            if first {
                first = false;
            } else {
                write!(f, ", ")?;
            }
            write!(f, "{}", parameter)?;
        }
        write!(f, ")")
    }
}

/// An argument.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Arg {
    /// Identifier `arg`.
    Ident(Ident),
    /// Wildcard argument.
    Wildcard,
}

impl Arg {
    pub fn to_ident(&self) -> syn::Ident {
        match self {
            Arg::Ident(ident) => ident.clone(),
            Arg::Wildcard => syn::Ident::new("_", proc_macro2::Span::call_site()),
        }
    }
    pub fn is_wildcard(&self) -> bool {
        match self {
            Arg::Ident(_) => false,
            Arg::Wildcard => true,
        }
    }
}

impl fmt::Display for Arg {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Arg::Ident(ident) => write!(f, "{}", ident),
            Arg::Wildcard => write!(f, "_"),
        }
    }
}

/// A richer type of atom, which can be negated, and used as
/// premises/hypotheses in rules.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Literal {
    pub is_negated: bool,
    pub predicate: Ident,
    pub args: Vec<Arg>,
}

impl fmt::Display for Literal {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if self.is_negated {
            write!(f, "!")?;
        }
        write!(f, "{}(", self.predicate)?;
        let mut first = true;
        for arg in &self.args {
            if first {
                first = false;
            } else {
                write!(f, ", ")?;
            }
            write!(f, "{}", arg)?;
        }
        write!(f, ")")
    }
}

/// A head of a rule.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuleHead {
    pub predicate: Ident,
    pub args: Vec<Ident>,
}

impl fmt::Display for RuleHead {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}(", self.predicate)?;
        let mut first = true;
        for arg in &self.args {
            if first {
                first = false;
            } else {
                write!(f, ", ")?;
            }
            write!(f, "{}", arg)?;
        }
        write!(f, ")")
    }
}

/// A rule describing how to derive new facts.
///
/// ```plain
/// Internal(x, y) :- Input(x, y).
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Rule {
    pub head: RuleHead,
    pub body: Vec<Literal>,
}

impl fmt::Display for Rule {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} :- ", self.head)?;
        let mut first = true;
        for literal in &self.body {
            if first {
                first = false;
            } else {
                write!(f, ", ")?;
            }
            write!(f, "{}", literal)?;
        }
        write!(f, ".")
    }
}

/// A Datalog program.
#[derive(Debug, Clone)]
pub struct Program {
    pub decls: OrderedMap<String, PredicateDecl>,
    pub rules: Vec<Rule>,
}