raf-source 0.0.0

Workspace source index: a Tree file seam with disk and memory backends under canonical path containment.
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
// SPDX-FileCopyrightText: 2026 Blackcat InformaticsĀ® Inc. <paudley@blackcatinformatics.ca>
// SPDX-License-Identifier: MIT OR Apache-2.0 OR MulanPSL-2.0

//! Bounded parsing: a pre-scan, then `syn` on a dedicated thread.

use std::panic;
use std::thread;

use crate::budget::Budget;
use crate::error::{LoadError, LoadErrorKind};
use crate::meter::{ConfigurationUsage, FactAllowance, Meter, NativeAdmission, Usage};
use crate::path::RelPath;
use crate::prescan::{Scan, prescan_file, shebang};
use crate::{ActiveConfiguration, LoadOptions, TreeError};

mod entry;
#[cfg(target_os = "linux")]
pub(crate) mod parallel;

/// The only worker output retained by the canonical walk.
pub(crate) struct Extracted {
    pub(crate) text: String,
    pub(crate) head: ExtractedHead,
    pub(crate) scan: Scan,
}

pub(crate) struct ExtractedHead {
    pub(crate) facts: Result<(crate::facts::FileFacts, usize), ExtractionError>,
    pub(crate) configuration_usage: Option<ConfigurationUsage>,
}

pub(crate) enum ExtractionError {
    Configuration(LoadError),
    Facts(crate::facts::ExtractError),
}

/// Admit declaration selection and facts only after the canonical walk grants
/// the current file's budget. Diagnostic paths belong to that same reach.
pub(crate) fn extract_head(
    tree: &mut syn::File,
    path: &RelPath,
    text: &str,
    allowance: FactAllowance,
    configuration: Option<(&ActiveConfiguration, &LoadOptions, Usage)>,
) -> ExtractedHead {
    let Some((configuration, options, usage)) = configuration else {
        return ExtractedHead {
            facts: crate::facts::extract(tree, text, allowance).map_err(ExtractionError::Facts),
            configuration_usage: None,
        };
    };
    let local = Meter::resume(options, usage);
    let facts = crate::configuration::filter(tree, configuration, &local, path)
        .map_err(ExtractionError::Configuration)
        .and_then(|()| {
            crate::facts::extract(tree, text, allowance).map_err(ExtractionError::Facts)
        });
    ExtractedHead {
        facts,
        configuration_usage: Some(local.configuration_usage()),
    }
}

/// A native storage refusal located at `file`.
pub(crate) fn storage(file: &RelPath, source: purrdf_lex::allocation::StorageError) -> LoadError {
    LoadError::new(file, None, LoadErrorKind::Storage(source))
}

/// Borrowed candidate spelling; materialization belongs to the admitted executor.
#[derive(Clone, Copy)]
pub(crate) enum Candidate<'a> {
    Existing(&'a RelPath),
    Joined {
        base: &'a RelPath,
        stem: Option<&'a str>,
        input: &'a str,
        suffix: &'a str,
    },
}

#[cfg(target_os = "linux")]
#[derive(Clone, Copy)]
pub(crate) struct ConfigurationOrdinal(pub(crate) usize);

/// A configuration admitted during canonical target selection.
#[cfg(target_os = "linux")]
#[derive(Clone, Copy)]
pub(crate) enum ConfigurationKey {
    Selected,
    Locked(crate::PackageId, ConfigurationOrdinal),
}

/// The canonical reach's allowances and optional extraction context.
#[cfg(target_os = "linux")]
pub(crate) struct ExtractionGrant {
    pub(crate) allowance: FactAllowance,
    pub(crate) usage: Usage,
    pub(crate) configuration: Option<ConfigurationKey>,
}

/// A coordinator-only parse executor, with no shared Tree or meter.
pub(crate) trait Parser {
    /// Whether another speculative candidate can be inspected now.
    fn has_capacity(&self) -> bool;
    fn resize_frontier(
        &self,
        previous: usize,
        next: usize,
    ) -> Result<(), purrdf_lex::allocation::StorageError>;
    /// False leaves this candidate for a future frontier advance.
    fn speculate(
        &self,
        tree: &dyn crate::Tree,
        candidate: Candidate<'_>,
        options: &LoadOptions,
        seen: &dyn Fn(&crate::FileId) -> bool,
    ) -> bool;
    #[cfg(target_os = "linux")]
    fn parse(
        &self,
        path: &RelPath,
        id: &crate::FileId,
        text: String,
        options: &LoadOptions,
        grant: ExtractionGrant,
    ) -> Result<Extracted, LoadError>;
}

/// The stack of the thread that parses, in bytes: 64 MiB.
///
/// The caller's stack is not used, so a deep file costs this thread and not
/// the thread of a test or of a tool.
pub const PARSE_STACK_BYTES: usize = 64 * 1024 * 1024;

/// An immutable source admitted by the caller-thread guard scan.
///
/// Private fields bind the handle to its borrowed path and text. Reading counts
/// starts no worker or native lexer. Its consuming parse methods use that
/// same text without repeating the guard scan. Admission is not syntax
/// validation and does not establish a complete native heap or work bound.
#[derive(Debug)]
pub struct PreparedSource<'source> {
    file: &'source RelPath,
    text: &'source str,
    scan: Scan,
    native_bound: usize,
}

/// Guarded source lexed on its existing scoped worker, before syntax parsing.
///
/// Private fields bind the path, ignored header and original native tokens.
/// The ticket is available only inside [`PreparedSource::with_lexed`]. Its
/// consuming parse methods use that same stream on the current worker; they
/// perform no additional guard scan, lex or worker startup.
#[derive(Debug)]
pub struct LexedSource<'source> {
    file: &'source RelPath,
    original: proc_macro2::TokenStream,
    header: Option<String>,
}

impl<'source> LexedSource<'source> {
    fn new(file: &'source RelPath, text: &str) -> Result<Self, LoadError> {
        let (original, header) = lex_source(file, text)?;
        Ok(Self {
            file,
            original,
            header,
        })
    }

    /// Borrow the original tokens before the native syntax parser starts.
    ///
    /// Cloning or iterating native tokens can allocate. Callers must admit
    /// measurement itself before using this view to admit later parser work.
    #[must_use]
    pub const fn tokens(&self) -> &proc_macro2::TokenStream {
        &self.original
    }

    /// Parse the ticket's stream and lend the syntax on the current worker.
    ///
    /// # Errors
    /// Returns located native syntax errors before the visitor runs.
    ///
    /// # Panics
    /// Parser and visitor panics unwind this worker; the enclosing prepared
    /// operation resumes their original payload on its caller after joining.
    pub fn parse<R>(self, visit: impl FnOnce(&syn::File) -> R) -> Result<R, LoadError> {
        self.parse_mut(|tree| visit(tree))
    }

    /// Parse once and lend the syntax with its original native tokens.
    ///
    /// # Errors
    /// Returns located native syntax errors before the visitor runs.
    ///
    /// # Panics
    /// Parser and visitor panics follow the enclosing worker's joined path.
    pub fn parse_with_tokens<R>(
        self,
        visit: impl FnOnce(&syn::File, proc_macro2::TokenStream) -> R,
    ) -> Result<R, LoadError> {
        let Self {
            file,
            original,
            header,
        } = self;
        let tree = syntax(file, original.clone(), header)?;
        Ok(visit(&tree, original))
    }

    fn into_syntax(self) -> Result<syn::File, LoadError> {
        syntax(self.file, self.original, self.header)
    }

    fn parse_mut<R>(self, visit: impl FnOnce(&mut syn::File) -> R) -> Result<R, LoadError> {
        self.into_syntax().map(|mut tree| visit(&mut tree))
    }
}

/// Check the default file-token and recursion guards without starting a worker.
///
/// The returned handle binds the counts and subsequent parsing to immutable
/// borrowed input. It performs no filesystem access or source mutation.
///
/// # Errors
/// Returns the located guard refusal, or storage-size overflow when the native
/// token ceiling cannot be represented. Syntax is checked only when parsing.
pub fn prepare_source<'source>(
    file: &'source RelPath,
    text: &'source str,
) -> Result<PreparedSource<'source>, LoadError> {
    PreparedSource::new(file, text, Budget::FileTokens.limit())
}

impl<'source> PreparedSource<'source> {
    fn new(
        file: &'source RelPath,
        text: &'source str,
        max_tokens: usize,
    ) -> Result<Self, LoadError> {
        let scan = prescan_file(file, text, max_tokens)?;
        let native_bound = scan
            .tokens
            .checked_mul(3)
            .and_then(|tokens| text.len().checked_mul(2).map(|bytes| tokens.min(bytes)))
            .ok_or_else(|| {
                LoadError::new(
                    file,
                    None,
                    LoadErrorKind::Storage(purrdf_lex::allocation::StorageError::SizeOverflow),
                )
            })?;
        Ok(Self {
            file,
            text,
            scan,
            native_bound,
        })
    }

    /// Units compared against the guard's file-token limit.
    ///
    /// Numeric guard runs can fuse native leaves; this is not a native-node count.
    #[must_use]
    pub const fn token_count(&self) -> usize {
        self.scan.tokens
    }

    /// The highest additive recursion counter reached by the guard scan.
    #[must_use]
    pub const fn recursion(&self) -> usize {
        self.scan.recursion
    }

    /// Upper bound on complete native token-tree nodes if lexing succeeds.
    ///
    /// At most three native nodes arise per guard unit; source bytes separately
    /// bound documentation lowering at twice their length. This is the smaller
    /// checked bound and does not bound native AST storage or parser work.
    #[must_use]
    pub const fn native_token_bound(&self) -> usize {
        self.native_bound
    }

    /// Lex on one scoped worker and lend a ticket before syntax parsing starts.
    ///
    /// The callback may admit parser resources from the actual token stream,
    /// then consume the ticket. Measurement needs its own prior admission.
    /// Lexing alone does not claim valid syntax or compiler acceptance. The
    /// callback's typed result is retained unchanged; only its `Send` value
    /// leaves the joined worker. No source code or Git state is changed.
    ///
    /// # Errors
    /// Returns located native lexing, storage or worker-start errors. Syntax
    /// errors are returned by the ticket's consuming parse methods.
    ///
    /// # Panics
    /// Resumes parser or callback panics after joining, with the original payload.
    pub fn with_lexed<R: Send>(
        self,
        visit: impl FnOnce(LexedSource<'source>) -> R + Send,
    ) -> Result<R, LoadError> {
        let Self { file, text, .. } = self;
        on_worker(file, move || LexedSource::new(file, text).map(visit))
    }

    /// Parse the admitted text on its scoped worker, then join it.
    ///
    /// # Errors
    /// Returns the native storage, syntax or worker-start errors of [`parse_source`].
    ///
    /// # Panics
    /// Resumes parser or visitor panics on the caller with the original payload.
    pub fn parse<R: Send>(
        self,
        visit: impl FnOnce(&syn::File) -> R + Send,
    ) -> Result<R, LoadError> {
        self.with_lexed(|lexed| lexed.parse(visit))?
    }

    /// Parse once and lend the original native tokens to the worker visitor.
    ///
    /// # Errors
    /// Returns the native errors of [`parse_source_with_tokens`], without rescanning.
    ///
    /// # Panics
    /// Resumes parser or visitor panics on the caller with the original payload.
    pub fn parse_with_tokens<R: Send>(
        self,
        visit: impl FnOnce(&syn::File, proc_macro2::TokenStream) -> R + Send,
    ) -> Result<R, LoadError> {
        self.with_lexed(|lexed| lexed.parse_with_tokens(visit))?
    }

    fn parse_mut<R: Send>(
        self,
        visit: impl FnOnce(&mut syn::File) -> R + Send,
    ) -> Result<R, LoadError> {
        self.with_lexed(|lexed| lexed.parse_mut(visit))?
    }
}

/// Parse `text` as a Rust file and run `visit` on the syntax tree.
///
/// The recursion budgets and the token budget, at its default limit
/// ([`Budget::FileTokens`](crate::Budget::FileTokens)), are checked on the
/// caller's thread first. The parse
/// and `visit` then run on a scoped thread named after `file`, with a stack of
/// [`PARSE_STACK_BYTES`]; a stack overflow in the runtime names that thread.
/// A panic in `visit` or in the parser is raised again on the caller's thread.
///
/// The tree is dropped when `visit` returns, so `visit` copies out what the
/// caller keeps.
///
/// # Errors
///
/// Returns a [`LoadError`] naming `file` when the text exceeds a budget
/// ([`LoadErrorKind::Budget`]), is not valid Rust ([`LoadErrorKind::Syntax`])
/// or the thread cannot start ([`LoadErrorKind::Spawn`]).
///
/// # Panics
///
/// Panics only when `visit` or the parser panics, with the original payload.
pub fn parse_source<R: Send>(
    file: &RelPath,
    text: &str,
    visit: impl FnOnce(&syn::File) -> R + Send,
) -> Result<R, LoadError> {
    prepare_source(file, text)?.parse(visit)
}

/// Parse once and give the visitor the syntax and its original native tokens.
///
/// The same file token and recursion checks as [`parse_source`] run before the
/// worker starts. Both native values stay on that worker; only `Send` results
/// return. The AST is parsed from one shared stream clone; native parsing can
/// copy token payloads. The complete source is not lexed a second time, and
/// caller-thread spans are never invalidated.
///
/// Byte ranges index the original `text`, including after a leading BOM or
/// shebang. The BOM is handled by the native lexer. Language-ignored shebang
/// bytes are replaced with same-length whitespace solely for lexical input;
/// the original header is retained in `syn::File::shebang`. No file is edited
/// and the header is never executed. Native parser/token/TLS heap and visitor
/// allocations retain their separate resource contracts.
///
/// # Errors
/// Returns the located native budget, storage, syntax or worker-start refusal.
/// The visitor is never called after a failed admission, lex or parse.
///
/// # Panics
/// Resumes parser or visitor panics on the caller with their original payload.
pub fn parse_source_with_tokens<R: Send>(
    file: &RelPath,
    text: &str,
    visit: impl FnOnce(&syn::File, proc_macro2::TokenStream) -> R + Send,
) -> Result<R, LoadError> {
    prepare_source(file, text)?.parse_with_tokens(visit)
}

/// One explicitly selected source and its owned syntax tree.
///
/// The syntax and its spans stay on the worker that parsed them. A batch visitor
/// can move these records into its own analysis structures and return `Send`
/// report data through [`parse_sources`].
pub struct ParsedSource {
    /// The caller's source identity; no discovery or module selection is performed.
    pub path: RelPath,
    /// The original source text, moved from the input without copying.
    pub text: String,
    /// The syntax tree, owned by the visitor.
    pub syntax: syn::File,
}

/// Parse an explicit corpus once and give all its syntax trees to one visitor.
///
/// Input order and identities are preserved, including repeated identities.
/// Before parsing any file, the complete input is checked against
/// `options.max_file_bytes`, `options.max_total_bytes`, `options.max_file_tokens`
/// and the native recursion budgets. The result-vector allocation is charged to
/// `options.max_item_bytes`. This bounds source input and corpus-container storage;
/// it does not meter the aggregate heap of retained `syn` trees or allocations
/// made by `visit`. Each file retains the parser's per-file resource bounds.
///
/// Parsing, visiting and dropping the trees run on one scoped worker with
/// [`PARSE_STACK_BYTES`]. The visitor runs exactly once, after every file parses,
/// including for an empty corpus. Only its `Send` result leaves the worker.
/// A visitor returning a `Result` retains its own typed error in that result.
/// No filesystem, Cargo, target selection or duplicate policy is involved.
///
/// # Errors
///
/// Returns the native [`LoadError`] naming the input that exceeded a limit or
/// failed to parse. Worker startup and corpus-vector allocation failures are
/// also errors. No failed corpus reaches the visitor as a partial success.
///
/// # Panics
///
/// A parser or visitor panic resumes on the caller with its original payload.
pub fn parse_sources<R: Send>(
    inputs: Vec<(RelPath, String)>,
    options: &LoadOptions,
    visit: impl FnOnce(Vec<ParsedSource>) -> R + Send,
) -> Result<R, LoadError> {
    let meter = Meter::new(options);
    for (file, text) in &inputs {
        if text.len() as u64 > options.max_file_bytes {
            return Err(LoadError::new(
                file,
                None,
                LoadErrorKind::Tree(Box::new(TreeError::TooLarge {
                    path: file.to_string(),
                    limit: options.max_file_bytes,
                })),
            ));
        }
        meter.read(file, text)?;
        prescan_file(file, text, options.max_file_tokens)?;
    }
    let file = inputs
        .first()
        .map_or_else(RelPath::root, |(file, _)| file.clone());
    let worker_name = file.clone();
    on_worker(&worker_name, move || {
        let mut trees = Vec::new();
        let mut admission = NativeAdmission::items(&meter, &file, None, 0);
        purrdf_lex::allocation::Memory::new(&mut admission)
            .reserve(&mut trees, inputs.len())
            .map_err(|error| admission.graph_error(error.into()))?;
        for (path, text) in inputs {
            let syntax = parse_syntax(&path, &text)?;
            trees.push(ParsedSource { path, text, syntax });
        }
        Ok(visit(trees))
    })
}

/// [`parse_source`] with a token limit of `max_tokens`, also returning what
/// the pre-scan counted.
pub(crate) fn parse_counted<R: Send>(
    file: &RelPath,
    text: &str,
    max_tokens: usize,
    visit: impl FnOnce(&syn::File) -> R + Send,
) -> Result<(R, Scan), LoadError> {
    parse_counted_mut(file, text, max_tokens, |tree| visit(tree))
}

/// The same bounded worker, allowing declaration selection before fact extraction.
pub(crate) fn parse_counted_mut<R: Send>(
    file: &RelPath,
    text: &str,
    max_tokens: usize,
    visit: impl FnOnce(&mut syn::File) -> R + Send,
) -> Result<(R, Scan), LoadError> {
    let prepared = PreparedSource::new(file, text, max_tokens)?;
    let scan = prepared.scan;
    prepared.parse_mut(visit).map(|result| (result, scan))
}

fn on_worker<R: Send>(
    file: &RelPath,
    work: impl FnOnce() -> Result<R, LoadError> + Send,
) -> Result<R, LoadError> {
    thread::scope(|scope| {
        let worker = thread::Builder::new()
            .name(file.to_string())
            .stack_size(PARSE_STACK_BYTES)
            .spawn_scoped(scope, move || {
                entry::claim_registry(file)?;
                work()
            })
            .map_err(|source| LoadError::new(file, None, LoadErrorKind::Spawn(source)))?;
        match worker.join() {
            Ok(result) => result,
            Err(payload) => panic::resume_unwind(payload),
        }
    })
}

fn parse_syntax(file: &RelPath, text: &str) -> Result<syn::File, LoadError> {
    LexedSource::new(file, text)?.into_syntax()
}

fn lex_source(
    file: &RelPath,
    text: &str,
) -> Result<(proc_macro2::TokenStream, Option<String>), LoadError> {
    use purrdf_lex::allocation::{Memory, Resident};
    let mut resident = Resident;
    let mut memory = Memory::new(&mut resident);
    let mut header = None;
    let normalized = if let Some(range) = shebang(text) {
        let error = |source| LoadError::new(file, Some(1), LoadErrorKind::Storage(source));
        header = Some(memory.string(&text[range.clone()]).map_err(error)?);
        // Padding preserves byte positions and all newlines. There are no
        // syntax positions within the ignored first-line header itself.
        std::borrow::Cow::Owned(
            memory
                .format(&format_args!(
                    "{}{blank:width$}{}",
                    &text[..range.start],
                    &text[range.end..],
                    blank = "",
                    width = range.len()
                ))
                .map_err(error)?,
        )
    } else {
        std::borrow::Cow::Borrowed(text)
    };
    let original = normalized
        .parse::<proc_macro2::TokenStream>()
        .map_err(|error| located_syntax(file, error.span(), error.to_string()))?;
    Ok((original, header))
}

fn syntax(
    file: &RelPath,
    original: proc_macro2::TokenStream,
    header: Option<String>,
) -> Result<syn::File, LoadError> {
    #[cfg(all(test, target_os = "linux"))]
    let _parsing = parallel::tests::parsing(file);
    let mut tree: syn::File = syn::parse2(original)
        .map_err(|error| located_syntax(file, error.span(), error.to_string()))?;
    tree.shebang = header;
    Ok(tree)
}

fn located_syntax(file: &RelPath, span: proc_macro2::Span, message: String) -> LoadError {
    // Read thread-local span data before returning the error to the caller.
    let start = span.start();
    LoadError::new(
        file,
        Some(start.line),
        LoadErrorKind::Syntax {
            message,
            column: start.column + 1,
        },
    )
}