997d22550547521dd902d712726a1206a38f174a
[platform/upstream/harfbuzz.git] / src / hb-ot-layout-gsubgpos-private.hh
1 /*
2  * Copyright © 2007,2008,2009,2010  Red Hat, Inc.
3  * Copyright © 2010,2012  Google, Inc.
4  *
5  *  This is part of HarfBuzz, a text shaping library.
6  *
7  * Permission is hereby granted, without written agreement and without
8  * license or royalty fees, to use, copy, modify, and distribute this
9  * software and its documentation for any purpose, provided that the
10  * above copyright notice and the following two paragraphs appear in
11  * all copies of this software.
12  *
13  * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
14  * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
15  * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
16  * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
17  * DAMAGE.
18  *
19  * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
20  * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
21  * FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
22  * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
23  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
24  *
25  * Red Hat Author(s): Behdad Esfahbod
26  * Google Author(s): Behdad Esfahbod
27  */
28
29 #ifndef HB_OT_LAYOUT_GSUBGPOS_PRIVATE_HH
30 #define HB_OT_LAYOUT_GSUBGPOS_PRIVATE_HH
31
32 #include "hb-buffer-private.hh"
33 #include "hb-ot-layout-gdef-table.hh"
34 #include "hb-set-private.hh"
35
36
37 namespace OT {
38
39
40 #ifndef HB_DEBUG_CLOSURE
41 #define HB_DEBUG_CLOSURE (HB_DEBUG+0)
42 #endif
43
44 #define TRACE_CLOSURE(this) \
45         hb_auto_trace_t<HB_DEBUG_CLOSURE, hb_void_t> trace \
46         (&c->debug_depth, c->get_name (), this, HB_FUNC, \
47          "");
48
49 struct hb_closure_context_t :
50        hb_dispatch_context_t<hb_closure_context_t, hb_void_t, HB_DEBUG_CLOSURE>
51 {
52   inline const char *get_name (void) { return "CLOSURE"; }
53   typedef return_t (*recurse_func_t) (hb_closure_context_t *c, unsigned int lookup_index);
54   template <typename T>
55   inline return_t dispatch (const T &obj) { obj.closure (this); return HB_VOID; }
56   static return_t default_return_value (void) { return HB_VOID; }
57   bool stop_sublookup_iteration (return_t r HB_UNUSED) const { return false; }
58   return_t recurse (unsigned int lookup_index)
59   {
60     if (unlikely (nesting_level_left == 0 || !recurse_func))
61       return default_return_value ();
62
63     nesting_level_left--;
64     recurse_func (this, lookup_index);
65     nesting_level_left++;
66     return HB_VOID;
67   }
68
69   hb_face_t *face;
70   hb_set_t *glyphs;
71   recurse_func_t recurse_func;
72   unsigned int nesting_level_left;
73   unsigned int debug_depth;
74
75   hb_closure_context_t (hb_face_t *face_,
76                         hb_set_t *glyphs_,
77                         unsigned int nesting_level_left_ = HB_MAX_NESTING_LEVEL) :
78                           face (face_),
79                           glyphs (glyphs_),
80                           recurse_func (NULL),
81                           nesting_level_left (nesting_level_left_),
82                           debug_depth (0) {}
83
84   void set_recurse_func (recurse_func_t func) { recurse_func = func; }
85 };
86
87
88
89 #ifndef HB_DEBUG_WOULD_APPLY
90 #define HB_DEBUG_WOULD_APPLY (HB_DEBUG+0)
91 #endif
92
93 #define TRACE_WOULD_APPLY(this) \
94         hb_auto_trace_t<HB_DEBUG_WOULD_APPLY, bool> trace \
95         (&c->debug_depth, c->get_name (), this, HB_FUNC, \
96          "%d glyphs", c->len);
97
98 struct hb_would_apply_context_t :
99        hb_dispatch_context_t<hb_would_apply_context_t, bool, HB_DEBUG_WOULD_APPLY>
100 {
101   inline const char *get_name (void) { return "WOULD_APPLY"; }
102   template <typename T>
103   inline return_t dispatch (const T &obj) { return obj.would_apply (this); }
104   static return_t default_return_value (void) { return false; }
105   bool stop_sublookup_iteration (return_t r) const { return r; }
106
107   hb_face_t *face;
108   const hb_codepoint_t *glyphs;
109   unsigned int len;
110   bool zero_context;
111   unsigned int debug_depth;
112
113   hb_would_apply_context_t (hb_face_t *face_,
114                             const hb_codepoint_t *glyphs_,
115                             unsigned int len_,
116                             bool zero_context_) :
117                               face (face_),
118                               glyphs (glyphs_),
119                               len (len_),
120                               zero_context (zero_context_),
121                               debug_depth (0) {}
122 };
123
124
125
126 #ifndef HB_DEBUG_COLLECT_GLYPHS
127 #define HB_DEBUG_COLLECT_GLYPHS (HB_DEBUG+0)
128 #endif
129
130 #define TRACE_COLLECT_GLYPHS(this) \
131         hb_auto_trace_t<HB_DEBUG_COLLECT_GLYPHS, hb_void_t> trace \
132         (&c->debug_depth, c->get_name (), this, HB_FUNC, \
133          "");
134
135 struct hb_collect_glyphs_context_t :
136        hb_dispatch_context_t<hb_collect_glyphs_context_t, hb_void_t, HB_DEBUG_COLLECT_GLYPHS>
137 {
138   inline const char *get_name (void) { return "COLLECT_GLYPHS"; }
139   typedef return_t (*recurse_func_t) (hb_collect_glyphs_context_t *c, unsigned int lookup_index);
140   template <typename T>
141   inline return_t dispatch (const T &obj) { obj.collect_glyphs (this); return HB_VOID; }
142   static return_t default_return_value (void) { return HB_VOID; }
143   bool stop_sublookup_iteration (return_t r HB_UNUSED) const { return false; }
144   return_t recurse (unsigned int lookup_index)
145   {
146     if (unlikely (nesting_level_left == 0 || !recurse_func))
147       return default_return_value ();
148
149     /* Note that GPOS sets recurse_func to NULL already, so it doesn't get
150      * past the previous check.  For GSUB, we only want to collect the output
151      * glyphs in the recursion.  If output is not requested, we can go home now.
152      *
153      * Note further, that the above is not exactly correct.  A recursed lookup
154      * is allowed to match input that is not matched in the context, but that's
155      * not how most fonts are built.  It's possible to relax that and recurse
156      * with all sets here if it proves to be an issue.
157      */
158
159     if (output == hb_set_get_empty ())
160       return HB_VOID;
161
162     /* Return if new lookup was recursed to before. */
163     if (recursed_lookups.has (lookup_index))
164       return HB_VOID;
165
166     hb_set_t *old_before = before;
167     hb_set_t *old_input  = input;
168     hb_set_t *old_after  = after;
169     before = input = after = hb_set_get_empty ();
170
171     nesting_level_left--;
172     recurse_func (this, lookup_index);
173     nesting_level_left++;
174
175     before = old_before;
176     input  = old_input;
177     after  = old_after;
178
179     recursed_lookups.add (lookup_index);
180
181     return HB_VOID;
182   }
183
184   hb_face_t *face;
185   hb_set_t *before;
186   hb_set_t *input;
187   hb_set_t *after;
188   hb_set_t *output;
189   recurse_func_t recurse_func;
190   hb_set_t recursed_lookups;
191   unsigned int nesting_level_left;
192   unsigned int debug_depth;
193
194   hb_collect_glyphs_context_t (hb_face_t *face_,
195                                hb_set_t  *glyphs_before, /* OUT. May be NULL */
196                                hb_set_t  *glyphs_input,  /* OUT. May be NULL */
197                                hb_set_t  *glyphs_after,  /* OUT. May be NULL */
198                                hb_set_t  *glyphs_output, /* OUT. May be NULL */
199                                unsigned int nesting_level_left_ = HB_MAX_NESTING_LEVEL) :
200                               face (face_),
201                               before (glyphs_before ? glyphs_before : hb_set_get_empty ()),
202                               input  (glyphs_input  ? glyphs_input  : hb_set_get_empty ()),
203                               after  (glyphs_after  ? glyphs_after  : hb_set_get_empty ()),
204                               output (glyphs_output ? glyphs_output : hb_set_get_empty ()),
205                               recurse_func (NULL),
206                               recursed_lookups (),
207                               nesting_level_left (nesting_level_left_),
208                               debug_depth (0)
209   {
210     recursed_lookups.init ();
211   }
212   ~hb_collect_glyphs_context_t (void)
213   {
214     recursed_lookups.fini ();
215   }
216
217   void set_recurse_func (recurse_func_t func) { recurse_func = func; }
218 };
219
220
221
222 #ifndef HB_DEBUG_GET_COVERAGE
223 #define HB_DEBUG_GET_COVERAGE (HB_DEBUG+0)
224 #endif
225
226 /* XXX Can we remove this? */
227
228 template <typename set_t>
229 struct hb_add_coverage_context_t :
230        hb_dispatch_context_t<hb_add_coverage_context_t<set_t>, const Coverage &, HB_DEBUG_GET_COVERAGE>
231 {
232   inline const char *get_name (void) { return "GET_COVERAGE"; }
233   typedef const Coverage &return_t;
234   template <typename T>
235   inline return_t dispatch (const T &obj) { return obj.get_coverage (); }
236   static return_t default_return_value (void) { return Null(Coverage); }
237   bool stop_sublookup_iteration (return_t r) const
238   {
239     r.add_coverage (set);
240     return false;
241   }
242
243   hb_add_coverage_context_t (set_t *set_) :
244                             set (set_),
245                             debug_depth (0) {}
246
247   set_t *set;
248   unsigned int debug_depth;
249 };
250
251
252
253 #ifndef HB_DEBUG_APPLY
254 #define HB_DEBUG_APPLY (HB_DEBUG+0)
255 #endif
256
257 #define TRACE_APPLY(this) \
258         hb_auto_trace_t<HB_DEBUG_APPLY, bool> trace \
259         (&c->debug_depth, c->get_name (), this, HB_FUNC, \
260          "idx %d gid %u lookup %d", \
261          c->buffer->idx, c->buffer->cur().codepoint, (int) c->lookup_index);
262
263 struct hb_apply_context_t :
264        hb_dispatch_context_t<hb_apply_context_t, bool, HB_DEBUG_APPLY>
265 {
266   struct matcher_t
267   {
268     inline matcher_t (void) :
269              lookup_props (0),
270              ignore_zwnj (false),
271              ignore_zwj (false),
272              mask (-1),
273 #define arg1(arg) (arg) /* Remove the macro to see why it's needed! */
274              syllable arg1(0),
275 #undef arg1
276              match_func (NULL),
277              match_data (NULL) {};
278
279     typedef bool (*match_func_t) (hb_codepoint_t glyph_id, const USHORT &value, const void *data);
280
281     inline void set_ignore_zwnj (bool ignore_zwnj_) { ignore_zwnj = ignore_zwnj_; }
282     inline void set_ignore_zwj (bool ignore_zwj_) { ignore_zwj = ignore_zwj_; }
283     inline void set_lookup_props (unsigned int lookup_props_) { lookup_props = lookup_props_; }
284     inline void set_mask (hb_mask_t mask_) { mask = mask_; }
285     inline void set_syllable (uint8_t syllable_)  { syllable = syllable_; }
286     inline void set_match_func (match_func_t match_func_,
287                                 const void *match_data_)
288     { match_func = match_func_; match_data = match_data_; }
289
290     enum may_match_t {
291       MATCH_NO,
292       MATCH_YES,
293       MATCH_MAYBE
294     };
295
296     inline may_match_t may_match (const hb_glyph_info_t &info,
297                                   const USHORT          *glyph_data) const
298     {
299       if (!(info.mask & mask) ||
300           (syllable && syllable != info.syllable ()))
301         return MATCH_NO;
302
303       if (match_func)
304         return match_func (info.codepoint, *glyph_data, match_data) ? MATCH_YES : MATCH_NO;
305
306       return MATCH_MAYBE;
307     }
308
309     enum may_skip_t {
310       SKIP_NO,
311       SKIP_YES,
312       SKIP_MAYBE
313     };
314
315     inline may_skip_t
316     may_skip (const hb_apply_context_t *c,
317               const hb_glyph_info_t    &info) const
318     {
319       if (!c->check_glyph_property (&info, lookup_props))
320         return SKIP_YES;
321
322       if (unlikely (_hb_glyph_info_is_default_ignorable_and_not_fvs (&info) &&
323                     (ignore_zwnj || !_hb_glyph_info_is_zwnj (&info)) &&
324                     (ignore_zwj || !_hb_glyph_info_is_zwj (&info))))
325         return SKIP_MAYBE;
326
327       return SKIP_NO;
328     }
329
330     protected:
331     unsigned int lookup_props;
332     bool ignore_zwnj;
333     bool ignore_zwj;
334     hb_mask_t mask;
335     uint8_t syllable;
336     match_func_t match_func;
337     const void *match_data;
338   };
339
340   struct skipping_iterator_t
341   {
342     inline void init (hb_apply_context_t *c_, bool context_match = false)
343     {
344       c = c_;
345       match_glyph_data = NULL,
346       matcher.set_match_func (NULL, NULL);
347       matcher.set_lookup_props (c->lookup_props);
348       /* Ignore ZWNJ if we are matching GSUB context, or matching GPOS. */
349       matcher.set_ignore_zwnj (context_match || c->table_index == 1);
350       /* Ignore ZWJ if we are matching GSUB context, or matching GPOS, or if asked to. */
351       matcher.set_ignore_zwj (context_match || c->table_index == 1 || c->auto_zwj);
352       matcher.set_mask (context_match ? -1 : c->lookup_mask);
353     }
354     inline void set_lookup_props (unsigned int lookup_props)
355     {
356       matcher.set_lookup_props (lookup_props);
357     }
358     inline void set_match_func (matcher_t::match_func_t match_func_,
359                                 const void *match_data_,
360                                 const USHORT glyph_data[])
361     {
362       matcher.set_match_func (match_func_, match_data_);
363       match_glyph_data = glyph_data;
364     }
365
366     inline void reset (unsigned int start_index_,
367                        unsigned int num_items_)
368     {
369       idx = start_index_;
370       num_items = num_items_;
371       end = c->buffer->len;
372       matcher.set_syllable (start_index_ == c->buffer->idx ? c->buffer->cur().syllable () : 0);
373     }
374
375     inline void reject (void) { num_items++; match_glyph_data--; }
376
377     inline bool next (void)
378     {
379       assert (num_items > 0);
380       while (idx + num_items < end)
381       {
382         idx++;
383         const hb_glyph_info_t &info = c->buffer->info[idx];
384
385         matcher_t::may_skip_t skip = matcher.may_skip (c, info);
386         if (unlikely (skip == matcher_t::SKIP_YES))
387           continue;
388
389         matcher_t::may_match_t match = matcher.may_match (info, match_glyph_data);
390         if (match == matcher_t::MATCH_YES ||
391             (match == matcher_t::MATCH_MAYBE &&
392              skip == matcher_t::SKIP_NO))
393         {
394           num_items--;
395           match_glyph_data++;
396           return true;
397         }
398
399         if (skip == matcher_t::SKIP_NO)
400           return false;
401       }
402       return false;
403     }
404     inline bool prev (void)
405     {
406       assert (num_items > 0);
407       while (idx >= num_items)
408       {
409         idx--;
410         const hb_glyph_info_t &info = c->buffer->out_info[idx];
411
412         matcher_t::may_skip_t skip = matcher.may_skip (c, info);
413         if (unlikely (skip == matcher_t::SKIP_YES))
414           continue;
415
416         matcher_t::may_match_t match = matcher.may_match (info, match_glyph_data);
417         if (match == matcher_t::MATCH_YES ||
418             (match == matcher_t::MATCH_MAYBE &&
419              skip == matcher_t::SKIP_NO))
420         {
421           num_items--;
422           match_glyph_data++;
423           return true;
424         }
425
426         if (skip == matcher_t::SKIP_NO)
427           return false;
428       }
429       return false;
430     }
431
432     unsigned int idx;
433     protected:
434     hb_apply_context_t *c;
435     matcher_t matcher;
436     const USHORT *match_glyph_data;
437
438     unsigned int num_items;
439     unsigned int end;
440   };
441
442
443   inline const char *get_name (void) { return "APPLY"; }
444   typedef return_t (*recurse_func_t) (hb_apply_context_t *c, unsigned int lookup_index);
445   template <typename T>
446   inline return_t dispatch (const T &obj) { return obj.apply (this); }
447   static return_t default_return_value (void) { return false; }
448   bool stop_sublookup_iteration (return_t r) const { return r; }
449   return_t recurse (unsigned int lookup_index)
450   {
451     if (unlikely (nesting_level_left == 0 || !recurse_func))
452       return default_return_value ();
453
454     nesting_level_left--;
455     bool ret = recurse_func (this, lookup_index);
456     nesting_level_left++;
457     return ret;
458   }
459
460   unsigned int table_index; /* GSUB/GPOS */
461   hb_font_t *font;
462   hb_face_t *face;
463   hb_buffer_t *buffer;
464   hb_direction_t direction;
465   hb_mask_t lookup_mask;
466   bool auto_zwj;
467   recurse_func_t recurse_func;
468   unsigned int nesting_level_left;
469   unsigned int lookup_props;
470   const GDEF &gdef;
471   bool has_glyph_classes;
472   skipping_iterator_t iter_input, iter_context;
473   unsigned int lookup_index;
474   unsigned int debug_depth;
475
476
477   hb_apply_context_t (unsigned int table_index_,
478                       hb_font_t *font_,
479                       hb_buffer_t *buffer_) :
480                         table_index (table_index_),
481                         font (font_), face (font->face), buffer (buffer_),
482                         direction (buffer_->props.direction),
483                         lookup_mask (1),
484                         auto_zwj (true),
485                         recurse_func (NULL),
486                         nesting_level_left (HB_MAX_NESTING_LEVEL),
487                         lookup_props (0),
488                         gdef (*hb_ot_layout_from_face (face)->gdef),
489                         has_glyph_classes (gdef.has_glyph_classes ()),
490                         iter_input (),
491                         iter_context (),
492                         lookup_index ((unsigned int) -1),
493                         debug_depth (0) {}
494
495   inline void set_lookup_mask (hb_mask_t mask) { lookup_mask = mask; }
496   inline void set_auto_zwj (bool auto_zwj_) { auto_zwj = auto_zwj_; }
497   inline void set_recurse_func (recurse_func_t func) { recurse_func = func; }
498   inline void set_lookup_index (unsigned int lookup_index_) { lookup_index = lookup_index_; }
499   inline void set_lookup_props (unsigned int lookup_props_)
500   {
501     lookup_props = lookup_props_;
502     iter_input.init (this, false);
503     iter_context.init (this, true);
504   }
505
506   inline bool
507   match_properties_mark (hb_codepoint_t  glyph,
508                          unsigned int    glyph_props,
509                          unsigned int    match_props) const
510   {
511     /* If using mark filtering sets, the high short of
512      * match_props has the set index.
513      */
514     if (match_props & LookupFlag::UseMarkFilteringSet)
515       return gdef.mark_set_covers (match_props >> 16, glyph);
516
517     /* The second byte of match_props has the meaning
518      * "ignore marks of attachment type different than
519      * the attachment type specified."
520      */
521     if (match_props & LookupFlag::MarkAttachmentType)
522       return (match_props & LookupFlag::MarkAttachmentType) == (glyph_props & LookupFlag::MarkAttachmentType);
523
524     return true;
525   }
526
527   inline bool
528   check_glyph_property (const hb_glyph_info_t *info,
529                         unsigned int  match_props) const
530   {
531     hb_codepoint_t glyph = info->codepoint;
532     unsigned int glyph_props = _hb_glyph_info_get_glyph_props (info);
533
534     /* Not covered, if, for example, glyph class is ligature and
535      * match_props includes LookupFlags::IgnoreLigatures
536      */
537     if (glyph_props & match_props & LookupFlag::IgnoreFlags)
538       return false;
539
540     if (unlikely (glyph_props & HB_OT_LAYOUT_GLYPH_PROPS_MARK))
541       return match_properties_mark (glyph, glyph_props, match_props);
542
543     return true;
544   }
545
546   inline void _set_glyph_props (hb_codepoint_t glyph_index,
547                           unsigned int class_guess = 0,
548                           bool ligature = false,
549                           bool component = false) const
550   {
551     unsigned int add_in = _hb_glyph_info_get_glyph_props (&buffer->cur()) &
552                           HB_OT_LAYOUT_GLYPH_PROPS_PRESERVE;
553     add_in |= HB_OT_LAYOUT_GLYPH_PROPS_SUBSTITUTED;
554     if (ligature)
555     {
556       add_in |= HB_OT_LAYOUT_GLYPH_PROPS_LIGATED;
557       /* In the only place that the MULTIPLIED bit is used, Uniscribe
558        * seems to only care about the "last" transformation between
559        * Ligature and Multiple substitions.  Ie. if you ligate, expand,
560        * and ligate again, it forgives the multiplication and acts as
561        * if only ligation happened.  As such, clear MULTIPLIED bit.
562        */
563       add_in &= ~HB_OT_LAYOUT_GLYPH_PROPS_MULTIPLIED;
564     }
565     if (component)
566       add_in |= HB_OT_LAYOUT_GLYPH_PROPS_MULTIPLIED;
567     if (likely (has_glyph_classes))
568       _hb_glyph_info_set_glyph_props (&buffer->cur(), add_in | gdef.get_glyph_props (glyph_index));
569     else if (class_guess)
570       _hb_glyph_info_set_glyph_props (&buffer->cur(), add_in | class_guess);
571   }
572
573   inline void replace_glyph (hb_codepoint_t glyph_index) const
574   {
575     _set_glyph_props (glyph_index);
576     buffer->replace_glyph (glyph_index);
577   }
578   inline void replace_glyph_inplace (hb_codepoint_t glyph_index) const
579   {
580     _set_glyph_props (glyph_index);
581     buffer->cur().codepoint = glyph_index;
582   }
583   inline void replace_glyph_with_ligature (hb_codepoint_t glyph_index,
584                                            unsigned int class_guess) const
585   {
586     _set_glyph_props (glyph_index, class_guess, true);
587     buffer->replace_glyph (glyph_index);
588   }
589   inline void output_glyph_for_component (hb_codepoint_t glyph_index,
590                                           unsigned int class_guess) const
591   {
592     _set_glyph_props (glyph_index, class_guess, false, true);
593     buffer->output_glyph (glyph_index);
594   }
595 };
596
597
598
599 typedef bool (*intersects_func_t) (hb_set_t *glyphs, const USHORT &value, const void *data);
600 typedef void (*collect_glyphs_func_t) (hb_set_t *glyphs, const USHORT &value, const void *data);
601 typedef bool (*match_func_t) (hb_codepoint_t glyph_id, const USHORT &value, const void *data);
602
603 struct ContextClosureFuncs
604 {
605   intersects_func_t intersects;
606 };
607 struct ContextCollectGlyphsFuncs
608 {
609   collect_glyphs_func_t collect;
610 };
611 struct ContextApplyFuncs
612 {
613   match_func_t match;
614 };
615
616
617 static inline bool intersects_glyph (hb_set_t *glyphs, const USHORT &value, const void *data HB_UNUSED)
618 {
619   return glyphs->has (value);
620 }
621 static inline bool intersects_class (hb_set_t *glyphs, const USHORT &value, const void *data)
622 {
623   const ClassDef &class_def = *reinterpret_cast<const ClassDef *>(data);
624   return class_def.intersects_class (glyphs, value);
625 }
626 static inline bool intersects_coverage (hb_set_t *glyphs, const USHORT &value, const void *data)
627 {
628   const OffsetTo<Coverage> &coverage = (const OffsetTo<Coverage>&)value;
629   return (data+coverage).intersects (glyphs);
630 }
631
632 static inline bool intersects_array (hb_closure_context_t *c,
633                                      unsigned int count,
634                                      const USHORT values[],
635                                      intersects_func_t intersects_func,
636                                      const void *intersects_data)
637 {
638   for (unsigned int i = 0; i < count; i++)
639     if (likely (!intersects_func (c->glyphs, values[i], intersects_data)))
640       return false;
641   return true;
642 }
643
644
645 static inline void collect_glyph (hb_set_t *glyphs, const USHORT &value, const void *data HB_UNUSED)
646 {
647   glyphs->add (value);
648 }
649 static inline void collect_class (hb_set_t *glyphs, const USHORT &value, const void *data)
650 {
651   const ClassDef &class_def = *reinterpret_cast<const ClassDef *>(data);
652   class_def.add_class (glyphs, value);
653 }
654 static inline void collect_coverage (hb_set_t *glyphs, const USHORT &value, const void *data)
655 {
656   const OffsetTo<Coverage> &coverage = (const OffsetTo<Coverage>&)value;
657   (data+coverage).add_coverage (glyphs);
658 }
659 static inline void collect_array (hb_collect_glyphs_context_t *c HB_UNUSED,
660                                   hb_set_t *glyphs,
661                                   unsigned int count,
662                                   const USHORT values[],
663                                   collect_glyphs_func_t collect_func,
664                                   const void *collect_data)
665 {
666   for (unsigned int i = 0; i < count; i++)
667     collect_func (glyphs, values[i], collect_data);
668 }
669
670
671 static inline bool match_glyph (hb_codepoint_t glyph_id, const USHORT &value, const void *data HB_UNUSED)
672 {
673   return glyph_id == value;
674 }
675 static inline bool match_class (hb_codepoint_t glyph_id, const USHORT &value, const void *data)
676 {
677   const ClassDef &class_def = *reinterpret_cast<const ClassDef *>(data);
678   return class_def.get_class (glyph_id) == value;
679 }
680 static inline bool match_coverage (hb_codepoint_t glyph_id, const USHORT &value, const void *data)
681 {
682   const OffsetTo<Coverage> &coverage = (const OffsetTo<Coverage>&)value;
683   return (data+coverage).get_coverage (glyph_id) != NOT_COVERED;
684 }
685
686 static inline bool would_match_input (hb_would_apply_context_t *c,
687                                       unsigned int count, /* Including the first glyph (not matched) */
688                                       const USHORT input[], /* Array of input values--start with second glyph */
689                                       match_func_t match_func,
690                                       const void *match_data)
691 {
692   if (count != c->len)
693     return false;
694
695   for (unsigned int i = 1; i < count; i++)
696     if (likely (!match_func (c->glyphs[i], input[i - 1], match_data)))
697       return false;
698
699   return true;
700 }
701 static inline bool match_input (hb_apply_context_t *c,
702                                 unsigned int count, /* Including the first glyph (not matched) */
703                                 const USHORT input[], /* Array of input values--start with second glyph */
704                                 match_func_t match_func,
705                                 const void *match_data,
706                                 unsigned int *end_offset,
707                                 unsigned int match_positions[HB_MAX_CONTEXT_LENGTH],
708                                 bool *p_is_mark_ligature = NULL,
709                                 unsigned int *p_total_component_count = NULL)
710 {
711   TRACE_APPLY (NULL);
712
713   if (unlikely (count > HB_MAX_CONTEXT_LENGTH)) return_trace (false);
714
715   hb_buffer_t *buffer = c->buffer;
716
717   hb_apply_context_t::skipping_iterator_t &skippy_iter = c->iter_input;
718   skippy_iter.reset (buffer->idx, count - 1);
719   skippy_iter.set_match_func (match_func, match_data, input);
720
721   /*
722    * This is perhaps the trickiest part of OpenType...  Remarks:
723    *
724    * - If all components of the ligature were marks, we call this a mark ligature.
725    *
726    * - If there is no GDEF, and the ligature is NOT a mark ligature, we categorize
727    *   it as a ligature glyph.
728    *
729    * - Ligatures cannot be formed across glyphs attached to different components
730    *   of previous ligatures.  Eg. the sequence is LAM,SHADDA,LAM,FATHA,HEH, and
731    *   LAM,LAM,HEH form a ligature, leaving SHADDA,FATHA next to eachother.
732    *   However, it would be wrong to ligate that SHADDA,FATHA sequence.o
733    *   There is an exception to this: If a ligature tries ligating with marks that
734    *   belong to it itself, go ahead, assuming that the font designer knows what
735    *   they are doing (otherwise it can break Indic stuff when a matra wants to
736    *   ligate with a conjunct...)
737    */
738
739   bool is_mark_ligature = _hb_glyph_info_is_mark (&buffer->cur());
740
741   unsigned int total_component_count = 0;
742   total_component_count += _hb_glyph_info_get_lig_num_comps (&buffer->cur());
743
744   unsigned int first_lig_id = _hb_glyph_info_get_lig_id (&buffer->cur());
745   unsigned int first_lig_comp = _hb_glyph_info_get_lig_comp (&buffer->cur());
746
747   match_positions[0] = buffer->idx;
748   for (unsigned int i = 1; i < count; i++)
749   {
750     if (!skippy_iter.next ()) return_trace (false);
751
752     match_positions[i] = skippy_iter.idx;
753
754     unsigned int this_lig_id = _hb_glyph_info_get_lig_id (&buffer->info[skippy_iter.idx]);
755     unsigned int this_lig_comp = _hb_glyph_info_get_lig_comp (&buffer->info[skippy_iter.idx]);
756
757     if (first_lig_id && first_lig_comp) {
758       /* If first component was attached to a previous ligature component,
759        * all subsequent components should be attached to the same ligature
760        * component, otherwise we shouldn't ligate them. */
761       if (first_lig_id != this_lig_id || first_lig_comp != this_lig_comp)
762         return_trace (false);
763     } else {
764       /* If first component was NOT attached to a previous ligature component,
765        * all subsequent components should also NOT be attached to any ligature
766        * component, unless they are attached to the first component itself! */
767       if (this_lig_id && this_lig_comp && (this_lig_id != first_lig_id))
768         return_trace (false);
769     }
770
771     is_mark_ligature = is_mark_ligature && _hb_glyph_info_is_mark (&buffer->info[skippy_iter.idx]);
772     total_component_count += _hb_glyph_info_get_lig_num_comps (&buffer->info[skippy_iter.idx]);
773   }
774
775   *end_offset = skippy_iter.idx - buffer->idx + 1;
776
777   if (p_is_mark_ligature)
778     *p_is_mark_ligature = is_mark_ligature;
779
780   if (p_total_component_count)
781     *p_total_component_count = total_component_count;
782
783   return_trace (true);
784 }
785 static inline bool ligate_input (hb_apply_context_t *c,
786                                  unsigned int count, /* Including the first glyph */
787                                  unsigned int match_positions[HB_MAX_CONTEXT_LENGTH], /* Including the first glyph */
788                                  unsigned int match_length,
789                                  hb_codepoint_t lig_glyph,
790                                  bool is_mark_ligature,
791                                  unsigned int total_component_count)
792 {
793   TRACE_APPLY (NULL);
794
795   hb_buffer_t *buffer = c->buffer;
796
797   buffer->merge_clusters (buffer->idx, buffer->idx + match_length);
798
799   /*
800    * - If it *is* a mark ligature, we don't allocate a new ligature id, and leave
801    *   the ligature to keep its old ligature id.  This will allow it to attach to
802    *   a base ligature in GPOS.  Eg. if the sequence is: LAM,LAM,SHADDA,FATHA,HEH,
803    *   and LAM,LAM,HEH for a ligature, they will leave SHADDA and FATHA wit a
804    *   ligature id and component value of 2.  Then if SHADDA,FATHA form a ligature
805    *   later, we don't want them to lose their ligature id/component, otherwise
806    *   GPOS will fail to correctly position the mark ligature on top of the
807    *   LAM,LAM,HEH ligature.  See:
808    *     https://bugzilla.gnome.org/show_bug.cgi?id=676343
809    *
810    * - If a ligature is formed of components that some of which are also ligatures
811    *   themselves, and those ligature components had marks attached to *their*
812    *   components, we have to attach the marks to the new ligature component
813    *   positions!  Now *that*'s tricky!  And these marks may be following the
814    *   last component of the whole sequence, so we should loop forward looking
815    *   for them and update them.
816    *
817    *   Eg. the sequence is LAM,LAM,SHADDA,FATHA,HEH, and the font first forms a
818    *   'calt' ligature of LAM,HEH, leaving the SHADDA and FATHA with a ligature
819    *   id and component == 1.  Now, during 'liga', the LAM and the LAM-HEH ligature
820    *   form a LAM-LAM-HEH ligature.  We need to reassign the SHADDA and FATHA to
821    *   the new ligature with a component value of 2.
822    *
823    *   This in fact happened to a font...  See:
824    *   https://bugzilla.gnome.org/show_bug.cgi?id=437633
825    */
826
827   unsigned int klass = is_mark_ligature ? 0 : HB_OT_LAYOUT_GLYPH_PROPS_LIGATURE;
828   unsigned int lig_id = is_mark_ligature ? 0 : _hb_allocate_lig_id (buffer);
829   unsigned int last_lig_id = _hb_glyph_info_get_lig_id (&buffer->cur());
830   unsigned int last_num_components = _hb_glyph_info_get_lig_num_comps (&buffer->cur());
831   unsigned int components_so_far = last_num_components;
832
833   if (!is_mark_ligature)
834   {
835     _hb_glyph_info_set_lig_props_for_ligature (&buffer->cur(), lig_id, total_component_count);
836     if (_hb_glyph_info_get_general_category (&buffer->cur()) == HB_UNICODE_GENERAL_CATEGORY_NON_SPACING_MARK)
837     {
838       _hb_glyph_info_set_general_category (&buffer->cur(), HB_UNICODE_GENERAL_CATEGORY_OTHER_LETTER);
839     }
840   }
841   c->replace_glyph_with_ligature (lig_glyph, klass);
842
843   for (unsigned int i = 1; i < count; i++)
844   {
845     while (buffer->idx < match_positions[i] && !buffer->in_error)
846     {
847       if (!is_mark_ligature) {
848         unsigned int this_comp = _hb_glyph_info_get_lig_comp (&buffer->cur());
849         if (this_comp == 0)
850           this_comp = last_num_components;
851         unsigned int new_lig_comp = components_so_far - last_num_components +
852                                     MIN (this_comp, last_num_components);
853           _hb_glyph_info_set_lig_props_for_mark (&buffer->cur(), lig_id, new_lig_comp);
854       }
855       buffer->next_glyph ();
856     }
857
858     last_lig_id = _hb_glyph_info_get_lig_id (&buffer->cur());
859     last_num_components = _hb_glyph_info_get_lig_num_comps (&buffer->cur());
860     components_so_far += last_num_components;
861
862     /* Skip the base glyph */
863     buffer->idx++;
864   }
865
866   if (!is_mark_ligature && last_lig_id) {
867     /* Re-adjust components for any marks following. */
868     for (unsigned int i = buffer->idx; i < buffer->len; i++) {
869       if (last_lig_id == _hb_glyph_info_get_lig_id (&buffer->info[i])) {
870         unsigned int this_comp = _hb_glyph_info_get_lig_comp (&buffer->info[i]);
871         if (!this_comp)
872           break;
873         unsigned int new_lig_comp = components_so_far - last_num_components +
874                                     MIN (this_comp, last_num_components);
875         _hb_glyph_info_set_lig_props_for_mark (&buffer->info[i], lig_id, new_lig_comp);
876       } else
877         break;
878     }
879   }
880   return_trace (true);
881 }
882
883 static inline bool match_backtrack (hb_apply_context_t *c,
884                                     unsigned int count,
885                                     const USHORT backtrack[],
886                                     match_func_t match_func,
887                                     const void *match_data)
888 {
889   TRACE_APPLY (NULL);
890
891   hb_apply_context_t::skipping_iterator_t &skippy_iter = c->iter_context;
892   skippy_iter.reset (c->buffer->backtrack_len (), count);
893   skippy_iter.set_match_func (match_func, match_data, backtrack);
894
895   for (unsigned int i = 0; i < count; i++)
896     if (!skippy_iter.prev ())
897       return_trace (false);
898
899   return_trace (true);
900 }
901
902 static inline bool match_lookahead (hb_apply_context_t *c,
903                                     unsigned int count,
904                                     const USHORT lookahead[],
905                                     match_func_t match_func,
906                                     const void *match_data,
907                                     unsigned int offset)
908 {
909   TRACE_APPLY (NULL);
910
911   hb_apply_context_t::skipping_iterator_t &skippy_iter = c->iter_context;
912   skippy_iter.reset (c->buffer->idx + offset - 1, count);
913   skippy_iter.set_match_func (match_func, match_data, lookahead);
914
915   for (unsigned int i = 0; i < count; i++)
916     if (!skippy_iter.next ())
917       return_trace (false);
918
919   return_trace (true);
920 }
921
922
923
924 struct LookupRecord
925 {
926   inline bool sanitize (hb_sanitize_context_t *c) const
927   {
928     TRACE_SANITIZE (this);
929     return_trace (c->check_struct (this));
930   }
931
932   USHORT        sequenceIndex;          /* Index into current glyph
933                                          * sequence--first glyph = 0 */
934   USHORT        lookupListIndex;        /* Lookup to apply to that
935                                          * position--zero--based */
936   public:
937   DEFINE_SIZE_STATIC (4);
938 };
939
940
941 template <typename context_t>
942 static inline void recurse_lookups (context_t *c,
943                                     unsigned int lookupCount,
944                                     const LookupRecord lookupRecord[] /* Array of LookupRecords--in design order */)
945 {
946   for (unsigned int i = 0; i < lookupCount; i++)
947     c->recurse (lookupRecord[i].lookupListIndex);
948 }
949
950 static inline bool apply_lookup (hb_apply_context_t *c,
951                                  unsigned int count, /* Including the first glyph */
952                                  unsigned int match_positions[HB_MAX_CONTEXT_LENGTH], /* Including the first glyph */
953                                  unsigned int lookupCount,
954                                  const LookupRecord lookupRecord[], /* Array of LookupRecords--in design order */
955                                  unsigned int match_length)
956 {
957   TRACE_APPLY (NULL);
958
959   hb_buffer_t *buffer = c->buffer;
960   unsigned int end;
961
962   /* All positions are distance from beginning of *output* buffer.
963    * Adjust. */
964   {
965     unsigned int bl = buffer->backtrack_len ();
966     end = bl + match_length;
967
968     int delta = bl - buffer->idx;
969     /* Convert positions to new indexing. */
970     for (unsigned int j = 0; j < count; j++)
971       match_positions[j] += delta;
972   }
973
974   for (unsigned int i = 0; i < lookupCount && !buffer->in_error; i++)
975   {
976     unsigned int idx = lookupRecord[i].sequenceIndex;
977     if (idx >= count)
978       continue;
979
980     /* Don't recurse to ourself at same position.
981      * Note that this test is too naive, it doesn't catch longer loops. */
982     if (idx == 0 && lookupRecord[i].lookupListIndex == c->lookup_index)
983       continue;
984
985     buffer->move_to (match_positions[idx]);
986
987     unsigned int orig_len = buffer->backtrack_len () + buffer->lookahead_len ();
988     if (!c->recurse (lookupRecord[i].lookupListIndex))
989       continue;
990
991     unsigned int new_len = buffer->backtrack_len () + buffer->lookahead_len ();
992     int delta = new_len - orig_len;
993
994     if (!delta)
995         continue;
996
997     /* Recursed lookup changed buffer len.  Adjust. */
998
999     end = int (end) + delta;
1000     if (end <= match_positions[idx])
1001     {
1002       /* There can't be any further changes. */
1003       assert (end == match_positions[idx]);
1004       break;
1005     }
1006
1007     unsigned int next = idx + 1; /* next now is the position after the recursed lookup. */
1008
1009     if (delta > 0)
1010     {
1011       if (unlikely (delta + count > HB_MAX_CONTEXT_LENGTH))
1012         break;
1013     }
1014     else
1015     {
1016       /* NOTE: delta is negative. */
1017       delta = MAX (delta, (int) next - (int) count);
1018       next -= delta;
1019     }
1020
1021     /* Shift! */
1022     memmove (match_positions + next + delta, match_positions + next,
1023              (count - next) * sizeof (match_positions[0]));
1024     next += delta;
1025     count += delta;
1026
1027     /* Fill in new entries. */
1028     for (unsigned int j = idx + 1; j < next; j++)
1029       match_positions[j] = match_positions[j - 1] + 1;
1030
1031     /* And fixup the rest. */
1032     for (; next < count; next++)
1033       match_positions[next] += delta;
1034   }
1035
1036   buffer->move_to (end);
1037
1038   return_trace (true);
1039 }
1040
1041
1042
1043 /* Contextual lookups */
1044
1045 struct ContextClosureLookupContext
1046 {
1047   ContextClosureFuncs funcs;
1048   const void *intersects_data;
1049 };
1050
1051 struct ContextCollectGlyphsLookupContext
1052 {
1053   ContextCollectGlyphsFuncs funcs;
1054   const void *collect_data;
1055 };
1056
1057 struct ContextApplyLookupContext
1058 {
1059   ContextApplyFuncs funcs;
1060   const void *match_data;
1061 };
1062
1063 static inline void context_closure_lookup (hb_closure_context_t *c,
1064                                            unsigned int inputCount, /* Including the first glyph (not matched) */
1065                                            const USHORT input[], /* Array of input values--start with second glyph */
1066                                            unsigned int lookupCount,
1067                                            const LookupRecord lookupRecord[],
1068                                            ContextClosureLookupContext &lookup_context)
1069 {
1070   if (intersects_array (c,
1071                         inputCount ? inputCount - 1 : 0, input,
1072                         lookup_context.funcs.intersects, lookup_context.intersects_data))
1073     recurse_lookups (c,
1074                      lookupCount, lookupRecord);
1075 }
1076
1077 static inline void context_collect_glyphs_lookup (hb_collect_glyphs_context_t *c,
1078                                                   unsigned int inputCount, /* Including the first glyph (not matched) */
1079                                                   const USHORT input[], /* Array of input values--start with second glyph */
1080                                                   unsigned int lookupCount,
1081                                                   const LookupRecord lookupRecord[],
1082                                                   ContextCollectGlyphsLookupContext &lookup_context)
1083 {
1084   collect_array (c, c->input,
1085                  inputCount ? inputCount - 1 : 0, input,
1086                  lookup_context.funcs.collect, lookup_context.collect_data);
1087   recurse_lookups (c,
1088                    lookupCount, lookupRecord);
1089 }
1090
1091 static inline bool context_would_apply_lookup (hb_would_apply_context_t *c,
1092                                                unsigned int inputCount, /* Including the first glyph (not matched) */
1093                                                const USHORT input[], /* Array of input values--start with second glyph */
1094                                                unsigned int lookupCount HB_UNUSED,
1095                                                const LookupRecord lookupRecord[] HB_UNUSED,
1096                                                ContextApplyLookupContext &lookup_context)
1097 {
1098   return would_match_input (c,
1099                             inputCount, input,
1100                             lookup_context.funcs.match, lookup_context.match_data);
1101 }
1102 static inline bool context_apply_lookup (hb_apply_context_t *c,
1103                                          unsigned int inputCount, /* Including the first glyph (not matched) */
1104                                          const USHORT input[], /* Array of input values--start with second glyph */
1105                                          unsigned int lookupCount,
1106                                          const LookupRecord lookupRecord[],
1107                                          ContextApplyLookupContext &lookup_context)
1108 {
1109   unsigned int match_length = 0;
1110   unsigned int match_positions[HB_MAX_CONTEXT_LENGTH];
1111   return match_input (c,
1112                       inputCount, input,
1113                       lookup_context.funcs.match, lookup_context.match_data,
1114                       &match_length, match_positions)
1115       && apply_lookup (c,
1116                        inputCount, match_positions,
1117                        lookupCount, lookupRecord,
1118                        match_length);
1119 }
1120
1121 struct Rule
1122 {
1123   inline void closure (hb_closure_context_t *c, ContextClosureLookupContext &lookup_context) const
1124   {
1125     TRACE_CLOSURE (this);
1126     const LookupRecord *lookupRecord = &StructAtOffset<LookupRecord> (inputZ, inputZ[0].static_size * (inputCount ? inputCount - 1 : 0));
1127     context_closure_lookup (c,
1128                             inputCount, inputZ,
1129                             lookupCount, lookupRecord,
1130                             lookup_context);
1131   }
1132
1133   inline void collect_glyphs (hb_collect_glyphs_context_t *c, ContextCollectGlyphsLookupContext &lookup_context) const
1134   {
1135     TRACE_COLLECT_GLYPHS (this);
1136     const LookupRecord *lookupRecord = &StructAtOffset<LookupRecord> (inputZ, inputZ[0].static_size * (inputCount ? inputCount - 1 : 0));
1137     context_collect_glyphs_lookup (c,
1138                                    inputCount, inputZ,
1139                                    lookupCount, lookupRecord,
1140                                    lookup_context);
1141   }
1142
1143   inline bool would_apply (hb_would_apply_context_t *c, ContextApplyLookupContext &lookup_context) const
1144   {
1145     TRACE_WOULD_APPLY (this);
1146     const LookupRecord *lookupRecord = &StructAtOffset<LookupRecord> (inputZ, inputZ[0].static_size * (inputCount ? inputCount - 1 : 0));
1147     return_trace (context_would_apply_lookup (c, inputCount, inputZ, lookupCount, lookupRecord, lookup_context));
1148   }
1149
1150   inline bool apply (hb_apply_context_t *c, ContextApplyLookupContext &lookup_context) const
1151   {
1152     TRACE_APPLY (this);
1153     const LookupRecord *lookupRecord = &StructAtOffset<LookupRecord> (inputZ, inputZ[0].static_size * (inputCount ? inputCount - 1 : 0));
1154     return_trace (context_apply_lookup (c, inputCount, inputZ, lookupCount, lookupRecord, lookup_context));
1155   }
1156
1157   public:
1158   inline bool sanitize (hb_sanitize_context_t *c) const
1159   {
1160     TRACE_SANITIZE (this);
1161     return inputCount.sanitize (c)
1162         && lookupCount.sanitize (c)
1163         && c->check_range (inputZ,
1164                            inputZ[0].static_size * inputCount
1165                            + lookupRecordX[0].static_size * lookupCount);
1166   }
1167
1168   protected:
1169   USHORT        inputCount;             /* Total number of glyphs in input
1170                                          * glyph sequence--includes the first
1171                                          * glyph */
1172   USHORT        lookupCount;            /* Number of LookupRecords */
1173   USHORT        inputZ[VAR];            /* Array of match inputs--start with
1174                                          * second glyph */
1175   LookupRecord  lookupRecordX[VAR];     /* Array of LookupRecords--in
1176                                          * design order */
1177   public:
1178   DEFINE_SIZE_ARRAY2 (4, inputZ, lookupRecordX);
1179 };
1180
1181 struct RuleSet
1182 {
1183   inline void closure (hb_closure_context_t *c, ContextClosureLookupContext &lookup_context) const
1184   {
1185     TRACE_CLOSURE (this);
1186     unsigned int num_rules = rule.len;
1187     for (unsigned int i = 0; i < num_rules; i++)
1188       (this+rule[i]).closure (c, lookup_context);
1189   }
1190
1191   inline void collect_glyphs (hb_collect_glyphs_context_t *c, ContextCollectGlyphsLookupContext &lookup_context) const
1192   {
1193     TRACE_COLLECT_GLYPHS (this);
1194     unsigned int num_rules = rule.len;
1195     for (unsigned int i = 0; i < num_rules; i++)
1196       (this+rule[i]).collect_glyphs (c, lookup_context);
1197   }
1198
1199   inline bool would_apply (hb_would_apply_context_t *c, ContextApplyLookupContext &lookup_context) const
1200   {
1201     TRACE_WOULD_APPLY (this);
1202     unsigned int num_rules = rule.len;
1203     for (unsigned int i = 0; i < num_rules; i++)
1204     {
1205       if ((this+rule[i]).would_apply (c, lookup_context))
1206         return_trace (true);
1207     }
1208     return_trace (false);
1209   }
1210
1211   inline bool apply (hb_apply_context_t *c, ContextApplyLookupContext &lookup_context) const
1212   {
1213     TRACE_APPLY (this);
1214     unsigned int num_rules = rule.len;
1215     for (unsigned int i = 0; i < num_rules; i++)
1216     {
1217       if ((this+rule[i]).apply (c, lookup_context))
1218         return_trace (true);
1219     }
1220     return_trace (false);
1221   }
1222
1223   inline bool sanitize (hb_sanitize_context_t *c) const
1224   {
1225     TRACE_SANITIZE (this);
1226     return_trace (rule.sanitize (c, this));
1227   }
1228
1229   protected:
1230   OffsetArrayOf<Rule>
1231                 rule;                   /* Array of Rule tables
1232                                          * ordered by preference */
1233   public:
1234   DEFINE_SIZE_ARRAY (2, rule);
1235 };
1236
1237
1238 struct ContextFormat1
1239 {
1240   inline void closure (hb_closure_context_t *c) const
1241   {
1242     TRACE_CLOSURE (this);
1243
1244     const Coverage &cov = (this+coverage);
1245
1246     struct ContextClosureLookupContext lookup_context = {
1247       {intersects_glyph},
1248       NULL
1249     };
1250
1251     unsigned int count = ruleSet.len;
1252     for (unsigned int i = 0; i < count; i++)
1253       if (cov.intersects_coverage (c->glyphs, i)) {
1254         const RuleSet &rule_set = this+ruleSet[i];
1255         rule_set.closure (c, lookup_context);
1256       }
1257   }
1258
1259   inline void collect_glyphs (hb_collect_glyphs_context_t *c) const
1260   {
1261     TRACE_COLLECT_GLYPHS (this);
1262     (this+coverage).add_coverage (c->input);
1263
1264     struct ContextCollectGlyphsLookupContext lookup_context = {
1265       {collect_glyph},
1266       NULL
1267     };
1268
1269     unsigned int count = ruleSet.len;
1270     for (unsigned int i = 0; i < count; i++)
1271       (this+ruleSet[i]).collect_glyphs (c, lookup_context);
1272   }
1273
1274   inline bool would_apply (hb_would_apply_context_t *c) const
1275   {
1276     TRACE_WOULD_APPLY (this);
1277
1278     const RuleSet &rule_set = this+ruleSet[(this+coverage).get_coverage (c->glyphs[0])];
1279     struct ContextApplyLookupContext lookup_context = {
1280       {match_glyph},
1281       NULL
1282     };
1283     return_trace (rule_set.would_apply (c, lookup_context));
1284   }
1285
1286   inline const Coverage &get_coverage (void) const
1287   {
1288     return this+coverage;
1289   }
1290
1291   inline bool apply (hb_apply_context_t *c) const
1292   {
1293     TRACE_APPLY (this);
1294     unsigned int index = (this+coverage).get_coverage (c->buffer->cur().codepoint);
1295     if (likely (index == NOT_COVERED))
1296       return_trace (false);
1297
1298     const RuleSet &rule_set = this+ruleSet[index];
1299     struct ContextApplyLookupContext lookup_context = {
1300       {match_glyph},
1301       NULL
1302     };
1303     return_trace (rule_set.apply (c, lookup_context));
1304   }
1305
1306   inline bool sanitize (hb_sanitize_context_t *c) const
1307   {
1308     TRACE_SANITIZE (this);
1309     return_trace (coverage.sanitize (c, this) && ruleSet.sanitize (c, this));
1310   }
1311
1312   protected:
1313   USHORT        format;                 /* Format identifier--format = 1 */
1314   OffsetTo<Coverage>
1315                 coverage;               /* Offset to Coverage table--from
1316                                          * beginning of table */
1317   OffsetArrayOf<RuleSet>
1318                 ruleSet;                /* Array of RuleSet tables
1319                                          * ordered by Coverage Index */
1320   public:
1321   DEFINE_SIZE_ARRAY (6, ruleSet);
1322 };
1323
1324
1325 struct ContextFormat2
1326 {
1327   inline void closure (hb_closure_context_t *c) const
1328   {
1329     TRACE_CLOSURE (this);
1330     if (!(this+coverage).intersects (c->glyphs))
1331       return;
1332
1333     const ClassDef &class_def = this+classDef;
1334
1335     struct ContextClosureLookupContext lookup_context = {
1336       {intersects_class},
1337       &class_def
1338     };
1339
1340     unsigned int count = ruleSet.len;
1341     for (unsigned int i = 0; i < count; i++)
1342       if (class_def.intersects_class (c->glyphs, i)) {
1343         const RuleSet &rule_set = this+ruleSet[i];
1344         rule_set.closure (c, lookup_context);
1345       }
1346   }
1347
1348   inline void collect_glyphs (hb_collect_glyphs_context_t *c) const
1349   {
1350     TRACE_COLLECT_GLYPHS (this);
1351     (this+coverage).add_coverage (c->input);
1352
1353     const ClassDef &class_def = this+classDef;
1354     struct ContextCollectGlyphsLookupContext lookup_context = {
1355       {collect_class},
1356       &class_def
1357     };
1358
1359     unsigned int count = ruleSet.len;
1360     for (unsigned int i = 0; i < count; i++)
1361       (this+ruleSet[i]).collect_glyphs (c, lookup_context);
1362   }
1363
1364   inline bool would_apply (hb_would_apply_context_t *c) const
1365   {
1366     TRACE_WOULD_APPLY (this);
1367
1368     const ClassDef &class_def = this+classDef;
1369     unsigned int index = class_def.get_class (c->glyphs[0]);
1370     const RuleSet &rule_set = this+ruleSet[index];
1371     struct ContextApplyLookupContext lookup_context = {
1372       {match_class},
1373       &class_def
1374     };
1375     return_trace (rule_set.would_apply (c, lookup_context));
1376   }
1377
1378   inline const Coverage &get_coverage (void) const
1379   {
1380     return this+coverage;
1381   }
1382
1383   inline bool apply (hb_apply_context_t *c) const
1384   {
1385     TRACE_APPLY (this);
1386     unsigned int index = (this+coverage).get_coverage (c->buffer->cur().codepoint);
1387     if (likely (index == NOT_COVERED)) return_trace (false);
1388
1389     const ClassDef &class_def = this+classDef;
1390     index = class_def.get_class (c->buffer->cur().codepoint);
1391     const RuleSet &rule_set = this+ruleSet[index];
1392     struct ContextApplyLookupContext lookup_context = {
1393       {match_class},
1394       &class_def
1395     };
1396     return_trace (rule_set.apply (c, lookup_context));
1397   }
1398
1399   inline bool sanitize (hb_sanitize_context_t *c) const
1400   {
1401     TRACE_SANITIZE (this);
1402     return_trace (coverage.sanitize (c, this) && classDef.sanitize (c, this) && ruleSet.sanitize (c, this));
1403   }
1404
1405   protected:
1406   USHORT        format;                 /* Format identifier--format = 2 */
1407   OffsetTo<Coverage>
1408                 coverage;               /* Offset to Coverage table--from
1409                                          * beginning of table */
1410   OffsetTo<ClassDef>
1411                 classDef;               /* Offset to glyph ClassDef table--from
1412                                          * beginning of table */
1413   OffsetArrayOf<RuleSet>
1414                 ruleSet;                /* Array of RuleSet tables
1415                                          * ordered by class */
1416   public:
1417   DEFINE_SIZE_ARRAY (8, ruleSet);
1418 };
1419
1420
1421 struct ContextFormat3
1422 {
1423   inline void closure (hb_closure_context_t *c) const
1424   {
1425     TRACE_CLOSURE (this);
1426     if (!(this+coverageZ[0]).intersects (c->glyphs))
1427       return;
1428
1429     const LookupRecord *lookupRecord = &StructAtOffset<LookupRecord> (coverageZ, coverageZ[0].static_size * glyphCount);
1430     struct ContextClosureLookupContext lookup_context = {
1431       {intersects_coverage},
1432       this
1433     };
1434     context_closure_lookup (c,
1435                             glyphCount, (const USHORT *) (coverageZ + 1),
1436                             lookupCount, lookupRecord,
1437                             lookup_context);
1438   }
1439
1440   inline void collect_glyphs (hb_collect_glyphs_context_t *c) const
1441   {
1442     TRACE_COLLECT_GLYPHS (this);
1443     (this+coverageZ[0]).add_coverage (c->input);
1444
1445     const LookupRecord *lookupRecord = &StructAtOffset<LookupRecord> (coverageZ, coverageZ[0].static_size * glyphCount);
1446     struct ContextCollectGlyphsLookupContext lookup_context = {
1447       {collect_coverage},
1448       this
1449     };
1450
1451     context_collect_glyphs_lookup (c,
1452                                    glyphCount, (const USHORT *) (coverageZ + 1),
1453                                    lookupCount, lookupRecord,
1454                                    lookup_context);
1455   }
1456
1457   inline bool would_apply (hb_would_apply_context_t *c) const
1458   {
1459     TRACE_WOULD_APPLY (this);
1460
1461     const LookupRecord *lookupRecord = &StructAtOffset<LookupRecord> (coverageZ, coverageZ[0].static_size * glyphCount);
1462     struct ContextApplyLookupContext lookup_context = {
1463       {match_coverage},
1464       this
1465     };
1466     return_trace (context_would_apply_lookup (c, glyphCount, (const USHORT *) (coverageZ + 1), lookupCount, lookupRecord, lookup_context));
1467   }
1468
1469   inline const Coverage &get_coverage (void) const
1470   {
1471     return this+coverageZ[0];
1472   }
1473
1474   inline bool apply (hb_apply_context_t *c) const
1475   {
1476     TRACE_APPLY (this);
1477     unsigned int index = (this+coverageZ[0]).get_coverage (c->buffer->cur().codepoint);
1478     if (likely (index == NOT_COVERED)) return_trace (false);
1479
1480     const LookupRecord *lookupRecord = &StructAtOffset<LookupRecord> (coverageZ, coverageZ[0].static_size * glyphCount);
1481     struct ContextApplyLookupContext lookup_context = {
1482       {match_coverage},
1483       this
1484     };
1485     return_trace (context_apply_lookup (c, glyphCount, (const USHORT *) (coverageZ + 1), lookupCount, lookupRecord, lookup_context));
1486   }
1487
1488   inline bool sanitize (hb_sanitize_context_t *c) const
1489   {
1490     TRACE_SANITIZE (this);
1491     if (!c->check_struct (this)) return_trace (false);
1492     unsigned int count = glyphCount;
1493     if (!count) return_trace (false); /* We want to access coverageZ[0] freely. */
1494     if (!c->check_array (coverageZ, coverageZ[0].static_size, count)) return_trace (false);
1495     for (unsigned int i = 0; i < count; i++)
1496       if (!coverageZ[i].sanitize (c, this)) return_trace (false);
1497     const LookupRecord *lookupRecord = &StructAtOffset<LookupRecord> (coverageZ, coverageZ[0].static_size * count);
1498     return_trace (c->check_array (lookupRecord, lookupRecord[0].static_size, lookupCount));
1499   }
1500
1501   protected:
1502   USHORT        format;                 /* Format identifier--format = 3 */
1503   USHORT        glyphCount;             /* Number of glyphs in the input glyph
1504                                          * sequence */
1505   USHORT        lookupCount;            /* Number of LookupRecords */
1506   OffsetTo<Coverage>
1507                 coverageZ[VAR];         /* Array of offsets to Coverage
1508                                          * table in glyph sequence order */
1509   LookupRecord  lookupRecordX[VAR];     /* Array of LookupRecords--in
1510                                          * design order */
1511   public:
1512   DEFINE_SIZE_ARRAY2 (6, coverageZ, lookupRecordX);
1513 };
1514
1515 struct Context
1516 {
1517   template <typename context_t>
1518   inline typename context_t::return_t dispatch (context_t *c) const
1519   {
1520     TRACE_DISPATCH (this, u.format);
1521     if (unlikely (!c->may_dispatch (this, &u.format))) return_trace (c->no_dispatch_return_value ());
1522     switch (u.format) {
1523     case 1: return_trace (c->dispatch (u.format1));
1524     case 2: return_trace (c->dispatch (u.format2));
1525     case 3: return_trace (c->dispatch (u.format3));
1526     default:return_trace (c->default_return_value ());
1527     }
1528   }
1529
1530   protected:
1531   union {
1532   USHORT                format;         /* Format identifier */
1533   ContextFormat1        format1;
1534   ContextFormat2        format2;
1535   ContextFormat3        format3;
1536   } u;
1537 };
1538
1539
1540 /* Chaining Contextual lookups */
1541
1542 struct ChainContextClosureLookupContext
1543 {
1544   ContextClosureFuncs funcs;
1545   const void *intersects_data[3];
1546 };
1547
1548 struct ChainContextCollectGlyphsLookupContext
1549 {
1550   ContextCollectGlyphsFuncs funcs;
1551   const void *collect_data[3];
1552 };
1553
1554 struct ChainContextApplyLookupContext
1555 {
1556   ContextApplyFuncs funcs;
1557   const void *match_data[3];
1558 };
1559
1560 static inline void chain_context_closure_lookup (hb_closure_context_t *c,
1561                                                  unsigned int backtrackCount,
1562                                                  const USHORT backtrack[],
1563                                                  unsigned int inputCount, /* Including the first glyph (not matched) */
1564                                                  const USHORT input[], /* Array of input values--start with second glyph */
1565                                                  unsigned int lookaheadCount,
1566                                                  const USHORT lookahead[],
1567                                                  unsigned int lookupCount,
1568                                                  const LookupRecord lookupRecord[],
1569                                                  ChainContextClosureLookupContext &lookup_context)
1570 {
1571   if (intersects_array (c,
1572                         backtrackCount, backtrack,
1573                         lookup_context.funcs.intersects, lookup_context.intersects_data[0])
1574    && intersects_array (c,
1575                         inputCount ? inputCount - 1 : 0, input,
1576                         lookup_context.funcs.intersects, lookup_context.intersects_data[1])
1577    && intersects_array (c,
1578                        lookaheadCount, lookahead,
1579                        lookup_context.funcs.intersects, lookup_context.intersects_data[2]))
1580     recurse_lookups (c,
1581                      lookupCount, lookupRecord);
1582 }
1583
1584 static inline void chain_context_collect_glyphs_lookup (hb_collect_glyphs_context_t *c,
1585                                                         unsigned int backtrackCount,
1586                                                         const USHORT backtrack[],
1587                                                         unsigned int inputCount, /* Including the first glyph (not matched) */
1588                                                         const USHORT input[], /* Array of input values--start with second glyph */
1589                                                         unsigned int lookaheadCount,
1590                                                         const USHORT lookahead[],
1591                                                         unsigned int lookupCount,
1592                                                         const LookupRecord lookupRecord[],
1593                                                         ChainContextCollectGlyphsLookupContext &lookup_context)
1594 {
1595   collect_array (c, c->before,
1596                  backtrackCount, backtrack,
1597                  lookup_context.funcs.collect, lookup_context.collect_data[0]);
1598   collect_array (c, c->input,
1599                  inputCount ? inputCount - 1 : 0, input,
1600                  lookup_context.funcs.collect, lookup_context.collect_data[1]);
1601   collect_array (c, c->after,
1602                  lookaheadCount, lookahead,
1603                  lookup_context.funcs.collect, lookup_context.collect_data[2]);
1604   recurse_lookups (c,
1605                    lookupCount, lookupRecord);
1606 }
1607
1608 static inline bool chain_context_would_apply_lookup (hb_would_apply_context_t *c,
1609                                                      unsigned int backtrackCount,
1610                                                      const USHORT backtrack[] HB_UNUSED,
1611                                                      unsigned int inputCount, /* Including the first glyph (not matched) */
1612                                                      const USHORT input[], /* Array of input values--start with second glyph */
1613                                                      unsigned int lookaheadCount,
1614                                                      const USHORT lookahead[] HB_UNUSED,
1615                                                      unsigned int lookupCount HB_UNUSED,
1616                                                      const LookupRecord lookupRecord[] HB_UNUSED,
1617                                                      ChainContextApplyLookupContext &lookup_context)
1618 {
1619   return (c->zero_context ? !backtrackCount && !lookaheadCount : true)
1620       && would_match_input (c,
1621                             inputCount, input,
1622                             lookup_context.funcs.match, lookup_context.match_data[1]);
1623 }
1624
1625 static inline bool chain_context_apply_lookup (hb_apply_context_t *c,
1626                                                unsigned int backtrackCount,
1627                                                const USHORT backtrack[],
1628                                                unsigned int inputCount, /* Including the first glyph (not matched) */
1629                                                const USHORT input[], /* Array of input values--start with second glyph */
1630                                                unsigned int lookaheadCount,
1631                                                const USHORT lookahead[],
1632                                                unsigned int lookupCount,
1633                                                const LookupRecord lookupRecord[],
1634                                                ChainContextApplyLookupContext &lookup_context)
1635 {
1636   unsigned int match_length = 0;
1637   unsigned int match_positions[HB_MAX_CONTEXT_LENGTH];
1638   return match_input (c,
1639                       inputCount, input,
1640                       lookup_context.funcs.match, lookup_context.match_data[1],
1641                       &match_length, match_positions)
1642       && match_backtrack (c,
1643                           backtrackCount, backtrack,
1644                           lookup_context.funcs.match, lookup_context.match_data[0])
1645       && match_lookahead (c,
1646                           lookaheadCount, lookahead,
1647                           lookup_context.funcs.match, lookup_context.match_data[2],
1648                           match_length)
1649       && apply_lookup (c,
1650                        inputCount, match_positions,
1651                        lookupCount, lookupRecord,
1652                        match_length);
1653 }
1654
1655 struct ChainRule
1656 {
1657   inline void closure (hb_closure_context_t *c, ChainContextClosureLookupContext &lookup_context) const
1658   {
1659     TRACE_CLOSURE (this);
1660     const HeadlessArrayOf<USHORT> &input = StructAfter<HeadlessArrayOf<USHORT> > (backtrack);
1661     const ArrayOf<USHORT> &lookahead = StructAfter<ArrayOf<USHORT> > (input);
1662     const ArrayOf<LookupRecord> &lookup = StructAfter<ArrayOf<LookupRecord> > (lookahead);
1663     chain_context_closure_lookup (c,
1664                                   backtrack.len, backtrack.array,
1665                                   input.len, input.array,
1666                                   lookahead.len, lookahead.array,
1667                                   lookup.len, lookup.array,
1668                                   lookup_context);
1669   }
1670
1671   inline void collect_glyphs (hb_collect_glyphs_context_t *c, ChainContextCollectGlyphsLookupContext &lookup_context) const
1672   {
1673     TRACE_COLLECT_GLYPHS (this);
1674     const HeadlessArrayOf<USHORT> &input = StructAfter<HeadlessArrayOf<USHORT> > (backtrack);
1675     const ArrayOf<USHORT> &lookahead = StructAfter<ArrayOf<USHORT> > (input);
1676     const ArrayOf<LookupRecord> &lookup = StructAfter<ArrayOf<LookupRecord> > (lookahead);
1677     chain_context_collect_glyphs_lookup (c,
1678                                          backtrack.len, backtrack.array,
1679                                          input.len, input.array,
1680                                          lookahead.len, lookahead.array,
1681                                          lookup.len, lookup.array,
1682                                          lookup_context);
1683   }
1684
1685   inline bool would_apply (hb_would_apply_context_t *c, ChainContextApplyLookupContext &lookup_context) const
1686   {
1687     TRACE_WOULD_APPLY (this);
1688     const HeadlessArrayOf<USHORT> &input = StructAfter<HeadlessArrayOf<USHORT> > (backtrack);
1689     const ArrayOf<USHORT> &lookahead = StructAfter<ArrayOf<USHORT> > (input);
1690     const ArrayOf<LookupRecord> &lookup = StructAfter<ArrayOf<LookupRecord> > (lookahead);
1691     return_trace (chain_context_would_apply_lookup (c,
1692                                                     backtrack.len, backtrack.array,
1693                                                     input.len, input.array,
1694                                                     lookahead.len, lookahead.array, lookup.len,
1695                                                     lookup.array, lookup_context));
1696   }
1697
1698   inline bool apply (hb_apply_context_t *c, ChainContextApplyLookupContext &lookup_context) const
1699   {
1700     TRACE_APPLY (this);
1701     const HeadlessArrayOf<USHORT> &input = StructAfter<HeadlessArrayOf<USHORT> > (backtrack);
1702     const ArrayOf<USHORT> &lookahead = StructAfter<ArrayOf<USHORT> > (input);
1703     const ArrayOf<LookupRecord> &lookup = StructAfter<ArrayOf<LookupRecord> > (lookahead);
1704     return_trace (chain_context_apply_lookup (c,
1705                                               backtrack.len, backtrack.array,
1706                                               input.len, input.array,
1707                                               lookahead.len, lookahead.array, lookup.len,
1708                                               lookup.array, lookup_context));
1709   }
1710
1711   inline bool sanitize (hb_sanitize_context_t *c) const
1712   {
1713     TRACE_SANITIZE (this);
1714     if (!backtrack.sanitize (c)) return_trace (false);
1715     const HeadlessArrayOf<USHORT> &input = StructAfter<HeadlessArrayOf<USHORT> > (backtrack);
1716     if (!input.sanitize (c)) return_trace (false);
1717     const ArrayOf<USHORT> &lookahead = StructAfter<ArrayOf<USHORT> > (input);
1718     if (!lookahead.sanitize (c)) return_trace (false);
1719     const ArrayOf<LookupRecord> &lookup = StructAfter<ArrayOf<LookupRecord> > (lookahead);
1720     return_trace (lookup.sanitize (c));
1721   }
1722
1723   protected:
1724   ArrayOf<USHORT>
1725                 backtrack;              /* Array of backtracking values
1726                                          * (to be matched before the input
1727                                          * sequence) */
1728   HeadlessArrayOf<USHORT>
1729                 inputX;                 /* Array of input values (start with
1730                                          * second glyph) */
1731   ArrayOf<USHORT>
1732                 lookaheadX;             /* Array of lookahead values's (to be
1733                                          * matched after the input sequence) */
1734   ArrayOf<LookupRecord>
1735                 lookupX;                /* Array of LookupRecords--in
1736                                          * design order) */
1737   public:
1738   DEFINE_SIZE_MIN (8);
1739 };
1740
1741 struct ChainRuleSet
1742 {
1743   inline void closure (hb_closure_context_t *c, ChainContextClosureLookupContext &lookup_context) const
1744   {
1745     TRACE_CLOSURE (this);
1746     unsigned int num_rules = rule.len;
1747     for (unsigned int i = 0; i < num_rules; i++)
1748       (this+rule[i]).closure (c, lookup_context);
1749   }
1750
1751   inline void collect_glyphs (hb_collect_glyphs_context_t *c, ChainContextCollectGlyphsLookupContext &lookup_context) const
1752   {
1753     TRACE_COLLECT_GLYPHS (this);
1754     unsigned int num_rules = rule.len;
1755     for (unsigned int i = 0; i < num_rules; i++)
1756       (this+rule[i]).collect_glyphs (c, lookup_context);
1757   }
1758
1759   inline bool would_apply (hb_would_apply_context_t *c, ChainContextApplyLookupContext &lookup_context) const
1760   {
1761     TRACE_WOULD_APPLY (this);
1762     unsigned int num_rules = rule.len;
1763     for (unsigned int i = 0; i < num_rules; i++)
1764       if ((this+rule[i]).would_apply (c, lookup_context))
1765         return_trace (true);
1766
1767     return_trace (false);
1768   }
1769
1770   inline bool apply (hb_apply_context_t *c, ChainContextApplyLookupContext &lookup_context) const
1771   {
1772     TRACE_APPLY (this);
1773     unsigned int num_rules = rule.len;
1774     for (unsigned int i = 0; i < num_rules; i++)
1775       if ((this+rule[i]).apply (c, lookup_context))
1776         return_trace (true);
1777
1778     return_trace (false);
1779   }
1780
1781   inline bool sanitize (hb_sanitize_context_t *c) const
1782   {
1783     TRACE_SANITIZE (this);
1784     return_trace (rule.sanitize (c, this));
1785   }
1786
1787   protected:
1788   OffsetArrayOf<ChainRule>
1789                 rule;                   /* Array of ChainRule tables
1790                                          * ordered by preference */
1791   public:
1792   DEFINE_SIZE_ARRAY (2, rule);
1793 };
1794
1795 struct ChainContextFormat1
1796 {
1797   inline void closure (hb_closure_context_t *c) const
1798   {
1799     TRACE_CLOSURE (this);
1800     const Coverage &cov = (this+coverage);
1801
1802     struct ChainContextClosureLookupContext lookup_context = {
1803       {intersects_glyph},
1804       {NULL, NULL, NULL}
1805     };
1806
1807     unsigned int count = ruleSet.len;
1808     for (unsigned int i = 0; i < count; i++)
1809       if (cov.intersects_coverage (c->glyphs, i)) {
1810         const ChainRuleSet &rule_set = this+ruleSet[i];
1811         rule_set.closure (c, lookup_context);
1812       }
1813   }
1814
1815   inline void collect_glyphs (hb_collect_glyphs_context_t *c) const
1816   {
1817     TRACE_COLLECT_GLYPHS (this);
1818     (this+coverage).add_coverage (c->input);
1819
1820     struct ChainContextCollectGlyphsLookupContext lookup_context = {
1821       {collect_glyph},
1822       {NULL, NULL, NULL}
1823     };
1824
1825     unsigned int count = ruleSet.len;
1826     for (unsigned int i = 0; i < count; i++)
1827       (this+ruleSet[i]).collect_glyphs (c, lookup_context);
1828   }
1829
1830   inline bool would_apply (hb_would_apply_context_t *c) const
1831   {
1832     TRACE_WOULD_APPLY (this);
1833
1834     const ChainRuleSet &rule_set = this+ruleSet[(this+coverage).get_coverage (c->glyphs[0])];
1835     struct ChainContextApplyLookupContext lookup_context = {
1836       {match_glyph},
1837       {NULL, NULL, NULL}
1838     };
1839     return_trace (rule_set.would_apply (c, lookup_context));
1840   }
1841
1842   inline const Coverage &get_coverage (void) const
1843   {
1844     return this+coverage;
1845   }
1846
1847   inline bool apply (hb_apply_context_t *c) const
1848   {
1849     TRACE_APPLY (this);
1850     unsigned int index = (this+coverage).get_coverage (c->buffer->cur().codepoint);
1851     if (likely (index == NOT_COVERED)) return_trace (false);
1852
1853     const ChainRuleSet &rule_set = this+ruleSet[index];
1854     struct ChainContextApplyLookupContext lookup_context = {
1855       {match_glyph},
1856       {NULL, NULL, NULL}
1857     };
1858     return_trace (rule_set.apply (c, lookup_context));
1859   }
1860
1861   inline bool sanitize (hb_sanitize_context_t *c) const
1862   {
1863     TRACE_SANITIZE (this);
1864     return_trace (coverage.sanitize (c, this) && ruleSet.sanitize (c, this));
1865   }
1866
1867   protected:
1868   USHORT        format;                 /* Format identifier--format = 1 */
1869   OffsetTo<Coverage>
1870                 coverage;               /* Offset to Coverage table--from
1871                                          * beginning of table */
1872   OffsetArrayOf<ChainRuleSet>
1873                 ruleSet;                /* Array of ChainRuleSet tables
1874                                          * ordered by Coverage Index */
1875   public:
1876   DEFINE_SIZE_ARRAY (6, ruleSet);
1877 };
1878
1879 struct ChainContextFormat2
1880 {
1881   inline void closure (hb_closure_context_t *c) const
1882   {
1883     TRACE_CLOSURE (this);
1884     if (!(this+coverage).intersects (c->glyphs))
1885       return;
1886
1887     const ClassDef &backtrack_class_def = this+backtrackClassDef;
1888     const ClassDef &input_class_def = this+inputClassDef;
1889     const ClassDef &lookahead_class_def = this+lookaheadClassDef;
1890
1891     struct ChainContextClosureLookupContext lookup_context = {
1892       {intersects_class},
1893       {&backtrack_class_def,
1894        &input_class_def,
1895        &lookahead_class_def}
1896     };
1897
1898     unsigned int count = ruleSet.len;
1899     for (unsigned int i = 0; i < count; i++)
1900       if (input_class_def.intersects_class (c->glyphs, i)) {
1901         const ChainRuleSet &rule_set = this+ruleSet[i];
1902         rule_set.closure (c, lookup_context);
1903       }
1904   }
1905
1906   inline void collect_glyphs (hb_collect_glyphs_context_t *c) const
1907   {
1908     TRACE_COLLECT_GLYPHS (this);
1909     (this+coverage).add_coverage (c->input);
1910
1911     const ClassDef &backtrack_class_def = this+backtrackClassDef;
1912     const ClassDef &input_class_def = this+inputClassDef;
1913     const ClassDef &lookahead_class_def = this+lookaheadClassDef;
1914
1915     struct ChainContextCollectGlyphsLookupContext lookup_context = {
1916       {collect_class},
1917       {&backtrack_class_def,
1918        &input_class_def,
1919        &lookahead_class_def}
1920     };
1921
1922     unsigned int count = ruleSet.len;
1923     for (unsigned int i = 0; i < count; i++)
1924       (this+ruleSet[i]).collect_glyphs (c, lookup_context);
1925   }
1926
1927   inline bool would_apply (hb_would_apply_context_t *c) const
1928   {
1929     TRACE_WOULD_APPLY (this);
1930
1931     const ClassDef &backtrack_class_def = this+backtrackClassDef;
1932     const ClassDef &input_class_def = this+inputClassDef;
1933     const ClassDef &lookahead_class_def = this+lookaheadClassDef;
1934
1935     unsigned int index = input_class_def.get_class (c->glyphs[0]);
1936     const ChainRuleSet &rule_set = this+ruleSet[index];
1937     struct ChainContextApplyLookupContext lookup_context = {
1938       {match_class},
1939       {&backtrack_class_def,
1940        &input_class_def,
1941        &lookahead_class_def}
1942     };
1943     return_trace (rule_set.would_apply (c, lookup_context));
1944   }
1945
1946   inline const Coverage &get_coverage (void) const
1947   {
1948     return this+coverage;
1949   }
1950
1951   inline bool apply (hb_apply_context_t *c) const
1952   {
1953     TRACE_APPLY (this);
1954     unsigned int index = (this+coverage).get_coverage (c->buffer->cur().codepoint);
1955     if (likely (index == NOT_COVERED)) return_trace (false);
1956
1957     const ClassDef &backtrack_class_def = this+backtrackClassDef;
1958     const ClassDef &input_class_def = this+inputClassDef;
1959     const ClassDef &lookahead_class_def = this+lookaheadClassDef;
1960
1961     index = input_class_def.get_class (c->buffer->cur().codepoint);
1962     const ChainRuleSet &rule_set = this+ruleSet[index];
1963     struct ChainContextApplyLookupContext lookup_context = {
1964       {match_class},
1965       {&backtrack_class_def,
1966        &input_class_def,
1967        &lookahead_class_def}
1968     };
1969     return_trace (rule_set.apply (c, lookup_context));
1970   }
1971
1972   inline bool sanitize (hb_sanitize_context_t *c) const
1973   {
1974     TRACE_SANITIZE (this);
1975     return_trace (coverage.sanitize (c, this) &&
1976                   backtrackClassDef.sanitize (c, this) &&
1977                   inputClassDef.sanitize (c, this) &&
1978                   lookaheadClassDef.sanitize (c, this) &&
1979                   ruleSet.sanitize (c, this));
1980   }
1981
1982   protected:
1983   USHORT        format;                 /* Format identifier--format = 2 */
1984   OffsetTo<Coverage>
1985                 coverage;               /* Offset to Coverage table--from
1986                                          * beginning of table */
1987   OffsetTo<ClassDef>
1988                 backtrackClassDef;      /* Offset to glyph ClassDef table
1989                                          * containing backtrack sequence
1990                                          * data--from beginning of table */
1991   OffsetTo<ClassDef>
1992                 inputClassDef;          /* Offset to glyph ClassDef
1993                                          * table containing input sequence
1994                                          * data--from beginning of table */
1995   OffsetTo<ClassDef>
1996                 lookaheadClassDef;      /* Offset to glyph ClassDef table
1997                                          * containing lookahead sequence
1998                                          * data--from beginning of table */
1999   OffsetArrayOf<ChainRuleSet>
2000                 ruleSet;                /* Array of ChainRuleSet tables
2001                                          * ordered by class */
2002   public:
2003   DEFINE_SIZE_ARRAY (12, ruleSet);
2004 };
2005
2006 struct ChainContextFormat3
2007 {
2008   inline void closure (hb_closure_context_t *c) const
2009   {
2010     TRACE_CLOSURE (this);
2011     const OffsetArrayOf<Coverage> &input = StructAfter<OffsetArrayOf<Coverage> > (backtrack);
2012
2013     if (!(this+input[0]).intersects (c->glyphs))
2014       return;
2015
2016     const OffsetArrayOf<Coverage> &lookahead = StructAfter<OffsetArrayOf<Coverage> > (input);
2017     const ArrayOf<LookupRecord> &lookup = StructAfter<ArrayOf<LookupRecord> > (lookahead);
2018     struct ChainContextClosureLookupContext lookup_context = {
2019       {intersects_coverage},
2020       {this, this, this}
2021     };
2022     chain_context_closure_lookup (c,
2023                                   backtrack.len, (const USHORT *) backtrack.array,
2024                                   input.len, (const USHORT *) input.array + 1,
2025                                   lookahead.len, (const USHORT *) lookahead.array,
2026                                   lookup.len, lookup.array,
2027                                   lookup_context);
2028   }
2029
2030   inline void collect_glyphs (hb_collect_glyphs_context_t *c) const
2031   {
2032     TRACE_COLLECT_GLYPHS (this);
2033     const OffsetArrayOf<Coverage> &input = StructAfter<OffsetArrayOf<Coverage> > (backtrack);
2034
2035     (this+input[0]).add_coverage (c->input);
2036
2037     const OffsetArrayOf<Coverage> &lookahead = StructAfter<OffsetArrayOf<Coverage> > (input);
2038     const ArrayOf<LookupRecord> &lookup = StructAfter<ArrayOf<LookupRecord> > (lookahead);
2039     struct ChainContextCollectGlyphsLookupContext lookup_context = {
2040       {collect_coverage},
2041       {this, this, this}
2042     };
2043     chain_context_collect_glyphs_lookup (c,
2044                                          backtrack.len, (const USHORT *) backtrack.array,
2045                                          input.len, (const USHORT *) input.array + 1,
2046                                          lookahead.len, (const USHORT *) lookahead.array,
2047                                          lookup.len, lookup.array,
2048                                          lookup_context);
2049   }
2050
2051   inline bool would_apply (hb_would_apply_context_t *c) const
2052   {
2053     TRACE_WOULD_APPLY (this);
2054
2055     const OffsetArrayOf<Coverage> &input = StructAfter<OffsetArrayOf<Coverage> > (backtrack);
2056     const OffsetArrayOf<Coverage> &lookahead = StructAfter<OffsetArrayOf<Coverage> > (input);
2057     const ArrayOf<LookupRecord> &lookup = StructAfter<ArrayOf<LookupRecord> > (lookahead);
2058     struct ChainContextApplyLookupContext lookup_context = {
2059       {match_coverage},
2060       {this, this, this}
2061     };
2062     return_trace (chain_context_would_apply_lookup (c,
2063                                                     backtrack.len, (const USHORT *) backtrack.array,
2064                                                     input.len, (const USHORT *) input.array + 1,
2065                                                     lookahead.len, (const USHORT *) lookahead.array,
2066                                                     lookup.len, lookup.array, lookup_context));
2067   }
2068
2069   inline const Coverage &get_coverage (void) const
2070   {
2071     const OffsetArrayOf<Coverage> &input = StructAfter<OffsetArrayOf<Coverage> > (backtrack);
2072     return this+input[0];
2073   }
2074
2075   inline bool apply (hb_apply_context_t *c) const
2076   {
2077     TRACE_APPLY (this);
2078     const OffsetArrayOf<Coverage> &input = StructAfter<OffsetArrayOf<Coverage> > (backtrack);
2079
2080     unsigned int index = (this+input[0]).get_coverage (c->buffer->cur().codepoint);
2081     if (likely (index == NOT_COVERED)) return_trace (false);
2082
2083     const OffsetArrayOf<Coverage> &lookahead = StructAfter<OffsetArrayOf<Coverage> > (input);
2084     const ArrayOf<LookupRecord> &lookup = StructAfter<ArrayOf<LookupRecord> > (lookahead);
2085     struct ChainContextApplyLookupContext lookup_context = {
2086       {match_coverage},
2087       {this, this, this}
2088     };
2089     return_trace (chain_context_apply_lookup (c,
2090                                               backtrack.len, (const USHORT *) backtrack.array,
2091                                               input.len, (const USHORT *) input.array + 1,
2092                                               lookahead.len, (const USHORT *) lookahead.array,
2093                                               lookup.len, lookup.array, lookup_context));
2094   }
2095
2096   inline bool sanitize (hb_sanitize_context_t *c) const
2097   {
2098     TRACE_SANITIZE (this);
2099     if (!backtrack.sanitize (c, this)) return_trace (false);
2100     const OffsetArrayOf<Coverage> &input = StructAfter<OffsetArrayOf<Coverage> > (backtrack);
2101     if (!input.sanitize (c, this)) return_trace (false);
2102     if (!input.len) return_trace (false); /* To be consistent with Context. */
2103     const OffsetArrayOf<Coverage> &lookahead = StructAfter<OffsetArrayOf<Coverage> > (input);
2104     if (!lookahead.sanitize (c, this)) return_trace (false);
2105     const ArrayOf<LookupRecord> &lookup = StructAfter<ArrayOf<LookupRecord> > (lookahead);
2106     return_trace (lookup.sanitize (c));
2107   }
2108
2109   protected:
2110   USHORT        format;                 /* Format identifier--format = 3 */
2111   OffsetArrayOf<Coverage>
2112                 backtrack;              /* Array of coverage tables
2113                                          * in backtracking sequence, in  glyph
2114                                          * sequence order */
2115   OffsetArrayOf<Coverage>
2116                 inputX          ;       /* Array of coverage
2117                                          * tables in input sequence, in glyph
2118                                          * sequence order */
2119   OffsetArrayOf<Coverage>
2120                 lookaheadX;             /* Array of coverage tables
2121                                          * in lookahead sequence, in glyph
2122                                          * sequence order */
2123   ArrayOf<LookupRecord>
2124                 lookupX;                /* Array of LookupRecords--in
2125                                          * design order) */
2126   public:
2127   DEFINE_SIZE_MIN (10);
2128 };
2129
2130 struct ChainContext
2131 {
2132   template <typename context_t>
2133   inline typename context_t::return_t dispatch (context_t *c) const
2134   {
2135     TRACE_DISPATCH (this, u.format);
2136     if (unlikely (!c->may_dispatch (this, &u.format))) return_trace (c->no_dispatch_return_value ());
2137     switch (u.format) {
2138     case 1: return_trace (c->dispatch (u.format1));
2139     case 2: return_trace (c->dispatch (u.format2));
2140     case 3: return_trace (c->dispatch (u.format3));
2141     default:return_trace (c->default_return_value ());
2142     }
2143   }
2144
2145   protected:
2146   union {
2147   USHORT                format; /* Format identifier */
2148   ChainContextFormat1   format1;
2149   ChainContextFormat2   format2;
2150   ChainContextFormat3   format3;
2151   } u;
2152 };
2153
2154
2155 template <typename T>
2156 struct ExtensionFormat1
2157 {
2158   inline unsigned int get_type (void) const { return extensionLookupType; }
2159
2160   template <typename X>
2161   inline const X& get_subtable (void) const
2162   {
2163     unsigned int offset = extensionOffset;
2164     if (unlikely (!offset)) return Null(typename T::LookupSubTable);
2165     return StructAtOffset<typename T::LookupSubTable> (this, offset);
2166   }
2167
2168   template <typename context_t>
2169   inline typename context_t::return_t dispatch (context_t *c) const
2170   {
2171     TRACE_DISPATCH (this, format);
2172     if (unlikely (!c->may_dispatch (this, this))) return_trace (c->no_dispatch_return_value ());
2173     return_trace (get_subtable<typename T::LookupSubTable> ().dispatch (c, get_type ()));
2174   }
2175
2176   /* This is called from may_dispatch() above with hb_sanitize_context_t. */
2177   inline bool sanitize (hb_sanitize_context_t *c) const
2178   {
2179     TRACE_SANITIZE (this);
2180     return_trace (c->check_struct (this) && extensionOffset != 0);
2181   }
2182
2183   protected:
2184   USHORT        format;                 /* Format identifier. Set to 1. */
2185   USHORT        extensionLookupType;    /* Lookup type of subtable referenced
2186                                          * by ExtensionOffset (i.e. the
2187                                          * extension subtable). */
2188   ULONG         extensionOffset;        /* Offset to the extension subtable,
2189                                          * of lookup type subtable. */
2190   public:
2191   DEFINE_SIZE_STATIC (8);
2192 };
2193
2194 template <typename T>
2195 struct Extension
2196 {
2197   inline unsigned int get_type (void) const
2198   {
2199     switch (u.format) {
2200     case 1: return u.format1.get_type ();
2201     default:return 0;
2202     }
2203   }
2204   template <typename X>
2205   inline const X& get_subtable (void) const
2206   {
2207     switch (u.format) {
2208     case 1: return u.format1.template get_subtable<typename T::LookupSubTable> ();
2209     default:return Null(typename T::LookupSubTable);
2210     }
2211   }
2212
2213   template <typename context_t>
2214   inline typename context_t::return_t dispatch (context_t *c) const
2215   {
2216     TRACE_DISPATCH (this, u.format);
2217     if (unlikely (!c->may_dispatch (this, &u.format))) return_trace (c->no_dispatch_return_value ());
2218     switch (u.format) {
2219     case 1: return_trace (u.format1.dispatch (c));
2220     default:return_trace (c->default_return_value ());
2221     }
2222   }
2223
2224   protected:
2225   union {
2226   USHORT                format;         /* Format identifier */
2227   ExtensionFormat1<T>   format1;
2228   } u;
2229 };
2230
2231
2232 /*
2233  * GSUB/GPOS Common
2234  */
2235
2236 struct GSUBGPOS
2237 {
2238   static const hb_tag_t GSUBTag = HB_OT_TAG_GSUB;
2239   static const hb_tag_t GPOSTag = HB_OT_TAG_GPOS;
2240
2241   inline unsigned int get_script_count (void) const
2242   { return (this+scriptList).len; }
2243   inline const Tag& get_script_tag (unsigned int i) const
2244   { return (this+scriptList).get_tag (i); }
2245   inline unsigned int get_script_tags (unsigned int start_offset,
2246                                        unsigned int *script_count /* IN/OUT */,
2247                                        hb_tag_t     *script_tags /* OUT */) const
2248   { return (this+scriptList).get_tags (start_offset, script_count, script_tags); }
2249   inline const Script& get_script (unsigned int i) const
2250   { return (this+scriptList)[i]; }
2251   inline bool find_script_index (hb_tag_t tag, unsigned int *index) const
2252   { return (this+scriptList).find_index (tag, index); }
2253
2254   inline unsigned int get_feature_count (void) const
2255   { return (this+featureList).len; }
2256   inline hb_tag_t get_feature_tag (unsigned int i) const
2257   { return i == Index::NOT_FOUND_INDEX ? HB_TAG_NONE : (this+featureList).get_tag (i); }
2258   inline unsigned int get_feature_tags (unsigned int start_offset,
2259                                         unsigned int *feature_count /* IN/OUT */,
2260                                         hb_tag_t     *feature_tags /* OUT */) const
2261   { return (this+featureList).get_tags (start_offset, feature_count, feature_tags); }
2262   inline const Feature& get_feature (unsigned int i) const
2263   { return (this+featureList)[i]; }
2264   inline bool find_feature_index (hb_tag_t tag, unsigned int *index) const
2265   { return (this+featureList).find_index (tag, index); }
2266
2267   inline unsigned int get_lookup_count (void) const
2268   { return (this+lookupList).len; }
2269   inline const Lookup& get_lookup (unsigned int i) const
2270   { return (this+lookupList)[i]; }
2271
2272   inline bool sanitize (hb_sanitize_context_t *c) const
2273   {
2274     TRACE_SANITIZE (this);
2275     return_trace (version.sanitize (c) &&
2276                   likely (version.major == 1) &&
2277                   scriptList.sanitize (c, this) &&
2278                   featureList.sanitize (c, this) &&
2279                   lookupList.sanitize (c, this));
2280   }
2281
2282   protected:
2283   FixedVersion<>version;        /* Version of the GSUB/GPOS table--initially set
2284                                  * to 0x00010000u */
2285   OffsetTo<ScriptList>
2286                 scriptList;     /* ScriptList table */
2287   OffsetTo<FeatureList>
2288                 featureList;    /* FeatureList table */
2289   OffsetTo<LookupList>
2290                 lookupList;     /* LookupList table */
2291   public:
2292   DEFINE_SIZE_STATIC (10);
2293 };
2294
2295
2296 } /* namespace OT */
2297
2298
2299 #endif /* HB_OT_LAYOUT_GSUBGPOS_PRIVATE_HH */