import_optimization_demo/
import_optimization_demo.rs1use perl_lsp_code_actions::{CodeActionKind, CodeActionsProvider};
7use perl_parser_core::Parser;
8
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 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 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}