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
use std::collections::{HashMap, HashSet};
use anyhow::{bail, Result};
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use crate::ast::pl::{Expr, Ident};
use crate::ast::rq::RelationColumn;
use super::context::{Decl, DeclKind, TableDecl};
use super::{Frame, FrameColumn};
pub const NS_STD: &str = "std";
pub const NS_FRAME: &str = "_frame";
pub const NS_FRAME_RIGHT: &str = "_right";
pub const NS_PARAM: &str = "_param";
pub const NS_DEFAULT_DB: &str = "default_db";
pub const NS_SELF: &str = "_self";
pub const NS_INFER: &str = "_infer";
#[derive(Default, Serialize, Deserialize, Clone)]
pub struct Module {
pub(super) names: HashMap<String, Decl>,
pub redirects: Vec<Ident>,
pub shadowed: Option<Box<Decl>>,
}
impl Module {
pub fn singleton<S: ToString>(name: S, entry: Decl) -> Module {
Module {
names: HashMap::from([(name.to_string(), entry)]),
..Default::default()
}
}
pub fn new() -> Module {
Module {
names: HashMap::from([
(
"default_db".to_string(),
Decl::from(DeclKind::Module(Module {
names: HashMap::from([(
NS_INFER.to_string(),
Decl::from(DeclKind::Infer(Box::new(DeclKind::TableDecl(TableDecl {
columns: vec![RelationColumn::Wildcard],
expr: None,
})))),
)]),
shadowed: None,
redirects: vec![],
})),
),
(NS_STD.to_string(), Decl::from(DeclKind::default())),
]),
shadowed: None,
redirects: vec![
Ident::from_name(NS_FRAME),
Ident::from_name(NS_FRAME_RIGHT),
Ident::from_name(NS_PARAM),
Ident::from_name(NS_STD),
],
}
}
pub fn insert(&mut self, ident: Ident, entry: Decl) -> Result<Option<Decl>> {
let mut ns = self;
for part in ident.path {
let entry = ns.names.entry(part.clone()).or_default();
match &mut entry.kind {
DeclKind::Module(inner) => {
ns = inner;
}
_ => bail!("path does not resolve to a module or a table"),
}
}
Ok(ns.names.insert(ident.name, entry))
}
pub fn get_mut(&mut self, ident: &Ident) -> Option<&mut Decl> {
let mut ns = self;
for part in &ident.path {
let entry = ns.names.get_mut(part);
match entry {
Some(Decl {
kind: DeclKind::Module(inner),
..
}) => {
ns = inner;
}
_ => return None,
}
}
ns.names.get_mut(&ident.name)
}
pub fn get(&self, fq_ident: &Ident) -> Option<&Decl> {
let mut ns = self;
for (index, part) in fq_ident.path.iter().enumerate() {
let decl = ns.names.get(part);
if let Some(decl) = decl {
match &decl.kind {
DeclKind::Module(inner) => {
ns = inner;
}
DeclKind::LayeredModules(stack) => {
let next = fq_ident.path.get(index + 1).unwrap_or(&fq_ident.name);
let mut found = false;
for n in stack.iter().rev() {
if n.names.contains_key(next) {
ns = n;
found = true;
break;
}
}
if !found {
return None;
}
}
_ => return None,
}
} else {
return None;
}
}
ns.names.get(&fq_ident.name)
}
pub fn lookup(&self, ident: &Ident) -> HashSet<Ident> {
fn lookup_in(module: &Module, ident: Ident) -> HashSet<Ident> {
let (prefix, ident) = ident.pop_front();
if let Some(ident) = ident {
if let Some(entry) = module.names.get(&prefix) {
let redirected = match &entry.kind {
DeclKind::Module(ns) => ns.lookup(&ident),
DeclKind::LayeredModules(stack) => {
let mut r = HashSet::new();
for ns in stack.iter().rev() {
r = ns.lookup(&ident);
if !r.is_empty() {
break;
}
}
r
}
_ => HashSet::new(),
};
return redirected
.into_iter()
.map(|i| Ident::from_name(&prefix) + i)
.collect();
}
} else if let Some(decl) = module.names.get(&prefix) {
if let DeclKind::Module(inner) = &decl.kind {
if inner.names.contains_key(NS_SELF) {
return HashSet::from([Ident::from_path(vec![
prefix,
NS_SELF.to_string(),
])]);
}
}
return HashSet::from([Ident::from_name(prefix)]);
}
HashSet::new()
}
log::trace!("lookup {ident}");
let mut res = HashSet::new();
res.extend(lookup_in(self, ident.clone()));
for redirect in &self.redirects {
log::trace!("... following redirect {redirect}");
res.extend(lookup_in(self, redirect.clone() + ident.clone()));
}
res
}
pub(super) fn insert_frame(&mut self, frame: &Frame, namespace: &str) {
let namespace = self.names.entry(namespace.to_string()).or_default();
let namespace = namespace.kind.as_module_mut().unwrap();
for (col_index, column) in frame.columns.iter().enumerate() {
let input_name = match column {
FrameColumn::All { input_name, .. } => Some(input_name),
FrameColumn::Single { name, .. } => name.as_ref().and_then(|n| n.path.first()),
};
let ns;
if let Some(input_name) = input_name {
let entry = match namespace.names.get_mut(input_name) {
Some(x) => x,
None => {
namespace.redirects.push(Ident::from_name(input_name));
let input = frame.find_input(input_name).unwrap();
let mut sub_ns = Module::default();
if let Some(fq_table) = input.table.clone() {
let self_decl = Decl {
declared_at: Some(input.id),
kind: DeclKind::InstanceOf(fq_table),
order: 0,
};
sub_ns.names.insert(NS_SELF.to_string(), self_decl);
}
let sub_ns = Decl {
declared_at: Some(input.id),
kind: DeclKind::Module(sub_ns),
order: 0,
};
namespace.names.entry(input_name.clone()).or_insert(sub_ns)
}
};
ns = entry.kind.as_module_mut().unwrap()
} else {
ns = namespace;
}
match column {
FrameColumn::All { input_name, .. } => {
let input = frame.inputs.iter().find(|i| &i.name == input_name).unwrap();
let kind = DeclKind::Infer(Box::new(DeclKind::Column(input.id)));
let declared_at = Some(input.id);
let decl = Decl {
kind,
declared_at,
order: col_index + 1,
};
ns.names.insert(NS_INFER.to_string(), decl);
}
FrameColumn::Single {
name: Some(name),
expr_id,
} => {
let decl = Decl {
kind: DeclKind::Column(*expr_id),
declared_at: None,
order: col_index + 1,
};
ns.names.insert(name.name.clone(), decl);
}
_ => {}
}
}
}
pub(super) fn insert_frame_col(&mut self, namespace: &str, name: String, id: usize) {
let namespace = self.names.entry(namespace.to_string()).or_default();
let namespace = namespace.kind.as_module_mut().unwrap();
namespace.names.insert(name, DeclKind::Column(id).into());
}
pub fn shadow(&mut self, ident: &str) {
let shadowed = self.names.remove(ident).map(Box::new);
let entry = DeclKind::Module(Module {
shadowed,
..Default::default()
});
self.names.insert(ident.to_string(), entry.into());
}
pub fn unshadow(&mut self, ident: &str) {
if let Some(entry) = self.names.remove(ident) {
let ns = entry.kind.into_module().unwrap();
if let Some(shadowed) = ns.shadowed {
self.names.insert(ident.to_string(), *shadowed);
}
}
}
pub fn stack_push(&mut self, ident: &str, namespace: Module) {
let entry = self
.names
.entry(ident.to_string())
.or_insert_with(|| DeclKind::LayeredModules(Vec::new()).into());
let stack = entry.kind.as_layered_modules_mut().unwrap();
stack.push(namespace);
}
pub fn stack_pop(&mut self, ident: &str) -> Option<Module> {
(self.names.get_mut(ident))
.and_then(|e| e.kind.as_layered_modules_mut())
.and_then(|stack| stack.pop())
}
pub(crate) fn into_exprs(self) -> HashMap<String, Expr> {
self.names
.into_iter()
.map(|(k, v)| (k, *v.kind.into_expr().unwrap()))
.collect()
}
pub(crate) fn from_exprs(exprs: HashMap<String, Expr>) -> Module {
Module {
names: exprs
.into_iter()
.map(|(key, expr)| {
let decl = Decl {
kind: DeclKind::Expr(Box::new(expr)),
..Default::default()
};
(key, decl)
})
.collect(),
..Default::default()
}
}
pub fn as_decls(&self) -> Vec<(Ident, &Decl)> {
let mut r = Vec::new();
for (name, decl) in &self.names {
match &decl.kind {
DeclKind::Module(module) => r.extend(
module
.as_decls()
.into_iter()
.map(|(inner, decl)| (Ident::from_name(name) + inner, decl)),
),
_ => r.push((Ident::from_name(name), decl)),
}
}
r
}
}
impl std::fmt::Debug for Module {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut ds = f.debug_struct("Namespace");
if !self.redirects.is_empty() {
let aliases = self.redirects.iter().map(|x| x.to_string()).collect_vec();
ds.field("aliases", &aliases);
}
if self.names.len() < 10 {
ds.field("names", &self.names);
} else {
ds.field("names", &format!("... {} entries ...", self.names.len()));
}
if let Some(f) = &self.shadowed {
ds.field("shadowed", f);
}
ds.finish()
}
}