initial version of annotation formatting

This commit is contained in:
Folkert 2020-07-09 17:41:21 +02:00
parent 1fc17626d4
commit 672b67d527
5 changed files with 200 additions and 30 deletions

View file

@ -1,36 +1,38 @@
use crate::annotation::fmt_annotation;
use crate::expr::{fmt_expr, is_multiline_expr};
use crate::pattern::fmt_pattern;
use crate::spaces::{fmt_spaces, newline, INDENT};
use bumpalo::collections::String;
use roc_parse::ast::{Def, Expr};
use roc_parse::ast::{Def, Expr, Pattern, TypeAnnotation};
pub fn fmt_def<'a>(buf: &mut String<'a>, def: &'a Def<'a>, indent: u16) {
use roc_parse::ast::Def::*;
match def {
Annotation(_, _) => panic!("TODO have format_def support Annotation"),
Alias { .. } => panic!("TODO have format_def support Alias"),
Body(loc_pattern, loc_expr) => {
fmt_pattern(buf, &loc_pattern.value, indent, true, false);
buf.push_str(" =");
if is_multiline_expr(&loc_expr.value) {
match &loc_expr.value {
Expr::Record { .. } | Expr::List(_) => {
newline(buf, indent + INDENT);
fmt_expr(buf, &loc_expr.value, indent + INDENT, false, true);
}
_ => {
buf.push(' ');
fmt_expr(buf, &loc_expr.value, indent, false, true);
}
}
} else {
Annotation(loc_pattern, loc_annotation) => {
fmt_type_annotation(buf, &loc_pattern.value, &loc_annotation.value, indent);
}
Alias { name, vars, ann } => {
buf.push_str(name.value);
if vars.is_empty() {
buf.push(' ');
fmt_expr(buf, &loc_expr.value, indent, false, true);
} else {
for var in *vars {
buf.push(' ');
fmt_pattern(buf, &var.value, indent, false, false);
}
}
buf.push_str(" : ");
fmt_annotation(buf, &ann.value, indent);
}
Body(loc_pattern, loc_expr) => {
fmt_body(buf, &loc_pattern.value, &loc_expr.value, indent);
}
TypedBody(_loc_pattern, _loc_annotation, _loc_expr) => {
panic!("TODO support Annotation in TypedBody");
unreachable!("annotations and bodies have not yet been merged into TypedBody");
}
SpaceBefore(sub_def, spaces) => {
fmt_spaces(buf, spaces.iter(), indent);
@ -44,3 +46,39 @@ pub fn fmt_def<'a>(buf: &mut String<'a>, def: &'a Def<'a>, indent: u16) {
Nested(def) => fmt_def(buf, def, indent),
}
}
pub fn fmt_body<'a>(
buf: &mut String<'a>,
pattern: &'a Pattern<'a>,
body: &'a Expr<'a>,
indent: u16,
) {
fmt_pattern(buf, pattern, indent, true, false);
buf.push_str(" =");
if is_multiline_expr(body) {
match body {
Expr::Record { .. } | Expr::List(_) => {
newline(buf, indent + INDENT);
fmt_expr(buf, body, indent + INDENT, false, true);
}
_ => {
buf.push(' ');
fmt_expr(buf, body, indent, false, true);
}
}
} else {
buf.push(' ');
fmt_expr(buf, body, indent, false, true);
}
}
pub fn fmt_type_annotation<'a>(
buf: &mut String<'a>,
pattern: &'a Pattern<'a>,
annotation: &'a TypeAnnotation<'a>,
indent: u16,
) {
fmt_pattern(buf, pattern, indent, true, false);
buf.push_str(" : ");
fmt_annotation(buf, annotation, indent);
}