leo_parser/parser/
mod.rs

1// Copyright (C) 2019-2025 Provable Inc.
2// This file is part of the Leo library.
3
4// The Leo library is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// The Leo library is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
16
17//! The parser to convert Leo code text into a [`Program`] AST type.
18//!
19//! This module contains the [`parse()`] function which calls the underlying [`tokenize()`]
20//! method to create a new program AST.
21
22use crate::{Token, tokenizer::*};
23
24use leo_ast::*;
25use leo_errors::{Handler, ParserError, Result};
26use leo_span::Span;
27
28use snarkvm::prelude::Network;
29
30use indexmap::IndexMap;
31use std::unreachable;
32
33mod context;
34pub(super) use context::ParserContext;
35
36mod expression;
37mod file;
38mod statement;
39pub(super) mod type_;
40
41/// Creates a new program from a given file path and source code text.
42pub fn parse<N: Network>(
43    handler: Handler,
44    node_builder: &NodeBuilder,
45    source: &str,
46    start_pos: u32,
47) -> Result<Program> {
48    let mut tokens = ParserContext::<N>::new(handler, node_builder, crate::tokenize(source, start_pos)?);
49
50    tokens.parse_program()
51}
52
53pub fn parse_expression<N: Network>(
54    handler: Handler,
55    node_builder: &NodeBuilder,
56    source: &str,
57    start_pos: u32,
58) -> Result<Expression> {
59    let mut context = ParserContext::<N>::new(handler, node_builder, crate::tokenize(source, start_pos)?);
60
61    let expression = context.parse_expression()?;
62    if context.token.token == Token::Eof {
63        Ok(expression)
64    } else {
65        Err(ParserError::unexpected(context.token.token, Token::Eof, context.token.span).into())
66    }
67}
68
69pub fn parse_statement<N: Network>(
70    handler: Handler,
71    node_builder: &NodeBuilder,
72    source: &str,
73    start_pos: u32,
74) -> Result<Statement> {
75    let mut context = ParserContext::<N>::new(handler, node_builder, crate::tokenize(source, start_pos)?);
76
77    let statement = context.parse_statement()?;
78    if context.token.token == Token::Eof {
79        Ok(statement)
80    } else {
81        Err(ParserError::unexpected(context.token.token, Token::Eof, context.token.span).into())
82    }
83}