rested 0.11.0

Language/Interpreter for easily defining and running requests to an http server.
Documentation
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::Mutex;
mod completions;
mod hover;
mod position;
mod warnings;

use crate::config::get_env_from_dir_path_or_from_home_dir;
use crate::interpreter::environment::Environment;
use crate::interpreter::{self, runner};
use crate::lexer;
use crate::lexer::locations::{GetSpan, Location};
use crate::parser::ast_visit::VisitWith;
use crate::parser::{self, ast};
use anyhow::{anyhow, Context};
use completions::*;
use tower_lsp::jsonrpc::Result;
use tower_lsp::{lsp_types::*, LspService, Server};
use tower_lsp::{Client, LanguageServer};
use tracing::{debug, error, info, warn};

use self::position::ContainsPosition;

trait IntoPosition {
    fn into_position(self) -> Position;
}

impl IntoPosition for Location {
    fn into_position(self) -> Position {
        Position {
            line: self.line as u32,
            character: self.col as u32,
        }
    }
}

impl IntoPosition for lexer::locations::Position {
    fn into_position(self) -> Position {
        Position {
            line: self.line as u32,
            character: self.col as u32,
        }
    }
}

#[derive(Debug)]
struct Backend {
    pub client: Client,
    pub documents: TextDocuments,
}

#[derive(Debug)]
struct TextDocuments {
    pub inner: Mutex<HashMap<Url, String>>,
}

impl TextDocuments {
    fn new() -> Self {
        Self {
            inner: Mutex::new(HashMap::new()),
        }
    }

    fn get(&self, uri: &Url) -> Option<String> {
        match self.inner.lock() {
            Ok(map) => map.get(uri).cloned(),
            Err(_) => None,
        }
    }

    fn put(&self, url: Url, text: String) {
        if let Ok(mut map) = self.inner.lock() {
            map.insert(url, text);
        }
    }
}

struct ChangedDocumentItem {
    pub uri: Url,

    pub version: Option<i32>,

    pub text: String,
}

impl Backend {
    async fn workspace_uris(&self) -> Result<Option<Vec<Url>>> {
        let paths = self
            .client
            .workspace_folders()
            .await?
            .map(|folders| folders.into_iter().map(|f| f.uri).collect::<Vec<_>>());

        Ok(paths)
    }

    async fn get_env(&self) -> anyhow::Result<Environment> {
        let workspace_uris = match self.workspace_uris().await {
            Ok(workspace_uris) => workspace_uris,
            _ => {
                self.client
                    .log_message(
                        MessageType::WARNING,
                        "didn't define the root_dir for rstdls",
                    )
                    .await;
                None
            }
        };

        let env = get_env_from_dir_path_or_from_home_dir(
            workspace_uris
                .and_then(|uris| uris.first().and_then(|uri| uri.to_file_path().ok()))
                .as_deref(),
        )?;

        return Ok(env);
    }

    async fn log_error(&self, err: impl Into<Box<dyn std::error::Error>>) {
        self.client
            .log_message(MessageType::ERROR, format!("{:#}", err.into()))
            .await;
    }

    async fn on_change(&self, params: ChangedDocumentItem) {
        let Ok(env) = self.get_env().await else {
            self.client
                .log_message(MessageType::ERROR, "failed to initialize the environment")
                .await;

            return self
                .client
                .publish_diagnostics(params.uri, vec![], params.version)
                .await;
        };

        // Handle warnings...

        let program = parser::Parser::new(&params.text).parse();

        let mut w = warnings::EnvVarsNotInAllNamespaces::new(&env);

        for item in program.items.iter() {
            item.visit_with(&mut w)
        }

        let mut diagnostics = w.warnings;

        // Done handling warnings

        let Err(interp_errors) = program.interpret(&env) else {
            self.documents.put(params.uri.clone(), params.text);

            return self
                .client
                .publish_diagnostics(params.uri, diagnostics, params.version)
                .await;
        };

        match interp_errors {
            interpreter::error::InterpreterError::ParseErrors(p) => {
                for err in p.errors.iter() {
                    let range = Range {
                        start: match &err.inner_error {
                            parser::error::ParseError::ExpectedToken { found, .. }
                            | parser::error::ParseError::ExpectedEitherOfTokens { found, .. } => {
                                found.start.into_position()
                            }
                        },
                        end: match &err.inner_error {
                            parser::error::ParseError::ExpectedToken { found, .. }
                            | parser::error::ParseError::ExpectedEitherOfTokens { found, .. } => {
                                found.span().end.into_position()
                            }
                        },
                    };

                    diagnostics.push(Diagnostic::new_simple(range, err.inner_error.to_string()));

                    if let Some(msg) = err.message.clone() {
                        diagnostics.push(Diagnostic::new_simple(range, msg.to_string()))
                    }
                }
            }
            interpreter::error::InterpreterError::EvalErrors(errors) => {
                for err in errors.iter() {
                    let range = Range {
                        start: err.span.start.into_position(),
                        end: err.span.end.into_position(),
                    };

                    diagnostics.push(Diagnostic::new_simple(range, err.inner_error.to_string()));

                    if let Some(msg) = err.message.clone() {
                        diagnostics.push(Diagnostic::new_simple(range, msg.to_string()))
                    }
                }
            }
        }

        self.documents.put(params.uri.clone(), params.text);

        diagnostics.reverse();

        self.client
            .publish_diagnostics(params.uri, diagnostics, params.version)
            .await;
    }
}

#[tower_lsp::async_trait]
impl LanguageServer for Backend {
    async fn initialize(&self, _: InitializeParams) -> Result<InitializeResult> {
        Ok(InitializeResult {
            server_info: None,
            capabilities: ServerCapabilities {
                text_document_sync: Some(TextDocumentSyncCapability::Kind(
                    TextDocumentSyncKind::FULL,
                )),
                completion_provider: Some(CompletionOptions {
                    ..CompletionOptions::default()
                }),
                hover_provider: Some(HoverProviderCapability::Simple(true)),
                document_formatting_provider: Some(OneOf::Left(true)),
                code_lens_provider: Some(CodeLensOptions {
                    resolve_provider: None,
                }),
                execute_command_provider: Some(ExecuteCommandOptions {
                    commands: vec!["run".to_string()],
                    ..Default::default()
                }),
                ..ServerCapabilities::default()
            },
        })
    }

    async fn initialized(&self, _: InitializedParams) {
        self.client
            .log_message(MessageType::INFO, "server initialized!")
            .await;
    }

    async fn hover(&self, params: HoverParams) -> Result<Option<Hover>> {
        let uri = params.text_document_position_params.text_document.uri;
        let current_position = params.text_document_position_params.position;

        debug!("cursor position -> {:?}", current_position);

        let Some(text) = self.documents.get(&uri) else {
            error!("failed to get the text by uri: {}", uri);

            debug!("{:?}", self.documents);

            return Ok(None);
        };

        let program = parser::Parser::new(&text).parse();

        let env = match self.get_env().await {
            Ok(env) => env,
            Err(err) => {
                self.client
                    .log_message(MessageType::ERROR, format!("{err:#}"))
                    .await;
                return Ok(None);
            }
        };

        let Some(current_item) = program
            .items
            .iter()
            .find(|i| i.span().contains(&current_position))
        else {
            debug!("cursor is apparently not on any items");
            debug!("{:?}", program);
            return Ok(None);
        };

        let program = match program.interpret(&env) {
            Ok(program) => Some(program),
            Err(err) => {
                self.client
                    .log_message(MessageType::ERROR, format!("{err:#}"))
                    .await;
                None
            }
        };

        let mut hover = hover::HoverDocsResolver::new(program, current_position, env);

        current_item.visit_with(&mut hover);

        Ok(Some(Hover {
            contents: HoverContents::Markup(MarkupContent {
                kind: MarkupKind::Markdown,
                value: hover.docs.unwrap_or_default(),
            }),
            range: None,
        }))
    }

    async fn completion(&self, params: CompletionParams) -> Result<Option<CompletionResponse>> {
        let position = params.text_document_position.position;

        debug!("cursor position -> {:?}", position);

        let Some(text) = self
            .documents
            .get(&params.text_document_position.text_document.uri)
        else {
            error!(
                "failed to get the text by uri: {}",
                params.text_document_position.text_document.uri
            );

            debug!("{:?}", self.documents);

            return Ok(None);
        };

        let program = parser::Parser::new(&text).parse();

        let env = match self.get_env().await {
            Ok(env) => env,
            Err(err) => {
                self.client
                    .log_message(MessageType::ERROR, format!("{err:#}"))
                    .await;
                return Ok(None);
            }
        };

        let mut completions_collector = CompletionsCollector::new(&program, position, env);

        let Some(current_item) = program.items.iter().find(|i| i.span().contains(&position)) else {
            debug!("cursor is apparently not on any items");
            debug!("{:?}", program);
            return Ok(Some(CompletionResponse::Array(item_keywords())));
        };

        debug!("cursor on item -> {:?}", current_item);

        current_item.visit_with(&mut completions_collector);

        debug!("done collecting completions");

        return Ok(completions_collector.into_response());
    }

    async fn did_open(&self, params: DidOpenTextDocumentParams) {
        self.on_change(ChangedDocumentItem {
            uri: params.text_document.uri,
            version: Some(params.text_document.version),
            text: params.text_document.text,
        })
        .await;
    }

    async fn did_save(&self, params: DidSaveTextDocumentParams) {
        let text = match std::fs::read_to_string(params.text_document.uri.path())
            .context("failed to read file after save")
        {
            Ok(text) => text,
            Err(err) => {
                self.client
                    .log_message(MessageType::WARNING, format!("{err:#}"))
                    .await;
                return;
            }
        };

        self.on_change(ChangedDocumentItem {
            uri: params.text_document.uri,
            version: None,
            text,
        })
        .await;
    }

    async fn did_change(&self, params: DidChangeTextDocumentParams) {
        self.on_change(ChangedDocumentItem {
            uri: params.text_document.uri,
            version: Some(params.text_document.version),
            text: params.content_changes[0].text.clone(),
        })
        .await;
    }

    async fn did_close(&self, params: DidCloseTextDocumentParams) {
        self.documents
            .inner
            .lock()
            .expect("failed to get lock for text documents")
            .remove(&params.text_document.uri);
    }

    async fn formatting(&self, params: DocumentFormattingParams) -> Result<Option<Vec<TextEdit>>> {
        let uri = params.text_document.uri;
        let Some(text) = self.documents.get(&uri) else {
            warn!(
                "formatting request for an unknown document, by uri: {}",
                uri
            );
            return Ok(None);
        };

        let program = ast::Program::from(&text);
        let formatted_text = match program.to_formatted_string() {
            Ok(formatted_text) => formatted_text,
            Err(err) => {
                error!("failed to format the source text");
                error!("{err:#}");
                return Ok(None);
            }
        };

        let start = Position::new(0, 0);
        let Some(end) = program.items.last().map(|item| {
            let pos = item.span().end;
            Position {
                line: (pos.line as u32) + 1,
                character: (pos.col as u32),
            }
        }) else {
            info!("document has no items to format: {uri}");
            return Ok(None);
        };

        Ok(Some(vec![TextEdit {
            range: Range::new(start, end),
            new_text: formatted_text,
        }]))
    }

    async fn code_lens(&self, params: CodeLensParams) -> Result<Option<Vec<CodeLens>>> {
        let env = match self.get_env().await {
            Ok(env) => env,
            Err(err) => {
                self.client
                    .log_message(MessageType::ERROR, format!("{err:#}"))
                    .await;
                return Ok(None);
            }
        };

        let uri = params.text_document.uri;
        let Some(text) = self.documents.get(&uri) else {
            warn!("codeLens request for an unknown document, by uri: {}", uri);
            return Ok(None);
        };

        let program = parser::Parser::new(&text).parse();

        let program = match program.interpret(&env) {
            Ok(p) => p,
            Err(err) => {
                self.log_error(anyhow!("{err:#}")).await;
                return Ok(None);
            }
        };

        let codelenses = program
            .items
            .iter()
            .map(|item| {
                let range = Range {
                    start: item.span.start.into_position(),
                    end: item.span.end.into_position(),
                };
                let arg = runner::request_id::RequestId::from(item);

                CodeLens {
                    range,
                    command: Some(Command {
                        title: "Run".to_string(),
                        command: "run".to_string(),
                        arguments: Some(vec![
                            serde_json::Value::String(uri.to_string()),
                            serde_json::Value::String(arg.as_string()),
                        ]),
                    }),
                    data: None,
                }
            })
            .collect();

        Ok(Some(codelenses))
    }

    async fn execute_command(
        &self,
        params: ExecuteCommandParams,
    ) -> Result<Option<serde_json::Value>> {
        match params.command.as_ref() {
            "run" => {
                let args = params
                    .arguments
                    .into_iter()
                    .map(|arg| {
                        arg.as_str()
                            .expect("we should have passed args from the code_lens method")
                            .to_string()
                    })
                    .collect::<Vec<_>>();

                let [path, request_id] = args.as_slice() else {
                    self.log_error(anyhow!(
                        "incorrect number of arguments for 'run' command: {:?}",
                        args
                    ))
                    .await;
                    return Ok(None);
                };

                let uri = Url::from_str(path).expect("failed to read path argument as a Url");
                let path = uri.path();

                let request_id = runner::request_id::RequestId::from_str(request_id)
                    .expect("found invalid request id passed to 'run' command")
                    .url_or_name;

                let Ok(code) = interpreter::read_program_text(Some(path.into())) else {
                    self.log_error(anyhow!("failed to read file from path: {}", path))
                        .await;
                    return Ok(None);
                };

                let env = match self.get_env().await {
                    Ok(env) => env,
                    Err(err) => {
                        self.client
                            .log_message(MessageType::ERROR, format!("{err:#}"))
                            .await;
                        return Ok(None);
                    }
                };

                let Ok(program) = interpreter::interpret_program(&code, env) else {
                    self.log_error(anyhow!("failed to interpret program")).await;
                    return Ok(None);
                };

                info!("running request, id: {}", request_id);

                let response = program
                    .run_ureq(Some(&[request_id]))
                    .iter()
                    .map(|(id, res)| {
                        let mut text = String::new();
                        text.push('`');
                        text.push_str(&id.as_string());
                        text.push('`');
                        text.push('\n');

                        let res = match res {
                            runner::RunResponse::Success(s) => {
                                text.push_str("```json\n");
                                s
                            }
                            runner::RunResponse::Failure(s) => {
                                text.push_str("```sh\n");
                                s
                            }
                        };

                        text.push_str(res);
                        text.push_str("\n```");
                        return text;
                    })
                    .collect::<Vec<_>>()
                    .join("\n\n");

                assert_ne!(
                    response.len(),
                    0,
                    "there must be response(s) to the request"
                );

                return Ok(Some(serde_json::Value::Array(
                    response
                        .lines()
                        .map(|line| serde_json::Value::String(line.to_string()))
                        .collect(),
                )));
            }
            _ => Ok(None),
        }
    }

    async fn shutdown(&self) -> Result<()> {
        Ok(())
    }
}

pub fn start(level: tracing::Level) {
    let subscriber = tracing_subscriber::fmt()
        .pretty()
        .with_max_level(level)
        .with_ansi(false)
        .with_writer(std::io::stderr)
        .finish();

    tracing::subscriber::with_default(subscriber, || {
        tokio::runtime::Builder::new_multi_thread()
            .enable_all()
            .build()
            .unwrap()
            .block_on(run());
    })
}

#[tracing::instrument]
async fn run() {
    let stdin = tokio::io::stdin();
    let stdout = tokio::io::stdout();

    let (service, socket) = LspService::new(|client| Backend {
        client,
        documents: TextDocuments::new(),
    });

    Server::new(stdin, stdout, socket).serve(service).await;
}