devalang_core/core/lexer/
driver.rs1use crate::core::lexer::{handler::driver::handle_content_lexing, token::Token};
2use devalang_utils::path::normalize_path;
3use std::fs;
4use std::path::Path;
5
6pub struct Lexer {}
7
8impl Default for Lexer {
9 fn default() -> Self {
10 Self::new()
11 }
12}
13
14impl Lexer {
15 pub fn new() -> Self {
16 Lexer {}
17 }
18
19 pub fn lex_from_source(&self, source: &str) -> Result<Vec<Token>, String> {
20 handle_content_lexing(source.to_string())
21 }
22
23 pub fn lex_tokens(&self, entrypoint: &str) -> Result<Vec<Token>, String> {
24 let path = normalize_path(entrypoint);
25 let resolved_path = Self::resolve_entry_path(&path)?;
26
27 let file_content = fs::read_to_string(&resolved_path).map_err(|e| {
28 format!(
29 "Failed to read the entrypoint file '{}': {}",
30 resolved_path, e
31 )
32 })?;
33
34 handle_content_lexing(file_content).map_err(|e| format!("Failed to lex the content: {}", e))
35 }
36
37 fn resolve_entry_path(path: &str) -> Result<String, String> {
38 let candidate = Path::new(path);
39
40 if candidate.is_dir() {
41 let index_path = candidate.join("index.deva");
42 if index_path.exists() {
43 Ok(index_path.to_string_lossy().replace("\\", "/"))
44 } else {
45 Err(format!(
46 "Expected 'index.deva' in directory '{}', but it was not found",
47 path
48 ))
49 }
50 } else if candidate.is_file() {
51 return Ok(path.to_string());
52 } else {
53 return Err(format!(
54 "Provided entrypoint '{}' is not a valid file or directory",
55 path
56 ));
57 }
58 }
59}