6532ee7e0f7c440e6ba762baf42903a07097857c
[platform/upstream/harfbuzz.git] / src / gen-indic-table.py
1 #!/usr/bin/env python
2
3 from __future__ import print_function, division, absolute_import
4
5 import io, sys
6
7 if len (sys.argv) != 4:
8         print ("usage: ./gen-indic-table.py IndicSyllabicCategory.txt IndicPositionalCategory.txt Blocks.txt", file=sys.stderr)
9         sys.exit (1)
10
11 ALLOWED_SINGLES = [0x00A0, 0x25CC]
12 ALLOWED_BLOCKS = [
13         'Basic Latin',
14         'Latin-1 Supplement',
15         'Devanagari',
16         'Bengali',
17         'Gurmukhi',
18         'Gujarati',
19         'Oriya',
20         'Tamil',
21         'Telugu',
22         'Kannada',
23         'Malayalam',
24         'Sinhala',
25         'Myanmar',
26         'Khmer',
27         'Vedic Extensions',
28         'General Punctuation',
29         'Superscripts and Subscripts',
30         'Devanagari Extended',
31         'Myanmar Extended-B',
32         'Myanmar Extended-A',
33 ]
34
35 files = [io.open (x, encoding='utf-8') for x in sys.argv[1:]]
36
37 headers = [[f.readline () for i in range (2)] for f in files]
38
39 data = [{} for f in files]
40 values = [{} for f in files]
41 for i, f in enumerate (files):
42         for line in f:
43
44                 j = line.find ('#')
45                 if j >= 0:
46                         line = line[:j]
47
48                 fields = [x.strip () for x in line.split (';')]
49                 if len (fields) == 1:
50                         continue
51
52                 uu = fields[0].split ('..')
53                 start = int (uu[0], 16)
54                 if len (uu) == 1:
55                         end = start
56                 else:
57                         end = int (uu[1], 16)
58
59                 t = fields[1]
60
61                 for u in range (start, end + 1):
62                         data[i][u] = t
63                 values[i][t] = values[i].get (t, 0) + end - start + 1
64
65 # Merge data into one dict:
66 defaults = ('Other', 'Not_Applicable', 'No_Block')
67 for i,v in enumerate (defaults):
68         values[i][v] = values[i].get (v, 0) + 1
69 combined = {}
70 for i,d in enumerate (data):
71         for u,v in d.items ():
72                 if i == 2 and not u in combined:
73                         continue
74                 if not u in combined:
75                         combined[u] = list (defaults)
76                 combined[u][i] = v
77 combined = {k:v for k,v in combined.items() if k in ALLOWED_SINGLES or v[2] in ALLOWED_BLOCKS}
78 data = combined
79 del combined
80 num = len (data)
81
82 for u in [0x17CD, 0x17CE, 0x17CF, 0x17D0, 0x17D3]:
83         if data[u][0] == 'Other':
84                 data[u][0] = "Vowel_Dependent"
85
86 # Move the outliers NO-BREAK SPACE and DOTTED CIRCLE out
87 singles = {}
88 for u in ALLOWED_SINGLES:
89         singles[u] = data[u]
90         del data[u]
91
92 print ("/* == Start of generated table == */")
93 print ("/*")
94 print (" * The following table is generated by running:")
95 print (" *")
96 print (" *   ./gen-indic-table.py IndicSyllabicCategory.txt IndicPositionalCategory.txt Blocks.txt")
97 print (" *")
98 print (" * on files with these headers:")
99 print (" *")
100 for h in headers:
101         for l in h:
102                 print (" * %s" % (l.strip()))
103 print (" */")
104 print ()
105 print ('#include "hb-ot-shape-complex-indic.hh"')
106 print ()
107
108 # Shorten values
109 short = [{
110         "Bindu":                'Bi',
111         "Cantillation_Mark":    'Ca',
112         "Joiner":               'ZWJ',
113         "Non_Joiner":           'ZWNJ',
114         "Number":               'Nd',
115         "Visarga":              'Vs',
116         "Vowel":                'Vo',
117         "Vowel_Dependent":      'M',
118         "Consonant_Prefixed":   'CPrf',
119         "Other":                'x',
120 },{
121         "Not_Applicable":       'x',
122 }]
123 all_shorts = [{},{}]
124
125 # Add some of the values, to make them more readable, and to avoid duplicates
126
127
128 for i in range (2):
129         for v,s in short[i].items ():
130                 all_shorts[i][s] = v
131
132 what = ["INDIC_SYLLABIC_CATEGORY", "INDIC_MATRA_CATEGORY"]
133 what_short = ["ISC", "IMC"]
134 print ('#pragma GCC diagnostic push')
135 print ('#pragma GCC diagnostic ignored "-Wunused-macros"')
136 for i in range (2):
137         print ()
138         vv = sorted (values[i].keys ())
139         for v in vv:
140                 v_no_and = v.replace ('_And_', '_')
141                 if v in short[i]:
142                         s = short[i][v]
143                 else:
144                         s = ''.join ([c for c in v_no_and if ord ('A') <= ord (c) <= ord ('Z')])
145                         if s in all_shorts[i]:
146                                 raise Exception ("Duplicate short value alias", v, all_shorts[i][s])
147                         all_shorts[i][s] = v
148                         short[i][v] = s
149                 print ("#define %s_%s   %s_%s   %s/* %3d chars; %s */" %
150                         (what_short[i], s, what[i], v.upper (),
151                         '       '* ((48-1 - len (what[i]) - 1 - len (v)) // 8),
152                         values[i][v], v))
153 print ('#pragma GCC diagnostic pop')
154 print ()
155 print ("#define _(S,M) INDIC_COMBINE_CATEGORIES (ISC_##S, IMC_##M)")
156 print ()
157 print ()
158
159 total = 0
160 used = 0
161 last_block = None
162 def print_block (block, start, end, data):
163         global total, used, last_block
164         if block and block != last_block:
165                 print ()
166                 print ()
167                 print ("  /* %s */" % block)
168         num = 0
169         assert start % 8 == 0
170         assert (end+1) % 8 == 0
171         for u in range (start, end+1):
172                 if u % 8 == 0:
173                         print ()
174                         print ("  /* %04X */" % u, end="")
175                 if u in data:
176                         num += 1
177                 d = data.get (u, defaults)
178                 print ("%9s" % ("_(%s,%s)," % (short[0][d[0]], short[1][d[1]])), end="")
179
180         total += end - start + 1
181         used += num
182         if block:
183                 last_block = block
184
185 uu = sorted (data.keys ())
186
187 last = -100000
188 num = 0
189 offset = 0
190 starts = []
191 ends = []
192 print ("static const INDIC_TABLE_ELEMENT_TYPE indic_table[] = {")
193 for u in uu:
194         if u <= last:
195                 continue
196         block = data[u][2]
197
198         start = u//8*8
199         end = start+1
200         while end in uu and block == data[end][2]:
201                 end += 1
202         end = (end-1)//8*8 + 7
203
204         if start != last + 1:
205                 if start - last <= 1+16*3:
206                         print_block (None, last+1, start-1, data)
207                         last = start-1
208                 else:
209                         if last >= 0:
210                                 ends.append (last + 1)
211                                 offset += ends[-1] - starts[-1]
212                         print ()
213                         print ()
214                         print ("#define indic_offset_0x%04xu %d" % (start, offset))
215                         starts.append (start)
216
217         print_block (block, start, end, data)
218         last = end
219 ends.append (last + 1)
220 offset += ends[-1] - starts[-1]
221 print ()
222 print ()
223 occupancy = used * 100. / total
224 page_bits = 12
225 print ("}; /* Table items: %d; occupancy: %d%% */" % (offset, occupancy))
226 print ()
227 print ("INDIC_TABLE_ELEMENT_TYPE")
228 print ("hb_indic_get_categories (hb_codepoint_t u)")
229 print ("{")
230 print ("  switch (u >> %d)" % page_bits)
231 print ("  {")
232 pages = set ([u>>page_bits for u in starts+ends+list (singles.keys ())])
233 for p in sorted(pages):
234         print ("    case 0x%0Xu:" % p)
235         for u,d in singles.items ():
236                 if p != u>>page_bits: continue
237                 print ("      if (unlikely (u == 0x%04Xu)) return _(%s,%s);" % (u, short[0][d[0]], short[1][d[1]]))
238         for (start,end) in zip (starts, ends):
239                 if p not in [start>>page_bits, end>>page_bits]: continue
240                 offset = "indic_offset_0x%04xu" % start
241                 print ("      if (hb_in_range<hb_codepoint_t> (u, 0x%04Xu, 0x%04Xu)) return indic_table[u - 0x%04Xu + %s];" % (start, end-1, start, offset))
242         print ("      break;")
243         print ("")
244 print ("    default:")
245 print ("      break;")
246 print ("  }")
247 print ("  return _(x,x);")
248 print ("}")
249 print ()
250 print ("#undef _")
251 for i in range (2):
252         print
253         vv = sorted (values[i].keys ())
254         for v in vv:
255                 print ("#undef %s_%s" %
256                         (what_short[i], short[i][v]))
257 print ()
258 print ("/* == End of generated table == */")
259
260 # Maintain at least 30% occupancy in the table */
261 if occupancy < 30:
262         raise Exception ("Table too sparse, please investigate: ", occupancy)