cairo_lang_semantic/expr/
fmt.rs

1use cairo_lang_defs::db::DefsGroup;
2use cairo_lang_defs::ids::FunctionWithBodyId;
3use cairo_lang_utils::Upcast;
4
5use crate::db::SemanticGroup;
6
7/// Holds all the information needed for formatting expressions.
8/// Acts like a "db" for DebugWithDb.
9pub struct ExprFormatter<'a> {
10    pub db: &'a (dyn SemanticGroup + 'static),
11    pub function_id: FunctionWithBodyId,
12}
13
14impl Upcast<dyn SemanticGroup + 'static> for ExprFormatter<'_> {
15    fn upcast(&self) -> &(dyn SemanticGroup + 'static) {
16        self.db
17    }
18}
19impl Upcast<dyn DefsGroup + 'static> for ExprFormatter<'_> {
20    fn upcast(&self) -> &(dyn DefsGroup + 'static) {
21        self.db
22    }
23}
24
25/// A wrapper around std::fmt::Formatter that counts the number of characters written so far.
26pub struct CountingWriter<'a, 'b> {
27    inner: &'a mut std::fmt::Formatter<'b>,
28    count: usize,
29}
30
31impl<'a, 'b> CountingWriter<'a, 'b> {
32    pub fn new(inner: &'a mut std::fmt::Formatter<'b>) -> Self {
33        Self { inner, count: 0 }
34    }
35
36    pub fn count(&self) -> usize {
37        self.count
38    }
39}
40
41impl<'a, 'b> std::fmt::Write for CountingWriter<'a, 'b> {
42    fn write_str(&mut self, s: &str) -> std::fmt::Result {
43        self.count += s.len();
44        self.inner.write_str(s)
45    }
46}