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
use super::{
ast::{ComponentDef, NamespaceDef},
parser,
};
use crate::LibrarySignatures;
use calyx_utils::{CalyxResult, Error, WithPos};
use std::{
collections::HashSet,
path::{Path, PathBuf},
};
const COMPILE_LIB: &str = include_str!("../resources/compile.futil");
#[derive(Default)]
pub struct Workspace {
pub components: Vec<ComponentDef>,
pub declarations: Vec<ComponentDef>,
pub lib: LibrarySignatures,
pub original_imports: Vec<String>,
pub metadata: Option<String>,
}
impl Workspace {
fn canonicalize_import<S>(
import: S,
parent: &Path,
lib_path: &Path,
) -> CalyxResult<PathBuf>
where
S: AsRef<Path> + Clone + WithPos,
{
let absolute_import = import.as_ref();
if absolute_import.is_absolute() && absolute_import.exists() {
return Ok(import.as_ref().to_path_buf());
}
let relative_import = parent.join(import.clone());
if relative_import.exists() {
return Ok(relative_import);
}
let library_import = lib_path.join(import.clone());
if library_import.exists() {
return Ok(library_import);
}
Err(Error::invalid_file(
format!("Import path `{}` found neither as an absolute path, nor in the parent ({}), nor in library path ({})",
import.as_ref().to_string_lossy(),
parent.to_string_lossy(),
lib_path.to_string_lossy()
)).with_pos(&import))
}
#[cfg(not(target_arch = "wasm32"))]
fn canonicalize_extern<S>(
extern_path: S,
parent: &Path,
) -> CalyxResult<PathBuf>
where
S: AsRef<Path> + Clone + WithPos,
{
parent
.join(extern_path.clone())
.canonicalize()
.map_err(|_| {
Error::invalid_file(format!(
"Extern path `{}` not found in parent directory ({})",
extern_path.as_ref().to_string_lossy(),
parent.to_string_lossy(),
))
.with_pos(&extern_path)
})
}
pub fn from_compile_lib() -> CalyxResult<Self> {
let mut ns = NamespaceDef::construct_from_str(COMPILE_LIB)?;
assert!(
ns.imports.is_empty(),
"core library should not contain any imports"
);
assert!(
ns.metadata.is_none(),
"core library should not contain any metadata"
);
assert!(
ns.externs.len() == 1 && ns.externs[0].0.is_none(),
"core library should only contain inline externs"
);
let (_, externs) = ns.externs.pop().unwrap();
let mut lib = LibrarySignatures::default();
for ext in externs {
lib.add_inline_primitive(ext);
}
let ws = Workspace {
components: ns.components,
lib,
..Default::default()
};
Ok(ws)
}
pub fn construct(
file: &Option<PathBuf>,
lib_path: &Path,
) -> CalyxResult<Self> {
Self::construct_with_all_deps::<false>(
file.iter().cloned().collect(),
lib_path,
)
}
pub fn construct_shallow(
file: &Option<PathBuf>,
lib_path: &Path,
) -> CalyxResult<Self> {
Self::construct_with_all_deps::<true>(
file.iter().cloned().collect(),
lib_path,
)
}
fn get_parent(p: &Path) -> PathBuf {
let maybe_parent = p.parent();
match maybe_parent {
None => PathBuf::from("."),
Some(path) => {
if path.to_string_lossy() == "" {
PathBuf::from(".")
} else {
PathBuf::from(path)
}
}
}
}
pub fn merge_namespace(
&mut self,
ns: NamespaceDef,
is_source: bool,
parent: &Path,
shallow: bool,
lib_path: &Path,
) -> CalyxResult<Vec<(PathBuf, bool)>> {
for (path, exts) in ns.externs {
match path {
Some(p) => {
#[cfg(not(target_arch = "wasm32"))]
let abs_path = Self::canonicalize_extern(p, parent)?;
#[cfg(target_arch = "wasm32")]
let abs_path = p.into();
let p = self.lib.add_extern(abs_path, exts);
if is_source {
p.set_source();
}
}
None => {
for ext in exts {
let p = self.lib.add_inline_primitive(ext);
if is_source {
p.set_source();
}
}
}
}
}
if !is_source && shallow {
self.declarations.extend(&mut ns.components.into_iter());
} else {
self.components.extend(&mut ns.components.into_iter());
}
let deps = ns
.imports
.into_iter()
.map(|p| {
Self::canonicalize_import(p, parent, lib_path)
.map(|s| (s, false))
})
.collect::<CalyxResult<_>>()?;
Ok(deps)
}
pub fn construct_with_all_deps<const SHALLOW: bool>(
mut files: Vec<PathBuf>,
lib_path: &Path,
) -> CalyxResult<Self> {
let first = files.pop();
let ns = NamespaceDef::construct(&first)?;
let parent_path = first
.as_ref()
.map(|p| Self::get_parent(p))
.unwrap_or_else(|| PathBuf::from("."));
let mut dependencies: Vec<(PathBuf, bool)> =
files.into_iter().map(|p| (p, true)).collect();
let mut already_imported: HashSet<PathBuf> = HashSet::new();
let mut ws = Workspace::default();
let abs_lib_path = lib_path.canonicalize().map_err(|err| {
Error::invalid_file(format!(
"Failed to canonicalize library path `{}`: {}",
lib_path.to_string_lossy(),
err
))
})?;
ws.original_imports =
ns.imports.iter().map(|imp| imp.to_string()).collect();
ws.metadata = ns.metadata.clone();
let parent_canonical = parent_path.canonicalize().map_err(|err| {
Error::invalid_file(format!(
"Failed to canonicalize parent path `{}`: {}",
parent_path.to_string_lossy(),
err
))
})?;
let mut deps = ws.merge_namespace(
ns,
true,
&parent_canonical,
false,
&abs_lib_path,
)?;
dependencies.append(&mut deps);
while let Some((p, source)) = dependencies.pop() {
if already_imported.contains(&p) {
continue;
}
let ns = parser::CalyxParser::parse_file(&p)?;
let parent = Self::get_parent(&p);
let mut deps = ws.merge_namespace(
ns,
source,
&parent,
SHALLOW,
&abs_lib_path,
)?;
dependencies.append(&mut deps);
already_imported.insert(p);
}
Ok(ws)
}
}