<commit_before>use crate::{MatchFinder, SsrRule};
use expect_test::{expect, Expect};
use ide_db::base_db::{salsa::Durability, FileId, FilePosition, FileRange, SourceDatabaseExt};
use rustc_hash::FxHashSet;
use std::sync::Arc;
use test_utils::{mark, RangeOrOffset};

fn parse_error_text(query: &str) -> String {
    format!("{}", query.parse::<SsrRule>().unwrap_err())
}

#[test]
fn parser_empty_query() {
    assert_eq!(parse_error_text(""), "Parse error: Cannot find delimiter `==>>`");
}

#[test]
fn parser_no_delimiter() {
    assert_eq!(parse_error_text("foo()"), "Parse error: Cannot find delimiter `==>>`");
}

#[test]
fn parser_two_delimiters() {
    assert_eq!(
        parse_error_text("foo() ==>> a ==>> b "),
        "Parse error: More than one delimiter found"
    );
}

#[test]
fn parser_repeated_name() {
    assert_eq!(
        parse_error_text("foo($a, $a) ==>>"),
        "Parse error: Placeholder `$a` repeats more than once"
    );
}

#[test]
fn parser_invalid_pattern() {
    assert_eq!(
        parse_error_text(" ==>> ()"),
        "Parse error: Not a valid Rust expression, type, item, path or pattern"
    );
}

#[test]
fn parser_invalid_template() {
    assert_eq!(
        parse_error_text("() ==>> )"),
        "Parse error: Not a valid Rust expression, type, item, path or pattern"
    );
}

#[test]
fn parser_undefined_placeholder_in_replacement() {
    assert_eq!(
        parse_error_text("42 ==>> $a"),
        "Parse error: Replacement contains undefined placeholders: $a"
    );
}

/// `code` may optionally contain a cursor marker `<|>`. If it doesn't, then the position will be
/// the start of the file. If there's a second cursor marker, then we'll return a single range.
pub(crate) fn single_file(code: &str) -> (ide_db::RootDatabase, FilePosition, Vec<FileRange>) {
    use ide_db::base_db::fixture::WithFixture;
    use ide_db::symbol_index::SymbolsDatabase;
    let (mut db, file_id, range_or_offset) = if code.contains(test_utils::CURSOR_MARKER) {
        ide_db::RootDatabase::with_range_or_offset(code)
    } else {
        let (db, file_id) = ide_db::RootDatabase::with_single_file(code);
        (db, file_id, RangeOrOffset::Offset(0.into()))
    };
    let selections;
    let position;
    match range_or_offset {
        RangeOrOffset::Range(range) => {
            position = FilePosition { file_id, offset: range.start() };
            selections = vec![FileRange { file_id, range: range }];
        }
        RangeOrOffset::Offset(offset) => {
            position = FilePosition { file_id, offset };
            selections = vec![];
        }
    }
    let mut local_roots = FxHashSet::default();
    local_roots.insert(ide_db::base_db::fixture::WORKSPACE);
    db.set_local_roots_with_durability(Arc::new(local_roots), Durability::HIGH);
    (db, position, selections)
}

fn assert_ssr_transform(rule: &str, input: &str, expected: Expect) {
    assert_ssr_transforms(&[rule], input, expected);
}

fn assert_ssr_transforms(rules: &[&str], input: &str, expected: Expect) {
    let (db, position, selections) = single_file(input);
    let mut match_finder = MatchFinder::in_context(&db, position, selections);
    for rule in rules {
        let rule: SsrRule = rule.parse().unwrap();
        match_finder.add_rule(rule).unwrap();
    }
    let edits = match_finder.edits();
    if edits.is_empty() {
        panic!("No edits were made");
    }
    assert_eq!(edits[0].file_id, position.file_id);
    // Note, db.file_text is not necessarily the same as `input`, since fixture parsing alters
    // stuff.
    let mut actual = db.file_text(position.file_id).to_string();
    edits[0].edit.apply(&mut actual);
    expected.assert_eq(&actual);
}

fn print_match_debug_info(match_finder: &MatchFinder, file_id: FileId, snippet: &str) {
    let debug_info = match_finder.debug_where_text_equal(file_id, snippet);
    println!(
        "Match debug info: {} nodes had text exactly equal to '{}'",
        debug_info.len(),
        snippet
    );
    for (index, d) in debug_info.iter().enumerate() {
        println!("Node #{}\n{:#?}\n", index, d);
    }
}

fn assert_matches(pattern: &str, code: &str, expected: &[&str]) {
    let (db, position, selections) = single_file(code);
    let mut match_finder = MatchFinder::in_context(&db, position, selections);
    match_finder.add_search_pattern(pattern.parse().unwrap()).unwrap();
    let matched_strings: Vec<String> =
        match_finder.matches().flattened().matches.iter().map(|m| m.matched_text()).collect();
    if matched_strings != expected && !expected.is_empty() {
        print_match_debug_info(&match_finder, position.file_id, &expected[0]);
    }
    assert_eq!(matched_strings, expected);
}

fn assert_no_match(pattern: &str, code: &str) {
    let (db, position, selections) = single_file(code);
    let mut match_finder = MatchFinder::in_context(&db, position, selections);
    match_finder.add_search_pattern(pattern.parse().unwrap()).unwrap();
    let matches = match_finder.matches().flattened().matches;
    if !matches.is_empty() {
        print_match_debug_info(&match_finder, position.file_id, &matches[0].matched_text());
        panic!("Got {} matches when we expected none: {:#?}", matches.len(), matches);
    }
}

fn assert_match_failure_reason(pattern: &str, code: &str, snippet: &str, expected_reason: &str) {
    let (db, position, selections) = single_file(code);
    let mut match_finder = MatchFinder::in_context(&db, position, selections);
    match_finder.add_search_pattern(pattern.parse().unwrap()).unwrap();
    let mut reasons = Vec::new();
    for d in match_finder.debug_where_text_equal(position.file_id, snippet) {
        if let Some(reason) = d.match_failure_reason() {
            reasons.push(reason.to_owned());
        }
    }
    assert_eq!(reasons, vec![expected_reason]);
}

#[test]
fn ssr_function_to_method() {
    assert_ssr_transform(
        "my_function($a, $b) ==>> ($a).my_method($b)",
        "fn my_function() {} fn main() { loop { my_function( other_func(x, y), z + w) } }",
        expect![["fn my_function() {} fn main() { loop { (other_func(x, y)).my_method(z + w) } }"]],
    )
}

#[test]
fn ssr_nested_function() {
    assert_ssr_transform(
        "foo($a, $b, $c) ==>> bar($c, baz($a, $b))",
        r#"
            //- /lib.rs crate:foo
            fn foo() {}
            fn bar() {}
            fn baz() {}
            fn main { foo  (x + value.method(b), x+y-z, true && false) }
            "#,
        expect![[r#"
            fn foo() {}<commit_msg>ssr: Add tests for raw LetStmt matching<commit_after>use crate::{MatchFinder, SsrRule};
use expect_test::{expect, Expect};
use ide_db::base_db::{salsa::Durability, FileId, FilePosition, FileRange, SourceDatabaseExt};
use rustc_hash::FxHashSet;
use std::sync::Arc;
use test_utils::{mark, RangeOrOffset};

fn parse_error_text(query: &str) -> String {
    format!("{}", query.parse::<SsrRule>().unwrap_err())
}

#[test]
fn parser_empty_query() {
    assert_eq!(parse_error_text(""), "Parse error: Cannot find delimiter `==>>`");
}

#[test]
fn parser_no_delimiter() {
    assert_eq!(parse_error_text("foo()"), "Parse error: Cannot find delimiter `==>>`");
}

#[test]
fn parser_two_delimiters() {
    assert_eq!(
        parse_error_text("foo() ==>> a ==>> b "),
        "Parse error: More than one delimiter found"
    );
}

#[test]
fn parser_repeated_name() {
    assert_eq!(
        parse_error_text("foo($a, $a) ==>>"),
        "Parse error: Placeholder `$a` repeats more than once"
    );
}

#[test]
fn parser_invalid_pattern() {
    assert_eq!(
        parse_error_text(" ==>> ()"),
        "Parse error: Not a valid Rust expression, type, item, path or pattern"
    );
}

#[test]
fn parser_invalid_template() {
    assert_eq!(
        parse_error_text("() ==>> )"),
        "Parse error: Not a valid Rust expression, type, item, path or pattern"
    );
}

#[test]
fn parser_undefined_placeholder_in_replacement() {
    assert_eq!(
        parse_error_text("42 ==>> $a"),
        "Parse error: Replacement contains undefined placeholders: $a"
    );
}

/// `code` may optionally contain a cursor marker `<|>`. If it doesn't, then the position will be
/// the start of the file. If there's a second cursor marker, then we'll return a single range.
pub(crate) fn single_file(code: &str) -> (ide_db::RootDatabase, FilePosition, Vec<FileRange>) {
    use ide_db::base_db::fixture::WithFixture;
    use ide_db::symbol_index::SymbolsDatabase;
    let (mut db, file_id, range_or_offset) = if code.contains(test_utils::CURSOR_MARKER) {
        ide_db::RootDatabase::with_range_or_offset(code)
    } else {
        let (db, file_id) = ide_db::RootDatabase::with_single_file(code);
        (db, file_id, RangeOrOffset::Offset(0.into()))
    };
    let selections;
    let position;
    match range_or_offset {
        RangeOrOffset::Range(range) => {
            position = FilePosition { file_id, offset: range.start() };
            selections = vec![FileRange { file_id, range: range }];
        }
        RangeOrOffset::Offset(offset) => {
            position = FilePosition { file_id, offset };
            selections = vec![];
        }
    }
    let mut local_roots = FxHashSet::default();
    local_roots.insert(ide_db::base_db::fixture::WORKSPACE);
    db.set_local_roots_with_durability(Arc::new(local_roots), Durability::HIGH);
    (db, position, selections)
}

fn assert_ssr_transform(rule: &str, input: &str, expected: Expect) {
    assert_ssr_transforms(&[rule], input, expected);
}

fn assert_ssr_transforms(rules: &[&str], input: &str, expected: Expect) {
    let (db, position, selections) = single_file(input);
    let mut match_finder = MatchFinder::in_context(&db, position, selections);
    for rule in rules {
        let rule: SsrRule = rule.parse().unwrap();
        match_finder.add_rule(rule).unwrap();
    }
    let edits = match_finder.edits();
    if edits.is_empty() {
        panic!("No edits were made");
    }
    assert_eq!(edits[0].file_id, position.file_id);
    // Note, db.file_text is not necessarily the same as `input`, since fixture parsing alters
    // stuff.
    let mut actual = db.file_text(position.file_id).to_string();
    edits[0].edit.apply(&mut actual);
    expected.assert_eq(&actual);
}

fn print_match_debug_info(match_finder: &MatchFinder, file_id: FileId, snippet: &str) {
    let debug_info = match_finder.debug_where_text_equal(file_id, snippet);
    println!(
        "Match debug info: {} nodes had text exactly equal to '{}'",
        debug_info.len(),
        snippet
    );
    for (index, d) in debug_info.iter().enumerate() {
        println!("Node #{}\n{:#?}\n", index, d);
    }
}

fn assert_matches(pattern: &str, code: &str, expected: &[&str]) {
    let (db, position, selections) = single_file(code);
    let mut match_finder = MatchFinder::in_context(&db, position, selections);
    match_finder.add_search_pattern(pattern.parse().unwrap()).unwrap();
    let matched_strings: Vec<String> =
        match_finder.matches().flattened().matches.iter().map(|m| m.matched_text()).collect();
    if matched_strings != expected && !expected.is_empty() {
        print_match_debug_info(&match_finder, position.file_id, &expected[0]);
    }
    assert_eq!(matched_strings, expected);
}

fn assert_no_match(pattern: &str, code: &str) {
    let (db, position, selections) = single_file(code);
    let mut match_finder = MatchFinder::in_context(&db, position, selections);
    match_finder.add_search_pattern(pattern.parse().unwrap()).unwrap();
    let matches = match_finder.matches().flattened().matches;
    if !matches.is_empty() {
        print_match_debug_info(&match_finder, position.file_id, &matches[0].matched_text());
        panic!("Got {} matches when we expected none: {:#?}", matches.len(), matches);
    }
}

fn assert_match_failure_reason(pattern: &str, code: &str, snippet: &str, expected_reason: &str) {
    let (db, position, selections) = single_file(code);
    let mut match_finder = MatchFinder::in_context(&db, position, selections);
    match_finder.add_search_pattern(pattern.parse().unwrap()).unwrap();
    let mut reasons = Vec::new();
    for d in match_finder.debug_where_text_equal(position.file_id, snippet) {
        if let Some(reason) = d.match_failure_reason() {
            reasons.push(reason.to_owned());
        }
    }
    assert_eq!(reasons, vec![expected_reason]);
}

#[test]
fn ssr_let_stmt_in_macro_match() {
    assert_matches(
        "let a = 0",
        r#"
            macro_rules! m1 { ($a:stmt) => {$a}; }
            fn f() {m1!{ let a = 0 };}"#,
        // FIXME: Whitespace is not part of the matched block
        &["leta=0"],
    );
}

#[test]
fn ssr_let_stmt_in_fn_match() {
    assert_matches("let $a = 10;", "fn main() { let x = 10; x }", &["let x = 10;"]);
    assert_matches("let $a = $b;", "fn main() { let x = 10; x }", &["let x = 10;"]);
}

#[test]
fn ssr_block_expr_match() {
    assert_matches("{ let $a = $b; }", "fn main() { let x = 10; }", &["{ let x = 10; }"]);
    assert_matches("{ let $a = $b; $c }", "fn main() { let x = 10; x }", &["{ let x = 10; x }"]);
}

#[test]
fn ssr_let_stmt_replace() {
    // Pattern and template with trailing semicolon
    assert_ssr_transform(
        "let $a = $b; ==>> let $a = 11;",
        "fn main() { let x = 10; x }",
        expect![["fn main() { let x = 11; x }"]],
    );
}

#[test]
fn ssr_let_stmt_replace_expr() {
    // Trailing semicolon should be dropped from the new expression
    assert_ssr_transform(
        "let $a = $b; ==>> $b",
        "fn main() { let x = 10; }",
        expect![["fn main() { 10 }"]],
    );
}

#[test]
fn ssr_function_to_method() {
    assert_ssr_transform(
        "my_function($a, $b) ==>> ($a).my_method($b)",
        "fn my_function() {} fn main() { loop { my_function( other_func(x, y), z + w) } }",
        expect![["fn my_function() {} fn main() { loop { (other_func(x, y)).my_method(z + w) } }"]],
    )
}

#[test]
fn ssr_nested_function() {
    assert_ssr_transform(
        "foo($a, $b, $c) ==>> bar($c, baz($a, $b))",
        r#"
            //- /lib.rs crate:foo
            fn foo() {}
            fn bar() {}
            fn baz() {}
            fn main { foo  (x + value.method(b), x+y-z, true && false) }
            "#,
        expect![[r#"
            fn foo() {}
{'fraction_non_alphanumeric': 0.1643011955533804, 'fraction_numerical': 0.0032860239110676084, 'mean_word_length': 3.4533001245330013, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 64, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4703178', 'n_tokens_mistral': 4838, 'n_tokens_neox': 4812, 'n_words': 1088}