3 """Generator of the function to prohibit certain vowel sequences.
5 It creates ``_hb_preprocess_text_vowel_constraints``, which inserts dotted
6 circles into sequences prohibited by the USE script development spec.
7 This function should be used as the ``preprocess_text`` of an
8 ``hb_ot_complex_shaper_t``.
10 usage: ./gen-vowel-constraints.py ms-use/IndicShapingInvalidCluster.txt Scripts.txt
13 * https://unicode.org/Public/UCD/latest/ucd/Scripts.txt
19 sys.stdout.buffer.write (s.encode ('utf-8'))
22 if len (sys.argv) != 3:
25 with open (sys.argv[2], encoding='utf-8') as f:
26 scripts_header = [f.readline () for i in range (2)]
33 fields = [x.strip () for x in line.split (';')]
36 uu = fields[0].split ('..')
37 start = int (uu[0], 16)
43 for u in range (start, end + 1):
45 if script not in script_order:
46 script_order[script] = start
48 class ConstraintSet (object):
49 """A set of prohibited code point sequences.
52 constraint (List[int]): A prohibited code point sequence.
55 def __init__ (self, constraint):
56 # Either a list or a dictionary. As a list of code points, it
57 # represents a prohibited code point sequence. As a dictionary,
58 # it represents a set of prohibited sequences, where each item
59 # represents the set of prohibited sequences starting with the
60 # key (a code point) concatenated with any of the values
64 def add (self, constraint):
65 """Add a constraint to this set."""
70 if isinstance (self._c, list):
71 if constraint == self._c[:len (constraint)]:
73 elif self._c != constraint[:len (self._c)]:
74 self._c = {self._c[0]: ConstraintSet (self._c[1:])}
75 if isinstance (self._c, dict):
77 self._c[first].add (rest)
79 self._c[first] = ConstraintSet (rest)
83 return (' ' * depth).replace (' ', '\t')
85 def __str__ (self, index=0, depth=4):
87 indent = self._indent (depth)
88 if isinstance (self._c, list):
89 if len (self._c) == 0:
90 assert index == 2, 'Cannot use `matched` for this constraint; the general case has not been implemented'
91 s.append ('{}matched = true;\n'.format (indent))
92 elif len (self._c) == 1:
93 assert index == 1, 'Cannot use `matched` for this constraint; the general case has not been implemented'
94 s.append ('{}matched = 0x{:04X}u == buffer->cur ({}).codepoint;\n'.format (indent, next (iter (self._c)), index or ''))
96 s.append ('{}if (0x{:04X}u == buffer->cur ({}).codepoint &&\n'.format (indent, self._c[0], index or ''))
98 s.append ('{}buffer->idx + {} < count &&\n'.format (self._indent (depth + 2), index + 1))
99 for i, cp in enumerate (self._c[1:], start=1):
100 s.append ('{}0x{:04X}u == buffer->cur ({}).codepoint{}\n'.format (
101 self._indent (depth + 2), cp, index + i, ')' if i == len (self._c) - 1 else ' &&'))
102 s.append ('{}{{\n'.format (indent))
103 for i in range (index):
104 s.append ('{}(void) buffer->next_glyph ();\n'.format (self._indent (depth + 1)))
105 s.append ('{}matched = true;\n'.format (self._indent (depth + 1)))
106 s.append ('{}}}\n'.format (indent))
108 s.append ('{}switch (buffer->cur ({}).codepoint)\n'.format(indent, index or ''))
109 s.append ('{}{{\n'.format (indent))
110 cases = collections.defaultdict (set)
111 for first, rest in sorted (self._c.items ()):
112 cases[rest.__str__ (index + 1, depth + 2)].add (first)
113 for body, labels in sorted (cases.items (), key=lambda b_ls: sorted (b_ls[1])[0]):
114 for i, cp in enumerate (sorted (labels)):
116 s.append (self._indent (depth + 1))
119 s.append ('case 0x{:04X}u:{}'.format (cp, '\n' if i % 4 == 3 else ''))
120 if len (labels) % 4 != 0:
123 s.append ('{}break;\n'.format (self._indent (depth + 2)))
124 s.append ('{}}}\n'.format (indent))
128 with open (sys.argv[1], encoding='utf-8') as f:
129 constraints_header = []
131 line = f.readline ().strip ()
134 constraints_header.append(line)
139 constraint = [int (cp, 16) for cp in line.split (';')[0].split ()]
140 if not constraint: continue
141 assert 2 <= len (constraint), 'Prohibited sequence is too short: {}'.format (constraint)
142 script = scripts[constraint[0]]
143 if script in constraints:
144 constraints[script].add (constraint)
146 constraints[script] = ConstraintSet (constraint)
147 assert constraints, 'No constraints found'
149 print ('/* == Start of generated functions == */')
151 print (' * The following functions are generated by running:')
153 print (' * %s ms-use/IndicShapingInvalidCluster.txt Scripts.txt' % sys.argv[0])
155 print (' * on files with these headers:')
157 for line in constraints_header:
158 print (' * %s' % line.strip ())
160 for line in scripts_header:
161 print (' * %s' % line.strip ())
165 print ('#include "hb.hh"')
167 print ('#ifndef HB_NO_OT_SHAPE')
169 print ('#include "hb-ot-shape-complex-vowel-constraints.hh"')
171 print ('static void')
172 print ('_output_dotted_circle (hb_buffer_t *buffer)')
174 print (' (void) buffer->output_glyph (0x25CCu);')
175 print (' _hb_glyph_info_reset_continuation (&buffer->prev());')
178 print ('static void')
179 print ('_output_with_dotted_circle (hb_buffer_t *buffer)')
181 print (' _output_dotted_circle (buffer);')
182 print (' (void) buffer->next_glyph ();')
187 print ('_hb_preprocess_text_vowel_constraints (const hb_ot_shape_plan_t *plan HB_UNUSED,')
188 print ('\t\t\t\t hb_buffer_t *buffer,')
189 print ('\t\t\t\t hb_font_t *font HB_UNUSED)')
191 print ('#ifdef HB_NO_OT_SHAPE_COMPLEX_VOWEL_CONSTRAINTS')
194 print (' if (buffer->flags & HB_BUFFER_FLAG_DO_NOT_INSERT_DOTTED_CIRCLE)')
197 print (' /* UGLY UGLY UGLY business of adding dotted-circle in the middle of')
198 print (' * vowel-sequences that look like another vowel. Data for each script')
199 print (' * collected from the USE script development spec.')
201 print (' * https://github.com/harfbuzz/harfbuzz/issues/1019')
203 print (' buffer->clear_output ();')
204 print (' unsigned int count = buffer->len;')
205 print (' switch ((unsigned) buffer->props.script)')
208 for script, constraints in sorted (constraints.items (), key=lambda s_c: script_order[s_c[0]]):
209 print (' case HB_SCRIPT_{}:'.format (script.upper ()))
210 print (' for (buffer->idx = 0; buffer->idx + 1 < count && buffer->successful;)')
212 print ('\tbool matched = false;')
213 write (str (constraints))
214 print ('\t(void) buffer->next_glyph ();')
215 print ('\tif (matched) _output_with_dotted_circle (buffer);')
223 print (' buffer->sync ();')
229 print ('/* == End of generated functions == */')