Skip to content

Commit

Permalink
Merge pull request #135 from michaelb/dev
Browse files Browse the repository at this point in the history
dev
  • Loading branch information
michaelb authored Jan 10, 2022
2 parents 4ab5996 + 302931d commit 1d6e498
Show file tree
Hide file tree
Showing 15 changed files with 194 additions and 54 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
## v1.1.2
- auto detection of entry point for many languages
- CFLAGS and other variables
- Python3\_fifo plots work

## v1.1.1
- Fix terminal display issues
- Configurable display options
Expand Down
22 changes: 11 additions & 11 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "sniprun"
version = "1.1.1"
version = "1.1.2"
authors = ["michaelb <[email protected]>"]
edition = "2018"

Expand Down
18 changes: 17 additions & 1 deletion doc/C_original.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,20 @@ require'sniprun'.setup({
})
```

This interpeter will also only import (all) #include \<...> but not any #include "..."
If you run with GCC, Sniprun will be able to run function + code in the same snippet, or functions + main() function regardlessly,but only the latter is supported by clang.

This interpreter will also only import (all) #include \<...> but not any #include "..." (systems-wide include only, not the headers from your project, unless the environment variable `$C_INCLUDE_PATH` or `$CPLUS_INCLUDE_PATH` have been set). In this case, please make sure those variable cover **ALL** the paths needed to fetch every header file `#include`'d


the C\_original interpreter will also make use of the following environment variables:

- `$C_INCLUDE_PATH`
- `$C_PLUS_INCLUDE_PATH`
- `$LIBRARY_PATH`
- `$CFLAGS`


and will add them to the build options it uses. Please specify _absolute path_, and not relative ones!


Using a tool such as [direnv](https://direnv.net/) may be really useful to set up those variables when you `cd` into your project' directory.
10 changes: 0 additions & 10 deletions lua/sniprun.lua
Original file line number Diff line number Diff line change
Expand Up @@ -312,16 +312,6 @@ function M.health()
local health_error = vim.fn['health#report_error']
local health_warn = vim.fn['health#report_warn']
health_start('Installation')
if vim.fn.executable('tree-sitter') == 0 then
health_warn('`tree-sitter` executable not found (): File support and higher may not work properly')
else
local handle = io.popen('tree-sitter -V')
local result = handle:read("*a")
handle:close()
local version = vim.split(result,'\n')[1]:match('[^tree%psitter].*')
health_ok('`tree-sitter` found '..version..' , sniprun will try to make good use of that')
end


if vim.fn.executable('cargo') == 0 then health_warn("Rust toolchain not available", {"[optionnal] Install the rust toolchain https://www.rust-lang.org/tools/install"})
else health_ok("Rust toolchain found") end
Expand Down
Empty file modified ressources/init_repl.sh
100755 → 100644
Empty file.
11 changes: 11 additions & 0 deletions ressources/sync_repl.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#!/bin/bash
working_dir="$1/fifo_repl"
echo "sync requested" >> $working_dir/log

pipe=pipe_in
out=out_file
err=err_file

echo "" > $working_dir/$pipe

echo "sync done" >> $working_dir/log
12 changes: 12 additions & 0 deletions src/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ pub trait InterpreterUtils {
fn set_pid(&self, pid: u32);
fn get_pid(&self) -> Option<u32>;
fn get_interpreter_option(data: &DataHolder, option: &str) -> Option<neovim_lib::Value>;
fn contains_main(entry: &str, snippet: &str, comment: &str) -> bool;
}

impl<T: Interpreter> InterpreterUtils for T {
Expand Down Expand Up @@ -291,6 +292,17 @@ impl<T: Interpreter> InterpreterUtils for T {

None
}

fn contains_main(entry: &str, snippet: &str, comment: &str) -> bool {
let compact_main: String = entry.split_whitespace().collect();
let compact_snippet: String = snippet
.lines()
.filter(|l| !l.trim().starts_with(comment))
.collect::<String>()
.split_whitespace()
.collect();
return compact_snippet.contains(&compact_main);
}
}

pub trait ReplLikeInterpreter {
Expand Down
73 changes: 56 additions & 17 deletions src/interpreters/C_original.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@ pub struct C_original {
}

impl C_original {
fn fetch_imports(&mut self)-> Result<(), SniprunError> {
fn fetch_imports(&mut self) -> Result<(), SniprunError> {
if self.support_level < SupportLevel::Import {
return Ok(());
}

let mut v = vec![];
let mut errored = true;
if let Some(real_nvim_instance) = self.data.nvim_instance.clone() {
info!("got real nvim isntance");
info!("got real nvim instance");
let mut rvi = real_nvim_instance.lock().unwrap();
if let Ok(buffer) = rvi.get_current_buf() {
info!("got buffer");
Expand All @@ -40,6 +40,12 @@ impl C_original {
if line.starts_with("#include <") {
self.imports.push(line.to_string());
}
if line.starts_with("#include")
&& (std::env::var("C_INCLUDE_PATH").is_ok()
|| std::env::var("CPLUS_INCLUDE_PATH").is_ok())
{
self.imports.push(line.to_string());
}
}
info!("fecthed imports : {:?}", self.imports);
Ok(())
Expand All @@ -48,7 +54,9 @@ impl C_original {
fn fetch_config(&mut self) {
let default_compiler = String::from("gcc");
self.compiler = default_compiler;
if let Some(used_compiler) = C_original::get_interpreter_option(&self.get_data(), "compiler") {
if let Some(used_compiler) =
C_original::get_interpreter_option(&self.get_data(), "compiler")
{
if let Some(compiler_string) = used_compiler.as_str() {
info!("Using custom compiler: {}", compiler_string);
self.compiler = compiler_string.to_string();
Expand Down Expand Up @@ -133,8 +141,10 @@ impl Interpreter for C_original {

fn add_boilerplate(&mut self) -> Result<(), SniprunError> {
self.fetch_imports()?;

self.code = String::from("int main() {\n") + &self.code + "\nreturn 0;}";

if !C_original::contains_main(&"int main (", &self.code, &"//") {
self.code = String::from("int main() {\n") + &self.code + "\nreturn 0;}";
}
if !self.imports.iter().any(|s| s.contains("<stdio.h>")) {
self.code = String::from("#include <stdio.h>\n") + &self.code;
}
Expand All @@ -146,20 +156,47 @@ impl Interpreter for C_original {
fn build(&mut self) -> Result<(), SniprunError> {
info!("starting build");
//write code to file

let mut build_args: Vec<String> = vec![];
if let Ok(cflags) = std::env::var("CFLAGS") {
info!("CFLAGS env var found : {}", cflags);
build_args.extend(cflags.split_whitespace().map(|s| s.to_owned()));
}

if let Ok(c_incl_path) = std::env::var("C_INCLUDE_PATH") {
info!("C_INCLUDE_PATH env var found : {}", c_incl_path);
build_args.extend(c_incl_path.split(':').map(|s| String::from("-I") + s));
}

if let Ok(cplus_incl_path) = std::env::var("CPLUS_INCLUDE_PATH") {
info!("CPLUS_INCLUDE_PATH env var found : {}", cplus_incl_path);
build_args.extend(cplus_incl_path.split(':').map(|s| String::from("-I") + s));
}

if let Ok(library_path) = std::env::var("LIBRARY_PATH") {
info!("LIBRARY_PATH env var found : {}", library_path);
build_args.extend(library_path.split(':').map(|s| String::from("-L") + s));
}

let mut _file =
File::create(&self.main_file_path).expect("Failed to create file for c-original");
write(&self.main_file_path, &self.code).expect("Unable to write to file for c-original");
let output = Command::new(&self.compiler)
let mut cmd = Command::new(&self.compiler);
let cmd = cmd
.arg(&self.main_file_path)
.arg("-o")
.arg(&self.bin_path)
.output()
.expect("Unable to start process");
.arg("-v")
.args(&build_args);

info!("full gcc command emitted:\n{}\n", format!("{:?}",cmd).replace("\"", ""));

let output = cmd.output().expect("Unable to start process");

//TODO if relevant, return the error number (parse it from stderr)
if !output.status.success() {
let error_message = String::from_utf8(output.stderr).unwrap();
info!("Returning nice C error message: {}", error_message);
info!("Full GCC error message: {}", error_message);
let mut relevant_error = String::new();

let mut break_loop = false;
Expand All @@ -171,17 +208,20 @@ impl Interpreter for C_original {
if line.contains("error") {
// info!("breaking at position {:?}", line.split_at(line.find("error").unwrap()).1);
relevant_error += line
.split_at(line.find("error").unwrap())
.1
.trim_start_matches("error: ")
.trim_end_matches("error:")
.trim_start_matches("error");
.split_at(line.find("error").unwrap())
.1
.trim_start_matches("error: ")
.trim_end_matches("error:")
.trim_start_matches("error");
break_loop = true;
}
}

Err(SniprunError::CompilationError(relevant_error))
} else {

let compiler_output = String::from_utf8(output.stdout).unwrap();
info!("compiler output:\n{}\n", compiler_output);
Ok(())
}
}
Expand Down Expand Up @@ -217,7 +257,7 @@ mod test_c_original {
// should panic if not an Ok()
let string_result = res.unwrap();
assert_eq!(string_result, "1=1\n");
}
}

#[test]
#[serial(c_original)]
Expand All @@ -229,8 +269,7 @@ mod test_c_original {

match res {
Err(SniprunError::CompilationError(_)) => (),
_ => panic!("Compilation should have failed")
_ => panic!("Compilation should have failed"),
};
}

}
5 changes: 4 additions & 1 deletion src/interpreters/Cpp_original.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,10 @@ impl Interpreter for Cpp_original {

fn add_boilerplate(&mut self) -> Result<(), SniprunError> {
self.fetch_imports()?;
self.code = String::from("int main() {\n") + &self.code + "\nreturn 0;}";

if !Cpp_original::contains_main(&"int main (", &self.code, &"//") {
self.code = String::from("int main() {\n") + &self.code + "\nreturn 0;}";
}
if !self.imports.iter().any(|s| s.contains("<iostream>")) {
self.code = String::from("#include <iostream>\n") + &self.code;
}
Expand Down
14 changes: 13 additions & 1 deletion src/interpreters/Go_original.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,19 @@ impl Interpreter for Go_original {
}

fn add_boilerplate(&mut self) -> Result<(), SniprunError> {
self.code = String::from("package main \nimport \"fmt\"\nfunc main() {") + &self.code + "}";

if !Go_original::contains_main(&"func main (", &self.code, &"//") {
self.code = String::from("func main() {") + &self.code + "}";
}

if !Go_original::contains_main(&"import \"fmt\"", &self.code, &"//") {
self.code = String::from("import \"fmt\"\n") + &self.code;
}

if !Go_original::contains_main(&"package main", &self.code, &"//") {
self.code = String::from("package main\n") + &self.code;
}

Ok(())
}

Expand Down
17 changes: 10 additions & 7 deletions src/interpreters/Java_original.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,13 +82,16 @@ impl Interpreter for Java_original {
}

fn add_boilerplate(&mut self) -> Result<(), SniprunError> {
self.code = String::from(
"public class Main {
public static void main(String[] args) {
",
) + &self.code
+ "}
}";

if !Java_original::contains_main(&"public static void main(", &self.code, &"//") {
self.code = String::from(
"public class Main {
public static void main(String[] args) {
",
) + &self.code
+ "}
}";
}
Ok(())
}

Expand Down
Loading

0 comments on commit 1d6e498

Please sign in to comment.