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
////////////////////////////////////////////////////////////////////////////////
// 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 ;
use RandomState;
use ;
use crate::;
/// An in-memory representation of the Ad Astra script module.
///
/// This object owns the script's source code text, its syntax and semantics,
/// and is responsible for keeping this data in sync with source code edits,
/// ensuring the up-to-date semantics are available for query.
///
/// To execute the script's source code, you need to load it into the
/// ScriptModule object, compile it, and then run the compiled assembly.
///
/// ## Creation
///
/// To create a ScriptModule, you can load the source code text, for example,
/// from disk, and then pass it into the ScriptModule constructor:
/// [ScriptModule::new].
///
/// The constructor requires an additional parameter, which is a package
/// metadata object. The module will be analyzed under the Rust symbols exported
/// into this package object. For more details, see the
/// [ScriptPackage](crate::runtime::ScriptPackage) documentation.
///
/// ```rust
/// # use ad_astra::{
/// # analysis::ScriptModule, export, lady_deirdre::analysis::TriggerHandle,
/// # runtime::ScriptPackage,
/// # };
/// #
/// #[export(package)]
/// #[derive(Default)]
/// struct Package;
///
/// let _module = ScriptModule::<TriggerHandle>::new(
/// Package::meta(),
/// "let foo = 10;",
/// );
/// ```
///
/// ## Access
///
/// The ScriptModule is specifically designed for use in multi-threaded
/// environments. Although multi-threading is not a strict requirement, and
/// the ScriptModule can also be used in single-threaded applications, its
/// access API follows the read-write lock design pattern to address
/// concurrent access operations.
///
/// You access the ScriptModule's content using read and write access guards,
/// similar to [RwLock](std::sync::RwLock). The
/// [read](ScriptModule::read) and [write](ScriptModule::write) functions
/// provide read and write access guards, respectively. Both functions may block
/// if the ScriptModule is currently locked for the opposite type of access,
/// though non-blocking "try_" variants are available. Like RwLock, you can
/// have multiple read guards simultaneously, but at most one write guard.
///
/// ```rust
/// # use ad_astra::{
/// # analysis::{ModuleRead, ScriptModule},
/// # export,
/// # lady_deirdre::analysis::TriggerHandle,
/// # runtime::ScriptPackage,
/// # };
/// #
/// # #[export(package)]
/// # #[derive(Default)]
/// # struct Package;
/// #
/// // Module creation
/// let module = ScriptModule::new(Package::meta(), "let foo = 10;");
///
/// let handle = TriggerHandle::new();
/// let module_read = module.read(&handle, 1).unwrap(); // Acquiring read guard.
///
/// println!("{}", module_read.text()); // Prints module source code.
/// ```
///
/// ## Available Operations
///
/// The [ModuleReadGuard] object, created by the [read](ScriptModule::read)
/// function, implements the [ModuleRead](crate::analysis::ModuleRead) trait,
/// which provides the following operations:
///
/// - Reading the source code text via the
/// [text](crate::analysis::ModuleRead::text) function.
/// - Requesting source code diagnostics (errors and warnings) via the
/// [diagnostics](crate::analysis::ModuleRead::diagnostics) function.
/// - Querying for semantic metadata about specific syntax constructs within
/// specified source code ranges via the
/// [symbols](crate::analysis::ModuleRead::symbols) function.
/// - Compiling the module into Ad Astra assembly for execution via the
/// [compile](crate::analysis::ModuleRead::compile) function.
///
/// The [ModuleWriteGuard] object, created by the [write](ScriptModule::write)
/// function, represents exclusive access to the ScriptModule content. This
/// object implements both the ModuleRead and
/// [ModuleWrite](crate::analysis::ModuleWrite) traits. Through the ModuleRead
/// trait, you gain access to the operations listed above, and through the
/// ModuleWrite trait, you can perform content mutation operations:
///
/// - Editing the source code text within a specified range via the
/// [edit](crate::analysis::ModuleWrite::edit) function.
/// - Probing the source code for code-completion candidates via the
/// [completions](crate::analysis::ModuleWrite::completions) function. Even
/// though this function does not ultimately change the source code text, it
/// requires write access to probe the code through temporary mutation.
///
/// ## Multi-Threaded Design
///
/// A key difference from RwLock is that the ScriptModule's access
/// guards can be gracefully interrupted.
///
/// Both [read](ScriptModule::read) and [write](ScriptModule::write) access
/// functions (including their "try_" variants) require two additional
/// parameters: an access priority number and a handle object.
///
/// The handle object allows you to revoke previously granted read/write access
/// from another thread. The priority number indicates the priority of the task
/// you intend to perform with the access guard object.
///
/// For example, if several working threads are currently reading the
/// ScriptModule with one priority number, and another working thread
/// simultaneously attempts to acquire write access with a higher priority
/// number, the ScriptModule automatically revokes all read access grants to
/// prioritize the write access.
///
/// When the ScriptModule revokes an access grant, all guard access operations
/// will start yielding an
/// [Interrupted](crate::analysis::ModuleError::Interrupted) error. In this
/// case, the thread owning the guard should drop the guard object as soon as
/// possible to allow another working thread to proceed. The former thread can
/// later acquire a new access guard to continue its work.
///
/// ```rust
/// # use ad_astra::{
/// # analysis::{ModuleError, ModuleRead, ScriptModule},
/// # export,
/// # lady_deirdre::analysis::{TaskHandle, TriggerHandle},
/// # runtime::ScriptPackage,
/// # };
/// #
/// # #[export(package)]
/// # #[derive(Default)]
/// # struct Package;
/// #
/// let module = ScriptModule::new(Package::meta(), "let foo = 10;");
///
/// let handle = TriggerHandle::new();
/// let module_read = module.read(&handle, 1).unwrap(); // Acquiring read access.
///
/// // Revoking access manually.
/// // In a multi-threaded environment, you can clone and move this `handle`
/// // object into another working thread and trigger it there instead.
/// handle.trigger();
///
/// // Since the read access has been revoked, the diagnostics request function
/// // returns an Interrupted error.
/// assert!(matches!(
/// module_read.diagnostics(2),
/// Err(ModuleError::Interrupted(_)),
/// ));
/// ```
///
/// Although Ad Astra does not have a built-in worker manager and does not spawn
/// any threads, the above mechanism helps you organize highly concurrent
/// multi-threaded analysis tools with task priorities.
///
/// Note that analysis read operations (such as
/// [diagnostics](crate::analysis::ModuleRead::diagnostics) or
/// [symbols](crate::analysis::ModuleRead::symbols)) typically don't block each
/// other when requested from independent threads. Ad Astra's semantic analyzer
/// can infer module semantics concurrently.
///
/// ## Incremental Analysis
///
/// When you [edit](crate::analysis::ModuleWrite::edit) the source code of the
/// ScriptModule, the underlying algorithm does not reparse the entire module's
/// syntax. Instead, it typically reparses only a small fragment that includes
/// the edited text and updates the existing in-memory data structures. This
/// technique, known as incremental reparsing, allows for quick updates to
/// script modules with every keystroke, even when the source code text is
/// large.
///
/// Additionally, semantic analysis is demand-driven. The ScriptModule does not
/// compute the script's semantics until specific semantic facts are queried.
/// When these facts are queried, the underlying algorithm attempts to compute
/// (or update previously computed) the smallest subset of the inner semantic
/// representation required to fulfill the request. Thus, semantic analysis
/// is also incremental and usually localized to the specific query.
///
/// ## Identification
///
/// Each instance of the ScriptModule has a globally unique associated
/// identifier ([Id]). This Id object is Copy, Eq, Ord, and Hash, and is unique
/// per ScriptModule instance within the current process.
///
/// Most API objects related to script modules also expose their script module
/// ids. These identifiers can be retrieved using the [Identifiable::id]
/// function and compared for equality.
///
/// Additionally, in multi-script projects, you can use the identifier as a key
/// type in a hash map to store multiple ScriptModule instances within a single
/// hash map.
///
/// ## Naming
///
/// The API allows you to assign a potentially non-unique string name to a
/// ScriptModule instance using the [ScriptModule::rename] function. For
/// example, if you load a script from disk, you might consider assigning
/// the file name to the ScriptModule object as a module name.
///
/// API functions that print a module's content to the terminal will use the
/// assigned name of the ScriptModule as a content header, which helps
/// simplify script identification.