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
638 lines (567 loc) · 17.8 KB
/
import.rs
File metadata and controls
638 lines (567 loc) · 17.8 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
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
// 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_syntax_only, ParseError};
use error::error::{WaveError, WaveErrorKind};
use lexer::Lexer;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
enum TargetAttr<'a> {
Supported(&'a str),
Unsupported,
}
fn parse_target_os_attr(line: &str) -> Option<TargetAttr<'_>> {
let trimmed = line.trim();
if !trimmed.starts_with("#[target(os=\"") || !trimmed.ends_with("\")]") {
return None;
}
let start = "#[target(os=\"".len();
let end = trimmed.len() - 3; // ")]"
let os = &trimmed[start..end];
if os == "linux" || os == "macos" {
Some(TargetAttr::Supported(os))
} else {
Some(TargetAttr::Unsupported)
}
}
fn is_supported_target_item_start(line: &str) -> bool {
fn has_ident_boundary(rest: &str) -> bool {
match rest.chars().next() {
None => true,
Some(c) => !(c.is_ascii_alphanumeric() || c == '_'),
}
}
let trimmed = line.trim_start();
for kw in ["fun", "struct", "enum", "const", "static", "type", "proto"] {
if let Some(rest) = trimmed.strip_prefix(kw) {
if has_ident_boundary(rest) {
return true;
}
}
}
false
}
fn scan_target_item_line(
line: &str,
in_block_comment: &mut bool,
depth: &mut i32,
seen_open: &mut bool,
saw_semicolon: &mut bool,
) {
let mut chars = line.chars().peekable();
let mut in_string = false;
let mut in_char = false;
let mut escape = false;
while let Some(ch) = chars.next() {
if *in_block_comment {
if ch == '*' && chars.peek() == Some(&'/') {
chars.next();
*in_block_comment = false;
}
continue;
}
if in_string {
if escape {
escape = false;
continue;
}
if ch == '\\' {
escape = true;
continue;
}
if ch == '"' {
in_string = false;
}
continue;
}
if in_char {
if escape {
escape = false;
continue;
}
if ch == '\\' {
escape = true;
continue;
}
if ch == '\'' {
in_char = false;
}
continue;
}
if ch == '/' {
if chars.peek() == Some(&'/') {
break;
}
if chars.peek() == Some(&'*') {
chars.next();
*in_block_comment = true;
continue;
}
}
if ch == '"' {
in_string = true;
continue;
}
if ch == '\'' {
in_char = true;
continue;
}
if ch == '{' {
*depth += 1;
*seen_open = true;
continue;
}
if ch == '}' {
if *depth > 0 {
*depth -= 1;
}
continue;
}
if ch == ';' {
*saw_semicolon = true;
}
}
}
fn consume_target_item(lines: &[&str], mut idx: usize, keep: bool, out: &mut Vec<String>) -> usize {
let mut depth: i32 = 0;
let mut seen_open = false;
let mut in_block_comment = false;
while idx < lines.len() {
let line = lines[idx];
if keep {
out.push(line.to_string());
} else {
out.push(String::new());
}
let mut saw_semicolon = false;
scan_target_item_line(
line,
&mut in_block_comment,
&mut depth,
&mut seen_open,
&mut saw_semicolon,
);
idx += 1;
if seen_open {
if depth == 0 {
break;
}
} else if saw_semicolon {
break;
}
}
idx
}
fn preprocess_target_attrs(source: &str) -> String {
let host = std::env::consts::OS;
let lines: Vec<&str> = source.lines().collect();
let mut out: Vec<String> = Vec::with_capacity(lines.len());
let mut idx: usize = 0;
while idx < lines.len() {
let line = lines[idx];
if let Some(target_attr) = parse_target_os_attr(line) {
// Attribute line is removed for parser compatibility,
// but we keep its line slot to preserve diagnostics.
out.push(String::new());
idx += 1;
let keep_item = match target_attr {
TargetAttr::Supported(target_os) => target_os == host,
// Ignore unsupported target values.
TargetAttr::Unsupported => true,
};
// Attribute applies to the next top-level item.
// Preserve line count for any leading blanks/comments.
while idx < lines.len() {
let item_line = lines[idx];
let trimmed = item_line.trim_start();
let is_leading_comment = trimmed.starts_with("//")
|| trimmed.starts_with("/*")
|| trimmed.starts_with('*')
|| trimmed.starts_with("*/");
if trimmed.is_empty() || is_leading_comment {
if keep_item {
out.push(item_line.to_string());
} else {
out.push(String::new());
}
idx += 1;
continue;
}
if is_supported_target_item_start(trimmed) {
idx = consume_target_item(&lines, idx, keep_item, &mut out);
} else if keep_item {
out.push(item_line.to_string());
idx += 1;
} else {
out.push(String::new());
idx += 1;
}
break;
}
continue;
}
out.push(line.to_string());
idx += 1;
}
let mut processed = out.join("\n");
if source.ends_with('\n') {
processed.push('\n');
}
processed
}
pub struct ImportedUnit {
pub abs_path: PathBuf,
pub ast: Vec<ASTNode>,
}
#[derive(Debug, Clone, Default)]
pub struct ImportConfig {
pub dep_roots: Vec<PathBuf>,
pub dep_packages: HashMap<String, PathBuf>,
}
pub fn local_import_unit(
path: &str,
already_imported: &mut HashSet<String>,
base_dir: &Path,
) -> Result<ImportedUnit, WaveError> {
local_import_unit_with_config(path, already_imported, base_dir, &ImportConfig::default())
}
pub fn local_import_unit_with_config(
path: &str,
already_imported: &mut HashSet<String>,
base_dir: &Path,
config: &ImportConfig,
) -> 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 external_import_unit(path, already_imported, config);
}
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_with_config(path, already_imported, base_dir, &ImportConfig::default())?
.ast,
)
}
pub fn local_import_with_config(
path: &str,
already_imported: &mut HashSet<String>,
base_dir: &Path,
config: &ImportConfig,
) -> Result<Vec<ASTNode>, WaveError> {
Ok(local_import_unit_with_config(path, already_imported, base_dir, config)?.ast)
}
fn resolve_external_package_root(
package: &str,
config: &ImportConfig,
) -> Result<Option<PathBuf>, Vec<PathBuf>> {
if let Some(path) = config.dep_packages.get(package) {
return Ok(Some(path.clone()));
}
let mut matches = Vec::new();
for root in &config.dep_roots {
let candidate = root.join(package);
if candidate.is_dir() {
matches.push(candidate);
}
}
match matches.len() {
0 => Ok(None),
1 => Ok(matches.into_iter().next()),
_ => Err(matches),
}
}
fn external_import_unit(
path: &str,
already_imported: &mut HashSet<String>,
config: &ImportConfig,
) -> Result<ImportedUnit, WaveError> {
let mut parts = path.split("::");
let package = parts.next().unwrap_or("").trim();
let module_parts: Vec<&str> = parts.collect();
if package.is_empty()
|| module_parts.is_empty()
|| module_parts.iter().any(|s| s.trim().is_empty())
{
return Err(WaveError::new(
WaveErrorKind::SyntaxError("Invalid external import path".to_string()),
format!(
"invalid external import '{}': expected `package::module::path`",
path
),
path,
0,
0,
)
.with_help("use at least two segments, for example: import(\"math::vector::ops\")"));
}
let package_root = match resolve_external_package_root(package, config) {
Ok(Some(root)) => root,
Ok(None) => {
let mut err = WaveError::new(
WaveErrorKind::SyntaxError("External dependency not found".to_string()),
format!(
"could not resolve external package '{}' for import '{}'",
package, path
),
path,
0,
0,
)
.with_help("provide dependency paths with `--dep-root <dir>` or `--dep <name>=<path>`")
.with_suggestion("example: wavec run main.wave --dep-root .vex/dep")
.with_suggestion(format!(
"example: wavec run main.wave --dep {}=/abs/path/to/{}",
package, package
));
if !config.dep_roots.is_empty() {
let roots = config
.dep_roots
.iter()
.map(|p| p.display().to_string())
.collect::<Vec<_>>()
.join(", ");
err = err.with_note(format!("currently configured dependency roots: {}", roots));
}
return Err(err);
}
Err(candidates) => {
let roots = candidates
.iter()
.map(|p| p.display().to_string())
.collect::<Vec<_>>()
.join(", ");
return Err(WaveError::new(
WaveErrorKind::SyntaxError("Ambiguous external package root".to_string()),
format!(
"package '{}' is found in multiple dependency roots; resolution is ambiguous",
package
),
path,
0,
0,
)
.with_note(format!("candidates: {}", roots))
.with_help("pin the package path explicitly with `--dep <name>=<path>`"));
}
};
if !package_root.is_dir() {
return Err(WaveError::new(
WaveErrorKind::SyntaxError("Dependency path is not a directory".to_string()),
format!(
"configured dependency path for package '{}' is invalid: {}",
package,
package_root.display()
),
path,
0,
0,
)
.with_help("pass a valid directory path via `--dep <name>=<path>`"));
}
let module_rel = module_parts.join("/");
let module_file = if module_rel.ends_with(".wave") {
module_rel
} else {
format!("{}.wave", module_rel)
};
let candidates = [
package_root.join(&module_file),
package_root.join("src").join(&module_file),
];
for candidate in &candidates {
if candidate.exists() && candidate.is_file() {
return parse_wave_file(candidate, path, already_imported);
}
}
let searched = candidates
.iter()
.map(|p| p.display().to_string())
.collect::<Vec<_>>()
.join(", ");
Err(WaveError::new(
WaveErrorKind::SyntaxError("File not found".to_string()),
format!(
"could not find external import target '{}' in package '{}'",
path, package
),
path,
0,
0,
)
.with_note(format!("searched paths: {}", searched))
.with_help("check package/module names or pass an explicit path with `--dep <name>=<path>`"))
}
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 raw_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 content = preprocess_target_attrs(&raw_content);
let mut lexer = Lexer::new_with_file(&content, abs_path.display().to_string());
let tokens = lexer.tokenize()?;
let ast = parse_syntax_only(&tokens).map_err(|e| {
let (kind, phase, code) = match &e {
ParseError::Syntax(_) => (
WaveErrorKind::SyntaxError(e.message().to_string()),
"syntax",
"E2001",
),
ParseError::Semantic(_) => (
WaveErrorKind::InvalidStatement(e.message().to_string()),
"semantic",
"E3001",
),
};
let mut we = WaveError::new(
kind,
format!(
"{} validation failed for '{}': {}",
phase,
abs_path.display(),
e.message()
),
display_name,
e.line().max(1),
e.column().max(1),
)
.with_code(code)
.with_source_code(content.clone());
if let Some(ctx) = e.context() {
we = we.with_context(ctx.to_string());
}
if !e.expected().is_empty() {
we = we.with_expected_many(e.expected().iter().cloned());
}
if let Some(found) = e.found() {
we = we.with_found(found.to_string());
}
if let Some(note) = e.note() {
we = we.with_note(note.to_string());
}
if let Some(help) = e.help() {
we = we.with_help(help.to_string());
}
we
})?;
Ok(ImportedUnit { abs_path, ast })
}