1use proc_macro::TokenStream;
33use proc_macro2::{Span, TokenStream as TokenStream2};
34use quote::{format_ident, quote};
35use syn::parse::{Parse, ParseStream};
36use syn::punctuated::Punctuated;
37use syn::{braced, Ident, LitInt, LitStr, Path, Result, Token};
38
39mod dts;
40mod fdt;
41mod ir;
42
43pub(crate) use ir::*;
44
45mod kw {
46 syn::custom_keyword!(name);
47 syn::custom_keyword!(backend);
48 syn::custom_keyword!(from);
49 syn::custom_keyword!(bus);
50 syn::custom_keyword!(device);
51 syn::custom_keyword!(gpio);
52 syn::custom_keyword!(periph);
53 syn::custom_keyword!(chip);
54 syn::custom_keyword!(node);
55}
56
57#[proc_macro]
60pub fn device_tree(input: TokenStream) -> TokenStream {
61 match expand(syn::parse_macro_input!(input as DslTree)) {
62 Ok(tokens) => tokens.into(),
63 Err(err) => err.to_compile_error().into(),
64 }
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68enum Backend {
69 Stm32,
70}
71
72#[derive(Debug)]
73struct DslTree {
74 name: Option<LitStr>,
75 backend: Option<Backend>,
76 chip: Option<LitStr>,
77 from: Option<LitStr>,
78 nodes: Vec<DslNode>,
79}
80
81impl Parse for DslTree {
82 fn parse(input: ParseStream) -> Result<Self> {
83 let mut tree_name = None;
84 let mut backend_kind = None;
85 let mut chip = None;
86 let mut from = None;
87 let mut nodes = Vec::new();
88
89 while !input.is_empty() {
90 if input.peek(kw::name) {
91 input.parse::<kw::name>()?;
92 tree_name = Some(input.parse()?);
93 input.parse::<Token![;]>()?;
94 } else if input.peek(kw::backend) {
95 input.parse::<kw::backend>()?;
96 let kw_ident: Ident = input.parse()?;
97 input.parse::<Token![;]>()?;
98 backend_kind = Some(match kw_ident.to_string().as_str() {
99 "stm32" => Backend::Stm32,
100 other => {
101 return Err(syn::Error::new(
102 kw_ident.span(),
103 format!("unknown backend `{other}`; supported: `stm32`"),
104 ))
105 }
106 });
107 } else if input.peek(kw::chip) {
108 input.parse::<kw::chip>()?;
109 chip = Some(input.parse()?);
110 input.parse::<Token![;]>()?;
111 } else if input.peek(kw::from) {
112 input.parse::<kw::from>()?;
113 from = Some(input.parse()?);
114 input.parse::<Token![;]>()?;
115 } else {
116 nodes.push(input.parse()?);
117 }
118 }
119
120 Ok(Self {
121 name: tree_name,
122 backend: backend_kind,
123 chip,
124 from,
125 nodes,
126 })
127 }
128}
129
130impl Parse for DslNode {
131 fn parse(input: ParseStream) -> Result<Self> {
132 let (is_bus, is_device, is_gpio, is_periph, is_node) = (
133 input.peek(kw::bus),
134 input.peek(kw::device),
135 input.peek(kw::gpio),
136 input.peek(kw::periph),
137 input.peek(kw::node),
138 );
139 if !is_bus && !is_device && !is_gpio && !is_periph && !is_node {
140 return Err(input.error("expected `bus`, `device`, `gpio`, `periph` or `node`"));
141 }
142 if is_bus {
143 input.parse::<kw::bus>()?;
144 } else if is_device {
145 input.parse::<kw::device>()?;
146 } else if is_gpio {
147 input.parse::<kw::gpio>()?;
148 } else if is_periph {
149 input.parse::<kw::periph>()?;
150 } else {
151 input.parse::<kw::node>()?;
152 }
153
154 let id: Ident = input.parse()?;
155
156 if is_node {
157 let content;
159 braced!(content in input);
160 let props: Punctuated<DslProp, Token![,]> =
161 content.parse_terminated(DslProp::parse, Token![,])?;
162 let props: Vec<DslProp> = props.into_iter().collect();
163 let deps: Vec<Ident> = props
164 .iter()
165 .filter_map(|p| match &p.value {
166 PropValue::Ref(ident) => Some(ident.clone()),
167 _ => None,
168 })
169 .collect();
170 input.parse::<Option<Token![;]>>()?;
171 return Ok(Self {
172 id,
173 kind: NodeKindAst::Device,
174 driver: None,
175 props,
176 deps,
177 });
178 }
179
180 input.parse::<Token![:]>()?;
181
182 let (kind, driver) = if is_bus {
183 let kw_ident: Ident = input.parse()?;
184 let kind = match kw_ident.to_string().as_str() {
185 "I2c" => BusKindAst::I2c,
186 "Spi" => BusKindAst::Spi,
187 "Uart" => BusKindAst::Uart,
188 other => {
189 return Err(syn::Error::new(
190 kw_ident.span(),
191 format!("unknown bus kind `{other}`; expected `I2c`, `Spi` or `Uart`"),
192 ))
193 }
194 };
195 (NodeKindAst::Bus(kind), None)
196 } else if is_gpio {
197 let kw_ident: Ident = input.parse()?;
198 let kind = match kw_ident.to_string().as_str() {
199 "Out" => GpioKindAst::Out,
200 "In" => GpioKindAst::In,
201 "Pin" => GpioKindAst::Pin,
202 other => {
203 return Err(syn::Error::new(
204 kw_ident.span(),
205 format!("unknown gpio kind `{other}`; expected `Out`, `In` or `Pin`"),
206 ))
207 }
208 };
209 (NodeKindAst::Gpio(kind), None)
210 } else if is_periph {
211 let kw_ident: Ident = input.parse()?;
212 let kind = match kw_ident.to_string().as_str() {
213 "Rng" => PeriphKindAst::Rng,
214 "Adc" => PeriphKindAst::Adc,
215 "Crc" => PeriphKindAst::Crc,
216 "Dac" => PeriphKindAst::Dac,
217 "Cordic" => PeriphKindAst::Cordic,
218 "Pwm" => PeriphKindAst::Pwm,
219 "Can" => PeriphKindAst::Can,
220 "Usb" => PeriphKindAst::Usb,
221 "Qei" => PeriphKindAst::Qei,
222 "InputCapture" => PeriphKindAst::InputCapture,
223 "Sdmmc" => PeriphKindAst::Sdmmc,
224 "I2s" => PeriphKindAst::I2s,
225 "PwmInput" => PeriphKindAst::PwmInput,
226 "ComplementaryPwm" => PeriphKindAst::ComplementaryPwm,
227 other => {
228 return Err(syn::Error::new(
229 kw_ident.span(),
230 format!(
231 "unknown peripheral kind `{other}`; expected `Rng`/`Adc`/`Crc`/`Dac`/`Cordic`/`Pwm`/`Can`/`Usb`/`Qei`/`InputCapture`/`Sdmmc`/`I2s`/`PwmInput`/`ComplementaryPwm`"
232 ),
233 ))
234 }
235 };
236 (NodeKindAst::Peripheral(kind), None)
237 } else {
238 (NodeKindAst::Device, Some(input.parse()?))
239 };
240
241 let content;
242 braced!(content in input);
243 let props: Punctuated<DslProp, Token![,]> =
244 content.parse_terminated(DslProp::parse, Token![,])?;
245 let props: Vec<DslProp> = props.into_iter().collect();
246 let deps: Vec<Ident> = props
247 .iter()
248 .filter_map(|p| match &p.value {
249 PropValue::Ref(ident) => Some(ident.clone()),
250 _ => None,
251 })
252 .collect();
253
254 input.parse::<Option<Token![;]>>()?;
256
257 Ok(Self {
258 id,
259 kind,
260 driver,
261 props,
262 deps,
263 })
264 }
265}
266
267impl Parse for DslProp {
268 fn parse(input: ParseStream) -> Result<Self> {
269 let key: Ident = input.parse()?;
270 input.parse::<Token![:]>()?;
271 let value = if input.peek(LitStr) {
272 PropValue::Str(input.parse()?)
273 } else if input.peek(LitInt) {
274 PropValue::U32(input.parse()?)
275 } else if input.peek(Ident) {
276 PropValue::Ref(input.parse()?)
277 } else {
278 return Err(input.error("expected string, integer or node reference"));
279 };
280 Ok(Self { key, value })
281 }
282}
283
284impl DslNode {
285 fn prop(&self, key: &str) -> Option<&DslProp> {
286 self.props.iter().find(|p| p.key == key)
287 }
288
289 fn prop_str(&self, key: &str) -> Result<String> {
290 let prop = self.prop(key).ok_or_else(|| {
291 syn::Error::new(
292 self.id.span(),
293 format!("`{}` is missing required prop `{key}`", self.id),
294 )
295 })?;
296 match &prop.value {
297 PropValue::Str(lit) => Ok(lit.value()),
298 _ => Err(syn::Error::new(
299 prop.key.span(),
300 format!("prop `{key}` must be a string"),
301 )),
302 }
303 }
304
305 fn prop_u32_any(&self, keys: &[&str]) -> Option<u32> {
306 keys.iter()
307 .find_map(|key| self.prop(key))
308 .and_then(|prop| match &prop.value {
309 PropValue::U32(lit) => lit.base10_parse().ok(),
310 _ => None,
311 })
312 }
313
314 fn prop_array(&self, key: &str) -> Option<&[u32]> {
316 match self.prop(key).map(|p| &p.value) {
317 Some(PropValue::Array(v)) => Some(v),
318 _ => None,
319 }
320 }
321
322 fn prop_str_opt(&self, key: &str) -> Result<Option<String>> {
323 match self.prop(key) {
324 None => Ok(None),
325 Some(prop) => match &prop.value {
326 PropValue::Str(s) => Ok(Some(s.value())),
327 _ => Err(syn::Error::new(
328 prop.key.span(),
329 format!("prop `{key}` must be a string"),
330 )),
331 },
332 }
333 }
334
335 fn prop_bool(&self, key: &str) -> bool {
337 match self.prop(key).map(|p| &p.value) {
338 Some(PropValue::Bool(b)) => *b,
339 Some(PropValue::U32(lit)) => lit
340 .base10_parse::<u32>()
341 .map(|v| v != 0)
342 .unwrap_or(false),
343 Some(PropValue::Str(s)) => s.value() == "true" || s.value() == "1",
344 _ => false,
345 }
346 }
347
348 fn pin_ident(&self, key: &str) -> Result<Ident> {
349 let pin = self.prop_str(key)?;
350 syn::parse_str::<Ident>(&pin).map_err(|_| {
351 syn::Error::new(
352 self.id.span(),
353 format!("prop `{key}` value `{pin}` is not a valid pin name"),
354 )
355 })
356 }
357
358 fn pin_ident_opt(&self, key: &str) -> Result<Option<Ident>> {
359 if self.prop(key).is_none() {
360 return Ok(None);
361 }
362 self.pin_ident(key).map(Some)
363 }
364
365 fn dma_channel(&self, key: &str) -> Result<(String, Ident)> {
366 let name = self.prop_str(key)?;
367 let ident = syn::parse_str::<Ident>(&name).map_err(|_| {
368 syn::Error::new(
369 self.id.span(),
370 format!("prop `{key}` value `{name}` is not a valid DMA channel name"),
371 )
372 })?;
373 Ok((name, ident))
374 }
375}
376
377fn expand(mut tree: DslTree) -> Result<TokenStream2> {
378 let mut track = TokenStream2::new();
379 if let Some(from) = tree.from.take() {
380 if !tree.nodes.is_empty() {
381 return Err(syn::Error::new(
382 from.span(),
383 "cannot combine inline nodes with `from` (use either Rust DSL nodes or a DTS file)",
384 ));
385 }
386 let path = from.value();
387 let loaded = if path.ends_with(".dtb") {
388 fdt::load_dtb(&path)
389 } else {
390 dts::load_dts(&path)
391 }
392 .map_err(|e| {
393 syn::Error::new(from.span(), format!("failed to load `{path}`: {e}"))
394 })?;
395 tree.nodes = loaded.nodes;
396 if tree.name.is_none() {
397 if let Some(model) = loaded.model {
398 tree.name = Some(LitStr::new(&model, Span::call_site()));
399 }
400 }
401 for file in loaded.files {
403 let lit = LitStr::new(&file, Span::call_site());
404 track.extend(quote! {
405 const _: &[u8] = include_bytes!(#lit);
406 });
407 }
408 }
409
410 validate(&tree)?;
411
412 let name = tree
413 .name
414 .as_ref()
415 .map(|lit| lit.value())
416 .unwrap_or_else(|| "board".to_string());
417 let name_lit = LitStr::new(&name, Span::call_site());
418
419 let nodes = tree.nodes.iter().map(node_expr);
420 let mut out = quote! {
421 #[allow(non_upper_case_globals)]
422 pub static TREE: ::embassy_dt::TreeDesc = ::embassy_dt::TreeDesc::new(
423 #name_lit,
424 &[ #(#nodes),* ],
425 );
426 #track
427 };
428
429 if tree.backend.is_some() {
430 out.extend(stm32_board(&tree)?);
431 }
432
433 Ok(out)
434}
435
436fn node_expr(node: &DslNode) -> TokenStream2 {
437 let id = LitStr::new(&node.id.to_string(), node.id.span());
438 let kind = match &node.kind {
439 NodeKindAst::Bus(kind) => {
440 let kind = match kind {
441 BusKindAst::I2c => quote!(I2c),
442 BusKindAst::Spi => quote!(Spi),
443 BusKindAst::Uart => quote!(Uart),
444 };
445 quote!(::embassy_dt::NodeKind::Bus(::embassy_dt::BusKind::#kind))
446 }
447 NodeKindAst::Gpio(_) => quote!(::embassy_dt::NodeKind::Gpio),
448 NodeKindAst::Peripheral(_) => quote!(::embassy_dt::NodeKind::Peripheral),
449 NodeKindAst::Device => quote!(::embassy_dt::NodeKind::Device),
450 };
451 let deps = node.deps.iter().map(|d| LitStr::new(&d.to_string(), d.span()));
452 let props = node.props.iter().map(|p| {
453 let key = LitStr::new(&p.key.to_string(), p.key.span());
454 let value = match &p.value {
455 PropValue::Str(lit) => quote!(::embassy_dt::Prop::Str(#lit)),
456 PropValue::U32(lit) => quote!(::embassy_dt::Prop::U32(#lit)),
457 PropValue::Ref(ident) => {
458 let s = LitStr::new(&ident.to_string(), ident.span());
459 quote!(::embassy_dt::Prop::Str(#s))
460 }
461 PropValue::Array(vals) => {
462 let vals = vals.iter();
463 quote!(::embassy_dt::Prop::Array(&[#(#vals),*]))
464 }
465 PropValue::Bool(b) => quote!(::embassy_dt::Prop::Bool(#b)),
466 };
467 quote!((#key, #value))
468 });
469 quote! {
470 ::embassy_dt::NodeDesc::new(
471 #id,
472 #kind,
473 &[#(#deps),*],
474 &[#(#props),*],
475 )
476 }
477}
478
479fn validate(tree: &DslTree) -> Result<()> {
481 for (i, node) in tree.nodes.iter().enumerate() {
482 if tree.nodes[..i].iter().any(|prev| prev.id == node.id) {
483 return Err(syn::Error::new(
484 node.id.span(),
485 format!("duplicate node id `{}`", node.id),
486 ));
487 }
488 }
489
490 for node in &tree.nodes {
491 for dep in &node.deps {
492 if !tree.nodes.iter().any(|n| &n.id == dep) {
493 return Err(syn::Error::new(
494 dep.span(),
495 format!("node `{}` depends on unknown node `{}`", node.id, dep),
496 ));
497 }
498 }
499 }
500
501 let n = tree.nodes.len();
504 let index_of = |id: &Ident| tree.nodes.iter().position(|n| &n.id == id).unwrap();
505 let mut indeg = vec![0usize; n];
506 for node in &tree.nodes {
507 indeg[index_of(&node.id)] = node.deps.len();
508 }
509 let mut queue: Vec<usize> = (0..n).filter(|&i| indeg[i] == 0).collect();
510 let mut removed = 0usize;
511 while let Some(i) = queue.pop() {
512 removed += 1;
513 for (j, node) in tree.nodes.iter().enumerate() {
514 if node.deps.iter().any(|d| index_of(d) == i) {
515 indeg[j] -= 1;
516 if indeg[j] == 0 {
517 queue.push(j);
518 }
519 }
520 }
521 }
522 if removed < n {
523 for (i, node) in tree.nodes.iter().enumerate() {
524 if indeg[i] > 0 {
525 return Err(syn::Error::new(
526 node.id.span(),
527 format!("dependency cycle involving node `{}`", node.id),
528 ));
529 }
530 }
531 }
532
533 Ok(())
534}
535
536fn stm32_board(tree: &DslTree) -> Result<TokenStream2> {
557 let chip = chip_name(tree)?;
558 let mut fields = Vec::new();
559 let mut inits = Vec::new();
560 let mut statics = Vec::new();
562 let mut bindings: Vec<(String, Vec<TokenStream2>)> = Vec::new();
564 let mut devices: Vec<(&DslNode, &Path)> = Vec::new();
566
567 for node in &tree.nodes {
568 match &node.kind {
569 NodeKindAst::Bus(BusKindAst::I2c) => {
570 let periph = periph_ident(node)?;
571 let scl = node.pin_ident("scl")?;
572 let sda = node.pin_ident("sda")?;
573 let (dma_tx_str, dma_tx) = node.dma_channel("dma_tx")?;
574 let (dma_rx_str, dma_rx) = node.dma_channel("dma_rx")?;
575 let freq = node.prop_u32_any(&["freq", "frequency"]).unwrap_or(100_000);
576 let field = &node.id;
577 let shared = node.prop_bool("shared");
578
579 push_dma_bindings(&mut bindings, &dma_tx_str, &dma_tx, node, chip.as_deref())?;
580 push_dma_bindings(&mut bindings, &dma_rx_str, &dma_rx, node, chip.as_deref())?;
581 let f0 = chip
584 .as_deref()
585 .map(|c| c.contains("f0"))
586 .unwrap_or(false);
587 let irq_base = periph.to_string();
588 let ev_irq = if f0 {
589 format_ident!("{}", irq_base)
590 } else {
591 format_ident!("{}_EV", irq_base)
592 };
593 let er_irq = if f0 {
594 format_ident!("{}", irq_base)
595 } else {
596 format_ident!("{}_ER", irq_base)
597 };
598 push_binding(&mut bindings, ev_irq, quote! {
599 ::embassy_stm32::i2c::EventInterruptHandler<::embassy_stm32::peripherals::#periph>
600 });
601 push_binding(&mut bindings, er_irq, quote! {
602 ::embassy_stm32::i2c::ErrorInterruptHandler<::embassy_stm32::peripherals::#periph>
603 });
604
605 if shared {
606 let mux_name = format_ident!("{}_MUTEX", field.to_string());
607 statics.push(quote! {
608 #[allow(non_upper_case_globals)]
609 static mut #mux_name: Option<
610 ::embassy_sync::mutex::Mutex<
611 ::embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex,
612 ::embassy_stm32::i2c::I2c<
613 'static,
614 ::embassy_stm32::mode::Async,
615 ::embassy_stm32::i2c::mode::Master,
616 >,
617 >,
618 > = None;
619 });
620 fields.push(quote! {
621 pub #field: ::embassy_embedded_hal::shared_bus::asynch::i2c::I2cDevice<
622 'static,
623 ::embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex,
624 ::embassy_stm32::i2c::I2c<
625 'static,
626 ::embassy_stm32::mode::Async,
627 ::embassy_stm32::i2c::mode::Master,
628 >,
629 >
630 });
631 inits.push(quote! {
632 #field: {
633 let raw = {
634 let mut config = ::embassy_stm32::i2c::Config::default();
635 config.frequency = ::embassy_stm32::time::Hertz(#freq);
636 ::embassy_stm32::i2c::I2c::new(
637 p.#periph, p.#scl, p.#sda,
638 p.#dma_tx, p.#dma_rx,
639 DtIrqs,
640 config,
641 )
642 };
643 unsafe {
644 #mux_name = Some(::embassy_sync::mutex::Mutex::new(raw));
645 }
646 ::embassy_embedded_hal::shared_bus::asynch::i2c::I2cDevice::new(
647 unsafe { #mux_name.as_ref() }.expect("i2c mutex"),
648 )
649 },
650 });
651 } else {
652 fields.push(quote! {
653 pub #field: ::embassy_stm32::i2c::I2c<
654 'static,
655 ::embassy_stm32::mode::Async,
656 ::embassy_stm32::i2c::mode::Master,
657 >
658 });
659 inits.push(quote! {
660 #field: {
661 let mut config = ::embassy_stm32::i2c::Config::default();
662 config.frequency = ::embassy_stm32::time::Hertz(#freq);
663 ::embassy_stm32::i2c::I2c::new(
664 p.#periph, p.#scl, p.#sda,
665 p.#dma_tx, p.#dma_rx,
666 DtIrqs,
667 config,
668 )
669 },
670 });
671 }
672 }
673 NodeKindAst::Bus(BusKindAst::Spi) => {
674 let periph = periph_ident(node)?;
675 let sck = node.pin_ident("sck")?;
676 let mosi = node.pin_ident("mosi")?;
677 let miso = node.pin_ident("miso")?;
678 let (dma_tx_str, dma_tx) = node.dma_channel("dma_tx")?;
679 let (dma_rx_str, dma_rx) = node.dma_channel("dma_rx")?;
680 let freq = node.prop_u32_any(&["freq", "frequency"]).unwrap_or(1_000_000);
681 let field = &node.id;
682 let is_slave = node
683 .prop_str("mode")
684 .map(|m| m == "slave")
685 .unwrap_or(false);
686 let shared = node.prop_bool("shared");
687
688 push_dma_bindings(&mut bindings, &dma_tx_str, &dma_tx, node, chip.as_deref())?;
689 push_dma_bindings(&mut bindings, &dma_rx_str, &dma_rx, node, chip.as_deref())?;
690
691 if shared {
692 let mux_name = format_ident!("{}_MUTEX", field.to_string());
693 statics.push(quote! {
694 #[allow(non_upper_case_globals)]
695 static mut #mux_name: Option<
696 ::embassy_sync::mutex::Mutex<
697 ::embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex,
698 ::embassy_stm32::spi::Spi<
699 'static,
700 ::embassy_stm32::mode::Async,
701 ::embassy_stm32::spi::mode::Master,
702 >,
703 >,
704 > = None;
705 });
706 fields.push(quote! {
707 pub #field: &'static ::embassy_sync::mutex::Mutex<
709 ::embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex,
710 ::embassy_stm32::spi::Spi<
711 'static,
712 ::embassy_stm32::mode::Async,
713 ::embassy_stm32::spi::mode::Master,
714 >,
715 >
716 });
717 inits.push(quote! {
718 #field: {
719 let raw = {
720 let mut config = ::embassy_stm32::spi::Config::default();
721 config.frequency = ::embassy_stm32::time::Hertz(#freq);
722 ::embassy_stm32::spi::Spi::new(
723 p.#periph, p.#sck, p.#mosi, p.#miso,
724 p.#dma_tx, p.#dma_rx,
725 DtIrqs,
726 config,
727 )
728 };
729 unsafe {
730 #mux_name = Some(::embassy_sync::mutex::Mutex::new(raw));
731 }
732 unsafe { #mux_name.as_ref() }.expect("spi mutex")
733 },
734 });
735 } else if is_slave {
736 let cs = node.pin_ident("cs")?;
737 fields.push(quote! {
738 pub #field: ::embassy_stm32::spi::Spi<
739 'static,
740 ::embassy_stm32::mode::Async,
741 ::embassy_stm32::spi::mode::Slave,
742 >
743 });
744 inits.push(quote! {
745 #field: {
746 let mut config = ::embassy_stm32::spi::Config::default();
747 config.frequency = ::embassy_stm32::time::Hertz(#freq);
748 ::embassy_stm32::spi::Spi::new_slave(
749 p.#periph, p.#sck, p.#mosi, p.#miso, p.#cs,
750 p.#dma_tx, p.#dma_rx,
751 DtIrqs,
752 config,
753 )
754 },
755 });
756 } else {
757 fields.push(quote! {
758 pub #field: ::embassy_stm32::spi::Spi<
759 'static,
760 ::embassy_stm32::mode::Async,
761 ::embassy_stm32::spi::mode::Master,
762 >
763 });
764 inits.push(quote! {
765 #field: {
766 let mut config = ::embassy_stm32::spi::Config::default();
767 config.frequency = ::embassy_stm32::time::Hertz(#freq);
768 ::embassy_stm32::spi::Spi::new(
769 p.#periph, p.#sck, p.#mosi, p.#miso,
770 p.#dma_tx, p.#dma_rx,
771 DtIrqs,
772 config,
773 )
774 },
775 });
776 }
777 }
778 NodeKindAst::Bus(BusKindAst::Uart) => {
779 let periph = periph_ident(node)?;
780 let rx = node.pin_ident("rx")?;
781 let tx = node.pin_ident("tx")?;
782 let (dma_tx_str, dma_tx) = node.dma_channel("dma_tx")?;
783 let (dma_rx_str, dma_rx) = node.dma_channel("dma_rx")?;
784 let baud = node.prop_u32_any(&["baud", "baudrate"]).unwrap_or(115_200);
785 let field = &node.id;
786
787 push_binding(&mut bindings, periph.clone(), quote! {
788 ::embassy_stm32::usart::InterruptHandler<::embassy_stm32::peripherals::#periph>
789 });
790 push_dma_bindings(&mut bindings, &dma_tx_str, &dma_tx, node, chip.as_deref())?;
791 push_dma_bindings(&mut bindings, &dma_rx_str, &dma_rx, node, chip.as_deref())?;
792
793 fields.push(quote! {
794 pub #field: ::embassy_stm32::usart::Uart<'static, ::embassy_stm32::mode::Async>
795 });
796 inits.push(quote! {
797 #field: {
798 let mut config = ::embassy_stm32::usart::Config::default();
799 config.baudrate = #baud;
800 ::embassy_stm32::usart::Uart::new(
801 p.#periph, p.#rx, p.#tx,
802 p.#dma_tx, p.#dma_rx,
803 DtIrqs,
804 config,
805 )
806 .expect("embassy-dt: invalid UART configuration")
807 },
808 });
809 }
810 NodeKindAst::Gpio(gpio_kind) => {
811 let pin = node.pin_ident("pin")?;
812 let field = &node.id;
813 match gpio_kind {
814 GpioKindAst::Out => {
815 let level = match node.prop_str("level")?.as_str() {
816 "high" => quote!(High),
817 "low" => quote!(Low),
818 other => {
819 return Err(syn::Error::new(
820 node.id.span(),
821 format!("gpio `{}`: `level` must be `high` or `low`, got `{other}`", node.id),
822 ))
823 }
824 };
825 fields.push(quote! {
826 pub #field: ::embassy_stm32::gpio::Output<'static>
827 });
828 inits.push(quote! {
829 #field: ::embassy_stm32::gpio::Output::new(
830 p.#pin,
831 ::embassy_stm32::gpio::Level::#level,
832 ::embassy_stm32::gpio::Speed::VeryHigh,
833 ),
834 });
835 }
836 GpioKindAst::In => {
837 let pull = match node.prop_str("pull")?.as_str() {
838 "up" => quote!(Up),
839 "down" => quote!(Down),
840 "none" => quote!(None),
841 other => {
842 return Err(syn::Error::new(
843 node.id.span(),
844 format!("gpio `{}`: `pull` must be `up`/`down`/`none`, got `{other}`", node.id),
845 ))
846 }
847 };
848 if node.prop_bool("exti") {
849 let f0 = chip
851 .as_deref()
852 .map(|c| c.contains("f0"))
853 .unwrap_or(false);
854 let (ch, irq, tl) = exti_info(&pin.to_string(), f0)?;
855 push_binding(&mut bindings, irq, quote! {
856 ::embassy_stm32::exti::InterruptHandler<::embassy_stm32::interrupt::typelevel::#tl>
857 });
858 fields.push(quote! {
859 pub #field: ::embassy_stm32::exti::ExtiInput<'static, ::embassy_stm32::mode::Async>
860 });
861 inits.push(quote! {
862 #field: ::embassy_stm32::exti::ExtiInput::new(
863 p.#pin,
864 p.#ch,
865 ::embassy_stm32::gpio::Pull::#pull,
866 DtIrqs,
867 ),
868 });
869 } else {
870 fields.push(quote! {
871 pub #field: ::embassy_stm32::gpio::Input<'static>
872 });
873 inits.push(quote! {
874 #field: ::embassy_stm32::gpio::Input::new(
875 p.#pin,
876 ::embassy_stm32::gpio::Pull::#pull,
877 ),
878 });
879 }
880 }
881 GpioKindAst::Pin => {
882 fields.push(quote! {
885 pub #field: ::embassy_stm32::Peri<'static, ::embassy_stm32::peripherals::#pin>
886 });
887 inits.push(quote! {
888 #field: p.#pin,
889 });
890 }
891 }
892 }
893 NodeKindAst::Peripheral(kind) => {
894 let periph = periph_ident(node)?;
895 let field = &node.id;
896 match kind {
897 PeriphKindAst::Rng => {
898 push_binding(&mut bindings, periph.clone(), quote! {
899 ::embassy_stm32::rng::InterruptHandler<::embassy_stm32::peripherals::#periph>
900 });
901 fields.push(quote! {
902 pub #field: ::embassy_stm32::rng::Rng<'static, ::embassy_stm32::peripherals::#periph>
903 });
904 inits.push(quote! {
905 #field: ::embassy_stm32::rng::Rng::new(p.#periph, DtIrqs),
906 });
907 }
908 PeriphKindAst::Adc => {
909 match chip_name(tree)? {
910 Some(chip)
914 if chip.contains("h723")
915 || chip.contains("f411")
916 || chip.contains("l476")
917 || chip.contains("g4") =>
918 {
919 fields.push(quote! {
920 pub #field: ::embassy_stm32::adc::Adc<'static, ::embassy_stm32::peripherals::#periph>
921 });
922 if chip.contains("g4") {
923 inits.push(quote! {
924 #field: ::embassy_stm32::adc::Adc::new(
925 p.#periph,
926 ::embassy_stm32::adc::AdcConfig::default(),
927 ),
928 });
929 } else {
930 inits.push(quote! {
931 #field: ::embassy_stm32::adc::Adc::new(p.#periph),
932 });
933 }
934 }
935 Some(chip) if chip.contains("f103") || chip.contains("f1") => {
936 push_binding(&mut bindings, Ident::new("ADC1_2", Span::call_site()), quote! {
938 ::embassy_stm32::adc::InterruptHandler<::embassy_stm32::peripherals::#periph>
939 });
940 fields.push(quote! {
941 pub #field: ::embassy_stm32::adc::Adc<'static, ::embassy_stm32::peripherals::#periph>
942 });
943 inits.push(quote! {
944 #field: ::embassy_stm32::adc::Adc::new(p.#periph),
945 });
946 }
947 Some(chip) if chip.contains("f091") || chip.contains("f0") => {
948 push_binding(
951 &mut bindings,
952 Ident::new("ADC1_COMP", Span::call_site()),
953 quote! {
954 ::embassy_stm32::adc::InterruptHandler<::embassy_stm32::peripherals::#periph>
955 },
956 );
957 fields.push(quote! {
958 pub #field: ::embassy_stm32::adc::Adc<'static, ::embassy_stm32::peripherals::#periph>
959 });
960 inits.push(quote! {
961 #field: ::embassy_stm32::adc::Adc::new(p.#periph, DtIrqs),
962 });
963 }
964 _ => {
965 return Err(syn::Error::new(
966 node.id.span(),
967 "stm32 backend: `adc` is not supported for this chip (supported: stm32h723zg / stm32f411ce / stm32l476rg / stm32g474re / stm32f103c8 / stm32f091rc)",
968 ))
969 }
970 }
971 if let Some(pin) = node.pin_ident_opt("pin")? {
975 let pin_field = format_ident!("{}_pin", node.id);
976 fields.push(quote! {
977 pub #pin_field: ::embassy_stm32::Peri<'static, ::embassy_stm32::peripherals::#pin>
978 });
979 inits.push(quote! {
980 #pin_field: p.#pin,
981 });
982 }
983 }
984 PeriphKindAst::Crc => {
985 match chip_name(tree)? {
986 Some(chip) if chip.contains("h723") => {
987 fields.push(quote! {
988 pub #field: ::embassy_stm32::crc::Crc<'static>
989 });
990 inits.push(quote! {
991 #field: ::embassy_stm32::crc::Crc::new(
992 p.#periph,
993 ::embassy_stm32::crc::Config::new(
994 ::embassy_stm32::crc::InputReverseConfig::None,
995 false,
996 ::embassy_stm32::crc::PolySize::Width32,
997 0xFFFF_FFFF,
998 0x04C1_1DB7,
999 )
1000 .expect("embassy-dt: invalid CRC config"),
1001 ),
1002 });
1003 }
1004 Some(chip)
1005 if chip.contains("f411")
1006 || chip.contains("l476")
1007 || chip.contains("f103")
1008 || chip.contains("f1")
1009 =>
1010 {
1011 fields.push(quote! {
1012 pub #field: ::embassy_stm32::crc::Crc<'static>
1013 });
1014 inits.push(quote! {
1015 #field: ::embassy_stm32::crc::Crc::new(p.#periph),
1016 });
1017 }
1018 Some(chip) if chip.contains("f0") => {
1019 fields.push(quote! {
1021 pub #field: ::embassy_stm32::crc::Crc<'static>
1022 });
1023 inits.push(quote! {
1024 #field: ::embassy_stm32::crc::Crc::new(
1025 p.#periph,
1026 ::embassy_stm32::crc::Config::new(
1027 ::embassy_stm32::crc::InputReverseConfig::None,
1028 false,
1029 ::embassy_stm32::crc::PolySize::Width32,
1030 0xFFFF_FFFF,
1031 0x04C1_1DB7,
1032 )
1033 .expect("embassy-dt: invalid CRC config"),
1034 ),
1035 });
1036 }
1037 _ => {
1038 return Err(syn::Error::new(
1039 node.id.span(),
1040 "stm32 backend: `crc` is not supported for this chip (declare `chip \"stm32h723zg\"` or `chip \"stm32f411ce\"`)",
1041 ))
1042 }
1043 }
1044 }
1045 PeriphKindAst::Dac => {
1046 let pin = node.pin_ident("pin")?;
1047 fields.push(quote! {
1048 pub #field: ::embassy_stm32::dac::DacChannel<'static, ::embassy_stm32::mode::Blocking>
1049 });
1050 inits.push(quote! {
1051 #field: ::embassy_stm32::dac::DacChannel::new_blocking(p.#periph, p.#pin),
1052 });
1053 }
1054 PeriphKindAst::Cordic => {
1055 match chip_name(tree)? {
1059 Some(chip) if chip.contains("g4") => {
1060 fields.push(quote! {
1061 pub #field: ::embassy_stm32::cordic::Cordic<'static, ::embassy_stm32::peripherals::#periph>
1062 });
1063 inits.push(quote! {
1064 #field: ::embassy_stm32::cordic::Cordic::new(
1065 p.#periph,
1066 ::embassy_stm32::cordic::Config::new(
1067 ::embassy_stm32::cordic::Function::Cos,
1068 ::embassy_stm32::cordic::Precision::Iters24,
1069 ::embassy_stm32::cordic::Scale::default(),
1070 )
1071 .expect("embassy-dt: invalid CORDIC config")
1072 .res_count(::embassy_stm32::cordic::AccessCount::Two),
1073 ),
1074 });
1075 }
1076 _ => {
1077 return Err(syn::Error::new(
1078 node.id.span(),
1079 "stm32 backend: `cordic` is not supported for this chip (supported: stm32g4xx)",
1080 ))
1081 }
1082 }
1083 }
1084 PeriphKindAst::Pwm => {
1085 let ch1 = node.pin_ident_opt("ch1")?;
1086 let ch2 = node.pin_ident_opt("ch2")?;
1087 let ch3 = node.pin_ident_opt("ch3")?;
1088 let ch4 = node.pin_ident_opt("ch4")?;
1089 let freq = node.prop_u32_any(&["freq", "frequency"]).unwrap_or(1_000);
1090 let afio = chip_name(tree)?
1094 .as_deref()
1095 .map(|c| c.contains("f1"))
1096 .unwrap_or(false);
1097 let ch1 = pwm_pin(ch1, afio);
1098 let ch2 = pwm_pin(ch2, afio);
1099 let ch3 = pwm_pin(ch3, afio);
1100 let ch4 = pwm_pin(ch4, afio);
1101 fields.push(quote! {
1102 pub #field: ::embassy_stm32::timer::simple_pwm::SimplePwm<'static, ::embassy_stm32::peripherals::#periph>
1103 });
1104 inits.push(quote! {
1105 #field: ::embassy_stm32::timer::simple_pwm::SimplePwm::new(
1106 p.#periph,
1107 #ch1, #ch2, #ch3, #ch4,
1108 ::embassy_stm32::time::Hertz(#freq),
1109 ::embassy_stm32::timer::low_level::CountingMode::EdgeAlignedUp,
1110 ),
1111 });
1112 }
1113 PeriphKindAst::Can => {
1114 let rx = node.pin_ident("rx")?;
1115 let tx = node.pin_ident("tx")?;
1116 match chip_name(tree)? {
1117 Some(chip) if chip.contains("h723") || chip.contains("g4") => {
1118 let it0 = format_ident!("{}_IT0", periph.to_string());
1119 let it1 = format_ident!("{}_IT1", periph.to_string());
1120 push_binding(&mut bindings, it0, quote! {
1121 ::embassy_stm32::can::IT0InterruptHandler<::embassy_stm32::peripherals::#periph>
1122 });
1123 push_binding(&mut bindings, it1, quote! {
1124 ::embassy_stm32::can::IT1InterruptHandler<::embassy_stm32::peripherals::#periph>
1125 });
1126 fields.push(quote! {
1127 pub #field: ::embassy_stm32::can::Can<'static>
1128 });
1129 inits.push(quote! {
1130 #field: ::embassy_stm32::can::CanConfigurator::new(
1131 p.#periph, p.#rx, p.#tx, DtIrqs,
1132 )
1133 .into_normal_mode(),
1134 });
1135 }
1136 Some(chip)
1137 if chip.contains("f4") || chip.contains("f1") || chip.contains("f0") =>
1138 {
1139 let f1 = chip.contains("f1");
1143 let f0 = chip.contains("f0");
1144 let tx_irq = if f1 {
1147 Ident::new("USB_HP_CAN1_TX", Span::call_site())
1148 } else if f0 {
1149 Ident::new("CEC_CAN", Span::call_site())
1150 } else {
1151 format_ident!("{}_TX", periph.to_string())
1152 };
1153 let rx0 = if f1 {
1154 Ident::new("USB_LP_CAN1_RX0", Span::call_site())
1155 } else if f0 {
1156 Ident::new("CEC_CAN", Span::call_site())
1157 } else {
1158 format_ident!("{}_RX0", periph.to_string())
1159 };
1160 let rx1 = if f1 {
1161 Ident::new("CAN1_RX1", Span::call_site())
1162 } else if f0 {
1163 Ident::new("CEC_CAN", Span::call_site())
1164 } else {
1165 format_ident!("{}_RX1", periph.to_string())
1166 };
1167 let sce = if f1 {
1168 Ident::new("CAN1_SCE", Span::call_site())
1169 } else if f0 {
1170 Ident::new("CEC_CAN", Span::call_site())
1171 } else {
1172 format_ident!("{}_SCE", periph.to_string())
1173 };
1174 push_binding(&mut bindings, tx_irq, quote! {
1175 ::embassy_stm32::can::TxInterruptHandler<::embassy_stm32::peripherals::#periph>
1176 });
1177 push_binding(&mut bindings, rx0, quote! {
1178 ::embassy_stm32::can::Rx0InterruptHandler<::embassy_stm32::peripherals::#periph>
1179 });
1180 push_binding(&mut bindings, rx1, quote! {
1181 ::embassy_stm32::can::Rx1InterruptHandler<::embassy_stm32::peripherals::#periph>
1182 });
1183 push_binding(&mut bindings, sce, quote! {
1184 ::embassy_stm32::can::SceInterruptHandler<::embassy_stm32::peripherals::#periph>
1185 });
1186 fields.push(quote! {
1187 pub #field: ::embassy_stm32::can::Can<'static>
1188 });
1189 inits.push(quote! {
1190 #field: ::embassy_stm32::can::Can::new(p.#periph, p.#rx, p.#tx, DtIrqs),
1191 });
1192 }
1193 _ => {
1194 return Err(syn::Error::new(
1195 node.id.span(),
1196 "stm32 backend: `can` is not supported for this chip (declare `chip \"stm32h723zg\"` / `chip \"stm32g474re\"` / `chip \"stm32f103c8\"` or a F4 chip with bxCAN)",
1197 ))
1198 }
1199 }
1200 }
1201 PeriphKindAst::Usb => {
1202 let dp = node.pin_ident("dp")?;
1203 let dm = node.pin_ident("dm")?;
1204 let chip = chip_name(tree)?;
1205 let ep_out =
1206 node.prop_u32_any(&["ep_out", "ep_out_buf"]).unwrap_or(256) as usize;
1207 let ep_buf = format_ident!("{}_EP_BUF", field.to_string());
1208 let periph_str = periph.to_string();
1209 let irq_name = if chip.as_deref().map(|c| c.contains("f1")).unwrap_or(false) {
1214 "USB_LP_CAN1_RX0".to_string()
1215 } else if chip.as_deref().map(|c| c.contains("f0")).unwrap_or(false) {
1216 periph_str.clone()
1218 } else if chip.as_deref().map(|c| c.contains("g4")).unwrap_or(false) {
1219 format!("{}_LP", periph_str)
1220 } else {
1221 periph_str
1222 .strip_prefix("USB_")
1223 .unwrap_or(&periph_str)
1224 .to_string()
1225 };
1226 let irq = format_ident!("{}", irq_name);
1227 push_binding(&mut bindings, irq, quote! {
1228 ::embassy_stm32::usb::InterruptHandler<::embassy_stm32::peripherals::#periph>
1229 });
1230 fields.push(quote! {
1231 pub #field: ::embassy_stm32::usb::Driver<'static, ::embassy_stm32::peripherals::#periph>
1232 });
1233 match chip {
1234 Some(chip) if chip.contains("h723") => {
1235 statics.push(quote! {
1236 #[allow(non_upper_case_globals)]
1237 static mut #ep_buf: [u8; #ep_out] = [0; #ep_out];
1238 });
1239 inits.push(quote! {
1240 #field: unsafe {
1241 ::embassy_stm32::usb::Driver::new_hs(
1242 p.#periph, DtIrqs, p.#dp, p.#dm,
1243 &mut #ep_buf,
1244 ::embassy_stm32::usb::Config::default(),
1245 )
1246 },
1247 });
1248 }
1249 Some(chip) if chip.contains("f411") => {
1250 statics.push(quote! {
1251 #[allow(non_upper_case_globals)]
1252 static mut #ep_buf: [u8; #ep_out] = [0; #ep_out];
1253 });
1254 inits.push(quote! {
1255 #field: unsafe {
1256 ::embassy_stm32::usb::Driver::new_fs(
1257 p.#periph, DtIrqs, p.#dp, p.#dm,
1258 &mut #ep_buf,
1259 ::embassy_stm32::usb::Config::default(),
1260 )
1261 },
1262 });
1263 }
1264 Some(chip)
1265 if chip.contains("g4")
1266 || chip.contains("f1")
1267 || chip.contains("f0") =>
1268 {
1269 inits.push(quote! {
1271 #field: ::embassy_stm32::usb::Driver::new(
1272 p.#periph, DtIrqs, p.#dp, p.#dm,
1273 ),
1274 });
1275 }
1276 _ => {
1277 return Err(syn::Error::new(
1278 node.id.span(),
1279 "stm32 backend: `usb` is not supported for this chip (declare `chip \"stm32h723zg\"` / `chip \"stm32f411ce\"` / `chip \"stm32g474re\"` / `chip \"stm32f103c8\"` / `chip \"stm32f091rc\"`)",
1280 ))
1281 }
1282 }
1283 }
1284 PeriphKindAst::Qei => {
1285 let ch1 = node.pin_ident("ch1")?;
1286 let ch2 = node.pin_ident("ch2")?;
1287 fields.push(quote! {
1288 pub #field: ::embassy_stm32::timer::qei::Qei<'static, ::embassy_stm32::peripherals::#periph>
1289 });
1290 inits.push(quote! {
1291 #field: ::embassy_stm32::timer::qei::Qei::new(
1292 p.#periph, p.#ch1, p.#ch2,
1293 ::embassy_stm32::timer::qei::Config::default(),
1294 ),
1295 });
1296 }
1297 PeriphKindAst::InputCapture => {
1298 let ch1 = capture_pin(node.pin_ident_opt("ch1")?);
1299 let ch2 = capture_pin(node.pin_ident_opt("ch2")?);
1300 let ch3 = capture_pin(node.pin_ident_opt("ch3")?);
1301 let ch4 = capture_pin(node.pin_ident_opt("ch4")?);
1302 let freq = node
1303 .prop_u32_any(&["freq", "frequency"])
1304 .unwrap_or(1_000_000);
1305 push_binding(&mut bindings, cc_irq(&periph), quote! {
1306 ::embassy_stm32::timer::CaptureCompareInterruptHandler<::embassy_stm32::peripherals::#periph>
1307 });
1308 fields.push(quote! {
1309 pub #field: ::embassy_stm32::timer::input_capture::InputCapture<'static, ::embassy_stm32::peripherals::#periph>
1310 });
1311 inits.push(quote! {
1312 #field: ::embassy_stm32::timer::input_capture::InputCapture::new(
1313 p.#periph,
1314 #ch1, #ch2, #ch3, #ch4,
1315 DtIrqs,
1316 ::embassy_stm32::time::Hertz(#freq),
1317 ::embassy_stm32::timer::low_level::CountingMode::EdgeAlignedUp,
1318 ),
1319 });
1320 }
1321 PeriphKindAst::Sdmmc => {
1322 let clk = node.pin_ident("clk")?;
1323 let cmd = node.pin_ident("cmd")?;
1324 let d0 = node.pin_ident("d0")?;
1325 match chip_name(tree)? {
1326 Some(chip) if chip.contains("h723") => {
1327 push_binding(&mut bindings, periph.clone(), quote! {
1328 ::embassy_stm32::sdmmc::InterruptHandler<::embassy_stm32::peripherals::#periph>
1329 });
1330 fields.push(quote! {
1331 pub #field: ::embassy_stm32::sdmmc::Sdmmc<'static>
1332 });
1333 inits.push(quote! {
1334 #field: ::embassy_stm32::sdmmc::Sdmmc::new_1bit(
1335 p.#periph, DtIrqs,
1336 p.#clk, p.#cmd, p.#d0,
1337 ::embassy_stm32::sdmmc::Config::default(),
1338 ),
1339 });
1340 }
1341 _ => {
1342 return Err(syn::Error::new(
1343 node.id.span(),
1344 "stm32 backend: `sdmmc` is not supported for this chip (supported: stm32h723zg)",
1345 ))
1346 }
1347 }
1348 }
1349 PeriphKindAst::I2s => {
1350 let sd = node.pin_ident("sd")?;
1351 let ws = node.pin_ident("ws")?;
1352 let ck = node.pin_ident("ck")?;
1353 let (dma_str, dma) = node.dma_channel("dma")?;
1354 let buf_words =
1355 node.prop_u32_any(&["buffer", "buf"]).unwrap_or(256) as usize;
1356 let buf = format_ident!("{}_DMA_BUF", field.to_string());
1357 push_dma_bindings(&mut bindings, &dma_str, &dma, node, chip.as_deref())?;
1358 fields.push(quote! {
1359 pub #field: ::embassy_stm32::i2s::I2S<'static, u16>
1360 });
1361 statics.push(quote! {
1362 #[allow(non_upper_case_globals)]
1363 static mut #buf: [u16; #buf_words] = [0; #buf_words];
1364 });
1365 inits.push(quote! {
1366 #field: unsafe {
1367 ::embassy_stm32::i2s::I2S::new_txonly_nomck(
1368 p.#periph, p.#sd, p.#ws, p.#ck,
1369 p.#dma,
1370 &mut #buf,
1371 DtIrqs,
1372 ::embassy_stm32::i2s::Config::default(),
1373 )
1374 },
1375 });
1376 }
1377 PeriphKindAst::PwmInput => {
1378 let pin = node.pin_ident("pin")?;
1379 let freq = node
1380 .prop_u32_any(&["freq", "frequency"])
1381 .unwrap_or(10_000);
1382 push_binding(&mut bindings, cc_irq(&periph), quote! {
1383 ::embassy_stm32::timer::CaptureCompareInterruptHandler<::embassy_stm32::peripherals::#periph>
1384 });
1385 fields.push(quote! {
1386 pub #field: ::embassy_stm32::timer::pwm_input::PwmInput<'static, ::embassy_stm32::peripherals::#periph>
1387 });
1388 inits.push(quote! {
1389 #field: ::embassy_stm32::timer::pwm_input::PwmInput::new_ch1(
1390 p.#periph, p.#pin, DtIrqs,
1391 ::embassy_stm32::gpio::Pull::None,
1392 ::embassy_stm32::time::Hertz(#freq),
1393 ),
1394 });
1395 }
1396 PeriphKindAst::ComplementaryPwm => {
1397 let afio = chip_name(tree)?
1398 .as_deref()
1399 .map(|c| c.contains("f1"))
1400 .unwrap_or(false);
1401 let ch1 = pwm_pin(node.pin_ident_opt("ch1")?, afio);
1402 let ch1n = comp_pin(node.pin_ident_opt("ch1n")?);
1403 let ch2 = pwm_pin(node.pin_ident_opt("ch2")?, afio);
1404 let ch2n = comp_pin(node.pin_ident_opt("ch2n")?);
1405 let ch3 = pwm_pin(node.pin_ident_opt("ch3")?, afio);
1406 let ch3n = comp_pin(node.pin_ident_opt("ch3n")?);
1407 let ch4 = pwm_pin(node.pin_ident_opt("ch4")?, afio);
1408 let ch4n = comp_pin(node.pin_ident_opt("ch4n")?);
1409 let freq = node
1410 .prop_u32_any(&["freq", "frequency"])
1411 .unwrap_or(10_000);
1412 let counting = match node.prop_str_opt("counting")?.as_deref() {
1417 None | Some("edge-aligned-up") => quote!(
1418 ::embassy_stm32::timer::low_level::CountingMode::EdgeAlignedUp
1419 ),
1420 Some("edge-aligned-down") => quote!(
1421 ::embassy_stm32::timer::low_level::CountingMode::EdgeAlignedDown
1422 ),
1423 Some("center-aligned-1") | Some("center-aligned-down") => quote!(
1424 ::embassy_stm32::timer::low_level::CountingMode::CenterAlignedDownInterrupts
1425 ),
1426 Some("center-aligned-2") | Some("center-aligned-up") => quote!(
1427 ::embassy_stm32::timer::low_level::CountingMode::CenterAlignedUpInterrupts
1428 ),
1429 Some("center-aligned-3") | Some("center-aligned-both") => quote!(
1430 ::embassy_stm32::timer::low_level::CountingMode::CenterAlignedBothInterrupts
1431 ),
1432 Some(other) => {
1433 return Err(syn::Error::new(
1434 node.id.span(),
1435 format!(
1436 "complementary-pwm: unsupported `counting` `{other}` \
1437 (edge-aligned-up / edge-aligned-down / \
1438 center-aligned-1 / center-aligned-2 / center-aligned-3)"
1439 ),
1440 ))
1441 }
1442 };
1443 fields.push(quote! {
1444 pub #field: ::embassy_stm32::timer::complementary_pwm::ComplementaryPwm<'static, ::embassy_stm32::peripherals::#periph>
1445 });
1446 inits.push(quote! {
1447 #field: ::embassy_stm32::timer::complementary_pwm::ComplementaryPwm::new(
1448 p.#periph,
1449 #ch1, #ch1n, #ch2, #ch2n,
1450 #ch3, #ch3n, #ch4, #ch4n,
1451 ::embassy_stm32::time::Hertz(#freq),
1452 #counting,
1453 ),
1454 });
1455 }
1456 }
1457 }
1458 NodeKindAst::Device => {
1459 let Some(driver) = &node.driver else {
1460 continue; };
1462 for dep in &node.deps {
1463 let dep_node = tree.nodes.iter().find(|n| &n.id == dep).ok_or_else(|| {
1464 syn::Error::new(
1465 dep.span(),
1466 format!("device `{}` depends on unknown node `{}`", node.id, dep),
1467 )
1468 })?;
1469 match dep_node.kind {
1470 NodeKindAst::Device => {
1471 return Err(syn::Error::new(
1472 node.id.span(),
1473 "device-to-device dependencies are not supported yet \
1474 (v1 设备独占总线;设备依赖设备留待共享总线)",
1475 ))
1476 }
1477 NodeKindAst::Bus(_) | NodeKindAst::Gpio(_) | NodeKindAst::Peripheral(_) => {}
1478 }
1479 }
1480 devices.push((node, driver));
1481 }
1482 }
1483 }
1484
1485 for (i, (node, _)) in devices.iter().enumerate() {
1487 for dep in &node.deps {
1488 let dep_node = tree.nodes.iter().find(|n| &n.id == dep).unwrap();
1489 if dep_node.prop_bool("shared") {
1490 continue;
1491 }
1492 if let Some((prev, _)) = devices[..i]
1493 .iter()
1494 .find(|(prev, _)| prev.deps.iter().any(|d| d == dep))
1495 {
1496 return Err(syn::Error::new(
1497 node.id.span(),
1498 format!(
1499 "bus `{dep}` is shared by devices `{}` and `{}`; \
1500 shared buses are not supported yet",
1501 prev.id, node.id
1502 ),
1503 ));
1504 }
1505 }
1506 }
1507
1508 if fields.is_empty() {
1509 return Err(syn::Error::new(
1510 Span::call_site(),
1511 "stm32 backend: the tree must declare at least one bus, gpio or periph node",
1512 ));
1513 }
1514
1515 let irqs = bindings.iter().map(|(irq, handlers)| {
1516 let irq = format_ident!("{}", irq);
1517 let mut merged = TokenStream2::new();
1518 for (i, handler) in handlers.iter().enumerate() {
1519 if i > 0 {
1520 merged.extend(quote!(,));
1521 }
1522 merged.extend(handler.clone());
1523 }
1524 quote! {
1525 #irq => #merged;
1526 }
1527 });
1528
1529 let device_tokens = if devices.is_empty() {
1530 TokenStream2::new()
1531 } else {
1532 let fields = devices.iter().map(|(node, driver)| {
1533 let id = &node.id;
1534 quote! { pub #id: #driver }
1535 });
1536 let inits = devices
1537 .iter()
1538 .map(|(node, driver)| -> Result<TokenStream2> {
1539 let id = &node.id;
1540 let dev_ty = format_ident!("{}_Ty", id.to_string());
1541 let id_str = LitStr::new(&id.to_string(), id.span());
1542 let has_shared_spi = node.deps.iter().any(|d| {
1545 tree.nodes.iter().any(|n| {
1546 &n.id == d
1547 && matches!(n.kind, NodeKindAst::Bus(BusKindAst::Spi))
1548 && n.prop_bool("shared")
1549 })
1550 });
1551 let args = node
1552 .deps
1553 .iter()
1554 .filter(|dep| {
1555 if !has_shared_spi {
1556 return true;
1557 }
1558 !matches!(
1559 tree.nodes
1560 .iter()
1561 .find(|n| &n.id == *dep)
1562 .map(|n| n.kind),
1563 Some(NodeKindAst::Gpio(GpioKindAst::Pin))
1564 )
1565 })
1566 .map(|dep| {
1567 let field = format_ident!("{}", dep.to_string());
1568 let dep_node = tree.nodes.iter().find(|n| &n.id == dep).unwrap();
1569 match dep_node.kind {
1570 NodeKindAst::Bus(BusKindAst::I2c) if dep_node.prop_bool("shared") => {
1571 Ok(quote! { self.#field.clone() })
1573 }
1574 NodeKindAst::Bus(BusKindAst::Spi) if dep_node.prop_bool("shared") => {
1575 let cs = node
1577 .deps
1578 .iter()
1579 .find(|d| {
1580 tree.nodes.iter().any(|n| {
1581 &n.id == *d
1582 && matches!(
1583 n.kind,
1584 NodeKindAst::Gpio(GpioKindAst::Pin)
1585 )
1586 })
1587 })
1588 .ok_or_else(|| {
1589 syn::Error::new(
1590 node.id.span(),
1591 format!(
1592 "device `{}` on shared SPI `{dep}` needs a `gpio ...: Pin` CS dependency",
1593 node.id
1594 ),
1595 )
1596 })?;
1597 let cs_field = format_ident!("{}", cs.to_string());
1598 Ok(quote! {
1599 ::embassy_embedded_hal::shared_bus::asynch::spi::SpiDevice::new(
1600 self.#field,
1601 ::embassy_stm32::gpio::Output::new(
1602 self.#cs_field,
1603 ::embassy_stm32::gpio::Level::High,
1604 ::embassy_stm32::gpio::Speed::VeryHigh,
1605 ),
1606 )
1607 })
1608 }
1609 _ => Ok(quote! { self.#field }),
1610 }
1611 })
1612 .collect::<Result<Vec<_>>>()?;
1613 Ok(quote! {
1614 type #dev_ty = #driver;
1616 let #id = #dev_ty::init(#(#args),*, &TREE.node(#id_str).unwrap()).await?;
1617 })
1618 })
1619 .collect::<Result<Vec<_>>>()?;
1620 let members = devices.iter().map(|(node, _)| {
1621 let id = &node.id;
1622 quote! { #id }
1623 });
1624 quote! {
1625 #[allow(non_upper_case_globals)]
1627 pub struct BoardDevices {
1628 #(#fields),*
1629 }
1630
1631 impl Board {
1632 pub async fn init_devices(
1637 self,
1638 ) -> Result<BoardDevices, ::embassy_dt::DeviceError> {
1639 #(#inits)*
1640 Ok(BoardDevices { #(#members),* })
1641 }
1642 }
1643 }
1644 };
1645
1646 let clock_tokens = clock_config_tokens(tree)?;
1647
1648 Ok(quote! {
1649 #[allow(non_upper_case_globals)]
1651 pub struct Board {
1652 #(#fields),*
1653 }
1654
1655 impl Board {
1656 pub fn init(p: ::embassy_stm32::Peripherals) -> Self {
1658 Self { #(#inits)* }
1659 }
1660 }
1661
1662 ::embassy_stm32::bind_interrupts!(struct DtIrqs {
1664 #(#irqs)*
1665 });
1666
1667 #(#statics)*
1668
1669 #device_tokens
1670
1671 #clock_tokens
1672 })
1673}
1674
1675
1676fn periph_ident(node: &DslNode) -> Result<Ident> {
1677 let name = node.prop_str("periph")?;
1678 syn::parse_str::<Ident>(&name).map_err(|_| {
1679 syn::Error::new(
1680 node.id.span(),
1681 "stm32 backend: prop `periph` must be a valid peripheral name like `I2C1`",
1682 )
1683 })
1684}
1685
1686fn chip_name(tree: &DslTree) -> Result<Option<String>> {
1688 Ok(tree
1689 .chip
1690 .as_ref()
1691 .map(|lit| lit.value()))
1692}
1693
1694fn clock_config_tokens(tree: &DslTree) -> Result<TokenStream2> {
1710 let Some(clock) = tree.nodes.iter().find(|n| n.id == "clock") else {
1711 return Ok(TokenStream2::new());
1712 };
1713 if let Some(sysclk) = clock.prop_u32_any(&["system"]) {
1715 return intent_clock(tree, clock, sysclk);
1716 }
1717 let stmts = match chip_name(tree)? {
1718 Some(chip) if chip.contains("h723") => h7_clock_config(clock)?,
1719 Some(chip) if chip.contains("f411") => f4_clock_config(clock)?,
1720 Some(chip) if chip.contains("l476") => l4_clock_config(clock)?,
1721 Some(chip) if chip.contains("g4") => g4_clock_config(clock)?,
1722 Some(chip) if chip.contains("f103") || chip.contains("f1") => {
1723 f1_clock_config(clock)?
1724 }
1725 Some(chip) if chip.contains("f091") || chip.contains("f0") => {
1726 f0_clock_config(clock)?
1727 }
1728 _ => {
1729 return Err(syn::Error::new(
1730 clock.id.span(),
1731 "stm32 backend: `clock` node is not supported for this chip",
1732 ))
1733 }
1734 };
1735 Ok(quote! {
1736 pub fn clock_config() -> ::embassy_stm32::Config {
1738 let mut config = ::embassy_stm32::Config::default();
1739 #(#stmts)*
1740 config
1741 }
1742 })
1743}
1744
1745fn intent_clock(tree: &DslTree, clock: &DslNode, sysclk: u32) -> Result<TokenStream2> {
1748 for key in ["pll1", "pll", "sys", "ahb", "apb1", "clk48"] {
1750 if clock.prop(key).is_some() {
1751 return Err(syn::Error::new(
1752 clock.id.span(),
1753 format!(
1754 "clock: cannot mix intent (`system`) with explicit property `{key}`"
1755 ),
1756 ));
1757 }
1758 }
1759 let usb = clock.prop_u32_any(&["usb"]);
1760 let hse = clock.prop_u32_any(&["hse"]);
1761 let i2s = clock.prop_u32_any(&["i2s"]);
1762 let adc = clock.prop_u32_any(&["adc"]);
1763 let sdmmc = clock.prop_u32_any(&["sdmmc"]);
1764 let mut node = match chip_name(tree)? {
1765 Some(chip) if chip.contains("h723") => {
1766 let plan = plan_h7(sysclk, usb, hse, i2s, adc, sdmmc).map_err(|msg| {
1767 syn::Error::new(clock.id.span(), format!("clock: {msg}"))
1768 })?;
1769 synth_h7_node(&plan)
1770 }
1771 Some(chip) if chip.contains("f411") => {
1772 let plan = plan_f4(sysclk, usb, hse).map_err(|msg| {
1773 syn::Error::new(clock.id.span(), format!("clock: {msg}"))
1774 })?;
1775 synth_f4_node(&plan)
1776 }
1777 Some(chip) if chip.contains("l476") => {
1778 let plan = plan_l4(sysclk, usb, hse).map_err(|msg| {
1779 syn::Error::new(clock.id.span(), format!("clock: {msg}"))
1780 })?;
1781 synth_l4_node(&plan)
1782 }
1783 Some(chip) if chip.contains("g4") => {
1784 let plan = plan_g4(sysclk, usb, hse, adc).map_err(|msg| {
1785 syn::Error::new(clock.id.span(), format!("clock: {msg}"))
1786 })?;
1787 synth_g4_node(&plan)
1788 }
1789 Some(chip) if chip.contains("f103") || chip.contains("f1") => {
1790 let plan = plan_f1(sysclk, usb, hse, adc).map_err(|msg| {
1791 syn::Error::new(clock.id.span(), format!("clock: {msg}"))
1792 })?;
1793 synth_f1_node(&plan)
1794 }
1795 Some(chip) if chip.contains("f091") || chip.contains("f0") => {
1796 let plan = plan_f0(sysclk, usb, hse).map_err(|msg| {
1797 syn::Error::new(clock.id.span(), format!("clock: {msg}"))
1798 })?;
1799 synth_f0_node(&plan)
1800 }
1801 _ => {
1802 return Err(syn::Error::new(
1803 clock.id.span(),
1804 "stm32 backend: `clock` node is not supported for this chip",
1805 ))
1806 }
1807 };
1808 let chip = chip_name(tree)?;
1814 if chip.as_deref().map(|c| c.contains("g4")).unwrap_or(false) {
1815 let has_can = tree
1816 .nodes
1817 .iter()
1818 .any(|n| matches!(n.kind, NodeKindAst::Peripheral(PeriphKindAst::Can)));
1819 if has_can && hse.is_none() && clock.prop_str_opt("fdcan")?.is_none() {
1823 upsert_prop(
1824 &mut node,
1825 "fdcan",
1826 PropValue::Str(LitStr::new("pclk1", Span::call_site())),
1827 );
1828 }
1829 for key in ["fdcan", "adc12", "adc345"] {
1830 if let Some(sel) = clock.prop_str_opt(key)? {
1831 upsert_prop(
1832 &mut node,
1833 key,
1834 PropValue::Str(LitStr::new(&sel, Span::call_site())),
1835 );
1836 }
1837 }
1838 for key in ["pllp", "pllq"] {
1841 if let Some(v) = clock.prop_u32_any(&[key]) {
1842 upsert_prop(
1843 &mut node,
1844 key,
1845 PropValue::U32(LitInt::new(&v.to_string(), Span::call_site())),
1846 );
1847 }
1848 }
1849 }
1850 let stmts = match chip_name(tree)? {
1851 Some(chip) if chip.contains("h723") => h7_clock_config(&node)?,
1852 Some(chip) if chip.contains("f411") => f4_clock_config(&node)?,
1853 Some(chip) if chip.contains("l476") => l4_clock_config(&node)?,
1854 Some(chip) if chip.contains("g4") => g4_clock_config(&node)?,
1855 Some(chip) if chip.contains("f103") || chip.contains("f1") => {
1856 f1_clock_config(&node)?
1857 }
1858 Some(chip) if chip.contains("f091") || chip.contains("f0") => {
1859 f0_clock_config(&node)?
1860 }
1861 _ => unreachable!(),
1862 };
1863 Ok(quote! {
1864 pub fn clock_config() -> ::embassy_stm32::Config {
1866 let mut config = ::embassy_stm32::Config::default();
1867 #(#stmts)*
1868 config
1869 }
1870 })
1871}
1872
1873#[derive(Debug)]
1878struct H7Plan {
1879 prediv: u32,
1880 mul: u32,
1881 divp: u32,
1882 ahb: u32,
1883 apb: u32,
1884 scale1: bool,
1885 usb48: bool,
1886 source_hse: bool,
1887 pll2: Option<(u32, u32, u32, u32)>,
1888 spi123: Option<&'static str>,
1889 adc_sel: Option<&'static str>,
1890 sdmmc_sel: Option<&'static str>,
1891}
1892
1893fn plan_h7(
1896 sysclk: u32,
1897 usb: Option<u32>,
1898 hse: Option<u32>,
1899 i2s: Option<u32>,
1900 adc: Option<u32>,
1901 sdmmc: Option<u32>,
1902) -> std::result::Result<H7Plan, String> {
1903 let input = hse.unwrap_or(64_000_000) as u64;
1905 let source_hse = hse.is_some();
1906 if let Some(h) = hse {
1907 if !(1_000_000..=50_000_000).contains(&h) {
1908 return Err(format!("HSE frequency {h} Hz out of range (1–50 MHz)"));
1909 }
1910 }
1911 const VCO_MIN: u64 = 192_000_000;
1912 const VCO_MAX: u64 = 836_000_000;
1913
1914 if sysclk > 550_000_000 {
1915 return Err(format!("system clock {sysclk} Hz exceeds H723 maximum (550 MHz)"));
1916 }
1917 if let Some(u) = usb {
1918 if u != 48_000_000 {
1919 return Err("only 48 MHz USB clock is supported".into());
1920 }
1921 }
1922
1923 if let (Some(i), Some(a)) = (i2s, adc) {
1926 if i != a {
1927 return Err(
1928 "`i2s` and `adc` share PLL2_P output; use the same frequency".into(),
1929 );
1930 }
1931 }
1932 let freq_p = i2s.or(adc);
1933 let pll2 = plan_h7_pll2(freq_p, sdmmc, input)?;
1934 let spi123 = i2s.map(|_| "pll2_p");
1935 let adc_sel = adc.map(|_| "pll2_p");
1936 let sdmmc_sel = sdmmc.map(|_| "pll2_r");
1937
1938 let mut best: Option<(u64, u32, u32, u32)> = None;
1940 for divp in 1u32..=64 {
1941 let vco = sysclk as u64 * divp as u64;
1942 if !(VCO_MIN..=VCO_MAX).contains(&vco) {
1943 continue;
1944 }
1945 for prediv in 1u32..=64 {
1946 let num = vco * prediv as u64;
1947 if num % input != 0 {
1948 continue;
1949 }
1950 let mul = num / input;
1951 if (4..=512).contains(&mul) {
1952 let cand = (vco, prediv, mul as u32, divp);
1953 if best.as_ref().map_or(true, |b| cand.0 < b.0) {
1954 best = Some(cand);
1955 }
1956 }
1957 }
1958 }
1959 let (_, prediv, mul, divp) = best
1960 .ok_or_else(|| format!("cannot find a valid PLL1 config for {sysclk} Hz"))?;
1961 let ahb = pick_div(sysclk, 275_000_000, &[1, 2, 4, 8, 16, 64, 128, 256, 512])
1962 .ok_or("cannot satisfy AHB frequency limit")?;
1963 let apb = pick_div(sysclk / ahb, 137_500_000, &[1, 2, 4, 8, 16])
1964 .ok_or("cannot satisfy APB frequency limit")?;
1965 Ok(H7Plan {
1966 prediv,
1967 mul,
1968 divp,
1969 ahb,
1970 apb,
1971 scale1: sysclk <= 400_000_000,
1972 usb48: usb.is_some(),
1973 source_hse,
1974 pll2,
1975 spi123,
1976 adc_sel,
1977 sdmmc_sel,
1978 })
1979}
1980
1981fn plan_h7_pll2(
1983 freq_p: Option<u32>,
1984 freq_r: Option<u32>,
1985 input: u64,
1986) -> std::result::Result<Option<(u32, u32, u32, u32)>, String> {
1987 if freq_p.is_none() && freq_r.is_none() {
1988 return Ok(None);
1989 }
1990 let mut best: Option<(u64, u32, u32, u32, u32)> = None;
1991 for divp in 1u32..=128 {
1992 for divr in 1u32..=128 {
1993 let vco_p = freq_p.map(|f| f as u64 * divp as u64);
1994 let vco_r = freq_r.map(|f| f as u64 * divr as u64);
1995 let vco = match (vco_p, vco_r) {
1996 (Some(a), Some(b)) if a == b => a,
1997 (Some(a), None) => a,
1998 (None, Some(b)) => b,
1999 _ => continue,
2000 };
2001 if !(192_000_000..=836_000_000).contains(&vco) {
2002 continue;
2003 }
2004 for prediv in 1u32..=64 {
2005 let num = vco * prediv as u64;
2006 if num % input != 0 {
2007 continue;
2008 }
2009 let mul = num / input;
2010 if (4..=512).contains(&mul) {
2011 let cand = (vco, prediv, mul as u32, divp, divr);
2012 if best.as_ref().map_or(true, |b| cand.0 < b.0) {
2013 best = Some(cand);
2014 }
2015 }
2016 }
2017 }
2018 }
2019 let (_, prediv, mul, divp, divr) = best.ok_or_else(|| {
2020 format!(
2021 "cannot find a valid PLL2 config for peripheral clocks (P={:?}, R={:?})",
2022 freq_p, freq_r
2023 )
2024 })?;
2025 Ok(Some((prediv, mul, divp, divr)))
2026}
2027
2028#[derive(Debug)]
2029struct F4Plan {
2030 hse: u32,
2031 prediv: u32,
2032 mul: u32,
2033 divp: u32,
2034 divq: u32,
2035 usb48: bool,
2036 source_hse: bool,
2037 ahb: u32,
2038 apb1: u32,
2039 apb2: u32,
2040}
2041
2042fn plan_f4(
2049 sysclk: u32,
2050 usb: Option<u32>,
2051 hse: Option<u32>,
2052) -> std::result::Result<F4Plan, String> {
2053 let input = hse.unwrap_or(16_000_000) as u64;
2055 let source_hse = hse.is_some();
2056 if sysclk > 100_000_000 {
2057 return Err(format!(
2058 "system clock {sysclk} Hz exceeds F411 maximum (100 MHz)"
2059 ));
2060 }
2061 if let Some(u) = usb {
2062 if u != 48_000_000 {
2063 return Err("only 48 MHz USB clock is supported".into());
2064 }
2065 }
2066
2067 let mut best: Option<(u64, u32, u32, u32, u32)> = None;
2068 for divp in [2u32, 4, 6, 8] {
2069 let vco = sysclk as u64 * divp as u64;
2070 if !(100_000_000..=432_000_000).contains(&vco) {
2071 continue;
2072 }
2073 let divq = match usb {
2075 Some(u) => {
2076 if vco % u as u64 == 0 {
2077 let q = vco / u as u64;
2078 if (2..=15).contains(&q) {
2079 Some(q as u32)
2080 } else {
2081 continue;
2082 }
2083 } else {
2084 continue;
2085 }
2086 }
2087 None => Some(4),
2088 };
2089 for prediv in 2u32..=63 {
2090 let num = vco * prediv as u64;
2091 if num % input != 0 {
2092 continue;
2093 }
2094 let mul = num / input;
2095 if (4..=432).contains(&mul) {
2096 let cand = (vco, prediv, mul as u32, divp, divq.unwrap_or(4));
2097 if best.as_ref().map_or(true, |b| cand.0 < b.0) {
2098 best = Some(cand);
2099 }
2100 }
2101 }
2102 }
2103 let (_, prediv, mul, divp, divq) = best.ok_or_else(|| {
2104 format!(
2105 "cannot find a valid PLL config for {sysclk} Hz{} on F4 \
2106 (no HSI48; 100 MHz system cannot provide 48 MHz USB, try 96 MHz)",
2107 usb.map(|_| " + 48 MHz USB").unwrap_or("")
2108 )
2109 })?;
2110 let ahb = pick_div(sysclk, 100_000_000, &[1, 2, 4, 8, 16, 64, 128, 256, 512])
2111 .ok_or("cannot satisfy AHB frequency limit")?;
2112 let apb1 = pick_div(sysclk / ahb, 50_000_000, &[1, 2, 4, 8, 16])
2113 .ok_or("cannot satisfy APB1 frequency limit")?;
2114 let apb2 = pick_div(sysclk / ahb, 100_000_000, &[1, 2, 4, 8, 16])
2115 .ok_or("cannot satisfy APB2 frequency limit")?;
2116 Ok(F4Plan {
2117 hse: input as u32,
2118 prediv,
2119 mul,
2120 divp,
2121 divq,
2122 usb48: usb.is_some(),
2123 source_hse,
2124 ahb,
2125 apb1,
2126 apb2,
2127 })
2128}
2129
2130fn pick_div(freq: u32, max: u32, divs: &[u32]) -> Option<u32> {
2132 divs.iter()
2133 .copied()
2134 .find(|&d| freq / d <= max)
2135}
2136
2137fn synth_h7_node(plan: &H7Plan) -> DslNode {
2138 let mut props = vec![
2139 prop(
2140 "source",
2141 PropValue::Str(LitStr::new(
2142 if plan.source_hse { "hse" } else { "hsi" },
2143 Span::call_site(),
2144 )),
2145 ),
2146 prop(
2147 "pll1",
2148 PropValue::Array(vec![plan.prediv, plan.mul, plan.divp]),
2149 ),
2150 prop(
2151 "sys",
2152 PropValue::Str(LitStr::new("pll1_p", Span::call_site())),
2153 ),
2154 prop("ahb", PropValue::U32(LitInt::new(&plan.ahb.to_string(), Span::call_site()))),
2155 prop("apb1", PropValue::U32(LitInt::new(&plan.apb.to_string(), Span::call_site()))),
2156 prop("apb2", PropValue::U32(LitInt::new(&plan.apb.to_string(), Span::call_site()))),
2157 prop("apb3", PropValue::U32(LitInt::new(&plan.apb.to_string(), Span::call_site()))),
2158 prop("apb4", PropValue::U32(LitInt::new(&plan.apb.to_string(), Span::call_site()))),
2159 prop(
2160 "voltage",
2161 PropValue::Str(LitStr::new(
2162 if plan.scale1 { "scale1" } else { "scale0" },
2163 Span::call_site(),
2164 )),
2165 ),
2166 ];
2167 if let Some((prediv, mul, divp, divr)) = plan.pll2 {
2168 props.push(prop(
2169 "pll2",
2170 PropValue::Array(vec![prediv, mul, divp, divr]),
2171 ));
2172 }
2173 if let Some(sel) = plan.spi123 {
2174 props.push(prop(
2175 "spi123sel",
2176 PropValue::Str(LitStr::new(sel, Span::call_site())),
2177 ));
2178 }
2179 if let Some(sel) = plan.adc_sel {
2180 props.push(prop(
2181 "adcsel",
2182 PropValue::Str(LitStr::new(sel, Span::call_site())),
2183 ));
2184 }
2185 if let Some(sel) = plan.sdmmc_sel {
2186 props.push(prop(
2187 "sdmmcsel",
2188 PropValue::Str(LitStr::new(sel, Span::call_site())),
2189 ));
2190 }
2191 if plan.usb48 {
2192 props.push(prop("hsi48", PropValue::Bool(true)));
2193 props.push(prop(
2194 "usb",
2195 PropValue::Str(LitStr::new("hsi48", Span::call_site())),
2196 ));
2197 }
2198 DslNode {
2199 id: Ident::new("clock", Span::call_site()),
2200 kind: NodeKindAst::Device,
2201 driver: None,
2202 props,
2203 deps: Vec::new(),
2204 }
2205}
2206
2207fn synth_f4_node(plan: &F4Plan) -> DslNode {
2208 let mut props = vec![
2209 prop(
2210 "source",
2211 PropValue::Str(LitStr::new(
2212 if plan.source_hse { "hse" } else { "hsi" },
2213 Span::call_site(),
2214 )),
2215 ),
2216 prop(
2217 "pll",
2218 PropValue::Array(vec![plan.prediv, plan.mul, plan.divp, plan.divq]),
2219 ),
2220 prop(
2221 "sys",
2222 PropValue::Str(LitStr::new("pll1_p", Span::call_site())),
2223 ),
2224 prop("ahb", PropValue::U32(LitInt::new(&plan.ahb.to_string(), Span::call_site()))),
2225 prop("apb1", PropValue::U32(LitInt::new(&plan.apb1.to_string(), Span::call_site()))),
2226 prop("apb2", PropValue::U32(LitInt::new(&plan.apb2.to_string(), Span::call_site()))),
2227 ];
2228 if plan.source_hse {
2229 props.push(prop("hse", PropValue::U32(LitInt::new(&plan.hse.to_string(), Span::call_site()))));
2230 }
2231 if plan.usb48 {
2232 props.push(prop(
2233 "clk48",
2234 PropValue::Str(LitStr::new("pll1_q", Span::call_site())),
2235 ));
2236 }
2237 DslNode {
2238 id: Ident::new("clock", Span::call_site()),
2239 kind: NodeKindAst::Device,
2240 driver: None,
2241 props,
2242 deps: Vec::new(),
2243 }
2244}
2245
2246#[derive(Debug)]
2247struct L4Plan {
2248 hse: Option<u32>,
2249 prediv: u32,
2250 mul: u32,
2251 divr: u32,
2252 usb48: bool,
2253}
2254
2255fn plan_l4(
2259 sysclk: u32,
2260 usb: Option<u32>,
2261 hse: Option<u32>,
2262) -> std::result::Result<L4Plan, String> {
2263 if sysclk > 80_000_000 {
2264 return Err(format!(
2265 "system clock {sysclk} Hz exceeds L476 maximum (80 MHz)"
2266 ));
2267 }
2268 if let Some(u) = usb {
2269 if u != 48_000_000 {
2270 return Err("only 48 MHz USB clock is supported".into());
2271 }
2272 }
2273 let input = hse.unwrap_or(16_000_000) as u64;
2274
2275 let mut best: Option<(u64, u32, u32, u32)> = None;
2276 for divr in [2u32, 4, 6, 8] {
2277 let vco = sysclk as u64 * divr as u64;
2278 if !(96_000_000..=344_000_000).contains(&vco) {
2279 continue;
2280 }
2281 for prediv in 1u32..=8 {
2282 let num = vco * prediv as u64;
2283 if num % input != 0 {
2284 continue;
2285 }
2286 let mul = num / input;
2287 if (8..=86).contains(&mul) {
2288 let cand = (vco, prediv, mul as u32, divr);
2289 if best.as_ref().map_or(true, |b| cand.0 < b.0) {
2290 best = Some(cand);
2291 }
2292 }
2293 }
2294 }
2295 let (_, prediv, mul, divr) = best
2296 .ok_or_else(|| format!("cannot find a valid PLL config for {sysclk} Hz"))?;
2297 Ok(L4Plan {
2298 hse,
2299 prediv,
2300 mul,
2301 divr,
2302 usb48: usb.is_some(),
2303 })
2304}
2305
2306fn synth_l4_node(plan: &L4Plan) -> DslNode {
2307 let mut props = vec![
2308 prop(
2309 "source",
2310 PropValue::Str(LitStr::new(
2311 if plan.hse.is_some() { "hse" } else { "hsi" },
2312 Span::call_site(),
2313 )),
2314 ),
2315 prop(
2316 "pll",
2317 PropValue::Array(vec![plan.prediv, plan.mul, plan.divr]),
2318 ),
2319 prop(
2320 "sys",
2321 PropValue::Str(LitStr::new("pll1_r", Span::call_site())),
2322 ),
2323 prop("ahb", PropValue::U32(LitInt::new("1", Span::call_site()))),
2324 prop("apb1", PropValue::U32(LitInt::new("1", Span::call_site()))),
2325 prop("apb2", PropValue::U32(LitInt::new("1", Span::call_site()))),
2326 ];
2327 if let Some(h) = plan.hse {
2328 props.push(prop("hse", PropValue::U32(LitInt::new(&h.to_string(), Span::call_site()))));
2329 }
2330 if plan.usb48 {
2331 props.push(prop(
2334 "msi",
2335 PropValue::Str(LitStr::new("48m", Span::call_site())),
2336 ));
2337 }
2338 DslNode {
2339 id: Ident::new("clock", Span::call_site()),
2340 kind: NodeKindAst::Device,
2341 driver: None,
2342 props,
2343 deps: Vec::new(),
2344 }
2345}
2346
2347#[derive(Debug)]
2348struct G4Plan {
2349 hse: Option<u32>,
2350 prediv: u32,
2351 mul: u32,
2352 divr: u32,
2353 usb48: bool,
2354 adc: bool,
2355 boost: bool,
2356}
2357
2358fn plan_g4(
2365 sysclk: u32,
2366 usb: Option<u32>,
2367 hse: Option<u32>,
2368 adc: Option<u32>,
2369) -> std::result::Result<G4Plan, String> {
2370 if sysclk > 170_000_000 {
2371 return Err(format!(
2372 "system clock {sysclk} Hz exceeds G474 maximum (170 MHz)"
2373 ));
2374 }
2375 if let Some(u) = usb {
2376 if u != 48_000_000 {
2377 return Err("only 48 MHz USB clock is supported".into());
2378 }
2379 }
2380 if let Some(h) = hse {
2381 if !(4_000_000..=48_000_000).contains(&h) {
2382 return Err(format!("HSE frequency {h} Hz out of range (4–48 MHz)"));
2383 }
2384 }
2385 let input = hse.unwrap_or(16_000_000) as u64;
2386
2387 let mut best: Option<(u64, u32, u32, u32)> = None;
2388 for divr in [2u32, 4, 6, 8] {
2389 let vco = sysclk as u64 * divr as u64;
2390 if !(96_000_000..=344_000_000).contains(&vco) {
2391 continue;
2392 }
2393 for prediv in 1u32..=8 {
2394 let in_freq = input / prediv as u64;
2395 if !(2_660_000..=16_000_000).contains(&in_freq) {
2396 continue;
2397 }
2398 let num = vco * prediv as u64;
2399 if num % input != 0 {
2400 continue;
2401 }
2402 let mul = num / input;
2403 if (8..=127).contains(&mul) {
2404 let cand = (vco, prediv, mul as u32, divr);
2405 if best.as_ref().map_or(true, |b| cand.0 < b.0) {
2406 best = Some(cand);
2407 }
2408 }
2409 }
2410 }
2411 let (_, prediv, mul, divr) = best
2412 .ok_or_else(|| format!("cannot find a valid PLL config for {sysclk} Hz"))?;
2413 Ok(G4Plan {
2414 hse,
2415 prediv,
2416 mul,
2417 divr,
2418 usb48: usb.is_some(),
2419 adc: adc.is_some(),
2420 boost: sysclk > 150_000_000,
2421 })
2422}
2423
2424fn synth_g4_node(plan: &G4Plan) -> DslNode {
2425 let mut props = vec![
2426 prop(
2427 "source",
2428 PropValue::Str(LitStr::new(
2429 if plan.hse.is_some() { "hse" } else { "hsi" },
2430 Span::call_site(),
2431 )),
2432 ),
2433 prop(
2434 "pll",
2435 PropValue::Array(vec![plan.prediv, plan.mul, plan.divr]),
2436 ),
2437 prop(
2438 "sys",
2439 PropValue::Str(LitStr::new("pll1_r", Span::call_site())),
2440 ),
2441 prop("ahb", PropValue::U32(LitInt::new("1", Span::call_site()))),
2442 prop("apb1", PropValue::U32(LitInt::new("1", Span::call_site()))),
2443 prop("apb2", PropValue::U32(LitInt::new("1", Span::call_site()))),
2444 ];
2445 if let Some(h) = plan.hse {
2446 props.push(prop("hse", PropValue::U32(LitInt::new(&h.to_string(), Span::call_site()))));
2447 }
2448 if plan.usb48 {
2449 props.push(prop("hsi48", PropValue::Bool(true)));
2452 props.push(prop("hsi48_sync", PropValue::Bool(true)));
2453 }
2454 if plan.adc {
2455 props.push(prop(
2457 "adc12",
2458 PropValue::Str(LitStr::new("sys", Span::call_site())),
2459 ));
2460 }
2461 if plan.boost {
2462 props.push(prop("boost", PropValue::Bool(true)));
2463 }
2464 DslNode {
2465 id: Ident::new("clock", Span::call_site()),
2466 kind: NodeKindAst::Device,
2467 driver: None,
2468 props,
2469 deps: Vec::new(),
2470 }
2471}
2472
2473#[derive(Debug)]
2474struct F1Plan {
2475 hse: Option<u32>,
2476 prediv: u32,
2477 mul: u32,
2478 apb1: u32,
2479 adc_pre: Option<u32>,
2480 usb48: bool,
2481}
2482
2483fn plan_f1(
2492 sysclk: u32,
2493 usb: Option<u32>,
2494 hse: Option<u32>,
2495 adc: Option<u32>,
2496) -> std::result::Result<F1Plan, String> {
2497 if let Some(h) = hse {
2498 if !(4_000_000..=16_000_000).contains(&h) {
2499 return Err(format!("HSE frequency {h} Hz out of range (4–16 MHz)"));
2500 }
2501 }
2502 let max_sys = if hse.is_some() { 72_000_000 } else { 64_000_000 };
2503 if sysclk > max_sys {
2504 return Err(format!(
2505 "system clock {sysclk} Hz exceeds F1 maximum ({max_sys} Hz, \
2506 HSI 上限 64 MHz,72 MHz 需要 HSE)"
2507 ));
2508 }
2509 if let Some(u) = usb {
2510 if u != 48_000_000 {
2511 return Err("only 48 MHz USB clock is supported".into());
2512 }
2513 if sysclk != 72_000_000 && sysclk != 48_000_000 {
2515 return Err(
2516 "F1 USB requires SYSCLK = 72 MHz (with HSE) or 48 MHz (HSI)".into(),
2517 );
2518 }
2519 }
2520 let input = hse.unwrap_or(8_000_000) as u64;
2521
2522 let mut best: Option<(u32, u32)> = None;
2523 for prediv in 1u32..=2 {
2524 if hse.is_none() && prediv != 2 {
2525 continue;
2527 }
2528 let in_freq = input / prediv as u64;
2529 if !(1_000_000..=25_000_000).contains(&in_freq) {
2530 continue;
2531 }
2532 if sysclk as u64 % in_freq != 0 {
2533 continue;
2534 }
2535 let mul = sysclk as u64 / in_freq;
2536 if (2..=16).contains(&mul) {
2537 best = Some((prediv, mul as u32));
2538 }
2539 }
2540 let (prediv, mul) = best
2541 .ok_or_else(|| format!("cannot find a valid PLL config for {sysclk} Hz"))?;
2542
2543 let apb1 = if sysclk > 36_000_000 { 2 } else { 1 };
2545
2546 let adc_pre = adc
2548 .map(|_| {
2549 [2u32, 4, 6, 8]
2550 .into_iter()
2551 .find(|pre| sysclk / pre <= 14_000_000)
2552 .ok_or_else(|| format!("cannot find ADC prescaler for {sysclk} Hz"))
2553 })
2554 .transpose()?;
2555
2556 Ok(F1Plan {
2557 hse,
2558 prediv,
2559 mul,
2560 apb1,
2561 adc_pre,
2562 usb48: usb.is_some(),
2563 })
2564}
2565
2566fn synth_f1_node(plan: &F1Plan) -> DslNode {
2567 let mut props = vec![
2568 prop(
2569 "source",
2570 PropValue::Str(LitStr::new(
2571 if plan.hse.is_some() { "hse" } else { "hsi" },
2572 Span::call_site(),
2573 )),
2574 ),
2575 prop(
2576 "pll",
2577 PropValue::Array(vec![plan.prediv, plan.mul]),
2578 ),
2579 prop(
2580 "sys",
2581 PropValue::Str(LitStr::new("pll1_p", Span::call_site())),
2582 ),
2583 prop("ahb", PropValue::U32(LitInt::new("1", Span::call_site()))),
2584 prop(
2585 "apb1",
2586 PropValue::U32(LitInt::new(&plan.apb1.to_string(), Span::call_site())),
2587 ),
2588 prop("apb2", PropValue::U32(LitInt::new("1", Span::call_site()))),
2589 ];
2590 if let Some(h) = plan.hse {
2591 props.push(prop("hse", PropValue::U32(LitInt::new(&h.to_string(), Span::call_site()))));
2592 }
2593 if let Some(pre) = plan.adc_pre {
2594 props.push(prop(
2595 "adc_pre",
2596 PropValue::U32(LitInt::new(&pre.to_string(), Span::call_site())),
2597 ));
2598 }
2599 let _ = plan.usb48; DslNode {
2601 id: Ident::new("clock", Span::call_site()),
2602 kind: NodeKindAst::Device,
2603 driver: None,
2604 props,
2605 deps: Vec::new(),
2606 }
2607}
2608
2609#[derive(Debug)]
2610struct F0Plan {
2611 hse: Option<u32>,
2612 prediv: u32,
2613 mul: u32,
2614 usb48: bool,
2615}
2616
2617fn plan_f0(
2624 sysclk: u32,
2625 usb: Option<u32>,
2626 hse: Option<u32>,
2627) -> std::result::Result<F0Plan, String> {
2628 if sysclk > 48_000_000 {
2629 return Err(format!(
2630 "system clock {sysclk} Hz exceeds F091 maximum (48 MHz)"
2631 ));
2632 }
2633 if let Some(u) = usb {
2634 if u != 48_000_000 {
2635 return Err("only 48 MHz USB clock is supported".into());
2636 }
2637 }
2638 if let Some(h) = hse {
2639 if !(4_000_000..=32_000_000).contains(&h) {
2640 return Err(format!("HSE frequency {h} Hz out of range (4–32 MHz)"));
2641 }
2642 }
2643 let input = hse.unwrap_or(8_000_000) as u64;
2644
2645 let mut best: Option<(u32, u32)> = None;
2646 for prediv in 1u32..=16 {
2647 let in_freq = input / prediv as u64;
2648 if !(1_000_000..=24_000_000).contains(&in_freq) {
2649 continue;
2650 }
2651 if sysclk as u64 % in_freq != 0 {
2652 continue;
2653 }
2654 let mul = sysclk as u64 / in_freq;
2655 let out = in_freq * mul;
2656 if best.is_none()
2657 && (2..=16).contains(&mul)
2658 && (16_000_000..=48_000_000).contains(&out)
2659 {
2660 best = Some((prediv, mul as u32));
2661 }
2662 }
2663 let (prediv, mul) = best
2664 .ok_or_else(|| format!("cannot find a valid PLL config for {sysclk} Hz"))?;
2665 Ok(F0Plan {
2666 hse,
2667 prediv,
2668 mul,
2669 usb48: usb.is_some(),
2670 })
2671}
2672
2673fn synth_f0_node(plan: &F0Plan) -> DslNode {
2674 let mut props = vec![
2675 prop(
2676 "source",
2677 PropValue::Str(LitStr::new(
2678 if plan.hse.is_some() { "hse" } else { "hsi" },
2679 Span::call_site(),
2680 )),
2681 ),
2682 prop(
2683 "pll",
2684 PropValue::Array(vec![plan.prediv, plan.mul]),
2685 ),
2686 prop(
2687 "sys",
2688 PropValue::Str(LitStr::new("pll1_p", Span::call_site())),
2689 ),
2690 prop("ahb", PropValue::U32(LitInt::new("1", Span::call_site()))),
2691 prop("apb1", PropValue::U32(LitInt::new("1", Span::call_site()))),
2692 ];
2693 if let Some(h) = plan.hse {
2694 props.push(prop("hse", PropValue::U32(LitInt::new(&h.to_string(), Span::call_site()))));
2695 }
2696 if plan.usb48 {
2697 props.push(prop("hsi48", PropValue::Bool(true)));
2699 props.push(prop("hsi48_sync", PropValue::Bool(true)));
2700 }
2701 DslNode {
2702 id: Ident::new("clock", Span::call_site()),
2703 kind: NodeKindAst::Device,
2704 driver: None,
2705 props,
2706 deps: Vec::new(),
2707 }
2708}
2709
2710fn prop(key: &str, value: PropValue) -> DslProp {
2711 DslProp {
2712 key: Ident::new(key, Span::call_site()),
2713 value,
2714 }
2715}
2716
2717fn upsert_prop(node: &mut DslNode, key: &str, value: PropValue) {
2719 node.props.retain(|p| p.key != key);
2720 node.props.push(prop(key, value));
2721}
2722
2723fn h7_clock_config(node: &DslNode) -> Result<Vec<TokenStream2>> {
2724 let mut stmts = Vec::new();
2725
2726 if let Some(hsi) = node.prop_str_opt("hsi")? {
2727 let v = match hsi.as_str() {
2728 "div1" => quote!(DIV1),
2729 "div2" => quote!(DIV2),
2730 "div4" => quote!(DIV4),
2731 "div8" => quote!(DIV8),
2732 other => {
2733 return Err(syn::Error::new(
2734 node.id.span(),
2735 format!("clock: unsupported `hsi` value `{other}` (div1/div2/div4/div8)"),
2736 ))
2737 }
2738 };
2739 stmts.push(quote! {
2740 config.rcc.hsi = Some(::embassy_stm32::rcc::HSIPrescaler::#v);
2741 });
2742 }
2743 if node.prop_bool("csi") {
2744 stmts.push(quote! { config.rcc.csi = true; });
2745 }
2746 if node.prop_bool("hsi48") {
2747 stmts.push(quote! {
2748 config.rcc.hsi48 = Some(::embassy_stm32::rcc::Hsi48Config { sync_from_usb: true });
2749 });
2750 }
2751 if let Some(pll) = node.prop_array("pll1") {
2752 if pll.len() < 3 {
2753 return Err(syn::Error::new(
2754 node.id.span(),
2755 "clock: `pll1` needs at least <prediv mul divp>",
2756 ));
2757 }
2758 let source = node.prop_str_opt("source")?.ok_or_else(|| {
2759 syn::Error::new(node.id.span(), "clock: `source` is required with `pll1`")
2760 })?;
2761 let src = match source.as_str() {
2762 "hsi" => quote!(HSI),
2763 "csi" => quote!(CSI),
2764 "hse" => quote!(HSE),
2765 other => {
2766 return Err(syn::Error::new(
2767 node.id.span(),
2768 format!("clock: unsupported `source` `{other}` (hsi/csi/hse)"),
2769 ))
2770 }
2771 };
2772 let pre = format_ident!("DIV{}", pll[0]);
2773 let mul = format_ident!("MUL{}", pll[1]);
2774 let divp = format_ident!("DIV{}", pll[2]);
2775 let divq = match pll.get(3) {
2776 Some(n) => {
2777 let v = format_ident!("DIV{}", n);
2778 quote!(Some(::embassy_stm32::rcc::PllDiv::#v))
2779 }
2780 None => quote!(None),
2781 };
2782 let divr = match pll.get(4) {
2783 Some(n) => {
2784 let v = format_ident!("DIV{}", n);
2785 quote!(Some(::embassy_stm32::rcc::PllDiv::#v))
2786 }
2787 None => quote!(None),
2788 };
2789 stmts.push(quote! {
2790 config.rcc.pll1 = Some(::embassy_stm32::rcc::Pll {
2791 source: ::embassy_stm32::rcc::PllSource::#src,
2792 prediv: ::embassy_stm32::rcc::PllPreDiv::#pre,
2793 mul: ::embassy_stm32::rcc::PllMul::#mul,
2794 divp: Some(::embassy_stm32::rcc::PllDiv::#divp),
2795 divq: #divq,
2796 divr: #divr,
2797 });
2798 });
2799 }
2800 if let Some(sys) = node.prop_str_opt("sys")? {
2801 let v = match sys.as_str() {
2802 "hsi" => quote!(HSI),
2803 "csi" => quote!(CSI),
2804 "hse" => quote!(HSE),
2805 "pll1_p" => quote!(PLL1_P),
2806 "pll2_p" => quote!(PLL2_P),
2807 "pll3_p" => quote!(PLL3_P),
2808 other => {
2809 return Err(syn::Error::new(
2810 node.id.span(),
2811 format!("clock: unsupported `sys` `{other}`"),
2812 ))
2813 }
2814 };
2815 stmts.push(quote! { config.rcc.sys = ::embassy_stm32::rcc::Sysclk::#v; });
2816 }
2817 if let Some(n) = node.prop_u32_any(&["ahb"]) {
2818 let v = format_ident!("DIV{}", n);
2819 stmts.push(quote! { config.rcc.ahb_pre = ::embassy_stm32::rcc::AHBPrescaler::#v; });
2820 }
2821 for key in ["apb1", "apb2", "apb3", "apb4"] {
2822 if let Some(n) = node.prop_u32_any(&[key]) {
2823 let field = format_ident!("{}_pre", key);
2824 let v = format_ident!("DIV{}", n);
2825 stmts.push(quote! { config.rcc.#field = ::embassy_stm32::rcc::APBPrescaler::#v; });
2826 }
2827 }
2828 if let Some(usb) = node.prop_str_opt("usb")? {
2829 let v = match usb.as_str() {
2830 "disable" => quote!(DISABLE),
2831 "pll1_q" => quote!(PLL1_Q),
2832 "pll3_q" => quote!(PLL3_Q),
2833 "hsi48" => quote!(HSI48),
2834 other => {
2835 return Err(syn::Error::new(
2836 node.id.span(),
2837 format!("clock: unsupported `usb` `{other}`"),
2838 ))
2839 }
2840 };
2841 stmts.push(quote! { config.rcc.mux.usbsel = ::embassy_stm32::rcc::mux::Usbsel::#v; });
2842 }
2843 if let Some(pll2) = node.prop_array("pll2") {
2844 if pll2.len() < 4 {
2845 return Err(syn::Error::new(
2846 node.id.span(),
2847 "clock: `pll2` needs <prediv mul divp divr>",
2848 ));
2849 }
2850 let source = node.prop_str_opt("source")?.ok_or_else(|| {
2851 syn::Error::new(node.id.span(), "clock: `source` is required with `pll2`")
2852 })?;
2853 let src = match source.as_str() {
2854 "hsi" => quote!(HSI),
2855 "csi" => quote!(CSI),
2856 "hse" => quote!(HSE),
2857 other => {
2858 return Err(syn::Error::new(
2859 node.id.span(),
2860 format!("clock: unsupported `source` `{other}` (hsi/csi/hse)"),
2861 ))
2862 }
2863 };
2864 let pre = format_ident!("DIV{}", pll2[0]);
2865 let mul = format_ident!("MUL{}", pll2[1]);
2866 let divp = format_ident!("DIV{}", pll2[2]);
2867 let divr = format_ident!("DIV{}", pll2[3]);
2868 stmts.push(quote! {
2869 config.rcc.pll2 = Some(::embassy_stm32::rcc::Pll {
2870 source: ::embassy_stm32::rcc::PllSource::#src,
2871 prediv: ::embassy_stm32::rcc::PllPreDiv::#pre,
2872 mul: ::embassy_stm32::rcc::PllMul::#mul,
2873 divp: Some(::embassy_stm32::rcc::PllDiv::#divp),
2874 divq: None,
2875 divr: Some(::embassy_stm32::rcc::PllDiv::#divr),
2876 });
2877 });
2878 }
2879 if let Some(sel) = node.prop_str_opt("spi123sel")? {
2880 let v = match sel.as_str() {
2881 "pll1_q" => quote!(PLL1_Q),
2882 "pll2_p" => quote!(PLL2_P),
2883 "pll3_p" => quote!(PLL3_P),
2884 "per" => quote!(PER),
2885 other => {
2886 return Err(syn::Error::new(
2887 node.id.span(),
2888 format!("clock: unsupported `spi123sel` `{other}`"),
2889 ))
2890 }
2891 };
2892 stmts.push(quote! { config.rcc.mux.spi123sel = ::embassy_stm32::rcc::mux::Saisel::#v; });
2893 }
2894 if let Some(sel) = node.prop_str_opt("adcsel")? {
2895 let v = match sel.as_str() {
2896 "pll2_p" => quote!(PLL2_P),
2897 "pll3_r" => quote!(PLL3_R),
2898 "per" => quote!(PER),
2899 other => {
2900 return Err(syn::Error::new(
2901 node.id.span(),
2902 format!("clock: unsupported `adcsel` `{other}`"),
2903 ))
2904 }
2905 };
2906 stmts.push(quote! { config.rcc.mux.adcsel = ::embassy_stm32::rcc::mux::Adcsel::#v; });
2907 }
2908 if let Some(sel) = node.prop_str_opt("sdmmcsel")? {
2909 let v = match sel.as_str() {
2910 "pll1_q" => quote!(PLL1_Q),
2911 "pll2_r" => quote!(PLL2_R),
2912 other => {
2913 return Err(syn::Error::new(
2914 node.id.span(),
2915 format!("clock: unsupported `sdmmcsel` `{other}`"),
2916 ))
2917 }
2918 };
2919 stmts.push(quote! { config.rcc.mux.sdmmcsel = ::embassy_stm32::rcc::mux::Sdmmcsel::#v; });
2920 }
2921 if let Some(voltage) = node.prop_str_opt("voltage")? {
2922 let v = match voltage.as_str() {
2923 "scale0" => quote!(Scale0),
2924 "scale1" => quote!(Scale1),
2925 "scale2" => quote!(Scale2),
2926 "scale3" => quote!(Scale3),
2927 other => {
2928 return Err(syn::Error::new(
2929 node.id.span(),
2930 format!("clock: unsupported `voltage` `{other}`"),
2931 ))
2932 }
2933 };
2934 stmts.push(quote! { config.rcc.voltage_scale = ::embassy_stm32::rcc::VoltageScale::#v; });
2935 }
2936 Ok(stmts)
2937}
2938
2939fn f4_clock_config(node: &DslNode) -> Result<Vec<TokenStream2>> {
2940 let mut stmts = Vec::new();
2941
2942 if let Some(hse) = node.prop_u32_any(&["hse"]) {
2943 let mode = match node.prop_str_opt("hse-mode")?.as_deref() {
2944 None | Some("oscillator") => quote!(Oscillator),
2945 Some("bypass") => quote!(Bypass),
2946 Some(other) => {
2947 return Err(syn::Error::new(
2948 node.id.span(),
2949 format!("clock: unsupported `hse-mode` `{other}` (oscillator/bypass)"),
2950 ))
2951 }
2952 };
2953 stmts.push(quote! {
2954 config.rcc.hse = Some(::embassy_stm32::rcc::Hse {
2955 freq: ::embassy_stm32::time::Hertz(#hse),
2956 mode: ::embassy_stm32::rcc::HseMode::#mode,
2957 });
2958 });
2959 }
2960 if let Some(pll) = node.prop_array("pll") {
2961 if pll.len() < 4 {
2962 return Err(syn::Error::new(
2963 node.id.span(),
2964 "clock: `pll` needs <prediv mul divp divq>",
2965 ));
2966 }
2967 let source = node.prop_str_opt("source")?.ok_or_else(|| {
2968 syn::Error::new(node.id.span(), "clock: `source` is required with `pll`")
2969 })?;
2970 let src = match source.as_str() {
2971 "hse" => quote!(HSE),
2972 "hsi" => quote!(HSI),
2973 other => {
2974 return Err(syn::Error::new(
2975 node.id.span(),
2976 format!("clock: unsupported `source` `{other}` (hse/hsi)"),
2977 ))
2978 }
2979 };
2980 let pre = format_ident!("DIV{}", pll[0]);
2981 let mul = format_ident!("MUL{}", pll[1]);
2982 let divp = format_ident!("DIV{}", pll[2]);
2983 let divq = format_ident!("DIV{}", pll[3]);
2984 stmts.push(quote! {
2985 config.rcc.pll_src = ::embassy_stm32::rcc::PllSource::#src;
2986 config.rcc.pll = Some(::embassy_stm32::rcc::Pll {
2987 prediv: ::embassy_stm32::rcc::PllPreDiv::#pre,
2988 mul: ::embassy_stm32::rcc::PllMul::#mul,
2989 divp: Some(::embassy_stm32::rcc::PllPDiv::#divp),
2990 divq: Some(::embassy_stm32::rcc::PllQDiv::#divq),
2991 divr: None,
2992 });
2993 });
2994 }
2995 if let Some(sys) = node.prop_str_opt("sys")? {
2996 let v = match sys.as_str() {
2997 "hsi" => quote!(HSI),
2998 "hse" => quote!(HSE),
2999 "pll1_p" => quote!(PLL1_P),
3000 other => {
3001 return Err(syn::Error::new(
3002 node.id.span(),
3003 format!("clock: unsupported `sys` `{other}`"),
3004 ))
3005 }
3006 };
3007 stmts.push(quote! { config.rcc.sys = ::embassy_stm32::rcc::Sysclk::#v; });
3008 }
3009 if let Some(n) = node.prop_u32_any(&["ahb"]) {
3010 let v = format_ident!("DIV{}", n);
3011 stmts.push(quote! { config.rcc.ahb_pre = ::embassy_stm32::rcc::AHBPrescaler::#v; });
3012 }
3013 for key in ["apb1", "apb2"] {
3014 if let Some(n) = node.prop_u32_any(&[key]) {
3015 let field = format_ident!("{}_pre", key);
3016 let v = format_ident!("DIV{}", n);
3017 stmts.push(quote! { config.rcc.#field = ::embassy_stm32::rcc::APBPrescaler::#v; });
3018 }
3019 }
3020 if let Some(clk48) = node.prop_str_opt("clk48")? {
3021 let v = match clk48.as_str() {
3022 "pll1_q" => quote!(PLL1_Q),
3023 "pll_sai_q" => quote!(PLLSAI1_Q),
3024 other => {
3025 return Err(syn::Error::new(
3026 node.id.span(),
3027 format!("clock: unsupported `clk48` `{other}` (pll1_q/pll_sai_q)"),
3028 ))
3029 }
3030 };
3031 stmts.push(quote! { config.rcc.mux.clk48sel = ::embassy_stm32::rcc::mux::Clk48sel::#v; });
3032 }
3033 Ok(stmts)
3034}
3035
3036fn l4_clock_config(node: &DslNode) -> Result<Vec<TokenStream2>> {
3037 let mut stmts = Vec::new();
3038
3039 if let Some(source) = node.prop_str_opt("source")? {
3040 if source == "hsi" {
3041 stmts.push(quote! { config.rcc.hsi = true; });
3043 }
3044 }
3045 if let Some(hse) = node.prop_u32_any(&["hse"]) {
3046 let mode = match node.prop_str_opt("hse-mode")?.as_deref() {
3047 None | Some("oscillator") => quote!(Oscillator),
3048 Some("bypass") => quote!(Bypass),
3049 Some(other) => {
3050 return Err(syn::Error::new(
3051 node.id.span(),
3052 format!("clock: unsupported `hse-mode` `{other}`"),
3053 ))
3054 }
3055 };
3056 stmts.push(quote! {
3057 config.rcc.hse = Some(::embassy_stm32::rcc::Hse {
3058 freq: ::embassy_stm32::time::Hertz(#hse),
3059 mode: ::embassy_stm32::rcc::HseMode::#mode,
3060 });
3061 });
3062 }
3063 if let Some(pll) = node.prop_array("pll") {
3064 if pll.len() < 3 {
3066 return Err(syn::Error::new(
3067 node.id.span(),
3068 "clock: `pll` needs <prediv mul divr> on L4",
3069 ));
3070 }
3071 let pre = format_ident!("DIV{}", pll[0]);
3072 let mul = format_ident!("MUL{}", pll[1]);
3073 let divr = format_ident!("DIV{}", pll[2]);
3074 let src = match node.prop_str_opt("source")?.as_deref() {
3075 None | Some("hsi") => quote!(HSI),
3076 Some("hse") => quote!(HSE),
3077 Some("msi") => quote!(MSI),
3078 Some(other) => {
3079 return Err(syn::Error::new(
3080 node.id.span(),
3081 format!("clock: unsupported `source` `{other}`"),
3082 ))
3083 }
3084 };
3085 stmts.push(quote! {
3086 config.rcc.pll = Some(::embassy_stm32::rcc::Pll {
3087 source: ::embassy_stm32::rcc::PllSource::#src,
3088 prediv: ::embassy_stm32::rcc::PllPreDiv::#pre,
3089 mul: ::embassy_stm32::rcc::PllMul::#mul,
3090 divp: None,
3091 divq: None,
3092 divr: Some(::embassy_stm32::rcc::PllRDiv::#divr),
3093 });
3094 });
3095 }
3096 if let Some(sys) = node.prop_str_opt("sys")? {
3097 let v = match sys.as_str() {
3098 "msi" => quote!(MSI),
3099 "hsi" => quote!(HSI),
3100 "hse" => quote!(HSE),
3101 "pll1_r" => quote!(PLL1_R),
3102 other => {
3103 return Err(syn::Error::new(
3104 node.id.span(),
3105 format!("clock: unsupported `sys` `{other}`"),
3106 ))
3107 }
3108 };
3109 stmts.push(quote! { config.rcc.sys = ::embassy_stm32::rcc::Sysclk::#v; });
3110 }
3111 if let Some(n) = node.prop_u32_any(&["ahb"]) {
3112 let v = format_ident!("DIV{}", n);
3113 stmts.push(quote! { config.rcc.ahb_pre = ::embassy_stm32::rcc::AHBPrescaler::#v; });
3114 }
3115 for key in ["apb1", "apb2"] {
3116 if let Some(n) = node.prop_u32_any(&[key]) {
3117 let field = format_ident!("{}_pre", key);
3118 let v = format_ident!("DIV{}", n);
3119 stmts.push(quote! { config.rcc.#field = ::embassy_stm32::rcc::APBPrescaler::#v; });
3120 }
3121 }
3122 if node.prop_bool("hsi48") {
3123 stmts.push(quote! {
3124 config.rcc.hsi48 = Some(::embassy_stm32::rcc::Hsi48Config::default());
3125 });
3126 }
3127 if let Some(msi) = node.prop_str_opt("msi")? {
3128 let v = match msi.as_str() {
3129 "48m" => quote!(RANGE48M),
3130 "24m" => quote!(RANGE24M),
3131 "16m" => quote!(RANGE16M),
3132 "4m" => quote!(RANGE4M),
3133 "2m" => quote!(RANGE2M),
3134 "1m" => quote!(RANGE1M),
3135 other => {
3136 return Err(syn::Error::new(
3137 node.id.span(),
3138 format!("clock: unsupported `msi` range `{other}`"),
3139 ))
3140 }
3141 };
3142 stmts.push(quote! { config.rcc.msi = Some(::embassy_stm32::rcc::MSIRange::#v); });
3143 }
3144 if let Some(voltage) = node.prop_str_opt("voltage")? {
3145 let v = match voltage.as_str() {
3146 "range1" => quote!(RANGE1),
3147 "range2" => quote!(RANGE2),
3148 other => {
3149 return Err(syn::Error::new(
3150 node.id.span(),
3151 format!("clock: unsupported `voltage` `{other}`"),
3152 ))
3153 }
3154 };
3155 stmts.push(quote! { config.rcc.voltage_scale = ::embassy_stm32::rcc::VoltageScale::#v; });
3156 }
3157 Ok(stmts)
3158}
3159
3160fn g4_clock_config(node: &DslNode) -> Result<Vec<TokenStream2>> {
3161 let mut stmts = Vec::new();
3162
3163 if let Some(source) = node.prop_str_opt("source")? {
3164 if source == "hsi" {
3165 stmts.push(quote! { config.rcc.hsi = true; });
3167 }
3168 }
3169 if let Some(hse) = node.prop_u32_any(&["hse"]) {
3170 let mode = match node.prop_str_opt("hse-mode")?.as_deref() {
3171 None | Some("oscillator") => quote!(Oscillator),
3172 Some("bypass") => quote!(Bypass),
3173 Some(other) => {
3174 return Err(syn::Error::new(
3175 node.id.span(),
3176 format!("clock: unsupported `hse-mode` `{other}`"),
3177 ))
3178 }
3179 };
3180 stmts.push(quote! {
3181 config.rcc.hse = Some(::embassy_stm32::rcc::Hse {
3182 freq: ::embassy_stm32::time::Hertz(#hse),
3183 mode: ::embassy_stm32::rcc::HseMode::#mode,
3184 });
3185 });
3186 }
3187 if let Some(pll) = node.prop_array("pll") {
3188 if pll.len() < 3 {
3193 return Err(syn::Error::new(
3194 node.id.span(),
3195 "clock: `pll` needs <prediv mul divr> on G4",
3196 ));
3197 }
3198 let pre = format_ident!("DIV{}", pll[0]);
3199 let mul = format_ident!("MUL{}", pll[1]);
3200 let divr = format_ident!("DIV{}", pll[2]);
3201 let src = match node.prop_str_opt("source")?.as_deref() {
3202 None | Some("hsi") => quote!(HSI),
3203 Some("hse") => quote!(HSE),
3204 Some("msi") => quote!(MSI),
3205 Some(other) => {
3206 return Err(syn::Error::new(
3207 node.id.span(),
3208 format!("clock: unsupported `source` `{other}`"),
3209 ))
3210 }
3211 };
3212 let divp = match node.prop_u32_any(&["pllp"]) {
3213 Some(n) if (2..=31).contains(&n) => {
3214 let v = format_ident!("DIV{}", n);
3215 quote!(Some(::embassy_stm32::rcc::PllPDiv::#v))
3216 }
3217 Some(n) => {
3218 return Err(syn::Error::new(
3219 node.id.span(),
3220 format!("clock: `pllp` must be 2..=31 on G4, got {n}"),
3221 ))
3222 }
3223 None => quote!(None),
3224 };
3225 let divq = match node.prop_u32_any(&["pllq"]) {
3226 Some(n) if [2, 4, 6, 8].contains(&n) => {
3227 let v = format_ident!("DIV{}", n);
3228 quote!(Some(::embassy_stm32::rcc::PllQDiv::#v))
3229 }
3230 Some(n) => {
3231 return Err(syn::Error::new(
3232 node.id.span(),
3233 format!("clock: `pllq` must be 2/4/6/8 on G4, got {n}"),
3234 ))
3235 }
3236 None => quote!(None),
3237 };
3238 stmts.push(quote! {
3239 config.rcc.pll = Some(::embassy_stm32::rcc::Pll {
3240 source: ::embassy_stm32::rcc::PllSource::#src,
3241 prediv: ::embassy_stm32::rcc::PllPreDiv::#pre,
3242 mul: ::embassy_stm32::rcc::PllMul::#mul,
3243 divp: #divp,
3244 divq: #divq,
3245 divr: Some(::embassy_stm32::rcc::PllRDiv::#divr),
3246 });
3247 });
3248 }
3249 if let Some(sys) = node.prop_str_opt("sys")? {
3250 let v = match sys.as_str() {
3251 "hsi" => quote!(HSI),
3252 "hse" => quote!(HSE),
3253 "pll1_r" => quote!(PLL1_R),
3254 other => {
3255 return Err(syn::Error::new(
3256 node.id.span(),
3257 format!("clock: unsupported `sys` `{other}`"),
3258 ))
3259 }
3260 };
3261 stmts.push(quote! { config.rcc.sys = ::embassy_stm32::rcc::Sysclk::#v; });
3262 }
3263 if let Some(n) = node.prop_u32_any(&["ahb"]) {
3264 let v = format_ident!("DIV{}", n);
3265 stmts.push(quote! { config.rcc.ahb_pre = ::embassy_stm32::rcc::AHBPrescaler::#v; });
3266 }
3267 for key in ["apb1", "apb2"] {
3268 if let Some(n) = node.prop_u32_any(&[key]) {
3269 let field = format_ident!("{}_pre", key);
3270 let v = format_ident!("DIV{}", n);
3271 stmts.push(quote! { config.rcc.#field = ::embassy_stm32::rcc::APBPrescaler::#v; });
3272 }
3273 }
3274 if node.prop_bool("hsi48") {
3275 let sync = node.prop_bool("hsi48_sync");
3276 stmts.push(quote! {
3277 config.rcc.hsi48 = Some(::embassy_stm32::rcc::Hsi48Config {
3278 sync_from_usb: #sync,
3279 });
3280 });
3281 }
3282 if node.prop_bool("boost") {
3283 stmts.push(quote! { config.rcc.boost = true; });
3284 }
3285 if let Some(sel) = node.prop_str_opt("clk48")? {
3288 let v = match sel.as_str() {
3289 "hsi48" => quote!(HSI48),
3290 "pll1_q" => quote!(PLL1_Q),
3291 other => {
3292 return Err(syn::Error::new(
3293 node.id.span(),
3294 format!("clock: unsupported `clk48` `{other}` (hsi48/pll1_q)"),
3295 ))
3296 }
3297 };
3298 stmts.push(quote! { config.rcc.mux.clk48sel = ::embassy_stm32::rcc::mux::Clk48sel::#v; });
3299 }
3300 if let Some(sel) = node.prop_str_opt("adc12")? {
3301 let v = match sel.as_str() {
3302 "disable" => quote!(DISABLE),
3303 "pll1_p" => quote!(PLL1_P),
3304 "sys" => quote!(SYS),
3305 other => {
3306 return Err(syn::Error::new(
3307 node.id.span(),
3308 format!("clock: unsupported `adc12` `{other}` (disable/pll1_p/sys)"),
3309 ))
3310 }
3311 };
3312 stmts.push(quote! { config.rcc.mux.adc12sel = ::embassy_stm32::rcc::mux::Adcsel::#v; });
3313 }
3314 if let Some(sel) = node.prop_str_opt("fdcan")? {
3315 let v = match sel.as_str() {
3316 "hse" => quote!(HSE),
3317 "pll1_q" => quote!(PLL1_Q),
3318 "pclk1" => quote!(PCLK1),
3319 other => {
3320 return Err(syn::Error::new(
3321 node.id.span(),
3322 format!("clock: unsupported `fdcan` `{other}` (hse/pll1_q/pclk1)"),
3323 ))
3324 }
3325 };
3326 stmts.push(quote! { config.rcc.mux.fdcansel = ::embassy_stm32::rcc::mux::Fdcansel::#v; });
3327 }
3328 Ok(stmts)
3329}
3330
3331fn f1_clock_config(node: &DslNode) -> Result<Vec<TokenStream2>> {
3332 let mut stmts = Vec::new();
3333
3334 if let Some(source) = node.prop_str_opt("source")? {
3335 if source == "hsi" {
3336 stmts.push(quote! { config.rcc.hsi = true; });
3338 }
3339 }
3340 if let Some(hse) = node.prop_u32_any(&["hse"]) {
3341 let mode = match node.prop_str_opt("hse_mode")?.as_deref() {
3342 None | Some("oscillator") => quote!(Oscillator),
3343 Some("bypass") => quote!(Bypass),
3344 Some(other) => {
3345 return Err(syn::Error::new(
3346 node.id.span(),
3347 format!("clock: unsupported `hse-mode` `{other}`"),
3348 ))
3349 }
3350 };
3351 stmts.push(quote! {
3352 config.rcc.hse = Some(::embassy_stm32::rcc::Hse {
3353 freq: ::embassy_stm32::time::Hertz(#hse),
3354 mode: ::embassy_stm32::rcc::HseMode::#mode,
3355 });
3356 });
3357 }
3358 if let Some(pll) = node.prop_array("pll") {
3359 if pll.len() < 2 {
3361 return Err(syn::Error::new(
3362 node.id.span(),
3363 "clock: `pll` needs <prediv mul> on F1",
3364 ));
3365 }
3366 let pre = format_ident!("DIV{}", pll[0]);
3367 let mul = format_ident!("MUL{}", pll[1]);
3368 let src = match node.prop_str_opt("source")?.as_deref() {
3369 None | Some("hsi") => quote!(HSI),
3370 Some("hse") => quote!(HSE),
3371 Some(other) => {
3372 return Err(syn::Error::new(
3373 node.id.span(),
3374 format!("clock: unsupported `source` `{other}`"),
3375 ))
3376 }
3377 };
3378 stmts.push(quote! {
3379 config.rcc.pll = Some(::embassy_stm32::rcc::Pll {
3380 src: ::embassy_stm32::rcc::PllSource::#src,
3381 prediv: ::embassy_stm32::rcc::PllPreDiv::#pre,
3382 mul: ::embassy_stm32::rcc::PllMul::#mul,
3383 });
3384 });
3385 }
3386 if let Some(sys) = node.prop_str_opt("sys")? {
3387 let v = match sys.as_str() {
3388 "hsi" => quote!(HSI),
3389 "hse" => quote!(HSE),
3390 "pll1_p" => quote!(PLL1_P),
3391 other => {
3392 return Err(syn::Error::new(
3393 node.id.span(),
3394 format!("clock: unsupported `sys` `{other}`"),
3395 ))
3396 }
3397 };
3398 stmts.push(quote! { config.rcc.sys = ::embassy_stm32::rcc::Sysclk::#v; });
3399 }
3400 if let Some(n) = node.prop_u32_any(&["ahb"]) {
3401 let v = format_ident!("DIV{}", n);
3402 stmts.push(quote! { config.rcc.ahb_pre = ::embassy_stm32::rcc::AHBPrescaler::#v; });
3403 }
3404 for key in ["apb1", "apb2"] {
3405 if let Some(n) = node.prop_u32_any(&[key]) {
3406 let field = format_ident!("{}_pre", key);
3407 let v = format_ident!("DIV{}", n);
3408 stmts.push(quote! { config.rcc.#field = ::embassy_stm32::rcc::APBPrescaler::#v; });
3409 }
3410 }
3411 if let Some(n) = node.prop_u32_any(&["adc_pre"]) {
3412 let v = format_ident!("DIV{}", n);
3413 stmts.push(quote! { config.rcc.adc_pre = ::embassy_stm32::rcc::ADCPrescaler::#v; });
3414 }
3415 Ok(stmts)
3416}
3417
3418fn f0_clock_config(node: &DslNode) -> Result<Vec<TokenStream2>> {
3419 let mut stmts = Vec::new();
3420
3421 if let Some(source) = node.prop_str_opt("source")? {
3422 if source == "hsi" {
3423 stmts.push(quote! { config.rcc.hsi = true; });
3424 }
3425 }
3426 if let Some(hse) = node.prop_u32_any(&["hse"]) {
3427 let mode = match node.prop_str_opt("hse_mode")?.as_deref() {
3428 None | Some("oscillator") => quote!(Oscillator),
3429 Some("bypass") => quote!(Bypass),
3430 Some(other) => {
3431 return Err(syn::Error::new(
3432 node.id.span(),
3433 format!("clock: unsupported `hse-mode` `{other}`"),
3434 ))
3435 }
3436 };
3437 stmts.push(quote! {
3438 config.rcc.hse = Some(::embassy_stm32::rcc::Hse {
3439 freq: ::embassy_stm32::time::Hertz(#hse),
3440 mode: ::embassy_stm32::rcc::HseMode::#mode,
3441 });
3442 });
3443 }
3444 if let Some(pll) = node.prop_array("pll") {
3445 if pll.len() < 2 {
3447 return Err(syn::Error::new(
3448 node.id.span(),
3449 "clock: `pll` needs <prediv mul> on F0",
3450 ));
3451 }
3452 let pre = format_ident!("DIV{}", pll[0]);
3453 let mul = format_ident!("MUL{}", pll[1]);
3454 let src = match node.prop_str_opt("source")?.as_deref() {
3455 None | Some("hsi") => quote!(HSI),
3456 Some("hse") => quote!(HSE),
3457 Some("hsi48") => quote!(HSI48),
3458 Some(other) => {
3459 return Err(syn::Error::new(
3460 node.id.span(),
3461 format!("clock: unsupported `source` `{other}`"),
3462 ))
3463 }
3464 };
3465 stmts.push(quote! {
3466 config.rcc.pll = Some(::embassy_stm32::rcc::Pll {
3467 src: ::embassy_stm32::rcc::PllSource::#src,
3468 prediv: ::embassy_stm32::rcc::PllPreDiv::#pre,
3469 mul: ::embassy_stm32::rcc::PllMul::#mul,
3470 });
3471 });
3472 }
3473 if let Some(sys) = node.prop_str_opt("sys")? {
3474 let v = match sys.as_str() {
3475 "hsi" => quote!(HSI),
3476 "hse" => quote!(HSE),
3477 "pll1_p" => quote!(PLL1_P),
3478 "hsi48" => quote!(HSI48),
3479 other => {
3480 return Err(syn::Error::new(
3481 node.id.span(),
3482 format!("clock: unsupported `sys` `{other}`"),
3483 ))
3484 }
3485 };
3486 stmts.push(quote! { config.rcc.sys = ::embassy_stm32::rcc::Sysclk::#v; });
3487 }
3488 if let Some(n) = node.prop_u32_any(&["ahb"]) {
3489 let v = format_ident!("DIV{}", n);
3490 stmts.push(quote! { config.rcc.ahb_pre = ::embassy_stm32::rcc::AHBPrescaler::#v; });
3491 }
3492 if let Some(n) = node.prop_u32_any(&["apb1"]) {
3493 let v = format_ident!("DIV{}", n);
3494 stmts.push(quote! { config.rcc.apb1_pre = ::embassy_stm32::rcc::APBPrescaler::#v; });
3495 }
3496 if node.prop_bool("hsi48") {
3497 let sync = node.prop_bool("hsi48_sync");
3498 stmts.push(quote! {
3499 config.rcc.hsi48 = Some(::embassy_stm32::rcc::Hsi48Config {
3500 sync_from_usb: #sync,
3501 });
3502 });
3503 }
3504 Ok(stmts)
3505}
3506
3507fn stream_irq(channel: &str, node: &DslNode, chip: Option<&str>) -> Result<Ident> {
3511 let irq = if chip.map(|c| c.contains("f0")).unwrap_or(false) {
3512 let num: u32 = channel
3515 .rsplit('_')
3516 .next()
3517 .and_then(|s| s.strip_prefix("CH"))
3518 .and_then(|s| s.parse().ok())
3519 .ok_or_else(|| {
3520 syn::Error::new(
3521 node.id.span(),
3522 format!("stm32 backend: cannot parse F0 DMA channel `{channel}`"),
3523 )
3524 })?;
3525 match num {
3526 1 => "DMA1_CHANNEL1".to_string(),
3527 2..=3 => "DMA1_CHANNEL2_3".to_string(),
3528 4..=7 => "DMA1_CHANNEL4_5_6_7".to_string(),
3529 _ => {
3530 return Err(syn::Error::new(
3531 node.id.span(),
3532 format!("stm32 backend: DMA channel `{channel}` is out of F0 range (DMA1_CH1..=CH7)"),
3533 ))
3534 }
3535 }
3536 } else if channel.contains("_STREAM") || channel.contains("_CHANNEL") {
3537 channel.to_string()
3538 } else if chip
3539 .map(|c| c.contains("l4") || c.contains("g4") || c.contains("f1") || c.contains("f0"))
3540 .unwrap_or(false)
3541 {
3542 channel.replace("_CH", "_CHANNEL")
3544 } else if channel.starts_with("BDMA_CH") {
3545 channel.replace("_CH", "_CHANNEL")
3547 } else if channel.contains("_CH") {
3548 channel.replace("_CH", "_STREAM")
3549 } else {
3550 return Err(syn::Error::new(
3551 node.id.span(),
3552 format!(
3553 "stm32 backend: cannot derive interrupt name from DMA channel `{channel}` (expected `DMA1_CH0` / `DMA1_STREAM0` style)"
3554 ),
3555 ));
3556 };
3557 syn::parse_str::<Ident>(&irq).map_err(|_| {
3558 syn::Error::new(
3559 node.id.span(),
3560 format!("stm32 backend: cannot derive interrupt name from DMA channel `{channel}`"),
3561 )
3562 })
3563}
3564
3565fn push_dma_bindings(
3566 bindings: &mut Vec<(String, Vec<TokenStream2>)>,
3567 channel: &str,
3568 channel_ident: &Ident,
3569 node: &DslNode,
3570 chip: Option<&str>,
3571) -> Result<()> {
3572 push_binding(bindings, stream_irq(channel, node, chip)?, quote! {
3573 ::embassy_stm32::dma::InterruptHandler<::embassy_stm32::peripherals::#channel_ident>
3574 });
3575 Ok(())
3576}
3577
3578fn push_binding(bindings: &mut Vec<(String, Vec<TokenStream2>)>, irq: Ident, handler: TokenStream2) {
3579 let name = irq.to_string();
3580 let key = handler.to_string();
3584 if let Some((_, existing)) = bindings.iter_mut().find(|(n, _)| *n == name) {
3585 if !existing.iter().any(|h| h.to_string() == key) {
3586 existing.push(handler);
3587 }
3588 } else {
3589 bindings.push((name, vec![handler]));
3590 }
3591}
3592
3593fn pwm_pin(pin: Option<Ident>, afio: bool) -> TokenStream2 {
3594 match pin {
3595 Some(pin) if afio => quote! {
3596 Some(::embassy_stm32::timer::simple_pwm::PwmPin::<_, _, ::embassy_stm32::gpio::AfioRemap<0>>::new(
3597 p.#pin,
3598 ::embassy_stm32::gpio::OutputType::PushPull,
3599 ))
3600 },
3601 Some(pin) => quote! {
3602 Some(::embassy_stm32::timer::simple_pwm::PwmPin::new(
3603 p.#pin,
3604 ::embassy_stm32::gpio::OutputType::PushPull,
3605 ))
3606 },
3607 None => quote!(None),
3608 }
3609}
3610
3611fn capture_pin(pin: Option<Ident>) -> TokenStream2 {
3612 match pin {
3613 Some(pin) => quote! {
3614 Some(::embassy_stm32::timer::input_capture::CapturePin::new(
3615 p.#pin,
3616 ::embassy_stm32::gpio::Pull::None,
3617 ))
3618 },
3619 None => quote!(None),
3620 }
3621}
3622
3623fn comp_pin(pin: Option<Ident>) -> TokenStream2 {
3624 match pin {
3625 Some(pin) => quote! {
3626 Some(::embassy_stm32::timer::complementary_pwm::ComplementaryPwmPin::new(
3627 p.#pin,
3628 ::embassy_stm32::gpio::OutputType::PushPull,
3629 ))
3630 },
3631 None => quote!(None),
3632 }
3633}
3634
3635fn exti_info(pin: &str, f0: bool) -> Result<(Ident, Ident, Ident)> {
3637 let digits: String = pin.chars().skip_while(|c| !c.is_ascii_digit()).collect();
3638 let num: u32 = digits.parse().map_err(|_| {
3639 syn::Error::new(
3640 Span::call_site(),
3641 format!("cannot derive EXTI channel from pin `{pin}`"),
3642 )
3643 })?;
3644 if num > 15 {
3645 return Err(syn::Error::new(
3646 Span::call_site(),
3647 format!("pin `{pin}` has no EXTI channel"),
3648 ));
3649 }
3650 let irq_name = if f0 {
3651 match num {
3653 0..=1 => "EXTI0_1".to_string(),
3654 2..=3 => "EXTI2_3".to_string(),
3655 _ => "EXTI4_15".to_string(),
3656 }
3657 } else {
3658 match num {
3659 0..=4 => format!("EXTI{num}"),
3660 5..=9 => "EXTI9_5".to_string(),
3661 _ => "EXTI15_10".to_string(),
3662 }
3663 };
3664 Ok((
3665 format_ident!("EXTI{num}"),
3666 format_ident!("{}", irq_name),
3667 format_ident!("{}", irq_name),
3668 ))
3669}
3670
3671fn cc_irq(periph: &Ident) -> Ident {
3674 let name = periph.to_string();
3675 if name.starts_with("TIM1") || name.starts_with("TIM8") {
3676 format_ident!("{}_CC", name)
3677 } else {
3678 periph.clone()
3679 }
3680}
3681
3682#[cfg(test)]
3683mod tests {
3684 use super::*;
3685
3686 fn parse(input: &str) -> Result<DslTree> {
3687 syn::parse_str(input)
3688 }
3689
3690 #[test]
3691 fn stm32_backend_generates_h7_clock_config() {
3692 let clock = clock_node(&[
3693 ("source", PropValue::Str(LitStr::new("hsi", Span::call_site()))),
3694 ("hsi", PropValue::Str(LitStr::new("div1", Span::call_site()))),
3695 ("csi", PropValue::Bool(true)),
3696 ("hsi48", PropValue::Bool(true)),
3697 ("pll1", PropValue::Array(vec![4, 50, 2])),
3698 ("sys", PropValue::Str(LitStr::new("pll1_p", Span::call_site()))),
3699 ("ahb", PropValue::U32(LitInt::new("2", Span::call_site()))),
3700 ("apb1", PropValue::U32(LitInt::new("2", Span::call_site()))),
3701 ("usb", PropValue::Str(LitStr::new("hsi48", Span::call_site()))),
3702 (
3703 "voltage",
3704 PropValue::Str(LitStr::new("scale1", Span::call_site())),
3705 ),
3706 ]);
3707 let stmts = h7_clock_config(&clock).unwrap();
3708 let tokens = quote!(#(#stmts)*).to_string().replace(' ', "");
3709 assert!(tokens.contains("HSIPrescaler::DIV1"));
3710 assert!(tokens.contains("PllSource::HSI"));
3711 assert!(tokens.contains("PllMul::MUL50"));
3712 assert!(tokens.contains("Sysclk::PLL1_P"));
3713 assert!(tokens.contains("Usbsel::HSI48"));
3714 assert!(tokens.contains("VoltageScale::Scale1"));
3715 }
3716
3717 #[test]
3718 fn stm32_backend_generates_f4_clock_config() {
3719 let clock = clock_node(&[
3720 ("source", PropValue::Str(LitStr::new("hse", Span::call_site()))),
3721 ("hse", PropValue::U32(LitInt::new("25000000", Span::call_site()))),
3722 ("pll", PropValue::Array(vec![4, 168, 2, 7])),
3723 ("sys", PropValue::Str(LitStr::new("pll1_p", Span::call_site()))),
3724 ("ahb", PropValue::U32(LitInt::new("1", Span::call_site()))),
3725 (
3726 "clk48",
3727 PropValue::Str(LitStr::new("pll1_q", Span::call_site())),
3728 ),
3729 ]);
3730 let stmts = f4_clock_config(&clock).unwrap();
3731 let tokens = quote!(#(#stmts)*).to_string().replace(' ', "");
3732 assert!(tokens.contains("HseMode::Oscillator"));
3733 assert!(tokens.contains("PllSource::HSE"));
3734 assert!(tokens.contains("PllMul::MUL168"));
3735 assert!(tokens.contains("PllQDiv::DIV7"));
3736 assert!(tokens.contains("Clk48sel::PLL1_Q"));
3737 }
3738
3739 #[test]
3740 fn clock_requires_source_with_pll() {
3741 let clock = clock_node(&[("pll1", PropValue::Array(vec![4, 50, 2]))]);
3742 let err = h7_clock_config(&clock).unwrap_err();
3743 assert!(err.to_string().contains("`source` is required"));
3744 }
3745
3746 #[test]
3747 fn parses_node_keyword_in_dsl() {
3748 let tree = parse(
3749 r#"
3750 node note { source: "hsi" };
3751 "#,
3752 )
3753 .unwrap();
3754 assert_eq!(tree.nodes.len(), 1);
3755 assert!(tree.nodes[0].driver.is_none());
3756 }
3757
3758 #[test]
3759 fn intent_h7_400mhz() {
3760 let p = plan_h7(400_000_000, Some(48_000_000), None, None, None, None).unwrap();
3761 assert_eq!((p.prediv, p.mul, p.divp), (4, 25, 1));
3762 assert_eq!((p.ahb, p.apb), (2, 2));
3763 assert!(p.scale1);
3764 assert!(p.usb48);
3765 assert!(!p.source_hse);
3766 assert!(p.pll2.is_none());
3767 }
3768
3769 #[test]
3770 fn intent_h7_550mhz_uses_scale0() {
3771 let p = plan_h7(550_000_000, None, None, None, None, None).unwrap();
3772 assert_eq!((p.prediv, p.mul, p.divp), (32, 275, 1));
3773 assert!(!p.scale1);
3774 assert!(!p.usb48);
3775 }
3776
3777 #[test]
3778 fn intent_h7_550mhz_with_hse() {
3779 let p = plan_h7(550_000_000, None, Some(8_000_000), None, None, None).unwrap();
3781 assert_eq!((p.prediv, p.mul, p.divp), (4, 275, 1));
3782 assert!(p.source_hse);
3783 assert!(!p.scale1);
3784 }
3785
3786 #[test]
3787 fn intent_h7_i2s_50mhz() {
3788 let p = plan_h7(400_000_000, None, None, Some(50_000_000), None, None).unwrap();
3789 assert_eq!(p.pll2, Some((8, 25, 4, 1)));
3790 assert_eq!(p.spi123, Some("pll2_p"));
3791 assert_eq!(p.sdmmc_sel, None);
3792 }
3793
3794 #[test]
3795 fn intent_h7_i2s_and_sdmmc_share_vco() {
3796 let p = plan_h7(
3797 400_000_000,
3798 None,
3799 None,
3800 Some(50_000_000),
3801 None,
3802 Some(25_000_000),
3803 )
3804 .unwrap();
3805 assert_eq!(p.pll2, Some((8, 25, 4, 8)));
3807 assert_eq!(p.spi123, Some("pll2_p"));
3808 assert_eq!(p.sdmmc_sel, Some("pll2_r"));
3809 }
3810
3811 #[test]
3812 fn intent_h7_adc_i2s_conflict() {
3813 let err = plan_h7(
3814 400_000_000,
3815 None,
3816 None,
3817 Some(50_000_000),
3818 Some(100_000_000),
3819 None,
3820 )
3821 .unwrap_err();
3822 assert!(err.contains("share PLL2_P"));
3823 }
3824
3825 #[test]
3826 fn intent_f4_96mhz_with_usb() {
3827 let p = plan_f4(96_000_000, Some(48_000_000), Some(25_000_000)).unwrap();
3828 assert_eq!((p.prediv, p.mul, p.divp, p.divq), (25, 192, 2, 4));
3829 assert_eq!((p.ahb, p.apb1, p.apb2), (1, 2, 1));
3830 assert!(p.usb48);
3831 assert!(p.source_hse);
3832 }
3833
3834 #[test]
3835 fn intent_f4_96mhz_hsi_no_crystal() {
3836 let p = plan_f4(96_000_000, Some(48_000_000), None).unwrap();
3838 assert_eq!((p.prediv, p.mul, p.divp, p.divq), (2, 24, 2, 4));
3839 assert!(!p.source_hse);
3840 assert!(p.usb48);
3841 }
3842
3843 #[test]
3844 fn intent_f4_100mhz_usb_impossible() {
3845 let err = plan_f4(100_000_000, Some(48_000_000), Some(25_000_000)).unwrap_err();
3846 assert!(err.contains("96 MHz"));
3847 }
3848
3849 #[test]
3850 fn intent_f4_100mhz_without_usb() {
3851 let p = plan_f4(100_000_000, None, Some(25_000_000)).unwrap();
3852 assert_eq!((p.prediv, p.mul, p.divp), (2, 16, 2));
3853 assert!(!p.usb48);
3854 assert!(p.source_hse);
3855 }
3856
3857 #[test]
3858 fn intent_l4_80mhz_hsi() {
3859 let p = plan_l4(80_000_000, Some(48_000_000), None).unwrap();
3861 assert_eq!((p.prediv, p.mul, p.divr), (1, 10, 2));
3862 assert!(p.usb48);
3863 assert!(p.hse.is_none());
3864 }
3865
3866 #[test]
3867 fn intent_l4_80mhz_hse() {
3868 let p = plan_l4(80_000_000, None, Some(8_000_000)).unwrap();
3870 assert_eq!((p.prediv, p.mul, p.divr), (1, 20, 2));
3871 assert_eq!(p.hse, Some(8_000_000));
3872 }
3873
3874 #[test]
3875 fn intent_l4_rejects_overclock() {
3876 let err = plan_l4(100_000_000, None, None).unwrap_err();
3877 assert!(err.contains("80 MHz"));
3878 }
3879
3880 #[test]
3881 fn intent_g4_170mhz_hsi_with_usb() {
3882 let p = plan_g4(170_000_000, Some(48_000_000), None, None).unwrap();
3884 assert_eq!((p.prediv, p.mul, p.divr), (4, 85, 2));
3885 assert!(p.usb48);
3886 assert!(p.boost);
3887 assert!(p.hse.is_none());
3888 }
3889
3890 #[test]
3891 fn intent_g4_80mhz_hsi_with_adc() {
3892 let p = plan_g4(80_000_000, None, None, Some(60_000_000)).unwrap();
3894 assert_eq!((p.prediv, p.mul, p.divr), (1, 10, 2));
3895 assert!(p.adc);
3896 assert!(!p.boost);
3897 }
3898
3899 #[test]
3900 fn intent_g4_170mhz_hse() {
3901 let p = plan_g4(170_000_000, None, Some(8_000_000), None).unwrap();
3903 assert_eq!((p.prediv, p.mul, p.divr), (2, 85, 2));
3904 assert_eq!(p.hse, Some(8_000_000));
3905 assert!(p.boost);
3906 }
3907
3908 #[test]
3909 fn intent_g4_rejects_overclock_and_bad_usb() {
3910 let err = plan_g4(200_000_000, None, None, None).unwrap_err();
3911 assert!(err.contains("170 MHz"));
3912 let err = plan_g4(80_000_000, Some(60_000_000), None, None).unwrap_err();
3913 assert!(err.contains("48 MHz"));
3914 }
3915
3916 #[test]
3917 fn stm32_backend_generates_g4_clock_config() {
3918 let clock = clock_node(&[
3919 ("source", PropValue::Str(LitStr::new("hsi", Span::call_site()))),
3920 ("pll", PropValue::Array(vec![4, 85, 2])),
3921 ("sys", PropValue::Str(LitStr::new("pll1_r", Span::call_site()))),
3922 ("hsi48", PropValue::Bool(true)),
3923 ("hsi48_sync", PropValue::Bool(true)),
3924 ("boost", PropValue::Bool(true)),
3925 (
3926 "adc12",
3927 PropValue::Str(LitStr::new("sys", Span::call_site())),
3928 ),
3929 (
3930 "fdcan",
3931 PropValue::Str(LitStr::new("pclk1", Span::call_site())),
3932 ),
3933 ]);
3934 let stmts = g4_clock_config(&clock).unwrap();
3935 let tokens = quote!(#(#stmts)*).to_string().replace(' ', "");
3936 assert!(tokens.contains("PllPreDiv::DIV4"));
3937 assert!(tokens.contains("PllMul::MUL85"));
3938 assert!(tokens.contains("PllRDiv::DIV2"));
3939 assert!(tokens.contains("Sysclk::PLL1_R"));
3940 assert!(tokens.contains("sync_from_usb:true"));
3941 assert!(tokens.contains("config.rcc.boost=true"));
3942 assert!(tokens.contains("mux.adc12sel"));
3943 assert!(tokens.contains("Adcsel::SYS"));
3944 assert!(tokens.contains("Fdcansel::PCLK1"));
3945 }
3946
3947 #[test]
3948 fn stm32_backend_generates_g4_clock_config_pll_pq() {
3949 let clock = clock_node(&[
3952 ("source", PropValue::Str(LitStr::new("hse", Span::call_site()))),
3953 ("hse", PropValue::U32(LitInt::new("8000000", Span::call_site()))),
3954 ("pll", PropValue::Array(vec![2, 85, 2])),
3955 ("pllp", PropValue::U32(LitInt::new("8", Span::call_site()))),
3956 ("pllq", PropValue::U32(LitInt::new("2", Span::call_site()))),
3957 ("sys", PropValue::Str(LitStr::new("pll1_r", Span::call_site()))),
3958 (
3959 "adc12",
3960 PropValue::Str(LitStr::new("pll1_p", Span::call_site())),
3961 ),
3962 ("boost", PropValue::Bool(true)),
3963 ]);
3964 let stmts = g4_clock_config(&clock).unwrap();
3965 let tokens = quote!(#(#stmts)*).to_string().replace(' ', "");
3966 assert!(tokens.contains("PllSource::HSE"));
3967 assert!(tokens.contains("PllPreDiv::DIV2"));
3968 assert!(tokens.contains("PllMul::MUL85"));
3969 assert!(tokens.contains("divp:Some(::embassy_stm32::rcc::PllPDiv::DIV8)"));
3970 assert!(tokens.contains("divq:Some(::embassy_stm32::rcc::PllQDiv::DIV2)"));
3971 assert!(tokens.contains("Adcsel::PLL1_P"));
3972 assert!(tokens.contains("PllRDiv::DIV2"));
3973 }
3974
3975 #[test]
3976 fn intent_g4_pll_pq_passthrough() {
3977 let tree = parse(
3980 r#"
3981 name "g4-foc";
3982 backend stm32;
3983 chip "stm32g474re";
3984 node clock {
3985 system: 170_000_000,
3986 pllp: 8,
3987 pllq: 2,
3988 adc12: "pll1_p",
3989 };
3990 periph adc0: Adc { periph: "ADC1" };
3991 "#,
3992 )
3993 .unwrap();
3994 let tokens = expand(tree).unwrap().to_string().replace(' ', "");
3995 assert!(tokens.contains("divp:Some(::embassy_stm32::rcc::PllPDiv::DIV8)"));
3996 assert!(tokens.contains("divq:Some(::embassy_stm32::rcc::PllQDiv::DIV2)"));
3997 assert!(tokens.contains("Adcsel::PLL1_P"));
3998 }
3999
4000 #[test]
4001 fn adc_optional_pin_generates_pin_field() {
4002 let tree = parse(
4003 r#"
4004 name "adc-pin";
4005 backend stm32;
4006 chip "stm32h723zg";
4007 periph adc0: Adc { periph: "ADC1", pin: "PA0" };
4008 "#,
4009 )
4010 .unwrap();
4011 let tokens = expand(tree).unwrap().to_string().replace(' ', "");
4012 assert!(
4013 tokens.contains("pubadc0_pin:::embassy_stm32::Peri<'static,::embassy_stm32::peripherals::PA0>"),
4014 "tokens: {tokens}"
4015 );
4016 assert!(tokens.contains("adc0_pin:p.PA0"), "tokens: {tokens}");
4017 }
4018
4019 #[test]
4020 fn adc_without_pin_has_no_pin_field() {
4021 let tree = parse(
4022 r#"
4023 name "adc-nopin";
4024 backend stm32;
4025 chip "stm32h723zg";
4026 periph adc0: Adc { periph: "ADC1" };
4027 "#,
4028 )
4029 .unwrap();
4030 let tokens = expand(tree).unwrap().to_string().replace(' ', "");
4031 assert!(!tokens.contains("adc0_pin"), "tokens: {tokens}");
4032 }
4033
4034 #[test]
4035 fn intent_g4_can_auto_fdcan_pclk1() {
4036 let tree = parse(
4040 r#"
4041 name "g4-can";
4042 backend stm32;
4043 chip "stm32g474re";
4044 node clock {
4045 system: 170_000_000,
4046 usb: 48_000_000,
4047 adc: 60_000_000,
4048 };
4049 periph can0: Can { periph: "FDCAN1", rx: "PB8", tx: "PB9" };
4050 "#,
4051 )
4052 .unwrap();
4053 let tokens = expand(tree).unwrap().to_string().replace(' ', "");
4054 assert!(tokens.contains("Fdcansel::PCLK1"));
4055 assert!(tokens.contains("Adcsel::SYS"));
4056 }
4057
4058 #[test]
4059 fn intent_g4_user_fdcan_prop_is_preserved() {
4060 let tree = parse(
4063 r#"
4064 name "g4-can";
4065 backend stm32;
4066 chip "stm32g474re";
4067 node clock {
4068 system: 170_000_000,
4069 adc: 60_000_000,
4070 fdcan: "pll1_q",
4071 };
4072 periph can0: Can { periph: "FDCAN1", rx: "PB8", tx: "PB9" };
4073 "#,
4074 )
4075 .unwrap();
4076 let tokens = expand(tree).unwrap().to_string().replace(' ', "");
4077 assert!(tokens.contains("Fdcansel::PLL1_Q"));
4078 }
4079
4080 #[test]
4081 fn intent_g4_can_dts_auto_fdcan_pclk1() {
4082 let dir = std::env::temp_dir()
4086 .join(format!("embassy-dt-intent-g4-{}", std::process::id()));
4087 std::fs::create_dir_all(&dir).unwrap();
4088 let dts = dir.join("g4-can.dts");
4089 std::fs::write(
4090 &dts,
4091 r#"
4092 /dts-v1/;
4093 / {
4094 model = "G4-Can";
4095 clock {
4096 system = <170000000>;
4097 usb = <48000000>;
4098 adc = <60000000>;
4099 };
4100 can0: can@40006400 {
4101 compatible = "embassy-dt,periph-can";
4102 periph = "FDCAN1";
4103 rx = "PB8";
4104 tx = "PB9";
4105 };
4106 led0: led@0 {
4107 compatible = "embassy-dt,gpio-out";
4108 pin = "PB0";
4109 level = "low";
4110 };
4111 };
4112 "#,
4113 )
4114 .unwrap();
4115 let input = format!(
4116 r#" name "g4-can"; backend stm32; chip "stm32g474re"; from "{}"; "#,
4117 dts.display()
4118 );
4119 let tree = parse(&input).unwrap();
4120 let tokens = expand(tree).unwrap().to_string().replace(' ', "");
4121 assert!(tokens.contains("Fdcansel::PCLK1"));
4122 assert!(tokens.contains("Adcsel::SYS"));
4123 assert!(tokens.contains("FDCAN1_IT0"));
4124 std::fs::remove_dir_all(&dir).ok();
4125 }
4126
4127 #[test]
4128 fn intent_f1_72mhz_hse_with_usb() {
4129 let p = plan_f1(72_000_000, Some(48_000_000), Some(8_000_000), Some(60_000_000)).unwrap();
4132 assert_eq!((p.prediv, p.mul), (1, 9));
4133 assert_eq!(p.apb1, 2);
4134 assert_eq!(p.adc_pre, Some(6));
4135 assert!(p.usb48);
4136 assert_eq!(p.hse, Some(8_000_000));
4137 }
4138
4139 #[test]
4140 fn intent_f1_64mhz_hsi() {
4141 let p = plan_f1(64_000_000, None, None, None).unwrap();
4143 assert_eq!((p.prediv, p.mul), (2, 16));
4144 assert_eq!(p.apb1, 2);
4145 assert!(p.adc_pre.is_none());
4146 }
4147
4148 #[test]
4149 fn intent_f1_48mhz_hsi_with_usb() {
4150 let p = plan_f1(48_000_000, Some(48_000_000), None, None).unwrap();
4152 assert_eq!((p.prediv, p.mul), (2, 12));
4153 assert_eq!(p.apb1, 2);
4154 assert!(p.usb48);
4155 }
4156
4157 #[test]
4158 fn intent_f1_rejects_usb_without_pll_48_72() {
4159 let err = plan_f1(64_000_000, Some(48_000_000), None, None).unwrap_err();
4160 assert!(err.contains("72 MHz"));
4161 let err = plan_f1(80_000_000, None, Some(8_000_000), None).unwrap_err();
4162 assert!(err.contains("72 MHz"));
4163 }
4164
4165 #[test]
4166 fn stm32_backend_generates_f1_clock_config() {
4167 let clock = clock_node(&[
4168 ("source", PropValue::Str(LitStr::new("hse", Span::call_site()))),
4169 ("hse", PropValue::U32(LitInt::new("8000000", Span::call_site()))),
4170 ("pll", PropValue::Array(vec![1, 9])),
4171 ("sys", PropValue::Str(LitStr::new("pll1_p", Span::call_site()))),
4172 ("ahb", PropValue::U32(LitInt::new("1", Span::call_site()))),
4173 ("apb1", PropValue::U32(LitInt::new("2", Span::call_site()))),
4174 ("apb2", PropValue::U32(LitInt::new("1", Span::call_site()))),
4175 ("adc_pre", PropValue::U32(LitInt::new("6", Span::call_site()))),
4176 ]);
4177 let stmts = f1_clock_config(&clock).unwrap();
4178 let tokens = quote!(#(#stmts)*).to_string().replace(' ', "");
4179 assert!(tokens.contains("PllSource::HSE"));
4180 assert!(tokens.contains("PllPreDiv::DIV1"));
4181 assert!(tokens.contains("PllMul::MUL9"));
4182 assert!(tokens.contains("Sysclk::PLL1_P"));
4183 assert!(tokens.contains("APBPrescaler::DIV2"));
4184 assert!(tokens.contains("ADCPrescaler::DIV6"));
4185 }
4186
4187 #[test]
4188 fn intent_f0_48mhz_hsi_with_usb() {
4189 let p = plan_f0(48_000_000, Some(48_000_000), None).unwrap();
4192 assert_eq!((p.prediv, p.mul), (1, 6));
4193 assert!(p.usb48);
4194 assert!(p.hse.is_none());
4195 }
4196
4197 #[test]
4198 fn intent_f0_48mhz_hse() {
4199 let p = plan_f0(48_000_000, None, Some(8_000_000)).unwrap();
4201 assert_eq!((p.prediv, p.mul), (1, 6));
4202 assert_eq!(p.hse, Some(8_000_000));
4203 }
4204
4205 #[test]
4206 fn intent_f0_rejects_overclock() {
4207 let err = plan_f0(64_000_000, None, None).unwrap_err();
4208 assert!(err.contains("48 MHz"));
4209 }
4210
4211 #[test]
4212 fn stm32_backend_generates_f0_clock_config() {
4213 let clock = clock_node(&[
4214 ("source", PropValue::Str(LitStr::new("hsi", Span::call_site()))),
4215 ("pll", PropValue::Array(vec![1, 6])),
4216 ("sys", PropValue::Str(LitStr::new("pll1_p", Span::call_site()))),
4217 ("ahb", PropValue::U32(LitInt::new("1", Span::call_site()))),
4218 ("apb1", PropValue::U32(LitInt::new("1", Span::call_site()))),
4219 ("hsi48", PropValue::Bool(true)),
4220 ("hsi48_sync", PropValue::Bool(true)),
4221 ]);
4222 let stmts = f0_clock_config(&clock).unwrap();
4223 let tokens = quote!(#(#stmts)*).to_string().replace(' ', "");
4224 assert!(tokens.contains("PllSource::HSI"));
4225 assert!(tokens.contains("PllPreDiv::DIV1"));
4226 assert!(tokens.contains("PllMul::MUL6"));
4227 assert!(tokens.contains("Sysclk::PLL1_P"));
4228 assert!(tokens.contains("sync_from_usb:true"));
4229 }
4230#[cfg(test)]
4231fn clock_node(props: &[(&str, PropValue)]) -> DslNode {
4232 DslNode {
4233 id: Ident::new("clock", Span::call_site()),
4234 kind: NodeKindAst::Device,
4235 driver: None,
4236 props: props
4237 .iter()
4238 .map(|(k, v)| DslProp {
4239 key: Ident::new(k, Span::call_site()),
4240 value: match v {
4241 PropValue::Str(s) => {
4242 PropValue::Str(LitStr::new(&s.value(), s.span()))
4243 }
4244 PropValue::U32(l) => {
4245 PropValue::U32(LitInt::new(l.base10_digits(), l.span()))
4246 }
4247 PropValue::Ref(i) => PropValue::Ref(Ident::new(&i.to_string(), i.span())),
4248 PropValue::Array(v) => PropValue::Array(v.clone()),
4249 PropValue::Bool(b) => PropValue::Bool(*b),
4250 },
4251 })
4252 .collect(),
4253 deps: Vec::new(),
4254 }
4255}
4256
4257 #[test]
4258 fn parses_tree_with_all_node_kinds() {
4259 let tree = parse(
4260 r#"
4261 name "demo";
4262 bus i2c0: I2c { periph: "I2C1", scl: "PB8", sda: "PB7", freq: 400_000 };
4263 bus uart0: Uart { periph: "USART1", rx: "PA10", tx: "PA9", baud: 115_200 };
4264 gpio led0: Out { pin: "PC13", level: "high" };
4265 periph rng0: Rng { periph: "RNG" };
4266 device bme280: Bme280Driver { bus: i2c0, addr: 0x76 };
4267 "#,
4268 )
4269 .unwrap();
4270 assert_eq!(tree.name.as_ref().unwrap().value(), "demo");
4271 assert_eq!(tree.nodes.len(), 5);
4272 assert!(matches!(
4273 tree.nodes[2].kind,
4274 NodeKindAst::Gpio(GpioKindAst::Out)
4275 ));
4276 assert!(matches!(
4277 tree.nodes[3].kind,
4278 NodeKindAst::Peripheral(PeriphKindAst::Rng)
4279 ));
4280 assert_eq!(tree.nodes[4].deps.len(), 1);
4281 assert_eq!(tree.nodes[4].deps[0].to_string(), "i2c0");
4282 }
4283
4284 #[test]
4285 fn detects_duplicate_ids() {
4286 let tree = parse(
4287 r#"
4288 bus i2c0: I2c {};
4289 bus i2c0: I2c {};
4290 "#,
4291 )
4292 .unwrap();
4293 let err = validate(&tree).unwrap_err();
4294 assert!(err.to_string().contains("duplicate node id `i2c0`"));
4295 }
4296
4297 #[test]
4298 fn detects_missing_dependency() {
4299 let tree = parse(r#"device a: A { bus: nope };"#).unwrap();
4300 let err = validate(&tree).unwrap_err();
4301 assert!(err.to_string().contains("unknown node `nope`"));
4302 }
4303
4304 #[test]
4305 fn detects_cycle() {
4306 let tree = parse(
4307 r#"
4308 device a: A { bus: b };
4309 device b: B { bus: a };
4310 "#,
4311 )
4312 .unwrap();
4313 let err = validate(&tree).unwrap_err();
4314 assert!(err.to_string().contains("cycle"));
4315 }
4316
4317 #[test]
4318 fn expand_generates_tree_static() {
4319 let tree = parse(
4320 r#"
4321 name "demo";
4322 bus i2c0: I2c { periph: "I2C1", scl: "PB8", sda: "PB7", freq: 400_000 };
4323 device bme280: Bme280Driver { bus: i2c0, addr: 0x76 };
4324 "#,
4325 )
4326 .unwrap();
4327 let tokens = expand(tree).unwrap().to_string();
4328 assert!(tokens.contains("pub static TREE"));
4329 assert!(tokens.contains("I2c"));
4330 assert!(tokens.contains("0x76"));
4331 }
4332
4333 #[test]
4334 fn stm32_backend_generates_board_for_all_bus_kinds() {
4335 let tree = parse(
4336 r#"
4337 name "demo";
4338 backend stm32;
4339 bus i2c0: I2c { periph: "I2C1", scl: "PB8", sda: "PB7", dma_tx: "DMA1_CH0", dma_rx: "DMA1_CH1", freq: 400_000 };
4340 bus spi0: Spi { periph: "SPI1", sck: "PA5", mosi: "PA7", miso: "PA6", dma_tx: "DMA1_CH2", dma_rx: "DMA1_CH3" };
4341 bus uart0: Uart { periph: "USART1", rx: "PA10", tx: "PA9", dma_tx: "DMA1_CH4", dma_rx: "DMA1_CH5", baud: 115_200 };
4342 gpio led0: Out { pin: "PC13", level: "high" };
4343 gpio btn0: In { pin: "PA0", pull: "up" };
4344 "#,
4345 )
4346 .unwrap();
4347 let tokens = expand(tree).unwrap().to_string().replace(' ', "");
4349 assert!(tokens.contains("pubstructBoard"));
4350 assert!(tokens.contains("I2c::new"));
4351 assert!(tokens.contains("Spi::new"));
4352 assert!(tokens.contains("Uart::new"));
4353 assert!(tokens.contains("Output::new"));
4354 assert!(tokens.contains("Input::new"));
4355 assert!(tokens.contains("p.I2C1"));
4356 assert!(tokens.contains("p.DMA1_CH0"));
4357 assert!(tokens.contains("DtIrqs"));
4358 assert!(tokens.contains("I2C1_EV"));
4359 assert!(tokens.contains("I2C1_ER"));
4360 assert!(tokens.contains("DMA1_STREAM0"));
4361 assert!(tokens.contains("USART1=>"));
4362 assert!(tokens.contains("DMA1_STREAM4"));
4363 }
4364
4365 #[test]
4366 fn stm32_backend_requires_uart_pins() {
4367 let tree = parse(
4368 r#"
4369 backend stm32;
4370 bus uart0: Uart { periph: "USART1" };
4371 "#,
4372 )
4373 .unwrap();
4374 let err = expand(tree).unwrap_err();
4375 assert!(err.to_string().contains("missing required prop `rx`"));
4376 }
4377
4378 #[test]
4379 fn stm32_backend_generates_peripherals() {
4380 let tree = parse(
4381 r#"
4382 name "demo";
4383 backend stm32;
4384 chip "stm32h723zg";
4385 periph rng0: Rng { periph: "RNG" };
4386 periph adc0: Adc { periph: "ADC1" };
4387 periph crc0: Crc { periph: "CRC" };
4388 periph dac0: Dac { periph: "DAC1", pin: "PA4" };
4389 periph pwm0: Pwm { periph: "TIM2", ch1: "PA0", ch2: "PA1", ch3: "PA2", ch4: "PA3", freq: 1000 };
4390 periph can0: Can { periph: "FDCAN1", rx: "PB8", tx: "PB9" };
4391 periph usb0: Usb { periph: "USB_OTG_HS", dp: "PA12", dm: "PA11", ep_out: 256 };
4392 periph qei0: Qei { periph: "TIM3", ch1: "PB4", ch2: "PB5" };
4393 periph ic0: InputCapture { periph: "TIM4", ch1: "PB6", freq: 1000000 };
4394 periph sdmmc0: Sdmmc { periph: "SDMMC1", clk: "PC12", cmd: "PD2", d0: "PC8" };
4395 periph i2s0: I2s { periph: "SPI3", sd: "PB2", ws: "PA15", ck: "PB3", dma: "DMA2_CH3", buffer: 512 };
4396 periph pwm_in0: PwmInput { periph: "TIM8", pin: "PC6", freq: 10000 };
4397 periph pwm_adv0: ComplementaryPwm { periph: "TIM1", ch1: "PA8", ch1n: "PB13", freq: 10000 };
4398 bus spi1: Spi { periph: "SPI2", sck: "PB13", mosi: "PB15", miso: "PB14", cs: "PB12", mode: "slave", dma_tx: "DMA1_CH6", dma_rx: "DMA1_CH7" };
4399 "#,
4400 )
4401 .unwrap();
4402 let tokens = expand(tree).unwrap().to_string().replace(' ', "");
4403 assert!(tokens.contains("Rng::new"));
4404 assert!(tokens.contains("Adc::new"));
4405 assert!(tokens.contains("Crc::new"));
4406 assert!(tokens.contains("DacChannel::new_blocking"));
4407 assert!(tokens.contains("SimplePwm::new"));
4408 assert!(tokens.contains("CanConfigurator::new"));
4409 assert!(tokens.contains("into_normal_mode"));
4410 assert!(tokens.contains("FDCAN1_IT0"));
4411 assert!(tokens.contains("FDCAN1_IT1"));
4412 assert!(tokens.contains("RNG=>"));
4413 assert!(tokens.contains("PolySize::Width32"));
4414 assert!(tokens.contains("Driver::new_hs"));
4415 assert!(tokens.contains("OTG_HS=>"));
4416 assert!(tokens.contains("Qei::new"));
4417 assert!(tokens.contains("InputCapture::new"));
4418 assert!(tokens.contains("Sdmmc::new_1bit"));
4419 assert!(tokens.contains("new_slave"));
4420 assert!(tokens.contains("EP_BUF"));
4421 assert!(tokens.contains("new_txonly_nomck"));
4422 assert!(tokens.contains("DMA_BUF"));
4423 assert!(tokens.contains("PwmInput::new_ch1"));
4424 assert!(tokens.contains("ComplementaryPwm::new"));
4425 assert!(tokens.contains("ComplementaryPwmPin::new"));
4426 }
4427
4428 #[test]
4429 fn complementary_pwm_counting_mode() {
4430 let tree = parse(
4433 r#"
4434 name "foc";
4435 backend stm32;
4436 chip "stm32g474re";
4437 periph pwm_m1: ComplementaryPwm {
4438 periph: "TIM1", ch1: "PA8", ch1n: "PB13",
4439 ch2: "PA9", ch2n: "PB14", ch3: "PA10", ch3n: "PB15",
4440 freq: 16000, counting: "center-aligned-3",
4441 };
4442 "#,
4443 )
4444 .unwrap();
4445 let tokens = expand(tree).unwrap().to_string().replace(' ', "");
4446 assert!(tokens.contains("CountingMode::CenterAlignedBothInterrupts"));
4447 assert!(!tokens.contains("CountingMode::EdgeAlignedUp"));
4448 }
4449
4450 #[test]
4451 fn complementary_pwm_rejects_bad_counting() {
4452 let tree = parse(
4453 r#"
4454 name "bad";
4455 backend stm32;
4456 chip "stm32g474re";
4457 periph pwm0: ComplementaryPwm { periph: "TIM1", counting: "sideways" };
4458 "#,
4459 )
4460 .unwrap();
4461 let err = expand(tree).unwrap_err();
4462 assert!(err.to_string().contains("unsupported `counting` `sideways`"));
4463 }
4464
4465 #[test]
4466 fn stm32_backend_generates_g4_cordic() {
4467 let tree = parse(
4470 r#"
4471 name "g4-cordic";
4472 backend stm32;
4473 chip "stm32g474re";
4474 periph cordic0: Cordic { periph: "CORDIC" };
4475 "#,
4476 )
4477 .unwrap();
4478 let tokens = expand(tree).unwrap().to_string().replace(' ', "");
4479 assert!(tokens.contains("Cordic::new"));
4480 assert!(tokens.contains("Function::Cos"));
4481 assert!(tokens.contains("Precision::Iters24"));
4482 assert!(tokens.contains("AccessCount::Two"));
4483 }
4484
4485 #[test]
4486 fn cordic_requires_g4_chip() {
4487 let tree = parse(
4488 r#"
4489 name "bad";
4490 backend stm32;
4491 chip "stm32f411ce";
4492 periph cordic0: Cordic { periph: "CORDIC" };
4493 "#,
4494 )
4495 .unwrap();
4496 let err = expand(tree).unwrap_err();
4497 assert!(err.to_string().contains("`cordic` is not supported for this chip"));
4498 }
4499
4500 #[test]
4501 fn stm32_backend_peripheral_requires_chip() {
4502 let tree = parse(
4503 r#"
4504 backend stm32;
4505 periph can0: Can { periph: "FDCAN1", rx: "PA11", tx: "PA12" };
4506 "#,
4507 )
4508 .unwrap();
4509 let err = expand(tree).unwrap_err();
4510 assert!(err.to_string().contains("declare `chip"));
4511 }
4512
4513 #[test]
4514 fn stm32_backend_generates_f411_variant_peripherals() {
4515 let tree = parse(
4516 r#"
4517 backend stm32;
4518 chip "stm32f411ce";
4519 periph rng0: Rng { periph: "RNG" };
4520 periph adc0: Adc { periph: "ADC1" };
4521 periph crc0: Crc { periph: "CRC" };
4522 periph dac0: Dac { periph: "DAC1", pin: "PA4" };
4523 periph pwm0: Pwm { periph: "TIM2", ch1: "PA0", ch2: "PA1" };
4524 "#,
4525 )
4526 .unwrap();
4527 let tokens = expand(tree).unwrap().to_string().replace(' ', "");
4528 assert!(tokens.contains("Adc::new"));
4529 assert!(!tokens.contains("ADC=>"));
4530 assert!(tokens.contains("Crc::new"));
4531 assert!(!tokens.contains("PolySize"));
4532 }
4533
4534}