blob: f70b1ed11dd0d6003a7c7a1b7ef7f1966c2c5fba [file] [log] [blame]
William M. Brack68aca052003-10-11 15:22:13 +00001#!/usr/bin/python -u
2#
3# Portions of this script have been (shamelessly) stolen from the
4# prior work of Daniel Veillard (genUnicode.py)
5#
6# I, however, take full credit for any bugs, errors or difficulties :-)
7#
8# William Brack
9# October 2003
10#
William M. Brack871611b2003-10-18 04:53:14 +000011# 18 October 2003
12# Modified to maintain binary compatibility with previous library versions
13# by adding a suffix 'Q' ('quick') to the macro generated for the original,
14# function, and adding generation of a function (with the original name) which
15# instantiates the macro.
16#
William M. Brack68aca052003-10-11 15:22:13 +000017
18import sys
19import string
20import time
21
22#
William M. Brack68aca052003-10-11 15:22:13 +000023# A routine to take a list of yes/no (1, 0) values and turn it
24# into a list of ranges. This will later be used to determine whether
25# to generate single-byte lookup tables, or inline comparisons
26#
27def makeRange(lst):
28 ret = []
29 pos = 0
30 while pos < len(lst):
31 try: # index generates exception if not present
32 s = lst[pos:].index(1) # look for start of next range
33 except:
34 break # if no more, finished
35 pos += s # pointer to start of possible range
36 try:
37 e = lst[pos:].index(0) # look for end of range
38 e += pos
39 except: # if no end, set to end of list
40 e = len(lst)
41 ret.append((pos, e-1)) # append range tuple to list
42 pos = e + 1 # ready to check for next range
43 return ret
44
45sources = "chvalid.def" # input filename
46
47# minTableSize gives the minimum number of ranges which must be present
48# before a 256-byte lookup table is produced. If there are less than this
49# number, a macro with inline comparisons is generated
50minTableSize = 6
51
William M. Brack68aca052003-10-11 15:22:13 +000052# dictionary of functions, key=name, element contains char-map and range-list
53Functs = {}
54
55state = 0
56
57try:
58 defines = open("chvalid.def", "r")
59except:
60 print "Missing chvalid.def, aborting ..."
61 sys.exit(1)
62
63#
64# The lines in the .def file have three types:-
65# name: Defines a new function block
66# ur: Defines individual or ranges of unicode values
67# end: Indicates the end of the function block
68#
69# These lines are processed below.
70#
71for line in defines.readlines():
72 # ignore blank lines, or lines beginning with '#'
73 if line[0] == '#':
74 continue
75 line = string.strip(line)
76 if line == '':
77 continue
78 # split line into space-separated fields, then split on type
79 try:
80 fields = string.split(line, ' ')
81 #
82 # name line:
83 # validate any previous function block already ended
84 # validate this function not already defined
85 # initialize an entry in the function dicitonary
86 # including a mask table with no values yet defined
87 #
88 if fields[0] == 'name':
89 name = fields[1]
90 if state != 0:
91 print "'name' %s found before previous name" \
92 "completed" % (fields[1])
93 continue
94 state = 1
95 if Functs.has_key(name):
96 print "name '%s' already present - may give" \
97 " wrong results" % (name)
98 else:
99 # dict entry with two list elements (chdata, rangedata)
100 Functs[name] = [ [], [] ]
101 for v in range(256):
102 Functs[name][0].append(0)
103 #
104 # end line:
105 # validate there was a preceding function name line
106 # set state to show no current function active
107 #
108 elif fields[0] == 'end':
109 if state == 0:
110 print "'end' found outside of function block"
111 continue
112 state = 0
113
114 #
115 # ur line:
116 # validate function has been defined
117 # process remaining fields on the line, which may be either
118 # individual unicode values or ranges of values
119 #
120 elif fields[0] == 'ur':
121 if state != 1:
122 raise ValidationError, "'ur' found outside of 'name' block"
123 for el in fields[1:]:
124 pos = string.find(el, '..')
125 # pos <=0 means not a range, so must be individual value
126 if pos <= 0:
127 # cheap handling of hex or decimal values
128 if el[0:2] == '0x':
129 value = int(el[2:],16)
130 elif el[0] == "'":
131 value = ord(el[1])
132 else:
133 value = int(el)
134 if ((value < 0) | (value > 0x1fffff)):
135 raise ValidationError, 'Illegal value (%s) in ch for'\
136 ' name %s' % (el,name)
137 # for ur we have only ranges (makes things simpler),
138 # so convert val to range
139 currange = (value, value)
140 # pos > 0 means this is a range, so isolate/validate
141 # the interval
142 else:
143 # split the range into it's first-val, last-val
144 (first, last) = string.split(el, "..")
145 # convert values from text into binary
146 if first[0:2] == '0x':
147 start = int(first[2:],16)
148 elif first[0] == "'":
149 start = ord(first[1])
150 else:
151 start = int(first)
152 if last[0:2] == '0x':
153 end = int(last[2:],16)
154 elif last[0] == "'":
155 end = ord(last[1])
156 else:
157 end = int(last)
158 if (start < 0) | (end > 0x1fffff) | (start > end):
159 raise ValidationError, "Invalid range '%s'" % el
160 currange = (start, end)
161 # common path - 'currange' has the range, now take care of it
162 # We split on single-byte values vs. multibyte
163 if currange[1] < 0x100: # single-byte
164 for ch in range(currange[0],currange[1]+1):
165 # validate that value not previously defined
166 if Functs[name][0][ch]:
167 msg = "Duplicate ch value '%s' for name '%s'" % (el, name)
168 raise ValidationError, msg
169 Functs[name][0][ch] = 1
170 else: # multi-byte
William M. Brack68aca052003-10-11 15:22:13 +0000171 if currange in Functs[name][1]:
172 raise ValidationError, "range already defined in" \
173 " function"
174 else:
175 Functs[name][1].append(currange)
176
177 except:
178 print "Failed to process line: %s" % (line)
179 raise
180#
181# At this point, the entire definition file has been processed. Now we
182# enter the output phase, where we generate the two files chvalid.c and'
183# chvalid.h
184#
185# To do this, we first output the 'static' data (heading, fixed
186# definitions, etc.), then output the 'dynamic' data (the results
187# of the above processing), and finally output closing 'static' data
188# (e.g. the subroutine to process the ranges)
189#
190
191#
192# Generate the headings:
193#
194try:
Daniel Veillard1a993962003-10-11 20:58:06 +0000195 header = open("include/libxml/chvalid.h", "w")
William M. Brack68aca052003-10-11 15:22:13 +0000196except:
Daniel Veillard1a993962003-10-11 20:58:06 +0000197 print "Failed to open include/libxml/chvalid.h"
William M. Brack68aca052003-10-11 15:22:13 +0000198 sys.exit(1)
199
200try:
201 output = open("chvalid.c", "w")
202except:
203 print "Failed to open chvalid.c"
204 sys.exit(1)
205
206date = time.asctime(time.localtime(time.time()))
207
208header.write(
209"""/*
210 * chvalid.h: this header exports interfaces for the character
211 * range validation APIs
212 *
213 * This file is automatically generated from the cvs source
214 * definition files using the genChRanges.py Python script
215 *
216 * Generation date: %s
217 * Sources: %s
218 * William Brack <wbrack@mmm.com.hk>
219 */
220
221#ifndef __XML_CHVALID_H__
222#define __XML_CHVALID_H__
223
William M. Brack871611b2003-10-18 04:53:14 +0000224#include <libxml/xmlversion.h>
225
William M. Brack68aca052003-10-11 15:22:13 +0000226#ifdef __cplusplus
227extern "C" {
228#endif
229
230/*
231 * Define our typedefs and structures
232 *
233 */
234typedef struct _xmlChSRange xmlChSRange;
235typedef xmlChSRange *xmlChSRangePtr;
236struct _xmlChSRange {
237 unsigned short low;
238 unsigned short high;
239};
240
241typedef struct _xmlChLRange xmlChLRange;
242typedef xmlChLRange *xmlChLRangePtr;
243struct _xmlChLRange {
William M. Brack196b3882003-10-18 12:42:41 +0000244 unsigned int low;
245 unsigned int high;
William M. Brack68aca052003-10-11 15:22:13 +0000246};
247
248typedef struct _xmlChRangeGroup xmlChRangeGroup;
249typedef xmlChRangeGroup *xmlChRangeGroupPtr;
250struct _xmlChRangeGroup {
251 int nbShortRange;
252 int nbLongRange;
253 xmlChSRangePtr shortRange; /* points to an array of ranges */
254 xmlChLRangePtr longRange;
255};
256
William M. Brack196b3882003-10-18 12:42:41 +0000257/**
258 * Range checking routine
259 */
William M. Brack871611b2003-10-18 04:53:14 +0000260XMLPUBFUN int XMLCALL
261 xmlCharInRange(unsigned int val, const xmlChRangeGroupPtr group);
William M. Brack68aca052003-10-11 15:22:13 +0000262
263""" % (date, sources));
264output.write(
265"""/*
266 * chvalid.c: this module implements the character range
267 * validation APIs
268 *
269 * This file is automatically generated from the cvs source
270 * definition files using the genChRanges.py Python script
271 *
272 * Generation date: %s
273 * Sources: %s
274 * William Brack <wbrack@mmm.com.hk>
275 */
276
Daniel Veillardfca7d832003-10-22 08:44:26 +0000277#define IN_LIBXML
278#include "libxml.h"
William M. Brack6819a4e2003-10-11 15:59:36 +0000279#include <libxml/chvalid.h>
William M. Brack68aca052003-10-11 15:22:13 +0000280
281/*
282 * The initial tables ({func_name}_tab) are used to validate whether a
283 * single-byte character is within the specified group. Each table
284 * contains 256 bytes, with each byte representing one of the 256
285 * possible characters. If the table byte is set, the character is
286 * allowed.
287 *
288 */
289""" % (date, sources));
290
291#
292# Now output the generated data.
293# We try to produce the best execution times. Tests have shown that validation
294# with direct table lookup is, when there are a "small" number of valid items,
295# still not as fast as a sequence of inline compares. So, if the single-byte
296# portion of a range has a "small" number of ranges, we output a macro for inline
297# compares, otherwise we output a 256-byte table and a macro to use it.
298#
299
300fkeys = Functs.keys() # Dictionary of all defined functions
301fkeys.sort() # Put some order to our output
302
303for f in fkeys:
304
305# First we convert the specified single-byte values into a group of ranges.
306# If the total number of such ranges is less than minTableSize, we generate
307# an inline macro for direct comparisons; if greater, we generate a lookup
308# table.
309 if max(Functs[f][0]) > 0: # only check if at least one entry
310 rangeTable = makeRange(Functs[f][0])
311 numRanges = len(rangeTable)
312 if numRanges >= minTableSize: # table is worthwhile
William M. Brack871611b2003-10-18 04:53:14 +0000313 header.write("XMLPUBVAR unsigned char %s_tab[256];\n" % f)
William M. Brack196b3882003-10-18 12:42:41 +0000314 header.write("""
315/**
316 * %s_ch:
317 * @c: char to validate
318 *
319 * Automatically generated by genChRanges.py
320 */
321""" % f)
William M. Brack68aca052003-10-11 15:22:13 +0000322 header.write("#define %s_ch(c)\t(%s_tab[(c)])\n" % (f, f))
323
324 # write the constant data to the code file
325 output.write("unsigned char %s_tab[256] = {\n" % f)
326 pline = " "
327 for n in range(255):
328 pline += " 0x%02x," % Functs[f][0][n]
329 if len(pline) > 72:
330 output.write(pline + "\n")
331 pline = " "
332 output.write(pline + " 0x%02x };\n\n" % Functs[f][0][255])
333
334 else: # inline check is used
335 # first another little optimisation - if space is present,
336 # put it at the front of the list so it is checked first
337 try:
338 ix = rangeTable.remove((0x20, 0x20))
339 rangeTable.insert(0, (0x20, 0x20))
340 except:
341 pass
William M. Brack68aca052003-10-11 15:22:13 +0000342 firstFlag = 1
William M. Brack196b3882003-10-18 12:42:41 +0000343
344 header.write("""
345/**
346 * %s_ch:
347 *
348 * @c: char to validate
349 *
350 * Automatically generated by genChRanges.py
351 */
352""" % f)
William M. Brackc4b81892003-10-12 10:42:46 +0000353 # okay, I'm tired of the messy lineup - let's automate it!
354 pline = "#define %s_ch(c)" % f
355 # 'ntab' is number of tabs needed to position to col. 33 from name end
356 ntab = 4 - (len(pline)) / 8
357 if ntab < 0:
358 ntab = 0
359 just = ""
360 for i in range(ntab):
361 just += "\t"
362 pline = pline + just + "("
William M. Brack68aca052003-10-11 15:22:13 +0000363 for rg in rangeTable:
364 if not firstFlag:
William M. Brackc4b81892003-10-12 10:42:46 +0000365 pline += " || \\\n\t\t\t\t "
William M. Brack68aca052003-10-11 15:22:13 +0000366 else:
367 firstFlag = 0
368 if rg[0] == rg[1]: # single value - check equal
William M. Brackc4b81892003-10-12 10:42:46 +0000369 pline += "((c) == 0x%x)" % rg[0]
370 else: # value range
371 pline += "((0x%x <= (c)) &&" % rg[0]
372 pline += " ((c) <= 0x%x))" % rg[1]
William M. Brack68aca052003-10-11 15:22:13 +0000373 pline += ")\n"
374 header.write(pline)
375
William M. Brack196b3882003-10-18 12:42:41 +0000376 header.write("""
377/**
378 * %sQ:
379 * @c: char to validate
380 *
381 * Automatically generated by genChRanges.py
382 */
383""" % f)
William M. Brack871611b2003-10-18 04:53:14 +0000384 pline = "#define %sQ(c)" % f
William M. Brackc4b81892003-10-12 10:42:46 +0000385 ntab = 4 - (len(pline)) / 8
386 if ntab < 0:
387 ntab = 0
388 just = ""
389 for i in range(ntab):
390 just += "\t"
391 header.write(pline + just + "(((c) < 0x100) ? \\\n\t\t\t\t ")
William M. Brack68aca052003-10-11 15:22:13 +0000392 if max(Functs[f][0]) > 0:
393 header.write("%s_ch((c)) :" % f)
394 else:
395 header.write("0 :")
396
397 # if no ranges defined, value invalid if >= 0x100
William M. Brackc4b81892003-10-12 10:42:46 +0000398 numRanges = len(Functs[f][1])
399 if numRanges == 0:
William M. Brack68aca052003-10-11 15:22:13 +0000400 header.write(" 0)\n\n")
401 else:
William M. Brackc4b81892003-10-12 10:42:46 +0000402 if numRanges >= minTableSize:
403 header.write(" \\\n\t\t\t\t xmlCharInRange((c), &%sGroup))\n\n" % f)
404 else: # if < minTableSize, generate inline code
405 firstFlag = 1
406 for rg in Functs[f][1]:
407 if not firstFlag:
408 pline += " || \\\n\t\t\t\t "
409 else:
410 firstFlag = 0
411 pline = "\\\n\t\t\t\t("
412 if rg[0] == rg[1]: # single value - check equal
413 pline += "((c) == 0x%x)" % rg[0]
414 else: # value range
415 pline += "((0x%x <= (c)) &&" % rg[0]
416 pline += " ((c) <= 0x%x))" % rg[1]
417 pline += "))\n\n"
418 header.write(pline)
419
William M. Brack68aca052003-10-11 15:22:13 +0000420
421 if len(Functs[f][1]) > 0:
William M. Brack871611b2003-10-18 04:53:14 +0000422 header.write("XMLPUBVAR xmlChRangeGroup %sGroup;\n" % f)
William M. Brack68aca052003-10-11 15:22:13 +0000423
424
425#
426# Next we do the unicode ranges
427#
428
429for f in fkeys:
430 if len(Functs[f][1]) > 0: # only generate if unicode ranges present
431 rangeTable = Functs[f][1]
432 rangeTable.sort() # ascending tuple sequence
433 numShort = 0
434 numLong = 0
435 for rg in rangeTable:
436 if rg[1] < 0x10000: # if short value
437 if numShort == 0: # first occurence
438 pline = "static xmlChSRange %s_srng[] = { " % f
439 else:
440 pline += ", "
441 numShort += 1
442 if len(pline) > 60:
443 output.write(pline + "\n")
444 pline = " "
445 pline += "{0x%x, 0x%x}" % (rg[0], rg[1])
446 else: # if long value
447 if numLong == 0: # first occurence
448 if numShort > 0: # if there were shorts, finish them off
449 output.write(pline + "};\n")
450 pline = "static xmlChLRange %s_lrng[] = { " % f
451 else:
452 pline += ", "
453 numLong += 1
454 if len(pline) > 60:
455 output.write(pline + "\n")
456 pline = " "
457 pline += "{0x%x, 0x%x}" % (rg[0], rg[1])
458 output.write(pline + "};\n") # finish off last group
459
William M. Brackc4b81892003-10-12 10:42:46 +0000460 pline = "xmlChRangeGroup %sGroup =\n\t{%d, %d, " % (f, numShort, numLong)
William M. Brack68aca052003-10-11 15:22:13 +0000461 if numShort > 0:
462 pline += "%s_srng" % f
William M. Brackc4b81892003-10-12 10:42:46 +0000463 else:
464 pline += "(xmlChSRangePtr)0"
William M. Brack68aca052003-10-11 15:22:13 +0000465 if numLong > 0:
466 pline += ", %s_lrng" % f
William M. Brackc4b81892003-10-12 10:42:46 +0000467 else:
468 pline += ", (xmlChLRangePtr)0"
William M. Brack68aca052003-10-11 15:22:13 +0000469
470 output.write(pline + "};\n\n")
William M. Brack68aca052003-10-11 15:22:13 +0000471
472output.write(
473"""
William M. Brack196b3882003-10-18 12:42:41 +0000474/**
475 * xmlCharInRange:
476 * @val: character to be validated
477 * @rptr: pointer to range to be used to validate
478 *
479 * Does a binary search of the range table to determine if char
480 * is valid
481 *
482 * Returns: true if character valid, false otherwise
483 */
William M. Brack68aca052003-10-11 15:22:13 +0000484int
Daniel Veillard2bd43222003-10-22 08:51:21 +0000485xmlCharInRange (unsigned int val, const xmlChRangeGroupPtr rptr) {
William M. Brack68aca052003-10-11 15:22:13 +0000486 int low, high, mid;
487 xmlChSRangePtr sptr;
488 xmlChLRangePtr lptr;
489 if (val < 0x10000) { /* is val in 'short' or 'long' array? */
490 if (rptr->nbShortRange == 0)
491 return 0;
492 low = 0;
William M. Brackc4b81892003-10-12 10:42:46 +0000493 high = rptr->nbShortRange - 1;
William M. Brack68aca052003-10-11 15:22:13 +0000494 sptr = rptr->shortRange;
495 while (low <= high) {
496 mid = (low + high) / 2;
William M. Brackc4b81892003-10-12 10:42:46 +0000497 if ((unsigned short) val < sptr[mid].low) {
William M. Brack68aca052003-10-11 15:22:13 +0000498 high = mid - 1;
William M. Brackc4b81892003-10-12 10:42:46 +0000499 } else {
500 if ((unsigned short) val > sptr[mid].high) {
501 low = mid + 1;
502 } else {
503 return 1;
504 }
505 }
William M. Brack68aca052003-10-11 15:22:13 +0000506 }
507 } else {
William M. Brackc4b81892003-10-12 10:42:46 +0000508 if (rptr->nbLongRange == 0) {
William M. Brack68aca052003-10-11 15:22:13 +0000509 return 0;
William M. Brackc4b81892003-10-12 10:42:46 +0000510 }
William M. Brack68aca052003-10-11 15:22:13 +0000511 low = 0;
William M. Brackc4b81892003-10-12 10:42:46 +0000512 high = rptr->nbLongRange - 1;
William M. Brack68aca052003-10-11 15:22:13 +0000513 lptr = rptr->longRange;
514 while (low <= high) {
515 mid = (low + high) / 2;
William M. Brackc4b81892003-10-12 10:42:46 +0000516 if (val < lptr[mid].low) {
William M. Brack68aca052003-10-11 15:22:13 +0000517 high = mid - 1;
William M. Brackc4b81892003-10-12 10:42:46 +0000518 } else {
519 if (val > lptr[mid].high) {
520 low = mid + 1;
521 } else {
522 return 1;
523 }
524 }
William M. Brack68aca052003-10-11 15:22:13 +0000525 }
526 }
527 return 0;
528}
529
530""");
531
William M. Brack871611b2003-10-18 04:53:14 +0000532#
533# finally, generate the ABI compatibility functions
534#
535for f in fkeys:
William M. Brack196b3882003-10-18 12:42:41 +0000536 output.write("""
537/**
538 * %s:
539 * @ch: character to validate
540 *
541 * This function is DEPRECATED. Use %s_ch
542 * or %sQ instead
543 *
544 * Returns true if argument valid, false otherwise
545 */
546""" % (f, f, f))
William M. Brack871611b2003-10-18 04:53:14 +0000547 output.write("int\n%s(unsigned int ch) {\n return(%sQ(ch));\n}\n\n" % (f,f))
548 header.write("XMLPUBFUN int XMLCALL\n\t\t%s(unsigned int ch);\n" % f);
549#
550# Run complete - write trailers and close the output files
551#
552
553header.write("""
554#ifdef __cplusplus
555}
556#endif
557#endif /* __XML_CHVALID_H__ */
558""");
559
560header.close()
William M. Brack68aca052003-10-11 15:22:13 +0000561output.close()
William M. Brack871611b2003-10-18 04:53:14 +0000562