use crate::parsing::ast::{
ArithmeticComputation, CalendarPeriodUnit, ComparisonComputation, DateCalendarKind,
DateRelativeKind, LogicalConnective,
};
use std::fmt::{self, Write};
pub(crate) trait SyntaxNode<'a>: Copy {
type Atom: fmt::Display + Clone;
fn view(self) -> SyntaxView<'a, Self>;
}
pub(crate) enum SyntaxView<'a, N: SyntaxNode<'a>> {
Atom {
atom: N::Atom,
starts_with_sign: bool,
},
ImplicitRowValue,
Logical {
connective: LogicalConnective,
operands: Vec<N>,
},
Chain {
level: &'a ArithmeticComputation,
operands: Vec<N>,
ops: Vec<&'a ArithmeticComputation>,
},
Comparison(N, &'a ComparisonComputation, N),
UnitConversion(N, &'a dyn fmt::Display),
Not(N),
IsVeto(N),
IsNotVeto(N),
Prefix(&'a dyn fmt::Display, N),
DateRelative(&'a DateRelativeKind, N),
DateCalendar(&'a DateCalendarKind, &'a CalendarPeriodUnit, N),
RangeLiteral(N, N),
PastFutureRange(&'a DateRelativeKind, N),
RangeContainment(N, N),
ListCommand {
list: N,
command: CommandView<'a, N>,
},
Member {
base: N,
path: N::Atom,
parenthesize_base: bool,
},
Negate(N),
Reciprocal(N),
Piecewise(Vec<(N, N)>),
}
pub(crate) enum CommandView<'a, N: SyntaxNode<'a>> {
Find(Vec<N>),
First,
Last,
Count,
Reduce(&'static str, Option<N>),
Predicate(&'static str, PredicateView<N>),
Sort {
descending: bool,
argument: Option<N>,
},
Top(N),
With(Vec<(Option<N::Atom>, N)>),
Key(Vec<N::Atom>),
Step(&'static str, Option<N>),
}
pub(crate) enum PredicateView<N> {
Value(N),
Instance(N),
}
pub(crate) struct Syntax<N>(pub N);
pub(crate) struct CommandSyntax<'v, 'a, N: SyntaxNode<'a>>(pub &'v CommandView<'a, N>);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OperandSide {
Left,
Inner,
Right,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Associativity {
Left,
Right,
}
pub fn arithmetic_precedence(op: &ArithmeticComputation) -> u8 {
match op {
ArithmeticComputation::Add | ArithmeticComputation::Subtract => 6,
ArithmeticComputation::Multiply
| ArithmeticComputation::Divide
| ArithmeticComputation::Modulo => 7,
ArithmeticComputation::Power => 9,
}
}
pub fn arithmetic_associativity(op: &ArithmeticComputation) -> Associativity {
match op {
ArithmeticComputation::Power => Associativity::Right,
ArithmeticComputation::Add
| ArithmeticComputation::Subtract
| ArithmeticComputation::Multiply
| ArithmeticComputation::Divide
| ArithmeticComputation::Modulo => Associativity::Left,
}
}
fn operand_needs_parentheses(
child_prec: u8,
parent_prec: u8,
side: OperandSide,
parent_assoc: Option<Associativity>,
) -> bool {
if child_prec < parent_prec {
return true;
}
if child_prec > parent_prec {
return false;
}
if parent_prec == COMPARISON_PRECEDENCE {
return true;
}
match parent_assoc {
None => false,
Some(Associativity::Left) => matches!(side, OperandSide::Inner | OperandSide::Right),
Some(Associativity::Right) => matches!(side, OperandSide::Left),
}
}
fn expression_precedence<'a, N: SyntaxNode<'a>>(node: N) -> u8 {
view_precedence(&node.view())
}
fn view_precedence<'a, N: SyntaxNode<'a>>(view: &SyntaxView<'a, N>) -> u8 {
match view {
SyntaxView::Logical { connective, .. } => connective_precedence(*connective),
SyntaxView::Not(_) | SyntaxView::IsNotVeto(_) | SyntaxView::Negate(_) => 3,
SyntaxView::Comparison(..)
| SyntaxView::IsVeto(_)
| SyntaxView::RangeContainment(..)
| SyntaxView::DateRelative(..)
| SyntaxView::DateCalendar(..) => COMPARISON_PRECEDENCE,
SyntaxView::ListCommand { .. } => PIPE_PRECEDENCE,
SyntaxView::Chain { level, .. } => arithmetic_precedence(level),
SyntaxView::Reciprocal(_) => arithmetic_precedence(&ArithmeticComputation::Multiply),
SyntaxView::UnitConversion(..) => 8,
SyntaxView::Prefix(..) => 10,
SyntaxView::RangeLiteral(..)
| SyntaxView::PastFutureRange(..)
| SyntaxView::Atom { .. }
| SyntaxView::Member { .. }
| SyntaxView::Piecewise(_) => OPERAND_PRECEDENCE,
SyntaxView::ImplicitRowValue => {
panic!("BUG: implicit row value rendered outside a predicate comparison")
}
}
}
fn connective_precedence(connective: LogicalConnective) -> u8 {
match connective {
LogicalConnective::And => 2,
LogicalConnective::Or => 1,
}
}
const COMPARISON_PRECEDENCE: u8 = 4;
const PIPE_PRECEDENCE: u8 = 5;
const OPERAND_PRECEDENCE: u8 = 11;
fn is_bare_argument<'a, N: SyntaxNode<'a>>(node: N) -> bool {
is_comparison_operand(node) && !starts_with_sign(node)
}
fn starts_with_sign<'a, N: SyntaxNode<'a>>(mut node: N) -> bool {
loop {
match node.view() {
SyntaxView::Atom {
starts_with_sign, ..
} => return starts_with_sign,
SyntaxView::RangeLiteral(left, _) => node = left,
_ => return false,
}
}
}
fn is_comparison_operand<'a, N: SyntaxNode<'a>>(node: N) -> bool {
expression_precedence(node) == OPERAND_PRECEDENCE
}
fn is_prefix_bare_operand<'a, N: SyntaxNode<'a>>(mut operand: N) -> bool {
loop {
match operand.view() {
SyntaxView::Prefix(_, inner) => operand = inner,
_ => return is_bare_argument(operand),
}
}
}
fn is_bare_predicate<'a, N: SyntaxNode<'a>>(form: &PredicateView<N>) -> bool {
match form {
PredicateView::Value(expr) => matches!(
expr.view(),
SyntaxView::Comparison(left, _, _) | SyntaxView::RangeContainment(left, _)
if matches!(left.view(), SyntaxView::ImplicitRowValue)
),
PredicateView::Instance(expr) => match expr.view() {
SyntaxView::Comparison(left, _, right) | SyntaxView::RangeContainment(left, right) => {
is_bare_argument(left) && is_comparison_operand(right)
}
_ => is_bare_argument(*expr),
},
}
}
fn command_ends_with_bare_argument<'a, N: SyntaxNode<'a>>(command: &CommandView<'a, N>) -> bool {
match command {
CommandView::Find(keys) => keys.iter().all(|key| is_bare_argument(*key)),
CommandView::Reduce(_, argument) => argument.is_some_and(is_bare_argument),
CommandView::Predicate(_, form) => is_bare_predicate(form),
CommandView::Top(n) => is_bare_argument(*n),
CommandView::Step(_, step) => step.is_some_and(is_bare_argument),
CommandView::With(_) => true,
CommandView::First
| CommandView::Last
| CommandView::Count
| CommandView::Sort { .. }
| CommandView::Key(_) => false,
}
}
enum TailStep<N> {
Decided(bool),
Continue(N),
}
fn ends_with_bare_argument<'a, N: SyntaxNode<'a>>(mut node: N) -> bool {
loop {
let view = node.view();
let my_prec = view_precedence(&view);
let right_spine = |right: N, parent_prec: u8, assoc: Option<Associativity>| {
if operand_needs_parentheses(
expression_precedence(right),
parent_prec,
OperandSide::Right,
assoc,
) {
TailStep::Decided(false)
} else {
TailStep::Continue(right)
}
};
let step = match view {
SyntaxView::ListCommand { command, .. } => {
TailStep::Decided(command_ends_with_bare_argument(&command))
}
SyntaxView::Chain {
level, operands, ..
} => right_spine(
*operands
.last()
.expect("BUG: n-ary chain must have operands"),
my_prec,
Some(arithmetic_associativity(level)),
),
SyntaxView::Logical { operands, .. } => right_spine(
*operands
.last()
.expect("BUG: conjunction must have operands"),
my_prec,
Some(Associativity::Left),
),
SyntaxView::Comparison(_, _, right)
| SyntaxView::RangeContainment(_, right)
| SyntaxView::RangeLiteral(_, right)
| SyntaxView::PastFutureRange(_, right) => right_spine(right, my_prec, None),
SyntaxView::Negate(right) => right_spine(
right,
arithmetic_precedence(&ArithmeticComputation::Multiply),
Some(Associativity::Left),
),
SyntaxView::Reciprocal(right) => right_spine(right, my_prec, Some(Associativity::Left)),
SyntaxView::Prefix(_, operand) | SyntaxView::Not(operand) => {
TailStep::Decided(is_prefix_bare_operand(operand))
}
SyntaxView::Atom { .. }
| SyntaxView::ImplicitRowValue
| SyntaxView::UnitConversion(..)
| SyntaxView::IsVeto(_)
| SyntaxView::IsNotVeto(_)
| SyntaxView::DateRelative(..)
| SyntaxView::DateCalendar(..)
| SyntaxView::Member { .. }
| SyntaxView::Piecewise(_) => TailStep::Decided(false),
};
match step {
TailStep::Decided(answer) => return answer,
TailStep::Continue(next) => node = next,
}
}
}
enum Piece<'a, N: SyntaxNode<'a>> {
Text(&'static str),
Owned(String),
Shown(&'a dyn fmt::Display),
Atom(N::Atom),
Node {
node: N,
alternate: bool,
},
Enter,
Leave,
Break(Wrap),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Wrap {
Starts,
Stays,
}
enum Token<'t> {
Text(fmt::Arguments<'t>),
Enter,
Leave,
Break(Wrap),
}
fn walk<'a, N: SyntaxNode<'a>>(
pieces: Vec<Piece<'a, N>>,
emit: &mut impl FnMut(Token<'_>) -> fmt::Result,
) -> fmt::Result {
let mut stack: Vec<Piece<'a, N>> = pieces.into_iter().rev().collect();
while let Some(piece) = stack.pop() {
match piece {
Piece::Text(text) => emit(Token::Text(format_args!("{text}")))?,
Piece::Owned(text) => emit(Token::Text(format_args!("{text}")))?,
Piece::Shown(shown) => emit(Token::Text(format_args!("{shown}")))?,
Piece::Atom(atom) => emit(Token::Text(format_args!("{atom}")))?,
Piece::Node { node, alternate } => {
stack.extend(node_pieces(node, alternate).into_iter().rev());
}
Piece::Enter => emit(Token::Enter)?,
Piece::Leave => emit(Token::Leave)?,
Piece::Break(wrap) => emit(Token::Break(wrap))?,
}
}
Ok(())
}
fn render<'a, N: SyntaxNode<'a>>(out: &mut impl Write, pieces: Vec<Piece<'a, N>>) -> fmt::Result {
walk(pieces, &mut |token| match token {
Token::Text(text) => out.write_fmt(text),
Token::Break(_) => out.write_str(" "),
Token::Enter | Token::Leave => Ok(()),
})
}
fn push_parenthesized<'a, N: SyntaxNode<'a>>(out: &mut Vec<Piece<'a, N>>, node: N) {
out.push(Piece::Text("("));
out.push(Piece::Node {
node,
alternate: false,
});
out.push(Piece::Text(")"));
}
fn binary_operand<'a, N: SyntaxNode<'a>>(
out: &mut Vec<Piece<'a, N>>,
child: N,
parent_prec: u8,
side: OperandSide,
parent_assoc: Option<Associativity>,
) {
if operand_needs_parentheses(
expression_precedence(child),
parent_prec,
side,
parent_assoc,
) {
push_parenthesized(out, child);
return;
}
let call_form = match side {
OperandSide::Left | OperandSide::Inner => ends_with_bare_argument(child),
OperandSide::Right => {
!matches!(child.view(), SyntaxView::Not(_)) && ends_with_bare_argument(child)
}
};
out.push(Piece::Node {
node: child,
alternate: call_form,
});
}
fn unary_operand<'a, N: SyntaxNode<'a>>(
out: &mut Vec<Piece<'a, N>>,
child: N,
parent_prec: u8,
parent_assoc: Option<Associativity>,
alternate: bool,
) {
if operand_needs_parentheses(
expression_precedence(child),
parent_prec,
OperandSide::Right,
parent_assoc,
) {
push_parenthesized(out, child);
} else {
out.push(Piece::Node {
node: child,
alternate,
});
}
}
fn call_tail<'a, N: SyntaxNode<'a>>(out: &mut Vec<Piece<'a, N>>, child: N) {
out.push(Piece::Node {
node: child,
alternate: ends_with_bare_argument(child),
});
}
fn prefix_operator<'a, N: SyntaxNode<'a>>(
out: &mut Vec<Piece<'a, N>>,
keyword: Piece<'a, N>,
operand: N,
alternate: bool,
) {
out.push(keyword);
if !alternate && is_prefix_bare_operand(operand) {
out.push(Piece::Text(" "));
out.push(Piece::Node {
node: operand,
alternate: false,
});
} else {
push_parenthesized(out, operand);
}
}
fn comparison_pieces<'a, N: SyntaxNode<'a>>(
left: N,
op: Piece<'a, N>,
right: N,
) -> Vec<Piece<'a, N>> {
let mut out = vec![Piece::Enter];
binary_operand(
&mut out,
left,
COMPARISON_PRECEDENCE,
OperandSide::Left,
None,
);
out.push(Piece::Break(Wrap::Starts));
out.push(op);
out.push(Piece::Text(" "));
binary_operand(
&mut out,
right,
COMPARISON_PRECEDENCE,
OperandSide::Right,
None,
);
out.push(Piece::Leave);
out
}
pub(crate) fn display_comparison<'a, N: SyntaxNode<'a>>(
left: N,
op: &ComparisonComputation,
right: N,
) -> String {
let mut text = String::new();
render(
&mut text,
comparison_pieces(left, Piece::Owned(op.to_string()), right),
)
.expect("BUG: writing to a String cannot fail");
text
}
fn joins_arithmetic(op: &ArithmeticComputation) -> bool {
matches!(
op,
ArithmeticComputation::Add | ArithmeticComputation::Multiply
)
}
fn uniform_chain<'a, N: SyntaxNode<'a>>(
node: N,
op: &ArithmeticComputation,
) -> Option<(Vec<N>, Vec<&'a ArithmeticComputation>)> {
match node.view() {
SyntaxView::Chain {
level,
operands,
ops,
} if joins_arithmetic(op) && level == op && ops.iter().all(|step| *step == op) => {
Some((operands, ops))
}
_ => None,
}
}
struct ChainFrame<'a, N> {
level: &'a ArithmeticComputation,
operands: Vec<N>,
ops: Vec<&'a ArithmeticComputation>,
index: usize,
}
fn flatten_arithmetic<'a, N: SyntaxNode<'a>>(
level: &'a ArithmeticComputation,
operands: Vec<N>,
ops: Vec<&'a ArithmeticComputation>,
) -> (Vec<N>, Vec<&'a ArithmeticComputation>) {
let mut flat_operands = Vec::with_capacity(operands.len());
let mut flat_ops = Vec::with_capacity(ops.len());
let mut stack = vec![ChainFrame {
level,
operands,
ops,
index: 0,
}];
while let Some(mut frame) = stack.pop() {
if frame.index >= frame.operands.len() {
continue;
}
let index = frame.index;
frame.index += 1;
let operand = frame.operands[index];
let level = frame.level;
let incoming = if index == 0 {
None
} else {
Some(
frame
.ops
.get(index - 1)
.copied()
.expect("BUG: chain has one operator per operand after the first"),
)
};
if frame.index < frame.operands.len() {
stack.push(frame);
}
match incoming {
None => {
if let Some((inner_level, inner_operands, inner_ops)) =
open_left_chain(operand, level)
{
stack.push(ChainFrame {
level: inner_level,
operands: inner_operands,
ops: inner_ops,
index: 0,
});
} else {
flat_operands.push(operand);
}
}
Some(op) => {
if let Some((inner_operands, inner_ops)) = uniform_chain(operand, op) {
flat_ops.push(op);
stack.push(ChainFrame {
level: op,
operands: inner_operands,
ops: inner_ops,
index: 0,
});
} else {
flat_ops.push(op);
flat_operands.push(operand);
}
}
}
}
(flat_operands, flat_ops)
}
fn open_left_chain<'a, N: SyntaxNode<'a>>(
node: N,
parent: &ArithmeticComputation,
) -> Option<(
&'a ArithmeticComputation,
Vec<N>,
Vec<&'a ArithmeticComputation>,
)> {
match node.view() {
SyntaxView::Chain {
level,
operands,
ops,
} if arithmetic_precedence(level) == arithmetic_precedence(parent)
&& arithmetic_associativity(level) == Associativity::Left
&& arithmetic_associativity(parent) == Associativity::Left =>
{
Some((level, operands, ops))
}
_ => None,
}
}
fn flatten_logical<'a, N: SyntaxNode<'a>>(
connective: LogicalConnective,
operands: Vec<N>,
) -> Vec<N> {
let mut flat = Vec::with_capacity(operands.len());
let mut pending: Vec<N> = operands.into_iter().rev().collect();
while let Some(operand) = pending.pop() {
match operand.view() {
SyntaxView::Logical {
connective: inner,
operands: inner_operands,
} if inner == connective => {
pending.extend(inner_operands.into_iter().rev());
}
_ => flat.push(operand),
}
}
flat
}
struct Segment {
place: Option<(usize, Wrap)>,
text: String,
nodes: Vec<bool>,
}
fn segments<'a, N: SyntaxNode<'a>>(node: N) -> Vec<Segment> {
let mut segments = vec![Segment {
place: None,
text: String::new(),
nodes: Vec::new(),
}];
let mut depth = 0;
walk(
vec![Piece::Node {
node,
alternate: false,
}],
&mut |token| {
let current = segments.last_mut().expect("BUG: segments start with one");
match token {
Token::Text(text) => return current.text.write_fmt(text),
Token::Enter => {
depth += 1;
current.nodes.push(true);
}
Token::Leave => {
depth -= 1;
current.nodes.push(false);
}
Token::Break(wrap) => segments.push(Segment {
place: Some((depth, wrap)),
text: String::new(),
nodes: Vec::new(),
}),
}
Ok(())
},
)
.expect("BUG: writing to a String cannot fail");
segments
}
fn operand_widths(segments: &[Segment]) -> Vec<usize> {
let mut widths = vec![0; segments.len()];
let mut later: Vec<usize> = Vec::new();
for (i, segment) in segments.iter().enumerate().rev() {
let depth = segment.place.map_or(0, |(depth, _)| depth);
let mut width = segment.text.len();
while let Some(&next) = later.last() {
let (next_depth, _) = segments[next]
.place
.expect("BUG: only the first segment has no place");
if next_depth <= depth {
break;
}
width += 1 + widths[next];
later.pop();
}
widths[i] = width;
later.push(i);
}
widths
}
pub(crate) fn display_wrapped<'a, N: SyntaxNode<'a>>(
node: N,
column: usize,
max_cols: usize,
indent: usize,
) -> String {
let root_is_operator = match node.view() {
SyntaxView::Chain { .. }
| SyntaxView::Logical { .. }
| SyntaxView::Comparison(..)
| SyntaxView::RangeContainment(..) => true,
SyntaxView::Atom { .. }
| SyntaxView::ImplicitRowValue
| SyntaxView::UnitConversion(..)
| SyntaxView::Not(_)
| SyntaxView::IsVeto(_)
| SyntaxView::IsNotVeto(_)
| SyntaxView::Prefix(..)
| SyntaxView::DateRelative(..)
| SyntaxView::DateCalendar(..)
| SyntaxView::RangeLiteral(..)
| SyntaxView::PastFutureRange(..)
| SyntaxView::ListCommand { .. }
| SyntaxView::Member { .. }
| SyntaxView::Negate(_)
| SyntaxView::Reciprocal(_)
| SyntaxView::Piecewise(_) => false,
};
let segments = segments(node);
let widths = operand_widths(&segments);
let mut out = String::new();
let mut line_width = column;
let mut line_indent = indent;
let mut line_depth = 0;
let mut node_indents: Vec<usize> = Vec::new();
for (segment, operand_width) in segments.iter().zip(widths) {
if let Some((depth, wrap)) = segment.place {
let node_indent = *node_indents
.last()
.expect("BUG: a place between operands is in a node");
let fits = |width: usize| line_width + 1 + width <= max_cols;
let stays = match wrap {
Wrap::Starts => false,
Wrap::Stays => node_indent + operand_width > max_cols && fits(segment.text.len()),
};
if line_depth <= depth && (fits(operand_width) || stays) {
out.push(' ');
line_width += 1;
} else {
out.push('\n');
out.push_str(&" ".repeat(node_indent));
line_width = node_indent;
line_indent = node_indent;
line_depth = depth;
}
}
out.push_str(&segment.text);
line_width += segment.text.len();
for opens in &segment.nodes {
if *opens {
let is_root_operator = root_is_operator && node_indents.is_empty();
node_indents.push(if is_root_operator {
indent
} else {
line_indent + 2
});
} else {
node_indents
.pop()
.expect("BUG: a node closes after it opens");
}
}
}
out
}
fn node_pieces<'a, N: SyntaxNode<'a>>(node: N, alternate: bool) -> Vec<Piece<'a, N>> {
let view = node.view();
let my_prec = view_precedence(&view);
let mut out = Vec::new();
match view {
SyntaxView::Atom { atom, .. } => out.push(Piece::Atom(atom)),
SyntaxView::ImplicitRowValue => {
panic!("BUG: implicit row value rendered outside a predicate comparison")
}
SyntaxView::Chain {
level,
operands,
ops,
} => {
let (operands, ops) = flatten_arithmetic(level, operands, ops);
let assoc = Some(arithmetic_associativity(level));
let mut ops = ops.into_iter();
out.push(Piece::Enter);
for (i, operand) in operands.into_iter().enumerate() {
let side = if i == 0 {
OperandSide::Left
} else {
let op = ops
.next()
.expect("BUG: chain has one operator per operand after the first");
out.push(Piece::Break(Wrap::Stays));
out.push(Piece::Shown(op));
out.push(Piece::Text(" "));
OperandSide::Right
};
binary_operand(&mut out, operand, my_prec, side, assoc);
}
out.push(Piece::Leave);
}
SyntaxView::Comparison(left, op, right) => {
if matches!(left.view(), SyntaxView::ImplicitRowValue) {
out.push(Piece::Shown(op));
out.push(Piece::Text(" "));
binary_operand(&mut out, right, my_prec, OperandSide::Right, None);
} else {
out.extend(comparison_pieces(left, Piece::Shown(op), right));
}
}
SyntaxView::UnitConversion(value, target) => {
binary_operand(&mut out, value, my_prec, OperandSide::Left, None);
out.push(Piece::Text(" as "));
out.push(Piece::Shown(target));
}
SyntaxView::IsNotVeto(operand) => {
binary_operand(
&mut out,
operand,
COMPARISON_PRECEDENCE,
OperandSide::Left,
None,
);
out.push(Piece::Text(" is not veto"));
}
SyntaxView::Not(operand) => {
prefix_operator(&mut out, Piece::Text("not"), operand, alternate);
}
SyntaxView::IsVeto(operand) => {
binary_operand(&mut out, operand, my_prec, OperandSide::Left, None);
out.push(Piece::Text(" is veto"));
}
SyntaxView::Logical {
connective,
operands,
} => {
let operands = flatten_logical(connective, operands);
let assoc = Some(Associativity::Left);
let last = operands.len() - 1;
out.push(Piece::Enter);
for (i, operand) in operands.into_iter().enumerate() {
let side = if i == 0 {
OperandSide::Left
} else {
out.push(Piece::Break(Wrap::Starts));
out.push(Piece::Text(connective.keyword()));
out.push(Piece::Text(" "));
if i == last {
OperandSide::Right
} else {
OperandSide::Inner
}
};
binary_operand(&mut out, operand, my_prec, side, assoc);
}
out.push(Piece::Leave);
}
SyntaxView::Prefix(keyword, operand) => {
prefix_operator(&mut out, Piece::Shown(keyword), operand, alternate);
}
SyntaxView::DateRelative(kind, date) => {
call_tail(&mut out, date);
out.push(Piece::Text(" "));
out.push(Piece::Shown(kind));
}
SyntaxView::DateCalendar(kind, unit, date) => {
call_tail(&mut out, date);
out.push(Piece::Text(" "));
out.push(Piece::Shown(kind));
out.push(Piece::Text(" "));
out.push(Piece::Shown(unit));
}
SyntaxView::RangeLiteral(left, right) => {
binary_operand(&mut out, left, my_prec, OperandSide::Left, None);
out.push(Piece::Text("..."));
binary_operand(&mut out, right, my_prec, OperandSide::Right, None);
}
SyntaxView::PastFutureRange(kind, offset) => {
match kind {
DateRelativeKind::InPast => out.push(Piece::Text("past ")),
DateRelativeKind::InFuture => out.push(Piece::Text("future ")),
}
unary_operand(&mut out, offset, my_prec, None, alternate);
}
SyntaxView::RangeContainment(value, range) => {
if matches!(value.view(), SyntaxView::ImplicitRowValue) {
out.push(Piece::Text("in "));
} else {
out.push(Piece::Enter);
binary_operand(&mut out, value, my_prec, OperandSide::Left, None);
out.push(Piece::Break(Wrap::Starts));
out.push(Piece::Text("in "));
}
binary_operand(&mut out, range, my_prec, OperandSide::Right, None);
if !matches!(value.view(), SyntaxView::ImplicitRowValue) {
out.push(Piece::Leave);
}
}
SyntaxView::ListCommand { list, command } => {
let mut commands = vec![(command, alternate)];
let mut base = list;
while let SyntaxView::ListCommand { list, command } = base.view() {
commands.push((command, false));
base = list;
}
out.push(Piece::Enter);
if expression_precedence(base) < my_prec {
push_parenthesized(&mut out, base);
} else {
out.push(Piece::Node {
node: base,
alternate: false,
});
}
for (command, alternate) in commands.iter().rev() {
out.push(Piece::Break(Wrap::Starts));
out.push(Piece::Text("-> "));
out.extend(command_pieces(command, *alternate));
}
out.push(Piece::Leave);
}
SyntaxView::Member {
base,
path,
parenthesize_base,
} => {
if parenthesize_base {
out.push(Piece::Text("("));
out.push(Piece::Node {
node: base,
alternate: false,
});
out.push(Piece::Text(")."));
} else {
out.push(Piece::Node {
node: base,
alternate: false,
});
out.push(Piece::Text("."));
}
out.push(Piece::Atom(path));
}
SyntaxView::Negate(operand) => {
out.push(Piece::Text("-"));
unary_operand(
&mut out,
operand,
arithmetic_precedence(&ArithmeticComputation::Multiply),
Some(Associativity::Left),
alternate,
);
}
SyntaxView::Reciprocal(operand) => {
out.push(Piece::Text("1/"));
unary_operand(
&mut out,
operand,
my_prec,
Some(Associativity::Left),
alternate,
);
}
SyntaxView::Piecewise(arms) => {
let mut arms = arms.into_iter();
let (_, default) = arms.next().expect("BUG: piecewise must have a default arm");
out.push(Piece::Node {
node: default,
alternate: false,
});
for (condition, result) in arms {
out.push(Piece::Text(" unless "));
out.push(Piece::Node {
node: condition,
alternate: false,
});
out.push(Piece::Text(": "));
out.push(Piece::Node {
node: result,
alternate: false,
});
}
}
}
out
}
fn command_argument<'a, N: SyntaxNode<'a>>(
out: &mut Vec<Piece<'a, N>>,
argument: N,
alternate: bool,
) {
if !alternate && is_bare_argument(argument) {
out.push(Piece::Text(" "));
out.push(Piece::Node {
node: argument,
alternate: false,
});
} else {
push_parenthesized(out, argument);
}
}
fn command_pieces<'a, N: SyntaxNode<'a>>(
command: &CommandView<'a, N>,
alternate: bool,
) -> Vec<Piece<'a, N>> {
let mut out = Vec::new();
match command {
CommandView::Find(keys) => {
let bare = !alternate && keys.iter().all(|key| is_bare_argument(*key));
out.push(Piece::Text(if bare { "find " } else { "find(" }));
for (i, key) in keys.iter().enumerate() {
if i > 0 {
out.push(Piece::Text(", "));
}
out.push(Piece::Node {
node: *key,
alternate: false,
});
}
if !bare {
out.push(Piece::Text(")"));
}
}
CommandView::First => out.push(Piece::Text("first")),
CommandView::Last => out.push(Piece::Text("last")),
CommandView::Count => out.push(Piece::Text("count")),
CommandView::Reduce(name, argument) => {
out.push(Piece::Text(name));
if let Some(argument) = argument {
command_argument(&mut out, *argument, alternate);
}
}
CommandView::Predicate(name, form) => {
out.push(Piece::Text(name));
if !alternate && is_bare_predicate(form) {
out.push(Piece::Text(" "));
out.extend(predicate_pieces(form));
} else {
out.push(Piece::Text("("));
out.extend(predicate_pieces(form));
out.push(Piece::Text(")"));
}
}
CommandView::Sort {
descending,
argument,
} => {
out.push(Piece::Text("sort"));
if let Some(argument) = argument {
command_argument(&mut out, *argument, alternate);
}
out.push(Piece::Text(if *descending { " desc" } else { " asc" }));
}
CommandView::Top(n) => {
out.push(Piece::Text("top"));
command_argument(&mut out, *n, alternate);
}
CommandView::Step(name, step) => {
out.push(Piece::Text(name));
if let Some(step) = step {
command_argument(&mut out, *step, alternate);
}
}
CommandView::With(rows) => {
out.push(Piece::Text(if alternate { "with(" } else { "with " }));
for (i, (label, value)) in rows.iter().enumerate() {
if i > 0 {
out.push(Piece::Text(", "));
}
if let Some(label) = label {
out.push(Piece::Atom(label.clone()));
out.push(Piece::Text(": "));
}
out.push(Piece::Node {
node: *value,
alternate: false,
});
}
if alternate {
out.push(Piece::Text(")"));
}
}
CommandView::Key(fields) => {
out.push(Piece::Text("key "));
for (i, field) in fields.iter().enumerate() {
if i > 0 {
out.push(Piece::Text(", "));
}
out.push(Piece::Atom(field.clone()));
}
}
}
out
}
fn predicate_pieces<'a, N: SyntaxNode<'a>>(form: &PredicateView<N>) -> Vec<Piece<'a, N>> {
match form {
PredicateView::Value(expr) | PredicateView::Instance(expr) => vec![Piece::Node {
node: *expr,
alternate: false,
}],
}
}
impl<'a, N: SyntaxNode<'a>> fmt::Display for Syntax<N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
render(
f,
vec![Piece::Node {
node: self.0,
alternate: f.alternate(),
}],
)
}
}
impl<'a, N: SyntaxNode<'a>> fmt::Display for CommandSyntax<'_, 'a, N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
render(f, command_pieces(self.0, f.alternate()))
}
}
#[cfg(test)]
mod tests {
use super::*;
enum Tree {
Name(&'static str),
Nary(ArithmeticComputation, Vec<Tree>),
Negate(Box<Tree>),
Reciprocal(Box<Tree>),
Abs(Box<Tree>),
And(Vec<Tree>),
}
impl<'a> SyntaxNode<'a> for &'a Tree {
type Atom = &'static str;
fn view(self) -> SyntaxView<'a, Self> {
match self {
Tree::Name(name) => SyntaxView::Atom {
atom: name,
starts_with_sign: false,
},
Tree::Nary(op, operands) => SyntaxView::Chain {
level: op,
operands: operands.iter().collect(),
ops: (1..operands.len()).map(|_| op).collect(),
},
Tree::Negate(operand) => SyntaxView::Negate(operand),
Tree::Reciprocal(operand) => SyntaxView::Reciprocal(operand),
Tree::Abs(operand) => SyntaxView::Prefix(&"abs", operand),
Tree::And(operands) => SyntaxView::Logical {
connective: LogicalConnective::And,
operands: operands.iter().collect(),
},
}
}
}
fn name(name: &'static str) -> Tree {
Tree::Name(name)
}
fn sum(operands: Vec<Tree>) -> Tree {
Tree::Nary(ArithmeticComputation::Add, operands)
}
fn product(operands: Vec<Tree>) -> Tree {
Tree::Nary(ArithmeticComputation::Multiply, operands)
}
fn power(base: Tree, exponent: Tree) -> Tree {
Tree::Nary(ArithmeticComputation::Power, vec![base, exponent])
}
fn print(tree: &Tree) -> String {
Syntax(tree).to_string()
}
#[test]
fn nary_chain_prints_operands_joined_by_operator() {
assert_eq!(
print(&sum(vec![name("a"), name("b"), name("c")])),
"a + b + c"
);
assert_eq!(
print(&product(vec![name("a"), name("b"), name("c")])),
"a * b * c"
);
}
#[test]
fn nary_wraps_looser_operands() {
let tree = product(vec![sum(vec![name("a"), name("b")]), name("c")]);
assert_eq!(print(&tree), "(a + b) * c");
}
#[test]
fn nary_keeps_tighter_operands_bare() {
let tree = sum(vec![name("a"), product(vec![name("b"), name("c")])]);
assert_eq!(print(&tree), "a + b * c");
}
#[test]
fn nary_same_operator_joins_nested_chain() {
let first = sum(vec![sum(vec![name("a"), name("b")]), name("c")]);
assert_eq!(print(&first), "a + b + c");
let later = sum(vec![name("a"), sum(vec![name("b"), name("c")])]);
assert_eq!(print(&later), "a + b + c");
let factors = product(vec![name("a"), product(vec![name("b"), name("c")])]);
assert_eq!(print(&factors), "a * b * c");
let difference = Tree::Nary(
ArithmeticComputation::Subtract,
vec![
name("a"),
Tree::Nary(ArithmeticComputation::Subtract, vec![name("b"), name("c")]),
],
);
assert_eq!(print(&difference), "a - (b - c)");
}
#[test]
fn nary_operand_ending_in_bare_argument_uses_call_form() {
let last = sum(vec![name("a"), Tree::Abs(Box::new(name("x")))]);
assert_eq!(print(&last), "a + abs(x)");
let first = sum(vec![Tree::Abs(Box::new(name("x"))), name("a")]);
assert_eq!(print(&first), "abs(x) + a");
}
#[test]
fn power_chain_is_right_associative() {
let right = power(name("a"), power(name("b"), name("c")));
assert_eq!(print(&right), "a ^ b ^ c");
let left = power(power(name("a"), name("b")), name("c"));
assert_eq!(print(&left), "(a ^ b) ^ c");
}
#[test]
fn negate_prints_atom_bare_and_wraps_arithmetic() {
assert_eq!(print(&Tree::Negate(Box::new(name("a")))), "-a");
let tree = Tree::Negate(Box::new(sum(vec![name("a"), name("b")])));
assert_eq!(print(&tree), "-(a + b)");
}
#[test]
fn negate_wraps_product_and_keeps_power_bare() {
let product_operand = Tree::Negate(Box::new(product(vec![name("a"), name("b")])));
assert_eq!(print(&product_operand), "-(a * b)");
let power_operand = Tree::Negate(Box::new(power(name("a"), name("b"))));
assert_eq!(print(&power_operand), "-a ^ b");
}
#[test]
fn negate_operand_of_arithmetic_is_wrapped() {
let tree = product(vec![name("a"), Tree::Negate(Box::new(name("b")))]);
assert_eq!(print(&tree), "a * (-b)");
}
#[test]
fn reciprocal_wraps_same_precedence_operand() {
assert_eq!(print(&Tree::Reciprocal(Box::new(name("a")))), "1/a");
let tree = Tree::Reciprocal(Box::new(product(vec![name("a"), name("b")])));
assert_eq!(print(&tree), "1/(a * b)");
}
#[test]
fn reciprocal_keeps_power_operand_bare() {
let tree = Tree::Reciprocal(Box::new(power(name("a"), name("b"))));
assert_eq!(print(&tree), "1/a ^ b");
}
#[test]
fn reciprocal_in_product_prints_bare_as_left_operand() {
let tree = product(vec![Tree::Reciprocal(Box::new(name("a"))), name("b")]);
assert_eq!(print(&tree), "1/a * b");
}
#[test]
fn broken_chain_starts_each_root_operator_on_a_new_line() {
let tree = sum(vec![
name("a"),
product(vec![name("b"), name("c")]),
name("d"),
]);
assert_eq!(display_wrapped(&tree, 2, 9, 2), "a\n + b * c\n + d");
}
#[test]
fn broken_conjunction_joins_nested_same_connective() {
let tree = Tree::And(vec![
name("a"),
Tree::And(vec![name("b"), name("c")]),
sum(vec![name("d"), name("e")]),
]);
assert_eq!(
display_wrapped(&tree, 4, 13, 4),
"a and b\n and c\n and d + e"
);
}
#[test]
fn filled_chain_parenthesizes_same_precedence_right_operand() {
let inner = Tree::Nary(ArithmeticComputation::Subtract, vec![name("b"), name("c")]);
let tree = Tree::Nary(ArithmeticComputation::Subtract, vec![name("a"), inner]);
assert_eq!(display_wrapped(&tree, 2, 11, 2), "a\n - (b - c)");
}
#[test]
fn filled_power_parenthesizes_same_precedence_left_operand() {
let tree = power(power(name("a"), name("b")), name("c"));
assert_eq!(display_wrapped(&tree, 2, 9, 2), "(a ^ b)\n ^ c");
}
#[test]
fn filled_chain_uses_call_form_for_bare_right_operand() {
let tree = product(vec![name("n"), Tree::Abs(Box::new(name("x")))]);
assert_eq!(display_wrapped(&tree, 2, 10, 2), "n\n * abs(x)");
}
}