aft-parse 0.67.1

Syntax parsing, imports and call resolution for Agent Foundational Toolkit
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
//! Hash-pinned, rebuildable grammar artifacts. Parsers may load stored grammars;
//! only an explicit command-level request is allowed to start a download.
use super::{
    download, extractors, manifests, storage, FailureCause, GrammarManifest, GrammarState,
    GrammarUnavailable,
};

use std::sync::LazyLock;
use std::sync::{Arc, OnceLock};
use std::time::Instant;

use parking_lot::{Condvar, Mutex, RwLock};
use tree_sitter::Language;

test_support_visibility! {
static ENGINE: LazyLock<Result<tree_sitter::wasmtime::Engine, String>> = LazyLock::new(|| {
    let mut config = tree_sitter::wasmtime::Config::new();
    config.parallel_compilation(false);
    // Cranelift translates source Wasm to Pulley bytecode only. A grammar must
    // never fall back to native code, including when this target is unavailable.
    config
        .target("pulley64")
        .map_err(|e| format!("Pulley target unavailable: {e}"))?;
    let engine = tree_sitter::wasmtime::Engine::new(&config)
        .map_err(|e| format!("Pulley engine unavailable: {e}"))?;
    if !engine.is_pulley() {
        return Err("grammar engine refused a non-Pulley target".into());
    }
    Ok(engine)
});
}

/// Report the target family from Wasmtime's actual engine, not the requested
/// configuration. Wasmtime's public query distinguishes Pulley from native.
pub fn engine_target(language: &str) -> Result<&'static str, GrammarUnavailable> {
    let engine = ENGINE.as_ref().map_err(|error| engine_failure(language, error))?;
    Ok(if engine.is_pulley() {
        "pulley"
    } else {
        "native"
    })
}

test_support_visibility! {
fn engine_failure(language: &str, error: &str) -> GrammarUnavailable {
    log::warn!("Pulley grammar engine unavailable: {error}");
    GrammarUnavailable::new(language, GrammarState::UnsupportedPlatform)
}
}

pub trait Clock: Send + Sync {
    fn now_ms(&self) -> u64;
}

struct MonotonicClock(Instant);
impl Clock for MonotonicClock {
    fn now_ms(&self) -> u64 {
        self.0.elapsed().as_millis().min(u64::MAX as u128) as u64
    }
}

test_support_visibility! {
struct Entry {
    #[cfg(feature = "test-hooks")]
    attempts_started: usize,
    #[cfg(any(test, feature = "test-support"))]
    pub root_generation: u64,
    #[cfg(not(any(test, feature = "test-support")))]
    root_generation: u64,
    loading: bool,
    language: Option<Language>,
    #[cfg(any(test, feature = "test-support"))]
    pub state: GrammarState,
    #[cfg(not(any(test, feature = "test-support")))]
    state: GrammarState,
    #[cfg(any(test, feature = "test-support"))]
    pub failures: u8,
    #[cfg(not(any(test, feature = "test-support")))]
    failures: u8,
    #[cfg(any(test, feature = "test-support"))]
    pub cause: Option<FailureCause>,
    #[cfg(not(any(test, feature = "test-support")))]
    cause: Option<FailureCause>,
    #[cfg(any(test, feature = "test-support"))]
    pub retry_at: u64,
    #[cfg(not(any(test, feature = "test-support")))]
    retry_at: u64,
    compiles: usize,
    compile_ms: f64,
}
}

impl Default for Entry {
    fn default() -> Self {
        Self {
            #[cfg(feature = "test-hooks")]
            attempts_started: 0,
            root_generation: 0,
            loading: false,
            language: None,
            state: GrammarState::NotDownloaded,
            failures: 0,
            cause: None,
            retry_at: 0,
            compiles: 0,
            compile_ms: 0.0,
        }
    }
}

struct Loaded {
    language: Result<Language, GrammarState>,
    compiles: usize,
    milliseconds: f64,
}

pub struct GrammarRegistry {
    manifest: GrammarManifest,
    #[cfg(any(test, feature = "test-support"))]
    pub storage_root: RwLock<Option<std::path::PathBuf>>,
    #[cfg(not(any(test, feature = "test-support")))]
    storage_root: RwLock<Option<std::path::PathBuf>>,
    #[cfg(any(test, feature = "test-support"))]
    pub entry: Mutex<Entry>,
    #[cfg(not(any(test, feature = "test-support")))]
    entry: Mutex<Entry>,
    changed: Condvar,
    clock: Arc<dyn Clock>,
    transport: OnceLock<Result<Arc<dyn download::Transport>, String>>,
    queries: Vec<String>,
    fault: RwLock<storage::StorageFault>,
    #[cfg(any(test, feature = "test-support"))]
    pub listeners: Mutex<std::collections::BTreeMap<u64, std::sync::mpsc::Sender<String>>>,
    #[cfg(not(any(test, feature = "test-support")))]
    listeners: Mutex<std::collections::BTreeMap<u64, std::sync::mpsc::Sender<String>>>,
    next_listener: std::sync::atomic::AtomicU64,
    #[cfg(any(test, feature = "test-support"))]
    forced_unavailable: Mutex<Option<GrammarUnavailable>>,
    #[cfg(any(any(test, feature = "test-support"), feature = "test-hooks"))]
    pub load_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
}

/// A readiness receiver whose registration ends with the receiver's lifetime.
pub struct ReadinessSubscription {
    receiver: std::sync::mpsc::Receiver<String>,
    _registration: ReadinessRegistration,
}

impl std::ops::Deref for ReadinessSubscription {
    type Target = std::sync::mpsc::Receiver<String>;
    fn deref(&self) -> &Self::Target {
        &self.receiver
    }
}

pub struct ReadinessRegistration {
    registry: std::sync::Weak<GrammarRegistry>,
    id: u64,
}

impl Drop for ReadinessRegistration {
    fn drop(&mut self) {
        if let Some(registry) = self.registry.upgrade() {
            registry.listeners.lock().remove(&self.id);
        }
    }
}

static REGISTRIES: LazyLock<super::RegistryMap<GrammarRegistry>> =
    LazyLock::new(|| super::registry_map(manifests(), |entry| GrammarRegistry::new(entry, None)));

/// Set the artifact location from the handling context, without reading or
/// compiling a grammar. Call only when the caller opts into dynamic parsing;
/// callers using built-in grammars only must not consult grammar storage.
pub fn configure(config: &crate::config::Config) {
    let root = crate::cache_location::cache_root(config);
    for registry in REGISTRIES.values() {
        registry.set_storage_root(root.clone());
    }
}

pub fn registry(language: &str) -> Option<&'static Arc<GrammarRegistry>> {
    REGISTRIES.get(language)
}

impl GrammarRegistry {
    test_support_visibility! {
fn new(manifest: &GrammarManifest, root: Option<std::path::PathBuf>) -> Arc<Self> {
        #[cfg(feature = "test-hooks")]
        let root = std::env::var_os("AFT_TEST_GRAMMAR_STORAGE")
            .map(std::path::PathBuf::from)
            .map(Some)
            .unwrap_or(root);
        let registry = Arc::new(Self {
            manifest: manifest.clone(),
            storage_root: RwLock::new(root),
            entry: Mutex::new(Entry::default()),
            changed: Condvar::new(),
            clock: Arc::new(MonotonicClock(Instant::now())),
            transport: OnceLock::new(),
            queries: extractors::queries(&manifest.language).iter().map(|query| (*query).into()).collect(),
            fault: RwLock::new(storage::StorageFault::None),
            listeners: Mutex::new(std::collections::BTreeMap::new()),
            next_listener: std::sync::atomic::AtomicU64::new(0),
            #[cfg(any(test, feature = "test-support"))]
            forced_unavailable: Mutex::new(None),
            #[cfg(any(any(test, feature = "test-support"), feature = "test-hooks"))]
            load_hook: Mutex::new(None),
        });
        #[cfg(feature = "test-hooks")]
        return test_seams::from_environment(registry);
        #[cfg(not(feature = "test-hooks"))]
        registry
    }
}

    pub fn identity(&self) -> &str {
        &self.manifest.sha256
    }

    pub fn compile_ms(&self) -> f64 {
        self.entry.lock().compile_ms
    }

    /// Observe availability without opening storage, compiling or requesting.
    pub fn status_snapshot(&self) -> Option<GrammarUnavailable> {
        #[cfg(any(test, feature = "test-support"))]
        if let Some(error) = self.forced_unavailable.lock().clone() {
            return Some(error);
        }
        let entry = self.entry.lock();
        entry.language.is_none().then(|| self.unavailable(&entry))
    }

    /// Whether a background driver can start an attempt on the current clock.
    pub fn retry_due(&self) -> bool {
        let entry = self.entry.lock();
        entry.language.is_none()
            && !entry.loading
            && (entry.state == GrammarState::NotDownloaded
                || matches!(
                    entry.state,
                    GrammarState::NetworkRetry | GrammarState::StorageRetry
                ) && self.clock.now_ms() >= entry.retry_at)
    }

    test_support_visibility! {
fn set_storage_root(&self, root: std::path::PathBuf) {
        let mut entry = self.entry.lock();
        let mut current = self.storage_root.write();
        if current.as_ref() != Some(&root) {
            *current = Some(root);
            let generation = entry.root_generation.wrapping_add(1);
            // Every root uses the same manifest hash, so a compiled language
            // remains in memory. Only root-specific attempts and failures reset.
            *entry = Entry {
                root_generation: generation,
                loading: entry.loading,
                language: entry.language.take(),
                compiles: entry.compiles,
                compile_ms: entry.compile_ms,
                ..Entry::default()
            };
            self.changed.notify_all();
        }
    }
}

    test_support_visibility! {
fn storage(&self) -> Option<storage::Storage> {
        self.storage_root
            .read()
            .clone()
            .map(|root| storage::Storage {
                root,
                fault: *self.fault.read(),
            })
    }
}

    test_support_visibility! {
fn unavailable(&self, entry: &Entry) -> GrammarUnavailable {
        let state = if entry.loading {
            GrammarState::Downloading
        } else {
            entry.state
        };
        let mut result = GrammarUnavailable::new(&self.manifest.language, state);
        if state == GrammarState::AttemptsExhausted {
            result.cause = entry.cause;
        }
        if matches!(
            state,
            GrammarState::NetworkRetry | GrammarState::StorageRetry
        ) {
            result.retry_after_ms = Some(entry.retry_at.saturating_sub(self.clock.now_ms()));
        }
        result
    }
}

    /// Verify and compile a stored grammar without holding the state mutex.
    /// Waiters release that mutex and have a finite wait; command-level request
    /// calls report an in-progress load immediately instead of waiting for it.
    pub fn stored(&self) -> Result<Language, GrammarUnavailable> {
        #[cfg(any(test, feature = "test-support"))]
        if let Some(error) = self.forced_unavailable.lock().clone() {
            return Err(error);
        }
        let mut entry = self.entry.lock();
        let wait_until = Instant::now() + std::time::Duration::from_secs(30);
        while entry.loading {
            let remaining = wait_until.saturating_duration_since(Instant::now());
            if remaining.is_zero() {
                return Err(self.unavailable(&entry));
            }
            self.changed.wait_for(&mut entry, remaining);
        }
        if let Some(language) = &entry.language {
            return Ok(language.clone());
        }
        if matches!(
            entry.state,
            GrammarState::LoadFailed
                | GrammarState::UnsupportedPlatform
                | GrammarState::Downloading
        ) {
            return Err(self.unavailable(&entry));
        }
        let Some(storage) = self.storage() else {
            return Err(self.unavailable(&entry));
        };
        let generation = entry.root_generation;
        entry.loading = true;
        drop(entry);
        let read = storage.read(&self.manifest);
        let loaded = match &read {
            Ok(Some(bytes)) => Some(self.compile_language(bytes)),
            _ => None,
        };
        let mut entry = self.entry.lock();
        entry.loading = false;
        if let Some(loaded) = loaded {
            self.publish_load(&mut entry, loaded);
        } else if read.is_err() && entry.root_generation == generation {
            let cooling_down =
                entry.state == GrammarState::StorageRetry && self.clock.now_ms() < entry.retry_at;
            if !cooling_down && entry.state != GrammarState::AttemptsExhausted {
                self.failed_attempt(&mut entry, FailureCause::Storage);
            }
        }
        self.changed.notify_all();
        entry
            .language
            .clone()
            .ok_or_else(|| self.unavailable(&entry))
    }

    /// Called by dynamic command preparation and checkout maintenance. Stored
    /// bytes win over a download, including the first request after a restart.
    pub fn request(self: &Arc<Self>) -> Result<Language, GrammarUnavailable> {
        #[cfg(any(test, feature = "test-support"))]
        if let Some(error) = self.forced_unavailable.lock().clone() {
            return Err(error);
        }
        {
            let entry = self.entry.lock();
            if entry.loading {
                return Err(self.unavailable(&entry));
            }
        }
        if let Ok(language) = self.stored() {
            return Ok(language);
        }
        let mut entry = self.entry.lock();
        if let Some(language) = &entry.language {
            return Ok(language.clone());
        }
        let Some(storage) = self.storage() else {
            return Err(self.unavailable(&entry));
        };
        let retry = matches!(
            entry.state,
            GrammarState::NetworkRetry | GrammarState::StorageRetry
        ) && self.clock.now_ms() >= entry.retry_at;
        if entry.state == GrammarState::NotDownloaded || retry {
            #[cfg(feature = "test-hooks")]
            {
                entry.attempts_started += 1;
            }
            entry.state = GrammarState::Downloading;
            let generation = entry.root_generation;
            let registry = Arc::clone(self);
            if std::thread::Builder::new()
                .name("aft-grammar-download".into())
                .spawn(move || registry.download(storage, generation))
                .is_err()
            {
                self.failed_attempt(&mut entry, FailureCause::Network);
                self.changed.notify_all();
            }
        }
        Err(self.unavailable(&entry))
    }

    fn failed_attempt(&self, entry: &mut Entry, cause: FailureCause) {
        entry.failures += 1;
        entry.cause = Some(cause);
        if entry.failures >= 5 {
            entry.state = GrammarState::AttemptsExhausted;
        } else {
            entry.state = match cause {
                FailureCause::Network => GrammarState::NetworkRetry,
                FailureCause::Storage => GrammarState::StorageRetry,
            };
            entry.retry_at = self
                .clock
                .now_ms()
                .saturating_add(30_000u64 << (entry.failures - 1));
        }
    }

    test_support_visibility! {
fn download(&self, storage: storage::Storage, generation: u64) {
        let transport = self.transport.get_or_init(|| {
            download::HttpsTransport::new()
                .map(|transport| Arc::new(transport) as Arc<dyn download::Transport>)
        });
        let fetched = match transport {
            Ok(transport) => download::fetch(&self.manifest, transport.as_ref()),
            Err(_) => Err(download::DownloadFailure::Network),
        };
        let (failure, stored) = match fetched {
            Ok(bytes) => (None, Some(storage.publish(&self.manifest, &bytes))),
            Err(error) => (Some(error), None),
        };
        let mut entry = self.entry.lock();
        if entry.root_generation != generation {
            self.changed.notify_all();
            return;
        }
        match (failure, stored) {
            (Some(download::DownloadFailure::Network), _) => {
                self.failed_attempt(&mut entry, FailureCause::Network)
            }
            (Some(download::DownloadFailure::Verification), _) => {
                entry.state = GrammarState::VerificationFailed
            }
            (_, Some(Err(error))) => {
                log::warn!(
                    "grammar storage unavailable at {}: {error}",
                    storage.folder().display()
                );
                self.failed_attempt(&mut entry, FailureCause::Storage);
            }
            (_, Some(Ok(bytes))) => {
                if entry.language.is_none() {
                    entry.loading = true;
                    drop(entry);
                    let loaded = self.compile_language(&bytes);
                    entry = self.entry.lock();
                    entry.loading = false;
                    self.publish_load(&mut entry, loaded);
                }
            }
            _ => entry.state = GrammarState::LoadFailed,
        }
        self.changed.notify_all();
    }
}

    fn compile_language(&self, bytes: &[u8]) -> Loaded {
        #[cfg(any(any(test, feature = "test-support"), feature = "test-hooks"))]
        if let Some(hook) = self.load_hook.lock().take() {
            hook();
        }
        let engine = match ENGINE.as_ref() {
            Ok(engine) => engine,
            Err(error) => {
                return Loaded {
                    language: Err(engine_failure(&self.manifest.language, error).state),
                    compiles: 0,
                    milliseconds: 0.0,
                }
            }
        };
        let mut compiles = 0;
        let mut milliseconds = 0.0;
        let result = (|| {
            let mut store =
                tree_sitter::WasmStore::new(engine).map_err(|error| error.to_string())?;
            compiles = 1;
            let start = Instant::now();
            let language = store.load_language(&self.manifest.language, bytes);
            milliseconds = start.elapsed().as_secs_f64() * 1000.0;
            let language = language.map_err(|error| error.to_string())?;
            if language.abi_version() != self.manifest.abi {
                return Err("grammar ABI differs from manifest".into());
            }
            for query in &self.queries {
                tree_sitter::Query::new(&language, query).map_err(|error| error.to_string())?;
            }
            Ok::<_, String>(language)
        })();
        let language = result.map_err(|error| {
            log::warn!("{} grammar load failed: {error}", self.manifest.language);
            GrammarState::LoadFailed
        });
        Loaded {
            language,
            compiles,
            milliseconds,
        }
    }

    fn publish_load(&self, entry: &mut Entry, loaded: Loaded) {
        entry.compiles += loaded.compiles;
        entry.compile_ms = loaded.milliseconds;
        match loaded.language {
            Ok(language) => {
                entry.language = Some(language);
                self.listeners
                    .lock()
                    .retain(|_, listener| listener.send(self.identity().into()).is_ok());
            }
            Err(state) => entry.state = state,
        }
    }

    /// Subscribe before the grammar is loaded; a ready grammar immediately emits its hash.
    pub fn subscribe(self: &Arc<Self>) -> ReadinessSubscription {
        let (tx, rx) = std::sync::mpsc::channel();
        ReadinessSubscription {
            receiver: rx,
            _registration: self.subscribe_to(tx),
        }
    }

    /// Register a shared receiver for maintenance that watches several grammars.
    pub fn subscribe_to(self: &Arc<Self>, tx: std::sync::mpsc::Sender<String>) -> ReadinessRegistration {
        let entry = self.entry.lock();
        if entry.language.is_some() {
            let _ = tx.send(self.identity().into());
        }
        let id = self
            .next_listener
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        self.listeners.lock().insert(id, tx);
        ReadinessRegistration {
            registry: Arc::downgrade(self),
            id,
        }
    }
}

pub fn prepare_parser(parser: &mut tree_sitter::Parser, language: &str) -> Result<(), GrammarUnavailable> {
    {
        let engine = ENGINE.as_ref().map_err(|error| engine_failure(language, error))?;
        let store = tree_sitter::WasmStore::new(engine).map_err(|error| {
            log::warn!("grammar parser store failed: {error}");
            GrammarUnavailable::new(language, GrammarState::LoadFailed)
        })?;
        parser.set_wasm_store(store).map_err(|error| {
            log::warn!("grammar parser store assignment failed: {error}");
            GrammarUnavailable::new(language, GrammarState::LoadFailed)
        })?;
        Ok(())
    }
}

#[cfg(any(any(test, feature = "test-support"), feature = "test-hooks"))]
#[path = "test_seams.rs"]
pub mod test_seams;