#![allow(dead_code)]
#![allow(missing_docs, clippy::unwrap_used, clippy::expect_used)]
use oxblade::Shape;
use oxblade::ast::Template;
use oxblade::check::{
Checker, ComponentDefinition, DiagnosticKind, Placeholder, Resolver, Scope, Signature,
};
use oxblade::lexer::DirectiveTable;
use oxblade::parser::parse;
use oxblade::shape::{TypeDesc, TypeRegistry};
use oxblade::span::SourceMap;
use std::collections::BTreeMap;
const EXAMPLES: &str = include_str!("../../../design/EXAMPLES.md");
type Map<T> = BTreeMap<String, T>;
#[derive(Shape)]
struct Named {
name: String,
}
#[derive(Shape)]
struct User {
name: String,
nickname: Option<String>,
}
#[derive(Shape)]
struct Stats {
population: i64,
#[serde(skip_serializing_if = "Option::is_none")]
title: Option<String>,
}
#[derive(Shape)]
struct CityDetails {
country: Named,
mayor: Option<Named>,
stats: Stats,
tags: Vec<String>,
}
#[derive(Shape)]
struct CitySummary {
name: String,
country: String,
score: i64,
slug: String,
}
#[derive(Shape)]
struct Cost {
amount: i64,
}
#[derive(Shape)]
#[serde(untagged)]
enum Money {
Integer(i64),
Fraction(f64),
}
#[derive(Shape)]
struct Section {
enabled: bool,
title: String,
}
#[derive(Shape)]
struct CityRent {
name: String,
rent: i64,
}
#[derive(Shape)]
struct PagedCity {
name: String,
slug: String,
}
#[derive(Shape)]
struct CitiesPage {
data: Vec<PagedCity>,
}
#[derive(Shape)]
struct CityCard {
name: String,
country: String,
slug: String,
score: i64,
reviews: i64,
badge: Option<String>,
costs: Map<i64>,
tags: Vec<String>,
updated_at: String,
}
#[derive(Shape)]
struct Settings {
name: String,
website: String,
public: bool,
city: String,
saved: Vec<String>,
}
#[derive(Shape)]
struct Alert {
#[serde(rename = "type", default)]
kind: String,
message: Option<String>,
}
fn model(case: usize, registry: &mut TypeRegistry) -> TypeDesc {
macro_rules! fields {
($model:ident; $($field:ident : $ty:ty),* $(,)?) => {{
#[derive(Shape)]
struct $model { $($field: $ty),* }
$model::serialize_shape(registry)
}};
}
match case {
1 => fields!(Model1; name: String, bio: oxblade::Html),
2 => {
fields!(Model2; nickname: Option<String>, city: Option<Named>, meta: Map<String>, user: User)
}
4 => fields!(Model4; flag: bool, off: bool, third: f64, half: f64, big: f64),
5 => fields!(Model5; title: String, fallback: String),
6 => fields!(Model6; hidden: bool, subtitle: Option<String>, tags: Vec<String>),
7 => fields!(Model7; plan: String),
8 => fields!(Model8; tones: Vec<String>),
9 | 36 | 43 => fields!(Model9; count: i64),
10 => fields!(Model10; scores: Vec<i64>),
11 => fields!(Model11; cities: Vec<String>),
12 => fields!(Model12; events: Vec<String>),
13 => fields!(Model13; costs: Map<Money>),
14 => fields!(Model14; tabs: Vec<(String, String)>),
15 => fields!(Model15; ids: Vec<i64>),
16 => fields!(Model16; regions: Map<Vec<String>>),
18 => fields!(Model18; answers: Map<i64>, total: i64),
19 => fields!(Model19; name: String, city: String, count: i64),
20 => fields!(Model20; a: String, b: String, x: i64, y: i64),
21 => fields!(Model21; size: String, price: String, zero: String, count: i64),
22 => fields!(Model22; city: CityDetails),
23 => fields!(Model23; codes: Vec<String>, prices: Map<i64>),
24 => {
fields!(Model24; codes: Vec<String>, word: String, slug: String, padded: String, nums: Vec<i64>, note: String)
}
25 | 26 | 30 => fields!(Model25; cities: Vec<CitySummary>),
27 => fields!(Model27; costs: Vec<Cost>),
28 => fields!(Model28; photos: Vec<String>),
29 => fields!(Model29; nums: Vec<i64>),
31 => fields!(Model31; tags: Vec<String>),
32 => fields!(Model32; title: String, lower: String, n: i64),
33 => fields!(Model33; slug: String, email: String),
34 => fields!(Model34; n: i64, price: f64, bytes: i64, share: f64, pop: i64),
35 => fields!(Model35; at: String),
37 => fields!(Model37; sections: Map<Section>),
38 => fields!(Model38; score: i64, highlight: bool),
45 => fields!(Model45; kind: String),
47 => fields!(Model47; name: String),
48 => fields!(Model48; rent: i64, show_food: bool, tags: Vec<String>),
50 => fields!(Model50; city: CityRent),
51 => fields!(Model51; email: String),
52 => fields!(Model52; auth_user: Option<Named>),
54 => {
fields!(Model54; payload: Map<String>, small: Map<i64>, tabs: Vec<String>, active: String)
}
55 => fields!(Model55; tabs: Vec<String>, slug: String),
56 => fields!(Model56; name: String, n: i64),
57 => fields!(Model57; price: f64, day: String),
58 => fields!(Model58; users: Vec<Named>),
59 => fields!(Model59; cities: CitiesPage),
60 => fields!(Model60; city: CitySummary),
61 => fields!(Model61; cities: Vec<CityCard>, budget: i64),
62 => fields!(Model62; user: Settings, cities: Map<String>),
3 | 17 | 39..=42 | 44 | 46 | 49 | 53 | 63 => fields!(EmptyModel;),
_ => panic!("missing model for example {case}"),
}
}
struct Example {
section: usize,
line: usize,
body: String,
}
fn examples() -> Vec<Example> {
let mut result = Vec::new();
let mut previous = "";
let mut section = 0;
let mut active = None::<Example>;
let mut fenced = false;
let mut component_rust = false;
for (index, line) in EXAMPLES.lines().enumerate() {
if line == "```" {
result.extend(active.take());
fenced = false;
} else if fenced {
if let Some(example) = &mut active {
example.body.push_str(line);
example.body.push('\n');
}
} else if line.starts_with("```") {
if line == "```rust" && section == 46 {
component_rust = true;
}
if line == "```blade"
&& (previous.ends_with("oxblade:")
|| component_rust
|| previous.starts_with("Identical, as is the component"))
{
active = Some(Example {
section,
line: index + 2,
body: String::new(),
});
component_rust = false;
}
fenced = true;
} else if line.starts_with("### ") {
section += 1;
}
if !line.trim().is_empty() {
previous = line;
}
}
result
}
fn dependency(section: usize, index: usize) -> Option<(&'static str, bool)> {
Some(match (section, index) {
(39, 0) => ("demo-button", true),
(40, 0) => ("demo-card", true),
(41, 0) => ("demo-menu", true),
(41, 1) => ("demo-menu-item", true),
(42, 0) => ("demo-tabs", true),
(42, 1) => ("demo-tabs.tab", true),
(43, 0) => ("demo-badge", true),
(44, 0) => ("demo-input", true),
(45, 0) => ("demo-alert", true),
(46, 1) => ("alert", true),
(49, 1) => ("demo-script", true),
(50, 0) => ("demo-page", false),
_ => return None,
})
}
#[derive(Default)]
struct Corpus {
views: Map<Template>,
components: Map<Template>,
class_props: Option<TypeDesc>,
}
impl Resolver for Corpus {
fn include(&self, name: &str) -> Option<&Template> {
self.views.get(name)
}
fn component(&self, name: &str) -> Option<ComponentDefinition<'_>> {
let name = name.strip_prefix("components.").unwrap_or(name);
let slots = if name == "demo-alert" {
BTreeMap::from([("title".into(), false)])
} else {
BTreeMap::new()
};
Some(ComponentDefinition {
slots,
helpers: if name == "alert" {
BTreeMap::from([("is_error".into(), Signature::new(vec![], TypeDesc::Bool))])
} else {
BTreeMap::new()
},
template: Some(self.components.get(name)?),
props: (name == "alert")
.then(|| self.class_props.clone())
.flatten(),
..Default::default()
})
}
}
fn parse_source(
sources: &mut SourceMap,
name: &str,
body: &str,
directives: &DirectiveTable,
) -> Template {
let id = sources.add(name, body).unwrap();
let parsed = parse(id, body, directives);
assert!(parsed.errors.is_empty(), "{name}: {:?}", parsed.errors);
parsed.template
}
#[test]
fn every_documented_oxblade_template_type_checks() {
let examples = examples();
assert_eq!(examples.len(), 75);
let mut directives = DirectiveTable::new();
directives.register_directive("money", true);
directives.register_condition("weekend");
let mut sources = SourceMap::new();
let mut registry = TypeRegistry::default();
let mut corpus = Corpus {
class_props: Some(Alert::deserialize_shape(&mut registry)),
..Default::default()
};
let mut roots = Vec::new();
let mut indices = BTreeMap::<_, usize>::new();
for example in examples {
let index = indices.entry(example.section).or_default();
let name = format!("design/EXAMPLES.md (line {})", example.line);
let template = parse_source(&mut sources, &name, &example.body, &directives);
if let Some((name, component)) = dependency(example.section, *index) {
if component {
corpus.components.insert(name.into(), template);
} else {
corpus.views.insert(name.into(), template);
}
} else {
roots.push((
example.section,
template,
model(example.section, &mut registry),
));
}
*index += 1;
}
assert_eq!(roots.len(), 63);
for (name, body) in [
(
"demo-layout",
include_str!(
"../../../conformance/cases/examples/i01-template-inheritance/views/demo-layout.blade.html"
),
),
(
"demo-row",
include_str!(
"../../../conformance/cases/examples/i02-includes-in-every-form/views/demo-row.blade.html"
),
),
(
"demo-item",
include_str!(
"../../../conformance/cases/examples/i02-includes-in-every-form/views/demo-item.blade.html"
),
),
(
"demo-empty",
include_str!(
"../../../conformance/cases/examples/i02-includes-in-every-form/views/demo-empty.blade.html"
),
),
] {
corpus.views.insert(
name.into(),
parse_source(&mut sources, name, body, &directives),
);
}
let item = PagedCity::serialize_shape(&mut registry);
let mut checker = Checker::new(®istry, &sources, &corpus);
checker
.paginators
.insert(std::any::type_name::<CitiesPage>().into(), item);
checker.conditions.insert(
"weekend".into(),
Signature::new(vec![TypeDesc::String], TypeDesc::Bool),
);
checker.routes.insert(
"places.show".into(),
vec![Placeholder {
name: "city".into(),
ty: TypeDesc::String,
optional: false,
model_key: Some("slug".into()),
}],
);
let mut failures = Vec::new();
for (section, template, model) in roots {
let scope: Scope = checker.scope(model);
let report = checker.check(&template, &scope);
if section == 63 {
assert_eq!(
report
.diagnostics
.iter()
.filter(|d| d.kind == DiagnosticKind::Error)
.map(|d| d.code)
.collect::<Vec<_>>(),
vec!["migration-todo"; 3]
);
} else if !report.is_clean() {
failures.push(report.render(&sources));
}
}
assert!(failures.is_empty(), "{}", failures.join("\n"));
}