lehit 0.2.0

Embeddable Lehit language frontend and Cranelift JIT runtime
Documentation
use chumsky::prelude::*;

use crate::parsing::{Span, ast::Expression, lexer::Token};

#[derive(Debug, Clone)]
pub struct IfExpressionDeclaration {
    pub span: Span,
    pub condition: Expression,
}

#[derive(Debug, Clone)]
pub struct IfExpression {
    pub span: Span,
    pub declaration: IfExpressionDeclaration,
    pub expression: Expression,
    pub else_ifs: Vec<IfExpressionElseIf>,
    pub else_: Option<IfExpressionElse>,
}

#[derive(Debug, Clone)]
pub struct IfExpressionElseIf {
    pub declaration: IfExpressionDeclaration,
    pub expression: Expression,
}

#[derive(Debug, Clone)]
pub struct IfExpressionElse {
    pub expression: Expression,
}

pub(crate) fn if_expression_parser<'src, I, EP>(
    expression_parser: EP,
) -> impl Parser<'src, I, IfExpression, extra::Err<Rich<'src, Token, Span>>> + Clone
where
    I: Input<'src, Token = Token, Span = Span>,
    EP: Parser<'src, I, Expression, extra::Err<Rich<'src, Token, Span>>> + Clone + 'src,
{
    if_expression_declaration_parser(expression_parser.clone())
        .then(expression_parser.clone())
        .then(
            if_expression_else_if_parser(expression_parser.clone())
                .repeated()
                .collect::<Vec<_>>(),
        )
        .then(just(Token::ElseKw).ignore_then(expression_parser).or_not())
        .map_with(|(((ied, expr), else_ifs), else_expr), ex| IfExpression {
            span: ex.span(),
            declaration: ied,
            expression: expr,
            else_ifs: else_ifs,
            else_: else_expr.map(|expr| IfExpressionElse { expression: expr }),
        })
}

pub(crate) fn if_expression_else_if_parser<'src, I, EP>(
    expression_parser: EP,
) -> impl Parser<'src, I, IfExpressionElseIf, extra::Err<Rich<'src, Token, Span>>> + Clone
where
    I: Input<'src, Token = Token, Span = Span>,
    EP: Parser<'src, I, Expression, extra::Err<Rich<'src, Token, Span>>> + Clone + 'src,
{
    just(Token::ElseKw)
        .ignore_then(if_expression_declaration_parser(expression_parser.clone()))
        .then(expression_parser)
        .map(|(ied, expr)| IfExpressionElseIf {
            declaration: ied,
            expression: expr,
        })
}

pub(crate) fn if_expression_declaration_parser<'src, I, EP>(
    expression_parser: EP,
) -> impl Parser<'src, I, IfExpressionDeclaration, extra::Err<Rich<'src, Token, Span>>> + Clone
where
    I: Input<'src, Token = Token, Span = Span>,
    EP: Parser<'src, I, Expression, extra::Err<Rich<'src, Token, Span>>> + Clone + 'src,
{
    just(Token::IfKw)
        .ignore_then(expression_parser)
        .map_with(|condition, ex| IfExpressionDeclaration {
            span: ex.span(),
            condition: condition,
        })
}