Skip to content

Commit

Permalink
Replace Term::deep_repr by the pretty printer
Browse files Browse the repository at this point in the history
  • Loading branch information
vkleen committed Apr 18, 2023
1 parent 87275ba commit 9521382
Show file tree
Hide file tree
Showing 10 changed files with 47 additions and 49 deletions.
6 changes: 2 additions & 4 deletions src/bin/nickel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use nickel_lang::program::{ColorOpt, Program};
use nickel_lang::repl::query_print;
#[cfg(feature = "repl")]
use nickel_lang::repl::rustyline_frontend;
use nickel_lang::term::{RichTerm, Term};
use nickel_lang::term::RichTerm;
use nickel_lang::{serialize, serialize::ExportFormat};
use std::path::{Path, PathBuf};
use std::{
Expand Down Expand Up @@ -220,9 +220,7 @@ fn main() {
stdout,
format,
}) => export_doc(&mut program, opts.file.as_ref(), output, stdout, format),
None => program
.eval_full()
.map(|t| println!("{}", Term::from(t).deep_repr())),
None => program.eval_full().map(|t| println!("{t}")),
};

if let Err(err) = result {
Expand Down
19 changes: 15 additions & 4 deletions src/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,17 @@ where
}

impl<'a, D, A> Pretty<'a, D, A> for RichTerm
where
D: NickelAllocatorExt<'a, A>,
D::Doc: Clone,
A: Clone + 'a,
{
fn pretty(self, allocator: &'a D) -> DocBuilder<'a, D, A> {
self.as_ref().pretty(allocator)
}
}

impl<'a, D, A> Pretty<'a, D, A> for &Term
where
D: NickelAllocatorExt<'a, A>,
D::Doc: Clone,
Expand All @@ -428,7 +439,7 @@ where
fn pretty(self, allocator: &'a D) -> DocBuilder<'a, D, A> {
use Term::*;

match self.as_ref() {
match self {
Null => allocator.text("null"),
Bool(v) => allocator.as_string(v),
Num(n) => allocator.as_string(format!("{}", n.to_sci())),
Expand Down Expand Up @@ -463,16 +474,16 @@ where
// TODO Pattern destructuring to implement.
FunPattern(..) => {
let mut params = vec![];
let mut rt = &self;
while let FunPattern(id, dst, t) = rt.as_ref() {
let mut rt = self;
while let FunPattern(id, dst, t) = rt {
params.push(if let Some(id) = id {
allocator
.as_string(id)
.append(allocator.text("@").append(dst.pretty(allocator)))
} else {
dst.pretty(allocator)
});
rt = t;
rt = t.as_ref();
}
allocator
.text("fun")
Expand Down
4 changes: 2 additions & 2 deletions src/repl/rustyline_frontend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ pub fn repl(histfile: PathBuf, color_opt: ColorOpt) -> Result<(), InitError> {
}),
Ok(Command::Print(exp)) => {
match repl.eval_full(&exp) {
Ok(EvalResult::Evaluated(rt)) => println!("{}\n", rt.as_ref().deep_repr()),
Ok(EvalResult::Evaluated(rt)) => println!("{rt}"),
Ok(EvalResult::Bound(_)) => (),
Err(err) => program::report(repl.cache_mut(), err, color_opt),
};
Expand All @@ -120,7 +120,7 @@ pub fn repl(histfile: PathBuf, color_opt: ColorOpt) -> Result<(), InitError> {
}
Ok(line) => {
match repl.eval_full(&line) {
Ok(EvalResult::Evaluated(rt)) => println!("{}\n", rt.as_ref().deep_repr()),
Ok(EvalResult::Evaluated(rt)) => println!("{rt}\n"),
Ok(EvalResult::Bound(_)) => (),
Err(err) => program::report(repl.cache_mut(), err, color_opt),
};
Expand Down
6 changes: 2 additions & 4 deletions src/repl/simple_frontend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ pub fn input<R: Repl>(repl: &mut R, line: &str) -> Result<InputResult, InputErro
Ok(Command::Print(exp)) => repl
.eval_full(&exp)
.map(|res| match res {
EvalResult::Evaluated(rt) => InputResult::Success(rt.as_ref().deep_repr()),
EvalResult::Evaluated(rt) => InputResult::Success(format!("{rt}\n")),
EvalResult::Bound(_) => InputResult::Blank,
})
.map_err(InputError::from),
Expand All @@ -82,9 +82,7 @@ pub fn input<R: Repl>(repl: &mut R, line: &str) -> Result<InputResult, InputErro
} else {
repl.eval_full(line)
.map(|eval_res| match eval_res {
EvalResult::Evaluated(rt) => {
InputResult::Success(format!("{}\n", rt.as_ref().deep_repr()))
}
EvalResult::Evaluated(rt) => InputResult::Success(format!("{rt}\n")),
EvalResult::Bound(_) => InputResult::Success(String::new()),
})
.map_err(InputError::from)
Expand Down
36 changes: 1 addition & 35 deletions src/term/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ pub mod record;
pub mod string;

use array::{Array, ArrayAttrs};
use pretty::BoxAllocator;
use record::{Field, FieldDeps, FieldMetadata, RecordData, RecordDeps};
use string::NickelString;

Expand Down Expand Up @@ -702,40 +703,6 @@ impl Term {
}
}

/// Return a deep string representation of a term, used for printing in the REPL
pub fn deep_repr(&self) -> String {
match self {
Term::Record(r) | Term::RecRecord(r, ..) => {
let fields_str: Vec<String> = r
.fields
.iter()
.map(|(ident, field)| {
if let Some(ref value) = field.value {
format!("{} = {}", ident, value.as_ref().deep_repr())
} else {
format!("{ident}")
}
})
.collect();

let suffix = match self {
Term::RecRecord(_, dyn_fields, ..) if !dyn_fields.is_empty() => ", ..",
_ => "",
};

format!("{{ {}{} }}", fields_str.join(", "), suffix)
}
Term::Array(elements, _) => {
let elements_str: Vec<String> = elements
.iter()
.map(|term| term.as_ref().deep_repr())
.collect();
format!("[ {} ]", elements_str.join(", "))
}
_ => self.shallow_repr(),
}
}

/// Determine if a term is in evaluated from, called weak head normal form (WHNF).
pub fn is_whnf(&self) -> bool {
match self {
Expand Down Expand Up @@ -1694,7 +1661,6 @@ impl From<Term> for RichTerm {
impl std::fmt::Display for RichTerm {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
use crate::pretty::*;
use pretty::BoxAllocator;

let allocator = BoxAllocator;

Expand Down
2 changes: 2 additions & 0 deletions tests/snapshot/inputs/eval/escaping.ncl
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
"a\"bcd\""

2 changes: 2 additions & 0 deletions tests/snapshot/inputs/eval/records.ncl
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
{ a = true, b | Number = 6 * 7 }

9 changes: 9 additions & 0 deletions tests/snapshot/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@ macro_rules! assert_snapshot_filtered {
}
}

#[test_resources("tests/snapshot/inputs/eval/*.ncl")]
fn check_eval_snapshots(file: &str) {
let file = TestFile::from_project_path(file);

let snapshot = NickelInvocation::new().file(&file).snapshot_stdout();

insta::assert_snapshot!(file.prefixed_test_name("eval"), snapshot);
}

#[test_resources("tests/snapshot/inputs/pretty/*.ncl")]
fn check_pretty_print_snapshots(file: &str) {
let file = TestFile::from_project_path(file);
Expand Down
6 changes: 6 additions & 0 deletions tests/snapshot/snapshots/snapshot__eval_escaping.ncl.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
source: tests/snapshot/main.rs
expression: snapshot
---
"a\"bcd\""

6 changes: 6 additions & 0 deletions tests/snapshot/snapshots/snapshot__eval_records.ncl.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
source: tests/snapshot/main.rs
expression: snapshot
---
{ a = true, b | Number = 42, }

0 comments on commit 9521382

Please sign in to comment.