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
#![warn(trivial_numeric_casts)]

extern crate ansi_term;
extern crate ascii;
extern crate getopts;
extern crate itertools;
extern crate llvm_sys;
extern crate matches;
extern crate pest;
extern crate quickcheck;
extern crate rand;
extern crate regex;
extern crate tempfile;

#[macro_use]
extern crate pest_derive;
extern crate core;

pub mod compiler;
pub mod parser;
pub mod shell;
pub mod parser_combinator;

use getopts::Options;
use std::fs;
use std::path::Path;
use tempfile::NamedTempFile;

/// Convert "foo.ijs" to "foo".
fn executable_name(ijs_path: &str) -> String {
    let bf_file_name = Path::new(ijs_path).file_name().unwrap().to_str().unwrap();

    let mut name_parts: Vec<_> = bf_file_name.split('.').collect();
    let parts_len = name_parts.len();
    if parts_len > 1 {
        name_parts.pop();
    }

    name_parts.join(".")
}

pub fn print_usage(bin_name: &str, opts: Options) {
    let brief = format!("Usage: {} SOURCE_FILE [options]", bin_name);
    print!("{}", opts.usage(&brief));
}

fn convert_io_error<T>(result: Result<T, std::io::Error>) -> Result<T, String> {
    match result {
        Ok(value) => Ok(value),
        Err(e) => Err(format!("{}", e)),
    }
}

pub fn compile(
    path: &str,
    target_triple: Option<String>,
    llvm_optimization_level: u8,
    do_strip_executable: bool,
    do_report_mem_usage: bool,
    do_verbose: bool,
    output_path: Option<String>,
) -> Result<(), String> {
    let jsrc = fs::read_to_string(path).expect("cannot open source of provided J program");

    let ast = match parser_combinator::parse(&jsrc[..]) {
        Ok(astnodes) => astnodes,
        Err(parse_error) => {
            panic!("{}", parse_error);
        }
    };
    println!("{:?}", ast);

//    let ast = match parser::parse(&jsrc[..]) {
//        Ok(instrs) => instrs,
//        Err(parse_error) => {
//            panic!("{}", parse_error);
//        }
//    };
//
//    if do_verbose {
//        for astnode in &ast {
//            println!("{:?}", astnode);
//        }
//    }
//
//    let mut llvm_module =
//        compiler::compile_to_module(path, target_triple.clone(), do_report_mem_usage, &ast);
//
//    compiler::optimise_ir(&mut llvm_module, llvm_optimization_level as i64);
//    let llvm_ir_cstr = llvm_module.to_cstring();
//    let llvm_ir = String::from_utf8_lossy(llvm_ir_cstr.as_bytes());
//
//    if do_verbose {
//        println!(
//            "LLVM IR optimized at level {}:\n{}",
//            llvm_optimization_level, llvm_ir
//        );
//    }
//
//    // Compile the LLVM IR to a temporary object file.
//    let object_file = try!(convert_io_error(NamedTempFile::new()));
//    let obj_file_path = object_file.path().to_str().expect("path not valid utf-8");
//
//    if do_verbose {
//        println!("Writing object file to {}", obj_file_path);
//    }
//
//    compiler::write_object_file(&mut llvm_module, &obj_file_path).unwrap();
//
//    let output_path = match output_path {
//        Some(op) => op,
//        None => executable_name(path),
//    };
//
//    if do_verbose {
//        println!("Writing executable to {}", output_path);
//    }
//
//    let res = link_object_file(&obj_file_path, &output_path, target_triple);
//    match res {
//        Ok(_) => (),
//        Err(e) => panic!(format!("Linking executable failed: {}", e)),
//    };
//
//    if do_strip_executable {
//        let strip_args = ["-s", &output_path[..]];
//        shell::run_shell_command("strip", &strip_args[..]).unwrap();
//        if do_verbose {
//            println!("Stripped executable of debug symbols.");
//        }
//    }

    Ok(())
}

fn link_object_file(
    object_file_path: &str,
    executable_path: &str,
    target_triple: Option<String>,
) -> Result<(), String> {
    // Link the object file.
    let clang_args = if let Some(ref target_triple) = target_triple {
        vec![
            object_file_path,
            "c_defns/jverbs.c",
            "c_defns/jmemory.c",
            "-target",
            &target_triple,
            "-o",
            &executable_path[..],
            "-lm",
        ]
    } else {
        vec![
            object_file_path,
            "c_defns/jverbs.c",
            "c_defns/jmemory.c",
            "-o",
            &executable_path[..],
            "-lm",
        ]
    };

    shell::run_shell_command("clang-7", &clang_args[..])
}

//#[test]
//fn executable_name_test() {
//    assert_eq!(executable_name("test.ijs"), "test");
//}
//
//#[test]
//fn executable_name_relative_path_test() {
//    assert_eq!(executable_name("dir/test.ijs"), "test");
//}