devalang_core/core/lexer/
driver.rs

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