Skip to main content

IfParser

This class provides functionality for parsing conditional expressions by processing a sequence of tokens into an executable or evaluatable structure. It handles the normalization of multi-word operators like 'is not' and 'not in' while implementing a top-down operator precedence parsing algorithm. The parser ensures all tokens are consumed and translates them into corresponding operator or literal objects.

Attributes

AttributeTypeDescription
error_classtype = ValueErrorThe exception class raised when the parser encounters unused tokens or syntax errors during the parsing process.

Constructor

Signature

def IfParser(
tokens: list
)

Parameters

NameTypeDescription
tokenslistA list of string tokens to be parsed.

Methods


translate_token()

@classmethod
def translate_token(
token: string
) - > object

Converts a raw string token into its corresponding operator object or a literal variable.

Parameters

NameTypeDescription
tokenstringThe raw string token extracted from the expression to be converted.

Returns

TypeDescription
objectAn instance of an operator class or a Literal object representing the token.

next_token()

@classmethod
def next_token() - > object

Advances the internal pointer and retrieves the next token from the mapped token list.

Returns

TypeDescription
objectThe next token object in the sequence, or EndToken if the end of the list is reached.

parse()

@classmethod
def parse() - > object

Initiates the parsing process and ensures that the entire expression has been consumed.

Returns

TypeDescription
objectThe result of the evaluated expression tree.

expression()

@classmethod
def expression(
rbp: integer = 0
) - > object

Parses an expression using Top Down Operator Precedence (Pratt parsing) based on binding powers.

Parameters

NameTypeDescription
rbpinteger = 0The right binding power used to determine operator precedence and nesting.

Returns

TypeDescription
objectThe parsed expression node or evaluated result.

create_var()

@classmethod
def create_var(
value: any
) - > [Literal](literal.md?sid=django_template_smartif_literal)

Wraps a raw value into a Literal object for use within the expression tree.

Parameters

NameTypeDescription
valueanyThe raw value or identifier to be treated as a literal in the expression.

Returns

TypeDescription
[Literal](literal.md?sid=django_template_smartif_literal)A Literal object instance containing the provided value.