Imported Upstream version 2.4.0
[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 # Move the outliers NO-BREAK SPACE and DOTTED CIRCLE out
83 singles = {}
84 for u in ALLOWED_SINGLES:
85         singles[u] = data[u]
86         del data[u]
87
88 print ("/* == Start of generated table == */")
89 print ("/*")
90 print (" * The following table is generated by running:")
91 print (" *")
92 print (" *   ./gen-indic-table.py IndicSyllabicCategory.txt IndicPositionalCategory.txt Blocks.txt")
93 print (" *")
94 print (" * on files with these headers:")
95 print (" *")
96 for h in headers:
97         for l in h:
98                 print (" * %s" % (l.strip()))
99 print (" */")
100 print ()
101 print ('#include "hb-ot-shape-complex-indic.hh"')
102 print ()
103
104 # Shorten values
105 short = [{
106         "Bindu":                'Bi',
107         "Cantillation_Mark":    'Ca',
108         "Joiner":               'ZWJ',
109         "Non_Joiner":           'ZWNJ',
110         "Number":               'Nd',
111         "Visarga":              'Vs',
112         "Vowel":                'Vo',
113         "Vowel_Dependent":      'M',
114         "Consonant_Prefixed":   'CPrf',
115         "Other":                'x',
116 },{
117         "Not_Applicable":       'x',
118 }]
119 all_shorts = [{},{}]
120
121 # Add some of the values, to make them more readable, and to avoid duplicates
122
123
124 for i in range (2):
125         for v,s in short[i].items ():
126                 all_shorts[i][s] = v
127
128 what = ["INDIC_SYLLABIC_CATEGORY", "INDIC_MATRA_CATEGORY"]
129 what_short = ["ISC", "IMC"]
130 print ('#pragma GCC diagnostic push')
131 print ('#pragma GCC diagnostic ignored "-Wunused-macros"')
132 for i in range (2):
133         print ()
134         vv = sorted (values[i].keys ())
135         for v in vv:
136                 v_no_and = v.replace ('_And_', '_')
137                 if v in short[i]:
138                         s = short[i][v]
139                 else:
140                         s = ''.join ([c for c in v_no_and if ord ('A') <= ord (c) <= ord ('Z')])
141                         if s in all_shorts[i]:
142                                 raise Exception ("Duplicate short value alias", v, all_shorts[i][s])
143                         all_shorts[i][s] = v
144                         short[i][v] = s
145                 print ("#define %s_%s   %s_%s   %s/* %3d chars; %s */" %
146                         (what_short[i], s, what[i], v.upper (),
147                         '       '* ((48-1 - len (what[i]) - 1 - len (v)) // 8),
148                         values[i][v], v))
149 print ('#pragma GCC diagnostic pop')
150 print ()
151 print ("#define _(S,M) INDIC_COMBINE_CATEGORIES (ISC_##S, IMC_##M)")
152 print ()
153 print ()
154
155 total = 0
156 used = 0
157 last_block = None
158 def print_block (block, start, end, data):
159         global total, used, last_block
160         if block and block != last_block:
161                 print ()
162                 print ()
163                 print ("  /* %s */" % block)
164         num = 0
165         assert start % 8 == 0
166         assert (end+1) % 8 == 0
167         for u in range (start, end+1):
168                 if u % 8 == 0:
169                         print ()
170                         print ("  /* %04X */" % u, end="")
171                 if u in data:
172                         num += 1
173                 d = data.get (u, defaults)
174                 print ("%9s" % ("_(%s,%s)," % (short[0][d[0]], short[1][d[1]])), end="")
175
176         total += end - start + 1
177         used += num
178         if block:
179                 last_block = block
180
181 uu = sorted (data.keys ())
182
183 last = -100000
184 num = 0
185 offset = 0
186 starts = []
187 ends = []
188 print ("static const INDIC_TABLE_ELEMENT_TYPE indic_table[] = {")
189 for u in uu:
190         if u <= last:
191                 continue
192         block = data[u][2]
193
194         start = u//8*8
195         end = start+1
196         while end in uu and block == data[end][2]:
197                 end += 1
198         end = (end-1)//8*8 + 7
199
200         if start != last + 1:
201                 if start - last <= 1+16*3:
202                         print_block (None, last+1, start-1, data)
203                         last = start-1
204                 else:
205                         if last >= 0:
206                                 ends.append (last + 1)
207                                 offset += ends[-1] - starts[-1]
208                         print ()
209                         print ()
210                         print ("#define indic_offset_0x%04xu %d" % (start, offset))
211                         starts.append (start)
212
213         print_block (block, start, end, data)
214         last = end
215 ends.append (last + 1)
216 offset += ends[-1] - starts[-1]
217 print ()
218 print ()
219 occupancy = used * 100. / total
220 page_bits = 12
221 print ("}; /* Table items: %d; occupancy: %d%% */" % (offset, occupancy))
222 print ()
223 print ("INDIC_TABLE_ELEMENT_TYPE")
224 print ("hb_indic_get_categories (hb_codepoint_t u)")
225 print ("{")
226 print ("  switch (u >> %d)" % page_bits)
227 print ("  {")
228 pages = set ([u>>page_bits for u in starts+ends+list (singles.keys ())])
229 for p in sorted(pages):
230         print ("    case 0x%0Xu:" % p)
231         for u,d in singles.items ():
232                 if p != u>>page_bits: continue
233                 print ("      if (unlikely (u == 0x%04Xu)) return _(%s,%s);" % (u, short[0][d[0]], short[1][d[1]]))
234         for (start,end) in zip (starts, ends):
235                 if p not in [start>>page_bits, end>>page_bits]: continue
236                 offset = "indic_offset_0x%04xu" % start
237                 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))
238         print ("      break;")
239         print ("")
240 print ("    default:")
241 print ("      break;")
242 print ("  }")
243 print ("  return _(x,x);")
244 print ("}")
245 print ()
246 print ("#undef _")
247 for i in range (2):
248         print
249         vv = sorted (values[i].keys ())
250         for v in vv:
251                 print ("#undef %s_%s" %
252                         (what_short[i], short[i][v]))
253 print ()
254 print ("/* == End of generated table == */")
255
256 # Maintain at least 30% occupancy in the table */
257 if occupancy < 30:
258         raise Exception ("Table too sparse, please investigate: ", occupancy)