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
//! Rustre compiler driver
//!
//! It is built around [yeter].

pub mod checks;
pub mod diagnostics;
pub mod eval;
pub mod id;
pub mod name_resolution;
pub mod node_state;
pub mod static_args;
mod types;

use crate::id::IdRef;
use crate::static_args::StaticArgs;
use crate::{
    diagnostics::{Diagnostic, Level, Span},
    types::check_node_equations,
};
use rustre_parser::ast::{
    AstNode, AstToken, Ident, NodeNode, NodeProfileNode, ParamsNode, Root, TypedIdsNode,
};
use std::path::PathBuf;
use std::rc::Rc;
use yeter::Database;

/// Builds a new compiler driver, that corresponds to a compilation session
pub fn driver() -> Database {
    Database::new()
}

// Inputs
// TODO: maybe they should be moved to their own module

#[derive(Clone, Hash)]
pub struct SourceFile {
    pub path: PathBuf,
    pub text: String,
}

impl SourceFile {
    pub fn new(path: PathBuf, text: String) -> SourceFile {
        SourceFile { path, text }
    }
}

#[derive(Clone, Debug, Hash)]
pub struct Signature {
    pub name: Option<Ident>,
    pub params: Vec<TypedIdsNode>,
    pub return_params: Vec<TypedIdsNode>,
}

impl Signature {
    pub fn from_name(name: Option<Ident>) -> Self {
        Self {
            name,
            params: Default::default(),
            return_params: Default::default(),
        }
    }

    #[inline]
    pub fn with_params(
        mut self,
        params: Vec<TypedIdsNode>,
        return_params: Vec<TypedIdsNode>,
    ) -> Self {
        self.params = params;
        self.return_params = return_params;
        self
    }
}

#[derive(Clone, Debug, Hash)]
pub struct TypedSignature {
    pub name: Option<Ident>,
    pub params: Vec<(Ident, types::Type)>,
    pub return_params: Vec<(Ident, types::Type)>,
}

impl TypedSignature {
    pub fn from_name(name: Option<Ident>) -> Self {
        Self {
            name,
            params: Default::default(),
            return_params: Default::default(),
        }
    }

    #[inline]
    pub fn with_params(
        mut self,
        params: Vec<(Ident, types::Type)>,
        return_params: Vec<(Ident, types::Type)>,
    ) -> Self {
        self.params = params;
        self.return_params = return_params;
        self
    }
}

/// **Query**: Parses a given file
#[yeter::query]
pub fn parse_file(db: &Database, file: SourceFile) -> Root {
    let source = file.text;

    let (root, errors) = rustre_parser::parse(&source);
    for error in errors {
        let span = Span {
            file: file.path.clone(),
            start: error.span.start,
            end: error.span.end,
        };

        Diagnostic::new(Level::Error, "parsing error")
            .with_attachment(span, error.msg)
            .emit(db);
    }

    root
}

/// **Query**: Returns a list of all directly and indirectly included files in the Lustre program
#[yeter::query]
pub fn files(_db: &Database) -> Option<Vec<SourceFile>>;

#[yeter::query]
fn parsed_files(db: &Database) -> Vec<Rc<Root>> {
    let files = files(db);
    if let Some(files) = files.as_ref() {
        files
            .iter()
            .map(|s| parse_file(db, s.clone()))
            .collect::<Vec<_>>()
    } else {
        vec![]
    }
}

#[yeter::query]
pub fn get_signature(db: &Database, node: NodeNode) -> Signature {
    let signature = Signature::from_name(node.id_node().and_then(|id| id.ident()));

    if node.equal().is_some() {
        if let Some(alias) = node.alias() {
            if let Some(alias_name) = alias.id_ref_node() {
                let id_ref = IdRef::from(alias_name);
                let alias_node = name_resolution::find_node(db, &None, id_ref)
                    .as_ref()
                    .clone()
                    .unwrap(); // TODO

                return Signature::clone(&get_signature(db, alias_node));
            }
        }

        return signature;
    }

    let sig = node.node_profile_node();

    let get_params = |f: fn(&NodeProfileNode) -> Option<ParamsNode>| {
        sig.clone()
            .and_then(|sig| f(&sig))
            .and_then(|p| p.all_var_decl_node().next())
            .iter()
            .flat_map(|v| v.all_typed_ids_node())
            .collect::<Vec<_>>()
    };

    signature.with_params(
        get_params(NodeProfileNode::params),
        get_params(NodeProfileNode::return_params),
    )
}

#[yeter::query]
pub fn get_typed_signature<'a>(
    db: &Database,
    callee_static_args: &'a StaticArgs,
    node: NodeNode,
) -> TypedSignature {
    let signature = TypedSignature::from_name(node.id_node().and_then(|id| id.ident()));

    if node.equal().is_some() {
        if let Some(alias) = node.alias() {
            if let Some(alias_name) = alias.id_ref_node() {
                let id_ref = IdRef::from(alias_name);
                let alias_node = name_resolution::find_node(db, &None, id_ref)
                    .as_ref()
                    .clone()
                    .unwrap(); // TODO

                let static_args = static_args::static_args_of_effective_node(
                    db,
                    Some(callee_static_args.clone()),
                    Some(node),
                    alias_node.clone(),
                    alias.static_args_node(),
                );

                let Some(static_args) = static_args.as_ref().as_ref() else {
                    Diagnostic::new(Level::Error, "cannot evaluate static arguments")
                        .with_attachment(
                            Span::of_node(db, alias.static_args_node().unwrap().syntax()),
                            "cannot evaluate",
                        )
                        .emit(db);

                    return TypedSignature::clone(&get_typed_signature(
                        db,
                        &StaticArgs::default(),
                        alias_node,
                    ));
                };

                check_node_equations(db, static_args.clone(), alias_node.clone());
                return TypedSignature::clone(&get_typed_signature(db, static_args, alias_node));
            }
        }

        return signature;
    }

    let sig = get_signature(db, node);

    let get_params = |params: &[TypedIdsNode]| {
        params
            .iter()
            .flat_map(|group| {
                let ty = group
                    .type_node()
                    .map(|t| types::type_of_ast_type(db, Some(callee_static_args.clone()), None, t))
                    .unwrap_or_default();

                group
                    .all_id_node()
                    .map(|id| id.ident().unwrap())
                    .zip(std::iter::repeat(ty.as_ref().clone()))
            })
            .collect::<Vec<_>>()
    };

    signature.with_params(get_params(&sig.params), get_params(&sig.return_params))
}

/// **Query:** Global program check
#[yeter::query]
pub fn check(db: &Database) {
    let files = parsed_files(db);
    for file in files.as_slice() {
        for node in file.all_node_node() {
            let static_params = static_args::static_params_of_node(db, node.clone());
            // We can't type-check a node with static params, each "instanciation" will have to be
            // verified individually.
            if static_params.is_empty() {
                let _ = get_typed_signature(db, &StaticArgs::default(), node.clone());
                let _name = node.id_node().unwrap().ident().unwrap();
                let _name = _name.text();
                let _ = check_node_equations(db, StaticArgs::default(), node.clone());
                // TODO better handling of state in nodes with static params
                node_state::check_node_function_state(db, node.clone(), &StaticArgs::default());
            }

            checks::check_arity(db, node);
        }
    }
}

/// Adds a source file to the list of files that are known by the compiler
pub fn add_source_file(db: &Database, path: PathBuf) {
    let contents = std::fs::read_to_string(&path).unwrap(); // TODO: report the error
    let file = SourceFile::new(path, contents);
    let files = files(db);
    let mut files = Option::clone(&files).unwrap_or_default();
    files.push(file);
    db.set::<files>((), Some(files));
}

pub fn add_source_contents(db: &mut Database, contents: String) {
    let file = SourceFile::new(PathBuf::new(), contents);
    let files = files(db);
    let mut files = Option::clone(&files).unwrap_or_default();
    files.push(file);
    db.set::<files>((), Some(files));
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    #[test]
    fn parse_query() {
        let driver = super::driver();
        super::add_source_file(&driver, Path::new("../tests/stable.lus").to_owned());
        let files = super::files(&driver);
        let files = files.as_ref().as_deref().unwrap_or_default();
        for file in files {
            let ast = super::parse_file(&driver, file.clone());
            assert_eq!(ast.all_include_statement().count(), 1);
        }
    }
}