1use std::fmt;
6
7use super::expr::Expr;
8use super::stmt::{write_body, Stmt};
9use super::types::{Declarator, TypeExpr};
10use super::{joined, write_comment, INDENT};
11
12#[derive(Debug, Clone, PartialEq)]
14pub struct DeclId {
15 pub decl: Declarator,
17 pub init: Option<Initializer>,
19}
20
21impl DeclId {
22 pub fn scalar(name: impl Into<String>) -> Self {
24 DeclId {
25 decl: Declarator::scalar(name),
26 init: None,
27 }
28 }
29
30 pub fn initialised(name: impl Into<String>, value: Expr) -> Self {
32 DeclId {
33 decl: Declarator::scalar(name),
34 init: Some(Initializer::Expr(value)),
35 }
36 }
37}
38
39impl fmt::Display for DeclId {
40 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41 write!(f, "{}", self.decl)?;
42 match &self.init {
43 Some(init) => write!(f, " = {init}"),
44 None => Ok(()),
45 }
46 }
47}
48
49#[derive(Debug, Clone, PartialEq)]
51pub enum Initializer {
52 Expr(Expr),
54 List(Vec<FieldInit>),
56}
57
58impl fmt::Display for Initializer {
59 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60 match self {
61 Initializer::Expr(e) => write!(f, "{e}"),
62 Initializer::List(items) => {
63 f.write_str("{ ")?;
64 joined(f, items, ", ")?;
65 f.write_str(" }")
66 }
67 }
68 }
69}
70
71#[derive(Debug, Clone, PartialEq)]
74pub struct FieldInit {
75 pub name: Option<String>,
77 pub value: Initializer,
79}
80
81impl fmt::Display for FieldInit {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 match &self.name {
84 Some(name) => write!(f, "{name}: {}", self.value),
85 None => write!(f, "{}", self.value),
86 }
87 }
88}
89
90#[derive(Debug, Clone, PartialEq)]
93pub struct VarDecl {
94 pub ty: TypeExpr,
96 pub ids: Vec<DeclId>,
98}
99
100impl VarDecl {
101 pub fn single(ty: TypeExpr, name: impl Into<String>, init: Option<Expr>) -> Self {
103 let decl = Declarator::scalar(name);
104 VarDecl {
105 ty,
106 ids: vec![DeclId {
107 decl,
108 init: init.map(Initializer::Expr),
109 }],
110 }
111 }
112}
113
114impl fmt::Display for VarDecl {
115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116 write!(f, "{} ", self.ty)?;
117 joined(f, &self.ids, ", ")?;
118 f.write_str(";")
119 }
120}
121
122#[derive(Debug, Clone, PartialEq)]
124pub struct TypeDef {
125 pub ty: TypeExpr,
127 pub ids: Vec<Declarator>,
129}
130
131impl fmt::Display for TypeDef {
132 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133 write!(f, "typedef {} ", self.ty)?;
134 joined(f, &self.ids, ", ")?;
135 f.write_str(";")
136 }
137}
138
139#[derive(Debug, Clone, PartialEq)]
141pub struct Param {
142 pub ty: TypeExpr,
144 pub by_ref: bool,
146 pub decl: Declarator,
148}
149
150impl Param {
151 pub fn value(ty: TypeExpr, name: impl Into<String>) -> Self {
153 Param {
154 ty,
155 by_ref: false,
156 decl: Declarator::scalar(name),
157 }
158 }
159}
160
161impl fmt::Display for Param {
162 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163 if self.by_ref {
164 write!(f, "{} &{}", self.ty, self.decl)
165 } else {
166 write!(f, "{} {}", self.ty, self.decl)
167 }
168 }
169}
170
171#[derive(Debug, Clone, PartialEq)]
173pub struct FnDecl {
174 pub ret: TypeExpr,
176 pub name: String,
178 pub params: Vec<Param>,
180 pub body_vars: Vec<BlockLocalDecl>,
183 pub body: Vec<Stmt>,
185}
186
187impl fmt::Display for FnDecl {
188 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189 write!(f, "{} {}(", self.ret, self.name)?;
190 joined(f, &self.params, ", ")?;
191 f.write_str(") {\n")?;
192 write_body(f, &self.body_vars, &self.body, 1)?;
193 f.write_str("}")
194 }
195}
196
197#[derive(Debug, Clone, PartialEq)]
200pub struct ExternDecl {
201 pub library: String,
203 pub decls: Vec<FwdDecl>,
205}
206
207impl fmt::Display for ExternDecl {
208 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
209 writeln!(f, "import \"{}\" {{", self.library)?;
210 for decl in &self.decls {
211 writeln!(f, "{INDENT}{decl};")?;
212 }
213 f.write_str("};")
214 }
215}
216
217#[derive(Debug, Clone, PartialEq)]
219pub struct FwdDecl {
220 pub alias: Option<String>,
222 pub ret: TypeExpr,
224 pub name: String,
226 pub params: Vec<Param>,
228}
229
230impl fmt::Display for FwdDecl {
231 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232 if let Some(alias) = &self.alias {
233 write!(f, "{alias} = ")?;
234 }
235 write!(f, "{} {}(", self.ret, self.name)?;
236 joined(f, &self.params, ", ")?;
237 f.write_str(")")
238 }
239}
240
241#[derive(Debug, Clone, PartialEq)]
244pub struct Instantiation {
245 pub name: String,
247 pub params: Vec<Param>,
249 pub template: String,
251 pub args: Vec<Expr>,
253}
254
255impl fmt::Display for Instantiation {
256 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
257 write!(f, "{}", self.name)?;
258 if !self.params.is_empty() {
259 f.write_str("(")?;
260 joined(f, &self.params, ", ")?;
261 f.write_str(")")?;
262 }
263 write!(f, " = {}(", self.template)?;
264 joined(f, &self.args, ", ")?;
265 f.write_str(");")
266 }
267}
268
269#[derive(Debug, Clone, PartialEq)]
275pub struct ChanPriority {
276 pub levels: Vec<Vec<ChanElement>>,
278}
279
280impl fmt::Display for ChanPriority {
281 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282 f.write_str("chan priority ")?;
283 for (i, level) in self.levels.iter().enumerate() {
284 if i > 0 {
285 f.write_str(" < ")?;
286 }
287 joined(f, level, ", ")?;
288 }
289 f.write_str(";")
290 }
291}
292
293#[derive(Debug, Clone, PartialEq)]
298pub enum ChanElement {
299 Default,
301 Chan {
303 name: String,
305 index: Vec<Expr>,
307 },
308}
309
310impl fmt::Display for ChanElement {
311 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
312 match self {
313 ChanElement::Default => f.write_str("default"),
314 ChanElement::Chan { name, index } => {
315 f.write_str(name)?;
316 for i in index {
317 write!(f, "[{i}]")?;
318 }
319 Ok(())
320 }
321 }
322 }
323}
324
325#[derive(Debug, Clone, PartialEq)]
327pub struct DynamicDecl {
328 pub name: String,
330 pub params: Vec<Param>,
332}
333
334impl fmt::Display for DynamicDecl {
335 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
336 write!(f, "dynamic {}(", self.name)?;
337 joined(f, &self.params, ", ")?;
338 f.write_str(");")
339 }
340}
341
342#[derive(Debug, Clone, PartialEq)]
346pub enum GlobalDecl {
347 Var(VarDecl),
349 Type(TypeDef),
351 Fn(FnDecl),
353 Extern(ExternDecl),
355 BeforeUpdate(Vec<Expr>),
357 AfterUpdate(Vec<Expr>),
359 Instantiation(Instantiation),
361 ChanPriority(ChanPriority),
363 Dynamic(DynamicDecl),
365 Comment(String),
367}
368
369impl fmt::Display for GlobalDecl {
370 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
371 match self {
372 GlobalDecl::Var(d) => write!(f, "{d}"),
373 GlobalDecl::Type(d) => write!(f, "{d}"),
374 GlobalDecl::Fn(d) => write!(f, "{d}"),
375 GlobalDecl::Extern(d) => write!(f, "{d}"),
376 GlobalDecl::BeforeUpdate(es) => update_block(f, "before_update", es),
377 GlobalDecl::AfterUpdate(es) => update_block(f, "after_update", es),
378 GlobalDecl::Instantiation(d) => write!(f, "{d}"),
379 GlobalDecl::ChanPriority(d) => write!(f, "{d}"),
380 GlobalDecl::Dynamic(d) => write!(f, "{d}"),
381 GlobalDecl::Comment(text) => write_comment(f, text),
382 }
383 }
384}
385
386fn update_block(f: &mut fmt::Formatter<'_>, keyword: &str, exprs: &[Expr]) -> fmt::Result {
388 write!(f, "{keyword} {{ ")?;
389 joined(f, exprs, ", ")?;
390 f.write_str(" }")
391}
392
393#[derive(Debug, Clone, PartialEq)]
400pub enum ProcLocalDecl {
401 Var(VarDecl),
403 Type(TypeDef),
405 Fn(FnDecl),
407 Comment(String),
409}
410
411impl fmt::Display for ProcLocalDecl {
412 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
413 match self {
414 ProcLocalDecl::Var(d) => write!(f, "{d}"),
415 ProcLocalDecl::Type(d) => write!(f, "{d}"),
416 ProcLocalDecl::Fn(d) => write!(f, "{d}"),
417 ProcLocalDecl::Comment(text) => write_comment(f, text),
418 }
419 }
420}
421
422#[derive(Debug, Clone, PartialEq)]
427pub enum BlockLocalDecl {
428 Var(VarDecl),
430 Type(TypeDef),
432}
433
434impl fmt::Display for BlockLocalDecl {
435 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
436 match self {
437 BlockLocalDecl::Var(d) => write!(f, "{d}"),
438 BlockLocalDecl::Type(d) => write!(f, "{d}"),
439 }
440 }
441}
442
443#[cfg(test)]
444mod tests {
445 use crate::xta_backend::xta::*;
446
447 fn int() -> TypeExpr {
448 TypeExpr::plain(Type::Int)
449 }
450
451 #[test]
452 fn const_int_variable() {
453 let d = GlobalDecl::Var(VarDecl::single(
454 TypeExpr::constant(Type::Int),
455 "ROUNDS",
456 Some(Expr::Int(5)),
457 ));
458 assert_eq!(d.to_string(), "const int ROUNDS = 5;");
459 }
460
461 #[test]
462 fn channel_declaration() {
463 let d = GlobalDecl::Var(VarDecl::single(TypeExpr::plain(Type::Chan), "ball", None));
464 assert_eq!(d.to_string(), "chan ball;");
465 }
466
467 #[test]
468 fn several_names_share_one_type() {
469 let d = VarDecl {
470 ty: int(),
471 ids: vec![
472 DeclId {
473 decl: Declarator {
474 name: "a".into(),
475 array: vec![ArrayDim::Size(Expr::Int(4))],
476 },
477 init: None,
478 },
479 DeclId::initialised("b", Expr::Int(0)),
480 ],
481 };
482 assert_eq!(d.to_string(), "int a[4], b = 0;");
485 }
486
487 #[test]
488 fn struct_typedef_prints_its_fields() {
489 let d = TypeDef {
490 ty: TypeExpr::plain(Type::Struct(vec![Field {
491 ty: int(),
492 ids: vec![Declarator::scalar("x"), Declarator::scalar("y")],
493 }])),
494 ids: vec![Declarator::scalar("point")],
495 };
496 assert_eq!(d.to_string(), "typedef struct {\n int x, y;\n} point;");
497 }
498
499 #[test]
500 fn brace_initialiser_labels_its_fields() {
501 let init = Initializer::List(vec![
502 FieldInit {
503 name: Some("x".into()),
504 value: Initializer::Expr(Expr::Int(1)),
505 },
506 FieldInit {
507 name: None,
508 value: Initializer::Expr(Expr::Int(2)),
509 },
510 ]);
511 let d = VarDecl {
512 ty: TypeExpr::plain(Type::Named("point".into())),
513 ids: vec![DeclId {
514 decl: Declarator::scalar("p"),
515 init: Some(init),
516 }],
517 };
518 assert_eq!(d.to_string(), "point p = { x: 1, 2 };");
519 }
520
521 #[test]
522 fn function_with_assert_and_return() {
523 let d = ProcLocalDecl::Fn(FnDecl {
524 ret: int(),
525 name: "io_tally".into(),
526 params: vec![Param::value(int(), "r")],
527 body_vars: Vec::new(),
528 body: vec![
529 Stmt::Assert(Expr::binary(BinOp::Le, Expr::Int(0), Expr::ident("r"))),
530 Stmt::Return(Some(Expr::binary(
531 BinOp::Add,
532 Expr::ident("r"),
533 Expr::Int(1),
534 ))),
535 ],
536 });
537 assert_eq!(
538 d.to_string(),
539 "int io_tally(int r) {\n assert((0) <= (r));\n return (r) + (1);\n}"
540 );
541 }
542
543 #[test]
544 fn void_function_with_no_parameters() {
545 let d = FnDecl {
546 ret: TypeExpr::plain(Type::Void),
547 name: "tally".into(),
548 params: Vec::new(),
549 body_vars: Vec::new(),
550 body: vec![Stmt::Expr(Expr::assign(
551 Expr::ident("rounds"),
552 AssignOp::Assign,
553 Expr::binary(BinOp::Add, Expr::ident("rounds"), Expr::Int(1)),
554 ))],
555 };
556 assert_eq!(
557 d.to_string(),
558 "void tally() {\n rounds = (rounds) + (1);\n}"
559 );
560 }
561
562 #[test]
563 fn by_reference_parameter_and_block_locals() {
564 let d = FnDecl {
565 ret: TypeExpr::plain(Type::Void),
566 name: "swap".into(),
567 params: vec![Param {
568 ty: int(),
569 by_ref: true,
570 decl: Declarator::scalar("a"),
571 }],
572 body_vars: vec![BlockLocalDecl::Var(VarDecl::single(
573 int(),
574 "t",
575 Some(Expr::Int(0)),
576 ))],
577 body: vec![Stmt::Expr(Expr::assign(
578 Expr::ident("a"),
579 AssignOp::Assign,
580 Expr::ident("t"),
581 ))],
582 };
583 assert_eq!(
584 d.to_string(),
585 "void swap(int &a) {\n int t = 0;\n a = t;\n}"
586 );
587 }
588
589 #[test]
590 fn comments_print_as_lines() {
591 assert_eq!(
592 GlobalDecl::Comment("TODO: buffered chan `ball` not yet translated".into()).to_string(),
593 "// TODO: buffered chan `ball` not yet translated"
594 );
595 assert_eq!(
598 Stmt::Comment(" requires 0 <= r".into()).to_string(),
599 "// requires 0 <= r"
600 );
601 }
602
603 #[test]
604 fn instantiation_and_system_forms() {
605 let d = GlobalDecl::Instantiation(Instantiation {
606 name: "ping".into(),
607 params: Vec::new(),
608 template: "Ping".into(),
609 args: Vec::new(),
610 });
611 assert_eq!(d.to_string(), "ping = Ping();");
612 }
613
614 #[test]
615 fn chan_priority_levels_and_default() {
616 let d = ChanPriority {
617 levels: vec![
618 vec![
619 ChanElement::Chan {
620 name: "a".into(),
621 index: Vec::new(),
622 },
623 ChanElement::Chan {
624 name: "b".into(),
625 index: vec![Expr::Int(0)],
626 },
627 ],
628 vec![ChanElement::Default],
629 ],
630 };
631 assert_eq!(d.to_string(), "chan priority a, b[0] < default;");
632 }
633
634 #[test]
635 fn extern_block_and_dynamic() {
636 let d = ExternDecl {
637 library: "libm".into(),
638 decls: vec![FwdDecl {
639 alias: Some("root".into()),
640 ret: TypeExpr::plain(Type::Double),
641 name: "sqrt".into(),
642 params: vec![Param::value(TypeExpr::plain(Type::Double), "x")],
643 }],
644 };
645 assert_eq!(
646 d.to_string(),
647 "import \"libm\" {\n root = double sqrt(double x);\n};"
648 );
649 assert_eq!(
650 DynamicDecl {
651 name: "Train".into(),
652 params: vec![Param::value(int(), "id")],
653 }
654 .to_string(),
655 "dynamic Train(int id);"
656 );
657 }
658}