Parser

Struct Parser 

Source
pub struct Parser<'sess, 'ast> {
    pub sess: &'sess Session,
    pub arena: &'ast Arena,
    pub token: Token,
    pub prev_token: Token,
    /* private fields */
}
Expand description

Solidity and Yul parser.

§Examples

use solar::{
    ast,
    interface::{Session, diagnostics::EmittedDiagnostics},
    parse::Parser,
};
use std::path::Path;

#[test]
fn main() -> Result<(), EmittedDiagnostics> {
    let path = Path::new("src/Counter.sol");

    // Create a new session with a buffer emitter.
    // This is required to capture the emitted diagnostics and to return them at the end.
    let sess = Session::builder().with_buffer_emitter(solar::interface::ColorChoice::Auto).build();

    // Enter the context and parse the file.
    let _ = sess.enter(|| -> solar::interface::Result<()> {
        // Set up the parser.
        let arena = ast::Arena::new();
        let mut parser = Parser::from_file(&sess, &arena, path)?;

        // Parse the file.
        let ast = parser.parse_file().map_err(|e| e.emit())?;
        println!("parsed {path:?}: {ast:#?}");
        Ok(())
    });

    // Return the emitted diagnostics as a `Result<(), _>`.
    // If any errors were emitted, this returns `Err(_)`, otherwise `Ok(())`.
    // Note that this discards warnings and other non-error diagnostics.
    sess.emitted_errors().unwrap()
}

Fields§

§sess: &'sess Session

The parser session.

§arena: &'ast Arena

The arena where the AST nodes are allocated.

§token: Token

The current token.

§prev_token: Token

The previous token.

Implementations§

Source§

impl<'sess, 'ast> Parser<'sess, 'ast>

Source

pub fn parse_expr(&mut self) -> PResult<'sess, Box<'ast, Expr<'ast>>>

Parses an expression.

Source§

impl<'sess, 'ast> Parser<'sess, 'ast>

Source

pub fn parse_file(&mut self) -> PResult<'sess, SourceUnit<'ast>>

Parses a source unit.

Source

pub fn parse_item(&mut self) -> PResult<'sess, Option<Item<'ast>>>

Parses an item.

Source

pub fn parse_semver_req(&mut self) -> PResult<'sess, SemverReq<'ast>>

Parses a SemVer version requirement.

See crates/ast/src/ast/semver.rs for more details on the implementation.

Source§

impl<'sess, 'ast> Parser<'sess, 'ast>

Source

pub fn parse_lit( &mut self, with_subdenomination: bool, ) -> PResult<'sess, (Lit<'ast>, Option<SubDenomination>)>

Parses a literal with an optional subdenomination.

Note that the subdenomination gets applied to the literal directly, and is returned just for display reasons.

Returns None if no subdenomination was parsed or if the literal is not a number or rational.

Source

pub fn parse_subdenomination(&mut self) -> Option<SubDenomination>

Parses a subdenomination.

Source§

impl<'sess, 'ast> Parser<'sess, 'ast>

Source

pub fn parse_stmt(&mut self) -> PResult<'sess, Stmt<'ast>>

Parses a statement.

Source

pub fn parse_stmt_boxed(&mut self) -> PResult<'sess, Box<'ast, Stmt<'ast>>>

Parses a statement into a new allocation.

Source§

impl<'sess, 'ast> Parser<'sess, 'ast>

Source

pub fn parse_type(&mut self) -> PResult<'sess, Type<'ast>>

Parses a type.

Source§

impl<'sess, 'ast> Parser<'sess, 'ast>

Source

pub fn parse_yul_file_object(&mut self) -> PResult<'sess, Object<'ast>>

Parses a Yul object or plain block.

The plain block gets returned as a Yul object named “object”, with a single code block. See: https://github.com/argotorg/solidity/blob/eff410eb746f202fe756a2473fd0c8a718348457/libyul/ObjectParser.cpp#L50

Source

pub fn parse_yul_object( &mut self, docs: DocComments<'ast>, ) -> PResult<'sess, Object<'ast>>

Source

pub fn parse_yul_stmt(&mut self) -> PResult<'sess, Stmt<'ast>>

Parses a Yul statement.

Source

pub fn parse_yul_stmt_unchecked(&mut self) -> PResult<'sess, Stmt<'ast>>

Parses a Yul statement, without setting in_yul.

Source

pub fn parse_yul_block(&mut self) -> PResult<'sess, Block<'ast>>

Parses a Yul block.

Source

pub fn parse_yul_block_unchecked(&mut self) -> PResult<'sess, Block<'ast>>

Parses a Yul block, without setting in_yul.

Source§

impl<'sess, 'ast> Parser<'sess, 'ast>

Source

pub fn new(sess: &'sess Session, arena: &'ast Arena, tokens: Vec<Token>) -> Self

Creates a new parser.

Source

pub fn from_source_code( sess: &'sess Session, arena: &'ast Arena, filename: FileName, src: impl Into<String>, ) -> Result<Self>

Creates a new parser from a source code string.

Source

pub fn from_file( sess: &'sess Session, arena: &'ast Arena, path: &Path, ) -> Result<Self>

Creates a new parser from a file.

The file will not be read if it has already been added into the source map.

Source

pub fn from_lazy_source_code( sess: &'sess Session, arena: &'ast Arena, filename: FileName, get_src: impl FnOnce() -> Result<String>, ) -> Result<Self>

Creates a new parser from a source code closure.

The closure will not be called if the file name has already been added into the source map.

Source

pub fn from_source_file( sess: &'sess Session, arena: &'ast Arena, file: &SourceFile, ) -> Self

Creates a new parser from a source file.

Note that the source file must be added to the source map before calling this function. Prefer using from_source_code or from_file instead.

Source

pub fn from_lexer(arena: &'ast Arena, lexer: Lexer<'sess, '_>) -> Self

Creates a new parser from a lexer.

Source

pub fn dcx(&self) -> &'sess DiagCtxt

Returns the diagnostic context.

Source

pub fn alloc<T>(&self, value: T) -> Box<'ast, T>

Allocates an object on the AST arena.

Source

pub fn alloc_path(&self, segments: &[Ident]) -> AstPath<'ast>

Allocates a list of objects on the AST arena.

§Panics

Panics if the list is empty.

Source

pub fn alloc_vec<T>(&self, values: Vec<T>) -> BoxSlice<'ast, T>

Allocates a list of objects on the AST arena.

Source

pub fn alloc_smallvec<A: Array>( &self, values: SmallVec<A>, ) -> BoxSlice<'ast, A::Item>

Allocates a list of objects on the AST arena.

Source

pub fn unexpected<T>(&mut self) -> PResult<'sess, T>

Returns an “unexpected token” error in a PResult for the current token.

Source

pub fn unexpected_error(&mut self) -> PErr<'sess>

Returns an “unexpected token” error for the current token.

Source

pub fn expect(&mut self, tok: TokenKind) -> PResult<'sess, Recovered>

Expects and consumes the token t. Signals an error if the next token is not t.

Source

pub fn expect_one_of( &mut self, edible: &[TokenKind], inedible: &[TokenKind], ) -> PResult<'sess, Recovered>

Expect next token to be edible or inedible token. If edible, then consume it; if inedible, then return without consuming anything. Signal a fatal error if next token is unexpected.

Source

pub fn eat_noexpect(&mut self, tok: TokenKind) -> bool

Consumes a token ‘tok’ if it exists. Returns whether the given token was present.

the main purpose of this function is to reduce the cluttering of the suggestions list which using the normal eat method could introduce in some cases.

Source

pub fn eat(&mut self, tok: TokenKind) -> bool

Consumes a token ‘tok’ if it exists. Returns whether the given token was present.

Source

pub fn eat_keyword(&mut self, kw: Symbol) -> bool

If the next token is the given keyword, eats it and returns true. Otherwise, returns false. An expectation is also added for diagnostics purposes.

Source

pub fn bump(&mut self)

Advance the parser by one token.

Source

pub fn bump_with(&mut self, next: Token)

Advance the parser by one token using provided token as the next one.

§Panics

Panics if the provided token is a comment.

Source

pub fn look_ahead(&self, dist: usize) -> Token

Returns the token dist tokens ahead of the current one.

Eof will be returned if the look-ahead is any distance past the end of the tokens.

Source

pub fn look_ahead_with<R>(&self, dist: usize, f: impl FnOnce(Token) -> R) -> R

Calls f with the token dist tokens ahead of the current one.

See look_ahead for more information.

Source

pub fn with_recursion_limit<T>( &mut self, context: &str, f: impl FnOnce(&mut Self) -> PResult<'sess, T>, ) -> PResult<'sess, T>

Runs f with recursion depth tracking and limit enforcement.

Source§

impl<'sess, 'ast> Parser<'sess, 'ast>

Common parsing methods.

Source

pub fn parse_spanned<T>( &mut self, f: impl FnOnce(&mut Self) -> PResult<'sess, T>, ) -> PResult<'sess, (Span, T)>

Provides a spanned parser.

Source

pub fn parse_doc_comments(&mut self) -> DocComments<'ast>

Parses contiguous doc comments. Can be empty.

Source

pub fn parse_path(&mut self) -> PResult<'sess, AstPath<'ast>>

Parses a qualified identifier: foo.bar.baz.

Source

pub fn parse_path_with(&mut self, first: Ident) -> PResult<'sess, AstPath<'ast>>

Parses a qualified identifier starting with the given identifier.

Source

pub fn parse_path_any(&mut self) -> PResult<'sess, AstPath<'ast>>

Parses a qualified identifier: foo.bar.baz.

Source

pub fn parse_ident(&mut self) -> PResult<'sess, Ident>

Parses an identifier.

Source

pub fn parse_ident_any(&mut self) -> PResult<'sess, Ident>

Parses an identifier. Does not check if the identifier is a reserved keyword.

Source

pub fn parse_ident_opt(&mut self) -> PResult<'sess, Option<Ident>>

Parses an optional identifier.

Auto Trait Implementations§

§

impl<'sess, 'ast> Freeze for Parser<'sess, 'ast>

§

impl<'sess, 'ast> !RefUnwindSafe for Parser<'sess, 'ast>

§

impl<'sess, 'ast> !Send for Parser<'sess, 'ast>

§

impl<'sess, 'ast> !Sync for Parser<'sess, 'ast>

§

impl<'sess, 'ast> Unpin for Parser<'sess, 'ast>

§

impl<'sess, 'ast> !UnwindSafe for Parser<'sess, 'ast>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T, R> CollectAndApply<T, R> for T

Source§

fn collect_and_apply<I, F>(iter: I, f: F) -> R
where I: Iterator<Item = T>, F: FnOnce(&[T]) -> R,

Equivalent to f(&iter.collect::<Vec<_>>()).

Source§

type Output = R

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more

Layout§

Note: Most layout information is completely unstable and may even differ between compilations. The only exception is types with certain repr(...) attributes. Please see the Rust Reference's “Type Layout” chapter for details on type layout guarantees.

Size: 100 bytes