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