cairo_lang_semantic/expr/
fmt.rs1use cairo_lang_debug::DebugWithDb;
2use cairo_lang_debug::debug::DebugDbUpcast;
3use cairo_lang_defs::ids::FunctionWithBodyId;
4use salsa::Database;
5
6use crate::items::function_with_body::FunctionWithBodySemantic;
7use crate::{ExprId, PatternId, StatementId};
8
9pub struct ExprFormatter<'db> {
12    pub db: &'db dyn Database,
13    pub function_id: FunctionWithBodyId<'db>,
14}
15
16impl<'db> DebugDbUpcast<'db, dyn Database> for ExprFormatter<'db> {
17    fn debug_db_upcast(&'db self) -> &'db dyn Database {
18        self.db
19    }
20}
21
22impl<'db> DebugWithDb<'db> for ExprId {
23    type Db = ExprFormatter<'db>;
24    fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &'db Self::Db) -> std::fmt::Result {
25        let expr = db.db.expr_semantic(db.function_id, *self);
26        expr.fmt(f, db)
27    }
28}
29
30impl<'db> DebugWithDb<'db> for PatternId {
31    type Db = ExprFormatter<'db>;
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &'db Self::Db) -> std::fmt::Result {
33        let pattern = db.db.pattern_semantic(db.function_id, *self);
34        pattern.fmt(f, db)
35    }
36}
37
38impl<'db> DebugWithDb<'db> for StatementId {
39    type Db = ExprFormatter<'db>;
40    fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &'db Self::Db) -> std::fmt::Result {
41        let statement = db.db.statement_semantic(db.function_id, *self);
42        statement.fmt(f, db)
43    }
44}
45
46pub struct CountingWriter<'a, 'b> {
48    inner: &'a mut std::fmt::Formatter<'b>,
49    count: usize,
50}
51
52impl<'a, 'b> CountingWriter<'a, 'b> {
53    pub fn new(inner: &'a mut std::fmt::Formatter<'b>) -> Self {
54        Self { inner, count: 0 }
55    }
56
57    pub fn count(&self) -> usize {
58        self.count
59    }
60}
61
62impl<'a, 'b> std::fmt::Write for CountingWriter<'a, 'b> {
63    fn write_str(&mut self, s: &str) -> std::fmt::Result {
64        self.count += s.len();
65        self.inner.write_str(s)
66    }
67}