forked from wavefnd/Wave
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimport.rs
More file actions
190 lines (166 loc) · 5.55 KB
/
import.rs
File metadata and controls
190 lines (166 loc) · 5.55 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
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
// This file is part of the Wave language project.
// Copyright (c) 2024–2026 Wave Foundation
// Copyright (c) 2024–2026 LunaStev and contributors
//
// This Source Code Form is subject to the terms of the
// Mozilla Public License, v. 2.0.
// If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.
//
// SPDX-License-Identifier: MPL-2.0
use crate::ast::{ASTNode};
use crate::{parse, ParseError};
use error::error::{WaveError, WaveErrorKind};
use lexer::Lexer;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
pub struct ImportedUnit {
pub abs_path: PathBuf,
pub ast: Vec<ASTNode>,
}
pub fn local_import_unit(
path: &str,
already_imported: &mut HashSet<String>,
base_dir: &Path,
) -> Result<ImportedUnit, WaveError> {
if path.trim().is_empty() {
return Err(WaveError::new(
WaveErrorKind::SyntaxError("Empty import path".to_string()),
"import path cannot be empty",
"<main>",
0,
0,
));
}
if path.starts_with("std::") {
return std_import_unit(path, already_imported);
}
if path.contains("::") {
return Err(WaveError::new(
WaveErrorKind::SyntaxError("External import is not supported".to_string()),
"External imports are not supported by the Wave compiler (standalone).",
path,
0,
0,
));
}
let target_file_name = if path.ends_with(".wave") {
path.to_string()
} else {
format!("{}.wave", path)
};
let found_path = base_dir.join(&target_file_name);
if !found_path.exists() || !found_path.is_file() {
return Err(WaveError::new(
WaveErrorKind::SyntaxError("File not found".to_string()),
format!("Could not find import target '{}'", target_file_name),
target_file_name.clone(),
0,
0,
));
}
parse_wave_file(&found_path, &target_file_name, already_imported)
}
pub fn local_import(
path: &str,
already_imported: &mut HashSet<String>,
base_dir: &Path,
) -> Result<Vec<ASTNode>, WaveError> {
Ok(local_import_unit(path, already_imported, base_dir)?.ast)
}
fn std_import_unit(path: &str, already_imported: &mut HashSet<String>) -> Result<ImportedUnit, WaveError> {
let rel = path.strip_prefix("std::").unwrap();
if rel.trim().is_empty() {
return Err(WaveError::new(
WaveErrorKind::SyntaxError("Empty std import".to_string()),
"std import path cannot be empty (example: import(\"std::io::format\"))",
path,
0,
0,
));
}
let std_root = std_root_dir(path)?;
// std::io::format -> ~/.wave/lib/wave/std/io/format.wave
let rel_path = rel.replace("::", "/");
let found_path = std_root.join(format!("{}.wave", rel_path));
if !found_path.exists() || !found_path.is_file() {
return Err(WaveError::new(
WaveErrorKind::SyntaxError("File not found".to_string()),
format!("Could not find std import target '{}'", found_path.display()),
path,
0,
0,
));
}
parse_wave_file(&found_path, path, already_imported)
}
fn std_root_dir(import_path: &str) -> Result<PathBuf, WaveError> {
let home = std::env::var("HOME").map_err(|_| {
WaveError::new(
WaveErrorKind::SyntaxError("std not installed".to_string()),
"HOME env not set; cannot locate std at ~/.wave/lib/wave/std",
import_path,
0,
0,
)
})?;
Ok(PathBuf::from(home).join(".wave/lib/wave/std"))
}
fn parse_wave_file(
found_path: &Path,
display_name: &str,
already_imported: &mut HashSet<String>,
) -> Result<ImportedUnit, WaveError> {
let abs_path = found_path.canonicalize().map_err(|e| {
WaveError::new(
WaveErrorKind::SyntaxError("Canonicalization failed".to_string()),
format!("Failed to canonicalize path: {}", e),
display_name,
0,
0,
)
})?;
let abs_path_str = abs_path
.to_str()
.ok_or_else(|| {
WaveError::new(
WaveErrorKind::UnexpectedChar('?'),
"Invalid path encoding",
display_name,
0,
0,
)
})?
.to_string();
if already_imported.contains(&abs_path_str) {
return Ok(ImportedUnit { abs_path, ast: vec![] });
}
already_imported.insert(abs_path_str);
let content = std::fs::read_to_string(&abs_path).map_err(|e| {
WaveError::new(
WaveErrorKind::SyntaxError("Read error".to_string()),
format!("Failed to read '{}': {}", abs_path.display(), e),
display_name,
0,
0,
)
})?;
let mut lexer = Lexer::new(&content);
let tokens = lexer.tokenize();
let ast = parse(&tokens).map_err(|e| {
let (kind, phase) = match &e {
ParseError::Syntax(msg) => (WaveErrorKind::SyntaxError(msg.clone()), "syntax"),
ParseError::Semantic(msg) => (WaveErrorKind::InvalidStatement(msg.clone()), "semantic"),
};
WaveError::new(
kind,
format!("{} validation failed for '{}': {}", phase, abs_path.display(), e.message()),
display_name,
1,
1,
)
.with_source(content.lines().next().unwrap_or("").to_string())
.with_label("here".to_string())
})?;
Ok(ImportedUnit { abs_path, ast })
}