use super::*;
use crate::compiler::ast::BinaryOp;
use crate::{Config, compile};
fn plain(kind: NixKind) -> NixExpr {
NixExpr::plain(kind)
}
fn words() -> NixExpr {
plain(NixKind::List(
(0..8)
.map(|index| plain(NixKind::String(format!("dependency-number-{index}"))))
.collect(),
))
}
fn fields() -> NixExpr {
plain(NixKind::AttrSet(
(0..8)
.map(|index| {
(
vec![format!("field{index}")],
plain(NixKind::String(format!("value-number-{index}"))),
)
})
.collect(),
))
}
fn source(expr: &NixExpr) -> String {
render(expr)
.source
.strip_prefix("# Generated by Rusix. Edit the Rust source.\n")
.unwrap()
.to_owned()
}
#[test]
fn short_expressions_and_collections_remain_inline() {
assert_eq!(source(&plain(NixKind::List(vec![]))), "[ ]\n");
assert_eq!(
source(&plain(NixKind::AttrSet(vec![(
vec!["enabled".into()],
plain(NixKind::Bool(true)),
)]))),
"{ \"enabled\" = true; }\n"
);
assert_eq!(
source(&plain(NixKind::Call(
Builtin::Div,
vec![plain(NixKind::Int(44)), plain(NixKind::Int(2))],
))),
"builtins.div 44 2\n"
);
}
#[test]
fn long_lists_break_one_item_per_line() {
let rendered = source(&words());
assert!(rendered.starts_with("[\n \"dependency-number-0\"\n"));
assert!(rendered.ends_with(" \"dependency-number-7\"\n]\n"));
assert_eq!(rendered.lines().count(), 10);
assert!(rendered.lines().all(|line| line.len() <= 100));
}
#[test]
fn long_attribute_sets_break_one_binding_per_line() {
let rendered = source(&fields());
assert!(rendered.starts_with("{\n \"field0\" = \"value-number-0\";\n"));
assert!(rendered.ends_with(" \"field7\" = \"value-number-7\";\n}\n"));
assert_eq!(rendered.lines().count(), 10);
}
#[test]
fn large_native_argument_sets_preserve_lazy_defaults() {
let arguments = (0..12)
.map(|index| {
(
format!("dependency{index}"),
(index == 11).then(|| plain(NixKind::Variable("dependency0".into()))),
)
})
.collect();
let function = plain(NixKind::ArgumentFunction(
arguments,
Box::new(plain(NixKind::Variable("dependency11".into()))),
));
let rendered = source(&function);
assert!(rendered.starts_with("{\n dependency0,\n dependency1,"));
assert!(rendered.contains(" dependency11 ? dependency0\n}:\n dependency11"));
assert!(rendered.lines().all(|line| line.len() <= 100));
}
#[test]
fn nested_groups_indent_by_two_spaces_and_fit_independently() {
let nested = plain(NixKind::List(vec![fields(), words()]));
let rendered = source(&nested);
assert!(rendered.contains("[\n {\n \"field0\""));
assert!(rendered.contains(" [\n \"dependency-number-0\""));
assert!(!rendered.contains('\t'));
assert!(rendered.lines().all(|line| !line.ends_with(' ')));
}
#[test]
fn complex_conditionals_break_branches_without_root_parentheses() {
let expression = plain(NixKind::If(
Box::new(plain(NixKind::Bool(true))),
Box::new(words()),
Box::new(plain(NixKind::String("fallback".into()))),
));
let rendered = source(&expression);
assert!(rendered.starts_with("if true then\n [\n"));
assert!(rendered.ends_with("else\n \"fallback\"\n"));
}
#[test]
fn lets_and_lambdas_choose_inline_or_structured_layout() {
let small = plain(NixKind::Let(
"x".into(),
Box::new(plain(NixKind::Int(1))),
Box::new(plain(NixKind::Variable("x".into()))),
));
assert_eq!(source(&small), "let x = 1; in x\n");
let large = plain(NixKind::Let(
"x".into(),
Box::new(words()),
Box::new(plain(NixKind::Lambda(
"value".into(),
Box::new(plain(NixKind::Variable("value".into()))),
))),
));
let rendered = source(&large);
assert!(rendered.starts_with("let\n x =\n [\n"));
assert!(rendered.ends_with("in\n value: value\n"));
}
#[test]
fn long_applications_and_binary_operands_break_without_blanket_grouping() {
let application = plain(NixKind::Apply(
Box::new(plain(NixKind::Variable("identity".into()))),
Box::new(words()),
));
assert!(source(&application).starts_with("identity\n [\n"));
let binary = plain(NixKind::Binary(
BinaryOp::Equal,
Box::new(words()),
Box::new(words()),
));
assert!(source(&binary).contains(" == [\n"));
}
#[test]
fn literal_contents_signed_numbers_and_quoted_segments_are_not_reformatted() {
let literal = " shell\n\t${leave-this-literal}\n".repeat(20);
let expression = plain(NixKind::List(vec![
plain(NixKind::String(literal.clone())),
plain(NixKind::Int(-42)),
plain(NixKind::Int(i64::MIN)),
plain(NixKind::Float(1.0)),
plain(NixKind::Select(
Box::new(plain(NixKind::Variable("value".into()))),
vec!["a.b".into(), "quoted\"name".into()],
)),
plain(NixKind::Path("./nixpkgs/lib".into())),
]));
let rendered = source(&expression);
assert!(rendered.contains("e(&literal)));
assert!(rendered.contains("(-42)"));
assert!(rendered.contains("(-9223372036854775807 - 1)"));
assert!(rendered.contains("1.0"));
assert!(rendered.contains("value.\"a.b\".\"quoted\\\"name\""));
assert!(rendered.contains("./nixpkgs/lib"));
}
#[test]
fn layout_and_spans_are_deterministic_in_both_modes() {
let config = Config::new().set_dynamic("long", vec!["a string with Unicode: λ"; 12]);
let ast = crate::compiler::lower(&config);
for options in [
RenderOptions::default(),
RenderOptions {
origin_comments: true,
},
] {
let first = render_with_options(&ast, options);
let second = render_with_options(&ast, options);
assert_eq!(
serde_json::to_value(&first).unwrap(),
serde_json::to_value(&second).unwrap()
);
assert!(!first.spans.is_empty());
assert_eq!(first.source.contains("# rn-"), options.origin_comments);
for span in &first.spans {
assert!(first.source.get(span.start..span.end).is_some());
assert!(span.start < span.end);
let preceding = &first.source[..span.start];
let line = preceding.bytes().filter(|byte| *byte == b'\n').count() + 1;
let column = preceding.rsplit('\n').next().unwrap().len() + 1;
assert!(first.at_position(line, column).is_some());
}
}
assert_eq!(compile(&config).unwrap().source, render(&ast).source);
}
fn significant(source: &str) -> String {
let mut result = String::new();
let mut chars = source.chars();
let mut quoted = false;
while let Some(c) = chars.next() {
if quoted {
result.push(c);
if c == '\\' {
result.push(chars.next().unwrap());
} else if c == '"' {
quoted = false;
}
} else if c == '#' {
for c in chars.by_ref() {
if c == '\n' {
break;
}
}
} else if !c.is_whitespace() {
result.push(c);
quoted = c == '"';
}
}
result
}
#[test]
fn every_syntax_variant_keeps_tokens_and_parentheses_across_layouts() {
let origin = Origin::new("layout.rs", 42, 7, "layout test");
let variable = || Box::new(plain(NixKind::Variable("value".into())));
let mut nodes = vec![
plain(NixKind::Bool(false)),
plain(NixKind::Int(-42)),
plain(NixKind::Float(0.5)),
plain(NixKind::Null),
plain(NixKind::String(
"spaces and \"quotes\"; # text\n${data}".into(),
)),
plain(NixKind::Path("./nixpkgs/lib".into())),
words(),
plain(NixKind::Group(Box::new(fields()))),
fields(),
plain(NixKind::Apply(variable(), Box::new(words()))),
plain(NixKind::If(
variable(),
Box::new(words()),
Box::new(fields()),
)),
plain(NixKind::Assert(variable(), Box::new(fields()))),
plain(NixKind::Let("value".into(), Box::new(words()), variable())),
plain(NixKind::Select(variable(), vec!["literal.dot".into()])),
plain(NixKind::ArgumentSelect(
variable(),
vec!["safe".into(), "odd name".into()],
)),
plain(NixKind::ArgumentSelect(variable(), vec![])),
plain(NixKind::Function(
vec!["first".into(), "second".into()],
Box::new(fields()),
)),
plain(NixKind::Lambda("argument".into(), Box::new(fields()))),
plain(NixKind::ArgumentFunction(
vec![("first".into(), Some(words()))],
Box::new(fields()),
)),
NixExpr::contextual(NixKind::Group(Box::new(fields())), origin.clone()),
];
for builtin in [
Builtin::Div,
Builtin::Throw,
Builtin::Import,
Builtin::GetAttr,
Builtin::ToPath,
Builtin::ToString,
] {
nodes.push(plain(NixKind::Call(builtin, vec![words()])));
}
for operator in [
BinaryOp::Equal,
BinaryOp::GreaterEqual,
BinaryOp::LessEqual,
BinaryOp::And,
BinaryOp::Add,
BinaryOp::AttrMerge,
] {
nodes.push(plain(NixKind::Binary(
operator,
Box::new(words()),
Box::new(fields()),
)));
}
let expression = NixExpr::attributed(NixKind::List(nodes), origin);
let flat = layout::render(
&super::expression(&expression, RenderOptions::default()),
usize::MAX,
);
for options in [
RenderOptions::default(),
RenderOptions {
origin_comments: true,
},
] {
let formatted = render_with_options(&expression, options);
assert_eq!(significant(&flat.source), significant(&formatted.source));
}
}
#[test]
fn byte_columns_map_failures_after_inline_unicode_in_both_modes() {
let config = Config::new()
.set_dynamic("good", "λé")
.set_dynamic("bad", rusix::Expr::int(1).divide(rusix::Expr::int(0)));
let session = crate::NixSession::new().unwrap();
let normal = compile(&config).unwrap();
let inspection = crate::compile_with_options(
&config,
RenderOptions {
origin_comments: true,
},
)
.unwrap();
let normal = session.evaluate_attribute(&normal, "bad").unwrap_err();
let inspection = session.evaluate_attribute(&inspection, "bad").unwrap_err();
crate::compiler::context_audit::equivalent_diagnostics(&normal, &inspection);
assert_eq!(normal.primary.as_ref().unwrap().purpose, "integer division");
assert_eq!(normal.provenance, crate::Provenance::SourceMap);
}