Skip to main content

ty_parser/
lib.rs

1#![deny(missing_docs)]
2
3//! C-syntax parser for the Ty programming language.
4
5mod lexer;
6mod parser;
7mod token;
8
9/// Source location (line and column).
10#[derive(Copy, Clone, Debug)]
11pub struct Span {
12    /// Line number (1-based).
13    pub line: u32,
14    /// Column number (1-based).
15    pub column: u32,
16}
17
18impl std::fmt::Display for Span {
19    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20        write!(formatter, "{}:{}", self.line, self.column)
21    }
22}
23
24/// A parse error with optional source location.
25#[derive(Debug)]
26pub struct Error {
27    /// Human-readable error description.
28    pub message: String,
29    /// Source location where the error occurred.
30    pub span: Option<Span>,
31}
32
33impl std::fmt::Display for Error {
34    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35        if let Some(span) = self.span {
36            write!(formatter, "{span}: {}", self.message)
37        } else {
38            write!(formatter, "{}", self.message)
39        }
40    }
41}
42
43impl std::error::Error for Error {}
44
45type Result<T> = std::result::Result<T, Error>;
46
47/// Parses Ty source code (C-syntax) into a typed AST module.
48pub fn parse(source: &str) -> Result<ty_ree::declaration::Module> {
49    let mut lexer = lexer::Lexer::new(source);
50    let tokens = lexer.tokenize()?;
51    let mut parser = parser::Parser::new(tokens);
52    parser.parse_module()
53}