ifc_lite_core/
project_locator.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! The one `IFCPROJECT` locator (XCUT-6, CORE-3, PROC-AL-12), whose search
6//! also finds the model's `IFCSITE`s ([`find_site_ids`]).
7//!
8//! Every reader that needs "the project" starts here: a SIMD keyword search
9//! plus a record-boundary check, never a full [`crate::EntityScanner`] walk.
10//! [`find_project_ids`] returns EVERY project id in file order (a federated
11//! file declares several, and per-owner unit contexts need all of them);
12//! [`find_project_id`] is its first element, the model's project.
13//! [`crate::EntityDecoder::project_id`] caches that answer per decoder.
14//!
15//! A scan that already visits every entity for another reason may keep
16//! noting the first `IFCPROJECT` it walks past: same policy (first in file
17//! order), no extra pass.
18
19use crate::express_id::parse_express_id;
20use crate::parser::find_keyword;
21
22/// Every `IFCPROJECT` express id in file order.
23///
24/// A refused id (issue #3421: an `IFCPROJECT` express id above `u32::MAX`) is
25/// reported through [`crate::parser::report_oversized_ids`] — the same sink
26/// the definition scanner uses (issue #3395/#3752) — because it is exactly
27/// that class of event: this function backtracks from `IFCPROJECT(` to the
28/// record's OWN id, so a refusal here is indistinguishable in kind from a scan
29/// refusing to index the record at all. Left unreported, it would default the
30/// file's unit scales with the silent-1000×-oversized symptom issue #1367
31/// already fixed for the "not found at all" case.
32pub fn find_project_ids(content: &[u8]) -> Vec<u32> {
33    let mut ids = Vec::new();
34    let refused = scan_records(content, b"IFCPROJECT(", &mut |id| {
35        ids.push(id);
36        true
37    });
38    crate::parser::report_oversized_ids(refused);
39    ids
40}
41
42/// The model's project: the first `IFCPROJECT` in file order, or `None` when
43/// the file has none. Stops at the first hit, so it costs no more than the
44/// distance to it. Reports a refused id like [`find_project_ids`].
45pub fn find_project_id(content: &[u8]) -> Option<u32> {
46    let mut first = None;
47    let refused = scan_records(content, b"IFCPROJECT(", &mut |id| {
48        first = Some(id);
49        false
50    });
51    crate::parser::report_oversized_ids(refused);
52    first
53}
54
55/// The first `IFCPROJECT` an entity scan meets: the fallback of
56/// [`crate::EntityDecoder::project_id`] for what the byte search cannot see
57/// (trivia between the keyword and `(`, a comment around `=`) or accepts
58/// wrongly (a record-shaped decoy inside a string). Runs only when the search
59/// finds no confirmed project, so the common path never pays for it.
60pub(crate) fn scan_for_project_id(content: &[u8]) -> Option<u32> {
61    let mut scanner = crate::parser::EntityScanner::new(content);
62    while let Some((id, kind, _, _)) = scanner.next_entity() {
63        if crate::parser::keyword_eq(kind, "IFCPROJECT") {
64            return Some(id);
65        }
66    }
67    None
68}
69
70/// The first `keyword` (uppercase, with its `(`) at or after `from`,
71/// case-insensitively. The `from` cut matters because [`scan_records`]
72/// resumes at `previous_hit + 1`, so a hit behind it would be returned forever.
73pub(crate) fn find_record_keyword(content: &[u8], from: usize, keyword: &[u8]) -> Option<usize> {
74    find_keyword(content.get(from..)?, keyword).map(|rel| from + rel)
75}
76
77/// Every `IFCSITE` express id in file order, by the same search as the
78/// project. A candidate is a byte-search hit; the caller confirms its type.
79/// An oversized id is skipped unreported: the definition scanner reports
80/// that record already, and this runs once per decoder.
81pub(crate) fn find_site_ids(content: &[u8]) -> Vec<u32> {
82    let mut ids = Vec::new();
83    scan_records(content, b"IFCSITE(", &mut |id| {
84        ids.push(id);
85        true
86    });
87    ids
88}
89
90/// Every `IFCSITE` an entity scan meets: the fallback of
91/// [`crate::EntityDecoder::is_site_placement`] when the byte search confirms
92/// none, as [`scan_for_project_id`] is for the project. The scan sees
93/// `IFCSITE (` and comments around `=`, which the byte search cannot; a file
94/// without the keyword at all skips it.
95pub(crate) fn scan_for_site_ids(content: &[u8]) -> Vec<u32> {
96    if find_keyword(content, b"IFCSITE").is_none() {
97        return Vec::new();
98    }
99    let mut scanner = crate::parser::EntityScanner::new(content);
100    let mut ids = Vec::new();
101    while let Some((id, kind, _, _)) = scanner.next_entity() {
102        if crate::parser::keyword_eq(kind, "IFCSITE") {
103            ids.push(id);
104        }
105    }
106    ids
107}
108
109/// Visit each id of a `keyword` record (the uppercase keyword with its `(`)
110/// in file order until `visit` returns `false`. Returns how many ids were
111/// refused as oversized. The search is case-insensitive (issue #4497: STEP
112/// keyword case is not significant) and resumes past each hit.
113fn scan_records(content: &[u8], keyword: &[u8], visit: &mut dyn FnMut(u32) -> bool) -> usize {
114    let mut refused = 0usize;
115    let mut from = 0usize;
116    // Search for the keyword+paren only; the `=` and `#<id>` are reconstructed by
117    // backtracking. Exporters vary the whitespace around `=` — Revit/EDM emits
118    // `#1593796= IFCPROJECT(` with a SPACE, so the old `=IFCPROJECT(` literal
119    // never matched and the whole unit chain silently defaulted (length → metres
120    // on a mm model, plane-angle → radians on a degree model, making arched
121    // openings render as full circles — issue #1367). The `(` must immediately
122    // follow, so `IFCPROJECT(` cannot collide with `IFCPROJECTEDCRS(`.
123    while let Some(kw) = find_record_keyword(content, from, keyword) {
124        // Backtrack over optional whitespace, then require '='.
125        let mut i = kw;
126        while i > 0 && content[i - 1].is_ascii_whitespace() {
127            i -= 1;
128        }
129        if i > 0 && content[i - 1] == b'=' {
130            i -= 1; // step over '='
131            // Optional whitespace between the express id and '='.
132            while i > 0 && content[i - 1].is_ascii_whitespace() {
133                i -= 1;
134            }
135            // Backtrack over the express id digits to the '#'.
136            let digits_end = i;
137            while i > 0 && content[i - 1].is_ascii_digit() {
138                i -= 1;
139            }
140            if i > 0 && content[i - 1] == b'#' && i < digits_end && starts_a_record(content, i - 1)
141            {
142                // Refuse (not wrap) above u32::MAX (#3421); a refused id just
143                // keeps searching. Counted (issue #3752) so the caller can
144                // report it via the scanner's own oversized-id sink instead
145                // of it vanishing.
146                match parse_express_id(&content[i..digits_end]) {
147                    Some(id) => {
148                        if !visit(id) {
149                            return refused;
150                        }
151                    }
152                    None => refused += 1,
153                }
154            }
155        }
156        // `IFCPROJECT(` not preceded by a record-starting `#<digits>=` (e.g.
157        // the whole thing quoted inside a string) — keep searching.
158        from = kw + 1;
159    }
160    refused
161}
162
163/// Does the `#` at `hash` begin a record, rather than sit inside a quoted
164/// string or a comment?
165///
166/// 10303-21 terminates every entity instance with `;`, so a declaration's
167/// `#` is preceded — across trivia only — by that `;` or by the start of
168/// input. Without this check a description or comment containing a
169/// record-shaped decoy such as `'note: #9=ifcproject( …'` is accepted, and
170/// the scan returns a WRONG express id AND stops, so the real project is
171/// never reached: `extract_length_unit_scale` then rejects that id on its
172/// `IFCPROJECT` type guard and the caller's `unwrap_or(1.0)` restores the
173/// 1000×-oversized millimetre default issue #4497 exists to remove. The
174/// hazard predates case-insensitive matching, which only widens it from
175/// uppercase decoys to ordinary lowercase prose.
176///
177/// Validating instead that the id decodes to an `IFCPROJECT` would be
178/// stricter, but it needs an entity index per candidate — the
179/// O(file)-scan-per-decoder cost [`resolve_unit_scales`] exists to keep
180/// dead. This stays a single linear byte scan.
181///
182/// "Trivia", not whitespace: a `/* … */` comment is legal wherever
183/// whitespace is, so `#1=IFCWALL(…); /* note */ #7=IFCPROJECT(…)` is a real
184/// declaration and must not be refused (the entity scanner's `skip_step_trivia`
185/// makes the same allowance in the forward direction).
186fn starts_a_record(content: &[u8], hash: usize) -> bool {
187    let mut i = hash;
188    loop {
189        while i > 0 && content[i - 1].is_ascii_whitespace() {
190            i -= 1;
191        }
192        // A closing `*/` here means a comment sits between the boundary and
193        // the `#`; skip back over it and re-test. An unopened `*/` is not
194        // trivia, so refuse rather than loop.
195        if i >= 2 && content[i - 1] == b'/' && content[i - 2] == b'*' {
196            match memchr::memmem::rfind(&content[..i - 2], b"/*") {
197                Some(open) => i = open,
198                None => return false,
199            }
200            continue;
201        }
202        return i == 0 || content[i - 1] == b';';
203    }
204}
205
206#[cfg(test)]
207#[path = "project_locator_tests.rs"]
208mod tests;