aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_proc_macro_srv/src/cli.rs
blob: c771f2b389115deb6078b4116eecec15bb6852b5 (plain)
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
//! Driver for proc macro server

use crate::{expand_task, list_macros};
use ra_proc_macro::msg::{self, Message};

use std::io;

fn read_request() -> Result<Option<msg::Request>, io::Error> {
    let stdin = io::stdin();
    let mut stdin = stdin.lock();
    msg::Request::read(&mut stdin)
}

fn write_response(res: Result<msg::Response, String>) -> Result<(), io::Error> {
    let msg: msg::Response = match res {
        Ok(res) => res,
        Err(err) => msg::Response::Error(msg::ResponseError {
            code: msg::ErrorCode::ExpansionError,
            message: err,
        }),
    };

    let stdout = io::stdout();
    let mut stdout = stdout.lock();
    msg.write(&mut stdout)
}

pub fn run() {
    loop {
        let req = match read_request() {
            Err(err) => {
                eprintln!("Read message error on ra_proc_macro_srv: {}", err.to_string());
                continue;
            }
            Ok(None) => continue,
            Ok(Some(req)) => req,
        };

        match req {
            msg::Request::ListMacro(task) => {
                if let Err(err) =
                    write_response(list_macros(&task).map(|it| msg::Response::ListMacro(it)))
                {
                    eprintln!("Write message error on list macro: {}", err);
                }
            }
            msg::Request::ExpansionMacro(task) => {
                if let Err(err) =
                    write_response(expand_task(&task).map(|it| msg::Response::ExpansionMacro(it)))
                {
                    eprintln!("Write message error on expansion macro: {}", err);
                }
            }
        }
    }
}