rust_hero 0.5.2

Rust assistant that utilizes NLP to enhance the quality of rust code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
use crate::query::{ExtractedFile, Language, QueryFormat, QueryOpts};
use anyhow;
use anyhow::{bail, Context, Result};
use crossbeam::channel;
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
use rust_bert::pipelines::common::{ConfigOption, ModelType, TokenizerOption};
use rust_bert::pipelines::sequence_classification::SequenceClassificationOption;
use rust_bert::resources::{RemoteResource, ResourceProvider};
use rust_tokenizers::tokenizer::TruncationStrategy;
use std::io::Write;
use tch::kind::Kind::Int64;
use tch::{nn, no_grad, Device, Kind, Tensor};
use tree_sitter::Parser;

#[global_allocator]
static ALLOCATOR: bump_alloc::BumpAlloc = bump_alloc::BumpAlloc::new();

/// Display the extracted syntax information of source file
pub fn show_languages(mut out: impl Write) -> Result<()> {
    for language in Language::all() {
        writeln!(out, "{}", language.to_string()).context("couldn't print a language")?;
    }

    Ok(())
}
/// SafeLanguageModel for classifying safe and unsafe keywords
pub struct SafeLanguageModel {
    /// TokenizerOption for safe model
    tokenizer: TokenizerOption,
    /// Configuration for language query
    opts: QueryOpts,
    /// Configuration for safe model
    config: ConfigOption,
    /// safe model
    model: SequenceClassificationOption,
}
impl SafeLanguageModel {
    /// Build a new `SafeLanguageModel`
    ///
    /// # Arguments
    ///
    /// * `opts` - `QueryOpts` object containing the detected language and file information
    ///
    /// # Returns
    ///
    /// * `SafeLanguageModel` object
    ///
    /// # Example
    ///
    /// ```no_run
    /// # fn main() -> anyhow::Result<()> {
    /// use rust_hero::query::Invocation;
    /// use rust_hero::safe::SafeLanguageModel;
    ///
    /// let args=[
    ///        "rust_hero",
    ///        "-q",
    ///        "rust",
    ///        "(function_item (identifier) @id) @function",
    ///        "--format=classes",
    ///        "--sort",
    ///        "--no-gitignore",
    ///        "data/error.rs",
    ///    ]
    /// .iter()
    /// .map(|s| s.to_string())
    /// .collect();
    /// let invocation = Invocation::from_args(args)?;
    /// match invocation {
    ///    Invocation::DoQuery(query_opts) => {
    ///         let safe_model = SafeLanguageModel::new(query_opts)?;
    ///    }
    ///     _ => (),
    /// }
    /// # Ok(())
    /// # }
    /// ```
    /// # Tips
    /// If runtime accident occurs:"Downloading <https://huggingface.co/Vincent-Xiao/codebert-curs/resolve/main/rust_model.ot> [477.81MiB].......memory allocation of 32768 bytes failed memory allocation of Aborted"
    /// you may set the network proxy for beteer downloading models from huggingface.co
    pub fn new(opts: QueryOpts) -> Result<SafeLanguageModel> {
        let config_resource = RemoteResource::from_pretrained((
            "codebert-curs/config",
            "https://huggingface.co/Vincent-Xiao/codebert-curs/resolve/main/config.json",
        ));
        let vocab_resource = RemoteResource::from_pretrained((
            "codebert-curs/vocab",
            "https://huggingface.co/Vincent-Xiao/codebert-curs/resolve/main/vocab.json",
        ));
        let merges_resource = RemoteResource::from_pretrained((
            "codebert-curs/merges",
            "https://huggingface.co/Vincent-Xiao/codebert-curs/resolve/main/merges.txt",
        ));
        let weights_resource = RemoteResource::from_pretrained((
            "codebert-curs/model",
            "https://huggingface.co/Vincent-Xiao/codebert-curs/resolve/main/rust_model.ot",
        ));
        let config_path = config_resource.get_local_path()?;
        let vocab_path = vocab_resource.get_local_path()?;
        let merges_path = Some(merges_resource.get_local_path()?);
        /* if runtime accident occurs:"Downloading https://huggingface.co/Vincent-Xiao/codebert-curs/resolve/main/rust_model.ot [477.81MiB]
            .......memory allocation of 32768 bytes failed
            memory allocation of Aborted"
            you may set the network proxy for beteer downloading models from huggingface.co
        */
        let weights_path = weights_resource.get_local_path()?;
        let device = Device::cuda_if_available();
        // let device = Device::Cpu;
        // if device == Device::Cpu {
        //     println!("inference device: cpu");
        // } else {
        //     println!("inference device: cuda");
        // }
        let tokenizer = TokenizerOption::from_file(
            ModelType::Roberta,
            vocab_path.to_str().unwrap(),
            merges_path.as_deref().map(|path| path.to_str().unwrap()),
            false,
            None,
            false,
        )?;

        let mut vs = nn::VarStore::new(device);
        let config = ConfigOption::from_file(ModelType::Bert, config_path);
        let model = SequenceClassificationOption::new(ModelType::Roberta, &vs.root(), &config)?;
        // use "?" to load model correctly instead of ".ok()"
        vs.load(weights_path)?;
        Ok(SafeLanguageModel {
            tokenizer,
            opts,
            config,
            model,
        })
    }

    /// Get the private `QueryOpts` of`SafeLanguageModel`
    pub fn get_opt(&self) -> &QueryOpts {
        &self.opts
    }

    /// Find the language (such as Rust) source file if you give a directory arg instead of one specific source file
    pub fn search_files(&self) -> Result<Vec<ignore::DirEntry>> {
        let opts = &self.opts;
        let mut builder = match opts.paths.split_first() {
            Some((first, rest)) => {
                let mut builder = ignore::WalkBuilder::new(first);
                for path in rest {
                    builder.add(path);
                }

                builder
            }
            None => bail!("I need at least one file or directory to walk!"),
        };

        let (root_sender, receiver) = channel::unbounded();

        builder
            .git_ignore(opts.git_ignore)
            .git_exclude(opts.git_ignore)
            .git_global(opts.git_ignore)
            .build_parallel()
            .run(|| {
                let sender = root_sender.clone();
                Box::new(move |entry_result| match entry_result {
                    Ok(entry) => match sender.send(entry) {
                        Ok(()) => ignore::WalkState::Continue,
                        Err(_) => ignore::WalkState::Quit,
                    },
                    Err(_) => ignore::WalkState::Quit,
                })
            });

        drop(root_sender);

        Ok(receiver.iter().collect())
    }

    /// Predict whether the fragment program containing unsafe keyword is `safe` or `unsafe`
    /// `safe` indicates that he unsafe keyword could be removed;
    ///  `unsafe` represents that he unsafe keyword should be reserved;
    pub fn classify(&self, extracted_file: &ExtractedFile) -> Result<Vec<String>> {
        let mut result: Vec<String> = vec![];
        // Define the cordinate if extraction "id"
        for extraction in &extracted_file.matches {
            let input_string = format!("{}", extraction.text);
            // only detect the unsafe function
            if !input_string.contains("unsafe") {
                continue;
            }
            // extract the coordonate of 'id'
            let r1 = extraction.start.row + 1;
            let c1 = extraction.start.column + 1;
            let r2 = extraction.end.row + 1;
            let c2 = extraction.end.column + 1;
            let input = [input_string.replace("unsafe ", " ")];
            //tokenizer
            let tokenized_input =
                self.tokenizer
                    .encode_list(&input, 512, &TruncationStrategy::LongestFirst, 0);
            let max_len = tokenized_input
                .iter()
                .map(|input| input.token_ids.len())
                .max()
                .unwrap();
            let tokenized_inputs = tokenized_input
                .iter()
                .map(|input| input.token_ids.clone())
                .map(|mut input| {
                    input.extend(vec![0; max_len - input.len()]);
                    input
                })
                .map(|input| Tensor::of_slice(&(input)))
                .collect::<Vec<_>>();
            let tokenized_masks = tokenized_input
                .iter()
                .map(|input| vec![1; input.token_ids.len()])
                .map(|mut input: Vec<i64>| {
                    input.extend(vec![0; max_len - input.len()]);
                    input
                })
                .map(|input| Tensor::of_slice(&(input)))
                .collect::<Vec<_>>();

            let device = Device::cuda_if_available();
            // let device = Device::Cpu;
            let input_tensor = Tensor::stack(tokenized_inputs.as_slice(), 0).to(device);
            let (batch_size, sequence_length) = (1, max_len as i64);

            let mask = Tensor::stack(tokenized_masks.as_slice(), 0).to(device);
            let token_type_ids = Tensor::zeros(&[batch_size, sequence_length], (Int64, device));

            let output = no_grad(|| {
                let output = self.model.forward_t(
                    Some(&input_tensor),
                    Some(&mask),
                    Some(&token_type_ids),
                    None,
                    None,
                    false,
                );
                output.softmax(-1, Kind::Float).detach().to(device)
            });
            let label_mapping = self.config.get_label_mapping().clone();
            let label_indices = output.as_ref().argmax(-1, true).squeeze_dim(1);
            let scores = output
                .gather(1, &label_indices.unsqueeze(-1), false)
                .squeeze_dim(1);
            let label_indices = label_indices.iter::<i64>().unwrap().collect::<Vec<i64>>();
            let scores = scores.iter::<f64>().unwrap().collect::<Vec<f64>>();

            for sentence_idx in 0..label_indices.len() {
                let label_string = label_mapping
                    .get(&label_indices[sentence_idx])
                    .unwrap()
                    .clone();
                let out = format!(
                    "{},{},{},{},{},{}(prob={:.2})",
                    extracted_file
                        .file
                        .as_ref()
                        .map(|f| f.to_str().unwrap_or("NON-UTF8 FILENAME"))
                        .unwrap_or("NO FILE"),
                    r1,
                    c1,
                    r2,
                    c2,
                    &label_string,
                    scores[sentence_idx],
                );
                result.push(out);
                // println!(
                //     "{},{},{},{},{},{}(prob={:.2})",
                //     extracted_file
                //         .file
                //         .as_ref()
                //         .map(|f| f.to_str().unwrap_or("NON-UTF8 FILENAME"))
                //         .unwrap_or("NO FILE"),
                //     r1,
                //     c1,
                //     r2,
                //     c2,
                //     &label_string,
                //     scores[sentence_idx]
                // );
            }
        }
        Ok(result)
    }

    /// Parser source files and call classify function to predict unsafe.
    ///
    /// # Returns
    ///
    /// * Classily result in forms of "source file name--cordinate of function containg unsafe keyword-- safe/unsafe--probability"
    ///
    /// # Example
    ///
    /// ```no_run
    /// # fn main() -> anyhow::Result<()> {
    /// use rust_hero::query::{Invocation, QueryFormat};
    /// use rust_hero::safe::SafeLanguageModel;
    /// use anyhow::Context;
    ///
    ///
    /// let args=[
    ///        "rust_hero",
    ///        "-q",
    ///        "rust",
    ///        "(function_item (identifier) @id) @function",
    ///        "--format=classes",
    ///        "--sort",
    ///        "--no-gitignore",
    ///        "data/error.rs",
    ///    ]
    /// .iter()
    /// .map(|s| s.to_string())
    /// .collect();
    /// let invocation = Invocation::from_args(args)?;
    /// match invocation {
    ///    Invocation::DoQuery(query_opts) => {
    ///         let safe_model = SafeLanguageModel::new(query_opts)?;
    ///         match safe_model.get_opt().format {
    ///             QueryFormat::Classes => {
    ///                 let output = safe_model
    ///                     .predict()
    ///                     .context("couldn't perform the prediction")?;
    ///                 for label in output {
    ///                     println!("{:?}", label);
    ///                 }
    ///             ()
    ///           }
    ///        _ => (),
    ///     }
    ///   }
    ///     _ => (),
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn predict(&self) -> Result<Vec<String>> {
        // You might think "why not use ParallelBridge here?" Well, the quick answer
        // is that I benchmarked it and having things separated here and handling
        // their own errors actually speeds up this part of the code by like 20%!
        let items: Vec<ignore::DirEntry> = self
            .search_files()
            .context("had a problem while walking the filesystem")?;

        let chooser = self
            .opts
            .extractor_chooser()
            .context("couldn't construct a filetype matcher")?;
        let mut extracted_files = items
            .par_iter()
            .filter_map({
                let chooser = &chooser;
                |entry| {
                    chooser
                        .extractor_for(entry)
                        .map(|extractor| (entry, extractor))
                }
            })
            .map_init(Parser::new, |parser, (entry, extractor)| {
                extractor
                    .extract_from_file(entry.path(), parser)
                    .with_context(|| {
                        format!("could not extract matches from {}", entry.path().display())
                    })
            })
            .filter_map(|result_containing_option| match result_containing_option {
                Ok(None) => None,
                Ok(Some(extraction)) => Some(Ok(extraction)),
                Err(err) => Some(Err(err)),
            })
            .collect::<Result<Vec<ExtractedFile>>>()
            .context("couldn't extract matches from files")?;

        if self.opts.sort {
            extracted_files.sort()
        }
        let mut result: Vec<String> = vec![];

        match self.opts.format {
            QueryFormat::Classes => {
                for extracted_file in extracted_files {
                    let out = self.classify(&extracted_file)?;
                    for label in out {
                        result.push(label);
                    }
                }
            }
            _ => bail!("You should call do_query function!"),
        }

        Ok(result)
    }

    /// Parser source files.
    ///
    /// # Returns
    ///
    /// * Concrete syntax tree for source files
    ///
    /// # Example
    ///
    /// ```no_run
    /// # fn main() -> anyhow::Result<()> {
    /// use rust_hero::query::{Invocation, QueryFormat};
    /// use rust_hero::safe::SafeLanguageModel;
    /// use std::io::{self, BufWriter, Write};
    ///
    ///
    /// let args=[
    ///        "rust_hero",
    ///        "-q",
    ///        "rust",
    ///        "(function_item (identifier) @id) @function",
    ///        "--format=pretty-json",
    ///        "--sort",
    ///        "--no-gitignore",
    ///        "data/error.rs",
    ///    ]
    /// .iter()
    /// .map(|s| s.to_string())
    /// .collect();
    /// let invocation = Invocation::from_args(args)?;
    /// let mut buffer = BufWriter::new(io::stdout());
    ///
    /// match invocation {
    ///    Invocation::DoQuery(query_opts) => {
    ///         let safe_model = SafeLanguageModel::new(query_opts)?;
    ///         match safe_model.get_opt().format {
    ///             QueryFormat::Json => safe_model.do_query(&mut buffer)?,
    ///             _ => (),
    ///         };
    ///   }
    ///    _ => (),
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn do_query(&self, mut out: impl Write) -> Result<()> {
        let items: Vec<ignore::DirEntry> = self
            .search_files()
            .context("had a problem while walking the filesystem")?;

        let chooser = self
            .opts
            .extractor_chooser()
            .context("couldn't construct a filetype matcher")?;
        let mut extracted_files = items
            .par_iter()
            .filter_map({
                let chooser = &chooser;
                |entry| {
                    chooser
                        .extractor_for(entry)
                        .map(|extractor| (entry, extractor))
                }
            })
            .map_init(Parser::new, |parser, (entry, extractor)| {
                extractor
                    .extract_from_file(entry.path(), parser)
                    .with_context(|| {
                        format!("could not extract matches from {}", entry.path().display())
                    })
            })
            .filter_map(|result_containing_option| match result_containing_option {
                Ok(None) => None,
                Ok(Some(extraction)) => Some(Ok(extraction)),
                Err(err) => Some(Err(err)),
            })
            .collect::<Result<Vec<ExtractedFile>>>()
            .context("couldn't extract matches from files")?;

        if self.opts.sort {
            extracted_files.sort()
        }

        match self.opts.format {
            QueryFormat::Classes => bail!("You should call predict function!"),

            QueryFormat::Lines => {
                for extracted_file in extracted_files {
                    write!(out, "{}", extracted_file).context("could not write lines")?;
                }
            }

            QueryFormat::Json => {
                serde_json::to_writer(out, &extracted_files)
                    .context("could not write JSON output")?;
            }
            QueryFormat::JsonLines => {
                for extracted_file in extracted_files {
                    writeln!(
                        out,
                        "{}",
                        serde_json::to_string(&extracted_file)
                            .context("could not write JSON output")?
                    )
                    .context("could not write line")?;
                }
            }

            QueryFormat::PrettyJson => {
                serde_json::to_writer_pretty(out, &extracted_files)
                    .context("could not write JSON output")?;
            }
        }

        Ok(())
    }
}