Skip to main content

CodeActionsProvider

Struct CodeActionsProvider 

Source
pub struct CodeActionsProvider { /* private fields */ }
Expand description

Code actions provider

Analyzes Perl source code and provides automated fixes and refactoring actions for common issues and improvement opportunities.

Implementations§

Source§

impl CodeActionsProvider

Source

pub fn new(source: String) -> Self

Create a new code actions provider

Examples found in repository?
examples/import_optimization_demo.rs (line 32)
9fn main() -> Result<(), Box<dyn std::error::Error>> {
10    let source = r#"#!/usr/bin/perl
11use warnings;
12use strict;
13use List::Util qw(max min sum);
14use Data::Dumper qw(Dumper);
15use List::Util qw(first);
16use JSON qw(encode_json decode_json to_json);
17
18# Only use some imports - others are unused
19my @numbers = (1, 2, 3, 4, 5);
20my $max = max(@numbers);
21print Dumper(\@numbers);
22my $json = encode_json({ max => $max });
23"#;
24
25    println!("Original Perl code:");
26    println!("{}", source);
27    println!("\n{}\n", "=".repeat(70));
28
29    let mut parser = Parser::new(source);
30    let ast = parser.parse()?;
31
32    let provider = CodeActionsProvider::new(source.to_string());
33    let actions = provider.get_code_actions(&ast, (0, source.len()), &[]);
34
35    println!("Available code actions:");
36    for (i, action) in actions.iter().enumerate() {
37        println!("  {}. {} ({:?})", i + 1, action.title, action.kind);
38    }
39
40    // Find the organize imports action
41    if let Some(organize_action) =
42        actions.iter().find(|a| matches!(a.kind, CodeActionKind::SourceOrganizeImports))
43    {
44        println!("\n{}\n", "=".repeat(70));
45        println!("Organize Imports Action:");
46        println!("  Title: {}", organize_action.title);
47        println!("  Edits: {} change(s)", organize_action.edit.changes.len());
48
49        for (i, edit) in organize_action.edit.changes.iter().enumerate() {
50            println!("\n  Edit #{}:", i + 1);
51            println!("    Range: {:?}", edit.location);
52            println!("    New text:");
53            for line in edit.new_text.lines() {
54                println!("      {}", line);
55            }
56        }
57    } else {
58        println!("\nNo 'Organize Imports' action available");
59    }
60
61    // Demonstrate missing imports detection
62    let source_with_missing = r#"use strict;
63use warnings;
64
65my $result = JSON::encode_json({key => 'value'});
66my $path = File::Spec::catfile('/tmp', 'test.txt');
67"#;
68
69    println!("\n{}\n", "=".repeat(70));
70    println!("Code with missing imports:");
71    println!("{}", source_with_missing);
72
73    let mut parser2 = Parser::new(source_with_missing);
74    let ast2 = parser2.parse()?;
75    let provider2 = CodeActionsProvider::new(source_with_missing.to_string());
76    let actions2 = provider2.get_code_actions(&ast2, (0, source_with_missing.len()), &[]);
77
78    println!("\nDetected actions:");
79    for (i, action) in actions2.iter().enumerate() {
80        if action.title.contains("import") {
81            println!("  {}. {}", i + 1, action.title);
82        }
83    }
84
85    Ok(())
86}
Source

pub fn get_code_actions( &self, ast: &Node, range: (usize, usize), diagnostics: &[Diagnostic], ) -> Vec<CodeAction>

Get code actions for a range

Examples found in repository?
examples/import_optimization_demo.rs (line 33)
9fn main() -> Result<(), Box<dyn std::error::Error>> {
10    let source = r#"#!/usr/bin/perl
11use warnings;
12use strict;
13use List::Util qw(max min sum);
14use Data::Dumper qw(Dumper);
15use List::Util qw(first);
16use JSON qw(encode_json decode_json to_json);
17
18# Only use some imports - others are unused
19my @numbers = (1, 2, 3, 4, 5);
20my $max = max(@numbers);
21print Dumper(\@numbers);
22my $json = encode_json({ max => $max });
23"#;
24
25    println!("Original Perl code:");
26    println!("{}", source);
27    println!("\n{}\n", "=".repeat(70));
28
29    let mut parser = Parser::new(source);
30    let ast = parser.parse()?;
31
32    let provider = CodeActionsProvider::new(source.to_string());
33    let actions = provider.get_code_actions(&ast, (0, source.len()), &[]);
34
35    println!("Available code actions:");
36    for (i, action) in actions.iter().enumerate() {
37        println!("  {}. {} ({:?})", i + 1, action.title, action.kind);
38    }
39
40    // Find the organize imports action
41    if let Some(organize_action) =
42        actions.iter().find(|a| matches!(a.kind, CodeActionKind::SourceOrganizeImports))
43    {
44        println!("\n{}\n", "=".repeat(70));
45        println!("Organize Imports Action:");
46        println!("  Title: {}", organize_action.title);
47        println!("  Edits: {} change(s)", organize_action.edit.changes.len());
48
49        for (i, edit) in organize_action.edit.changes.iter().enumerate() {
50            println!("\n  Edit #{}:", i + 1);
51            println!("    Range: {:?}", edit.location);
52            println!("    New text:");
53            for line in edit.new_text.lines() {
54                println!("      {}", line);
55            }
56        }
57    } else {
58        println!("\nNo 'Organize Imports' action available");
59    }
60
61    // Demonstrate missing imports detection
62    let source_with_missing = r#"use strict;
63use warnings;
64
65my $result = JSON::encode_json({key => 'value'});
66my $path = File::Spec::catfile('/tmp', 'test.txt');
67"#;
68
69    println!("\n{}\n", "=".repeat(70));
70    println!("Code with missing imports:");
71    println!("{}", source_with_missing);
72
73    let mut parser2 = Parser::new(source_with_missing);
74    let ast2 = parser2.parse()?;
75    let provider2 = CodeActionsProvider::new(source_with_missing.to_string());
76    let actions2 = provider2.get_code_actions(&ast2, (0, source_with_missing.len()), &[]);
77
78    println!("\nDetected actions:");
79    for (i, action) in actions2.iter().enumerate() {
80        if action.title.contains("import") {
81            println!("  {}. {}", i + 1, action.title);
82        }
83    }
84
85    Ok(())
86}

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more