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
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
////////////////////////////////////////////////////////////////////////////////
// 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::{marker::PhantomData, ops::Deref};

use ahash::{AHashMap, AHashSet, RandomState};
use compact_str::CompactString;
use lady_deirdre::{
    analysis::{AnalysisResult, SemanticAccess, Semantics, TaskHandle},
    arena::{Id, Identifiable},
    lexis::{Site, SiteSpan, SourceCode, TokenRef},
    syntax::{AbstractNode, NodeRef, PolyRef, SyntaxTree, Visitor},
    units::CompilationUnit,
};

use crate::{
    analysis::{
        symbols::{EntrySymbol, PackageSymbol, VarSymbol},
        Description,
        ModuleResultEx,
    },
    report::system_panic,
    runtime::{Ident, PackageMeta, ScriptIdent, TypeHint},
    semantics::{IdentSemantics, LocalNamespace, PackageSemantics, Tag},
    syntax::{ScriptDoc, ScriptNode},
};

pub(super) static PROMPT_STRING: &'static str = "__AD_ASTRA_COMPLETION";

/// A description object for code completion.
///
/// This object is returned by the
/// [completions](crate::analysis::ModuleWrite::completions) function, which
/// performs the actual estimation
#[derive(Clone)]
pub struct Completions {
    /// A globally unique identifier for the script module
    /// (same as [ScriptModule::id](crate::analysis::ScriptModule::id)).
    pub id: Id,

    /// An absolute index of the character within the script's source code.
    ///
    /// This value is the same as the one specified in the
    /// [completions](crate::analysis::ModuleWrite::completions) function.
    pub site: Site,

    /// A range of the source code text fragment that is supposed to be replaced
    /// by the completion candidate text.
    pub place: SiteSpan,

    /// A substring of the source code text that the completion algorithm
    /// attempted to complete. In most cases, this substring corresponds to the
    /// [place](Completions::span) replacement range.
    pub pattern: String,

    /// The type of language construct that the completion candidates attempt
    /// to complete.
    pub scope: CompletionScope,

    /// The list of completion candidates.
    pub items: Vec<CompletionItem>,
}

impl Identifiable for Completions {
    #[inline(always)]
    fn id(&self) -> Id {
        self.id
    }
}

impl Completions {
    pub(super) fn analyze<H: TaskHandle>(
        id: Id,
        site: Site,
        task: &impl SemanticAccess<ScriptNode, H, RandomState>,
    ) -> AnalysisResult<Self> {
        let doc_read = task.read_doc(id).forward()?;
        let doc = doc_read.deref();

        let from = match site > 0 {
            true => site - 1,
            false => site,
        };

        let to = match site < doc.length() {
            true => site + 1,
            false => site,
        };

        let subtree = doc.cover(from..to);

        let mut prompt_analyzer = PromptAnalyzer {
            task,
            doc,
            site,
            result: Ok(None),
            _handle: PhantomData,
        };

        doc.traverse_subtree(&subtree, &mut prompt_analyzer);

        Ok(prompt_analyzer.result?.unwrap_or_else(|| Self {
            id,
            site,
            place: site..site,
            pattern: String::new(),
            scope: CompletionScope::Unknown,
            items: Vec::new(),
        }))
    }
}

/// A completion candidate within the [Completions] code-completion description
/// object.
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct CompletionItem {
    /// The completion text that is supposed to replace the text at the
    /// [place](Completions#structfield.place) in the source code.
    ///
    /// You can convert this object to an actual string using the
    /// `item.label.to_string()` function.
    pub label: Ident,

    /// Additional metadata about the completed item.
    pub desc: Description,
}

/// A type of language construct targeted by the code completion.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[non_exhaustive]
pub enum CompletionScope {
    /// Indicates that code completion is not available at the specified
    /// location in the source code.
    Unknown,

    /// A code completion for a package inside an import statement:
    ///
    /// ```text
    /// use foo.bar.<completion site>;
    /// ```
    Import,

    /// A code completion inside an expression:
    ///
    /// ```text
    /// foo(bar, <completion site>)
    /// ```
    Expression,

    /// A code completion inside a statement within a block:
    ///
    /// ```text
    /// {
    ///     foo;
    ///     <completion site>
    ///     bar;
    /// }
    /// ```
    Statement,

    /// A code completion for an arm of a match statement:
    ///
    /// ```text
    /// match foo {
    ///     bar => {},
    ///     <completion site>
    ///     baz => (),
    /// }
    /// ```
    MatchArm,

    /// A code completion for a field access operator in an expression:
    ///
    /// ```text
    /// foo.bar.<completion site>
    /// ```
    Field,
}

struct PromptAnalyzer<'a, H: TaskHandle, T: SemanticAccess<ScriptNode, H, RandomState>> {
    task: &'a T,
    doc: &'a ScriptDoc,
    site: Site,
    result: AnalysisResult<Option<Completions>>,
    _handle: PhantomData<H>,
}

impl<'a, H: TaskHandle, T: SemanticAccess<ScriptNode, H, RandomState>> Visitor
    for PromptAnalyzer<'a, H, T>
{
    fn visit_token(&mut self, _token_ref: &TokenRef) {}

    fn enter_node(&mut self, node_ref: &NodeRef) -> bool {
        let Ok(None) = &self.result else {
            return false;
        };

        let Some(script_node) = node_ref.deref(self.doc) else {
            return true;
        };

        self.result = match script_node {
            ScriptNode::Package {
                token, semantics, ..
            } => self.analyze_package(token, semantics),

            ScriptNode::Ident {
                parent,
                token,
                semantics,
                ..
            } => self.analyze_ident(parent, token, semantics),

            ScriptNode::Field { parent, token, .. } => self.analyze_field(parent, token),
            _ => return true,
        };

        match &self.result {
            Ok(None) => {
                let Some(span) = script_node.span(self.doc) else {
                    return true;
                };

                if span.end < self.site || span.start > self.site {
                    return false;
                }

                true
            }
            _ => false,
        }
    }

    fn leave_node(&mut self, _node_ref: &NodeRef) {}
}

impl<'a, H: TaskHandle, T: SemanticAccess<ScriptNode, H, RandomState>> PromptAnalyzer<'a, H, T> {
    fn analyze_package(
        &self,
        token: &TokenRef,
        semantics: &Semantics<PackageSemantics>,
    ) -> AnalysisResult<Option<Completions>> {
        let Some(chunk) = token.chunk(self.doc) else {
            return Ok(None);
        };

        let Some(byte_index) = chunk.string.find(PROMPT_STRING) else {
            return Ok(None);
        };

        let pattern = &chunk.string[0..byte_index];

        let package_semantics = semantics.get().forward()?;

        let (_, resolution) = package_semantics
            .package_resolution
            .snapshot(self.task)
            .forward()?;

        let mut items = Vec::new();

        if let Some(parent) = resolution.parent {
            let parent_prototype = parent.ty().prototype();

            for component in parent_prototype.hint_all_components() {
                if !component.ty.is_package() {
                    continue;
                }

                items.push(CompletionItem {
                    label: Ident::Rust(component.name),
                    desc: Description::from_component(&component),
                });
            }
        };

        Ok(Some(Completions {
            id: self.doc.id(),
            site: self.site,
            place: chunk.start()..(chunk.end() - PROMPT_STRING.len()),
            pattern: String::from(pattern),
            scope: CompletionScope::Import,
            items,
        }))
    }

    fn analyze_ident(
        &self,
        parent: &NodeRef,
        token: &TokenRef,
        semantics: &Semantics<IdentSemantics>,
    ) -> AnalysisResult<Option<Completions>> {
        let Some(chunk) = token.chunk(self.doc) else {
            return Ok(None);
        };

        let Some(byte_index) = chunk.string.find(PROMPT_STRING) else {
            return Ok(None);
        };

        let pattern = &chunk.string[0..byte_index];

        let mut scope_attr = semantics.scope_attr().forward()?;

        let ident_semantics = semantics.get().forward()?;

        let (_, local_namespace) = ident_semantics.namespace.snapshot(self.task).forward()?;

        let mut accumulator = AHashMap::new();

        self.prompt_namespace(local_namespace.as_ref(), &mut accumulator)?;

        loop {
            let scope_ref = scope_attr.snapshot(self.task).forward()?.1.scope_ref;

            let Some(ScriptNode::Fn { semantics, .. }) = scope_ref.deref(self.doc) else {
                break;
            };

            scope_attr = semantics.scope_attr().forward()?;

            let fn_semantics = semantics.get().forward()?;

            let (_, fn_namespace) = fn_semantics.namespace.snapshot(self.task).forward()?;

            self.prompt_namespace(fn_namespace.as_ref(), &mut accumulator)?;
        }

        let mut scope = CompletionScope::Expression;

        if let Some(ScriptNode::Expr { parent, node, .. }) = parent.deref(self.doc) {
            match parent.deref(self.doc) {
                Some(ScriptNode::Clause { end, .. }) if end.is_nil() => {
                    scope = CompletionScope::Statement;
                }

                Some(ScriptNode::MatchArm { case, handler, .. })
                    if case == node && pattern.is_empty() && handler.is_nil() =>
                {
                    scope = CompletionScope::MatchArm;
                }

                _ => (),
            }
        }

        Ok(Some(Completions {
            id: self.doc.id(),
            site: self.site,
            place: chunk.start()..(chunk.end() - PROMPT_STRING.len()),
            pattern: String::from(pattern),
            scope,
            items: accumulator.into_values().collect(),
        }))
    }

    fn analyze_field(
        &self,
        parent: &NodeRef,
        token: &TokenRef,
    ) -> AnalysisResult<Option<Completions>> {
        let Some(chunk) = token.chunk(self.doc) else {
            return Ok(None);
        };

        let Some(byte_index) = chunk.string.find(PROMPT_STRING) else {
            return Ok(None);
        };

        let pattern = &chunk.string[0..byte_index];

        let mut items = Vec::new();

        loop {
            let Some(ScriptNode::Binary { left, .. }) = parent.deref(self.doc) else {
                break;
            };

            let Some(left_node) = left.deref(self.doc) else {
                break;
            };

            let (_, left_type_resolution) = left_node
                .type_resolution()
                .forward()?
                .snapshot(self.task)
                .forward()?;

            items = match &left_type_resolution.tag {
                Tag::Struct(struct_ref) => self.prompt_struct(&struct_ref)?,
                other => self.prompt_type(other)?,
            };

            break;
        }

        let place = chunk.start()..(chunk.end() - PROMPT_STRING.len());

        Ok(Some(Completions {
            id: self.doc.id(),
            site: self.site,
            place,
            pattern: String::from(pattern),
            scope: CompletionScope::Field,
            items,
        }))
    }

    fn prompt_namespace(
        &self,
        namespace: &LocalNamespace,
        accumulator: &mut AHashMap<CompactString, CompletionItem>,
    ) -> AnalysisResult<()> {
        for (key, value) in &namespace.map {
            if accumulator.contains_key(key) {
                continue;
            }

            let Some(decl_node) = value.as_ref().decl.deref(self.doc) else {
                continue;
            };

            let item = match decl_node {
                ScriptNode::Root { .. } => {
                    let Some(package) = PackageMeta::by_id(self.doc.id()) else {
                        system_panic!("Missing package.");
                    };

                    let Some(component) = package.ty().prototype().hint_component(key.as_str())
                    else {
                        continue;
                    };

                    CompletionItem {
                        label: Ident::Rust(component.name),
                        desc: Description::from_component(&component),
                    }
                }

                ScriptNode::Use { .. } => {
                    let Some(package_ref) = value.as_ref().defs.iter().next() else {
                        continue;
                    };

                    let Some(ScriptNode::Package { semantics, .. }) = package_ref.deref(self.doc)
                    else {
                        continue;
                    };

                    let package_semantics = semantics.get().forward()?;

                    let (_, package_resolution) = package_semantics
                        .package_resolution
                        .snapshot(self.task)
                        .forward()?;

                    let Some(package) = package_resolution.package else {
                        continue;
                    };

                    let Some(component) = package.ty().prototype().hint_component(key.as_str())
                    else {
                        continue;
                    };

                    CompletionItem {
                        label: Ident::Rust(component.name),
                        desc: Description {
                            type_hint: component.ty,
                            impl_symbol: PackageSymbol::from_package_ref(package_ref),
                            doc: component.doc.or(component.ty.doc()),
                        },
                    }
                }

                ScriptNode::For { .. } | ScriptNode::FnParams { .. } => {
                    let Some(var_ref) = value.as_ref().defs.iter().next() else {
                        continue;
                    };

                    let Some(ScriptNode::Var {
                        token, semantics, ..
                    }) = var_ref.deref(self.doc)
                    else {
                        continue;
                    };

                    let var_semantics = semantics.get().forward()?;

                    let (_, var_type_resolution) = var_semantics
                        .type_resolution
                        .snapshot(self.task)
                        .forward()?;

                    let ty = var_type_resolution.tag.type_hint();

                    CompletionItem {
                        label: Ident::Script(ScriptIdent::from_string(*token, key.clone())),
                        desc: Description {
                            type_hint: ty,
                            impl_symbol: VarSymbol::from_var_ref(var_ref),
                            doc: ty.doc(),
                        },
                    }
                }

                ScriptNode::Let { name, .. } => {
                    let Some(ScriptNode::Var { token, .. }) = name.deref(self.doc) else {
                        continue;
                    };

                    let mut resolution = Tag::Unset;

                    for def_ref in &value.as_ref().defs {
                        let Some(def_node) = def_ref.deref(self.doc) else {
                            continue;
                        };

                        let (_, def_type_resolution) = def_node
                            .type_resolution()
                            .forward()?
                            .snapshot(self.task)
                            .forward()?;

                        resolution.merge(def_type_resolution.tag);
                    }

                    if let Tag::Unset = &resolution {
                        resolution = Tag::dynamic();
                    }

                    let ty = resolution.type_hint();

                    CompletionItem {
                        label: Ident::Script(ScriptIdent::from_string(*token, key.clone())),
                        desc: Description {
                            type_hint: ty,
                            impl_symbol: VarSymbol::from_var_ref(name),
                            doc: ty.doc(),
                        },
                    }
                }

                _ => continue,
            };

            let _ = accumulator.insert(key.clone(), item);
        }

        Ok(())
    }

    fn prompt_struct(&self, struct_ref: &NodeRef) -> AnalysisResult<Vec<CompletionItem>> {
        let mut result = Vec::new();

        let Some(ScriptNode::Struct { semantics, .. }) = struct_ref.deref(self.doc) else {
            return Ok(result);
        };

        let struct_semantics = semantics.get().forward()?;

        let (_, struct_entries_vec) = struct_semantics
            .struct_entries_vec_syntax
            .snapshot(self.task)
            .forward()?;

        let capacity = struct_entries_vec.as_ref().vec.len();

        let mut visited = AHashSet::with_capacity(capacity);

        result.reserve(capacity);

        for (key, key_ref, value_ref) in &struct_entries_vec.as_ref().vec {
            if visited.contains(key) {
                continue;
            }

            let Some(ScriptNode::StructEntryKey { token, .. }) = key_ref.deref(self.doc) else {
                continue;
            };

            let mut ty = TypeHint::dynamic();

            if let Some(value_node) = value_ref.deref(self.doc) {
                let (_, value_type_resolution) = value_node
                    .type_resolution()
                    .forward()?
                    .snapshot(self.task)
                    .forward()?;

                ty = value_type_resolution.tag.type_hint();
            }

            result.push(CompletionItem {
                label: Ident::Script(ScriptIdent::from_string(*token, key.clone())),
                desc: Description {
                    type_hint: ty,
                    impl_symbol: EntrySymbol::from_struct_entry_key_ref(key_ref),
                    doc: ty.doc(),
                },
            });

            let _ = visited.insert(key);
        }

        Ok(result)
    }

    fn prompt_type(&self, tag: &Tag) -> AnalysisResult<Vec<CompletionItem>> {
        let mut result = Vec::new();

        let Some(ty) = tag.type_meta() else {
            return Ok(result);
        };

        result.reserve(ty.prototype().components_len());

        for component in ty.prototype().hint_all_components() {
            result.push(CompletionItem {
                label: Ident::Rust(component.name),
                desc: Description::from_component(&component),
            });
        }

        Ok(result)
    }
}