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
//! A parser for [Java Classfiles](https://docs.oracle.com/javase/specs/jvms/se10/html/jvms-4.html)

use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;

#[macro_use]
extern crate nom;

#[macro_use]
extern crate bitflags;

pub mod attribute_info;
pub mod constant_info;
pub mod field_info;
pub mod method_info;

pub mod code_attribute;

pub mod parser;
pub mod types;

pub use parser::class_parser;
pub use types::*;

/// Attempt to parse a class file given a class file given a path to a class file
/// (without .class extension)
///
/// ```rust
/// match classfile_parser::parse_class("./java-assets/compiled-classes/BasicClass") {
///     Ok(class_file) => {
///         println!("version {},{}", class_file.major_version, class_file.minor_version);
///     }
///     Err(ex) => panic!("Failed to parse: {}", ex),
/// };
/// ```
pub fn parse_class(class_name: &str) -> Result<ClassFile, String> {
    let class_file_name = &format!("{}.class", class_name);
    let path = Path::new(class_file_name);
    let display = path.display();

    let mut file = match File::open(&path) {
        Err(why) => {
            return Err(format!(
                "Unable to open {}: {}",
                display,
                Error::description(&why)
            ));
        }
        Ok(file) => file,
    };

    let mut class_bytes = Vec::new();
    if let Err(why) = file.read_to_end(&mut class_bytes) {
        return Err(format!(
            "Unable to read {}: {}",
            display,
            Error::description(&why)
        ));
    }

    let parsed_class = class_parser(&class_bytes);
    match parsed_class {
        Ok((_, c)) => Ok(c),
        _ => Err("Failed to parse class?".to_string()),
    }
}