1use std::collections::{BTreeSet, HashSet};
45
46use crate::ast::ProtectionDomainDecl;
47use crate::base::{BodyVarKind, ChanId, IdVec};
48use crate::ccfg::system::{Orchestration, System};
49use crate::ccfg::Ring;
50use crate::foreign::calls::call_sites;
51use crate::foreign::contract::ContractTable;
52use crate::tast::{ProgramView, Tast, TyEnv};
53
54use super::automaton::handler;
55use super::channel::{transpile_channel, transpile_channel_template};
56use super::contract::pancake_function;
57use super::func::Func;
58use super::types::{const_decl, struct_order, struct_typedef, typedef_name, var_decl};
59use super::xta::{
60 Expr, Instantiation, Nta, ProcLocalDecl, Template, Type, TypeExpr, VarDecl, KEYWORDS,
61};
62use super::{call, irq, queue};
63
64#[must_use]
69pub fn transpile(tast: &Tast, ccfg: &System, contracts: &ContractTable) -> Nta {
70 let tenv = &tast.tenv;
71 let mut nta = Nta::default();
72 let mut ch_template = transpile_channel_template();
73 let ch_instance = "ChannelAutogen".to_owned();
74
75 for id in struct_order(tenv) {
79 nta.global_declarations.push(struct_typedef(tenv, id));
80 }
81 for c in tenv.consts.iter() {
82 nta.global_declarations.push(const_decl(&c.name, &c.value));
83 }
84 nta.global_declarations
85 .extend(queue::decls(tenv, &ccfg.rings));
86 nta.global_declarations.extend(call::value_decls(tenv));
87 nta.global_declarations.extend(call::return_decls(tenv));
88 let irqs = irq::awaited(ccfg);
89 nta.global_declarations.extend(irq::decls(&irqs));
90
91 for ch in tenv.chans.iter() {
93 transpile_channel(&mut nta, tenv, ch, &mut ch_template);
94 }
95
96 for (id, pd) in tenv.pds.iter_enumerated() {
98 let names = ProgramView::new(tast, id);
99 let template = transpile_pd(pd, names, &ccfg.programs[id], contracts, &ccfg.rings);
100 let instance = uppaal_safe_name(&pd.name);
102 nta.instances.push(Instantiation {
103 name: instance.clone(),
104 params: Vec::new(),
105 template: template.name.clone(),
106 args: Vec::new(),
107 });
108 nta.system_processes.push(instance);
109 nta.templates.push(template);
110 }
111
112 nta.system_processes.push(ch_instance);
113 nta.templates.push(ch_template);
114 if let Some(environment) = irq::environment(&irqs) {
115 nta.instances.push(Instantiation {
116 name: "environment".to_owned(),
117 params: Vec::new(),
118 template: environment.name.clone(),
119 args: Vec::new(),
120 });
121 nta.system_processes.push("environment".to_owned());
122 nta.templates.push(environment);
123 }
124
125 nta
126}
127
128fn transpile_pd(
132 pd: &ProtectionDomainDecl,
133 names: ProgramView<'_>,
134 orchestration: &Orchestration,
135 contracts: &ContractTable,
136 rings: &IdVec<ChanId, Option<Ring>>,
137) -> Template {
138 let name = template_name(names.tenv, &pd.name);
139 let mut declarations = Vec::new();
140 let func = Func::new(contracts);
141
142 let body = names.body();
145 let mut seen_vars: HashSet<&str> = HashSet::new();
146 let hoisted = body.processes.iter().flat_map(|p| {
147 p.body_vars
148 .iter()
149 .filter(|v| {
150 matches!(
151 v.kind,
152 BodyVarKind::Decl | BodyVarKind::Binder { .. } | BodyVarKind::Param
153 )
154 })
155 .map(|v| (&v.name, &v.ty))
156 });
157 let locals = names.locals().iter().map(|v| (&v.name, &v.ty));
158 for (var, ty) in locals.chain(hoisted) {
159 if seen_vars.insert(var) {
160 let decl = var_decl(names, ty, var, true);
161 declarations.push(ProcLocalDecl::Var(decl));
162 }
163 }
164
165 let mut called = BTreeSet::new();
169 for site in call_sites(names.body()) {
170 called.insert(site.callee);
171 }
172 let mut declared: Vec<_> = called
173 .into_iter()
174 .filter_map(|f| contracts.contract(f))
175 .collect();
176 declared.sort_by(|a, b| a.name.cmp(&b.name));
177 for contract in declared {
178 declarations.push(ProcLocalDecl::Fn(pancake_function(contract)));
179 }
180
181 for (id, _) in names.body().events.iter_enumerated() {
184 declarations.push(ProcLocalDecl::Fn(func.event_function(names, id)));
185 }
186
187 let buffered =
189 queue::Buffered::of(names, [&orchestration.init, &orchestration.notified], rings);
190 if !buffered.received.is_empty() {
191 declarations.push(queue::awake_decl());
192 }
193 if orchestration.protected.is_some() {
194 declarations.push(ProcLocalDecl::Var(VarDecl::single(
195 TypeExpr::plain(Type::Int),
196 call::FROM,
197 Some(Expr::Int(0)),
198 )));
199 }
200 let automaton = handler(&pd.name, orchestration, names, &func, &buffered);
201
202 Template {
203 name,
204 params: Vec::new(),
205 declarations,
206 locations: automaton.locations,
207 init: automaton.init,
208 transitions: automaton.transitions,
209 }
210}
211
212fn template_name(tenv: &TyEnv, pd_name: &str) -> String {
216 let name = upper_camel(pd_name);
217 let taken = tenv
218 .structs
219 .iter_enumerated()
220 .any(|(id, _)| typedef_name(tenv, id) == name);
221 if taken {
222 format!("{name}Pd")
223 } else {
224 name
225 }
226}
227
228fn uppaal_safe_name(pd_name: &str) -> String {
231 if KEYWORDS.contains(&pd_name) {
232 format!("{pd_name}_pd")
233 } else {
234 pd_name.to_owned()
235 }
236}
237
238pub(super) fn upper_camel(snake: &str) -> String {
241 let mut out = String::with_capacity(snake.len());
242 for segment in snake.split('_') {
243 let mut chars = segment.chars();
244 if let Some(first) = chars.next() {
245 out.extend(first.to_uppercase());
246 out.push_str(chars.as_str());
247 }
248 }
249 out
250}
251
252#[cfg(test)]
253mod tests {
254 use super::upper_camel;
255
256 #[test]
257 fn upper_camel_single_segment() {
258 assert_eq!(upper_camel("phil0"), "Phil0");
259 }
260
261 #[test]
262 fn upper_camel_multi_segment() {
263 assert_eq!(upper_camel("eth_outer"), "EthOuter");
264 assert_eq!(upper_camel("eth_outer_foo"), "EthOuterFoo");
265 }
266
267 #[test]
268 fn upper_camel_empty() {
269 assert_eq!(upper_camel(""), "");
270 }
271}