Implement parser & formatter for Pair annotations.

This commit is contained in:
KtorZ 2024-05-01 13:49:52 +02:00 committed by Kasey
parent d8d2fb0ebc
commit b1f0dfdacd
4 changed files with 55 additions and 5 deletions

View File

@ -424,7 +424,14 @@ impl<'comments> Formatter<'comments> {
Annotation::Tuple { elems, .. } => {
wrap_args(elems.iter().map(|t| (self.annotation(t), false)))
}
Annotation::Pair { .. } => todo!(),
Annotation::Pair { fst, snd, .. } => "Pair"
.to_doc()
.append("<")
.append(self.annotation(fst))
.append(break_(",", ", "))
.append(self.annotation(snd))
.append(">")
.group(),
}
.group()
}

View File

@ -1,8 +1,9 @@
use chumsky::prelude::*;
use crate::ast;
use super::{error::ParseError, token::Token};
use crate::{
ast,
builtins::{PAIR, PRELUDE},
};
use chumsky::prelude::*;
pub fn parser() -> impl Parser<Token, ast::Annotation, Error = ParseError> {
recursive(|expression| {
@ -14,6 +15,31 @@ pub fn parser() -> impl Parser<Token, ast::Annotation, Error = ParseError> {
name,
}
}),
// Pair
select! {Token::Name { name } if name == PRELUDE => name}
.then_ignore(just(Token::Dot))
.or_not()
.then_ignore(select! {Token::UpName { name } if name == PAIR => name})
.ignore_then(
expression
.clone()
.separated_by(just(Token::Comma))
.exactly(2)
.delimited_by(just(Token::Less), just(Token::Greater)),
)
.map_with_span(|elems: Vec<ast::Annotation>, span| ast::Annotation::Pair {
location: span,
fst: elems
.first()
.expect("Pair should have exactly 2 elements")
.to_owned()
.into(),
snd: elems
.last()
.expect("Pair should have exactly 2 elements")
.to_owned()
.into(),
}),
// Tuple
expression
.clone()

View File

@ -792,3 +792,13 @@ fn superfluous_parens_in_binop() {
"#
);
}
#[test]
fn format_pairs() {
assert_format!(
r#"
pub fn foo(x: Pair<Int, Int>) {
Pair(x.1st, x.2nd)
}"#
);
}

View File

@ -0,0 +1,7 @@
---
source: crates/aiken-lang/src/tests/format.rs
description: "Code:\n\npub fn foo(x: Pair<Int, Int>) {\n Pair(x.1st, x.2nd)\n}"
---
pub fn foo(x: Pair<Int, Int>) {
Pair(x.1st, x.2nd)
}