use crate::ast::AstNode; use crate::generated::keywords::PLPGSQL_UNRESERVED_KEYWORDS; use crate::plpgsql::PlpgsqlReturns; use crate::quote::is_keyword_in; use crate::{SyntaxNode, SyntaxToken, ast, match_ast, syntax_error::SyntaxError, validation}; use squawk_parser::SyntaxKind::*; use squawk_rowan::{TextRange, WalkEvent}; pub(crate) fn validate(root: &SyntaxNode, returns: PlpgsqlReturns, acc: &mut Vec) { validation::validate_with(root, acc, |node, acc| validate_node(node, returns, acc)); } fn validate_node(node: &SyntaxNode, returns: PlpgsqlReturns, acc: &mut Vec) { match_ast! { match node { ast::PercentType(it) => validate_plpgsql_percent_type( it.syntax(), it.percent_type_clause().and_then(|it| it.percent_token()), "`%type`", acc, ), ast::PlpgsqlBlock(it) => validate_plpgsql_block(&it, acc), ast::PlpgsqlCaseStmt(it) => validate_no_bare_case(it.subject(), acc), ast::PlpgsqlCompOptionPrintStrictParams(it) => { validate_print_strict_params(&it, acc); }, ast::PlpgsqlCaseWhen(it) => validate_no_bare_case(it.cond(), acc), ast::PlpgsqlElsifClause(it) => validate_no_bare_case(it.cond(), acc), ast::PlpgsqlFetchStmt(it) => { validate_fetch_no_strict(it.into_clause(), acc); validate_fetch_single_row(&it, acc); }, ast::PlpgsqlForCursorStmt(it) => validate_for_cursor_single_var(&it, acc), ast::PlpgsqlForIStmt(it) => validate_for_i_single_var(&it, acc), ast::PlpgsqlForQueryStmt(it) => validate_for_query_no_reverse(&it, acc), ast::PlpgsqlIfStmt(it) => validate_no_bare_case(it.cond(), acc), ast::PlpgsqlDeclareSection(it) => validate_duplicate_declarations(&it, acc), ast::PlpgsqlVarDecl(it) => validate_not_null_default(&it, acc), ast::PlpgsqlRaiseStmt(it) => validate_raise_params(&it, acc), ast::PlpgsqlCondition(it) => validate_sqlstate(&it, acc), ast::PlpgsqlLabelNameRef(it) => validate_end_label(&it, acc), ast::PlpgsqlExitStmt(it) => { validate_exit(it.syntax(), it.label(), ExitKind::Exit, acc); }, ast::PlpgsqlContinueStmt(it) => { validate_exit(it.syntax(), it.label(), ExitKind::Continue, acc); }, ast::PlpgsqlGetDiagStmt(it) => validate_diag_items(&it, acc), ast::PlpgsqlReturnStmt(it) => validate_return(&it, returns, acc), ast::PlpgsqlForVariable(it) => validate_for_variable(&it, acc), ast::PlpgsqlPercentRowtype(it) => validate_plpgsql_percent_type( it.syntax(), it.percent_token(), "`%rowtype`", acc, ), _ => (), } } } fn validate_plpgsql_percent_type( syntax: &SyntaxNode, percent: Option, percent_type: &str, acc: &mut Vec, ) { if !syntax .parent() .is_some_and(|parent| matches!(parent.kind(), PLPGSQL_VAR_DECL | PLPGSQL_CURSOR_ARG)) { return; } let has_uescape = syntax .descendants_with_tokens() .any(|element| element.kind() == UESCAPE_KW); if !has_uescape { return; } let Some(percent) = percent else { return; }; acc.push(SyntaxError::new( format!("`uescape` is not allowed before {percent_type}"), percent.text_range(), )); } fn validate_plpgsql_block(it: &ast::PlpgsqlBlock, acc: &mut Vec) { if it.semicolon_token().is_some() || it .syntax() .parent() .is_none_or(|parent| parent.kind() != PLPGSQL_BODY) { return; } acc.push(SyntaxError::new( "missing semicolon after block", TextRange::empty(it.syntax().text_range().end()), )); } fn validate_print_strict_params( it: &ast::PlpgsqlCompOptionPrintStrictParams, acc: &mut Vec, ) { let Some(value) = it.option_value() else { return; }; let text = value.text(); if text != "on" && text != "off" { acc.push(SyntaxError::new( format!("unrecognized print_strict_params option {text}"), value.syntax().text_range(), )); } } // -- err // fetch all from c into x; // fetch forward 2 from c into x; // -- ok // fetch forward from c into x; fn validate_fetch_single_row(it: &ast::PlpgsqlFetchStmt, acc: &mut Vec) { let Some(direction) = it.direction() else { return; }; let multiple_rows = match &direction { ast::CursorAction::All(_) | ast::CursorAction::Expr(_) => true, ast::CursorAction::Forward(it) => it.all_token().is_some() || it.expr().is_some(), ast::CursorAction::Backward(it) => it.all_token().is_some() || it.expr().is_some(), _ => false, }; if multiple_rows { acc.push(SyntaxError::new( "`fetch` statement cannot return multiple rows", direction.syntax().text_range(), )); } } // -- err // fetch c into strict x; // -- ok // execute q into strict x; fn validate_fetch_no_strict(it: Option, acc: &mut Vec) { let Some(strict) = it.and_then(|it| it.strict_token()) else { return; }; acc.push(SyntaxError::new( "`fetch` does not support `strict`", strict.text_range(), )); } // -- err // for i, j in 1..2 loop null; end loop; // -- ok // for i in 1..2 loop null; end loop; fn validate_for_i_single_var(it: &ast::PlpgsqlForIStmt, acc: &mut Vec) { for var in it.vars().skip(1) { acc.push(SyntaxError::new( "integer `for` loop takes one variable", var.syntax().text_range(), )); } } // -- err // for a, b in c loop null; end loop; // -- ok // for a in c loop null; end loop; fn validate_for_cursor_single_var(it: &ast::PlpgsqlForCursorStmt, acc: &mut Vec) { for var in it.vars().skip(1) { acc.push(SyntaxError::new( "cursor `for` loop takes one variable", var.syntax().text_range(), )); } } // -- err // for r in reverse select 1 loop null; end loop; // -- ok // for r in select 1 loop null; end loop; fn validate_for_query_no_reverse(it: &ast::PlpgsqlForQueryStmt, acc: &mut Vec) { let Some(reverse) = it.reverse_token() else { return; }; acc.push(SyntaxError::new( "cannot specify `reverse` in query `for` loop", reverse.text_range(), )); } // -- err // if case when a then 1 end then // -- ok // if (case when a then 1 end) then fn validate_no_bare_case(cond: Option, acc: &mut Vec) { let Some(cond) = cond else { return; }; let mut depth = 0i32; let mut preorder = cond.syntax().preorder_with_tokens(); while let Some(event) = preorder.next() { let WalkEvent::Enter(element) = event else { continue; }; match element.kind() { L_PAREN | L_BRACK => depth += 1, R_PAREN | R_BRACK => depth -= 1, CASE_EXPR if depth == 0 => { acc.push(SyntaxError::new( "`case` expression must be parenthesized", element.text_range(), )); preorder.skip_subtree(); } _ => (), } } } fn validate_duplicate_declarations(it: &ast::PlpgsqlDeclareSection, acc: &mut Vec) { let mut decls = it.decls(); if decls.next().is_none() || decls.next().is_none() { return; } let names: Vec = it .decls() .filter_map(|decl| match decl { ast::PlpgsqlDecl::PlpgsqlAliasDecl(decl) => decl.name(), ast::PlpgsqlDecl::PlpgsqlCursorDecl(decl) => decl.name(), ast::PlpgsqlDecl::PlpgsqlVarDecl(decl) => decl.name(), }) .collect(); let texts: Vec<_> = names .iter() .map(|name| ast::normalize_name_node(name.syntax())) .collect(); for (i, text) in texts.iter().enumerate() { if texts[..i].contains(text) { acc.push(SyntaxError::new( format!("duplicate declaration of `{text}`"), names[i].syntax().text_range(), )); } } } fn validate_not_null_default(it: &ast::PlpgsqlVarDecl, acc: &mut Vec) { if it.init().is_some() { return; } let (Some(not_null), Some(name)) = (it.not_null(), it.name()) else { return; }; acc.push(SyntaxError::new( format!( "`not null` variable `{}` must have a default value", ast::normalize_name_node(name.syntax()) ), not_null.syntax().text_range(), )); } fn validate_raise_params(it: &ast::PlpgsqlRaiseStmt, acc: &mut Vec) { let Some(literal) = it.message().and_then(|message| message.literal()) else { return; }; let expected = match literal.kind() { Some(ast::LitKind::String(token)) if token.next_sibling_or_token().is_none() => { count_placeholders(token.text()) } _ => { let Some(message) = literal.decoded_value() else { return; }; count_placeholders(message.text()) } }; let found = it.params().count(); if expected == found { return; } let s = if expected == 1 { "" } else { "s" }; acc.push(SyntaxError::new( format!("`raise` message expects {expected} parameter{s}, found {found}"), literal.syntax().text_range(), )); } fn count_placeholders(message: &str) -> usize { let mut count = 0; let mut bytes = message.as_bytes().iter(); while let Some(&b) = bytes.next() { if b != b'%' { continue; } if bytes.as_slice().first() == Some(&b'%') { bytes.next(); } else { count += 1; } } count } fn validate_sqlstate(it: &ast::PlpgsqlCondition, acc: &mut Vec) { if it.sqlstate_token().is_none() { return; } let Some(string) = it.string_token() else { return; }; let code = string .text() .strip_prefix('\'') .and_then(|text| text.strip_suffix('\'')) .unwrap_or(string.text()); if code.len() == 5 && code .bytes() .all(|b| b.is_ascii_digit() || b.is_ascii_uppercase()) { return; } acc.push( SyntaxError::new( format!("invalid SQLSTATE code `{code}`"), string.text_range(), ) .with_hint("SQLSTATE codes are five digits or uppercase letters"), ); } #[derive(Clone, Copy, PartialEq)] enum ScopeKind { Block, Loop, } impl ScopeKind { fn label(self) -> &'static str { match self { ScopeKind::Block => "block", ScopeKind::Loop => "loop", } } } struct LabelScope { kind: ScopeKind, label: Option, end_label: Option, } fn label_scope(node: &SyntaxNode) -> Option { let label = |label: Option| label.and_then(|label| label.name()); let (kind, label, end_label) = match node.kind() { PLPGSQL_BLOCK => { let it = ast::PlpgsqlBlock::cast(node.clone())?; (ScopeKind::Block, label(it.label()), it.end_label()) } PLPGSQL_LOOP_STMT => { let it = ast::PlpgsqlLoopStmt::cast(node.clone())?; (ScopeKind::Loop, label(it.label()), it.end_label()) } PLPGSQL_WHILE_STMT => { let it = ast::PlpgsqlWhileStmt::cast(node.clone())?; (ScopeKind::Loop, label(it.label()), it.end_label()) } PLPGSQL_FOR_I_STMT => { let it = ast::PlpgsqlForIStmt::cast(node.clone())?; (ScopeKind::Loop, label(it.label()), it.end_label()) } PLPGSQL_FOR_QUERY_STMT => { let it = ast::PlpgsqlForQueryStmt::cast(node.clone())?; (ScopeKind::Loop, label(it.label()), it.end_label()) } PLPGSQL_FOR_CURSOR_STMT => { let it = ast::PlpgsqlForCursorStmt::cast(node.clone())?; (ScopeKind::Loop, label(it.label()), it.end_label()) } PLPGSQL_FOR_DYN_STMT => { let it = ast::PlpgsqlForDynStmt::cast(node.clone())?; (ScopeKind::Loop, label(it.label()), it.end_label()) } PLPGSQL_FOR_EACH_STMT => { let it = ast::PlpgsqlForEachStmt::cast(node.clone())?; (ScopeKind::Loop, label(it.label()), it.end_label()) } _ => return None, }; Some(LabelScope { kind, label, end_label, }) } fn validate_end_label(it: &ast::PlpgsqlLabelNameRef, acc: &mut Vec) { let Some(scope) = it.syntax().parent().and_then(|parent| label_scope(&parent)) else { return; }; if scope.end_label.as_ref() != Some(it) { return; } let end = ast::normalize_name_node(it.syntax()); let message = match scope.label { None => format!( "end label `{end}` specified for unlabeled {}", scope.kind.label() ), Some(label) => { let label = ast::normalize_name_node(label.syntax()); if label == end { return; } format!("end label `{end}` differs from label `{label}`") } }; acc.push(SyntaxError::new(message, it.syntax().text_range())); } #[derive(Clone, Copy)] enum ExitKind { Exit, Continue, } fn validate_exit( stmt: &SyntaxNode, label: Option, kind: ExitKind, acc: &mut Vec, ) { let mut scopes = stmt.ancestors().filter_map(|node| label_scope(&node)); match label { Some(label) => { let name = ast::normalize_name_node(label.syntax()); let Some(scope) = scopes.find(|scope| { scope .label .as_ref() .is_some_and(|it| ast::normalize_name_node(it.syntax()) == name) }) else { return; }; if matches!(kind, ExitKind::Continue) && scope.kind == ScopeKind::Block { acc.push(SyntaxError::new( format!("block label `{name}` cannot be used in `continue`"), label.syntax().text_range(), )); } } None => { if scopes.any(|scope| scope.kind == ScopeKind::Loop) { return; } let Some(token) = stmt.first_token() else { return; }; let message = match kind { ExitKind::Exit => "`exit` cannot be used outside a loop, unless it has a label", ExitKind::Continue => "`continue` cannot be used outside a loop", }; acc.push(SyntaxError::new(message, token.text_range())); } } } fn validate_diag_items(it: &ast::PlpgsqlGetDiagStmt, acc: &mut Vec) { let stacked = it.area().is_some_and(|area| area.stacked_token().is_some()); for item in it .items() .into_iter() .flat_map(|list| list.plpgsql_diag_items()) { let Some(kind) = item.kind() else { continue; }; let current_only = kind.row_count_token().is_some() || kind.pg_routine_oid_token().is_some(); let stacked_only = kind.returned_sqlstate_token().is_some() || kind.column_name_token().is_some() || kind.constraint_name_token().is_some() || kind.pg_datatype_name_token().is_some() || kind.message_text_token().is_some() || kind.table_name_token().is_some() || kind.schema_name_token().is_some() || kind.pg_exception_detail_token().is_some() || kind.pg_exception_hint_token().is_some() || kind.pg_exception_context_token().is_some(); if (stacked && !current_only) || (!stacked && !stacked_only) { continue; } let area = if stacked { "stacked" } else { "current" }; acc.push(SyntaxError::new( format!( "`{}` is not allowed in `get {area} diagnostics`", kind.syntax().text() ), kind.syntax().text_range(), )); } } fn validate_for_variable(it: &ast::PlpgsqlForVariable, acc: &mut Vec) { let Some(name) = it.name() else { return; }; let Some(token) = name.syntax().first_token() else { return; }; if token.text().starts_with('"') || !is_keyword_in(PLPGSQL_UNRESERVED_KEYWORDS, token.text()) { return; } let text = ast::normalize_name_node(name.syntax()); let declared = it .syntax() .ancestors() .filter_map(ast::PlpgsqlBlock::cast) .filter_map(|block| block.declare_section()) .flat_map(|section| section.decls()) .any(|decl| { let name = match decl { ast::PlpgsqlDecl::PlpgsqlAliasDecl(decl) => decl.name(), ast::PlpgsqlDecl::PlpgsqlCursorDecl(decl) => decl.name(), ast::PlpgsqlDecl::PlpgsqlVarDecl(decl) => decl.name(), }; name.is_some_and(|name| ast::normalize_name_node(name.syntax()) == text) }); if declared { return; } acc.push(SyntaxError::new( format!("expected a loop variable, found keyword `{}`", token.text()), token.text_range(), )); } fn validate_return( it: &ast::PlpgsqlReturnStmt, returns: PlpgsqlReturns, acc: &mut Vec, ) { let Some(range) = it .expr() .map(|expr| expr.syntax().text_range()) .or_else(|| it.var().map(|var| var.syntax().text_range())) else { return; }; let (message, hint) = match returns { PlpgsqlReturns::Value => return, PlpgsqlReturns::Void => ( "`return` cannot have a value in a function returning `void`", None, ), PlpgsqlReturns::Procedure => ("`return` cannot have a value in a procedure", None), PlpgsqlReturns::OutParams => ( "`return` cannot have a value in a function with `out` parameters", None, ), PlpgsqlReturns::Set => ( "`return` cannot have a value in a function returning a set", Some("use `return next` or `return query`"), ), }; let error = SyntaxError::new(message, range); acc.push(match hint { Some(hint) => error.with_hint(hint), None => error, }); }