Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Apply clippy lints and cargo fmt #17

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion .github/workflows/build-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ on:

env:
CARGO_TERM_COLOR: always
RUSTFLAGS: "-Dwarnings"

jobs:
build-and-test:
Expand All @@ -21,8 +22,12 @@ jobs:
steps:
- name: Install Emacs
run: sudo apt-get install -y emacs
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Formatting
run: cargo fmt --check
- name: Build
run: cargo build --verbose
- name: Linting
run: cargo clippy --all-targets --all-features
- name: Run tests
run: cargo test --verbose -- --nocapture
32 changes: 16 additions & 16 deletions examples/native-json-parser.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use emacs::{defun, Env, Result, Value, IntoLisp};
use emacs::{defun, Env, IntoLisp, Result, Value};
use serde_json as json;

// Emacs won't load the module without this.
Expand All @@ -11,37 +11,37 @@ fn init(env: &Env) -> Result<Value<'_>> {
}

fn json_to_lisp<'a>(env: &'a Env, val: &json::Value) -> Result<Value<'a>> {
match val {
&json::Value::Null | &json::Value::Bool(false) =>
().into_lisp(env),
&json::Value::Bool(true) =>
true.into_lisp(env),
&json::Value::Number(ref num) =>
match &val {
json::Value::Null | &json::Value::Bool(false) => ().into_lisp(env),
json::Value::Bool(true) => true.into_lisp(env),
json::Value::Number(num) => {
if num.is_f64() {
num.as_f64().unwrap().into_lisp(env)
} else if num.is_i64() {
num.as_i64().unwrap().into_lisp(env)
} else {
num.as_u64().unwrap().into_lisp(env)
},
&json::Value::String(ref s) =>
s.into_lisp(env),
&json::Value::Array(ref arr) => {
let vals = arr.iter().map(|x| json_to_lisp(env, x)).collect::<Result<Vec<_>>>()?;
}
}
json::Value::String(s) => s.into_lisp(env),
json::Value::Array(arr) => {
let vals = arr
.iter()
.map(|x| json_to_lisp(env, x))
.collect::<Result<Vec<_>>>()?;
env.vector(&vals)
},
&json::Value::Object(ref map) => {
}
json::Value::Object(map) => {
let mut vals: Vec<Value<'a>> = Vec::new();
for (k, v) in map {
vals.push(env.intern(&format!(":{}", k))?);
vals.push(json_to_lisp(env, v)?);
}
env.list(&vals)
},
}
}
}


#[defun]
fn parse(env: &Env, s: String) -> Result<Value<'_>> {
let start = std::time::Instant::now();
Expand Down
88 changes: 57 additions & 31 deletions src/app.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
use std::sync::{mpsc, Arc, atomic::{AtomicI32, self}};
use std::sync::{
atomic::{self, AtomicI32},
mpsc, Arc,
};

use log::{warn, info, debug};
use anyhow::{Result, Context};
use anyhow::{Context, Result};
use log::{debug, info, warn};
use serde_json as json;

use crate::{rpcio, bytecode::{self, BytecodeOptions}};
use crate::lsp_message::{LspRequest, LspResponse, LspResponseError};
use crate::{
bytecode::{self, BytecodeOptions},
rpcio,
};

fn process_channel_to_writer(channel_sub: mpsc::Receiver<String>,
channel_counter: Option<Arc<AtomicI32>>,
writer: impl std::io::Write) -> Result<()> {
fn process_channel_to_writer(
channel_sub: mpsc::Receiver<String>,
channel_counter: Option<Arc<AtomicI32>>,
writer: impl std::io::Write,
) -> Result<()> {
let mut bufwriter = std::io::BufWriter::new(writer);
for msg in channel_sub.iter() {
if let Some(ref channel_counter) = channel_counter {
Expand All @@ -24,23 +32,27 @@ const MAX_PENDING_MSG_COUNT: i32 = 128;

// Read from client, write to server.
// Or, if server is blocked, reject the request and fake reply when possible
fn process_client_reader(reader: impl std::io::Read,
server_channel_pub: mpsc::Sender<String>,
server_channel_counter: Arc<AtomicI32>,
client_channel_pub: mpsc::Sender<String>) -> Result<()> {
fn process_client_reader(
reader: impl std::io::Read,
server_channel_pub: mpsc::Sender<String>,
server_channel_counter: Arc<AtomicI32>,
client_channel_pub: mpsc::Sender<String>,
) -> Result<()> {
let mut bufreader = std::io::BufReader::new(reader);
loop {
let msg = rpcio::rpc_read(&mut bufreader)?;
if msg.is_empty() {
break
break;
}

if server_channel_counter.load(atomic::Ordering::Acquire) >= MAX_PENDING_MSG_COUNT {
let lsp_request: LspRequest = json::from_str(&msg)?;
// only cancel when it's not notification
if !lsp_request.is_notification() {
warn!("Buffer full, rejecting request: {} (id={:?})",
lsp_request.method, lsp_request.id);
warn!(
"Buffer full, rejecting request: {} (id={:?})",
lsp_request.method, lsp_request.id
);
let resp = LspResponse {
jsonrpc: lsp_request.jsonrpc,
id: lsp_request.id.unwrap(),
Expand All @@ -62,27 +74,32 @@ fn process_client_reader(reader: impl std::io::Read,
Ok(())
}

fn process_server_reader(reader: impl std::io::Read,
channel_pub: mpsc::Sender<String>,
bytecode_options: Option<BytecodeOptions>) -> Result<()> {
fn process_server_reader(
reader: impl std::io::Read,
channel_pub: mpsc::Sender<String>,
bytecode_options: Option<BytecodeOptions>,
) -> Result<()> {
let mut bufreader = std::io::BufReader::new(reader);
loop {
let msg = rpcio::rpc_read(&mut bufreader)?;
if msg.is_empty() {
break
break;
}
if let Some(ref bytecode_options) = bytecode_options {
let json_val = json::from_str(&msg)?;
match bytecode::generate_bytecode_repl(&json_val, bytecode_options.clone()) {
Ok(bytecode_str) => {
debug!("server->client: json {} bytes; converted to bytecode, {} bytes",
msg.len(), bytecode_str.len());
debug!(
"server->client: json {} bytes; converted to bytecode, {} bytes",
msg.len(),
bytecode_str.len()
);
channel_pub.send(bytecode_str)?;
continue
},
continue;
}
Err(err) => {
warn!("Failed to convert json to bytecode: {}", err);
},
}
}
}
debug!("server->client: json {} bytes; forward as-is", msg.len());
Expand All @@ -96,13 +113,18 @@ pub struct AppOptions {
pub bytecode_options: Option<bytecode::BytecodeOptions>,
}

pub fn run_app_forever(client_reader: impl std::io::Read + Send + 'static,
client_writer: impl std::io::Write + Send + 'static,
mut server_cmd: std::process::Command,
options: AppOptions) -> Result<std::process::ExitStatus> {
pub fn run_app_forever(
client_reader: impl std::io::Read + Send + 'static,
client_writer: impl std::io::Write + Send + 'static,
mut server_cmd: std::process::Command,
options: AppOptions,
) -> Result<std::process::ExitStatus> {
info!("Running server {:?}", server_cmd);
if let Some(ref bytecode_options) = options.bytecode_options {
info!("Will convert server json to bytecode! bytecode options: {:?}", bytecode_options);
info!(
"Will convert server json to bytecode! bytecode options: {:?}",
bytecode_options
);
} else {
info!("Bytecode disabled! Will forward server json as-is.")
}
Expand Down Expand Up @@ -149,9 +171,13 @@ pub fn run_app_forever(client_reader: impl std::io::Read + Send + 'static,
std::thread::spawn(move || {
debug!("Started client->server read thread");
process_client_reader(
client_reader, c2s_channel_pub, c2s_channel_counter, s2c_channel_pub)
.with_context(|| "Client->server read thread failed")
.unwrap();
client_reader,
c2s_channel_pub,
c2s_channel_counter,
s2c_channel_pub,
)
.with_context(|| "Client->server read thread failed")
.unwrap();
debug!("Finished client->server read thread");
});

Expand Down
Loading