no-mistakes-postgres-engine 0.109.131

PostgreSQL embedded SQL extraction, schema catalog, and replay-safety analysis for no-mistakes
Documentation
use super::{unwrap_ts_wrappers, Expression, ScopeVisitor};
use crate::embedded::walk::resolve::{for_each_bound_name, hoisted_names};
use oxc_ast::ast::{
    ArrowFunctionBody, ArrowFunctionExpression, BlockStatement, CatchClause, ForInStatement,
    ForOfStatement, ForStatement, FormalParameters, Function, IdentifierReference, ObjectProperty,
    SwitchStatement, VariableDeclaration,
};
use oxc_ast_visit::{walk, Visit};
use oxc_syntax::scope::ScopeFlags;
mod declarations;
use declarations::declaration_names;

pub(super) fn mutate(visitor: &mut ScopeVisitor<'_>, expression: &Expression<'_>) {
    struct Escape<'a, 'b> {
        visitor: &'a mut ScopeVisitor<'b>,
        shadowed: Vec<Vec<String>>,
        function_frames: Vec<usize>,
    }
    impl Escape<'_, '_> {
        fn is_shadowed(&self, name: &str) -> bool {
            self.shadowed
                .iter()
                .any(|scope| scope.iter().any(|bound| bound == name))
        }
        fn push_function_frame(&mut self, params: &FormalParameters<'_>) {
            let mut names = Vec::new();
            for param in &params.items {
                for_each_bound_name(&param.pattern, &mut |name| names.push(name.to_owned()));
            }
            if let Some(rest) = &params.rest {
                for_each_bound_name(&rest.rest.argument, &mut |name| names.push(name.to_owned()));
            }
            self.function_frames.push(self.shadowed.len());
            self.shadowed.push(names);
        }
        fn pop_function_frame(&mut self) {
            self.shadowed.pop();
            self.function_frames.pop();
        }
        fn with_lexical_scope(&mut self, names: Vec<String>, walk: impl FnOnce(&mut Self)) {
            self.shadowed.push(names);
            walk(self);
            self.shadowed.pop();
        }
    }
    impl<'a> Visit<'a> for Escape<'_, '_> {
        fn visit_expression(&mut self, expr: &Expression<'a>) {
            match expr {
                Expression::BinaryExpression(_) | Expression::UnaryExpression(_) => {}
                Expression::ConditionalExpression(cond) => {
                    self.visit_expression(&cond.consequent);
                    self.visit_expression(&cond.alternate);
                }
                Expression::SequenceExpression(seq) => {
                    if let Some(last) = seq.expressions.last() {
                        self.visit_expression(last);
                    }
                }
                Expression::CallExpression(call)
                    if unwrap_ts_wrappers(&call.callee)
                        .as_member_expression()
                        .is_some_and(|member| {
                            !matches!(
                                member.static_property_name().and_then(|name| name.as_str()),
                                Some("bind" | "call" | "apply")
                            )
                        }) =>
                {
                    self.visit_arguments(&call.arguments);
                }
                _ => walk::walk_expression(self, expr),
            }
        }
        fn visit_object_property(&mut self, prop: &ObjectProperty<'a>) {
            self.visit_expression(&prop.value);
        }
        fn visit_function(&mut self, func: &Function<'a>, _flags: ScopeFlags) {
            self.push_function_frame(&func.params);
            if let Some(name) = &func.id {
                self.shadowed
                    .last_mut()
                    .unwrap()
                    .push(name.name.to_string());
            }
            self.visit_formal_parameters(&func.params);
            if let Some(body) = &func.body {
                self.shadowed
                    .last_mut()
                    .unwrap()
                    .extend(hoisted_names(&body.statements).into_keys());
                self.shadowed
                    .last_mut()
                    .unwrap()
                    .extend(declaration_names(body.statements.iter()));
                self.visit_function_body(body);
            }
            self.pop_function_frame();
        }
        fn visit_arrow_function_expression(&mut self, arrow: &ArrowFunctionExpression<'a>) {
            self.push_function_frame(&arrow.params);
            self.visit_formal_parameters(&arrow.params);
            if let ArrowFunctionBody::FunctionBody(body) = &arrow.body {
                self.shadowed
                    .last_mut()
                    .unwrap()
                    .extend(hoisted_names(&body.statements).into_keys());
                self.shadowed
                    .last_mut()
                    .unwrap()
                    .extend(declaration_names(body.statements.iter()));
            }
            self.visit_arrow_function_body(&arrow.body);
            self.pop_function_frame();
        }
        fn visit_block_statement(&mut self, block: &BlockStatement<'a>) {
            self.with_lexical_scope(declaration_names(block.body.iter()), |this| {
                walk::walk_block_statement(this, block);
            });
        }
        fn visit_for_statement(&mut self, stmt: &ForStatement<'a>) {
            self.with_lexical_scope(Vec::new(), |this| walk::walk_for_statement(this, stmt));
        }
        fn visit_for_in_statement(&mut self, stmt: &ForInStatement<'a>) {
            self.with_lexical_scope(Vec::new(), |this| walk::walk_for_in_statement(this, stmt));
        }
        fn visit_for_of_statement(&mut self, stmt: &ForOfStatement<'a>) {
            self.with_lexical_scope(Vec::new(), |this| walk::walk_for_of_statement(this, stmt));
        }
        fn visit_switch_statement(&mut self, stmt: &SwitchStatement<'a>) {
            self.visit_expression(&stmt.discriminant);
            let names =
                declaration_names(stmt.cases.iter().flat_map(|case| case.consequent.iter()));
            self.with_lexical_scope(names, |this| {
                for case in &stmt.cases {
                    this.visit_switch_case(case);
                }
            });
        }
        fn visit_catch_clause(&mut self, clause: &CatchClause<'a>) {
            let mut names = Vec::new();
            if let Some(param) = &clause.param {
                for_each_bound_name(&param.pattern, &mut |name| names.push(name.to_owned()));
            }
            self.with_lexical_scope(names, |this| walk::walk_catch_clause(this, clause));
        }
        fn visit_variable_declaration(&mut self, decl: &VariableDeclaration<'a>) {
            for declarator in &decl.declarations {
                if let Some(init) = &declarator.init {
                    self.visit_expression(init);
                }
                self.visit_binding_pattern(&declarator.id);
                let frame = if decl.kind.is_var() {
                    self.function_frames
                        .last()
                        .copied()
                        .and_then(|index| self.shadowed.get_mut(index))
                } else {
                    self.shadowed.last_mut()
                };
                if let Some(scope) = frame {
                    for_each_bound_name(&declarator.id, &mut |name| scope.push(name.to_owned()));
                }
            }
        }
        fn visit_identifier_reference(&mut self, id: &IdentifierReference<'a>) {
            if !self.is_shadowed(id.name.as_str()) {
                mutate_identifier(self.visitor, id);
            }
        }
    }
    Escape {
        visitor,
        shadowed: Vec::new(),
        function_frames: Vec::new(),
    }
    .visit_expression(expression);
}

fn mutate_identifier(visitor: &mut ScopeVisitor<'_>, id: &IdentifierReference<'_>) {
    if visitor
        .transaction_options
        .option_receiver_reads
        .get_mut()
        .remove(&id.span.start)
    {
        return;
    }
    let Some(identity) = visitor
        .lookup(id.name.as_str())
        .and_then(|binding| binding.value_identity)
    else {
        return;
    };
    let origin = visitor
        .transaction_options
        .aliases
        .get(&identity)
        .map(|captured| captured.identity)
        .unwrap_or(identity);
    visitor.transaction_options.mutated.insert(origin);
}