forge_doc/solang_ext/
visit.rs

1//! Visitor helpers to traverse the [solang Solidity Parse Tree](solang_parser::pt).
2
3use crate::solang_ext::{CodeLocationExt, pt::*};
4
5/// A trait that is invoked while traversing the Solidity Parse Tree.
6/// Each method of the [Visitor] trait is a hook that can be potentially overridden.
7///
8/// Currently the main implementer of this trait is the [`Formatter`](crate::Formatter<'_>) struct.
9pub trait Visitor {
10    type Error: std::error::Error;
11
12    fn visit_source(&mut self, _loc: Loc) -> Result<(), Self::Error> {
13        Ok(())
14    }
15
16    fn visit_source_unit(&mut self, _source_unit: &mut SourceUnit) -> Result<(), Self::Error> {
17        Ok(())
18    }
19
20    fn visit_contract(&mut self, _contract: &mut ContractDefinition) -> Result<(), Self::Error> {
21        Ok(())
22    }
23
24    fn visit_annotation(&mut self, annotation: &mut Annotation) -> Result<(), Self::Error> {
25        self.visit_source(annotation.loc)
26    }
27
28    fn visit_pragma(&mut self, pragma: &mut PragmaDirective) -> Result<(), Self::Error> {
29        self.visit_source(pragma.loc())
30    }
31
32    fn visit_import_plain(
33        &mut self,
34        _loc: Loc,
35        _import: &mut ImportPath,
36    ) -> Result<(), Self::Error> {
37        Ok(())
38    }
39
40    fn visit_import_global(
41        &mut self,
42        _loc: Loc,
43        _global: &mut ImportPath,
44        _alias: &mut Identifier,
45    ) -> Result<(), Self::Error> {
46        Ok(())
47    }
48
49    fn visit_import_renames(
50        &mut self,
51        _loc: Loc,
52        _imports: &mut [(Identifier, Option<Identifier>)],
53        _from: &mut ImportPath,
54    ) -> Result<(), Self::Error> {
55        Ok(())
56    }
57
58    fn visit_enum(&mut self, _enum: &mut EnumDefinition) -> Result<(), Self::Error> {
59        Ok(())
60    }
61
62    fn visit_assembly(
63        &mut self,
64        loc: Loc,
65        _dialect: &mut Option<StringLiteral>,
66        _block: &mut YulBlock,
67        _flags: &mut Option<Vec<StringLiteral>>,
68    ) -> Result<(), Self::Error> {
69        self.visit_source(loc)
70    }
71
72    fn visit_block(
73        &mut self,
74        loc: Loc,
75        _unchecked: bool,
76        _statements: &mut Vec<Statement>,
77    ) -> Result<(), Self::Error> {
78        self.visit_source(loc)
79    }
80
81    fn visit_args(&mut self, loc: Loc, _args: &mut Vec<NamedArgument>) -> Result<(), Self::Error> {
82        self.visit_source(loc)
83    }
84
85    /// Don't write semicolon at the end because expressions can appear as both
86    /// part of other node and a statement in the function body
87    fn visit_expr(&mut self, loc: Loc, _expr: &mut Expression) -> Result<(), Self::Error> {
88        self.visit_source(loc)
89    }
90
91    fn visit_ident(&mut self, loc: Loc, _ident: &mut Identifier) -> Result<(), Self::Error> {
92        self.visit_source(loc)
93    }
94
95    fn visit_ident_path(&mut self, idents: &mut IdentifierPath) -> Result<(), Self::Error> {
96        self.visit_source(idents.loc)
97    }
98
99    fn visit_emit(&mut self, loc: Loc, _event: &mut Expression) -> Result<(), Self::Error> {
100        self.visit_source(loc)?;
101        self.visit_stray_semicolon()?;
102
103        Ok(())
104    }
105
106    fn visit_var_definition(&mut self, var: &mut VariableDefinition) -> Result<(), Self::Error> {
107        self.visit_source(var.loc)?;
108        self.visit_stray_semicolon()?;
109
110        Ok(())
111    }
112
113    fn visit_var_definition_stmt(
114        &mut self,
115        loc: Loc,
116        _declaration: &mut VariableDeclaration,
117        _expr: &mut Option<Expression>,
118    ) -> Result<(), Self::Error> {
119        self.visit_source(loc)?;
120        self.visit_stray_semicolon()
121    }
122
123    fn visit_var_declaration(&mut self, var: &mut VariableDeclaration) -> Result<(), Self::Error> {
124        self.visit_source(var.loc)
125    }
126
127    fn visit_return(
128        &mut self,
129        loc: Loc,
130        _expr: &mut Option<Expression>,
131    ) -> Result<(), Self::Error> {
132        self.visit_source(loc)?;
133        self.visit_stray_semicolon()?;
134
135        Ok(())
136    }
137
138    fn visit_revert(
139        &mut self,
140        loc: Loc,
141        _error: &mut Option<IdentifierPath>,
142        _args: &mut Vec<Expression>,
143    ) -> Result<(), Self::Error> {
144        self.visit_source(loc)?;
145        self.visit_stray_semicolon()?;
146
147        Ok(())
148    }
149
150    fn visit_revert_named_args(
151        &mut self,
152        loc: Loc,
153        _error: &mut Option<IdentifierPath>,
154        _args: &mut Vec<NamedArgument>,
155    ) -> Result<(), Self::Error> {
156        self.visit_source(loc)?;
157        self.visit_stray_semicolon()?;
158
159        Ok(())
160    }
161
162    fn visit_break(&mut self, loc: Loc, _semicolon: bool) -> Result<(), Self::Error> {
163        self.visit_source(loc)
164    }
165
166    fn visit_continue(&mut self, loc: Loc, _semicolon: bool) -> Result<(), Self::Error> {
167        self.visit_source(loc)
168    }
169
170    #[expect(clippy::type_complexity)]
171    fn visit_try(
172        &mut self,
173        loc: Loc,
174        _expr: &mut Expression,
175        _returns: &mut Option<(Vec<(Loc, Option<Parameter>)>, Box<Statement>)>,
176        _clauses: &mut Vec<CatchClause>,
177    ) -> Result<(), Self::Error> {
178        self.visit_source(loc)
179    }
180
181    fn visit_if(
182        &mut self,
183        loc: Loc,
184        _cond: &mut Expression,
185        _if_branch: &mut Box<Statement>,
186        _else_branch: &mut Option<Box<Statement>>,
187        _is_first_stmt: bool,
188    ) -> Result<(), Self::Error> {
189        self.visit_source(loc)
190    }
191
192    fn visit_do_while(
193        &mut self,
194        loc: Loc,
195        _body: &mut Statement,
196        _cond: &mut Expression,
197    ) -> Result<(), Self::Error> {
198        self.visit_source(loc)
199    }
200
201    fn visit_while(
202        &mut self,
203        loc: Loc,
204        _cond: &mut Expression,
205        _body: &mut Statement,
206    ) -> Result<(), Self::Error> {
207        self.visit_source(loc)
208    }
209
210    fn visit_for(
211        &mut self,
212        loc: Loc,
213        _init: &mut Option<Box<Statement>>,
214        _cond: &mut Option<Box<Expression>>,
215        _update: &mut Option<Box<Expression>>,
216        _body: &mut Option<Box<Statement>>,
217    ) -> Result<(), Self::Error> {
218        self.visit_source(loc)
219    }
220
221    fn visit_function(&mut self, func: &mut FunctionDefinition) -> Result<(), Self::Error> {
222        self.visit_source(func.loc())?;
223        if func.body.is_none() {
224            self.visit_stray_semicolon()?;
225        }
226
227        Ok(())
228    }
229
230    fn visit_function_attribute(
231        &mut self,
232        attribute: &mut FunctionAttribute,
233    ) -> Result<(), Self::Error> {
234        self.visit_source(attribute.loc())?;
235        Ok(())
236    }
237
238    fn visit_var_attribute(
239        &mut self,
240        attribute: &mut VariableAttribute,
241    ) -> Result<(), Self::Error> {
242        self.visit_source(attribute.loc())?;
243        Ok(())
244    }
245
246    fn visit_base(&mut self, base: &mut Base) -> Result<(), Self::Error> {
247        self.visit_source(base.loc)
248    }
249
250    fn visit_parameter(&mut self, parameter: &mut Parameter) -> Result<(), Self::Error> {
251        self.visit_source(parameter.loc)
252    }
253
254    fn visit_struct(&mut self, structure: &mut StructDefinition) -> Result<(), Self::Error> {
255        self.visit_source(structure.loc)?;
256
257        Ok(())
258    }
259
260    fn visit_event(&mut self, event: &mut EventDefinition) -> Result<(), Self::Error> {
261        self.visit_source(event.loc)?;
262        self.visit_stray_semicolon()?;
263
264        Ok(())
265    }
266
267    fn visit_event_parameter(&mut self, param: &mut EventParameter) -> Result<(), Self::Error> {
268        self.visit_source(param.loc)
269    }
270
271    fn visit_error(&mut self, error: &mut ErrorDefinition) -> Result<(), Self::Error> {
272        self.visit_source(error.loc)?;
273        self.visit_stray_semicolon()?;
274
275        Ok(())
276    }
277
278    fn visit_error_parameter(&mut self, param: &mut ErrorParameter) -> Result<(), Self::Error> {
279        self.visit_source(param.loc)
280    }
281
282    fn visit_type_definition(&mut self, def: &mut TypeDefinition) -> Result<(), Self::Error> {
283        self.visit_source(def.loc)
284    }
285
286    fn visit_stray_semicolon(&mut self) -> Result<(), Self::Error> {
287        Ok(())
288    }
289
290    fn visit_using(&mut self, using: &mut Using) -> Result<(), Self::Error> {
291        self.visit_source(using.loc)?;
292        self.visit_stray_semicolon()?;
293
294        Ok(())
295    }
296
297    fn visit_yul_block(
298        &mut self,
299        loc: Loc,
300        _stmts: &mut Vec<YulStatement>,
301        _attempt_single_line: bool,
302    ) -> Result<(), Self::Error> {
303        self.visit_source(loc)
304    }
305
306    fn visit_yul_expr(&mut self, expr: &mut YulExpression) -> Result<(), Self::Error> {
307        self.visit_source(expr.loc())
308    }
309
310    fn visit_yul_assignment<T>(
311        &mut self,
312        loc: Loc,
313        _exprs: &mut Vec<T>,
314        _expr: &mut Option<&mut YulExpression>,
315    ) -> Result<(), Self::Error>
316    where
317        T: Visitable + CodeLocationExt,
318    {
319        self.visit_source(loc)
320    }
321
322    fn visit_yul_for(&mut self, stmt: &mut YulFor) -> Result<(), Self::Error> {
323        self.visit_source(stmt.loc)
324    }
325
326    fn visit_yul_function_call(&mut self, stmt: &mut YulFunctionCall) -> Result<(), Self::Error> {
327        self.visit_source(stmt.loc)
328    }
329
330    fn visit_yul_fun_def(&mut self, stmt: &mut YulFunctionDefinition) -> Result<(), Self::Error> {
331        self.visit_source(stmt.loc)
332    }
333
334    fn visit_yul_if(
335        &mut self,
336        loc: Loc,
337        _expr: &mut YulExpression,
338        _block: &mut YulBlock,
339    ) -> Result<(), Self::Error> {
340        self.visit_source(loc)
341    }
342
343    fn visit_yul_leave(&mut self, loc: Loc) -> Result<(), Self::Error> {
344        self.visit_source(loc)
345    }
346
347    fn visit_yul_switch(&mut self, stmt: &mut YulSwitch) -> Result<(), Self::Error> {
348        self.visit_source(stmt.loc)
349    }
350
351    fn visit_yul_var_declaration(
352        &mut self,
353        loc: Loc,
354        _idents: &mut Vec<YulTypedIdentifier>,
355        _expr: &mut Option<YulExpression>,
356    ) -> Result<(), Self::Error> {
357        self.visit_source(loc)
358    }
359
360    fn visit_yul_typed_ident(&mut self, ident: &mut YulTypedIdentifier) -> Result<(), Self::Error> {
361        self.visit_source(ident.loc)
362    }
363
364    fn visit_parser_error(&mut self, loc: Loc) -> Result<(), Self::Error> {
365        self.visit_source(loc)
366    }
367}
368
369/// Visitable trait for [`solang_parser::pt`] types.
370///
371/// All [`solang_parser::pt`] types, such as [Statement], should implement the [Visitable] trait
372/// that accepts a trait [Visitor] implementation, which has various callback handles for Solidity
373/// Parse Tree nodes.
374///
375/// We want to take a `&mut self` to be able to implement some advanced features in the future such
376/// as modifying the Parse Tree before formatting it.
377pub trait Visitable {
378    fn visit<V>(&mut self, v: &mut V) -> Result<(), V::Error>
379    where
380        V: Visitor;
381}
382
383impl<T> Visitable for &mut T
384where
385    T: Visitable,
386{
387    fn visit<V>(&mut self, v: &mut V) -> Result<(), V::Error>
388    where
389        V: Visitor,
390    {
391        T::visit(self, v)
392    }
393}
394
395impl<T> Visitable for Option<T>
396where
397    T: Visitable,
398{
399    fn visit<V>(&mut self, v: &mut V) -> Result<(), V::Error>
400    where
401        V: Visitor,
402    {
403        if let Some(inner) = self.as_mut() { inner.visit(v) } else { Ok(()) }
404    }
405}
406
407impl<T> Visitable for Box<T>
408where
409    T: Visitable,
410{
411    fn visit<V>(&mut self, v: &mut V) -> Result<(), V::Error>
412    where
413        V: Visitor,
414    {
415        T::visit(self, v)
416    }
417}
418
419impl<T> Visitable for Vec<T>
420where
421    T: Visitable,
422{
423    fn visit<V>(&mut self, v: &mut V) -> Result<(), V::Error>
424    where
425        V: Visitor,
426    {
427        for item in self.iter_mut() {
428            item.visit(v)?;
429        }
430        Ok(())
431    }
432}
433
434impl Visitable for SourceUnitPart {
435    fn visit<V>(&mut self, v: &mut V) -> Result<(), V::Error>
436    where
437        V: Visitor,
438    {
439        match self {
440            Self::ContractDefinition(contract) => v.visit_contract(contract),
441            Self::PragmaDirective(pragma) => v.visit_pragma(pragma),
442            Self::ImportDirective(import) => import.visit(v),
443            Self::EnumDefinition(enumeration) => v.visit_enum(enumeration),
444            Self::StructDefinition(structure) => v.visit_struct(structure),
445            Self::EventDefinition(event) => v.visit_event(event),
446            Self::ErrorDefinition(error) => v.visit_error(error),
447            Self::FunctionDefinition(function) => v.visit_function(function),
448            Self::VariableDefinition(variable) => v.visit_var_definition(variable),
449            Self::TypeDefinition(def) => v.visit_type_definition(def),
450            Self::StraySemicolon(_) => v.visit_stray_semicolon(),
451            Self::Using(using) => v.visit_using(using),
452            Self::Annotation(annotation) => v.visit_annotation(annotation),
453        }
454    }
455}
456
457impl Visitable for Import {
458    fn visit<V>(&mut self, v: &mut V) -> Result<(), V::Error>
459    where
460        V: Visitor,
461    {
462        match self {
463            Self::Plain(import, loc) => v.visit_import_plain(*loc, import),
464            Self::GlobalSymbol(global, import_as, loc) => {
465                v.visit_import_global(*loc, global, import_as)
466            }
467            Self::Rename(from, imports, loc) => v.visit_import_renames(*loc, imports, from),
468        }
469    }
470}
471
472impl Visitable for ContractPart {
473    fn visit<V>(&mut self, v: &mut V) -> Result<(), V::Error>
474    where
475        V: Visitor,
476    {
477        match self {
478            Self::StructDefinition(structure) => v.visit_struct(structure),
479            Self::EventDefinition(event) => v.visit_event(event),
480            Self::ErrorDefinition(error) => v.visit_error(error),
481            Self::EnumDefinition(enumeration) => v.visit_enum(enumeration),
482            Self::VariableDefinition(variable) => v.visit_var_definition(variable),
483            Self::FunctionDefinition(function) => v.visit_function(function),
484            Self::TypeDefinition(def) => v.visit_type_definition(def),
485            Self::StraySemicolon(_) => v.visit_stray_semicolon(),
486            Self::Using(using) => v.visit_using(using),
487            Self::Annotation(annotation) => v.visit_annotation(annotation),
488        }
489    }
490}
491
492impl Visitable for Statement {
493    fn visit<V>(&mut self, v: &mut V) -> Result<(), V::Error>
494    where
495        V: Visitor,
496    {
497        match self {
498            Self::Block { loc, unchecked, statements } => {
499                v.visit_block(*loc, *unchecked, statements)
500            }
501            Self::Assembly { loc, dialect, block, flags } => {
502                v.visit_assembly(*loc, dialect, block, flags)
503            }
504            Self::Args(loc, args) => v.visit_args(*loc, args),
505            Self::If(loc, cond, if_branch, else_branch) => {
506                v.visit_if(*loc, cond, if_branch, else_branch, true)
507            }
508            Self::While(loc, cond, body) => v.visit_while(*loc, cond, body),
509            Self::Expression(loc, expr) => {
510                v.visit_expr(*loc, expr)?;
511                v.visit_stray_semicolon()
512            }
513            Self::VariableDefinition(loc, declaration, expr) => {
514                v.visit_var_definition_stmt(*loc, declaration, expr)
515            }
516            Self::For(loc, init, cond, update, body) => v.visit_for(*loc, init, cond, update, body),
517            Self::DoWhile(loc, body, cond) => v.visit_do_while(*loc, body, cond),
518            Self::Continue(loc) => v.visit_continue(*loc, true),
519            Self::Break(loc) => v.visit_break(*loc, true),
520            Self::Return(loc, expr) => v.visit_return(*loc, expr),
521            Self::Revert(loc, error, args) => v.visit_revert(*loc, error, args),
522            Self::RevertNamedArgs(loc, error, args) => v.visit_revert_named_args(*loc, error, args),
523            Self::Emit(loc, event) => v.visit_emit(*loc, event),
524            Self::Try(loc, expr, returns, clauses) => v.visit_try(*loc, expr, returns, clauses),
525            Self::Error(loc) => v.visit_parser_error(*loc),
526        }
527    }
528}
529
530impl Visitable for Loc {
531    fn visit<V>(&mut self, v: &mut V) -> Result<(), V::Error>
532    where
533        V: Visitor,
534    {
535        v.visit_source(*self)
536    }
537}
538
539impl Visitable for Expression {
540    fn visit<V>(&mut self, v: &mut V) -> Result<(), V::Error>
541    where
542        V: Visitor,
543    {
544        v.visit_expr(self.loc(), self)
545    }
546}
547
548impl Visitable for Identifier {
549    fn visit<V>(&mut self, v: &mut V) -> Result<(), V::Error>
550    where
551        V: Visitor,
552    {
553        v.visit_ident(self.loc, self)
554    }
555}
556
557impl Visitable for VariableDeclaration {
558    fn visit<V>(&mut self, v: &mut V) -> Result<(), V::Error>
559    where
560        V: Visitor,
561    {
562        v.visit_var_declaration(self)
563    }
564}
565
566impl Visitable for YulBlock {
567    fn visit<V>(&mut self, v: &mut V) -> Result<(), V::Error>
568    where
569        V: Visitor,
570    {
571        v.visit_yul_block(self.loc, self.statements.as_mut(), false)
572    }
573}
574
575impl Visitable for YulStatement {
576    fn visit<V>(&mut self, v: &mut V) -> Result<(), V::Error>
577    where
578        V: Visitor,
579    {
580        match self {
581            Self::Assign(loc, exprs, expr) => v.visit_yul_assignment(*loc, exprs, &mut Some(expr)),
582            Self::Block(block) => v.visit_yul_block(block.loc, block.statements.as_mut(), false),
583            Self::Break(loc) => v.visit_break(*loc, false),
584            Self::Continue(loc) => v.visit_continue(*loc, false),
585            Self::For(stmt) => v.visit_yul_for(stmt),
586            Self::FunctionCall(stmt) => v.visit_yul_function_call(stmt),
587            Self::FunctionDefinition(stmt) => v.visit_yul_fun_def(stmt),
588            Self::If(loc, expr, block) => v.visit_yul_if(*loc, expr, block),
589            Self::Leave(loc) => v.visit_yul_leave(*loc),
590            Self::Switch(stmt) => v.visit_yul_switch(stmt),
591            Self::VariableDeclaration(loc, idents, expr) => {
592                v.visit_yul_var_declaration(*loc, idents, expr)
593            }
594            Self::Error(loc) => v.visit_parser_error(*loc),
595        }
596    }
597}
598
599macro_rules! impl_visitable {
600    ($type:ty, $func:ident) => {
601        impl Visitable for $type {
602            fn visit<V>(&mut self, v: &mut V) -> Result<(), V::Error>
603            where
604                V: Visitor,
605            {
606                v.$func(self)
607            }
608        }
609    };
610}
611
612impl_visitable!(SourceUnit, visit_source_unit);
613impl_visitable!(FunctionAttribute, visit_function_attribute);
614impl_visitable!(VariableAttribute, visit_var_attribute);
615impl_visitable!(Parameter, visit_parameter);
616impl_visitable!(Base, visit_base);
617impl_visitable!(EventParameter, visit_event_parameter);
618impl_visitable!(ErrorParameter, visit_error_parameter);
619impl_visitable!(IdentifierPath, visit_ident_path);
620impl_visitable!(YulExpression, visit_yul_expr);
621impl_visitable!(YulTypedIdentifier, visit_yul_typed_ident);