dsl_util: add trait for alias body parsing

This could be a closure argument passed to expand_aliases(), but it's nice
that the parsing function is constrained by the aliases map type.
This commit is contained in:
Yuya Nishihara 2024-05-18 12:44:48 +09:00
parent 7be4a0a560
commit 0efd2aa316
2 changed files with 33 additions and 4 deletions

View file

@ -17,9 +17,9 @@ use std::{error, mem};
use itertools::Itertools as _;
use jj_lib::dsl_util::{
self, collect_similar, AliasDeclaration, AliasDeclarationParser, AliasExpandError,
AliasExpandableExpression, AliasId, AliasesMap, ExpressionFolder, FoldableExpression,
InvalidArguments, StringLiteralParser,
self, collect_similar, AliasDeclaration, AliasDeclarationParser, AliasDefinitionParser,
AliasExpandError, AliasExpandableExpression, AliasId, AliasesMap, ExpressionFolder,
FoldableExpression, InvalidArguments, StringLiteralParser,
};
use once_cell::sync::Lazy;
use pest::iterators::{Pair, Pairs};
@ -583,6 +583,15 @@ impl AliasDeclarationParser for TemplateAliasParser {
}
}
impl AliasDefinitionParser for TemplateAliasParser {
type Output<'i> = ExpressionKind<'i>;
type Error = TemplateParseError;
fn parse_definition<'i>(&self, source: &'i str) -> Result<ExpressionNode<'i>, Self::Error> {
parse_template(source)
}
}
/// Expand aliases recursively.
pub fn expand_aliases<'i>(
node: ExpressionNode<'i>,
@ -614,7 +623,8 @@ pub fn expand_aliases<'i>(
locals,
};
// Parsed defn could be cached if needed.
parse_template(defn)
TemplateAliasParser
.parse_definition(defn)
.and_then(|node| expand_node(node, expanding_state))
.map(|node| ExpressionKind::alias_expanded(id, Box::new(node)))
.map_err(|e| e.within_alias_expansion(id, span))

View file

@ -324,6 +324,11 @@ pub enum AliasDeclaration {
Function(String, Vec<String>),
}
// AliasDeclarationParser and AliasDefinitionParser can be merged into a single
// trait, but it's unclear whether doing that would simplify the abstraction.
// For now, they have to be separate traits because revset isn't migrated to
// ExpressionNode tree yet.
/// Parser for symbol and function alias declaration.
pub trait AliasDeclarationParser {
/// Parse error type.
@ -333,6 +338,20 @@ pub trait AliasDeclarationParser {
fn parse_declaration(&self, source: &str) -> Result<AliasDeclaration, Self::Error>;
}
/// Parser for symbol and function alias definition.
pub trait AliasDefinitionParser {
/// Expression item type.
type Output<'i>;
/// Parse error type.
type Error;
/// Parses alias body.
fn parse_definition<'i>(
&self,
source: &'i str,
) -> Result<ExpressionNode<'i, Self::Output<'i>>, Self::Error>;
}
/// Expression item that supports alias substitution.
pub trait AliasExpandableExpression<'i>: FoldableExpression<'i> {
/// Wraps identifier.