exprim 0.4.1

A concurrent, memory-bounded PDF reader and renderer: parse, extract text, and rasterize pages on an immutable document snapshot
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
//! Content-stream interpretation: the PDF graphics-state machine that turns a
//! page's operators + resolved resources into a [`semantic::SemanticPage`]
//! (roadmap §7 Phase 2).
//!
//! Interpretation state is page-local by nature — the whole reason pages
//! parallelize. Everything here is owned by one compilation job; nothing is
//! shared except the immutable [`DocumentSnapshot`] it reads from, so any
//! number of pages compile concurrently with no coordination.
//!
//! Lowering a [`semantic::SemanticPage`] into the fully-explicit, interned
//! [`crate::page_ir::CompiledPage`] is deliberately Phase 3 work; this crate's
//! Phase 2 product is the semantic page and its deterministic dump.

use crate::document::{DocumentError, DocumentSnapshot, PageIndex, ParseContext};
use crate::page_ir::{CompiledPage, FillRule, PageBounds, Rect};

pub mod dump;
mod interpret;
mod lower;
pub mod marked;
mod mesh;
pub mod semantic;
pub mod state;
pub mod tokenizer;
pub mod trace;

pub use marked::MarkedContentSpan;
pub use semantic::{
    ActualTextSpan, ActualTextSpanId, SemColor, SemFont, SemImage, SemanticOp, SemanticPage,
    TextElement, TextRun,
};
pub use state::GraphicsState;
pub use tokenizer::{ContentLexer, Lexeme, Operand};
pub use trace::{OpTrace, PageTrace, TraceFrame, TraceFrameKind};

/// Budgets applied while interpreting a content stream. Owned by the caller,
/// threaded by reference — never global (blueprint §4.4).
#[derive(Debug, Clone)]
pub struct ContentLimits {
    /// Maximum operators executed across a page (including nested forms).
    pub max_ops: u64,
    /// Maximum XObject/pattern invocation nesting (recursion guard).
    pub max_invoke_depth: u32,
    /// Maximum nesting of a `/ColorSpace` entry that names another space
    /// (`/Indexed` over `/Separation` over `/ICCBased`, …). A malformed or
    /// cyclic resource cannot recurse past this.
    pub max_colorspace_depth: u32,
    /// Maximum `/Functions` nesting inside a Type 3 (stitching) function.
    pub max_function_depth: u32,
    /// Maximum nesting of a page's `/Contents` when it is an array of arrays
    /// or a reference chain.
    pub max_content_depth: usize,
    /// Limits for the underlying content tokenizer.
    pub syntax: crate::syntax::SyntaxLimits,
}

impl Default for ContentLimits {
    fn default() -> Self {
        Self {
            max_ops: 5_000_000,
            max_invoke_depth: 16,
            max_colorspace_depth: 8,
            max_function_depth: 32,
            max_content_depth: 8,
            syntax: crate::syntax::SyntaxLimits::default(),
        }
    }
}

#[derive(Debug, Clone, thiserror::Error)]
pub enum ContentError {
    #[error(transparent)]
    Document(#[from] DocumentError),
    #[error(transparent)]
    Syntax(#[from] crate::syntax::SyntaxError),
    #[error("operator budget exhausted after {0} operations")]
    OperatorBudget(u64),
    #[error("XObject/pattern recursion depth {0} exceeded")]
    RecursionDepth(u32),
    #[error("operand stack overflow ({0} operands)")]
    OperandStackOverflow(usize),
    #[error("operand nesting depth {0} exceeded")]
    NestingDepth(usize),
    #[error("malformed content stream: {0}")]
    Malformed(String),
    #[error("page compilation cancelled")]
    Cancelled,
    /// The inline-image framer could not locate the image's `EI` terminator.
    /// Recoverable: the run loop drops just the image and continues. This is a
    /// distinct variant (rather than reusing [`ContentError::Malformed`]) so the
    /// interpreter can attribute the recovery precisely without threading a
    /// `ParseContext` down into the ctx-free tokenizer (see `read_inline_image`).
    #[error("inline image framing failed: {0}")]
    InlineImage(String),
    #[error(transparent)]
    Font(#[from] crate::font::FontError),
    #[error(transparent)]
    Image(#[from] crate::image::ImageError),
    #[error(transparent)]
    Color(#[from] crate::color::ColorError),
}

impl ContentError {
    /// Whether this error must abort the whole page rather than being recovered
    /// past. The DoS guards and explicit cancellation are fatal — operator
    /// budget, XObject/pattern recursion depth, operand-stack overflow, operand
    /// nesting depth, and cancellation.
    /// Everything else (content malformation, unparseable tokens, and
    /// resource/decode failures) is *recoverable*: the interpreter drops the
    /// offending construct, records a recovery note, and continues, matching
    /// PDFium's content interpreter. Keeping the DoS guards on their own
    /// variants (not `Malformed`) makes this classification robust even when an
    /// error propagates out of a nested form/CharProc `run`.
    pub(crate) fn is_fatal(&self) -> bool {
        matches!(
            self,
            ContentError::OperatorBudget(_)
                | ContentError::RecursionDepth(_)
                | ContentError::OperandStackOverflow(_)
                | ContentError::NestingDepth(_)
                | ContentError::Cancelled
        )
    }
}

/// One-pass page compilation product for tightly integrated consumers such
/// as a document viewer. The semantic page remains available for text,
/// selection, links, structure recovery, recoloring policy, and diagnostics;
/// the compiled page is the reusable raster source.
///
/// Keeping both artifacts from one interpretation pass is deliberate. A
/// viewer must not call `compile_semantic` and then `compile` separately,
/// because that would parse and interpret the page twice and recreate the
/// bitmap-server boundary this workspace is designed to avoid.
#[derive(Debug, Clone)]
pub struct PageCompilation {
    pub semantic: std::sync::Arc<SemanticPage>,
    pub compiled: std::sync::Arc<CompiledPage>,
}

/// Compiles pages to the semantic IR. Cheap to construct; one per job or
/// reused per worker.
#[derive(Debug, Default)]
pub struct PageCompiler {
    limits: ContentLimits,
    /// Optional system font source (fonts.md Font Phase 7).
    ///
    /// Injected, never global, and absent by default: system fonts depend on
    /// what a machine happens to have installed, so enabling them trades
    /// this engine's determinism for PDFium-level coverage. Without one, a
    /// non-embedded font resolves to a bundled standard face and two
    /// machines still agree byte for byte.
    system_fonts: Option<std::sync::Arc<dyn crate::font::SystemFontProvider>>,
    /// Render annotation static appearance streams (`/AP /N`) after the page
    /// content, PDFium `FPDF_ANNOT` parity. Off by default; the render API's
    /// `AnnotationMode` maps onto this at integration.
    annotations: bool,
}

impl PageCompiler {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_limits(limits: ContentLimits) -> Self {
        Self {
            limits,
            ..Default::default()
        }
    }

    /// Resolve non-embedded fonts against installed system fonts before
    /// falling back to the bundled standard 14 (fonts.md Font Phase 7).
    ///
    /// This is what lets a document naming *DengXian* or *Cambria* — or any
    /// CJK font — render as intended, and it is what PDFium does. It also
    /// makes output depend on the host's installed fonts, which is why it is
    /// opt-in.
    pub fn with_system_fonts(
        mut self,
        provider: std::sync::Arc<dyn crate::font::SystemFontProvider>,
    ) -> Self {
        self.system_fonts = Some(provider);
        self
    }

    /// Render each annotation's normal (`/AP /N`) appearance stream after the
    /// page content — static appearances only, matching PDFium's
    /// `FPDF_ANNOT` display pass (two-pass order, `Hidden`/`NoView` skipped,
    /// `/AS` state selection, §12.5.5 rect fitting).
    pub fn with_annotations(mut self, on: bool) -> Self {
        self.annotations = on;
        self
    }

    /// Compile `page` of `snapshot` into a [`SemanticPage`] — the Phase 2
    /// product. `ctx` is the caller's worker-owned parse context; `&self`
    /// receives no document mutation whatsoever, so concurrent calls on
    /// different pages of the same snapshot are independent.
    pub fn compile_semantic(
        &self,
        snapshot: &DocumentSnapshot,
        page: PageIndex,
        ctx: &mut ParseContext,
    ) -> Result<SemanticPage, ContentError> {
        if ctx.is_cancelled() {
            return Err(ContentError::Cancelled);
        }
        let page_ref = snapshot.page(page)?.clone();
        let [x0, y0, x1, y1] = page_ref.crop_box;
        let bounds = PageBounds {
            crop: Rect { x0, y0, x1, y1 }.normalized(),
            rotate: page_ref.rotate,
        };

        let content =
            interpret::gather_content(snapshot, page_ref.contents.as_ref(), ctx, &self.limits)?;
        if ctx.is_cancelled() {
            return Err(ContentError::Cancelled);
        }
        let resources = interpret::resolve_resources(snapshot, page_ref.resources.as_ref(), ctx);

        let mut interp = interpret::Interpreter::new(
            snapshot,
            ctx,
            &self.limits,
            resources,
            self.system_fonts.clone(),
        );
        interp.run(&content)?;
        if self.annotations && !page_ref.annotations.is_empty() {
            interp.run_annotations(&page_ref.annotations)?;
        }
        Ok(interp.finish(bounds))
    }

    /// Inventory the page content stream's marked-content spans
    /// (`BMC`/`BDC`…`EMC`): tag names, content-stream offsets, and the
    /// user-space bounds of the text each span encloses.
    ///
    /// Neutral facts only — every tag is reported, structural (`/Span`,
    /// `/OC`) or otherwise; deciding which tags count as edit markers is
    /// the caller's job. Offsets are byte positions in the page's
    /// concatenated decoded content stream (one logical stream per
    /// ISO 32000-1 §7.8.2, so a `/Contents` array reads as one span of
    /// bytes). Spans inside nested content streams (form XObjects,
    /// annotation appearances, and the like) are separate byte streams and
    /// are not inventoried, and annotation appearance streams are not run
    /// at all.
    ///
    /// A separate interpretation pass: default compilation
    /// ([`Self::compile_semantic`], [`Self::compile`]) neither records
    /// spans nor changes its output when this exists.
    pub fn marked_content_spans(
        &self,
        snapshot: &DocumentSnapshot,
        page: PageIndex,
        ctx: &mut ParseContext,
    ) -> Result<Vec<MarkedContentSpan>, ContentError> {
        if ctx.is_cancelled() {
            return Err(ContentError::Cancelled);
        }
        let page_ref = snapshot.page(page)?.clone();
        let content =
            interpret::gather_content(snapshot, page_ref.contents.as_ref(), ctx, &self.limits)?;
        if ctx.is_cancelled() {
            return Err(ContentError::Cancelled);
        }
        let resources = interpret::resolve_resources(snapshot, page_ref.resources.as_ref(), ctx);

        let mut interp = interpret::Interpreter::new(
            snapshot,
            ctx,
            &self.limits,
            resources,
            self.system_fonts.clone(),
        );
        interp.set_record_marked();
        interp.run(&content)?;
        Ok(interp.take_marked_spans())
    }

    /// Compile `page` into a [`SemanticPage`] plus its audit sidecar, the
    /// [`PageTrace`]: per-op provenance (triggering operator, source stream
    /// object, nested-object stack, byte span, operator index, paint origin)
    /// recorded parallel to `SemanticPage::ops`.
    ///
    /// Audit-mode only: the semantic page is identical to what
    /// [`Self::compile_semantic`] produces, and default compilation neither
    /// allocates nor observes the trace. A separate interpretation pass, like
    /// [`Self::marked_content_spans`].
    pub fn compile_semantic_traced(
        &self,
        snapshot: &DocumentSnapshot,
        page: PageIndex,
        ctx: &mut ParseContext,
    ) -> Result<(SemanticPage, PageTrace), ContentError> {
        if ctx.is_cancelled() {
            return Err(ContentError::Cancelled);
        }
        let page_ref = snapshot.page(page)?.clone();
        let [x0, y0, x1, y1] = page_ref.crop_box;
        let bounds = PageBounds {
            crop: Rect { x0, y0, x1, y1 }.normalized(),
            rotate: page_ref.rotate,
        };

        let (content, segments) = interpret::gather_content_mapped(
            snapshot,
            page_ref.contents.as_ref(),
            ctx,
            &self.limits,
        )?;
        if ctx.is_cancelled() {
            return Err(ContentError::Cancelled);
        }
        let resources = interpret::resolve_resources(snapshot, page_ref.resources.as_ref(), ctx);

        let mut interp = interpret::Interpreter::new(
            snapshot,
            ctx,
            &self.limits,
            resources,
            self.system_fonts.clone(),
        );
        interp.set_record_trace(segments);
        interp.run(&content)?;
        if self.annotations && !page_ref.annotations.is_empty() {
            interp.run_annotations(&page_ref.annotations)?;
        }
        let trace = interp.take_trace();
        Ok((interp.finish(bounds), trace))
    }

    /// Compile once and retain both the semantic and lowered artifacts.
    ///
    /// This is the preferred entry point for document applications. Raster-
    /// only callers may continue to use [`Self::compile`].
    pub fn compile_artifacts(
        &self,
        snapshot: &DocumentSnapshot,
        page: PageIndex,
        ctx: &mut ParseContext,
    ) -> Result<PageCompilation, ContentError> {
        let semantic = std::sync::Arc::new(self.compile_semantic(snapshot, page, ctx)?);
        if ctx.is_cancelled() {
            return Err(ContentError::Cancelled);
        }
        let compiled = std::sync::Arc::new(lower::lower(semantic.as_ref()));
        if ctx.is_cancelled() {
            return Err(ContentError::Cancelled);
        }
        Ok(PageCompilation { semantic, compiled })
    }

    /// Compile `page` into the backend-neutral [`CompiledPage`] (roadmap §7
    /// Phase 3): compile the semantic page, then lower it — making implicit
    /// graphics state explicit, interning resources, and recording the clip
    /// stack. Painter order is preserved exactly.
    pub fn compile(
        &self,
        snapshot: &DocumentSnapshot,
        page: PageIndex,
        ctx: &mut ParseContext,
    ) -> Result<CompiledPage, ContentError> {
        let semantic = self.compile_semantic(snapshot, page, ctx)?;
        Ok(lower::lower(&semantic))
    }

    /// Compile a page and return coarse, allocation-free-at-call-site timing
    /// attribution for the semantic and IR-lowering phases.
    #[cfg(feature = "profiling")]
    pub fn compile_profiled(
        &self,
        snapshot: &DocumentSnapshot,
        page: PageIndex,
        ctx: &mut ParseContext,
    ) -> Result<(CompiledPage, crate::profiling::ProfileReport), ContentError> {
        let all = std::time::Instant::now();
        let page_start = std::time::Instant::now();
        let page_ref = snapshot.page(page)?.clone();
        let [x0, y0, x1, y1] = page_ref.crop_box;
        let bounds = PageBounds {
            crop: Rect { x0, y0, x1, y1 }.normalized(),
            rotate: page_ref.rotate,
        };
        let mut profile = crate::profiling::ProfileReport::new();
        profile.add_duration("compile.page_lookup", page_start.elapsed());

        let content_start = std::time::Instant::now();
        let content =
            interpret::gather_content(snapshot, page_ref.contents.as_ref(), ctx, &self.limits)?;
        profile.add_duration("compile.content_gather", content_start.elapsed());
        profile.increment("compile.content_bytes", content.len() as u64);

        let resources_start = std::time::Instant::now();
        let resources = interpret::resolve_resources(snapshot, page_ref.resources.as_ref(), ctx);
        profile.add_duration("compile.resources", resources_start.elapsed());

        let interpret_start = std::time::Instant::now();
        let mut interp = interpret::Interpreter::new(
            snapshot,
            ctx,
            &self.limits,
            resources,
            self.system_fonts.clone(),
        );
        interp.run(&content)?;
        if self.annotations && !page_ref.annotations.is_empty() {
            interp.run_annotations(&page_ref.annotations)?;
        }
        profile.add_duration("compile.interpret", interpret_start.elapsed());

        let finish_start = std::time::Instant::now();
        let semantic = interp.finish(bounds);
        profile.add_duration("compile.semantic_finish", finish_start.elapsed());
        let lower_start = std::time::Instant::now();
        let compiled = lower::lower(&semantic);
        profile.add_duration("compile.ir_lower", lower_start.elapsed());
        profile.add_duration("compile.total", all.elapsed());
        profile.increment("compile.operations", compiled.operations.len() as u64);
        profile.increment("compile.objects_visited", ctx.objects_visited as u64);
        profile.increment(
            "compile.decoded_stream_bytes",
            ctx.decoded_bytes_used as u64,
        );
        profile.increment("compile.recovery_events", ctx.recovery.len() as u64);
        profile.increment("compile.object_cache_hits", ctx.object_cache_hits as u64);
        profile.increment(
            "compile.object_cache_misses",
            ctx.object_cache_misses as u64,
        );
        profile.increment(
            "compile.object_stream_cache_hits",
            ctx.object_stream_cache_hits as u64,
        );
        profile.increment(
            "compile.object_stream_inflates",
            ctx.object_stream_inflates as u64,
        );
        Ok((compiled, profile))
    }

    /// Maps a path-painting operator's even-odd flag to the IR fill rule.
    pub fn map_fill_rule(even_odd: bool) -> FillRule {
        if even_odd {
            FillRule::EvenOdd
        } else {
            FillRule::NonZero
        }
    }
}

const fn _assert_send<T: Send>() {}
const _: () = _assert_send::<PageCompiler>();