Skip to main content

Parser

Struct Parser 

Source
pub struct Parser {
    pub tokens: Vec<Token>,
    pub cursor: usize,
    pub current_token: Token,
    pub base: Option<String>,
    pub spans: Vec<Span>,
    pub remapper: Remapper,
    pub(crate) loop_variables: Vec<String>,
}
Expand description

The Parser

Fields§

§tokens: Vec<Token>

Vector of the tokens

§cursor: usize

Current position

§current_token: Token

Current token

§base: Option<String>

Current base path for resolving imports

§spans: Vec<Span>

A collection of current spans

§remapper: Remapper

Our remapper

§loop_variables: Vec<String>

Stack of active for loop variable names (for nested loops)

Implementations§

Source§

impl Parser

Source

pub fn new(tokens: Vec<Token>, base: Option<String>) -> Self

Public associated function that instantiates a Parser.

Source

pub fn reset(&mut self)

Resets the current token and cursor to the first token in the parser’s token vec

PANICS if the tokens vec is empty!

Source

pub fn parse(&mut self) -> Result<Contract, ParserError>

Parse

Source

pub fn parse_imports(&mut self) -> Result<FilePath, ParserError>

Parses Contract Imports

Source

pub fn match_kind(&mut self, kind: TokenKind) -> Result<TokenKind, ParserError>

Match current token to a type.

Source

pub fn check(&mut self, kind: TokenKind) -> bool

Check the current token’s type against the given type.

Source

pub(crate) fn check_duplicate_label( &self, contract: &mut Contract, macro_name: &str, label: String, span: Span, ) -> Result<(), ParserError>

Checks whether the input label is unique in a macro.

Source

pub fn consume(&mut self)

Consumes the next token.

Source

pub fn consume_all(&mut self, kinds: Vec<TokenKind>)

Consumes following tokens until not contained in the kinds vec of TokenKinds.

Source

pub fn peek(&mut self) -> Option<Token>

Take a look at next token without consuming.

Source

pub fn peek_behind(&self) -> Option<Token>

Take a look at the previous token.

Source

pub fn parse_function(&mut self) -> Result<FunctionDefinition, ParserError>

Source

pub fn parse_event(&mut self) -> Result<EventDefinition, ParserError>

Parse an event.

Source

pub fn parse_constant(&mut self) -> Result<ConstantDefinition, ParserError>

Parse a constant.

Source

pub fn parse_custom_error(&mut self) -> Result<ErrorDefinition, ParserError>

Parse a custom error definition.

Source

pub fn parse_decorator(&mut self) -> Result<Decorator, ParserError>

Parses the decorator blocks above a macro definition.

Several #[...] blocks may be stacked; their flags are merged in source order. Flag names and arguments are only checked for syntax here, the test runner decides what they mean.

Source

pub(crate) fn parse_decorator_flag( &mut self, ) -> Result<DecoratorFlag, ParserError>

Parses a single decorator flag: name or name(arg, key = arg, ...).

Source

pub(crate) fn parse_decorator_arg( &mut self, flag: &str, ) -> Result<DecoratorArg, ParserError>

Parses a decorator flag argument, optionally prefixed with key =.

Source

pub(crate) fn span_from(&self, start: &Span) -> Span

The source range from start through the last consumed token.

Source

pub(crate) fn decorator_error(&self, hint: String) -> ParserError

Builds a decorator syntax error at the current token.

Source

pub fn parse_macro( &mut self, contract: &mut Contract, ) -> Result<MacroDefinition, ParserError>

Parses a macro.

It should parse the following : macro MACRO_NAME(args…) = takes (x) returns (n) {…}

Source

pub(crate) fn at_opcode_operand(&self) -> bool

Returns true if the current token can start an opcode operand.

Source

pub(crate) fn takes_opcode_operands(&self, o: Opcode) -> bool

Returns true if the opcode just consumed is followed by operands resolved at compile time, e.g. dupn 17 or push2 [SIZE]. A push followed by a hex literal keeps the plain form.

Source

pub(crate) fn parse_opcode_operands( &mut self, o: Opcode, opcode_span: Span, ) -> Result<Statement, ParserError>

Parses the operands of an opcode that carries immediate data.

Covers DUPN, SWAPN and EXCHANGE (dupn 17, exchange 1 2) as well as PUSH1..PUSH32 with a non-literal value (push2 [SIZE]). Each operand is a compile-time expression: a decimal or hex literal, [CONSTANT], <arg>, a loop variable, or a parenthesized expression. Literal operands are validated immediately; all others once resolved during codegen.

Source

pub fn parse_body( &mut self, macro_name: &str, contract: &mut Contract, ) -> Result<Vec<Statement>, ParserError>

Parse the body of a macro.

Only HEX, OPCODES, labels, builtins, and MACRO calls should be authorized.

Source

pub fn parse_for_loop( &mut self, macro_name: &str, ) -> Result<Statement, ParserError>

Parse a for loop statement

Syntax: for(var in start..end) { body } or for(var in start..end step N) { body }

Source

pub fn parse_if_statement( &mut self, macro_name: &str, ) -> Result<Statement, ParserError>

Parse a compile-time if statement

Source

pub(crate) fn parse_if_body( &mut self, macro_name: &str, ) -> Result<Vec<Statement>, ParserError>

Parse the body of an if statement (reuses for loop body parsing logic)

Source

pub(crate) fn parse_for_body( &mut self, macro_name: &str, ) -> Result<Vec<Statement>, ParserError>

Parse the body of a for loop (similar to parse_body but handles interpolation)

Source

pub fn parse_label( &mut self, parent_macro_name: String, ) -> Result<Vec<Statement>, ParserError>

Parse the body of a label.

§Examples

Below is an example of a label that contains a Macro Invocation, Literals, and Opcodes.

error:
    TRANSFER()
    0x20 0x00 return
Source

pub fn parse_newline(&mut self) -> Result<(), ParserError>

Parse new lines.

No-return since newlines are non-essential.

Source

pub(crate) fn at_builtin_expression_arg(&self) -> bool

Returns true if the current builtin argument is a compile-time expression rather than a single literal, constant, identifier, or builtin call, e.g. <arg> or [BASE] + 0x20.

Source

pub fn parse_builtin_args( &mut self, ) -> Result<Vec<BuiltinFunctionArg>, ParserError>

Parse the argument of a builtin function call.

Source

pub fn parse_args( &mut self, select_name: bool, select_type: bool, has_indexed: bool, ) -> Result<Vec<Argument>, ParserError>

Parse abi arguments

Arguments can be typed or not. Between parenthesis. Works for both inputs and outputs. It should parse the following : (uint256 a, bool b, …)

Source

pub fn parse_single_arg(&mut self) -> Result<usize, ParserError>

Parses the following : (x)

Source

pub(crate) fn parse_single_macro_argument( &mut self, ) -> Result<MacroArg, ParserError>

Parse a single macro argument

Source

pub fn parse_macro_call_args( &mut self, macro_name: String, ) -> Result<Vec<MacroArg>, ParserError>

Parse the arguments of a macro call.

Source

pub fn parse_table(&mut self) -> Result<TableDefinition, ParserError>

Parses a table (JumpTable, JumpTablePacked, or CodeTable).

It should parse the following : (jumptable|jumptable__packed|table) NAME() {…}

Source

pub fn parse_table_body( &mut self, is_code_table: bool, ) -> Result<Vec<Statement>, ParserError>

Parse the body of a table.

Only LabelCall and Code Statements should be authorized.

Source

pub fn parse_constant_push(&mut self) -> Result<(String, Span), ParserError>

Parses a constant push.

Source

pub fn parse_arg_call(&mut self) -> Result<(String, Span), ParserError>

Parses an argument call.

§Examples

When an argument is called in Huff, it is wrapped in angle brackets like so:

#define macro EXAMPLE_FUNCTION(error) = takes (0) returns (0) {
    <error> jumpi
}
Source

pub(crate) fn parse_arg_call_or_invocation( &mut self, parent_macro_name: String, ) -> Result<Statement, ParserError>

Parse an arg call or arg macro invocation: <arg> or <arg>(...) Returns either an ArgCall or ArgMacroInvocation statement

Source

pub(crate) fn parse_arg_call_or_invocation_after_angle( &mut self, parent_macro_name: String, angle_span: Span, ) -> Result<Statement, ParserError>

Parse an arg call or arg macro invocation after < has already been consumed This is used in for loop bodies where we check for loop variables first

Source

pub fn parse_nl_or_whitespace(&mut self) -> Result<(), ParserError>

Parses whitespaces and newlines until none are left.

Source

pub fn parse_arg_type(&mut self) -> Result<String, ParserError>

Parses the type of an argument as its canonical ABI name, such as uint256[] or (address,uint256)[2].

Source

pub(crate) fn parse_tuple_component(&mut self) -> Result<String, ParserError>

Parses a component of a tuple type, whose optional name is not part of the type

Source

pub fn parse_primitive_type( &mut self, prim: PrimitiveEVMType, ) -> Result<TokenKind, ParserError>

Parses a primitive EVM type. Arrays of primitive types are not considered as primitive types themselves.

Source

pub(crate) fn is_expression_context(&mut self) -> bool

Check if the current context indicates we’re parsing an expression (i.e., the next token is an operator)

Source

pub(crate) fn parse_constant_expression( &mut self, ) -> Result<Expression, ParserError>

Parse an arithmetic expression (entry point for constant expressions).

Implements operator precedence:

  • Lowest: ==, !=, <, >, <=, >= (comparison)
  • Higher: + - (additive)
  • Higher: * / % (multiplicative)
  • Highest: unary -, !, literals, parentheses
Source

pub(crate) fn parse_comparison_expression( &mut self, ) -> Result<Expression, ParserError>

Parse comparison operators (lowest precedence binary operators).

Source

pub(crate) fn parse_additive_expression( &mut self, ) -> Result<Expression, ParserError>

Parse addition and subtraction.

Source

pub(crate) fn parse_multiplicative_expression( &mut self, ) -> Result<Expression, ParserError>

Parse multiplication, division, and modulo (higher precedence).

Source

pub(crate) fn parse_unary_expression( &mut self, ) -> Result<Expression, ParserError>

Parse unary operators (negation and logical NOT).

Source

pub(crate) fn parse_primary_expression( &mut self, ) -> Result<Expression, ParserError>

Parse primary expressions: literals, bracketed constants, and parenthesized expressions.

Trait Implementations§

Source§

impl Clone for Parser

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Parser

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

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

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

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> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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<S, T> Upcast<T> for S
where T: UpcastFrom<S> + ?Sized, S: ?Sized,

Source§

fn upcast(&self) -> &T
where Self: ErasableGeneric, T: Sized + ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider ref type within the Wasm bindgen generics type system. Read more
Source§

fn upcast_into(self) -> T
where Self: Sized + ErasableGeneric, T: Sized + ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider type within the Wasm bindgen generics type system. Read more
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

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
§

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: 240 bytes