use crate::ast::*;
use crate::{Options, Parsed, parse};
fn ok(text: &str) -> TranslationUnit {
let parsed = parse("t.hlsl", text, Options::default());
let errors: Vec<String> = parsed
.diagnostics
.iter()
.map(|d| d.display(&parsed.files).to_string())
.collect();
assert!(errors.is_empty(), "{errors:#?}");
parsed.unit
}
fn errors(text: &str) -> Vec<String> {
let parsed: Parsed = parse("t.hlsl", text, Options::default());
parsed
.diagnostics
.iter()
.map(|d| d.display(&parsed.files).to_string())
.collect()
}
fn body(text: &str) -> Vec<Stmt> {
let unit = ok(text);
match &unit.items[..] {
[Item::Function(f)] => f.body.clone().expect("a body").stmts,
other => panic!("{other:?}"),
}
}
fn expr(text: &str) -> String {
let stmts = body(&format!("void f() {{ {text}; }}"));
match &stmts[0].kind {
StmtKind::Expr(e) => sexpr(e),
other => panic!("{other:?}"),
}
}
fn sexpr(e: &Expr) -> String {
let list = |items: &[Expr]| items.iter().map(sexpr).collect::<Vec<_>>().join(" ");
match &e.kind {
ExprKind::Literal(Literal::Int(s) | Literal::Float(s) | Literal::Str(s)) => s.clone(),
ExprKind::Literal(Literal::Bool(b)) => b.to_string(),
ExprKind::Ident(name) => name.clone(),
ExprKind::Unary(op, x) => format!("({op:?} {})", sexpr(x)),
ExprKind::Binary(op, a, b) => format!("({op:?} {} {})", sexpr(a), sexpr(b)),
ExprKind::Assign(op, a, b) => format!("(= {op:?} {} {})", sexpr(a), sexpr(b)),
ExprKind::Ternary(c, a, b) => format!("(? {} {} {})", sexpr(c), sexpr(a), sexpr(b)),
ExprKind::Comma(items) => format!("(, {})", list(items)),
ExprKind::Call(f, args) => format!("(call {} {})", sexpr(f), list(args)),
ExprKind::Construct(ty, args) => format!("(new {} {})", ty.name.name, list(args)),
ExprKind::Cast(ty, x) => format!("(cast {} {})", ty.name.name, sexpr(x)),
ExprKind::Member(x, name) => format!("(. {} {})", sexpr(x), name.name),
ExprKind::Index(x, i) => format!("([] {} {})", sexpr(x), sexpr(i)),
}
}
#[test]
fn precedence_and_associativity() {
assert_eq!(expr("a + b * c - d"), "(Sub (Add a (Mul b c)) d)");
assert_eq!(
expr("a || b && c | d ^ e & f"),
"(Or a (And b (BitOr c (BitXor d (BitAnd e f)))))"
);
assert_eq!(expr("a == b < c << d"), "(Eq a (Lt b (Shl c d)))");
assert_eq!(expr("a = b += c"), "(= None a (= Some(Add) b c))");
assert_eq!(expr("c ? a : b ? d : e"), "(? c a (? b d e))");
assert_eq!(expr("a, b = 1"), "(, a (= None b 1))");
}
#[test]
fn unary_postfix_and_casts() {
assert_eq!(expr("- -x++"), "(Neg (Neg (PostInc x)))");
assert_eq!(expr("!a.x[2].yz"), "(Not (. ([] (. a x) 2) yz))");
assert_eq!(expr("(float)x * 2"), "(Mul (cast float x) 2)");
assert_eq!(expr("(float2(1, 2)).y"), "(. (new float2 1 2) y)");
assert_eq!(expr("(x) - 1"), "(Sub x 1)");
assert_eq!(expr("float4(uv, 0, 1).xy"), "(. (new float4 uv 0 1) xy)");
assert_eq!(
expr("tex2D(sampler_main, uv).xyz"),
"(. (call tex2D sampler_main uv) xyz)"
);
assert_eq!(expr("tex.Sample(s, uv)"), "(call (. tex Sample) s uv)");
assert_eq!(expr("--i"), "(PreDec i)");
}
#[test]
fn a_template_constructor_in_parentheses_is_not_a_cast() {
assert_eq!(expr("(vector<float, 2>(1, 2)).y"), "(. (new vector 1 2) y)");
assert_eq!(expr("(vector<float, 2>)x"), "(cast vector x)");
assert_eq!(expr("(vector<vector<float, 2>>)x"), "(cast vector x)");
}
#[test]
fn a_variable_that_hides_a_type_name_is_not_a_cast() {
let stmts = body(
"void f(float sampler) { float texture = 1; x = (texture) + 1; y = (sampler) * 2; \
{ float S = 1; z = (S) - 1; } }",
);
let exprs: Vec<String> = stmts[1..]
.iter()
.map(|s| match &s.kind {
StmtKind::Expr(e) => sexpr(e),
StmtKind::Block(b) => match &b.stmts[1].kind {
StmtKind::Expr(e) => sexpr(e),
other => panic!("{other:?}"),
},
other => panic!("{other:?}"),
})
.collect();
assert_eq!(
exprs,
[
"(= None x (Add texture 1))",
"(= None y (Mul sampler 2))",
"(= None z (Sub S 1))",
]
);
let unit = ok("struct S { float a; };\nfloat4 texture;\n\
float f() { return (texture).x; }\nfloat g() { float S = 1; return (S) - 1; }\n\
S h(float y) { return (S)y; }");
let Item::Function(h) = &unit.items[4] else {
panic!()
};
let StmtKind::Return(Some(e)) = &h.body.as_ref().unwrap().stmts[0].kind else {
panic!()
};
assert_eq!(sexpr(e), "(cast S y)");
}
#[test]
fn template_types_split_a_double_close() {
let unit = ok("Texture2D<vector<float, 4>> tex; vector<float, 2 + 1> v;");
let Item::Variable(var) = &unit.items[0] else {
panic!()
};
assert_eq!(var.ty.name.name, "Texture2D");
let TypeArg::Type(inner) = &var.ty.args[0] else {
panic!()
};
assert_eq!(inner.name.name, "vector");
assert_eq!(inner.args.len(), 2);
assert_eq!(expr("vector<float, 2>(1, 2)"), "(new vector 1 2)");
}
#[test]
fn a_milkdrop_style_shader_parses() {
let text = r#"
#define sat saturate
sampler sampler_pw_noise_lq;
static const float PI = 3.14159265;
float4 _qa : register(c0);
float3 glow(float2 p, float r) { return sat(1 - length(p) / r).xxx; }
void main(float2 uv : TEXCOORD0, out float4 ret : COLOR0)
{
float3 c = tex2D(sampler_main, uv).xyz * 0.98f;
[unroll] for (int i = 0; i < 4; i++) {
c += glow(uv - 0.5, 0.1 + i * 0.05) * (i % 2 == 0 ? 1 : 0.5);
}
if (c.x > 1) c = 1; else { c *= 0.5; }
ret = float4(c, 1);
}
"#;
let unit = ok(text);
assert_eq!(unit.items.len(), 5);
let Item::Function(main) = &unit.items[4] else {
panic!()
};
assert_eq!(main.params.len(), 2);
assert_eq!(main.params[1].modifiers, [Modifier::Out]);
assert_eq!(
main.params[1].bindings.semantic.as_ref().unwrap().name,
"COLOR0"
);
let stmts = &main.body.as_ref().unwrap().stmts;
assert_eq!(stmts[1].attributes[0].name.name, "unroll");
assert!(matches!(stmts[1].kind, StmtKind::For { .. }));
assert!(matches!(
stmts[2].kind,
StmtKind::If {
otherwise: Some(_),
..
}
));
}
#[test]
fn declarations_with_bindings_initializers_and_annotations() {
let text = r#"
struct VSOut { float4 pos : SV_Position; nointerpolation float2 uv : TEXCOORD0; };
typedef float3 color, palette[4];
cbuffer Params : register(b0) { float4 tint : packoffset(c0); float gain : packoffset(c1.y); };
static const float2 offsets[2] = { {0.5, 0.5}, {1, 1}, };
color base = {1, 0, 0};
float amount < string UIName = "Amount"; > = 0.5;
texture tex;
sampler2D s : register(ps_3_0, s1) = sampler_state { Texture = <tex>; MinFilter = Linear; AddressU = (WRAP); };
float4 f(VSOut v, uniform float k = 2, float) : SV_Target { palette p; color c = (color)0; return 0; }
"#;
let unit = ok(text);
assert_eq!(unit.items.len(), 9);
let Item::Struct(s) = &unit.items[0] else {
panic!()
};
assert_eq!(s.fields[1].modifiers, [Modifier::Nointerpolation]);
let Item::Buffer(b) = &unit.items[2] else {
panic!()
};
let pack = b.members[1].declarators[0]
.bindings
.packoffset
.as_ref()
.unwrap();
assert_eq!(
(
pack.slot.name.as_str(),
pack.component.as_ref().unwrap().name.as_str()
),
("c1", "y")
);
let Item::Variable(offsets) = &unit.items[3] else {
panic!()
};
assert!(
matches!(&offsets.declarators[0].init, Some(Initializer::List(items, _)) if items.len() == 2)
);
let Item::Variable(amount) = &unit.items[5] else {
panic!()
};
assert!(amount.declarators[0].annotations.is_some());
let Item::Variable(sampler) = &unit.items[7] else {
panic!()
};
let reg = &sampler.declarators[0].bindings.registers[0];
assert_eq!(reg.profile.as_ref().unwrap().name, "ps_3_0");
let Some(Initializer::SamplerState(states, _)) = &sampler.declarators[0].init else {
panic!()
};
assert_eq!(states.len(), 3);
assert_eq!(states[0].value.kind, ExprKind::Ident("tex".into()));
let Item::Function(f) = &unit.items[8] else {
panic!()
};
assert!(f.params[2].name.is_none());
assert!(f.params[1].default.is_some());
assert_eq!(
f.return_bindings.semantic.as_ref().unwrap().name,
"SV_Target"
);
}
#[test]
fn a_greater_than_inside_an_annotation_entry_does_not_close_it() {
let unit = ok(
"float a < bool b = (1 > 0); int c = 2 > 1; vector<float, 2> v = 1; > = 0.5;\nfloat z < > ;",
);
assert_eq!(unit.items.len(), 2);
let Item::Variable(a) = &unit.items[0] else {
panic!()
};
assert!(matches!(
&a.declarators[0].init,
Some(Initializer::Expr(Expr {
kind: ExprKind::Literal(Literal::Float(_)),
..
}))
));
}
#[test]
fn statements() {
let stmts = body(
"void f() { ; { } while (a) a--; do { b++; } while (b < 3); \
switch (k) { case 0: case 1: x = 1; break; default: discard; } \
for (;;) { continue; } for (i = 0, j = 1; i < j; i++, j--) ; return; }",
);
let kinds: Vec<&str> = stmts
.iter()
.map(|s| match s.kind {
StmtKind::Empty => "empty",
StmtKind::Block(_) => "block",
StmtKind::While { .. } => "while",
StmtKind::DoWhile { .. } => "do",
StmtKind::Switch { .. } => "switch",
StmtKind::For { .. } => "for",
StmtKind::Return(None) => "return",
_ => "other",
})
.collect();
assert_eq!(
kinds,
[
"empty", "block", "while", "do", "switch", "for", "for", "return"
]
);
let StmtKind::Switch { cases, .. } = &stmts[4].kind else {
panic!()
};
assert_eq!(cases[0].labels.len(), 2);
assert_eq!(cases[0].stmts.len(), 2);
assert_eq!(cases[1].labels, [None]);
}
#[test]
fn variables_named_like_modifiers_and_types() {
assert_eq!(
expr("sample = linear * 2"),
"(= None sample (Mul linear 2))"
);
let stmts = body("void f() { float3 sample = 1; float texture = sample.x; texture += 1; }");
assert!(matches!(stmts[0].kind, StmtKind::Var(_)));
assert!(matches!(stmts[2].kind, StmtKind::Expr(_)));
}
#[test]
fn unknown_type_names_still_declare() {
let stmts = body("void f() { Light l; l.color = 1; }");
let StmtKind::Var(var) = &stmts[0].kind else {
panic!()
};
assert_eq!(var.ty.name.name, "Light");
}
#[test]
fn errors_are_reported_and_parsing_goes_on() {
let e = errors("void f() { x = ; y = 2 }\nfloat4 g() { return 1; }\nint 3;");
assert_eq!(e.len(), 3, "{e:#?}");
assert!(e[0].starts_with("t.hlsl:1:16: error: expected an expression"));
assert!(e[1].contains("expected `;`"));
assert!(e[2].starts_with("t.hlsl:3:5"));
let parsed = parse(
"t.hlsl",
"void f() { x = ; y = 1; }\nfloat4 g() { return 1; }",
Options::default(),
);
assert_eq!(parsed.unit.items.len(), 2);
let Item::Function(f) = &parsed.unit.items[0] else {
panic!()
};
assert_eq!(f.body.as_ref().unwrap().stmts.len(), 1);
}
#[test]
fn a_node_from_a_function_like_macro_covers_the_call() {
let parsed = parse(
"t.hlsl",
"#define GET(uv) tex2D(s, uv)\nvoid f() { x = GET(t); }",
Options::default(),
);
let Item::Function(f) = &parsed.unit.items[0] else {
panic!()
};
let StmtKind::Expr(e) = &f.body.as_ref().unwrap().stmts[0].kind else {
panic!()
};
assert_eq!(parsed.files.text(e.span), "x = GET(t)");
}
#[test]
fn errors_in_macros_point_at_the_call() {
let e = errors("#define BAD (1 +)\nvoid f() { x = BAD; }");
assert_eq!(e.len(), 1);
assert!(e[0].starts_with("t.hlsl:2:16"), "{e:?}");
}
#[test]
fn techniques_and_stray_tokens_are_errors() {
assert_eq!(errors("technique T { pass P { } }\nfloat x;").len(), 1);
let e = errors("technique11 T < string s = \"x\"; int n = 1; > { pass P { } }\nfloat x;");
assert_eq!(e.len(), 1, "{e:#?}");
assert_eq!(errors("void f() { else x; }").len(), 1);
assert_eq!(errors("[unroll] typedef float x;").len(), 1);
assert_eq!(errors("void f() {").len(), 1);
}
#[test]
fn deep_nesting_is_an_error_not_a_crash() {
let depth = 20_000;
let text = format!(
"void f() {{ x = {}1{}; }}",
"(".repeat(depth),
")".repeat(depth)
);
assert!(errors(&text).iter().any(|e| e.contains("nested more than")));
let text = format!("void f() {}{}", "{".repeat(depth), "}".repeat(depth));
assert!(errors(&text).iter().any(|e| e.contains("nested more than")));
let text = format!("void f() {{ x = {}1; }}", "-".repeat(depth));
assert!(errors(&text).iter().any(|e| e.contains("nested more than")));
let text = format!("void f() {{ x = {}1; }}", "a ? b : ".repeat(depth));
assert!(errors(&text).iter().any(|e| e.contains("nested more than")));
let text = format!(
"vector<{}float{}> v;",
"vector<".repeat(depth),
">".repeat(depth)
);
assert!(errors(&text).iter().any(|e| e.contains("nested more than")));
for chain in ["a = ", "a + ", "a * b + "] {
let text = format!("void f() {{ x = {}1; }}", chain.repeat(depth));
assert!(
errors(&text)
.iter()
.any(|e| e.contains("more than 256 levels")),
"{chain}"
);
}
let text = format!("void f() {{ x = a{}; }}", ".x".repeat(depth));
assert!(
errors(&text)
.iter()
.any(|e| e.contains("more than 256 levels"))
);
let text = format!("void f() {{ x = a{}; }}", "[0]".repeat(depth));
assert!(
errors(&text)
.iter()
.any(|e| e.contains("more than 256 levels"))
);
let inner = format!("a{}", " + a".repeat(150));
let text = format!(
"void f() {{ x = ({inner}) + ({inner}){}; }}",
" + a".repeat(150)
);
assert!(
errors(&text)
.iter()
.any(|e| e.contains("more than 256 levels"))
);
}
#[test]
fn long_chains_below_the_tree_limit_parse() {
ok(&format!("void f() {{ x = a{}; }}", " + a".repeat(200)));
ok(&format!("void f() {{ x = a{}; }}", ".x".repeat(200)));
assert!(expr(&format!("{}1", "a = ".repeat(100))).starts_with("(= None a (= None a"));
}
#[test]
fn nesting_below_the_limit_parses() {
let depth = 40;
ok(&format!(
"void f() {{ x = {}1{}; }}",
"(".repeat(depth),
")".repeat(depth)
));
ok(&format!(
"void f() {{ x = {}1{}; }}",
"a[".repeat(depth),
"]".repeat(depth)
));
ok(&format!(
"void f() {}{}",
"{".repeat(depth),
"}".repeat(depth)
));
}
#[test]
fn spans_cover_the_source_of_each_node() {
let parsed = parse("t.hlsl", "void f() { x = a + b; }", Options::default());
let Item::Function(f) = &parsed.unit.items[0] else {
panic!()
};
let StmtKind::Expr(e) = &f.body.as_ref().unwrap().stmts[0].kind else {
panic!()
};
assert_eq!(parsed.files.text(e.span), "x = a + b");
assert_eq!(parsed.files.text(f.span), "void f() { x = a + b; }");
}
#[test]
fn builtin_type_names() {
use crate::parser::is_builtin_type;
for t in [
"float",
"float1",
"float4x4",
"half3",
"min16float2",
"uint2x3",
"sampler2D",
"Texture2D",
] {
assert!(is_builtin_type(t), "{t}");
}
for t in ["float5", "float4x", "float0", "floaty", "Light"] {
assert!(!is_builtin_type(t), "{t}");
}
}
#[test]
fn the_deepest_accepted_nesting_fits_a_small_stack() {
let n = crate::parser::MAX_DEPTH - 2;
let inputs = [
format!("void f() {{ x = {}1{}; }}", "(".repeat(n), ")".repeat(n)),
format!("void f() {{ x = {}1{}; }}", "a[".repeat(n), "]".repeat(n)),
format!("void f() {{ x = {}1{}; }}", "f(".repeat(n), ")".repeat(n)),
format!(
"void f() {{ x = {}1{}; }}",
"float4(".repeat(n),
")".repeat(n)
),
format!("void f() {{ x = {}1; }}", "a ? b : ".repeat(n)),
format!("void f() {{ x = {}1; }}", "-".repeat(n)),
format!("void f() {}{}", "{".repeat(n), "}".repeat(n)),
format!("void f() {{ {}x = 1; }}", "if (a) ".repeat(n)),
format!("float a = {}1{};", "{".repeat(n), "}".repeat(n)),
format!("{}float x;{}", "namespace a { ".repeat(n), "}".repeat(n)),
format!("{}float x;{}", "struct a { ".repeat(n), "};".repeat(n)),
];
std::thread::Builder::new()
.stack_size(768 * 1024)
.spawn(move || {
for text in inputs {
let parsed = parse("t.hlsl", &text, Options::default());
assert!(!parsed.has_errors(), "{text:.40}");
}
})
.unwrap()
.join()
.unwrap();
}
#[test]
fn errors_in_a_switch_keep_the_other_cases_and_the_function() {
let text = "void f() { switch (k) { case 1 x = 1; break; case 2: y = 2; break; } z = 3; }\nfloat4 g() : COLOR { return 1; }";
let parsed = parse("t.hlsl", text, Options::default());
assert_eq!(parsed.diagnostics.len(), 1, "{:?}", parsed.diagnostics);
assert_eq!(parsed.unit.items.len(), 2);
let Item::Function(f) = &parsed.unit.items[0] else {
panic!()
};
let stmts = &f.body.as_ref().unwrap().stmts;
assert_eq!(stmts.len(), 2);
let StmtKind::Switch { cases, .. } = &stmts[0].kind else {
panic!()
};
assert_eq!(cases.len(), 2);
assert_eq!(cases[1].stmts.len(), 2);
let text = "void f() { switch (k) { case 0: x = 1 case 1: y = 2; break; } }";
let parsed = parse("t.hlsl", text, Options::default());
assert_eq!(parsed.diagnostics.len(), 1, "{:?}", parsed.diagnostics);
let Item::Function(f) = &parsed.unit.items[0] else {
panic!()
};
let StmtKind::Switch { cases, .. } = &f.body.as_ref().unwrap().stmts[0].kind else {
panic!()
};
assert_eq!(cases.len(), 2);
assert_eq!(cases[1].stmts.len(), 2);
}
#[test]
fn errors_in_struct_buffer_and_sampler_bodies_stay_inside_the_body() {
let cases = [
(
"struct S { float4 pos : SV_Position float2 uv; float3 n; };\nfloat4 main() : COLOR { return 0; }",
1,
),
("cbuffer B { float a b; float c; };\nfloat x;", 1),
(
"sampler s = sampler_state { Texture = ; MinFilter = Linear; };\nfloat x;",
1,
),
];
for (text, members) in cases {
let parsed = parse("t.hlsl", text, Options::default());
assert_eq!(
parsed.diagnostics.len(),
1,
"{text}: {:?}",
parsed.diagnostics
);
assert_eq!(parsed.unit.items.len(), 2, "{text}");
let kept = match &parsed.unit.items[0] {
Item::Struct(s) => s.fields.len(),
Item::Buffer(b) => b.members.len(),
Item::Variable(v) => match &v.declarators[0].init {
Some(Initializer::SamplerState(states, _)) => states.len(),
other => panic!("{other:?}"),
},
other => panic!("{other:?}"),
};
assert_eq!(kept, members, "{text}");
}
}
#[test]
fn geometry_hull_and_domain_shader_parameters() {
let text = "struct VS_OUT { float4 p : SV_Position; };\nstruct HS_OUT { float4 p : POS; };\n\
[maxvertexcount(3)] void GS(triangle float4 p[3] : SV_Position, inout TriangleStream<VS_OUT> s) { s.Append((VS_OUT)0); }\n\
HS_OUT HS(InputPatch<VS_OUT, 4> ip, uint i : SV_OutputControlPointID) { HS_OUT o; return o; }\n\
void DS(const OutputPatch<HS_OUT, 4> patch, lineadj float a[4] : A, point float b[1] : B, line float c[2] : C, triangleadj float d[6] : D) { }";
let unit = ok(text);
let Item::Function(gs) = &unit.items[2] else {
panic!()
};
assert_eq!(gs.params[0].modifiers, [Modifier::Triangle]);
assert_eq!(gs.params[1].ty.name.name, "TriangleStream");
let Item::Function(ds) = &unit.items[4] else {
panic!()
};
let mods: Vec<_> = ds.params[1..].iter().map(|p| p.modifiers[0]).collect();
assert_eq!(
mods,
[
Modifier::LineAdj,
Modifier::Point,
Modifier::Line,
Modifier::TriangleAdj
]
);
}
#[test]
fn the_d3d10_sampler_block() {
let unit =
ok("SamplerState samLinear { Filter = MIN_MAG_MIP_LINEAR; AddressU = Wrap; };\nfloat x;");
let Item::Variable(var) = &unit.items[0] else {
panic!()
};
let Some(Initializer::SamplerState(states, _)) = &var.declarators[0].init else {
panic!()
};
assert_eq!(states.len(), 2);
assert_eq!(errors("float x { a = 1; };").len(), 1);
}
#[test]
fn register_spaces_and_one_register_per_profile() {
let unit = ok(
"Texture2D tex : register(t0, space1);\nfloat4 c : register(vs_3_0, c0) : register(ps_3_0, c1);\nsampler s : register(s2);",
);
let reg = |i: usize, n: usize| {
let Item::Variable(v) = &unit.items[i] else {
panic!()
};
let r = &v.declarators[0].bindings.registers[n];
let name = |x: &Option<Ident>| x.as_ref().map(|x| x.name.clone());
(name(&r.profile), r.slot.name.clone(), name(&r.space))
};
assert_eq!(reg(0, 0), (None, "t0".into(), Some("space1".into())));
assert_eq!(reg(1, 0), (Some("vs_3_0".into()), "c0".into(), None));
assert_eq!(reg(1, 1), (Some("ps_3_0".into()), "c1".into(), None));
assert_eq!(reg(2, 0), (None, "s2".into(), None));
assert_eq!(errors("float a : register(a, b, c, d);").len(), 1);
}
#[test]
fn numbers_with_a_bad_suffix_or_exponent_are_errors() {
let e = errors(
"float a = 1.5u; float b = 3fu; int c = 0x1uuuLLL; float d = 1e+x; float e = 2e; float f = 1.0hf;",
);
assert_eq!(e.len(), 6, "{e:#?}");
assert!(
e.iter().all(|e| e.ends_with("is not a valid number")),
"{e:#?}"
);
assert!(e[3].contains("`1e+x`"), "{e:#?}");
ok("float f = 1.0h + 1.5L + 3f + 10u + 0x1Fu + 1e-3f + 2ul + 3ll + .5 + 2. + 1E3 + 0xFFLU;");
}
#[test]
fn adjacent_strings_join_into_one() {
let parsed = parse(
"t.hlsl",
"string s = \"a\" \"b\"\n\"\";",
Options::default(),
);
assert!(parsed.diagnostics.is_empty(), "{:?}", parsed.diagnostics);
let Item::Variable(s) = &parsed.unit.items[0] else {
panic!()
};
let Some(Initializer::Expr(e)) = &s.declarators[0].init else {
panic!()
};
assert_eq!(e.kind, ExprKind::Literal(Literal::Str("\"ab\"".into())));
assert_eq!(parsed.files.text(e.span), "\"a\" \"b\"\n\"\"");
}
#[test]
fn a_stray_character_is_reported_as_itself() {
assert_eq!(
errors("float x = 1 @;\n#if 0\n$\n#endif\n#define S(x) #x\nstring s = S($);"),
["t.hlsl:1:13: error: unexpected character `@`"]
);
}
#[test]
fn a_second_semantic_or_packoffset_is_an_error() {
let e = errors(
"float4 c : COLOR0 : register(c0) : COLOR1;\ncbuffer B { float a : packoffset(c0) : packoffset(c1); };\nfloat d;",
);
assert_eq!(e.len(), 2, "{e:#?}");
assert!(e[0].starts_with("t.hlsl:1:36"), "{e:#?}");
assert!(e[1].starts_with("t.hlsl:2:40"), "{e:#?}");
}
#[test]
fn a_split_double_close_belongs_to_both_type_spans() {
let parsed = parse(
"t.hlsl",
"Texture2D<vector<float, 4>> tex;",
Options::default(),
);
let Item::Variable(var) = &parsed.unit.items[0] else {
panic!()
};
let TypeArg::Type(inner) = &var.ty.args[0] else {
panic!()
};
assert_eq!(parsed.files.text(inner.span), "vector<float, 4>");
assert_eq!(
parsed.files.text(var.ty.span),
"Texture2D<vector<float, 4>>"
);
}
struct Body;
impl crate::IncludeResolver for Body {
fn resolve(&mut self, path: &str, _: bool, _: &str) -> Result<(String, String), String> {
Ok((path.to_string(), "x = 1;".to_string()))
}
}
#[test]
fn an_error_at_the_end_points_at_the_end_of_the_main_file() {
let mut resolver = Body;
let options = Options {
includes: Some(&mut resolver),
..Options::default()
};
let parsed = parse("t.hlsl", "void f() {\n#include \"body.h\"\n", options);
let e: Vec<String> = parsed
.diagnostics
.iter()
.map(|d| d.display(&parsed.files).to_string())
.collect();
assert_eq!(
e,
["t.hlsl:3:1: error: expected `}`, found the end of the input"]
);
}
#[test]
fn the_prelude_runs_first_and_its_macros_apply_to_the_source() {
let options = Options {
prelude: Some("#define q1 _qa.x\nfloat4 _qa;\n".to_string()),
..Options::default()
};
let parsed = parse("t.hlsl", "float f() { return q1; }", options);
assert!(!parsed.has_errors(), "{:?}", parsed.diagnostics);
assert_eq!(parsed.unit.items.len(), 2);
let Item::Function(f) = &parsed.unit.items[1] else {
panic!()
};
assert_eq!(parsed.files.get(f.span.file).unwrap().name, "t.hlsl");
}
#[test]
fn a_byte_order_mark_before_a_directive_is_skipped() {
let unit = ok("\u{FEFF}#define N 1\nfloat x = N;");
assert_eq!(unit.items.len(), 1);
}
fn global_types(text: &str) -> Vec<(String, String)> {
let parsed = parse("t.hlsl", text, Options::default());
assert!(!parsed.has_errors(), "{:?}", parsed.diagnostics);
parsed
.unit
.items
.iter()
.filter_map(|item| match item {
Item::Variable(v) => Some((
v.ty.name.name.clone(),
parsed.files.text(v.ty.span).to_string(),
)),
_ => None,
})
.collect()
}
#[test]
fn unsigned_and_signed_int_name_uint_and_int() {
let types = global_types(
"unsigned int a; unsigned b; signed int c; signed d; const unsigned int e = 1;\n\
vector<unsigned int, 4> f; matrix<signed int, 2, 2> g;",
);
let names: Vec<&str> = types.iter().map(|(n, _)| n.as_str()).collect();
assert_eq!(
names,
["uint", "uint", "int", "int", "uint", "vector", "matrix"]
);
assert_eq!(types[0].1, "unsigned int");
assert_eq!(types[1].1, "unsigned");
assert_eq!(
expr("(unsigned int)x + (unsigned)y + (signed int)z"),
"(Add (Add (cast uint x) (cast uint y)) (cast int z))"
);
let unit = ok(
"unsigned int f(unsigned int x) { unsigned int y = x; return y; }\ntypedef unsigned int u32;",
);
let Item::Function(f) = &unit.items[0] else {
panic!()
};
assert_eq!(f.return_type.name.name, "uint");
assert_eq!(f.params[0].ty.name.name, "uint");
let StmtKind::Var(y) = &f.body.as_ref().unwrap().stmts[0].kind else {
panic!()
};
assert_eq!(y.ty.name.name, "uint");
}
#[test]
fn enums_with_values_an_underlying_type_and_a_scope() {
let parsed = parse(
"t.hlsl",
"enum Color { Red, Green = 4, Blue };\nenum class Mode : uint { A = 1 << 2, B, };\n\
enum { up, down };\nenum Wide : unsigned int { X };\n\
void f() { enum L { P, Q }; int k = P; Color c = (Color)1; }",
Options::default(),
);
assert!(!parsed.has_errors(), "{:?}", parsed.diagnostics);
let enums: Vec<&EnumDef> = parsed
.unit
.items
.iter()
.filter_map(|i| match i {
Item::Enum(e) => Some(e),
_ => None,
})
.collect();
assert_eq!(enums.len(), 4);
let names = |e: &EnumDef| -> Vec<String> {
e.enumerators.iter().map(|n| n.name.name.clone()).collect()
};
assert_eq!(names(enums[0]), ["Red", "Green", "Blue"]);
assert!(!enums[0].scoped);
assert_eq!(parsed.files.text(enums[0].enumerators[1].span), "Green = 4");
assert!(enums[0].enumerators[0].value.is_none());
assert!(enums[1].scoped);
assert_eq!(enums[1].base.as_ref().unwrap().name.name, "uint");
assert_eq!(names(enums[1]), ["A", "B"]);
assert!(enums[2].name.is_none());
assert_eq!(names(enums[2]), ["up", "down"]);
assert_eq!(enums[3].base.as_ref().unwrap().name.name, "uint");
assert_eq!(
parsed.files.text(enums[1].span),
"enum class Mode : uint { A = 1 << 2, B, };"
);
let Item::Function(f) = &parsed.unit.items[4] else {
panic!()
};
let stmts = &f.body.as_ref().unwrap().stmts;
assert!(matches!(&stmts[0].kind, StmtKind::Enum(e) if names(e) == ["P", "Q"]));
let StmtKind::Var(c) = &stmts[2].kind else {
panic!()
};
let Some(Initializer::Expr(e)) = &c.declarators[0].init else {
panic!()
};
assert_eq!(sexpr(e), "(cast Color 1)");
}
#[test]
fn an_enumerator_hides_a_type_of_the_same_name() {
let stmts = body("void f() { enum { float2 }; x = (float2) + 1; }");
let StmtKind::Expr(e) = &stmts[1].kind else {
panic!()
};
assert_eq!(sexpr(e), "(= None x (Add float2 1))");
}
#[test]
fn bad_enums_are_errors() {
assert_eq!(errors("enum E { A B };\nfloat x;").len(), 1);
assert_eq!(errors("enum class { A };\nfloat x;").len(), 1);
assert_eq!(errors("enum E { A = };\nfloat x;").len(), 1);
assert_eq!(errors("enum E { A }\nfloat x;").len(), 1);
}
#[test]
fn namespaces_and_qualified_names() {
let text = "namespace N {\n\
static const float k = 2;\n\
struct S { float a; };\n\
enum class E { A, B };\n\
float f(float x) { S s = (S)0; return x * k + (float)E::A; }\n\
namespace M { typedef float4 V; float g() { return 1; } }\n\
}\n\
namespace { float hidden; }\n\
N::S s;\n\
N::M::V v;\n\
float h() { N::S t = (N::S)0; return N::f(N::k) + N::M::g() + (float)N::E::B; }\n\
float4 c() { return N::M::V(1, 2, 3, 4); }";
let parsed = parse("t.hlsl", text, Options::default());
assert!(!parsed.has_errors(), "{:?}", parsed.diagnostics);
let items = &parsed.unit.items;
let Item::Namespace(n) = &items[0] else {
panic!()
};
assert_eq!(n.name.as_ref().unwrap().name, "N");
assert_eq!(n.items.len(), 5);
assert!(matches!(&n.items[4], Item::Namespace(m) if m.items.len() == 2));
let Item::Namespace(unnamed) = &items[1] else {
panic!()
};
assert!(unnamed.name.is_none());
let Item::Variable(s) = &items[2] else {
panic!()
};
assert_eq!(s.ty.name.name, "N::S");
assert_eq!(parsed.files.text(s.ty.span), "N::S");
let Item::Variable(v) = &items[3] else {
panic!()
};
assert_eq!(v.ty.name.name, "N::M::V");
let ret = |i: usize| {
let Item::Function(f) = &items[i] else {
panic!()
};
let stmts = &f.body.as_ref().unwrap().stmts;
let StmtKind::Return(Some(e)) = &stmts.last().unwrap().kind else {
panic!()
};
(sexpr(e), parsed.files.text(e.span).to_string())
};
assert_eq!(
ret(4).0,
"(Add (Add (call N::f N::k) (call N::M::g )) (cast float N::E::B))"
);
assert_eq!(
ret(5),
(
"(new N::M::V 1 2 3 4)".to_string(),
"N::M::V(1, 2, 3, 4)".to_string()
)
);
let Item::Function(h) = &items[4] else {
panic!()
};
let StmtKind::Var(t) = &h.body.as_ref().unwrap().stmts[0].kind else {
panic!()
};
let Some(Initializer::Expr(e)) = &t.declarators[0].init else {
panic!()
};
assert_eq!(sexpr(e), "(cast N::S 0)");
}
#[test]
fn errors_in_a_namespace_stay_inside_it() {
let parsed = parse(
"t.hlsl",
"namespace N { float x float y; float z; }\nfloat w;",
Options::default(),
);
assert_eq!(parsed.diagnostics.len(), 1, "{:?}", parsed.diagnostics);
assert_eq!(parsed.unit.items.len(), 2);
assert!(matches!(&parsed.unit.items[0], Item::Namespace(n) if n.items.len() == 1));
assert_eq!(errors("namespace N { float x;").len(), 1);
let depth = 20_000;
let text = format!("{}{}", "namespace a { ".repeat(depth), "}".repeat(depth));
assert!(errors(&text).iter().any(|e| e.contains("nested more than")));
}
#[test]
fn struct_bases_methods_and_nested_types() {
let text = "struct B { float a; };\n\
struct D : B {\n\
float b;\n\
static float k;\n\
float sum() { return a + b; }\n\
void set(float v) { this.a = v; }\n\
};\n\
struct O { struct I { float x; } i; enum K { K0 }; typedef float2 F; F f; I j; };\n\
O::I oi;\n\
O::F of;\n\
float g(D d) { return ((D)d).sum() + d.sum(); }";
let unit = ok(text);
let Item::Struct(d) = &unit.items[1] else {
panic!()
};
assert_eq!(d.base.as_ref().unwrap().name.name, "B");
assert_eq!(d.fields.len(), 2);
assert_eq!(d.fields[1].modifiers, [Modifier::Static]);
let methods: Vec<&str> = d.methods.iter().map(|m| m.name.name.as_str()).collect();
assert_eq!(methods, ["sum", "set"]);
assert!(d.methods[0].body.is_some());
let Item::Struct(o) = &unit.items[2] else {
panic!()
};
assert!(matches!(
&o.nested[..],
[Item::Struct(_), Item::Enum(_), Item::Typedef(_)]
));
let fields: Vec<&str> = o
.fields
.iter()
.map(|f| f.declarators[0].name.name.as_str())
.collect();
assert_eq!(fields, ["i", "f", "j"]);
assert_eq!(o.fields[0].ty.name.name, "I");
let tys: Vec<&str> = unit.items[3..5]
.iter()
.map(|i| match i {
Item::Variable(v) => v.ty.name.name.as_str(),
other => panic!("{other:?}"),
})
.collect();
assert_eq!(tys, ["O::I", "O::F"]);
}
#[test]
fn structs_and_typedefs_inside_a_function() {
let stmts = body(
"void f() { struct L { float x; }; struct M { float y; } m, n; typedef float3 T; \
L l; T t = (T)0; m.y = 1; }",
);
assert!(matches!(&stmts[0].kind, StmtKind::Struct { def, vars: None } if def.name.name == "L"));
let StmtKind::Struct {
vars: Some(vars), ..
} = &stmts[1].kind
else {
panic!()
};
assert_eq!(vars.declarators.len(), 2);
assert_eq!(vars.ty.name.name, "M");
assert!(matches!(&stmts[2].kind, StmtKind::Typedef(t) if t.names[0].0.name == "T"));
assert!(matches!(&stmts[3].kind, StmtKind::Var(v) if v.ty.name.name == "L"));
let StmtKind::Var(t) = &stmts[4].kind else {
panic!()
};
let Some(Initializer::Expr(e)) = &t.declarators[0].init else {
panic!()
};
assert_eq!(sexpr(e), "(cast T 0)");
}
#[test]
fn an_error_in_a_method_stays_inside_the_struct() {
let parsed = parse(
"t.hlsl",
"struct S { float f() { x = ; return 1; } float g; };\nfloat z;",
Options::default(),
);
assert_eq!(parsed.diagnostics.len(), 1, "{:?}", parsed.diagnostics);
assert_eq!(parsed.unit.items.len(), 2);
let Item::Struct(s) = &parsed.unit.items[0] else {
panic!()
};
assert_eq!((s.methods.len(), s.fields.len()), (1, 1));
let depth = 20_000;
let text = format!("{}{}", "struct a { ".repeat(depth), "};".repeat(depth));
assert!(errors(&text).iter().any(|e| e.contains("nested more than")));
}
#[test]
fn attributes_on_globals_buffers_structs_fields_and_parameters() {
let text = "[[vk::binding(0, 1)]] Texture2D tex : register(t0);\n\
[[vk::binding(X, Y), vk::counter_binding(Z)]] RWStructuredBuffer<float> buf;\n\
[[vk::push_constant]] cbuffer PC { [[vk::offset(4)]] float a; };\n\
[[vk::constant_id(1)]] const bool flag = true;\n\
[[vk::image_format(\"rgba8\")]] RWTexture2D<float4> img;\n\
struct VSInput { [[vk::location(0)]] float4 pos : POSITION; };\n\
struct [raypayload] Payload { float4 color; };\n\
[[vk::location(1)]] float4 main([[vk::location(2)]] in float4 t : TEXCOORD) : TEXCOORD { return t; }";
let parsed = parse("t.hlsl", text, Options::default());
assert!(!parsed.has_errors(), "{:?}", parsed.diagnostics);
let items = &parsed.unit.items;
let attrs = |a: &[Attribute]| -> Vec<(String, usize, String)> {
a.iter()
.map(|a| {
(
a.name.name.clone(),
a.args.len(),
parsed.files.text(a.span).to_string(),
)
})
.collect()
};
let var = |i: usize| match &items[i] {
Item::Variable(v) => v,
other => panic!("{other:?}"),
};
assert_eq!(
attrs(&var(0).attributes),
[("vk::binding".into(), 2, "[[vk::binding(0, 1)]]".into())]
);
assert_eq!(
attrs(&var(1).attributes),
[
("vk::binding".into(), 2, "vk::binding(X, Y)".into()),
(
"vk::counter_binding".into(),
1,
"vk::counter_binding(Z)".into()
),
]
);
let Item::Buffer(pc) = &items[2] else {
panic!()
};
assert_eq!(pc.attributes[0].name.name, "vk::push_constant");
assert_eq!(pc.members[0].attributes[0].name.name, "vk::offset");
assert_eq!(var(3).attributes[0].name.name, "vk::constant_id");
assert_eq!(var(3).modifiers, [Modifier::Const]);
assert_eq!(var(4).attributes[0].args.len(), 1);
let Item::Struct(input) = &items[5] else {
panic!()
};
assert_eq!(input.fields[0].attributes[0].name.name, "vk::location");
let Item::Struct(payload) = &items[6] else {
panic!()
};
assert_eq!(
attrs(&payload.attributes),
[("raypayload".into(), 0, "[raypayload]".into())]
);
assert_eq!(payload.name.name, "Payload");
let Item::Function(main) = &items[7] else {
panic!()
};
assert_eq!(main.attributes[0].name.name, "vk::location");
assert_eq!(main.params[0].attributes[0].name.name, "vk::location");
assert_eq!(main.params[0].modifiers, [Modifier::In]);
}
#[test]
fn attributes_where_they_are_not_allowed_are_errors() {
assert_eq!(
errors("[[vk::binding(0)]] typedef float F;\nfloat x;").len(),
1
);
assert_eq!(errors("[unroll] struct S { float a; };\nfloat x;").len(), 1);
assert_eq!(errors("[[vk::binding(0)] float x;\nfloat y;").len(), 1);
assert_eq!(errors("[[a b]] float x;\nfloat y;").len(), 1);
}
#[test]
fn a_register_with_a_subcomponent() {
let unit = ok(
"sampler a : register(vs, s[8]);\nsampler b : register(ps, s[2]) : register(ps_5_0, s[0]);\n\
float4 c : register(c1[2]);\nTexture2D t : register(t0, space1);",
);
let regs: Vec<(String, Option<String>)> = unit
.items
.iter()
.flat_map(|i| match i {
Item::Variable(v) => v.declarators[0].bindings.registers.clone(),
other => panic!("{other:?}"),
})
.map(|r| (r.slot.name, r.subcomponent.map(|e| sexpr(&e))))
.collect();
let want = [
("s", Some("8")),
("s", Some("2")),
("s", Some("0")),
("c1", Some("2")),
("t0", None),
];
let want: Vec<(String, Option<String>)> = want
.iter()
.map(|(s, n)| (s.to_string(), n.map(str::to_string)))
.collect();
assert_eq!(regs, want);
assert_eq!(errors("float a : register(ps[1], c0);\nfloat b;").len(), 1);
assert_eq!(
errors("float a : register(t0, space1[2]);\nfloat b;").len(),
1
);
}
#[test]
fn unorm_and_snorm_in_template_arguments() {
let unit = ok("RWTexture2D<unorm float4> a; Texture2D<snorm float> b; RWBuffer<float4> c;");
let args: Vec<String> = unit
.items
.iter()
.map(|i| match i {
Item::Variable(v) => match &v.ty.args[0] {
TypeArg::Type(t) => t.name.name.clone(),
TypeArg::Modified(m, t) => format!("{m:?} {}", t.name.name),
other => panic!("{other:?}"),
},
other => panic!("{other:?}"),
})
.collect();
assert_eq!(args, ["[Unorm] float4", "[Snorm] float", "float4"]);
}
#[test]
fn coherence_export_and_mesh_shader_modifiers() {
let unit = ok(
"globallycoherent RWTexture2D<float4> a;\nreordercoherent RWStructuredBuffer<uint> b;\n\
export float identity(float x) { return x; }\n\
struct V { float4 p : SV_Position; };\nstruct P { uint n; };\n\
[outputtopology(\"triangle\")] void ms(in payload P p, out vertices V verts[64], \
out indices uint3 tris[126], out primitives P prims[126]) { }",
);
let Item::Variable(a) = &unit.items[0] else {
panic!()
};
assert_eq!(a.modifiers, [Modifier::Globallycoherent]);
let Item::Variable(b) = &unit.items[1] else {
panic!()
};
assert_eq!(b.modifiers, [Modifier::Reordercoherent]);
let Item::Function(f) = &unit.items[2] else {
panic!()
};
assert_eq!(f.modifiers, [Modifier::Export]);
let Item::Function(ms) = &unit.items[5] else {
panic!()
};
let mods: Vec<&[Modifier]> = ms.params.iter().map(|p| p.modifiers.as_slice()).collect();
assert_eq!(
mods,
[
&[Modifier::In, Modifier::Payload][..],
&[Modifier::Out, Modifier::Vertices],
&[Modifier::Out, Modifier::Indices],
&[Modifier::Out, Modifier::Primitives],
]
);
}
#[test]
fn templates_classes_and_interfaces_are_named_as_not_supported() {
for (text, word) in [
("template<typename T> T f(T x) { return x; }", "template"),
("class C { float x; };", "class"),
("interface I { float f(); };", "interface"),
] {
let e = errors(text);
assert!(
e.first()
.is_some_and(|m| m.contains(&format!("`{word}` is not supported yet"))),
"{e:?}"
);
}
}