summaryrefslogtreecommitdiff
path: root/isabelle-proto/src/main.rs
blob: b16b8ac87d8a8649764808fd41c8115c2f2c0619 (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
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
mod session;

use regex::Regex;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use serde_json::{Result, Value};
use session::IsabelleSession;

use std::{io::{BufRead, BufReader, BufWriter, Write}, path::PathBuf, process::{ChildStdout, Command, Stdio}};
use std::fmt::Debug;

use isabelle_unicode::PrettyUnicode;

use structopt::StructOpt;

type SessionID = String;
type TaskID = String;

#[derive(Serialize, Deserialize)]
#[serde(untagged)]
enum ClientCommand {
    UseTheories {
        session_id : SessionID,
        theories : Vec<String>,
        master_dir : Option<String>
    },
    SessionStart {
        session : String,
        include_sessions : Vec<String>
    },
    Echo (String),
    ShutDown
}

#[derive(Debug)]
enum SyncAnswer<T,E> {
    Ok (T),
    Error (E),
}

enum AsyncAnswer<T, E, N> {
    Finished (T),
    Failed (E),
    Note (N)
}

#[derive(Deserialize, Debug)]
struct ClientHello {
    isabelle_id : String,
    isabelle_version : String
}

#[derive(Deserialize)]
struct SessionStartedOk {
    session_id : String,
    tmp_dir : String,
    task : String
}

#[derive(Deserialize)]
struct SessionStartedNote {
    percentage : u8,
    task : TaskID,
    message : String,
    kind : String,
    session : String,
    theory : String
}

#[derive(Deserialize, Clone, Debug)]
struct SessionStartedFinished {
    session_id : SessionID,
    tmp_dir : String,
    task : TaskID
}



#[derive(Deserialize, Clone, Debug)]
struct UseTheoriesFinished {
    ok : bool,
    errors : Vec<IsabelleError>,
    nodes : Vec<IsabelleNode>,
    task : TaskID,
}

#[derive(Deserialize, Clone, Debug)]
struct IsabelleError {
    kind : String,
    message : String,
    pos : Span
}

#[derive(Deserialize, Clone, Debug)]
struct IsabelleNode {
    messages : Vec<IsabelleError>,
    exports : Vec<()>,
    status : Status,
    theory_name : String,
    node_name : String
}

#[derive(Deserialize, Clone, Debug)]
struct Status {
    percentage : u8,
    unprocessed : u64,
    running : u64,
    finished : u64,
    failed : u64,
    total : u64,
    consolidated : bool,
    canceled : bool,
    ok : bool,
    warned : u64
}

#[derive(Deserialize,Clone, Debug)]
struct Span {
    line : u64,
    offset : u64,
    end_offset : u64,
    file : String
}

#[derive(Deserialize)]
struct AsyncStartOk {
    task : TaskID
}

fn decode_sync<'a, T> (msg: &'a str) -> Option<SyncAnswer<T, String>>
where T: Deserialize<'a> {
    let regex = Regex::new(r"^[a-zA-Z]+\b").unwrap();
    let mat = regex.find(msg)?;
    let ty = &msg[..mat.end()];
    let rest = &msg[mat.end()..];

    match ty {
        "OK" => Some(SyncAnswer::Ok(serde_json::from_str(&rest).ok()?)),
        "ERROR" => Some(SyncAnswer::Error(rest.to_owned())),
        _ => None
    }
}

fn decode_async<'a,T,E,N> (msg: &'a str) -> Option<AsyncAnswer<T,E,N>>
where T: Deserialize<'a>, N: Deserialize<'a>, E: Deserialize<'a> {
    let regex = Regex::new(r"^[a-zA-Z]+\b").unwrap();
    let mat = regex.find(msg)?;
    let ty = &msg[..mat.end()];
    let rest = &msg[mat.end()..];

    match ty {
        "NOTE" => Some(AsyncAnswer::Note(serde_json::from_str(&rest).ok()?)),
        "FINISHED" => Some(AsyncAnswer::Finished(serde_json::from_str(&rest).ok()?)),
        "FAILED" => Some(AsyncAnswer::Failed(serde_json::from_str(&rest).ok()?)),
        _ => None
    }
}



trait Encode {
    fn encode (&self) -> String;
}

impl Encode for ClientCommand {
    fn encode (&self) -> String {
        let ty = match self {
            ClientCommand::UseTheories {..} => "use_theories",
            ClientCommand::SessionStart {..} => "session_start",
            ClientCommand::Echo (..) => "echo",
            ClientCommand::ShutDown => "shutdown"
        };

        let blob = serde_json::to_string(self).unwrap();

        let res = ty.to_owned() + &blob + "\n";
        println!("encoded: {}", res);
        res
    }
}

fn wait_for_client(pipe: &mut BufReader<ChildStdout>) -> Option<ClientHello> {
    for res in pipe.lines() {
        match res {
            Err(_) => (),
            Ok(line) => {
                let hello : Option<SyncAnswer<ClientHello, _>> = decode_sync(&line);
                if let Some(SyncAnswer::Ok(data)) = hello {
                    return Some(data);
                }
            }
        }
    }
    None
}


fn wait_for_async_task<'a,T,E,N,F>
    (reader: &mut BufReader<ChildStdout>, task: &str, mut prog: F) -> Option<T>
where T: DeserializeOwned, E: DeserializeOwned + Debug, N: DeserializeOwned,
F: FnMut(N)
{
    for res in reader.lines() {
        match res {
            Err(_) => (),
            Ok(line) => {
                let regex = Regex::new(r"^[0-9]+$").unwrap();
                if regex.is_match(&line) {

                } else {
                    match decode_async::<T,E,N>(&line)? {
                        AsyncAnswer::Finished(data)
                            => return Some(data),
                        AsyncAnswer::Failed(failed)
                            => panic!("building session failed: {:?}", failed),
                        AsyncAnswer::Note(val) => prog(val)
                    }
                }
            }
        }
    };
    None
}

fn get_async_task_id (reader: &mut BufReader<ChildStdout>) -> TaskID {
    let mut res = String::new();
    reader.read_line(&mut res).unwrap();
    match decode_sync(&res).unwrap() {
        SyncAnswer::Ok(AsyncStartOk { task }) => task,
        SyncAnswer::Error(_) => panic!("failed to start async task!")
    }
}

#[derive(StructOpt)]
#[structopt(name = "isabelle-proto-POC", about="proof of concept for communicating with an Isabelle server")]
struct Options {
    theory : String,
    #[structopt(name="directory", default_value=Box::leak(Box::new(std::env::current_dir().unwrap().into_os_string().into_string().unwrap())))]
    directory : String
}



fn main() {
    let options = Options::from_args();
    let mut session = IsabelleSession::start_with_client();

    let started = session.start_session("HOL".to_owned(),vec![]).unwrap();

    println!("{:?}", started);

    let theoryresults = session.load_theory(
        options.theory,
        Some(options.directory)
    );

    println!("loaded theory: {:?}", theoryresults);
}