Skip to main content

read_fonts/tables/layout/
closure.rs

1//! Support Layout Closure
2
3use types::{BigEndian, Compatible, GlyphId16, GlyphId24, Offset16};
4
5use super::{
6    ArrayOfOffsets, ChainedClassSequenceRule, ChainedClassSequenceRuleSet,
7    ChainedClassSequenceRuleSet2, ChainedSequenceContext, ChainedSequenceContextFormat1,
8    ChainedSequenceContextFormat2, ChainedSequenceContextFormat3, ChainedSequenceContextFormat4,
9    ChainedSequenceContextFormat5, ChainedSequenceRule, ChainedSequenceRule2,
10    ChainedSequenceRuleSet, ChainedSequenceRuleSet2, ClassDef, ClassDefFormat1, ClassDefFormat2,
11    ClassSequenceRule, ClassSequenceRuleSet, ClassSequenceRuleSet2, CoverageTable, ExtensionLookup,
12    Feature, FeatureList, FeatureVariations, GlyphId, LangSys, ReadError, Script, ScriptList,
13    SequenceContext, SequenceContextFormat1, SequenceContextFormat2, SequenceContextFormat3,
14    SequenceContextFormat4, SequenceContextFormat5, SequenceContextFormat6, SequenceLookupRecord,
15    SequenceRule, SequenceRule2, SequenceRuleSet, SequenceRuleSet2, Subtables, Tag,
16};
17use crate::{
18    collections::{FastHashMap, IntSet},
19    tables::{gpos::PositionLookupList, gsub::SubstitutionLookupList},
20    FontRead, MinByteRange,
21};
22
23use crate::limits::{
24    MAX_FEATURE_INDICES, MAX_LANGSYS, MAX_LOOKUP_VISIT_COUNT, MAX_RECURSION_DEPTH, MAX_SCRIPTS,
25};
26
27struct CollectFeaturesContext<'a> {
28    script_count: u16,
29    langsys_count: u16,
30    feature_index_count: u16,
31    visited_script: IntSet<u32>,
32    visited_langsys: IntSet<u32>,
33    feature_indices: &'a mut IntSet<u16>,
34    feature_indices_filter: IntSet<u16>,
35    table_head: usize,
36}
37
38impl<'a> CollectFeaturesContext<'a> {
39    pub(crate) fn new(
40        features: &IntSet<Tag>,
41        table_head: usize,
42        feature_list: &'a FeatureList<'a>,
43        feature_indices: &'a mut IntSet<u16>,
44    ) -> Self {
45        Self {
46            script_count: 0,
47            langsys_count: 0,
48            feature_index_count: 0,
49            visited_script: IntSet::empty(),
50            visited_langsys: IntSet::empty(),
51            feature_indices,
52            feature_indices_filter: feature_list
53                .feature_records()
54                .iter()
55                .enumerate()
56                .filter(|(_i, record)| features.contains(record.feature_tag()))
57                .map(|(idx, _)| idx as u16)
58                .collect(),
59            table_head,
60        }
61    }
62
63    /// Return true if the script limit has been exceeded or the script is visited before
64    pub(crate) fn script_visited(&mut self, s: &Script) -> bool {
65        if self.script_count > MAX_SCRIPTS {
66            return true;
67        }
68
69        self.script_count += 1;
70
71        let delta = (s.offset_data().as_bytes().as_ptr() as usize - self.table_head) as u32;
72        !self.visited_script.insert(delta)
73    }
74
75    /// Return true if the Langsys limit has been exceeded or the Langsys is visited before
76    pub(crate) fn langsys_visited(&mut self, langsys: &LangSys) -> bool {
77        if self.langsys_count > MAX_LANGSYS {
78            return true;
79        }
80
81        self.langsys_count += 1;
82
83        let delta = (langsys.offset_data().as_bytes().as_ptr() as usize - self.table_head) as u32;
84        !self.visited_langsys.insert(delta)
85    }
86
87    /// Returns true if the feature limit has been exceeded
88    pub(crate) fn feature_indices_limit_exceeded(&mut self, count: u16) -> bool {
89        let (new_count, overflow) = self.feature_index_count.overflowing_add(count);
90        if overflow {
91            self.feature_index_count = MAX_FEATURE_INDICES;
92            return true;
93        }
94        self.feature_index_count = new_count;
95        new_count > MAX_FEATURE_INDICES
96    }
97}
98
99impl ScriptList<'_> {
100    /// Return a set of all feature indices underneath the specified scripts, languages and features
101    pub(crate) fn collect_features(
102        &self,
103        layout_table_head: usize,
104        feature_list: &FeatureList,
105        scripts: &IntSet<Tag>,
106        languages: &IntSet<Tag>,
107        features: &IntSet<Tag>,
108    ) -> Result<IntSet<u16>, ReadError> {
109        let mut out = IntSet::empty();
110        let mut c =
111            CollectFeaturesContext::new(features, layout_table_head, feature_list, &mut out);
112        let script_records = self.script_records();
113        let font_data = self.offset_data();
114        if scripts.is_inverted() {
115            for record in script_records {
116                let tag = record.script_tag();
117                if !scripts.contains(tag) || record.script_offset().is_null() {
118                    continue;
119                }
120                let script = record.script(font_data)?;
121                script.collect_features(&mut c, languages)?;
122            }
123        } else {
124            for idx in scripts.iter().filter_map(|tag| self.index_for_tag(tag)) {
125                let record = script_records[idx as usize];
126                if record.script_offset().is_null() {
127                    continue;
128                }
129                let script = record.script(font_data)?;
130                script.collect_features(&mut c, languages)?;
131            }
132        }
133        Ok(out)
134    }
135}
136
137impl Script<'_> {
138    fn collect_features(
139        &self,
140        c: &mut CollectFeaturesContext,
141        languages: &IntSet<Tag>,
142    ) -> Result<(), ReadError> {
143        if c.script_visited(self) {
144            return Ok(());
145        }
146
147        let lang_sys_records = self.lang_sys_records();
148        let font_data = self.offset_data();
149
150        if let Some(default_lang_sys) = self.default_lang_sys().transpose()? {
151            default_lang_sys.collect_features(c);
152        }
153
154        if languages.is_inverted() {
155            for record in lang_sys_records {
156                let tag = record.lang_sys_tag();
157                if !languages.contains(tag) || record.lang_sys_offset().is_null() {
158                    continue;
159                }
160                let lang_sys = record.lang_sys(font_data)?;
161                lang_sys.collect_features(c);
162            }
163        } else {
164            for idx in languages
165                .iter()
166                .filter_map(|tag| self.lang_sys_index_for_tag(tag))
167            {
168                let record = lang_sys_records[idx as usize];
169                if record.lang_sys_offset().is_null() {
170                    continue;
171                }
172                let lang_sys = record.lang_sys(font_data)?;
173                lang_sys.collect_features(c);
174            }
175        }
176        Ok(())
177    }
178}
179
180impl LangSys<'_> {
181    fn collect_features(&self, c: &mut CollectFeaturesContext) {
182        if c.langsys_visited(self) {
183            return;
184        }
185
186        if c.feature_indices_filter.is_empty() {
187            return;
188        }
189
190        let required_feature_idx = self.required_feature_index();
191        if required_feature_idx != 0xFFFF
192            && !c.feature_indices_limit_exceeded(1)
193            && c.feature_indices_filter.contains(required_feature_idx)
194        {
195            c.feature_indices.insert(required_feature_idx);
196        }
197
198        if c.feature_indices_limit_exceeded(self.feature_index_count()) {
199            return;
200        }
201
202        for feature_index in self.feature_indices() {
203            let idx = feature_index.get();
204            if !c.feature_indices_filter.contains(idx) {
205                continue;
206            }
207            c.feature_indices.insert(idx);
208            c.feature_indices_filter.remove(idx);
209        }
210    }
211}
212
213impl Feature<'_> {
214    pub(crate) fn collect_lookups(&self) -> Vec<u16> {
215        self.lookup_list_indices()
216            .iter()
217            .map(|idx| idx.get())
218            .collect()
219    }
220}
221
222impl FeatureList<'_> {
223    pub(crate) fn collect_lookups(
224        &self,
225        feature_indices: &IntSet<u16>,
226    ) -> Result<IntSet<u16>, ReadError> {
227        let features_records = self.feature_records();
228        let num_features = self.feature_count();
229        let font_data = self.offset_data();
230        let mut lookup_idxes = IntSet::empty();
231
232        if feature_indices.is_inverted() {
233            for feature_rec in (0..num_features).filter_map(|i| {
234                feature_indices
235                    .contains(i)
236                    .then(|| features_records.get(i as usize))
237                    .flatten()
238            }) {
239                if feature_rec.feature_offset().is_null() {
240                    continue;
241                }
242                lookup_idxes.extend_unsorted(feature_rec.feature(font_data)?.collect_lookups());
243            }
244        } else {
245            for feature_rec in feature_indices
246                .iter()
247                .filter_map(|i| features_records.get(i as usize))
248            {
249                if feature_rec.feature_offset().is_null() {
250                    continue;
251                }
252                lookup_idxes.extend_unsorted(feature_rec.feature(font_data)?.collect_lookups());
253            }
254        }
255        Ok(lookup_idxes)
256    }
257}
258
259impl FeatureVariations<'_> {
260    pub(crate) fn collect_lookups(
261        &self,
262        feature_indices: &IntSet<u16>,
263    ) -> Result<IntSet<u16>, ReadError> {
264        let mut out = IntSet::empty();
265        if u64::from(self.feature_variation_record_count()) * 8
266            > self.offset_data().len().saturating_sub(8) as u64
267        {
268            return Err(ReadError::OutOfBounds);
269        }
270
271        for variation_rec in self.feature_variation_records() {
272            let Some(subs) = variation_rec
273                .feature_table_substitution(self.offset_data())
274                .transpose()?
275            else {
276                continue;
277            };
278
279            for sub_record in subs
280                .substitutions()
281                .iter()
282                .filter(|sub_rec| feature_indices.contains(sub_rec.feature_index()))
283            {
284                if sub_record.alternate_feature_offset().is_null() {
285                    continue;
286                }
287                let sub_f = sub_record.alternate_feature(subs.offset_data())?;
288                out.extend_unsorted(sub_f.lookup_list_indices().iter().map(|i| i.get()));
289            }
290        }
291        if self.version().compatible((1, 1)) {
292            let records = self
293                .lookup_variation_records()
294                .ok_or(ReadError::OutOfBounds)?;
295            for record in records
296                .iter()
297                .filter(|rec| feature_indices.contains(rec.feature_index()))
298            {
299                if record.feature_lookups_offset().is_null() {
300                    continue;
301                }
302                let lookups = record.feature_lookups(self.offset_data())?;
303                if u64::from(lookups.lookup_condition_count()) * 8
304                    > lookups.offset_data().len().saturating_sub(10) as u64
305                {
306                    return Err(ReadError::OutOfBounds);
307                }
308                for record in lookups.lookup_condition_records() {
309                    if record.lookup_index_list_offset().is_null() {
310                        continue;
311                    }
312                    let indices = record.lookup_index_list(lookups.offset_data())?;
313                    if indices.min_table_bytes().is_empty() {
314                        return Err(ReadError::OutOfBounds);
315                    }
316                    // Closure includes every design-space branch; do not evaluate conditions.
317                    out.extend_unsorted(indices.lookup_indices().iter().map(|i| i.get()));
318                }
319            }
320        }
321        Ok(out)
322    }
323}
324
325pub(crate) enum LayoutLookupList<'a> {
326    Gsub(&'a SubstitutionLookupList<'a>),
327    Gpos(&'a PositionLookupList<'a>),
328}
329
330pub(crate) struct LookupClosureCtx<'a> {
331    visited_lookups: IntSet<u16>,
332    inactive_lookups: IntSet<u16>,
333    glyph_set: &'a IntSet<GlyphId>,
334    lookup_count: u16,
335    nesting_level_left: usize,
336    lookup_list: &'a LayoutLookupList<'a>,
337}
338
339impl<'a> LookupClosureCtx<'a> {
340    pub(crate) fn new(glyph_set: &'a IntSet<GlyphId>, lookup_list: &'a LayoutLookupList) -> Self {
341        Self {
342            visited_lookups: IntSet::empty(),
343            inactive_lookups: IntSet::empty(),
344            glyph_set,
345            lookup_count: 0,
346            nesting_level_left: MAX_RECURSION_DEPTH,
347            lookup_list,
348        }
349    }
350
351    pub(crate) fn visited_lookups(&self) -> &IntSet<u16> {
352        &self.visited_lookups
353    }
354
355    pub(crate) fn inactive_lookups(&self) -> &IntSet<u16> {
356        &self.inactive_lookups
357    }
358
359    pub(crate) fn glyphs(&self) -> &IntSet<GlyphId> {
360        self.glyph_set
361    }
362
363    pub(crate) fn set_lookup_inactive(&mut self, lookup_index: u16) {
364        self.inactive_lookups.insert(lookup_index);
365    }
366
367    pub(crate) fn lookup_limit_exceed(&self) -> bool {
368        self.lookup_count > MAX_LOOKUP_VISIT_COUNT
369    }
370
371    // return false if lookup limit exceeded or lookup visited,and visited set is not modified
372    // Otherwise return true and insert lookup index into the visited set
373    pub(crate) fn should_visit_lookup(&mut self, lookup_index: u16) -> bool {
374        if self.lookup_count > MAX_LOOKUP_VISIT_COUNT {
375            return false;
376        }
377        self.lookup_count += 1;
378        self.visited_lookups.insert(lookup_index)
379    }
380
381    pub(crate) fn recurse(&mut self, lookup_index: u16) -> Result<(), ReadError> {
382        if self.nesting_level_left == 0 {
383            return Ok(());
384        }
385
386        if self.lookup_limit_exceed() || self.visited_lookups.contains(lookup_index) {
387            return Ok(());
388        }
389
390        self.nesting_level_left -= 1;
391        match self.lookup_list {
392            LayoutLookupList::Gpos(lookuplist) => {
393                match lookuplist.lookups().get(lookup_index as usize) {
394                    Err(ReadError::NullOffset) | Err(ReadError::InvalidCollectionIndex(_)) => (),
395                    lookup => lookup?.closure_lookups(self, lookup_index)?,
396                }
397            }
398            LayoutLookupList::Gsub(lookuplist) => {
399                match lookuplist.lookups().get(lookup_index as usize) {
400                    Err(ReadError::NullOffset) | Err(ReadError::InvalidCollectionIndex(_)) => (),
401                    lookup => lookup?.closure_lookups(self, lookup_index)?,
402                }
403            }
404        }
405        self.nesting_level_left += 1;
406        Ok(())
407    }
408}
409
410/// Compute the transitive closure of lookups
411pub(crate) trait LookupClosure {
412    fn closure_lookups(&self, _c: &mut LookupClosureCtx, _arg: u16) -> Result<(), ReadError> {
413        Ok(())
414    }
415}
416
417pub trait Intersect {
418    fn intersects(&self, glyph_set: &IntSet<GlyphId>) -> Result<bool, ReadError>;
419}
420
421impl Intersect for ClassDef<'_> {
422    fn intersects(&self, glyph_set: &IntSet<GlyphId>) -> Result<bool, ReadError> {
423        match self {
424            ClassDef::Format1(table) => table.intersects(glyph_set),
425            ClassDef::Format2(table) => table.intersects(glyph_set),
426            _ => Ok(self
427                .intersect_classes(glyph_set)
428                .iter()
429                .any(|class| class != 0)),
430        }
431    }
432}
433
434impl Intersect for ClassDefFormat1<'_> {
435    fn intersects(&self, glyph_set: &IntSet<GlyphId>) -> Result<bool, ReadError> {
436        let class_values = self.class_value_array();
437        if class_values.is_empty() {
438            return Ok(false);
439        }
440
441        let start = self.start_glyph_id().to_u32();
442        let end = start + self.glyph_count() as u32;
443
444        let mut start_glyph = GlyphId::from(start);
445        if glyph_set.contains(start_glyph) && class_values[0] != 0 {
446            return Ok(true);
447        }
448
449        while let Some(g) = glyph_set.next_after(start_glyph) {
450            let g = g.to_u32();
451            if g >= end {
452                break;
453            }
454            let Some(class) = class_values.get((g - start) as usize) else {
455                break;
456            };
457            if class.get() != 0 {
458                return Ok(true);
459            }
460            start_glyph = GlyphId::from(g);
461        }
462        Ok(false)
463    }
464}
465
466impl Intersect for ClassDefFormat2<'_> {
467    fn intersects(&self, glyph_set: &IntSet<GlyphId>) -> Result<bool, ReadError> {
468        let num_ranges = self.class_range_count();
469        let num_bits = 16 - num_ranges.leading_zeros();
470        if num_ranges as u64 > glyph_set.len() * num_bits as u64 {
471            for g in glyph_set.iter() {
472                if self.get(g) != 0 {
473                    return Ok(true);
474                }
475            }
476        } else {
477            for record in self.class_range_records() {
478                let first = GlyphId::from(record.start_glyph_id());
479                let last = GlyphId::from(record.end_glyph_id());
480                if glyph_set.intersects_range(first..=last) && record.class() != 0 {
481                    return Ok(true);
482                }
483            }
484        }
485        Ok(false)
486    }
487}
488
489impl<'a, T, Ext> LookupClosure for Subtables<'a, T, Ext>
490where
491    T: LookupClosure + Intersect + FontRead<'a, Args = ()> + 'a,
492    Ext: ExtensionLookup<'a, T> + 'a,
493{
494    /// Runs lookup closure on the subtables that intersect the glyph set, and
495    /// marks the lookup at `lookup_index` inactive if none of them do.
496    ///
497    /// This checks each subtable only once, instead of running a separate
498    /// `intersects` pass over the lookup first. A subtable that doesn't
499    /// intersect the glyph set recurses into no lookups, so skipping it
500    /// changes nothing.
501    fn closure_lookups(
502        &self,
503        c: &mut LookupClosureCtx,
504        lookup_index: u16,
505    ) -> Result<(), ReadError> {
506        let mut intersects = false;
507        for t in self.iter().filter_map(|table| match table {
508            Err(ReadError::NullOffset) => None,
509            other => Some(other),
510        }) {
511            let t = t?;
512            if t.intersects(c.glyphs())? {
513                intersects = true;
514                t.closure_lookups(c, lookup_index)?;
515            }
516        }
517        if !intersects {
518            c.set_lookup_inactive(lookup_index);
519        }
520        Ok(())
521    }
522}
523
524impl<'a, T> Intersect for ArrayOfOffsets<'a, T, Offset16>
525where
526    T: Intersect + FontRead<'a, Args = ()> + 'a,
527{
528    fn intersects(&self, glyph_set: &IntSet<GlyphId>) -> Result<bool, ReadError> {
529        for t in self.iter().filter_map(|table| match table {
530            Err(ReadError::NullOffset) => None,
531            other => Some(other),
532        }) {
533            if t?.intersects(glyph_set)? {
534                return Ok(true);
535            }
536        }
537        Ok(false)
538    }
539}
540
541// these are basically the same; but we need to jump through some hoops
542// to get the fields to line up
543pub(crate) enum ContextFormat1<'a> {
544    Plain(SequenceContextFormat1<'a>),
545    Chain(ChainedSequenceContextFormat1<'a>),
546    PlainWide(SequenceContextFormat4<'a>),
547    ChainWide(ChainedSequenceContextFormat4<'a>),
548}
549
550pub(crate) enum Format1RuleSet<'a> {
551    Plain(SequenceRuleSet<'a>),
552    Chain(ChainedSequenceRuleSet<'a>),
553    PlainWide(SequenceRuleSet2<'a>),
554    ChainWide(ChainedSequenceRuleSet2<'a>),
555}
556
557pub(crate) enum Format1Rule<'a> {
558    Plain(SequenceRule<'a>),
559    Chain(ChainedSequenceRule<'a>),
560    PlainWide(SequenceRule2<'a>),
561    ChainWide(ChainedSequenceRule2<'a>),
562}
563
564impl<'a> ContextFormat1<'a> {
565    pub(crate) fn coverage(&self) -> Option<Result<CoverageTable<'_>, ReadError>> {
566        match self {
567            ContextFormat1::Plain(table) if !table.coverage_offset().is_null() => {
568                Some(table.coverage())
569            }
570            ContextFormat1::Chain(table) if !table.coverage_offset().is_null() => {
571                Some(table.coverage())
572            }
573            ContextFormat1::PlainWide(table) if !table.coverage_offset().is_null() => {
574                Some(table.coverage())
575            }
576            ContextFormat1::ChainWide(table) if !table.coverage_offset().is_null() => {
577                Some(table.coverage())
578            }
579            _ => None,
580        }
581    }
582
583    pub(crate) fn rule_sets(
584        &self,
585    ) -> impl Iterator<Item = Option<Result<Format1RuleSet<'a>, ReadError>>> + '_ {
586        let count = match self {
587            Self::Plain(table) => table.seq_rule_sets().len(),
588            Self::Chain(table) => table.chained_seq_rule_sets().len(),
589            Self::PlainWide(table) => table.seq_rule_sets().len(),
590            Self::ChainWide(table) => table.chained_seq_rule_sets().len(),
591        };
592        (0..count).map(move |index| match self {
593            Self::Plain(table) => table
594                .seq_rule_sets()
595                .get(index)
596                .map(|rs| rs.map(Format1RuleSet::Plain)),
597            Self::Chain(table) => table
598                .chained_seq_rule_sets()
599                .get(index)
600                .map(|rs| rs.map(Format1RuleSet::Chain)),
601            Self::PlainWide(table) => table
602                .seq_rule_sets()
603                .get(index)
604                .map(|rs| rs.map(Format1RuleSet::PlainWide)),
605            Self::ChainWide(table) => table
606                .chained_seq_rule_sets()
607                .get(index)
608                .map(|rs| rs.map(Format1RuleSet::ChainWide)),
609        })
610    }
611}
612
613impl<'a> Format1RuleSet<'a> {
614    pub(crate) fn rules(
615        &self,
616    ) -> impl Iterator<Item = Option<Result<Format1Rule<'a>, ReadError>>> + '_ {
617        let count = match self {
618            Self::Plain(table) => table.seq_rules().len(),
619            Self::Chain(table) => table.chained_seq_rules().len(),
620            Self::PlainWide(table) => table.seq_rules().len(),
621            Self::ChainWide(table) => table.chained_seq_rules().len(),
622        };
623        (0..count).map(move |index| {
624            let rule = match self {
625                Self::Plain(table) => table.seq_rules().get(index).map(Format1Rule::Plain),
626                Self::Chain(table) => table.chained_seq_rules().get(index).map(Format1Rule::Chain),
627                Self::PlainWide(table) => table.seq_rules().get(index).map(Format1Rule::PlainWide),
628                Self::ChainWide(table) => table
629                    .chained_seq_rules()
630                    .get(index)
631                    .map(Format1Rule::ChainWide),
632            };
633            match rule {
634                Err(ReadError::NullOffset) => None,
635                other => Some(other),
636            }
637        })
638    }
639}
640
641impl Format1Rule<'_> {
642    pub(crate) fn input_count(&self) -> usize {
643        match self {
644            Self::Plain(table) => table.input_sequence().len() + 1,
645            Self::Chain(table) => table.input_sequence().len() + 1,
646            Self::PlainWide(table) => table.input_sequence().len() + 1,
647            Self::ChainWide(table) => table.input_sequence().len() + 1,
648        }
649    }
650
651    pub(crate) fn input_glyph(&self, index: usize) -> Option<GlyphId> {
652        match self {
653            Self::Plain(table) => table.input_sequence().get(index).map(|g| g.get().into()),
654            Self::Chain(table) => table.input_sequence().get(index).map(|g| g.get().into()),
655            Self::PlainWide(table) => table.input_sequence().get(index).map(|g| g.get().into()),
656            Self::ChainWide(table) => table.input_sequence().get(index).map(|g| g.get().into()),
657        }
658    }
659
660    pub(crate) fn lookup_records(&self) -> &[SequenceLookupRecord] {
661        match self {
662            Self::Plain(table) => table.seq_lookup_records(),
663            Self::Chain(table) => table.seq_lookup_records(),
664            Self::PlainWide(table) => table.seq_lookup_records(),
665            Self::ChainWide(table) => table.seq_lookup_records(),
666        }
667    }
668}
669
670impl Intersect for &[BigEndian<GlyphId16>] {
671    fn intersects(&self, glyph_set: &IntSet<GlyphId>) -> Result<bool, ReadError> {
672        Ok(self
673            .iter()
674            .all(|g| glyph_set.contains(GlyphId::from(g.get()))))
675    }
676}
677
678impl Intersect for &[BigEndian<GlyphId24>] {
679    fn intersects(&self, glyph_set: &IntSet<GlyphId>) -> Result<bool, ReadError> {
680        Ok(self
681            .iter()
682            .all(|g| glyph_set.contains(GlyphId::from(g.get()))))
683    }
684}
685
686impl Intersect for Format1Rule<'_> {
687    fn intersects(&self, glyph_set: &IntSet<GlyphId>) -> Result<bool, ReadError> {
688        match self {
689            Self::Plain(table) => table.input_sequence().intersects(glyph_set),
690            Self::Chain(table) => Ok(table.backtrack_sequence().intersects(glyph_set)?
691                && table.input_sequence().intersects(glyph_set)?
692                && table.lookahead_sequence().intersects(glyph_set)?),
693            Self::PlainWide(table) => table.input_sequence().intersects(glyph_set),
694            Self::ChainWide(table) => Ok(table.backtrack_sequence().intersects(glyph_set)?
695                && table.input_sequence().intersects(glyph_set)?
696                && table.lookahead_sequence().intersects(glyph_set)?),
697        }
698    }
699}
700
701impl LookupClosure for Format1Rule<'_> {
702    fn closure_lookups(&self, c: &mut LookupClosureCtx, _arg: u16) -> Result<(), ReadError> {
703        if c.lookup_limit_exceed() || !self.intersects(c.glyphs())? {
704            return Ok(());
705        }
706
707        for lookup_record in self.lookup_records() {
708            let index = lookup_record.lookup_list_index();
709            c.recurse(index)?;
710        }
711        Ok(())
712    }
713}
714
715pub(crate) enum ContextFormat2<'a> {
716    Plain(SequenceContextFormat2<'a>),
717    Chain(ChainedSequenceContextFormat2<'a>),
718    PlainWide(SequenceContextFormat5<'a>),
719    ChainWide(ChainedSequenceContextFormat5<'a>),
720}
721
722pub(crate) enum Format2RuleSet<'a> {
723    Plain(ClassSequenceRuleSet<'a>),
724    Chain(ChainedClassSequenceRuleSet<'a>),
725    PlainWide(ClassSequenceRuleSet2<'a>),
726    ChainWide(ChainedClassSequenceRuleSet2<'a>),
727}
728
729pub(crate) enum Format2Rule<'a> {
730    Plain(ClassSequenceRule<'a>),
731    Chain(ChainedClassSequenceRule<'a>),
732}
733
734#[derive(Default)]
735pub(crate) struct SeqCache {
736    input: FastHashMap<u16, bool>,
737    backtrack: FastHashMap<u16, bool>,
738    lookahead: FastHashMap<u16, bool>,
739}
740
741impl<'a> ContextFormat2<'a> {
742    pub(crate) fn coverage(&self) -> Option<Result<CoverageTable<'_>, ReadError>> {
743        match self {
744            ContextFormat2::Plain(table) if !table.coverage_offset().is_null() => {
745                Some(table.coverage())
746            }
747            ContextFormat2::Chain(table) if !table.coverage_offset().is_null() => {
748                Some(table.coverage())
749            }
750            Self::PlainWide(table) if !table.coverage_offset().is_null() => Some(table.coverage()),
751            Self::ChainWide(table) if !table.coverage_offset().is_null() => Some(table.coverage()),
752            _ => None,
753        }
754    }
755
756    pub(crate) fn input_class_def(&self) -> Option<Result<ClassDef<'_>, ReadError>> {
757        match self {
758            ContextFormat2::Plain(table_ref) if !table_ref.class_def_offset().is_null() => {
759                Some(table_ref.class_def())
760            }
761            ContextFormat2::Chain(table_ref) if !table_ref.input_class_def_offset().is_null() => {
762                Some(table_ref.input_class_def())
763            }
764            Self::PlainWide(table) if !table.class_def_offset().is_null() => {
765                Some(table.class_def())
766            }
767            Self::ChainWide(table) if !table.input_class_def_offset().is_null() => {
768                Some(table.input_class_def())
769            }
770            _ => None,
771        }
772    }
773
774    pub(crate) fn backtrack_class_def(&self) -> Option<Result<ClassDef<'_>, ReadError>> {
775        match self {
776            Self::Chain(table) if !table.backtrack_class_def_offset().is_null() => {
777                Some(table.backtrack_class_def())
778            }
779            Self::ChainWide(table) if !table.backtrack_class_def_offset().is_null() => {
780                Some(table.backtrack_class_def())
781            }
782            _ => None,
783        }
784    }
785
786    pub(crate) fn lookahead_class_def(&self) -> Option<Result<ClassDef<'_>, ReadError>> {
787        match self {
788            Self::Chain(table) if !table.lookahead_class_def_offset().is_null() => {
789                Some(table.lookahead_class_def())
790            }
791            Self::ChainWide(table) if !table.lookahead_class_def_offset().is_null() => {
792                Some(table.lookahead_class_def())
793            }
794            _ => None,
795        }
796    }
797
798    pub(crate) fn rule_sets(
799        &self,
800    ) -> impl Iterator<Item = Option<Result<Format2RuleSet<'a>, ReadError>>> + '_ {
801        let count = match self {
802            Self::Plain(table) => table.class_seq_rule_sets().len(),
803            Self::Chain(table) => table.chained_class_seq_rule_sets().len(),
804            Self::PlainWide(table) => table.class_seq_rule_sets().len(),
805            Self::ChainWide(table) => table.chained_class_seq_rule_sets().len(),
806        };
807        (0..count).map(move |index| match self {
808            Self::Plain(table) => table
809                .class_seq_rule_sets()
810                .get(index)
811                .map(|rs| rs.map(Format2RuleSet::Plain)),
812            Self::Chain(table) => table
813                .chained_class_seq_rule_sets()
814                .get(index)
815                .map(|rs| rs.map(Format2RuleSet::Chain)),
816            Self::PlainWide(table) => table
817                .class_seq_rule_sets()
818                .get(index)
819                .map(|rs| rs.map(Format2RuleSet::PlainWide)),
820            Self::ChainWide(table) => table
821                .chained_class_seq_rule_sets()
822                .get(index)
823                .map(|rs| rs.map(Format2RuleSet::ChainWide)),
824        })
825    }
826}
827
828impl<'a> Format2RuleSet<'a> {
829    pub(crate) fn rules(
830        &self,
831    ) -> impl Iterator<Item = Option<Result<Format2Rule<'a>, ReadError>>> + '_ {
832        let count = match self {
833            Self::Plain(table) => table.class_seq_rules().len(),
834            Self::Chain(table) => table.chained_class_seq_rules().len(),
835            Self::PlainWide(table) => table.class_seq_rules().len(),
836            Self::ChainWide(table) => table.chained_class_seq_rules().len(),
837        };
838        (0..count).map(move |index| {
839            let rule = match self {
840                Self::Plain(table) => table.class_seq_rules().get(index).map(Format2Rule::Plain),
841                Self::Chain(table) => table
842                    .chained_class_seq_rules()
843                    .get(index)
844                    .map(Format2Rule::Chain),
845                Self::PlainWide(table) => {
846                    table.class_seq_rules().get(index).map(Format2Rule::Plain)
847                }
848                Self::ChainWide(table) => table
849                    .chained_class_seq_rules()
850                    .get(index)
851                    .map(Format2Rule::Chain),
852            };
853            match rule {
854                Err(ReadError::NullOffset) => None,
855                other => Some(other),
856            }
857        })
858    }
859}
860
861impl Format2Rule<'_> {
862    pub(crate) fn input_sequence(&self) -> &[BigEndian<u16>] {
863        match self {
864            Self::Plain(table) => table.input_sequence(),
865            Self::Chain(table) => table.input_sequence(),
866        }
867    }
868
869    pub(crate) fn lookup_records(&self) -> &[SequenceLookupRecord] {
870        match self {
871            Self::Plain(table) => table.seq_lookup_records(),
872            Self::Chain(table) => table.seq_lookup_records(),
873        }
874    }
875
876    #[allow(clippy::too_many_arguments)]
877    pub(crate) fn intersects(
878        &self,
879        glyphs: &IntSet<GlyphId>,
880        input_class_def: &ClassDef,
881        backtrack_class_def: Option<&ClassDef>,
882        lookahead_class_def: Option<&ClassDef>,
883        seq_cache: &mut SeqCache,
884    ) -> bool {
885        match self {
886            Self::Plain(table) => table.intersects(glyphs, input_class_def, &mut seq_cache.input),
887            Self::Chain(table) => table.intersects(
888                glyphs,
889                input_class_def,
890                backtrack_class_def,
891                lookahead_class_def,
892                seq_cache,
893            ),
894        }
895    }
896}
897
898fn intersects_class(
899    class_def: &ClassDef,
900    glyphs: &IntSet<GlyphId>,
901    class: u16,
902    cache: &mut FastHashMap<u16, bool>,
903) -> bool {
904    *cache
905        .entry(class)
906        .or_insert_with(|| class_def.intersects_class_glyphs(glyphs, u32::from(class)))
907}
908impl ClassSequenceRule<'_> {
909    fn intersects(
910        &self,
911        glyphs: &IntSet<GlyphId>,
912        input_class_def: &ClassDef,
913        cache: &mut FastHashMap<u16, bool>,
914    ) -> bool {
915        self.input_sequence()
916            .iter()
917            .all(|c| intersects_class(input_class_def, glyphs, c.get(), cache))
918    }
919}
920
921impl ChainedClassSequenceRule<'_> {
922    #[allow(clippy::too_many_arguments)]
923    fn intersects(
924        &self,
925        glyphs: &IntSet<GlyphId>,
926        input_class_def: &ClassDef,
927        backtrack_class_def: Option<&ClassDef>,
928        lookahead_class_def: Option<&ClassDef>,
929        seq_cache: &mut SeqCache,
930    ) -> bool {
931        if !self
932            .input_sequence()
933            .iter()
934            .all(|c| intersects_class(input_class_def, glyphs, c.get(), &mut seq_cache.input))
935        {
936            return false;
937        }
938
939        if let Some(backtrack_class_def) = backtrack_class_def {
940            if !self.backtrack_sequence().iter().all(|c| {
941                intersects_class(
942                    backtrack_class_def,
943                    glyphs,
944                    c.get(),
945                    &mut seq_cache.backtrack,
946                )
947            }) {
948                return false;
949            }
950        } else if self.backtrack_glyph_count() != 0 {
951            return false;
952        }
953
954        if let Some(lookahead_class_def) = lookahead_class_def {
955            if !self.lookahead_sequence().iter().all(|c| {
956                intersects_class(
957                    lookahead_class_def,
958                    glyphs,
959                    c.get(),
960                    &mut seq_cache.lookahead,
961                )
962            }) {
963                return false;
964            }
965        } else if self.lookahead_glyph_count() != 0 {
966            return false;
967        }
968        true
969    }
970}
971
972pub(crate) enum ContextFormat3<'a> {
973    Plain(SequenceContextFormat3<'a>),
974    Chain(ChainedSequenceContextFormat3<'a>),
975    PlainWide(SequenceContextFormat6<'a>),
976}
977
978impl ContextFormat3<'_> {
979    pub(crate) fn input_count(&self) -> usize {
980        match self {
981            Self::Plain(table) => table.coverages().len(),
982            Self::Chain(table) => table.input_coverages().len(),
983            Self::PlainWide(table) => table.coverages().len(),
984        }
985    }
986
987    pub(crate) fn coverage(&self, index: usize) -> Result<CoverageTable<'_>, ReadError> {
988        match self {
989            Self::Plain(table) => table.coverages().get(index),
990            Self::Chain(table) => table.input_coverages().get(index),
991            Self::PlainWide(table) => table.coverages().get(index),
992        }
993    }
994
995    pub(crate) fn lookup_records(&self) -> &[SequenceLookupRecord] {
996        match self {
997            ContextFormat3::Plain(table) => table.seq_lookup_records(),
998            ContextFormat3::Chain(table) => table.seq_lookup_records(),
999            ContextFormat3::PlainWide(table) => table.seq_lookup_records(),
1000        }
1001    }
1002
1003    pub(crate) fn matches_glyphs(&self, glyphs: &IntSet<GlyphId>) -> Result<bool, ReadError> {
1004        match self {
1005            Self::Plain(table) => all_coverages_intersect(table.coverages().iter(), glyphs),
1006            Self::PlainWide(table) => all_coverages_intersect(table.coverages().iter(), glyphs),
1007            Self::Chain(table) => {
1008                Ok(
1009                    all_coverages_intersect(table.input_coverages().iter(), glyphs)?
1010                        && all_coverages_intersect(table.backtrack_coverages().iter(), glyphs)?
1011                        && all_coverages_intersect(table.lookahead_coverages().iter(), glyphs)?,
1012                )
1013            }
1014        }
1015    }
1016}
1017
1018/// Returns true if every coverage table intersects `glyphs`.
1019///
1020/// A null offset counts as a coverage that doesn't intersect.
1021fn all_coverages_intersect<'a>(
1022    coverages: impl Iterator<Item = Result<CoverageTable<'a>, ReadError>>,
1023    glyphs: &IntSet<GlyphId>,
1024) -> Result<bool, ReadError> {
1025    for coverage in coverages {
1026        let coverage = match coverage {
1027            Err(ReadError::NullOffset) => return Ok(false),
1028            other => other?,
1029        };
1030        if !coverage.intersects(glyphs) {
1031            return Ok(false);
1032        }
1033    }
1034    Ok(true)
1035}
1036
1037impl Intersect for ContextFormat1<'_> {
1038    fn intersects(&self, glyph_set: &IntSet<GlyphId>) -> Result<bool, ReadError> {
1039        let Some(coverage) = self.coverage().transpose()? else {
1040            return Ok(false);
1041        };
1042        for rule_set in coverage
1043            .iter()
1044            .zip(self.rule_sets())
1045            .filter_map(|(g, rule_set)| rule_set.filter(|_| glyph_set.contains(g)))
1046        {
1047            for rule in rule_set?.rules() {
1048                let Some(rule) = rule.transpose()? else {
1049                    continue;
1050                };
1051                if rule.intersects(glyph_set)? {
1052                    return Ok(true);
1053                }
1054            }
1055        }
1056        Ok(false)
1057    }
1058}
1059
1060impl LookupClosure for ContextFormat1<'_> {
1061    fn closure_lookups(&self, c: &mut LookupClosureCtx, arg: u16) -> Result<(), ReadError> {
1062        let Some(coverage) = self.coverage().transpose()? else {
1063            return Ok(());
1064        };
1065
1066        for (g, rule_set) in coverage
1067            .iter()
1068            .zip(self.rule_sets())
1069            .filter_map(|(g, rule_set)| rule_set.map(|rs| (g, rs)))
1070        {
1071            if !c.glyphs().contains(g) {
1072                continue;
1073            }
1074            if c.lookup_limit_exceed() {
1075                return Ok(());
1076            }
1077            for rule in rule_set?.rules() {
1078                let Some(rule) = rule.transpose()? else {
1079                    continue;
1080                };
1081                rule.closure_lookups(c, arg)?;
1082            }
1083        }
1084
1085        Ok(())
1086    }
1087}
1088
1089impl Intersect for ContextFormat2<'_> {
1090    fn intersects(&self, glyph_set: &IntSet<GlyphId>) -> Result<bool, ReadError> {
1091        let Some(coverage) = self.coverage().transpose()? else {
1092            return Ok(false);
1093        };
1094        if !coverage.intersects(glyph_set) {
1095            return Ok(false);
1096        }
1097        let retained_coverage_glyphs = coverage.intersect_set(glyph_set);
1098
1099        let Some(input_class_def) = self.input_class_def().transpose()? else {
1100            return Ok(false);
1101        };
1102
1103        let backtrack_class_def = self.backtrack_class_def().transpose()?;
1104        let lookahead_class_def = self.lookahead_class_def().transpose()?;
1105
1106        let primary_classes = input_class_def.intersect_classes(&retained_coverage_glyphs);
1107        let mut seq_cache = SeqCache::default();
1108        for rule_set in self.rule_sets().enumerate().filter_map(|(c, rule_set)| {
1109            primary_classes
1110                .contains(c as u32)
1111                .then_some(rule_set)
1112                .flatten()
1113        }) {
1114            for rule in rule_set?.rules() {
1115                let Some(rule) = rule.transpose()? else {
1116                    continue;
1117                };
1118                if rule.intersects(
1119                    glyph_set,
1120                    &input_class_def,
1121                    backtrack_class_def.as_ref(),
1122                    lookahead_class_def.as_ref(),
1123                    &mut seq_cache,
1124                ) {
1125                    return Ok(true);
1126                }
1127            }
1128        }
1129        Ok(false)
1130    }
1131}
1132
1133impl LookupClosure for ContextFormat2<'_> {
1134    fn closure_lookups(&self, c: &mut LookupClosureCtx, _arg: u16) -> Result<(), ReadError> {
1135        let Some(coverage) = self.coverage().transpose()? else {
1136            return Ok(());
1137        };
1138        if !coverage.intersects(c.glyphs()) {
1139            return Ok(());
1140        }
1141        let retained_coverage_glyphs = coverage.intersect_set(c.glyphs());
1142        let Some(input_class_def) = self.input_class_def().transpose()? else {
1143            return Ok(());
1144        };
1145
1146        let backtrack_class_def = self.backtrack_class_def().transpose()?;
1147        let lookahead_class_def = self.lookahead_class_def().transpose()?;
1148
1149        let primary_classes = input_class_def.intersect_classes(&retained_coverage_glyphs);
1150        let mut seq_cache = SeqCache::default();
1151        for rule_set in self.rule_sets().enumerate().filter_map(|(c, rule_set)| {
1152            primary_classes
1153                .contains(c as u32)
1154                .then_some(rule_set)
1155                .flatten()
1156        }) {
1157            if c.lookup_limit_exceed() {
1158                return Ok(());
1159            }
1160
1161            for rule in rule_set?.rules() {
1162                if c.lookup_limit_exceed() {
1163                    return Ok(());
1164                }
1165                let Some(rule) = rule.transpose()? else {
1166                    continue;
1167                };
1168
1169                if !rule.intersects(
1170                    c.glyphs(),
1171                    &input_class_def,
1172                    backtrack_class_def.as_ref(),
1173                    lookahead_class_def.as_ref(),
1174                    &mut seq_cache,
1175                ) {
1176                    continue;
1177                }
1178
1179                for lookup_record in rule.lookup_records() {
1180                    let index = lookup_record.lookup_list_index();
1181                    c.recurse(index)?;
1182                }
1183            }
1184        }
1185        Ok(())
1186    }
1187}
1188
1189impl Intersect for ContextFormat3<'_> {
1190    fn intersects(&self, glyph_set: &IntSet<GlyphId>) -> Result<bool, ReadError> {
1191        self.matches_glyphs(glyph_set)
1192    }
1193}
1194
1195impl LookupClosure for ContextFormat3<'_> {
1196    fn closure_lookups(&self, c: &mut LookupClosureCtx, _arg: u16) -> Result<(), ReadError> {
1197        if !self.intersects(c.glyphs())? {
1198            return Ok(());
1199        }
1200
1201        for lookup_record in self.lookup_records() {
1202            let index = lookup_record.lookup_list_index();
1203            c.recurse(index)?;
1204        }
1205
1206        Ok(())
1207    }
1208}
1209
1210impl Intersect for SequenceContext<'_> {
1211    #[inline]
1212    fn intersects(&self, glyph_set: &IntSet<GlyphId>) -> Result<bool, ReadError> {
1213        match self {
1214            Self::Format1(table) => ContextFormat1::Plain(table.clone()).intersects(glyph_set),
1215            Self::Format2(table) => ContextFormat2::Plain(table.clone()).intersects(glyph_set),
1216            Self::Format5(table) => ContextFormat2::PlainWide(table.clone()).intersects(glyph_set),
1217            Self::Format3(table) => ContextFormat3::Plain(table.clone()).intersects(glyph_set),
1218            Self::Format4(table) => ContextFormat1::PlainWide(table.clone()).intersects(glyph_set),
1219            Self::Format6(table) => ContextFormat3::PlainWide(table.clone()).intersects(glyph_set),
1220        }
1221    }
1222}
1223
1224impl LookupClosure for SequenceContext<'_> {
1225    fn closure_lookups(&self, c: &mut LookupClosureCtx, arg: u16) -> Result<(), ReadError> {
1226        match self {
1227            Self::Format1(table) => ContextFormat1::Plain(table.clone()).closure_lookups(c, arg),
1228            Self::Format2(table) => ContextFormat2::Plain(table.clone()).closure_lookups(c, arg),
1229            Self::Format5(table) => {
1230                ContextFormat2::PlainWide(table.clone()).closure_lookups(c, arg)
1231            }
1232            Self::Format3(table) => ContextFormat3::Plain(table.clone()).closure_lookups(c, arg),
1233            Self::Format4(table) => {
1234                ContextFormat1::PlainWide(table.clone()).closure_lookups(c, arg)
1235            }
1236            Self::Format6(table) => {
1237                ContextFormat3::PlainWide(table.clone()).closure_lookups(c, arg)
1238            }
1239        }
1240    }
1241}
1242
1243impl Intersect for ChainedSequenceContext<'_> {
1244    #[inline]
1245    fn intersects(&self, glyph_set: &IntSet<GlyphId>) -> Result<bool, ReadError> {
1246        match self {
1247            Self::Format1(table) => ContextFormat1::Chain(table.clone()).intersects(glyph_set),
1248            Self::Format2(table) => ContextFormat2::Chain(table.clone()).intersects(glyph_set),
1249            Self::Format5(table) => ContextFormat2::ChainWide(table.clone()).intersects(glyph_set),
1250            Self::Format3(table) => ContextFormat3::Chain(table.clone()).intersects(glyph_set),
1251            Self::Format4(table) => ContextFormat1::ChainWide(table.clone()).intersects(glyph_set),
1252        }
1253    }
1254}
1255
1256impl LookupClosure for ChainedSequenceContext<'_> {
1257    fn closure_lookups(&self, c: &mut LookupClosureCtx, arg: u16) -> Result<(), ReadError> {
1258        match self {
1259            Self::Format1(table) => ContextFormat1::Chain(table.clone()).closure_lookups(c, arg),
1260            Self::Format2(table) => ContextFormat2::Chain(table.clone()).closure_lookups(c, arg),
1261            Self::Format5(table) => {
1262                ContextFormat2::ChainWide(table.clone()).closure_lookups(c, arg)
1263            }
1264            Self::Format3(table) => ContextFormat3::Chain(table.clone()).closure_lookups(c, arg),
1265            Self::Format4(table) => {
1266                ContextFormat1::ChainWide(table.clone()).closure_lookups(c, arg)
1267            }
1268        }
1269    }
1270}
1271
1272#[cfg(test)]
1273mod lookup_variations_tests;
1274
1275#[cfg(test)]
1276mod tests {
1277    use super::*;
1278    use crate::FontData;
1279
1280    #[test]
1281    fn classdef_format1_short_read_no_panic() {
1282        // glyph_count is 5, but only one class value is present.
1283        let classdef = ClassDefFormat1::read(FontData::new(&[0, 1, 0, 10, 0, 5, 0, 1])).unwrap();
1284        let glyphs: IntSet<GlyphId> = [GlyphId::new(14)].into_iter().collect();
1285
1286        assert!(!classdef.intersects(&glyphs).unwrap());
1287    }
1288
1289    #[test]
1290    fn classdef_format2_does_not_alias_wide_glyphs() {
1291        let bytes = [
1292            0, 2, 0, 3, 0, 1, 0, 1, 0, 1, 0, 2, 0, 2, 0, 1, 0, 3, 0, 3, 0, 1,
1293        ];
1294        let classdef = ClassDefFormat2::read(FontData::new(&bytes)).unwrap();
1295        let glyphs: IntSet<GlyphId> = [GlyphId::new(65537)].into_iter().collect();
1296        assert!(!classdef.intersects(&glyphs).unwrap());
1297        assert!(!ClassDef::Format2(classdef).intersects(&glyphs).unwrap());
1298    }
1299}