Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add a pretty.rs based MonoType formatter #4809

Merged
merged 3 commits into from
Jun 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 11 additions & 11 deletions libflux/flux-core/src/doc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1548,7 +1548,7 @@ mod test {
description: None,
required: true,
} ],
flux_type: "(x:A) => int".to_string(),
flux_type: "(x: A) => int".to_string(),
is_option: false,
source_location: loc.get(49,9,49,21),
examples: vec![],
Expand Down Expand Up @@ -1674,7 +1674,7 @@ foo.a
description: Some("This is a description of x.".to_string()),
required: true,
} ],
flux_type: "(x:A) => int".to_string(),
flux_type: "(x: A) => int".to_string(),
is_option: false,
source_location: loc.get(49,9,49,21),
examples: vec![Example {
Expand Down Expand Up @@ -1806,7 +1806,7 @@ foo.a
description: Some("This is a description of x.".to_string()),
required: true,
} ],
flux_type: "(x:A) => int".to_string(),
flux_type: "(x: A) => int".to_string(),
is_option: false,
source_location: loc.get(36,9,36,21),
examples: vec![],
Expand Down Expand Up @@ -1955,7 +1955,7 @@ foo.a
required: false,
}
],
flux_type: "(<-p:A, x:A) => A where A: Addable".to_string(),
flux_type: "(<-p: A, x: A) => A where A: Addable".to_string(),
is_option: false,
source_location: loc.get(15,9,15,30),
examples: vec![],
Expand Down Expand Up @@ -2022,7 +2022,7 @@ foo.a
required: true,
},
],
flux_type: "(a:A, b:B, c:C) => int".to_string(),
flux_type: "(a: A, b: B, c: C) => int".to_string(),
is_option: false,
source_location: loc.get(14,9,14,27),
examples: vec![],
Expand Down Expand Up @@ -2122,7 +2122,7 @@ foo.a
description: Some("Y has a long description too.".to_string()),
required: true,
}],
flux_type: "(x:A, y:A) => A where A: Addable".to_string(),
flux_type: "(x: A, y: A) => A where A: Addable".to_string(),
is_option: false,
source_location: loc.get(20,9,20,27),
examples: vec![],
Expand Down Expand Up @@ -2183,7 +2183,7 @@ foo.a
description: Some("Y has a long description too.".to_string()),
required: false,
}],
flux_type: "(x:A, y:A) => A where A: Addable".to_string(),
flux_type: "(x: A, y: A) => A where A: Addable".to_string(),
is_option: false,
source_location: loc.get(20,9,20,27),
examples: vec![],
Expand Down Expand Up @@ -2236,7 +2236,7 @@ foo.a
headline: "f is a function.".to_string(),
description: None,
parameters: vec![],
flux_type: "(x:A) => A".to_string(),
flux_type: "(x: A) => A".to_string(),
is_option: false,
source_location: loc.get(6, 9, 6, 21),
examples: vec![],
Expand Down Expand Up @@ -2283,7 +2283,7 @@ foo.a
description: None,
required: true,
}],
flux_type: "(x:A, y:A) => A where A: Addable".to_string(),
flux_type: "(x: A, y: A) => A where A: Addable".to_string(),
is_option: false,
source_location: loc.get(9, 9, 9, 29),
examples: vec![],
Expand Down Expand Up @@ -2330,7 +2330,7 @@ foo.a
description: None,
required: true,
}],
flux_type: "(<-y:A, x:A) => A where A: Addable".to_string(),
flux_type: "(<-y: A, x: A) => A where A: Addable".to_string(),
is_option: false,
source_location: loc.get(9, 9, 9, 32),
examples: vec![],
Expand Down Expand Up @@ -2377,7 +2377,7 @@ foo.a
description: None,
required: true,
}],
flux_type: "(x:A, ?y:A) => A where A: Addable".to_string(),
flux_type: "(x: A, ?y: A) => A where A: Addable".to_string(),
is_option: false,
source_location: loc.get(9, 9, 9, 31),
examples: vec![],
Expand Down
9 changes: 4 additions & 5 deletions libflux/flux-core/src/formatter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,17 +70,16 @@ fn format_item_list<'doc>(
)
}

fn comma_list_with<'doc, I>(
pub(crate) fn comma_list_with<'doc, I>(
arena: &'doc Arena<'doc>,
docs: impl IntoIterator<Item = Doc<'doc>, IntoIter = I>,
line: Doc<'doc>,
) -> Doc<'doc>
where
I: ExactSizeIterator<Item = Doc<'doc>>,
I: Iterator<Item = Doc<'doc>>,
{
let docs = docs.into_iter();
let len = docs.len();
let trailing_comma = if len == 0 {
let mut docs = docs.into_iter().peekable();
let trailing_comma = if docs.peek().is_none() {
arena.nil()
} else {
arena.text(",").flat_alt(arena.nil())
Expand Down
4 changes: 4 additions & 0 deletions libflux/flux-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@
#[macro_use]
extern crate serde_derive;

#[macro_use]
#[cfg(test)]
extern crate pretty_assertions;

// Only include the doc module if the feature is enabled.
// The code has lots of dependencies we do not want as part of the crate by default.
#[cfg(feature = "doc")]
Expand Down
210 changes: 194 additions & 16 deletions libflux/flux-core/src/semantic/formatter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,14 @@ pub fn format_node(node: walk::Node) -> Result<String, Error> {
formatter.output()
}

/// Format a `MonoType`
pub fn format_monotype(typ: &MonoType) -> String {
let arena = Arena::default();
let mut formatter = DocFormatter { arena: &arena };
let doc = formatter.format_monotype(typ);
doc.pretty(120).to_string()
}

/// Struct to hold data related to formatting such as formatted code,
/// options, and errors.
/// Provides methods for formatting files and strings of source code.
Expand Down Expand Up @@ -292,7 +300,7 @@ impl Formatter {
}

fn format_text_part(&mut self, n: &semantic::nodes::TextPart) {
let escaped_string = self.escape_string(&n.value);
let escaped_string = escape_string(&n.value);
self.write_string(&escaped_string);
}

Expand Down Expand Up @@ -744,26 +752,12 @@ impl Formatter {
}
// Write out escaped string value
self.write_rune('"');
let escaped_string = self.escape_string(&n.value);
let escaped_string = escape_string(&n.value);
self.write_string(&escaped_string);
self.write_rune('"');
// self.write_string(&format!(":{}", MonoType::String.to_string()));
}

fn escape_string(&mut self, s: &str) -> String {
if !(s.contains('\"') || s.contains('\\')) {
return s.to_string();
}
let mut escaped = String::with_capacity(s.len() * 2);
for r in s.chars() {
if r == '"' || r == '\\' {
escaped.push('\\')
}
escaped.push(r)
}
escaped
}

fn format_boolean_literal(&mut self, n: &semantic::nodes::BooleanLit) {
let s: &str = if n.value { "true" } else { "false" };
self.write_string(s);
Expand Down Expand Up @@ -890,6 +884,190 @@ impl Formatter {
}
}

use pretty::{docs, DocAllocator};

use crate::formatter::comma_list_with;

type Arena<'doc> = pretty::Arena<'doc>;
type Doc<'doc> = pretty::DocBuilder<'doc, Arena<'doc>, ()>;

const MULTILINE: usize = 4;
const INDENT: isize = INDENT_BYTES.len() as isize;

struct DocFormatter<'doc> {
arena: &'doc Arena<'doc>,
}

impl<'doc> DocFormatter<'doc> {
fn base_multiline(&self, base: &ast::BaseNode) -> Doc<'doc> {
self.multiline(base.is_multiline())
}

fn multiline(&self, multiline: bool) -> Doc<'doc> {
if multiline {
self.arena.hardline()
} else {
self.arena.line()
}
}

fn base_multiline_(&self, base: &ast::BaseNode) -> Doc<'doc> {
self.multiline_(base.is_multiline())
}

fn multiline_(&self, multiline: bool) -> Doc<'doc> {
if multiline {
self.arena.hardline()
} else {
self.arena.line_()
}
}

fn format_monotype(&self, n: &'doc MonoType) -> Doc<'doc> {
let arena = self.arena;
match n {
MonoType::Error => arena.text("<error>"),
MonoType::Var(tv) => docs![arena, "#", tv.to_string()],
MonoType::BoundVar(tv) => arena.text(tv.to_string()),
MonoType::Builtin(nt) => arena.text(nt.to_string()),
MonoType::Collection(col) => match col.collection {
CollectionType::Array => {
docs![arena, "[", self.format_monotype(&col.arg), "]",]
}
CollectionType::Vector => {
docs![arena, "v[", self.format_monotype(&col.arg), "]",]
}
CollectionType::Stream => {
docs![arena, "stream[", self.format_monotype(&col.arg), "]",]
}
},
MonoType::Dict(dict) => {
docs![
arena,
"[",
self.format_monotype(&dict.key),
":",
self.format_monotype(&dict.val),
"]",
]
}
MonoType::Record(n) => {
let multiline = n.fields().count() > MULTILINE;
let line = self.multiline(multiline);
let line_ = self.multiline_(multiline);

let mut fields = n.fields();

let fields_doc = comma_list_with(
arena,
fields.by_ref().map(|p| {
docs![arena, p.k.to_string(), ": ", self.format_monotype(&p.v),].group()
}),
line,
);

docs![
arena,
"{",
docs![
arena,
line_.clone(),
if let Some(typ) = fields.tail() {
docs![
arena,
docs![arena, self.format_monotype(typ), arena.line(), "with",]
.group(),
arena.line(),
]
} else {
arena.nil()
},
fields_doc,
]
.nest(INDENT),
line_,
"}",
]
}
MonoType::Fun(n) => {
let multiline = n.parameters_len() > MULTILINE;
let line = self.multiline(multiline);
let line_ = self.multiline_(multiline);

docs![
arena,
"(",
docs![
arena,
line_.clone(),
comma_list_with(
arena,
n.pipe
.iter()
.map(|p| {
docs![
arena,
if p.k == "<-" {
docs![arena, &p.k]
} else {
docs![arena, "<-", &p.k]
},
": ",
self.format_monotype(&p.v),
]
})
.chain(n.req.iter().map(|(k, v)| {
docs![arena, k.as_str(), ": ", self.format_monotype(v),]
}))
.chain(n.opt.iter().map(|(name, argument)| {
docs![
arena,
"?",
name.as_str(),
": ",
self.format_monotype(&argument.typ),
match &argument.default {
Some(default) =>
docs![arena, " = ", self.format_monotype(default)],
None => arena.nil(),
}
]
})),
line,
),
]
.nest(INDENT),
line_.clone(),
")",
" => ",
self.format_monotype(&n.retn),
]
}
MonoType::Label(label) => self.format_string_literal(label),
}
.group()
}

fn format_string_literal(&self, value: &str) -> Doc<'doc> {
let arena = self.arena;
docs![arena, "\"", escape_string(value), "\""]
}
}

fn escape_string(s: &str) -> String {
if !(s.contains('\"') || s.contains('\\')) {
return s.to_string();
}
let mut escaped = String::with_capacity(s.len() * 2);
for r in s.chars() {
if r == '"' || r == '\\' {
escaped.push('\\')
}
escaped.push(r)
}
escaped
}

fn get_precedence(node: &walk::Node) -> u32 {
match node {
walk::Node::BinaryExpr(p) => Operator::new(&p.operator).get_precedence(),
Expand Down
Loading