ad-astra 1.0.0

Embeddable scripting language platform Ad Astra. Main Crate.
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
////////////////////////////////////////////////////////////////////////////////
// This file is part of "Ad Astra", an embeddable scripting programming       //
// language platform.                                                         //
//                                                                            //
// This work is proprietary software with source-available code.              //
//                                                                            //
// To copy, use, distribute, or contribute to this work, you must agree to    //
// the terms of the General License Agreement:                                //
//                                                                            //
// https://github.com/Eliah-Lakhin/ad-astra/blob/master/EULA.md               //
//                                                                            //
// The agreement grants a Basic Commercial License, allowing you to use       //
// this work in non-commercial and limited commercial products with a total   //
// gross revenue cap. To remove this commercial limit for one of your         //
// products, you must acquire a Full Commercial License.                      //
//                                                                            //
// If you contribute to the source code, documentation, or related materials, //
// you must grant me an exclusive license to these contributions.             //
// Contributions are governed by the "Contributions" section of the General   //
// License Agreement.                                                         //
//                                                                            //
// Copying the work in parts is strictly forbidden, except as permitted       //
// under the General License Agreement.                                       //
//                                                                            //
// If you do not or cannot agree to the terms of this Agreement,              //
// do not use this work.                                                      //
//                                                                            //
// This work is provided "as is", without any warranties, express or implied, //
// except where such disclaimers are legally invalid.                         //
//                                                                            //
// Copyright (c) 2024 Ilya Lakhin (Илья Александрович Лахин).                 //
// All rights reserved.                                                       //
////////////////////////////////////////////////////////////////////////////////

use std::thread::park_timeout;

use lady_deirdre::{
    lexis::{Position as LDPosition, SourceCode, ToSite, ToSpan},
    sync::Trigger,
};
use log::{error, warn};
use lsp_types::{
    error_codes::{REQUEST_CANCELLED, REQUEST_FAILED},
    request::SignatureHelpRequest,
    Documentation,
    ParameterInformation,
    ParameterLabel,
    Position,
    SignatureHelp,
    SignatureInformation,
    Uri,
};

use crate::{
    analysis::{
        symbols::{LookupOptions, ModuleSymbol, SymbolKind},
        ModuleError,
        ModuleRead,
        ModuleText,
    },
    runtime::ScriptOrigin,
    server::{
        file::{LspModule, ANALYSIS_PRIORITY},
        logger::LSP_SERVER_LOG,
        rpc::{LspHandle, OutgoingEx, RpcId, RpcLatches},
        tasks::{Task, TaskExecution, COOL_DOWN},
        utils::{lsp_position_to_ld, make_doc},
        LspServerConfig,
        RpcSender,
    },
};

pub(super) struct SendSignatureHelp {
    pub(super) config: LspServerConfig,
    pub(super) latches: RpcLatches,
    pub(super) outgoing: RpcSender,
    pub(super) module: LspModule,
}

impl Task for SendSignatureHelp {
    const EXECUTION: TaskExecution = TaskExecution::ExecuteEach;

    type Config = Self;

    type Message = SendSignatureHelpMessage;

    #[inline(always)]
    fn init(config: Self::Config) -> Self {
        config
    }

    fn handle(&mut self, message: Self::Message) -> bool {
        loop {
            if message.cancel.is_active() {
                warn!(target: LSP_SERVER_LOG, "[{}] Send signature help cancelled by the client.", message.uri.as_str());

                self.outgoing.send_err_response(
                    &self.latches,
                    message.id,
                    REQUEST_CANCELLED,
                    "Send signature help cancelled by the client.",
                );

                break;
            }

            let handle = LspHandle::new(&message.cancel);

            let module_read_guard = match self.module.as_ref().read(&handle, ANALYSIS_PRIORITY) {
                Ok(guard) => guard,

                Err(ModuleError::Interrupted(_)) => {
                    if message.cancel.is_active() {
                        warn!(target: LSP_SERVER_LOG, "[{}] Send signature help cancelled by the client.", message.uri.as_str());

                        self.outgoing.send_err_response(
                            &self.latches,
                            message.id,
                            REQUEST_CANCELLED,
                            "Send signature help cancelled by the client.",
                        );

                        break;
                    }

                    warn!(target: LSP_SERVER_LOG, "[{}] Send signature help interrupted.", message.uri.as_str());
                    park_timeout(COOL_DOWN);
                    continue;
                }

                Err(error) => {
                    error!(target: LSP_SERVER_LOG, "[{}] Send signature help error. {error}", message.uri.as_str());

                    self.outgoing.send_err_response(
                        &self.latches,
                        message.id,
                        REQUEST_FAILED,
                        "Send signature help error.",
                    );

                    break;
                }
            };

            let position = lsp_position_to_ld(&message.position);

            const SIGNATURE_SYMBOLS: u32 = SymbolKind::Call as u32;

            let symbols = match module_read_guard.symbols(
                position..position,
                LookupOptions::new().outer().filter(SIGNATURE_SYMBOLS),
            ) {
                Ok(symbols) => symbols,

                Err(ModuleError::Interrupted(_)) => {
                    if message.cancel.is_active() {
                        warn!(target: LSP_SERVER_LOG, "[{}] Send signature help cancelled by the client.", message.uri.as_str());

                        self.outgoing.send_err_response(
                            &self.latches,
                            message.id,
                            REQUEST_CANCELLED,
                            "Send signature help cancelled by the client.",
                        );

                        break;
                    }

                    warn!(target: LSP_SERVER_LOG, "[{}] Send signature help interrupted.", message.uri.as_str());
                    park_timeout(COOL_DOWN);
                    continue;
                }

                Err(error) => {
                    error!(target: LSP_SERVER_LOG, "[{}] Send signature help error. {error}", message.uri.as_str());

                    self.outgoing.send_err_response(
                        &self.latches,
                        message.id,
                        REQUEST_FAILED,
                        "Send signature help error.",
                    );

                    break;
                }
            };

            let Some(ModuleSymbol::Call(symbol)) = symbols.last() else {
                self.outgoing.send_ok_response::<SignatureHelpRequest>(
                    &self.latches,
                    message.id,
                    None,
                );

                break;
            };

            let text = module_read_guard.text();

            let args_origin = symbol.origin(&module_read_guard);
            let param_index = infer_param_index(&text, &position, args_origin);

            let receiver = symbol.receiver(&module_read_guard);

            let ty = match receiver.expr_ty(&module_read_guard) {
                Ok(ty) => ty,

                Err(ModuleError::Interrupted(_)) => {
                    if message.cancel.is_active() {
                        warn!(target: LSP_SERVER_LOG, "[{}] Send signature help cancelled by the client.", message.uri.as_str());

                        self.outgoing.send_err_response(
                            &self.latches,
                            message.id,
                            REQUEST_CANCELLED,
                            "Send signature help cancelled by the client.",
                        );

                        break;
                    }

                    warn!(target: LSP_SERVER_LOG, "[{}] Send signature help interrupted.", message.uri.as_str());
                    park_timeout(COOL_DOWN);
                    continue;
                }

                Err(error) => {
                    error!(target: LSP_SERVER_LOG, "[{}] Send signature help error. {error}", message.uri.as_str());

                    self.outgoing.send_err_response(
                        &self.latches,
                        message.id,
                        REQUEST_FAILED,
                        "Send signature help error.",
                    );

                    break;
                }
            };

            let Some(invocation) = ty.type_hint.invocation() else {
                self.outgoing.send_ok_response::<SignatureHelpRequest>(
                    &self.latches,
                    message.id,
                    None,
                );

                break;
            };

            let doc = make_doc(
                &module_read_guard,
                &text,
                self.config.capabilities.signature_help_markdown,
                self.config.language_id,
                false,
                &ty,
            );

            let mut params = Vec::with_capacity(invocation.arity().unwrap_or(0));

            if let Some(inputs) = &invocation.inputs {
                for param in inputs {
                    let documentation = match param.hint.is_dynamic() {
                        true => None,
                        false => Some(Documentation::String(param.hint.to_string())),
                    };

                    params.push(ParameterInformation {
                        label: ParameterLabel::Simple(
                            param
                                .name
                                .as_ref()
                                .map(|name| name.to_string())
                                .unwrap_or(String::from("?")),
                        ),

                        documentation,
                    });
                }
            }

            self.outgoing.send_ok_response::<SignatureHelpRequest>(
                &self.latches,
                message.id,
                Some(SignatureHelp {
                    signatures: vec![SignatureInformation {
                        label: invocation.to_string(),
                        documentation: doc.map(|content| Documentation::MarkupContent(content)),
                        parameters: Some(params),
                        active_parameter: None,
                    }],
                    active_signature: Some(0),
                    active_parameter: param_index.map(|index| index as u32),
                }),
            );

            break;
        }

        true
    }

    #[inline(always)]
    fn module(&self) -> &LspModule {
        &self.module
    }
}

pub(super) struct SendSignatureHelpMessage {
    pub(super) id: RpcId,
    pub(super) uri: Uri,
    pub(super) cancel: Trigger,
    pub(super) position: Position,
}

fn infer_param_index(
    text: &ModuleText,
    position: &LDPosition,
    args_origin: ScriptOrigin,
) -> Option<usize> {
    enum State {
        Args(usize),
        InlineComment(usize),
        MultilineComment(usize, usize),
    }

    let mut param_index = 0;

    let site = position.to_site(text)?;
    let mut args_span = args_origin.to_site_span(text)?;

    if args_span.start < args_span.end {
        args_span.start += 1;
    }

    if args_span.start < args_span.end {
        args_span.end -= 1;
    }

    let mut state = State::Args(0);

    for chunk in text.chunks(args_span) {
        match chunk.string {
            "," => {
                if let State::Args(1) = &state {
                    if chunk.end() <= site {
                        param_index += 1;
                        continue;
                    };

                    break;
                }
            }

            "//" => match &state {
                State::Args(nesting) => state = State::InlineComment(*nesting),
                State::InlineComment(_) => (),
                State::MultilineComment(_, _) => (),
            },

            "/*" => match &mut state {
                State::Args(nesting) => state = State::MultilineComment(*nesting, 1),
                State::InlineComment(_) => (),
                State::MultilineComment(_, nesting) => *nesting += 1,
            },

            "*/" => match &mut state {
                State::Args(..) => return None,
                State::InlineComment(_) => (),
                State::MultilineComment(args_nesting, comment_nesting) => {
                    *comment_nesting = match comment_nesting.checked_sub(1) {
                        Some(nesting) => nesting,
                        None => return None,
                    };

                    if *comment_nesting == 0 {
                        state = State::Args(*args_nesting);
                    }
                }
            },

            "\n" | "\r\n" => match &mut state {
                State::Args(..) => (),
                State::InlineComment(args_nesting) => state = State::Args(*args_nesting),
                State::MultilineComment(_, _) => (),
            },

            "{" | "[" | "(" => match &mut state {
                State::Args(nesting) => *nesting += 1,
                State::InlineComment(_) => (),
                State::MultilineComment(_, _) => (),
            },

            "}" | "]" => match &mut state {
                State::Args(nesting) => {
                    *nesting = match nesting.checked_sub(1) {
                        Some(nesting) => {
                            if nesting == 0 {
                                return None;
                            }

                            nesting
                        }
                        None => return None,
                    };
                }
                State::InlineComment(_) => {}
                State::MultilineComment(_, _) => {}
            },

            ")" => match &mut state {
                State::Args(nesting) => {
                    *nesting = match nesting.checked_sub(1) {
                        Some(nesting) => {
                            if nesting == 0 {
                                break;
                            }

                            nesting
                        }
                        None => return None,
                    };
                }
                State::InlineComment(_) => {}
                State::MultilineComment(_, _) => {}
            },

            _ => (),
        }
    }

    Some(param_index)
}