forked from circify/circ
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathparser.rs
More file actions
152 lines (140 loc) · 4.59 KB
/
Copy pathparser.rs
File metadata and controls
152 lines (140 loc) · 4.59 KB
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
//! Parsing and recursively loading Z#.
//!
//! Based on the original ZoKrates parser, with extra machinery for recursive loading and locating
//! the standard library.
use zokrates_pest_ast as ast;
use log::debug;
use std::collections::HashMap;
use std::env::var_os;
use crate::circify::includer::Loader;
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
use typed_arena::Arena;
/// A representation of the standard libary's location.
#[derive(Default)]
pub struct ZStdLib {
path: PathBuf,
}
impl ZStdLib {
/// Looks for a "ZoKrates/zokrates_stdlib/stdlib" path in some ancestor of the current
/// directory.
pub fn new() -> Self {
if let Some(p) = var_os("ZSHARP_STDLIB_PATH") {
let p = PathBuf::from(p);
if p.exists() {
return Self { path: p };
} else {
panic!(
"ZStdLib: ZSHARP_STDLIB_PATH {:?} does not appear to exist",
p
);
}
}
let p = std::env::current_dir().unwrap().canonicalize().unwrap();
assert!(p.is_absolute());
let stdlib_subdirs = vec![
"ZoKrates/zokrates_stdlib/stdlib",
"third_party/ZoKrates/zokrates_stdlib/stdlib",
];
for a in p.ancestors() {
for subdir in &stdlib_subdirs {
let mut q = a.to_path_buf();
q.push(subdir);
if q.exists() {
return Self { path: q };
}
}
}
panic!("Could not find ZoKrates/Z# stdlib from {}", p.display())
}
/// Turn `child`, relative to `parent` (or to the standard libary!), into an absolute path.
pub fn canonicalize(&self, parent: &Path, child: &str) -> PathBuf {
debug!("Looking for {} from {}", child, parent.display());
let paths = [parent.to_path_buf(), self.path.clone()];
for mut p in paths {
p.push(child);
debug!("Checking {}", p.display());
if p.exists() {
return p;
}
if p.extension().is_some() {
continue;
}
for ext in ["zok", "zx"] {
p.set_extension(ext);
debug!("Checking {}", p.display());
if p.exists() {
return p;
}
}
}
panic!("Could not find {} from {}", child, parent.display())
}
/// check if this path is the EMBED prototypes path
pub fn is_embed<P: AsRef<Path>>(&self, p: P) -> bool {
p.as_ref().starts_with(&self.path)
&& p.as_ref().file_stem().and_then(|s| s.to_str()) == Some("EMBED")
}
}
/// A recrusive Z# loader
#[derive(Default)]
pub struct ZLoad {
sources: Arena<String>,
stdlib: ZStdLib,
}
impl ZLoad {
/// Make a new Z# loader, looking for the standard library somewhere above the current
/// dirdirectory. See [ZStdLib::new].
pub fn new() -> Self {
Self {
sources: Arena::new(),
stdlib: ZStdLib::new(),
}
}
/// Recursively load a Z# file.
///
/// ## Returns
///
/// Returns a map from file paths to parsed files.
pub fn load<P: AsRef<Path>>(&self, p: &P) -> HashMap<PathBuf, ast::File<'_>> {
self.recursive_load(p).unwrap()
}
/// Get ref to contained ZStdLib
pub fn stdlib(&self) -> &ZStdLib {
&self.stdlib
}
}
impl<'a> Loader for &'a ZLoad {
type ParseError = ();
type AST = zokrates_pest_ast::File<'a>;
fn parse<P: AsRef<Path>>(&self, p: &P) -> Result<Self::AST, Self::ParseError> {
let mut s = String::new();
File::open(p).unwrap().read_to_string(&mut s).unwrap();
debug!("Parsing: {}", p.as_ref().display());
let s = self.sources.alloc(s);
let ast = ast::generate_ast(s);
if ast.is_err() {
panic!("{}", ast.unwrap_err());
}
Ok(ast.unwrap())
}
fn includes<P: AsRef<Path>>(&self, ast: &Self::AST, p: &P) -> Vec<PathBuf> {
let mut c = p.as_ref().to_path_buf();
c.pop();
ast.declarations
.iter()
.filter_map(|d| {
if let ast::SymbolDeclaration::Import(i) = d {
let ext = match i {
ast::ImportDirective::Main(m) => &m.source.value,
ast::ImportDirective::From(m) => &m.source.value,
};
Some(self.stdlib.canonicalize(&c, ext))
} else {
None
}
})
.collect()
}
}