Repository navigation
Expand file tree
/
Copy pathlower.rs
More file actions
794 lines (780 loc) · 34.1 KB
/
Copy pathlower.rs
File metadata and controls
794 lines (780 loc) · 34.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
//! Checked browser IR, with the same expression tree used by reference evaluation.
mod asynchronous;
pub(in crate::project) mod controls;
mod forms;
mod interactions;
mod reach;
use crate::checker::expression_type;
use crate::error::{Error, Location, Result};
use crate::hir::CheckedProgram;
use crate::syntax::{self, Expr, ExprKind, HtmlAttribute, HtmlNode, Statement};
use crate::value::Type;
use serde::Serialize;
use std::collections::{BTreeMap, BTreeSet};
#[derive(Clone, Debug, Serialize)]
pub(super) struct Expression {
pub ty: Type,
pub ast: Expr,
}
#[derive(Clone, Debug, Serialize)]
pub(super) enum EventValue {
Async {
expression: Expression,
remotes: BTreeMap<String, EventValue>,
},
Pure(Expression),
Remote {
operation: String,
arguments: Vec<Expression>,
types: Vec<Type>,
result: Type,
},
}
#[derive(Clone, Debug, Serialize)]
pub(super) struct Event {
pub parameters: Vec<(String, Type)>,
pub body: Vec<EventStep>,
pub location: Location,
}
#[derive(Clone, Debug, Serialize)]
pub(super) enum EventStep {
Assign(String, EventValue),
Emit(String, Vec<Expression>),
}
#[derive(Clone, Debug, Serialize)]
pub(super) struct Handler {
pub name: String,
pub arguments: Vec<Expression>,
}
#[derive(Clone, Debug, Serialize)]
pub(super) struct Function {
pub parameters: Vec<(String, Type)>,
pub result: Type,
pub body: Vec<Statement>,
pub location: Location,
}
#[derive(Clone, Debug, Serialize)]
pub(super) enum Node {
Field(controls::Control),
Submit(Expression),
Status(Expression),
Text(String),
Value(Expression),
Element {
tag: String,
attributes: Vec<(String, Attribute)>,
children: Vec<Self>,
},
When(Expression, Vec<Self>),
Each {
items: Expression,
binding: String,
key: Expression,
children: Vec<Self>,
},
Use {
component: String,
properties: Vec<(String, Expression)>,
outputs: BTreeMap<String, String>,
},
Route(String, Vec<Self>),
NamedRoute {
route: String,
binding: String,
children: Vec<Self>,
},
Watch {
stream: Expression,
into: String,
cursor: String,
payload: Type,
},
}
#[derive(Clone, Debug, Serialize)]
pub(super) enum Attribute {
Text(String),
Value(Expression),
Event(Handler),
Route(Expression),
Form { schema: String, binding: String },
Field(String),
Binding(String),
Checked(String),
}
#[derive(Clone, Debug, Serialize)]
pub(super) struct Component {
pub location: Location,
pub properties: Vec<(String, Type)>,
pub state: Vec<(String, Expression)>,
pub derived: Vec<(String, Expression)>,
pub events: BTreeMap<String, Event>,
pub outputs: BTreeMap<String, Vec<(String, Type)>>,
pub template: Vec<Node>,
}
#[derive(Clone, Debug, Serialize)]
pub(super) struct BrowserProgram {
pub actions: BTreeMap<String, Recovery>,
pub component: String,
pub components: BTreeMap<String, Component>,
pub functions: BTreeMap<String, Function>,
pub records: BTreeMap<String, BTreeMap<String, Type>>,
pub enums: BTreeMap<String, BTreeMap<String, Vec<Type>>>,
pub defaults: BTreeMap<String, BTreeMap<String, serde_json::Value>>,
pub wire_names: BTreeMap<String, String>,
pub aliases: BTreeMap<String, Type>,
pub routes: BTreeSet<String>,
pub schemas: super::schemas::Schemas,
}
#[derive(Clone, Debug, Serialize)]
pub(super) struct Recovery {
pub result: Type,
pub label: String,
}
struct Lower<'a> {
accounts: bool,
oauth: bool,
files: BTreeSet<String>,
channels: BTreeMap<String, Type>,
program: &'a CheckedProgram,
signatures: BTreeMap<String, Vec<(String, Type)>>,
routes: BTreeSet<String>,
schemas: &'a super::schemas::Schemas,
output_signatures: BTreeMap<String, BTreeMap<String, Vec<(String, Type)>>>,
}
#[derive(Debug)]
pub(super) struct Interfaces<'a> {
pub actions: &'a BTreeMap<String, super::actions::Binding>,
pub rpc: &'a BTreeMap<String, super::rpc::Operation>,
pub identity: Option<&'a super::accounts::Config>,
pub files: Option<&'a super::files::Config>,
pub channels: BTreeMap<String, Type>,
pub schemas: &'a super::schemas::Schemas,
}
pub(super) fn lower(
program: &CheckedProgram,
root: &str,
components: &[syntax::Component],
interfaces: Interfaces<'_>,
) -> Result<BrowserProgram> {
let Interfaces {
actions,
rpc,
identity,
files,
channels,
schemas,
} = interfaces;
let mut lower = Lower {
accounts: identity.is_some(),
oauth: identity.is_some_and(|config| config.oauth.is_some()),
channels,
files: files
.map(|c| c.bindings.keys().cloned().collect())
.unwrap_or_default(),
program,
signatures: BTreeMap::new(),
routes: BTreeSet::from(["/".into()]),
schemas,
output_signatures: interactions::output_signatures(program, components)?,
};
lower.signatures = property_signatures(program, components)?;
lower.check_root(root)?;
let mut checked = BTreeMap::new();
for c in components {
checked.insert(c.name.clone(), lower.component(c, rpc)?);
}
interactions::root_identity(root, &checked)?;
retain_components(root, &mut checked)?;
lower.routes = BTreeSet::from(["/".into()]);
for component in checked.values() {
collect_routes(&component.template, &mut lower.routes);
}
schemas.check_literals(&lower.routes)?;
let used = reach::used(program, &checked);
let functions = reachable_functions(program, &used.functions)?;
Ok(BrowserProgram {
actions: recovery_actions(&used.actions, actions, rpc),
component: root.into(),
components: checked,
functions,
records: program
.records
.iter()
.filter(|(n, _)| used.records.contains(*n))
.map(|(n, r)| {
(
n.clone(),
r.fields
.iter()
.map(|(n, f)| (n.clone(), f.ty.clone()))
.collect(),
)
})
.collect(),
enums: program
.enums
.iter()
.filter(|(n, _)| used.enums.contains(*n))
.map(|(n, e)| {
(
n.clone(),
e.variants
.iter()
.map(|(n, f)| (n.clone(), f.iter().map(|(_, ty)| ty.clone()).collect()))
.collect(),
)
})
.collect(),
defaults: program
.records
.iter()
.filter(|(n, _)| used.records.contains(*n))
.map(|(n, r)| {
Ok((
n.clone(),
r.fields
.iter()
.filter_map(|(n, f)| f.default.as_ref().map(|v| (n, v)))
.map(|(n, v)| Ok((n.clone(), super::wire::encode(v)?)))
.collect::<Result<_>>()?,
))
})
.collect::<Result<_>>()?,
wire_names: program
.enums
.iter()
.filter(|(n, _)| used.enums.contains(*n))
.flat_map(|(_, e)| e.variants.keys())
.map(|n| (n.clone(), super::resolve::public_name(n).into()))
.collect(),
aliases: program
.aliases
.iter()
.filter(|(n, _)| used.aliases.contains(*n))
.map(|(n, t)| (n.clone(), t.clone()))
.collect(),
routes: lower.routes,
schemas: schemas.clone(),
})
}
fn recovery_actions(
names: &BTreeSet<String>,
actions: &BTreeMap<String, super::actions::Binding>,
rpc: &BTreeMap<String, super::rpc::Operation>,
) -> BTreeMap<String, Recovery> {
names
.iter()
.filter_map(|name| {
actions
.get(name)
.filter(|binding| binding.durable())
.map(|binding| {
(
name.clone(),
Recovery {
result: rpc[name].client_result.clone(),
label: binding
.label
.clone()
.unwrap_or_else(|| name.replace('_', " ")),
},
)
})
})
.collect()
}
fn retain_components(root: &str, components: &mut BTreeMap<String, Component>) -> Result<()> {
let mut used = BTreeSet::new();
visit(root, components, &mut BTreeSet::new(), &mut used)?;
components.retain(|name, _| used.contains(name));
Ok(())
}
impl Lower<'_> {
fn check_root(&self, root: &str) -> Result<()> {
if !self.signatures.get(root).is_some_and(Vec::is_empty) {
return Err(error(
Location::default(),
"root component must exist and take no properties",
));
}
if !self.output_signatures[root].is_empty() {
return Err(error(
Location::default(),
"root component cannot declare unbound outputs",
));
}
Ok(())
}
fn expression(&self, value: &Expr, locals: &BTreeMap<String, Type>) -> Result<Expression> {
let ty = expression_type(self.program, locals.clone(), value)?;
if !crate::security::type_security(&ty, self.program).browser_managed {
return Err(error(
value.location,
"browser expression is not a managed browser value",
));
}
Ok(Expression {
ty,
ast: value.clone(),
})
}
fn component(
&mut self,
c: &syntax::Component,
rpc: &BTreeMap<String, super::rpc::Operation>,
) -> Result<Component> {
let properties = self.signatures[&c.name].clone();
let mut locals: BTreeMap<_, _> = properties.iter().cloned().collect();
let mut state = Vec::new();
for (n, t, e) in &c.states {
let ty = crate::checker::resolve_type(t, self.program, e.location)?;
if !crate::security::type_security(&ty, self.program).browser_managed {
return Err(error(
e.location,
"declared state type is not a finite managed browser value",
));
}
let value = self.expression(e, &locals)?;
if !ty.accepts(&value.ty) {
return Err(error(e.location, "state initializer type mismatch"));
}
state.push((
n.clone(),
Expression {
ty: ty.clone(),
ast: value.ast,
},
));
locals.insert(n.clone(), ty);
}
locals.extend([
("pending".into(), Type::Bool),
("error".into(), Type::Text),
("route".into(), Type::Text),
]);
let mut derived = Vec::new();
for (n, t, e) in &c.derived {
let ty = crate::checker::resolve_type(t, self.program, e.location)?;
if !crate::security::type_security(&ty, self.program).browser_managed {
return Err(error(
e.location,
"declared derived type is not a finite managed browser value",
));
}
let value = self.expression(e, &locals)?;
if !ty.accepts(&value.ty) {
return Err(error(e.location, "derived value type mismatch"));
}
locals.insert(n.clone(), ty.clone());
derived.push((n.clone(), Expression { ty, ast: value.ast }));
}
let events = self.events(c, &state, &locals, rpc)?;
let mutable = state
.iter()
.map(|(n, e)| (n.clone(), e.ty.clone()))
.collect();
let template = self.nodes(&c.template, &locals, &events, &mutable)?;
controls::bound(&template)?;
Ok(Component {
location: c.location,
properties,
state,
derived,
events,
outputs: self.output_signatures[&c.name].clone(),
template,
})
}
fn event(
&self,
e: &Expr,
locals: &BTreeMap<String, Type>,
rpc: &BTreeMap<String, super::rpc::Operation>,
) -> Result<EventValue> {
asynchronous::lower(self, e, locals, rpc)
}
fn remote(
&self,
e: &Expr,
locals: &BTreeMap<String, Type>,
rpc: &BTreeMap<String, super::rpc::Operation>,
) -> Result<EventValue> {
if let ExprKind::Call {
callee,
arguments,
types,
} = &e.kind
&& let ExprKind::Field(base, name) = &callee.kind
&& let ExprKind::Name(namespace) = &base.kind
&& ["rpc", "action", "session", "files"].contains(&namespace.as_str())
{
let (parameters, result, operation) = if namespace == "rpc" || namespace == "action" {
let op = rpc
.get(name)
.ok_or_else(|| error(e.location, "RPC is not declared in the manifest"))?;
if op.action != (namespace == "action") {
return Err(error(
e.location,
"actions cannot use ordinary RPC dispatch",
));
}
let result = op.client_result.clone();
(op.arguments.clone(), result, format!("{namespace}/{name}"))
} else if namespace == "files" {
let (parameters, result) = self.file_signature(name, arguments, e.location)?;
(parameters, result, format!("files/{name}"))
} else {
let params = match name.as_str() {
"login" => vec![Type::Text, Type::Text],
"oauth_login" if self.oauth => vec![Type::Text, Type::Text],
"logout" | "user" => vec![],
_ if self.accounts => super::accounts::signature(name)
.ok_or_else(|| error(e.location, "unknown account operation"))?,
_ => {
return Err(error(
e.location,
"unknown session operation or missing accounts-v1 profile",
));
}
};
(params, Type::Text, format!("session/{name}"))
};
if !types.is_empty()
|| arguments.len() != parameters.len()
|| arguments.iter().any(|(n, _)| n.is_some())
{
return Err(error(
e.location,
"remote arguments must match the declared positional signature",
));
}
let mut values = Vec::new();
for ((_, e), ty) in arguments.iter().zip(¶meters) {
let value = self.expression(e, locals)?;
if !(ty.accepts(&value.ty)
|| matches!(ty, Type::BoundedText(..)) && value.ty == Type::Text)
{
return Err(error(e.location, "remote argument type mismatch"));
}
values.push(value);
}
Ok(EventValue::Remote {
operation,
arguments: values,
types: parameters,
result,
})
} else {
Ok(EventValue::Pure(self.expression(e, locals)?))
}
}
fn file_signature(
&self,
name: &str,
arguments: &[(Option<String>, Expr)],
location: Location,
) -> Result<(Vec<Type>, Type)> {
let Some((
None,
Expr {
kind: ExprKind::Text(binding),
..
},
)) = arguments.first()
else {
return Err(error(
location,
"file binding must be a static declared name",
));
};
if !self.files.contains(binding)
|| !["upload", "status", "delete", "download"].contains(&name)
{
return Err(error(location, "unknown file binding or operation"));
}
if name == "upload"
&& !matches!(
arguments.get(2),
Some((
None,
Expr {
kind: ExprKind::Text(_),
..
}
))
)
{
return Err(error(location, "file input id must be static"));
}
let blob = Type::Blob(binding.clone());
Ok(match name {
"upload" => (vec![Type::Text, Type::Text, Type::Text], blob),
"status" => (vec![Type::Text, blob], Type::Text),
"download" => (vec![Type::Text, blob.clone()], blob),
"delete" => (vec![Type::Text, blob.clone()], Type::Option(Box::new(blob))),
_ => return Err(error(location, "unknown file operation")),
})
}
fn nodes(
&mut self,
nodes: &[HtmlNode],
locals: &BTreeMap<String, Type>,
events: &BTreeMap<String, Event>,
mutable: &BTreeMap<String, Type>,
) -> Result<Vec<Node>> {
nodes.iter().map(|node|match node {
HtmlNode::Text(s)=>Ok(Node::Text(s.clone())),
HtmlNode::Expression(e)=>{let v=self.expression(e,locals)?;if !matches!(v.ty,Type::Int|Type::Bool|Type::Text|Type::BoundedText(..)|Type::Id(_)) {return Err(error(e.location,"render compound values through explicit fields, match, each or formatting utilities"));}Ok(Node::Value(v))},
HtmlNode::Element{tag,attributes,children}=>{
let attrs:BTreeMap<_,_>=attributes.iter().map(|(n,v)|(n.as_str(),v)).collect();
if tag != "form" && attrs.contains_key("schema") {return Err(error(Location::default(),"schema belongs to a typed form"));}
let literal=|n:&str|match attrs.get(n) {Some(HtmlAttribute::Literal(s))=>Ok(s.clone()),_=>Err(error(Location::default(),"directive requires a static name/path"))};
let expr=|n:&str|match attrs.get(n) {Some(HtmlAttribute::Expression(e))=>Ok((*e).clone()),_=>Err(error(Location::default(),"directive requires an expression"))};
match tag.as_str() {
"field"=>{
if !children.iter().all(|n|matches!(n,HtmlNode::Text(s) if s.trim().is_empty())) {return Err(error(Location::default(),"field has no author-supplied children"));}
return Ok(Node::Field(self.control(&attrs,locals,mutable)?));
},
"submit"=>{
if attrs.len()!=1 || !children.iter().all(|n|matches!(n,HtmlNode::Text(s) if s.trim().is_empty())) {return Err(error(Location::default(),"submit requires only a nonempty label"));}
return Ok(Node::Submit(self.accessible_text(attrs.get("label").copied(),locals,true)?));
},
"status"=>{
if attrs.len()!=1 || !children.iter().all(|n|matches!(n,HtmlNode::Text(s) if s.trim().is_empty())) {return Err(error(Location::default(),"status requires only a Text value"));}
return Ok(Node::Status(self.accessible_text(attrs.get("value").copied(),locals,false)?));
},
"watch"=>{
if attrs.len()!=3 || !children.iter().all(|n|matches!(n,HtmlNode::Text(t) if t.trim().is_empty())) {return Err(error(Location::default(),"watch requires stream, into, cursor and no content"));}
let into=literal("into")?;let cursor=literal("cursor")?;let stream=self.expression(&expr("stream")?,locals)?;
let Type::Stream(channel)=&stream.ty else {return Err(error(stream.ast.location,"watch requires a typed Stream"));};
let payload=self.channels.get(channel).ok_or_else(||error(Location::default(),"unknown event channel"))?.clone();
if !mutable.contains_key(&into) || locals.get(&into)!=Some(&payload) || !mutable.contains_key(&cursor) || locals.get(&cursor)!=Some(&Type::Text) || into==cursor {return Err(error(Location::default(),"watch targets must be distinct mutable payload and Text cursor states"));}
return Ok(Node::Watch{stream,into,cursor,payload});
},
"when"=>{if attrs.len()!=1 {return Err(error(Location::default(),"when requires only test"));}let v=self.expression(&expr("test")?,locals)?;if v.ty!=Type::Bool {return Err(error(v.ast.location,"when test must be Bool"));}return Ok(Node::When(v,self.nodes(children,locals,events,mutable)?));},
"each"=>{if attrs.len()!=3 {return Err(error(Location::default(),"each requires items, as and key"));}let items=self.expression(&expr("items")?,locals)?;let Type::List(inner)=&items.ty else {return Err(error(items.ast.location,"each requires a List"));};let binding=literal("as")?;if !super::resolve::identifier(&binding) || locals.contains_key(&binding) {return Err(error(items.ast.location,"each binding must be a fresh local name"));}let mut nested=locals.clone();nested.insert(binding.clone(),(**inner).clone());let key=self.expression(&expr("key")?,&nested)?;if !matches!(key.ty,Type::Int|Type::Text|Type::BoundedText(..)|Type::Id(_)) {return Err(error(key.ast.location,"key requires Int, Text or Id"));}return Ok(Node::Each{items,binding,key,children:self.nodes(children,&nested,events,mutable)?});},
"route"=>{
if attrs.contains_key("name") {
if attrs.len()!=2 { return Err(error(Location::default(),"named route outlet requires name and as")); }
let route=literal("name")?;let binding=literal("as")?;
if !self.schemas.routes.contains_key(&route) || !super::resolve::identifier(&binding) || locals.contains_key(&binding) { return Err(error(Location::default(),"named route requires a visible schema and fresh binding")); }
let mut nested=locals.clone();nested.insert(binding.clone(),Type::Record(route.clone()));
return Ok(Node::NamedRoute{route,binding,children:self.nodes(children,&nested,events,mutable)?});
}
if attrs.len()!=1 {return Err(error(Location::default(),"route requires only path"));}let path=literal("path")?;crate::template::validate_internal_url(&path,Location::default())?;if path.contains(['?','#']) || path.starts_with("/_diamond") || path.starts_with("/assets/") {return Err(error(Location::default(),"route path is reserved or not canonical"));}self.routes.insert(path.clone());return Ok(Node::Route(path,self.nodes(children,locals,events,mutable)?));
},
"use"=>{if !children.iter().all(|n|matches!(n,HtmlNode::Text(s) if s.trim().is_empty())) {return Err(error(Location::default(),"use takes properties and output bindings only"));}return self.component_use(&literal("component")?,&attrs,locals,events);},
"html"|"head"|"body"|"title"=>return Err(error(Location::default(),"components render inside the document body")),_=>{}
}
let mut checked=Vec::new();
if tag=="img" && !attrs.contains_key("alt") {return Err(error(Location::default(),"images require an author-supplied alt description; empty alt explicitly marks decoration"));}
let mut handler_locals=locals.clone();
let form = if tag=="form" && attrs.contains_key("schema") {
let schema=literal("schema")?;let binding=literal("as")?;
if !self.schemas.forms.contains_key(&schema) || !super::resolve::identifier(&binding) || locals.contains_key(&binding) {return Err(error(Location::default(),"schema form requires a visible schema and fresh binding"));}
handler_locals.insert(binding.clone(),Type::Record(schema.clone()));
checked.push(("schema".into(),Attribute::Form{schema: schema.clone(),binding}));
if attrs.contains_key("method") || attrs.contains_key("action") {return Err(error(Location::default(),"schema form transport is owned by the runtime"));}
checked.push(("method".into(),Attribute::Text("post".into())));
Some(schema)
} else {None};
for (name,value) in attributes {
if form.is_some() && ["schema","as"].contains(&name.as_str()) {continue;}
let attr=match (name.as_str(),value) {
("on-click"|"on-submit",HtmlAttribute::Expression(expression)) if ((name=="on-click" && tag=="button") || (name=="on-submit" && tag=="form"))=>Attribute::Event(self.handler(expression,&handler_locals,events)?),
("on-click"|"on-submit",_)=>return Err(error(Location::default(),"event requires a declared handler on a button/form")),
("bind-value",HtmlAttribute::Expression(Expr{kind:ExprKind::Name(n),..})) if ["input","textarea","select"].contains(&tag.as_str()) && mutable.get(n)==Some(&Type::Text)=>Attribute::Binding(n.clone()),
("bind-checked",HtmlAttribute::Expression(Expr{kind:ExprKind::Name(n),..})) if tag=="input" && mutable.get(n)==Some(&Type::Bool)=>Attribute::Checked(n.clone()),
("bind-value"|"bind-checked",_)=>return Err(error(Location::default(),"binding requires compatible mutable state")),
("id",HtmlAttribute::Literal(s)) if ["diamond-app","diamond-error"].contains(&s.as_str())=>return Err(error(Location::default(),"component id is reserved by the runtime")),
(_,HtmlAttribute::Literal(s))=>Attribute::Text(s.clone()),
("href",HtmlAttribute::Expression(e))=>{
let value=self.expression(e,locals)?;
if !matches!(&value.ty,Type::Record(name) if self.schemas.routes.contains_key(name)) {return Err(error(e.location,"dynamic href requires a declared typed route value"));}
Attribute::Route(value)
},
("action"|"src",_)=>return Err(error(Location::default(),"URL attributes require static validated references")),
(_,HtmlAttribute::Expression(e))=>{
let value=self.expression(e,locals)?;
if tag=="option" && name=="value" && !matches!(value.ty,Type::Int|Type::Text|Type::BoundedText(..)|Type::Id(_)) {return Err(error(e.location,"option values require Int, Text or Id"));}
Attribute::Value(value)
},
};checked.push((name.clone(),attr));
}
let file_input = tag=="input" && checked.iter().any(|(n,v)| n=="type" && matches!(v,Attribute::Text(s) if s=="file"));
if file_input && (self.files.is_empty() || !checked.iter().any(|(n,v)|n=="id" && matches!(v,Attribute::Text(s) if super::resolve::identifier(s))) || checked.iter().any(|(n,_)| ["bind-value","bind-checked","value","multiple"].contains(&n.as_str()))) { return Err(error(Location::default(),"file inputs require a static id and a file profile, without bindings or multiple selection")); }
if tag=="input" && !file_input && (!checked.iter().any(|(n,_)|["bind-value","bind-checked"].contains(&n.as_str())) || checked.iter().any(|(n,v)| n=="value" || n=="type" && !matches!(v,Attribute::Text(s) if ["text","password","checkbox"].contains(&s.as_str())))) {return Err(error(Location::default(),"inputs require a binding and a static text/password/checkbox type"));}
if tag=="input" && !file_input {
let checkbox=checked.iter().any(|(n,v)|n=="type" && matches!(v,Attribute::Text(s) if s=="checkbox"));
let binding=checked.iter().any(|(_,v)|matches!(v,Attribute::Checked(_)));
if checkbox!=binding {return Err(error(Location::default(),"checkbox inputs require bind-checked; text/password inputs require bind-value"));}
}
if tag=="select" {
if !checked.iter().any(|(_,v)|matches!(v,Attribute::Binding(_))) {return Err(error(Location::default(),"select requires bind-value"));}
let mut values=BTreeSet::new();
validate_select_children(children,&mut values)?;
}
if tag=="form" && !checked.iter().any(|(n,_)|n=="on-submit") {return Err(error(Location::default(),"component forms require on-submit"));}
let mut children=self.nodes(children,locals,events,mutable)?;
if let Some(schema)=form { forms::controls(&mut children,&self.schemas.forms[&schema])?; }
Ok(Node::Element{tag:tag.clone(),attributes:checked,children})
}
}).collect()
}
}
fn error(location: Location, message: &str) -> Error {
Error::diagnostic("D330", location, message)
}
fn validate_select_children(
nodes: &[HtmlNode],
static_values: &mut BTreeSet<String>,
) -> Result<()> {
for node in nodes {
match node {
HtmlNode::Text(text) if text.trim().is_empty() => {}
HtmlNode::Element {
tag,
attributes,
children,
} if tag == "option" => {
let values = attributes
.iter()
.filter(|(name, _)| name == "value")
.collect::<Vec<_>>();
if values.len() != 1 {
return Err(error(
Location::default(),
"select options require exactly one value attribute",
));
}
if let HtmlAttribute::Literal(value) = &values[0].1
&& !static_values.insert(value.clone())
{
return Err(error(Location::default(), "duplicate select option value"));
}
if children
.iter()
.any(|child| !matches!(child, HtmlNode::Text(_) | HtmlNode::Expression(_)))
{
return Err(error(
Location::default(),
"option labels support text and scalar expressions only",
));
}
}
HtmlNode::Element { tag, children, .. } if ["each", "when"].contains(&tag.as_str()) => {
validate_select_children(children, static_values)?;
}
_ => {
return Err(error(
Location::default(),
"select supports option children, including options inside each or when",
));
}
}
}
Ok(())
}
fn collect_routes(nodes: &[Node], routes: &mut BTreeSet<String>) {
for node in nodes {
match node {
Node::Route(path, children) => {
routes.insert(path.clone());
collect_routes(children, routes);
}
Node::When(_, children)
| Node::NamedRoute { children, .. }
| Node::Each { children, .. }
| Node::Element { children, .. } => collect_routes(children, routes),
_ => {}
}
}
}
fn visit(
name: &str,
all: &BTreeMap<String, Component>,
active: &mut BTreeSet<String>,
done: &mut BTreeSet<String>,
) -> Result<()> {
if done.contains(name) {
return Ok(());
}
if !active.insert(name.into()) {
return Err(error(Location::default(), "component cycle"));
}
let mut names = BTreeSet::new();
dependencies(&all[name].template, &mut names);
for child in names {
visit(&child, all, active, done)?;
}
active.remove(name);
done.insert(name.into());
Ok(())
}
fn dependencies(nodes: &[Node], names: &mut BTreeSet<String>) {
for node in nodes {
match node {
Node::Use { component, .. } => {
names.insert(component.clone());
}
Node::Element { children, .. }
| Node::When(_, children)
| Node::Each { children, .. }
| Node::Route(_, children)
| Node::NamedRoute { children, .. } => dependencies(children, names),
_ => {}
}
}
}
fn property_signatures(
program: &CheckedProgram,
components: &[syntax::Component],
) -> Result<BTreeMap<String, Vec<(String, Type)>>> {
let mut signatures = BTreeMap::new();
for c in components {
let props = c
.properties
.iter()
.map(|(n, t)| {
let ty = crate::checker::resolve_type(t, program, c.location)?;
if !crate::security::type_security(&ty, program).browser_managed {
return Err(error(
c.location,
"component properties require finite managed browser types",
));
}
Ok((n.clone(), ty))
})
.collect::<Result<Vec<_>>>()?;
signatures.insert(c.name.clone(), props);
}
Ok(signatures)
}
fn reachable_functions(
program: &CheckedProgram,
names: &BTreeSet<String>,
) -> Result<BTreeMap<String, Function>> {
let functions = program
.functions
.iter()
.filter(|(n, _)| names.contains(*n))
.map(|(name, f)| {
if !f.effects.is_empty() {
return Err(error(
f.location,
"browser functions cannot carry host authority",
));
}
Ok((
name.clone(),
Function {
parameters: f.parameters.clone(),
result: f.result.clone(),
body: f.body.clone(),
location: f.location,
},
))
})
.collect::<Result<_>>()?;
Ok(functions)
}