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
//! Semantic resolver (name resolution, type checking and lowering to RQ)

pub mod ast_expand;
mod eval;
mod lowering;
mod module;
pub mod reporting;
mod resolver;

use anyhow::Result;
use itertools::Itertools;
use std::path::PathBuf;

use self::resolver::Resolver;
pub use self::resolver::ResolverOptions;
pub use eval::eval;
pub use lowering::lower_to_ir;

use crate::ir::constant::ConstExpr;
use crate::ir::decl::{Module, RootModule};
use crate::ir::pl::{self, Expr, ModuleDef, Stmt, StmtKind, TypeDef, VarDef};
use crate::ir::rq::RelationalQuery;
use crate::WithErrorInfo;
use crate::{Error, Reason, SourceTree};

/// Runs semantic analysis on the query and lowers PL to RQ.
pub fn resolve_and_lower(
    file_tree: SourceTree<Vec<prqlc_ast::stmt::Stmt>>,
    main_path: &[String],
    database_module_path: Option<&[String]>,
) -> Result<RelationalQuery> {
    let root_mod = resolve(file_tree, Default::default())?;

    let default_db = [NS_DEFAULT_DB.to_string()];
    let database_module_path = database_module_path.unwrap_or(&default_db);
    let (query, _) = lowering::lower_to_ir(root_mod, main_path, database_module_path)?;
    Ok(query)
}

/// Runs semantic analysis on the query.
pub fn resolve(
    file_tree: SourceTree<Vec<prqlc_ast::stmt::Stmt>>,
    options: ResolverOptions,
) -> Result<RootModule> {
    let root_module_def = compose_module_tree(file_tree)?;

    // expand AST into PL
    let root_module_def = ast_expand::expand_module_def(root_module_def)?;

    // init new root module
    let mut root_module = RootModule {
        module: Module::new_root(),
        ..Default::default()
    };
    let mut resolver = Resolver::new(&mut root_module, options);

    // resolve the module def into the root module
    resolver.fold_statements(root_module_def.stmts)?;

    Ok(root_module)
}

pub fn compose_module_tree(
    mut tree: SourceTree<Vec<prqlc_ast::stmt::Stmt>>,
) -> Result<prqlc_ast::stmt::ModuleDef> {
    // inject std module if it does not exist
    if !tree.sources.contains_key(&PathBuf::from("std.prql")) {
        let mut source_tree = SourceTree {
            sources: Default::default(),
            source_ids: tree.source_ids.clone(),
            root: None,
        };
        load_std_lib(&mut source_tree);
        let ast = crate::parser::parse(&source_tree).unwrap();
        let (path, content) = ast.sources.into_iter().next().unwrap();
        tree.insert(path, content);
    }

    // find root
    let root_path = PathBuf::from("");
    if tree.sources.get(&root_path).is_none() {
        if tree.sources.len() == 1 {
            // if there is only one file, use that as the root
            let (_, only) = tree.sources.drain().exactly_one().unwrap();
            tree.sources.insert(root_path, only);
        } else if let Some(root) = tree.sources.keys().find(path_starts_with_uppercase) {
            // if there is a path that starts with an uppercase, that's the root
            let root = tree.sources.remove(&root.clone()).unwrap();
            tree.sources.insert(root_path, root);
        } else {
            let file_names = tree
                .sources
                .keys()
                .map(|p| format!(" - {}", p.to_str().unwrap_or_default()))
                .sorted()
                .join("\n");

            return Err(Error::new_simple(format!(
                "Cannot find the root module within the following files:\n{file_names}"
            ))
            .push_hint("add a file prefixed with `_` to the root directory")
            .with_code("E0002")
            .into());
        }
    }

    // prepare paths and sort
    let mut sources: Vec<_> = Vec::with_capacity(tree.sources.len());
    for (path, stmts) in tree.sources {
        let path = os_path_to_prql_path(path)?;
        sources.push((path, stmts));
    }

    // ad-hoc sorting to get std to the last place
    // TODO: this should be figured out using references between modules and toposort
    sources.sort_by_key(|(path, _)| path.join("."));
    sources.reverse();

    // insert all sources into root module
    let mut root = prqlc_ast::stmt::ModuleDef {
        name: "Project".to_string(),
        stmts: Vec::new(),
    };

    fn insert_module_def(
        module: &mut prqlc_ast::stmt::ModuleDef,
        mut path: Vec<String>,
        stmts: Vec<prqlc_ast::stmt::Stmt>,
    ) {
        if path.is_empty() {
            module.stmts.extend(stmts);
        } else {
            let step = path.remove(0);

            // find submodule def
            let submodule = module
                .stmts
                .iter_mut()
                .find(|x| x.kind.as_module_def().map_or(false, |x| x.name == step));
            let submodule = if let Some(sm) = submodule {
                sm
            } else {
                // insert new module def
                module.stmts.push(prqlc_ast::stmt::Stmt::new(
                    prqlc_ast::stmt::StmtKind::ModuleDef(prqlc_ast::stmt::ModuleDef {
                        name: step,
                        stmts: Vec::new(),
                    }),
                ));
                module.stmts.last_mut().unwrap()
            };
            let submodule = submodule.kind.as_module_def_mut().unwrap();

            insert_module_def(submodule, path, stmts);
        }
    }
    for (path, stmts) in sources {
        insert_module_def(&mut root, path, stmts);
    }

    // TODO: make sure that the module tree is normalized

    // TODO: find correct resolution order
    // TODO: recursive references

    Ok(root)
}

/// Preferred way of injecting std module.
pub fn load_std_lib(source_tree: &mut SourceTree) {
    let path = PathBuf::from("std.prql");
    let content = include_str!("./std.prql");

    source_tree.insert(path, content.to_string());
}

pub fn os_path_to_prql_path(path: PathBuf) -> Result<Vec<String>> {
    // remove file format extension
    let path = path.with_extension("");

    // split by /
    path.components()
        .map(|x| {
            x.as_os_str()
                .to_str()
                .ok_or_else(|| anyhow::anyhow!("Invalid file path: {path:?}"))
                .map(str::to_string)
        })
        .try_collect()
}

fn path_starts_with_uppercase(p: &&PathBuf) -> bool {
    p.components()
        .next()
        .and_then(|x| x.as_os_str().to_str())
        .and_then(|x| x.chars().next())
        .map_or(false, |x| x.is_uppercase())
}

pub fn static_eval(expr: Expr, root_mod: &mut RootModule) -> Result<ConstExpr> {
    let mut resolver = Resolver::new(root_mod, ResolverOptions::default());

    resolver.static_eval_to_constant(expr)
}

pub fn is_ident_or_func_call(expr: &pl::Expr, name: &prqlc_ast::Ident) -> bool {
    match &expr.kind {
        pl::ExprKind::Ident(i) if i == name => true,
        pl::ExprKind::FuncCall(pl::FuncCall { name: n_expr, .. })
            if n_expr.kind.as_ident().map_or(false, |i| i == name) =>
        {
            true
        }
        _ => false,
    }
}

pub const NS_STD: &str = "std";
pub const NS_THIS: &str = "this";
pub const NS_THAT: &str = "that";
pub const NS_PARAM: &str = "_param";
pub const NS_DEFAULT_DB: &str = "default_db";
pub const NS_QUERY_DEF: &str = "prql";
pub const NS_MAIN: &str = "main";

// refers to the containing module (direct parent)
pub const NS_SELF: &str = "_self";

// implies we can infer new non-module declarations in the containing module
pub const NS_INFER: &str = "_infer";

// implies we can infer new module declarations in the containing module
pub const NS_INFER_MODULE: &str = "_infer_module";

pub const NS_GENERIC: &str = "_generic";

impl Stmt {
    pub fn new(kind: StmtKind) -> Stmt {
        Stmt {
            id: None,
            kind,
            span: None,
            annotations: Vec::new(),
        }
    }

    pub(crate) fn name(&self) -> &str {
        match &self.kind {
            StmtKind::QueryDef(_) => NS_QUERY_DEF,
            StmtKind::VarDef(VarDef { name, .. }) => name,
            StmtKind::TypeDef(TypeDef { name, .. }) => name,
            StmtKind::ModuleDef(ModuleDef { name, .. }) => name,
        }
    }
}

impl pl::Expr {
    fn try_cast<T, F, S2: ToString>(self, f: F, who: Option<&str>, expected: S2) -> Result<T, Error>
    where
        F: FnOnce(pl::ExprKind) -> Result<T, pl::ExprKind>,
    {
        f(self.kind).map_err(|i| {
            Error::new(Reason::Expected {
                who: who.map(|s| s.to_string()),
                expected: expected.to_string(),
                found: format!("`{}`", write_pl(pl::Expr::new(i))),
            })
            .with_span(self.span)
        })
    }
}

/// Write a PL IR to string.
///
/// Because PL needs to be restricted back to AST, ownerships of expr is required.
pub fn write_pl(expr: pl::Expr) -> String {
    let expr = ast_expand::restrict_expr(expr);

    crate::codegen::write_expr(&expr)
}
#[cfg(test)]
pub mod test {
    use anyhow::Result;
    use insta::assert_yaml_snapshot;

    use crate::ir::rq::RelationalQuery;
    use crate::parser::parse;

    use super::{resolve, resolve_and_lower, RootModule};

    pub fn parse_resolve_and_lower(query: &str) -> Result<RelationalQuery> {
        let source_tree = query.into();
        resolve_and_lower(parse(&source_tree)?, &[], None)
    }

    pub fn parse_and_resolve(query: &str) -> Result<RootModule> {
        let source_tree = query.into();
        resolve(parse(&source_tree)?, Default::default())
    }

    #[test]
    fn test_resolve_01() {
        assert_yaml_snapshot!(parse_resolve_and_lower(r###"
        from employees
        select !{foo}
        "###).unwrap().relation.columns, @r###"
        ---
        - Wildcard
        "###)
    }

    #[test]
    fn test_resolve_02() {
        assert_yaml_snapshot!(parse_resolve_and_lower(r###"
        from foo
        sort day
        window range:-4..4 (
            derive {next_four_days = sum b}
        )
        "###).unwrap().relation.columns, @r###"
        ---
        - Single: day
        - Single: b
        - Wildcard
        - Single: next_four_days
        "###)
    }

    #[test]
    fn test_resolve_03() {
        assert_yaml_snapshot!(parse_resolve_and_lower(r###"
        from a=albums
        filter is_sponsored
        select {a.*}
        "###).unwrap().relation.columns, @r###"
        ---
        - Single: is_sponsored
        - Wildcard
        "###)
    }

    #[test]
    fn test_resolve_04() {
        assert_yaml_snapshot!(parse_resolve_and_lower(r###"
        from x
        select {a, a, a = a + 1}
        "###).unwrap().relation.columns, @r###"
        ---
        - Single: ~
        - Single: ~
        - Single: a
        "###)
    }

    #[test]
    fn test_header() {
        assert_yaml_snapshot!(parse_resolve_and_lower(r#"
        prql target:sql.mssql version:"0"

        from employees
        "#).unwrap(), @r###"
        ---
        def:
          version: ^0
          other:
            target: sql.mssql
        tables:
          - id: 0
            name: ~
            relation:
              kind:
                ExternRef:
                  - employees
              columns:
                - Wildcard
        relation:
          kind:
            Pipeline:
              - From:
                  source: 0
                  columns:
                    - - Wildcard
                      - 0
                  name: employees
              - Select:
                  - 0
          columns:
            - Wildcard
        "### );

        assert!(parse_resolve_and_lower(
            r###"
        prql target:sql.bigquery version:foo
        from employees
        "###,
        )
        .is_err());

        assert!(parse_resolve_and_lower(
            r#"
        prql target:sql.bigquery version:"25"
        from employees
        "#,
        )
        .is_err());

        assert!(parse_resolve_and_lower(
            r###"
        prql target:sql.yah version:foo
        from employees
        "###,
        )
        .is_err());
    }
}