1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4#
5# Generated  by generateDS.py.
6#
7#
8# Command line options:
9#   ('--no-dates', '')
10#   ('--no-versions', '')
11#   ('-f', '')
12#   ('-o', '.../addon/doxmlparser/doxmlparser/index.py')
13#
14# Command line arguments:
15#  .../templates/xml/index.xsd
16#
17# Command line:
18#  .../generateDS --no-dates --no-versions -f -o ".../addon/doxmlparser/doxmlparser/index.py" .../templates/xml/index.xsd
19#
20# Current working directory (os.getcwd()):
21#   doxmlparser
22#
23
24import sys
25try:
26    ModulenotfoundExp_ = ModuleNotFoundError
27except NameError:
28    ModulenotfoundExp_ = ImportError
29from six.moves import zip_longest
30import os
31import re as re_
32import base64
33import datetime as datetime_
34import decimal as decimal_
35try:
36    from lxml import etree as etree_
37except ModulenotfoundExp_ :
38    from xml.etree import ElementTree as etree_
39
40
41Validate_simpletypes_ = True
42SaveElementTreeNode = True
43if sys.version_info.major == 2:
44    BaseStrType_ = basestring
45else:
46    BaseStrType_ = str
47
48
49def parsexml_(infile, parser=None, **kwargs):
50    if parser is None:
51        # Use the lxml ElementTree compatible parser so that, e.g.,
52        #   we ignore comments.
53        try:
54            parser = etree_.ETCompatXMLParser()
55        except AttributeError:
56            # fallback to xml.etree
57            parser = etree_.XMLParser()
58    try:
59        if isinstance(infile, os.PathLike):
60            infile = os.path.join(infile)
61    except AttributeError:
62        pass
63    doc = etree_.parse(infile, parser=parser, **kwargs)
64    return doc
65
66def parsexmlstring_(instring, parser=None, **kwargs):
67    if parser is None:
68        # Use the lxml ElementTree compatible parser so that, e.g.,
69        #   we ignore comments.
70        try:
71            parser = etree_.ETCompatXMLParser()
72        except AttributeError:
73            # fallback to xml.etree
74            parser = etree_.XMLParser()
75    element = etree_.fromstring(instring, parser=parser, **kwargs)
76    return element
77
78#
79# Namespace prefix definition table (and other attributes, too)
80#
81# The module generatedsnamespaces, if it is importable, must contain
82# a dictionary named GeneratedsNamespaceDefs.  This Python dictionary
83# should map element type names (strings) to XML schema namespace prefix
84# definitions.  The export method for any class for which there is
85# a namespace prefix definition, will export that definition in the
86# XML representation of that element.  See the export method of
87# any generated element type class for an example of the use of this
88# table.
89# A sample table is:
90#
91#     # File: generatedsnamespaces.py
92#
93#     GenerateDSNamespaceDefs = {
94#         "ElementtypeA": "http://www.xxx.com/namespaceA",
95#         "ElementtypeB": "http://www.xxx.com/namespaceB",
96#     }
97#
98# Additionally, the generatedsnamespaces module can contain a python
99# dictionary named GenerateDSNamespaceTypePrefixes that associates element
100# types with the namespace prefixes that are to be added to the
101# "xsi:type" attribute value.  See the exportAttributes method of
102# any generated element type and the generation of "xsi:type" for an
103# example of the use of this table.
104# An example table:
105#
106#     # File: generatedsnamespaces.py
107#
108#     GenerateDSNamespaceTypePrefixes = {
109#         "ElementtypeC": "aaa:",
110#         "ElementtypeD": "bbb:",
111#     }
112#
113
114try:
115    from generatedsnamespaces import GenerateDSNamespaceDefs as GenerateDSNamespaceDefs_
116except ModulenotfoundExp_ :
117    GenerateDSNamespaceDefs_ = {}
118try:
119    from generatedsnamespaces import GenerateDSNamespaceTypePrefixes as GenerateDSNamespaceTypePrefixes_
120except ModulenotfoundExp_ :
121    GenerateDSNamespaceTypePrefixes_ = {}
122
123#
124# You can replace the following class definition by defining an
125# importable module named "generatedscollector" containing a class
126# named "GdsCollector".  See the default class definition below for
127# clues about the possible content of that class.
128#
129try:
130    from generatedscollector import GdsCollector as GdsCollector_
131except ModulenotfoundExp_ :
132
133    class GdsCollector_(object):
134
135        def __init__(self, messages=None):
136            if messages is None:
137                self.messages = []
138            else:
139                self.messages = messages
140
141        def add_message(self, msg):
142            self.messages.append(msg)
143
144        def get_messages(self):
145            return self.messages
146
147        def clear_messages(self):
148            self.messages = []
149
150        def print_messages(self):
151            for msg in self.messages:
152                print("Warning: {}".format(msg))
153
154        def write_messages(self, outstream):
155            for msg in self.messages:
156                outstream.write("Warning: {}\n".format(msg))
157
158
159#
160# The super-class for enum types
161#
162
163try:
164    from enum import Enum
165except ModulenotfoundExp_ :
166    Enum = object
167
168#
169# The root super-class for element type classes
170#
171# Calls to the methods in these classes are generated by generateDS.py.
172# You can replace these methods by re-implementing the following class
173#   in a module named generatedssuper.py.
174
175try:
176    from generatedssuper import GeneratedsSuper
177except ModulenotfoundExp_ as exp:
178
179    class GeneratedsSuper(object):
180        __hash__ = object.__hash__
181        tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$')
182        class _FixedOffsetTZ(datetime_.tzinfo):
183            def __init__(self, offset, name):
184                self.__offset = datetime_.timedelta(minutes=offset)
185                self.__name = name
186            def utcoffset(self, dt):
187                return self.__offset
188            def tzname(self, dt):
189                return self.__name
190            def dst(self, dt):
191                return None
192        def gds_format_string(self, input_data, input_name=''):
193            return input_data
194        def gds_parse_string(self, input_data, node=None, input_name=''):
195            return input_data
196        def gds_validate_string(self, input_data, node=None, input_name=''):
197            if not input_data:
198                return ''
199            else:
200                return input_data
201        def gds_format_base64(self, input_data, input_name=''):
202            return base64.b64encode(input_data)
203        def gds_validate_base64(self, input_data, node=None, input_name=''):
204            return input_data
205        def gds_format_integer(self, input_data, input_name=''):
206            return '%d' % input_data
207        def gds_parse_integer(self, input_data, node=None, input_name=''):
208            try:
209                ival = int(input_data)
210            except (TypeError, ValueError) as exp:
211                raise_parse_error(node, 'Requires integer value: %s' % exp)
212            return ival
213        def gds_validate_integer(self, input_data, node=None, input_name=''):
214            try:
215                value = int(input_data)
216            except (TypeError, ValueError):
217                raise_parse_error(node, 'Requires integer value')
218            return value
219        def gds_format_integer_list(self, input_data, input_name=''):
220            if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_):
221                input_data = [str(s) for s in input_data]
222            return '%s' % ' '.join(input_data)
223        def gds_validate_integer_list(
224                self, input_data, node=None, input_name=''):
225            values = input_data.split()
226            for value in values:
227                try:
228                    int(value)
229                except (TypeError, ValueError):
230                    raise_parse_error(node, 'Requires sequence of integer values')
231            return values
232        def gds_format_float(self, input_data, input_name=''):
233            return ('%.15f' % input_data).rstrip('0')
234        def gds_parse_float(self, input_data, node=None, input_name=''):
235            try:
236                fval_ = float(input_data)
237            except (TypeError, ValueError) as exp:
238                raise_parse_error(node, 'Requires float or double value: %s' % exp)
239            return fval_
240        def gds_validate_float(self, input_data, node=None, input_name=''):
241            try:
242                value = float(input_data)
243            except (TypeError, ValueError):
244                raise_parse_error(node, 'Requires float value')
245            return value
246        def gds_format_float_list(self, input_data, input_name=''):
247            if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_):
248                input_data = [str(s) for s in input_data]
249            return '%s' % ' '.join(input_data)
250        def gds_validate_float_list(
251                self, input_data, node=None, input_name=''):
252            values = input_data.split()
253            for value in values:
254                try:
255                    float(value)
256                except (TypeError, ValueError):
257                    raise_parse_error(node, 'Requires sequence of float values')
258            return values
259        def gds_format_decimal(self, input_data, input_name=''):
260            return_value = '%s' % input_data
261            if '.' in return_value:
262                return_value = return_value.rstrip('0')
263                if return_value.endswith('.'):
264                    return_value = return_value.rstrip('.')
265            return return_value
266        def gds_parse_decimal(self, input_data, node=None, input_name=''):
267            try:
268                decimal_value = decimal_.Decimal(input_data)
269            except (TypeError, ValueError):
270                raise_parse_error(node, 'Requires decimal value')
271            return decimal_value
272        def gds_validate_decimal(self, input_data, node=None, input_name=''):
273            try:
274                value = decimal_.Decimal(input_data)
275            except (TypeError, ValueError):
276                raise_parse_error(node, 'Requires decimal value')
277            return value
278        def gds_format_decimal_list(self, input_data, input_name=''):
279            if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_):
280                input_data = [str(s) for s in input_data]
281            return ' '.join([self.gds_format_decimal(item) for item in input_data])
282        def gds_validate_decimal_list(
283                self, input_data, node=None, input_name=''):
284            values = input_data.split()
285            for value in values:
286                try:
287                    decimal_.Decimal(value)
288                except (TypeError, ValueError):
289                    raise_parse_error(node, 'Requires sequence of decimal values')
290            return values
291        def gds_format_double(self, input_data, input_name=''):
292            return '%s' % input_data
293        def gds_parse_double(self, input_data, node=None, input_name=''):
294            try:
295                fval_ = float(input_data)
296            except (TypeError, ValueError) as exp:
297                raise_parse_error(node, 'Requires double or float value: %s' % exp)
298            return fval_
299        def gds_validate_double(self, input_data, node=None, input_name=''):
300            try:
301                value = float(input_data)
302            except (TypeError, ValueError):
303                raise_parse_error(node, 'Requires double or float value')
304            return value
305        def gds_format_double_list(self, input_data, input_name=''):
306            if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_):
307                input_data = [str(s) for s in input_data]
308            return '%s' % ' '.join(input_data)
309        def gds_validate_double_list(
310                self, input_data, node=None, input_name=''):
311            values = input_data.split()
312            for value in values:
313                try:
314                    float(value)
315                except (TypeError, ValueError):
316                    raise_parse_error(
317                        node, 'Requires sequence of double or float values')
318            return values
319        def gds_format_boolean(self, input_data, input_name=''):
320            return ('%s' % input_data).lower()
321        def gds_parse_boolean(self, input_data, node=None, input_name=''):
322            if input_data in ('true', '1'):
323                bval = True
324            elif input_data in ('false', '0'):
325                bval = False
326            else:
327                raise_parse_error(node, 'Requires boolean value')
328            return bval
329        def gds_validate_boolean(self, input_data, node=None, input_name=''):
330            if input_data not in (True, 1, False, 0, ):
331                raise_parse_error(
332                    node,
333                    'Requires boolean value '
334                    '(one of True, 1, False, 0)')
335            return input_data
336        def gds_format_boolean_list(self, input_data, input_name=''):
337            if len(input_data) > 0 and not isinstance(input_data[0], BaseStrType_):
338                input_data = [str(s) for s in input_data]
339            return '%s' % ' '.join(input_data)
340        def gds_validate_boolean_list(
341                self, input_data, node=None, input_name=''):
342            values = input_data.split()
343            for value in values:
344                if value not in (True, 1, False, 0, ):
345                    raise_parse_error(
346                        node,
347                        'Requires sequence of boolean values '
348                        '(one of True, 1, False, 0)')
349            return values
350        def gds_validate_datetime(self, input_data, node=None, input_name=''):
351            return input_data
352        def gds_format_datetime(self, input_data, input_name=''):
353            if input_data.microsecond == 0:
354                _svalue = '%04d-%02d-%02dT%02d:%02d:%02d' % (
355                    input_data.year,
356                    input_data.month,
357                    input_data.day,
358                    input_data.hour,
359                    input_data.minute,
360                    input_data.second,
361                )
362            else:
363                _svalue = '%04d-%02d-%02dT%02d:%02d:%02d.%s' % (
364                    input_data.year,
365                    input_data.month,
366                    input_data.day,
367                    input_data.hour,
368                    input_data.minute,
369                    input_data.second,
370                    ('%f' % (float(input_data.microsecond) / 1000000))[2:],
371                )
372            if input_data.tzinfo is not None:
373                tzoff = input_data.tzinfo.utcoffset(input_data)
374                if tzoff is not None:
375                    total_seconds = tzoff.seconds + (86400 * tzoff.days)
376                    if total_seconds == 0:
377                        _svalue += 'Z'
378                    else:
379                        if total_seconds < 0:
380                            _svalue += '-'
381                            total_seconds *= -1
382                        else:
383                            _svalue += '+'
384                        hours = total_seconds // 3600
385                        minutes = (total_seconds - (hours * 3600)) // 60
386                        _svalue += '{0:02d}:{1:02d}'.format(hours, minutes)
387            return _svalue
388        @classmethod
389        def gds_parse_datetime(cls, input_data):
390            tz = None
391            if input_data[-1] == 'Z':
392                tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC')
393                input_data = input_data[:-1]
394            else:
395                results = GeneratedsSuper.tzoff_pattern.search(input_data)
396                if results is not None:
397                    tzoff_parts = results.group(2).split(':')
398                    tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1])
399                    if results.group(1) == '-':
400                        tzoff *= -1
401                    tz = GeneratedsSuper._FixedOffsetTZ(
402                        tzoff, results.group(0))
403                    input_data = input_data[:-6]
404            time_parts = input_data.split('.')
405            if len(time_parts) > 1:
406                micro_seconds = int(float('0.' + time_parts[1]) * 1000000)
407                input_data = '%s.%s' % (
408                    time_parts[0], "{}".format(micro_seconds).rjust(6, "0"), )
409                dt = datetime_.datetime.strptime(
410                    input_data, '%Y-%m-%dT%H:%M:%S.%f')
411            else:
412                dt = datetime_.datetime.strptime(
413                    input_data, '%Y-%m-%dT%H:%M:%S')
414            dt = dt.replace(tzinfo=tz)
415            return dt
416        def gds_validate_date(self, input_data, node=None, input_name=''):
417            return input_data
418        def gds_format_date(self, input_data, input_name=''):
419            _svalue = '%04d-%02d-%02d' % (
420                input_data.year,
421                input_data.month,
422                input_data.day,
423            )
424            try:
425                if input_data.tzinfo is not None:
426                    tzoff = input_data.tzinfo.utcoffset(input_data)
427                    if tzoff is not None:
428                        total_seconds = tzoff.seconds + (86400 * tzoff.days)
429                        if total_seconds == 0:
430                            _svalue += 'Z'
431                        else:
432                            if total_seconds < 0:
433                                _svalue += '-'
434                                total_seconds *= -1
435                            else:
436                                _svalue += '+'
437                            hours = total_seconds // 3600
438                            minutes = (total_seconds - (hours * 3600)) // 60
439                            _svalue += '{0:02d}:{1:02d}'.format(
440                                hours, minutes)
441            except AttributeError:
442                pass
443            return _svalue
444        @classmethod
445        def gds_parse_date(cls, input_data):
446            tz = None
447            if input_data[-1] == 'Z':
448                tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC')
449                input_data = input_data[:-1]
450            else:
451                results = GeneratedsSuper.tzoff_pattern.search(input_data)
452                if results is not None:
453                    tzoff_parts = results.group(2).split(':')
454                    tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1])
455                    if results.group(1) == '-':
456                        tzoff *= -1
457                    tz = GeneratedsSuper._FixedOffsetTZ(
458                        tzoff, results.group(0))
459                    input_data = input_data[:-6]
460            dt = datetime_.datetime.strptime(input_data, '%Y-%m-%d')
461            dt = dt.replace(tzinfo=tz)
462            return dt.date()
463        def gds_validate_time(self, input_data, node=None, input_name=''):
464            return input_data
465        def gds_format_time(self, input_data, input_name=''):
466            if input_data.microsecond == 0:
467                _svalue = '%02d:%02d:%02d' % (
468                    input_data.hour,
469                    input_data.minute,
470                    input_data.second,
471                )
472            else:
473                _svalue = '%02d:%02d:%02d.%s' % (
474                    input_data.hour,
475                    input_data.minute,
476                    input_data.second,
477                    ('%f' % (float(input_data.microsecond) / 1000000))[2:],
478                )
479            if input_data.tzinfo is not None:
480                tzoff = input_data.tzinfo.utcoffset(input_data)
481                if tzoff is not None:
482                    total_seconds = tzoff.seconds + (86400 * tzoff.days)
483                    if total_seconds == 0:
484                        _svalue += 'Z'
485                    else:
486                        if total_seconds < 0:
487                            _svalue += '-'
488                            total_seconds *= -1
489                        else:
490                            _svalue += '+'
491                        hours = total_seconds // 3600
492                        minutes = (total_seconds - (hours * 3600)) // 60
493                        _svalue += '{0:02d}:{1:02d}'.format(hours, minutes)
494            return _svalue
495        def gds_validate_simple_patterns(self, patterns, target):
496            # pat is a list of lists of strings/patterns.
497            # The target value must match at least one of the patterns
498            # in order for the test to succeed.
499            found1 = True
500            for patterns1 in patterns:
501                found2 = False
502                for patterns2 in patterns1:
503                    mo = re_.search(patterns2, target)
504                    if mo is not None and len(mo.group(0)) == len(target):
505                        found2 = True
506                        break
507                if not found2:
508                    found1 = False
509                    break
510            return found1
511        @classmethod
512        def gds_parse_time(cls, input_data):
513            tz = None
514            if input_data[-1] == 'Z':
515                tz = GeneratedsSuper._FixedOffsetTZ(0, 'UTC')
516                input_data = input_data[:-1]
517            else:
518                results = GeneratedsSuper.tzoff_pattern.search(input_data)
519                if results is not None:
520                    tzoff_parts = results.group(2).split(':')
521                    tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1])
522                    if results.group(1) == '-':
523                        tzoff *= -1
524                    tz = GeneratedsSuper._FixedOffsetTZ(
525                        tzoff, results.group(0))
526                    input_data = input_data[:-6]
527            if len(input_data.split('.')) > 1:
528                dt = datetime_.datetime.strptime(input_data, '%H:%M:%S.%f')
529            else:
530                dt = datetime_.datetime.strptime(input_data, '%H:%M:%S')
531            dt = dt.replace(tzinfo=tz)
532            return dt.time()
533        def gds_check_cardinality_(
534                self, value, input_name,
535                min_occurs=0, max_occurs=1, required=None):
536            if value is None:
537                length = 0
538            elif isinstance(value, list):
539                length = len(value)
540            else:
541                length = 1
542            if required is not None :
543                if required and length < 1:
544                    self.gds_collector_.add_message(
545                        "Required value {}{} is missing".format(
546                            input_name, self.gds_get_node_lineno_()))
547            if length < min_occurs:
548                self.gds_collector_.add_message(
549                    "Number of values for {}{} is below "
550                    "the minimum allowed, "
551                    "expected at least {}, found {}".format(
552                        input_name, self.gds_get_node_lineno_(),
553                        min_occurs, length))
554            elif length > max_occurs:
555                self.gds_collector_.add_message(
556                    "Number of values for {}{} is above "
557                    "the maximum allowed, "
558                    "expected at most {}, found {}".format(
559                        input_name, self.gds_get_node_lineno_(),
560                        max_occurs, length))
561        def gds_validate_builtin_ST_(
562                self, validator, value, input_name,
563                min_occurs=None, max_occurs=None, required=None):
564            if value is not None:
565                try:
566                    validator(value, input_name=input_name)
567                except GDSParseError as parse_error:
568                    self.gds_collector_.add_message(str(parse_error))
569        def gds_validate_defined_ST_(
570                self, validator, value, input_name,
571                min_occurs=None, max_occurs=None, required=None):
572            if value is not None:
573                try:
574                    validator(value)
575                except GDSParseError as parse_error:
576                    self.gds_collector_.add_message(str(parse_error))
577        def gds_str_lower(self, instring):
578            return instring.lower()
579        def get_path_(self, node):
580            path_list = []
581            self.get_path_list_(node, path_list)
582            path_list.reverse()
583            path = '/'.join(path_list)
584            return path
585        Tag_strip_pattern_ = re_.compile(r'\{.*\}')
586        def get_path_list_(self, node, path_list):
587            if node is None:
588                return
589            tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag)
590            if tag:
591                path_list.append(tag)
592            self.get_path_list_(node.getparent(), path_list)
593        def get_class_obj_(self, node, default_class=None):
594            class_obj1 = default_class
595            if 'xsi' in node.nsmap:
596                classname = node.get('{%s}type' % node.nsmap['xsi'])
597                if classname is not None:
598                    names = classname.split(':')
599                    if len(names) == 2:
600                        classname = names[1]
601                    class_obj2 = globals().get(classname)
602                    if class_obj2 is not None:
603                        class_obj1 = class_obj2
604            return class_obj1
605        def gds_build_any(self, node, type_name=None):
606            # provide default value in case option --disable-xml is used.
607            content = ""
608            content = etree_.tostring(node, encoding="unicode")
609            return content
610        @classmethod
611        def gds_reverse_node_mapping(cls, mapping):
612            return dict(((v, k) for k, v in mapping.items()))
613        @staticmethod
614        def gds_encode(instring):
615            if sys.version_info.major == 2:
616                if ExternalEncoding:
617                    encoding = ExternalEncoding
618                else:
619                    encoding = 'utf-8'
620                return instring.encode(encoding)
621            else:
622                return instring
623        @staticmethod
624        def convert_unicode(instring):
625            if isinstance(instring, str):
626                result = quote_xml(instring)
627            elif sys.version_info.major == 2 and isinstance(instring, unicode):
628                result = quote_xml(instring).encode('utf8')
629            else:
630                result = GeneratedsSuper.gds_encode(str(instring))
631            return result
632        def __eq__(self, other):
633            def excl_select_objs_(obj):
634                return (obj[0] != 'parent_object_' and
635                        obj[0] != 'gds_collector_')
636            if type(self) != type(other):
637                return False
638            return all(x == y for x, y in zip_longest(
639                filter(excl_select_objs_, self.__dict__.items()),
640                filter(excl_select_objs_, other.__dict__.items())))
641        def __ne__(self, other):
642            return not self.__eq__(other)
643        # Django ETL transform hooks.
644        def gds_djo_etl_transform(self):
645            pass
646        def gds_djo_etl_transform_db_obj(self, dbobj):
647            pass
648        # SQLAlchemy ETL transform hooks.
649        def gds_sqa_etl_transform(self):
650            return 0, None
651        def gds_sqa_etl_transform_db_obj(self, dbobj):
652            pass
653        def gds_get_node_lineno_(self):
654            if (hasattr(self, "gds_elementtree_node_") and
655                    self.gds_elementtree_node_ is not None):
656                return ' near line {}'.format(
657                    self.gds_elementtree_node_.sourceline)
658            else:
659                return ""
660
661
662    def getSubclassFromModule_(module, class_):
663        '''Get the subclass of a class from a specific module.'''
664        name = class_.__name__ + 'Sub'
665        if hasattr(module, name):
666            return getattr(module, name)
667        else:
668            return None
669
670
671#
672# If you have installed IPython you can uncomment and use the following.
673# IPython is available from http://ipython.scipy.org/.
674#
675
676## from IPython.Shell import IPShellEmbed
677## args = ''
678## ipshell = IPShellEmbed(args,
679##     banner = 'Dropping into IPython',
680##     exit_msg = 'Leaving Interpreter, back to program.')
681
682# Then use the following line where and when you want to drop into the
683# IPython shell:
684#    ipshell('<some message> -- Entering ipshell.\nHit Ctrl-D to exit')
685
686#
687# Globals
688#
689
690ExternalEncoding = ''
691# Set this to false in order to deactivate during export, the use of
692# name space prefixes captured from the input document.
693UseCapturedNS_ = True
694CapturedNsmap_ = {}
695Tag_pattern_ = re_.compile(r'({.*})?(.*)')
696String_cleanup_pat_ = re_.compile(r"[\n\r\s]+")
697Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)')
698CDATA_pattern_ = re_.compile(r"<!\[CDATA\[.*?\]\]>", re_.DOTALL)
699
700# Change this to redirect the generated superclass module to use a
701# specific subclass module.
702CurrentSubclassModule_ = None
703
704#
705# Support/utility functions.
706#
707
708
709def showIndent(outfile, level, pretty_print=True):
710    if pretty_print:
711        for idx in range(level):
712            outfile.write('    ')
713
714
715def quote_xml(inStr):
716    "Escape markup chars, but do not modify CDATA sections."
717    if not inStr:
718        return ''
719    s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr)
720    s2 = ''
721    pos = 0
722    matchobjects = CDATA_pattern_.finditer(s1)
723    for mo in matchobjects:
724        s3 = s1[pos:mo.start()]
725        s2 += quote_xml_aux(s3)
726        s2 += s1[mo.start():mo.end()]
727        pos = mo.end()
728    s3 = s1[pos:]
729    s2 += quote_xml_aux(s3)
730    return s2
731
732
733def quote_xml_aux(inStr):
734    s1 = inStr.replace('&', '&amp;')
735    s1 = s1.replace('<', '&lt;')
736    s1 = s1.replace('>', '&gt;')
737    return s1
738
739
740def quote_attrib(inStr):
741    s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr)
742    s1 = s1.replace('&', '&amp;')
743    s1 = s1.replace('<', '&lt;')
744    s1 = s1.replace('>', '&gt;')
745    if '"' in s1:
746        if "'" in s1:
747            s1 = '"%s"' % s1.replace('"', "&quot;")
748        else:
749            s1 = "'%s'" % s1
750    else:
751        s1 = '"%s"' % s1
752    return s1
753
754
755def quote_python(inStr):
756    s1 = inStr
757    if s1.find("'") == -1:
758        if s1.find('\n') == -1:
759            return "'%s'" % s1
760        else:
761            return "'''%s'''" % s1
762    else:
763        if s1.find('"') != -1:
764            s1 = s1.replace('"', '\\"')
765        if s1.find('\n') == -1:
766            return '"%s"' % s1
767        else:
768            return '"""%s"""' % s1
769
770
771def get_all_text_(node):
772    if node.text is not None:
773        text = node.text
774    else:
775        text = ''
776    for child in node:
777        if child.tail is not None:
778            text += child.tail
779    return text
780
781
782def find_attr_value_(attr_name, node):
783    attrs = node.attrib
784    attr_parts = attr_name.split(':')
785    value = None
786    if len(attr_parts) == 1:
787        value = attrs.get(attr_name)
788    elif len(attr_parts) == 2:
789        prefix, name = attr_parts
790        if prefix == 'xml':
791            namespace = 'http://www.w3.org/XML/1998/namespace'
792        else:
793            namespace = node.nsmap.get(prefix)
794        if namespace is not None:
795            value = attrs.get('{%s}%s' % (namespace, name, ))
796    return value
797
798
799def encode_str_2_3(instr):
800    return instr
801
802
803class GDSParseError(Exception):
804    pass
805
806
807def raise_parse_error(node, msg):
808    if node is not None:
809        msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, )
810    raise GDSParseError(msg)
811
812
813class MixedContainer:
814    # Constants for category:
815    CategoryNone = 0
816    CategoryText = 1
817    CategorySimple = 2
818    CategoryComplex = 3
819    # Constants for content_type:
820    TypeNone = 0
821    TypeText = 1
822    TypeString = 2
823    TypeInteger = 3
824    TypeFloat = 4
825    TypeDecimal = 5
826    TypeDouble = 6
827    TypeBoolean = 7
828    TypeBase64 = 8
829    def __init__(self, category, content_type, name, value):
830        self.category = category
831        self.content_type = content_type
832        self.name = name
833        self.value = value
834    def getCategory(self):
835        return self.category
836    def getContenttype(self, content_type):
837        return self.content_type
838    def getValue(self):
839        return self.value
840    def getName(self):
841        return self.name
842    def export(self, outfile, level, name, namespace,
843               pretty_print=True):
844        if self.category == MixedContainer.CategoryText:
845            # Prevent exporting empty content as empty lines.
846            if self.value.strip():
847                outfile.write(self.value)
848        elif self.category == MixedContainer.CategorySimple:
849            self.exportSimple(outfile, level, name)
850        else:    # category == MixedContainer.CategoryComplex
851            self.value.export(
852                outfile, level, namespace, name_=name,
853                pretty_print=pretty_print)
854    def exportSimple(self, outfile, level, name):
855        if self.content_type == MixedContainer.TypeString:
856            outfile.write('<%s>%s</%s>' % (
857                self.name, self.value, self.name))
858        elif self.content_type == MixedContainer.TypeInteger or \
859                self.content_type == MixedContainer.TypeBoolean:
860            outfile.write('<%s>%d</%s>' % (
861                self.name, self.value, self.name))
862        elif self.content_type == MixedContainer.TypeFloat or \
863                self.content_type == MixedContainer.TypeDecimal:
864            outfile.write('<%s>%f</%s>' % (
865                self.name, self.value, self.name))
866        elif self.content_type == MixedContainer.TypeDouble:
867            outfile.write('<%s>%g</%s>' % (
868                self.name, self.value, self.name))
869        elif self.content_type == MixedContainer.TypeBase64:
870            outfile.write('<%s>%s</%s>' % (
871                self.name,
872                base64.b64encode(self.value),
873                self.name))
874    def to_etree(self, element, mapping_=None, nsmap_=None):
875        if self.category == MixedContainer.CategoryText:
876            # Prevent exporting empty content as empty lines.
877            if self.value.strip():
878                if len(element) > 0:
879                    if element[-1].tail is None:
880                        element[-1].tail = self.value
881                    else:
882                        element[-1].tail += self.value
883                else:
884                    if element.text is None:
885                        element.text = self.value
886                    else:
887                        element.text += self.value
888        elif self.category == MixedContainer.CategorySimple:
889            subelement = etree_.SubElement(
890                element, '%s' % self.name)
891            subelement.text = self.to_etree_simple()
892        else:    # category == MixedContainer.CategoryComplex
893            self.value.to_etree(element)
894    def to_etree_simple(self, mapping_=None, nsmap_=None):
895        if self.content_type == MixedContainer.TypeString:
896            text = self.value
897        elif (self.content_type == MixedContainer.TypeInteger or
898                self.content_type == MixedContainer.TypeBoolean):
899            text = '%d' % self.value
900        elif (self.content_type == MixedContainer.TypeFloat or
901                self.content_type == MixedContainer.TypeDecimal):
902            text = '%f' % self.value
903        elif self.content_type == MixedContainer.TypeDouble:
904            text = '%g' % self.value
905        elif self.content_type == MixedContainer.TypeBase64:
906            text = '%s' % base64.b64encode(self.value)
907        return text
908    def exportLiteral(self, outfile, level, name):
909        if self.category == MixedContainer.CategoryText:
910            showIndent(outfile, level)
911            outfile.write(
912                'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % (
913                    self.category, self.content_type,
914                    self.name, self.value))
915        elif self.category == MixedContainer.CategorySimple:
916            showIndent(outfile, level)
917            outfile.write(
918                'model_.MixedContainer(%d, %d, "%s", "%s"),\n' % (
919                    self.category, self.content_type,
920                    self.name, self.value))
921        else:    # category == MixedContainer.CategoryComplex
922            showIndent(outfile, level)
923            outfile.write(
924                'model_.MixedContainer(%d, %d, "%s",\n' % (
925                    self.category, self.content_type, self.name,))
926            self.value.exportLiteral(outfile, level + 1)
927            showIndent(outfile, level)
928            outfile.write(')\n')
929
930
931class MemberSpec_(object):
932    def __init__(self, name='', data_type='', container=0,
933            optional=0, child_attrs=None, choice=None):
934        self.name = name
935        self.data_type = data_type
936        self.container = container
937        self.child_attrs = child_attrs
938        self.choice = choice
939        self.optional = optional
940    def set_name(self, name): self.name = name
941    def get_name(self): return self.name
942    def set_data_type(self, data_type): self.data_type = data_type
943    def get_data_type_chain(self): return self.data_type
944    def get_data_type(self):
945        if isinstance(self.data_type, list):
946            if len(self.data_type) > 0:
947                return self.data_type[-1]
948            else:
949                return 'xs:string'
950        else:
951            return self.data_type
952    def set_container(self, container): self.container = container
953    def get_container(self): return self.container
954    def set_child_attrs(self, child_attrs): self.child_attrs = child_attrs
955    def get_child_attrs(self): return self.child_attrs
956    def set_choice(self, choice): self.choice = choice
957    def get_choice(self): return self.choice
958    def set_optional(self, optional): self.optional = optional
959    def get_optional(self): return self.optional
960
961
962def _cast(typ, value):
963    if typ is None or value is None:
964        return value
965    return typ(value)
966
967#
968# Data representation classes.
969#
970
971
972class CompoundKind(str, Enum):
973    CLASS='class'
974    STRUCT='struct'
975    UNION='union'
976    INTERFACE='interface'
977    PROTOCOL='protocol'
978    CATEGORY='category'
979    EXCEPTION='exception'
980    FILE='file'
981    NAMESPACE='namespace'
982    GROUP='group'
983    PAGE='page'
984    EXAMPLE='example'
985    DIR='dir'
986    TYPE='type'
987    CONCEPT='concept'
988
989
990class MemberKind(str, Enum):
991    DEFINE='define'
992    PROPERTY='property'
993    EVENT='event'
994    VARIABLE='variable'
995    TYPEDEF='typedef'
996    ENUM='enum'
997    ENUMVALUE='enumvalue'
998    FUNCTION='function'
999    SIGNAL='signal'
1000    PROTOTYPE='prototype'
1001    FRIEND='friend'
1002    DCOP='dcop'
1003    SLOT='slot'
1004
1005
1006class DoxygenType(GeneratedsSuper):
1007    __hash__ = GeneratedsSuper.__hash__
1008    subclass = None
1009    superclass = None
1010    def __init__(self, version=None, lang=None, compound=None, gds_collector_=None, **kwargs_):
1011        self.gds_collector_ = gds_collector_
1012        self.gds_elementtree_node_ = None
1013        self.original_tagname_ = None
1014        self.parent_object_ = kwargs_.get('parent_object_')
1015        self.ns_prefix_ = None
1016        self.version = _cast(None, version)
1017        self.version_nsprefix_ = None
1018        self.lang = _cast(None, lang)
1019        self.lang_nsprefix_ = None
1020        if compound is None:
1021            self.compound = []
1022        else:
1023            self.compound = compound
1024        self.compound_nsprefix_ = None
1025    def factory(*args_, **kwargs_):
1026        if CurrentSubclassModule_ is not None:
1027            subclass = getSubclassFromModule_(
1028                CurrentSubclassModule_, DoxygenType)
1029            if subclass is not None:
1030                return subclass(*args_, **kwargs_)
1031        if DoxygenType.subclass:
1032            return DoxygenType.subclass(*args_, **kwargs_)
1033        else:
1034            return DoxygenType(*args_, **kwargs_)
1035    factory = staticmethod(factory)
1036    def get_ns_prefix_(self):
1037        return self.ns_prefix_
1038    def set_ns_prefix_(self, ns_prefix):
1039        self.ns_prefix_ = ns_prefix
1040    def get_compound(self):
1041        return self.compound
1042    def set_compound(self, compound):
1043        self.compound = compound
1044    def add_compound(self, value):
1045        self.compound.append(value)
1046    def insert_compound_at(self, index, value):
1047        self.compound.insert(index, value)
1048    def replace_compound_at(self, index, value):
1049        self.compound[index] = value
1050    def get_version(self):
1051        return self.version
1052    def set_version(self, version):
1053        self.version = version
1054    def get_lang(self):
1055        return self.lang
1056    def set_lang(self, lang):
1057        self.lang = lang
1058    def hasContent_(self):
1059        if (
1060            self.compound
1061        ):
1062            return True
1063        else:
1064            return False
1065    def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='DoxygenType', pretty_print=True):
1066        imported_ns_def_ = GenerateDSNamespaceDefs_.get('DoxygenType')
1067        if imported_ns_def_ is not None:
1068            namespacedef_ = imported_ns_def_
1069        if pretty_print:
1070            eol_ = '\n'
1071        else:
1072            eol_ = ''
1073        if self.original_tagname_ is not None and name_ == 'DoxygenType':
1074            name_ = self.original_tagname_
1075        if UseCapturedNS_ and self.ns_prefix_:
1076            namespaceprefix_ = self.ns_prefix_ + ':'
1077        showIndent(outfile, level, pretty_print)
1078        outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
1079        already_processed = set()
1080        self.exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='DoxygenType')
1081        if self.hasContent_():
1082            outfile.write('>%s' % (eol_, ))
1083            self.exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='DoxygenType', pretty_print=pretty_print)
1084            showIndent(outfile, level, pretty_print)
1085            outfile.write('</%s%s>%s' % (namespaceprefix_, name_, eol_))
1086        else:
1087            outfile.write('/>%s' % (eol_, ))
1088    def exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='DoxygenType'):
1089        if self.version is not None and 'version' not in already_processed:
1090            already_processed.add('version')
1091            outfile.write(' version=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.version), input_name='version')), ))
1092        if self.lang is not None and 'lang' not in already_processed:
1093            already_processed.add('lang')
1094            outfile.write(' xml:lang=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.lang), input_name='lang')), ))
1095    def exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='DoxygenType', fromsubclass_=False, pretty_print=True):
1096        if pretty_print:
1097            eol_ = '\n'
1098        else:
1099            eol_ = ''
1100        for compound_ in self.compound:
1101            namespaceprefix_ = self.compound_nsprefix_ + ':' if (UseCapturedNS_ and self.compound_nsprefix_) else ''
1102            compound_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='compound', pretty_print=pretty_print)
1103    def build(self, node, gds_collector_=None):
1104        self.gds_collector_ = gds_collector_
1105        if SaveElementTreeNode:
1106            self.gds_elementtree_node_ = node
1107        already_processed = set()
1108        self.ns_prefix_ = node.prefix
1109        self.buildAttributes(node, node.attrib, already_processed)
1110        for child in node:
1111            nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
1112            self.buildChildren(child, node, nodeName_, gds_collector_=gds_collector_)
1113        return self
1114    def buildAttributes(self, node, attrs, already_processed):
1115        value = find_attr_value_('version', node)
1116        if value is not None and 'version' not in already_processed:
1117            already_processed.add('version')
1118            self.version = value
1119        value = find_attr_value_('lang', node)
1120        if value is not None and 'lang' not in already_processed:
1121            already_processed.add('lang')
1122            self.lang = value
1123    def buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None):
1124        if nodeName_ == 'compound':
1125            obj_ = CompoundType.factory(parent_object_=self)
1126            obj_.build(child_, gds_collector_=gds_collector_)
1127            self.compound.append(obj_)
1128            obj_.original_tagname_ = 'compound'
1129# end class DoxygenType
1130
1131
1132class CompoundType(GeneratedsSuper):
1133    __hash__ = GeneratedsSuper.__hash__
1134    subclass = None
1135    superclass = None
1136    def __init__(self, refid=None, kind=None, name=None, member=None, gds_collector_=None, **kwargs_):
1137        self.gds_collector_ = gds_collector_
1138        self.gds_elementtree_node_ = None
1139        self.original_tagname_ = None
1140        self.parent_object_ = kwargs_.get('parent_object_')
1141        self.ns_prefix_ = None
1142        self.refid = _cast(None, refid)
1143        self.refid_nsprefix_ = None
1144        self.kind = _cast(None, kind)
1145        self.kind_nsprefix_ = None
1146        self.name = name
1147        self.name_nsprefix_ = None
1148        if member is None:
1149            self.member = []
1150        else:
1151            self.member = member
1152        self.member_nsprefix_ = None
1153    def factory(*args_, **kwargs_):
1154        if CurrentSubclassModule_ is not None:
1155            subclass = getSubclassFromModule_(
1156                CurrentSubclassModule_, CompoundType)
1157            if subclass is not None:
1158                return subclass(*args_, **kwargs_)
1159        if CompoundType.subclass:
1160            return CompoundType.subclass(*args_, **kwargs_)
1161        else:
1162            return CompoundType(*args_, **kwargs_)
1163    factory = staticmethod(factory)
1164    def get_ns_prefix_(self):
1165        return self.ns_prefix_
1166    def set_ns_prefix_(self, ns_prefix):
1167        self.ns_prefix_ = ns_prefix
1168    def get_name(self):
1169        return self.name
1170    def set_name(self, name):
1171        self.name = name
1172    def get_member(self):
1173        return self.member
1174    def set_member(self, member):
1175        self.member = member
1176    def add_member(self, value):
1177        self.member.append(value)
1178    def insert_member_at(self, index, value):
1179        self.member.insert(index, value)
1180    def replace_member_at(self, index, value):
1181        self.member[index] = value
1182    def get_refid(self):
1183        return self.refid
1184    def set_refid(self, refid):
1185        self.refid = refid
1186    def get_kind(self):
1187        return self.kind
1188    def set_kind(self, kind):
1189        self.kind = kind
1190    def validate_CompoundKind(self, value):
1191        # Validate type CompoundKind, a restriction on xsd:string.
1192        if value is not None and Validate_simpletypes_ and self.gds_collector_ is not None:
1193            if not isinstance(value, str):
1194                lineno = self.gds_get_node_lineno_()
1195                self.gds_collector_.add_message('Value "%(value)s"%(lineno)s is not of the correct base simple type (str)' % {"value": value, "lineno": lineno, })
1196                return False
1197            value = value
1198            enumerations = ['class', 'struct', 'union', 'interface', 'protocol', 'category', 'exception', 'file', 'namespace', 'group', 'page', 'example', 'dir', 'type', 'concept']
1199            if value not in enumerations:
1200                lineno = self.gds_get_node_lineno_()
1201                self.gds_collector_.add_message('Value "%(value)s"%(lineno)s does not match xsd enumeration restriction on CompoundKind' % {"value" : encode_str_2_3(value), "lineno": lineno} )
1202                result = False
1203    def hasContent_(self):
1204        if (
1205            self.name is not None or
1206            self.member
1207        ):
1208            return True
1209        else:
1210            return False
1211    def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CompoundType', pretty_print=True):
1212        imported_ns_def_ = GenerateDSNamespaceDefs_.get('CompoundType')
1213        if imported_ns_def_ is not None:
1214            namespacedef_ = imported_ns_def_
1215        if pretty_print:
1216            eol_ = '\n'
1217        else:
1218            eol_ = ''
1219        if self.original_tagname_ is not None and name_ == 'CompoundType':
1220            name_ = self.original_tagname_
1221        if UseCapturedNS_ and self.ns_prefix_:
1222            namespaceprefix_ = self.ns_prefix_ + ':'
1223        showIndent(outfile, level, pretty_print)
1224        outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
1225        already_processed = set()
1226        self.exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='CompoundType')
1227        if self.hasContent_():
1228            outfile.write('>%s' % (eol_, ))
1229            self.exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='CompoundType', pretty_print=pretty_print)
1230            showIndent(outfile, level, pretty_print)
1231            outfile.write('</%s%s>%s' % (namespaceprefix_, name_, eol_))
1232        else:
1233            outfile.write('/>%s' % (eol_, ))
1234    def exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='CompoundType'):
1235        if self.refid is not None and 'refid' not in already_processed:
1236            already_processed.add('refid')
1237            outfile.write(' refid=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.refid), input_name='refid')), ))
1238        if self.kind is not None and 'kind' not in already_processed:
1239            already_processed.add('kind')
1240            outfile.write(' kind=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.kind), input_name='kind')), ))
1241    def exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='CompoundType', fromsubclass_=False, pretty_print=True):
1242        if pretty_print:
1243            eol_ = '\n'
1244        else:
1245            eol_ = ''
1246        if self.name is not None:
1247            namespaceprefix_ = self.name_nsprefix_ + ':' if (UseCapturedNS_ and self.name_nsprefix_) else ''
1248            showIndent(outfile, level, pretty_print)
1249            outfile.write('<%sname>%s</%sname>%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.name), input_name='name')), namespaceprefix_ , eol_))
1250        for member_ in self.member:
1251            namespaceprefix_ = self.member_nsprefix_ + ':' if (UseCapturedNS_ and self.member_nsprefix_) else ''
1252            member_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='member', pretty_print=pretty_print)
1253    def build(self, node, gds_collector_=None):
1254        self.gds_collector_ = gds_collector_
1255        if SaveElementTreeNode:
1256            self.gds_elementtree_node_ = node
1257        already_processed = set()
1258        self.ns_prefix_ = node.prefix
1259        self.buildAttributes(node, node.attrib, already_processed)
1260        for child in node:
1261            nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
1262            self.buildChildren(child, node, nodeName_, gds_collector_=gds_collector_)
1263        return self
1264    def buildAttributes(self, node, attrs, already_processed):
1265        value = find_attr_value_('refid', node)
1266        if value is not None and 'refid' not in already_processed:
1267            already_processed.add('refid')
1268            self.refid = value
1269        value = find_attr_value_('kind', node)
1270        if value is not None and 'kind' not in already_processed:
1271            already_processed.add('kind')
1272            self.kind = value
1273            self.validate_CompoundKind(self.kind)    # validate type CompoundKind
1274    def buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None):
1275        if nodeName_ == 'name':
1276            value_ = child_.text
1277            value_ = self.gds_parse_string(value_, node, 'name')
1278            value_ = self.gds_validate_string(value_, node, 'name')
1279            self.name = value_
1280            self.name_nsprefix_ = child_.prefix
1281        elif nodeName_ == 'member':
1282            obj_ = MemberType.factory(parent_object_=self)
1283            obj_.build(child_, gds_collector_=gds_collector_)
1284            self.member.append(obj_)
1285            obj_.original_tagname_ = 'member'
1286# end class CompoundType
1287
1288
1289class MemberType(GeneratedsSuper):
1290    __hash__ = GeneratedsSuper.__hash__
1291    subclass = None
1292    superclass = None
1293    def __init__(self, refid=None, kind=None, name=None, gds_collector_=None, **kwargs_):
1294        self.gds_collector_ = gds_collector_
1295        self.gds_elementtree_node_ = None
1296        self.original_tagname_ = None
1297        self.parent_object_ = kwargs_.get('parent_object_')
1298        self.ns_prefix_ = None
1299        self.refid = _cast(None, refid)
1300        self.refid_nsprefix_ = None
1301        self.kind = _cast(None, kind)
1302        self.kind_nsprefix_ = None
1303        self.name = name
1304        self.name_nsprefix_ = None
1305    def factory(*args_, **kwargs_):
1306        if CurrentSubclassModule_ is not None:
1307            subclass = getSubclassFromModule_(
1308                CurrentSubclassModule_, MemberType)
1309            if subclass is not None:
1310                return subclass(*args_, **kwargs_)
1311        if MemberType.subclass:
1312            return MemberType.subclass(*args_, **kwargs_)
1313        else:
1314            return MemberType(*args_, **kwargs_)
1315    factory = staticmethod(factory)
1316    def get_ns_prefix_(self):
1317        return self.ns_prefix_
1318    def set_ns_prefix_(self, ns_prefix):
1319        self.ns_prefix_ = ns_prefix
1320    def get_name(self):
1321        return self.name
1322    def set_name(self, name):
1323        self.name = name
1324    def get_refid(self):
1325        return self.refid
1326    def set_refid(self, refid):
1327        self.refid = refid
1328    def get_kind(self):
1329        return self.kind
1330    def set_kind(self, kind):
1331        self.kind = kind
1332    def validate_MemberKind(self, value):
1333        # Validate type MemberKind, a restriction on xsd:string.
1334        if value is not None and Validate_simpletypes_ and self.gds_collector_ is not None:
1335            if not isinstance(value, str):
1336                lineno = self.gds_get_node_lineno_()
1337                self.gds_collector_.add_message('Value "%(value)s"%(lineno)s is not of the correct base simple type (str)' % {"value": value, "lineno": lineno, })
1338                return False
1339            value = value
1340            enumerations = ['define', 'property', 'event', 'variable', 'typedef', 'enum', 'enumvalue', 'function', 'signal', 'prototype', 'friend', 'dcop', 'slot']
1341            if value not in enumerations:
1342                lineno = self.gds_get_node_lineno_()
1343                self.gds_collector_.add_message('Value "%(value)s"%(lineno)s does not match xsd enumeration restriction on MemberKind' % {"value" : encode_str_2_3(value), "lineno": lineno} )
1344                result = False
1345    def hasContent_(self):
1346        if (
1347            self.name is not None
1348        ):
1349            return True
1350        else:
1351            return False
1352    def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='MemberType', pretty_print=True):
1353        imported_ns_def_ = GenerateDSNamespaceDefs_.get('MemberType')
1354        if imported_ns_def_ is not None:
1355            namespacedef_ = imported_ns_def_
1356        if pretty_print:
1357            eol_ = '\n'
1358        else:
1359            eol_ = ''
1360        if self.original_tagname_ is not None and name_ == 'MemberType':
1361            name_ = self.original_tagname_
1362        if UseCapturedNS_ and self.ns_prefix_:
1363            namespaceprefix_ = self.ns_prefix_ + ':'
1364        showIndent(outfile, level, pretty_print)
1365        outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
1366        already_processed = set()
1367        self.exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='MemberType')
1368        if self.hasContent_():
1369            outfile.write('>%s' % (eol_, ))
1370            self.exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='MemberType', pretty_print=pretty_print)
1371            showIndent(outfile, level, pretty_print)
1372            outfile.write('</%s%s>%s' % (namespaceprefix_, name_, eol_))
1373        else:
1374            outfile.write('/>%s' % (eol_, ))
1375    def exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='MemberType'):
1376        if self.refid is not None and 'refid' not in already_processed:
1377            already_processed.add('refid')
1378            outfile.write(' refid=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.refid), input_name='refid')), ))
1379        if self.kind is not None and 'kind' not in already_processed:
1380            already_processed.add('kind')
1381            outfile.write(' kind=%s' % (self.gds_encode(self.gds_format_string(quote_attrib(self.kind), input_name='kind')), ))
1382    def exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='MemberType', fromsubclass_=False, pretty_print=True):
1383        if pretty_print:
1384            eol_ = '\n'
1385        else:
1386            eol_ = ''
1387        if self.name is not None:
1388            namespaceprefix_ = self.name_nsprefix_ + ':' if (UseCapturedNS_ and self.name_nsprefix_) else ''
1389            showIndent(outfile, level, pretty_print)
1390            outfile.write('<%sname>%s</%sname>%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.name), input_name='name')), namespaceprefix_ , eol_))
1391    def build(self, node, gds_collector_=None):
1392        self.gds_collector_ = gds_collector_
1393        if SaveElementTreeNode:
1394            self.gds_elementtree_node_ = node
1395        already_processed = set()
1396        self.ns_prefix_ = node.prefix
1397        self.buildAttributes(node, node.attrib, already_processed)
1398        for child in node:
1399            nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
1400            self.buildChildren(child, node, nodeName_, gds_collector_=gds_collector_)
1401        return self
1402    def buildAttributes(self, node, attrs, already_processed):
1403        value = find_attr_value_('refid', node)
1404        if value is not None and 'refid' not in already_processed:
1405            already_processed.add('refid')
1406            self.refid = value
1407        value = find_attr_value_('kind', node)
1408        if value is not None and 'kind' not in already_processed:
1409            already_processed.add('kind')
1410            self.kind = value
1411            self.validate_MemberKind(self.kind)    # validate type MemberKind
1412    def buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None):
1413        if nodeName_ == 'name':
1414            value_ = child_.text
1415            value_ = self.gds_parse_string(value_, node, 'name')
1416            value_ = self.gds_validate_string(value_, node, 'name')
1417            self.name = value_
1418            self.name_nsprefix_ = child_.prefix
1419# end class MemberType
1420
1421
1422GDSClassesMapping = {
1423    'doxygenindex': DoxygenType,
1424}
1425
1426
1427USAGE_TEXT = """
1428Usage: python <Parser>.py [ -s ] <in_xml_file>
1429"""
1430
1431
1432def usage():
1433    print(USAGE_TEXT)
1434    sys.exit(1)
1435
1436
1437def get_root_tag(node):
1438    tag = Tag_pattern_.match(node.tag).groups()[-1]
1439    rootClass = GDSClassesMapping.get(tag)
1440    if rootClass is None:
1441        rootClass = globals().get(tag)
1442    return tag, rootClass
1443
1444
1445def get_required_ns_prefix_defs(rootNode):
1446    '''Get all name space prefix definitions required in this XML doc.
1447    Return a dictionary of definitions and a char string of definitions.
1448    '''
1449    nsmap = {
1450        prefix: uri
1451        for node in rootNode.iter()
1452        for (prefix, uri) in node.nsmap.items()
1453        if prefix is not None
1454    }
1455    namespacedefs = ' '.join([
1456        'xmlns:{}="{}"'.format(prefix, uri)
1457        for prefix, uri in nsmap.items()
1458    ])
1459    return nsmap, namespacedefs
1460
1461
1462def parse(inFileName, silence=False, print_warnings=True):
1463    global CapturedNsmap_
1464    gds_collector = GdsCollector_()
1465    parser = None
1466    doc = parsexml_(inFileName, parser)
1467    rootNode = doc.getroot()
1468    rootTag, rootClass = get_root_tag(rootNode)
1469    if rootClass is None:
1470        rootTag = 'DoxygenType'
1471        rootClass = DoxygenType
1472    rootObj = rootClass.factory()
1473    rootObj.build(rootNode, gds_collector_=gds_collector)
1474    CapturedNsmap_, namespacedefs = get_required_ns_prefix_defs(rootNode)
1475    if not SaveElementTreeNode:
1476        doc = None
1477        rootNode = None
1478    if not silence:
1479        sys.stdout.write('<?xml version="1.0" ?>\n')
1480        rootObj.export(
1481            sys.stdout, 0, name_=rootTag,
1482            namespacedef_=namespacedefs,
1483            pretty_print=True)
1484    if print_warnings and len(gds_collector.get_messages()) > 0:
1485        separator = ('-' * 50) + '\n'
1486        sys.stderr.write(separator)
1487        sys.stderr.write('----- Warnings -- count: {} -----\n'.format(
1488            len(gds_collector.get_messages()), ))
1489        gds_collector.write_messages(sys.stderr)
1490        sys.stderr.write(separator)
1491    return rootObj
1492
1493
1494def parseEtree(inFileName, silence=False, print_warnings=True,
1495               mapping=None, nsmap=None):
1496    parser = None
1497    doc = parsexml_(inFileName, parser)
1498    gds_collector = GdsCollector_()
1499    rootNode = doc.getroot()
1500    rootTag, rootClass = get_root_tag(rootNode)
1501    if rootClass is None:
1502        rootTag = 'DoxygenType'
1503        rootClass = DoxygenType
1504    rootObj = rootClass.factory()
1505    rootObj.build(rootNode, gds_collector_=gds_collector)
1506    # Enable Python to collect the space used by the DOM.
1507    if mapping is None:
1508        mapping = {}
1509    rootElement = rootObj.to_etree(
1510        None, name_=rootTag, mapping_=mapping, nsmap_=nsmap)
1511    reverse_mapping = rootObj.gds_reverse_node_mapping(mapping)
1512    if not SaveElementTreeNode:
1513        doc = None
1514        rootNode = None
1515    if not silence:
1516        content = etree_.tostring(
1517            rootElement, pretty_print=True,
1518            xml_declaration=True, encoding="utf-8")
1519        sys.stdout.write(str(content))
1520        sys.stdout.write('\n')
1521    if print_warnings and len(gds_collector.get_messages()) > 0:
1522        separator = ('-' * 50) + '\n'
1523        sys.stderr.write(separator)
1524        sys.stderr.write('----- Warnings -- count: {} -----\n'.format(
1525            len(gds_collector.get_messages()), ))
1526        gds_collector.write_messages(sys.stderr)
1527        sys.stderr.write(separator)
1528    return rootObj, rootElement, mapping, reverse_mapping
1529
1530
1531def parseString(inString, silence=False, print_warnings=True):
1532    '''Parse a string, create the object tree, and export it.
1533
1534    Arguments:
1535    - inString -- A string.  This XML fragment should not start
1536      with an XML declaration containing an encoding.
1537    - silence -- A boolean.  If False, export the object.
1538    Returns -- The root object in the tree.
1539    '''
1540    parser = None
1541    rootNode= parsexmlstring_(inString, parser)
1542    gds_collector = GdsCollector_()
1543    rootTag, rootClass = get_root_tag(rootNode)
1544    if rootClass is None:
1545        rootTag = 'DoxygenType'
1546        rootClass = DoxygenType
1547    rootObj = rootClass.factory()
1548    rootObj.build(rootNode, gds_collector_=gds_collector)
1549    if not SaveElementTreeNode:
1550        rootNode = None
1551    if not silence:
1552        sys.stdout.write('<?xml version="1.0" ?>\n')
1553        rootObj.export(
1554            sys.stdout, 0, name_=rootTag,
1555            namespacedef_='')
1556    if print_warnings and len(gds_collector.get_messages()) > 0:
1557        separator = ('-' * 50) + '\n'
1558        sys.stderr.write(separator)
1559        sys.stderr.write('----- Warnings -- count: {} -----\n'.format(
1560            len(gds_collector.get_messages()), ))
1561        gds_collector.write_messages(sys.stderr)
1562        sys.stderr.write(separator)
1563    return rootObj
1564
1565
1566def parseLiteral(inFileName, silence=False, print_warnings=True):
1567    parser = None
1568    doc = parsexml_(inFileName, parser)
1569    gds_collector = GdsCollector_()
1570    rootNode = doc.getroot()
1571    rootTag, rootClass = get_root_tag(rootNode)
1572    if rootClass is None:
1573        rootTag = 'DoxygenType'
1574        rootClass = DoxygenType
1575    rootObj = rootClass.factory()
1576    rootObj.build(rootNode, gds_collector_=gds_collector)
1577    # Enable Python to collect the space used by the DOM.
1578    if not SaveElementTreeNode:
1579        doc = None
1580        rootNode = None
1581    if not silence:
1582        sys.stdout.write('#from index import *\n\n')
1583        sys.stdout.write('import index as model_\n\n')
1584        sys.stdout.write('rootObj = model_.rootClass(\n')
1585        rootObj.exportLiteral(sys.stdout, 0, name_=rootTag)
1586        sys.stdout.write(')\n')
1587    if print_warnings and len(gds_collector.get_messages()) > 0:
1588        separator = ('-' * 50) + '\n'
1589        sys.stderr.write(separator)
1590        sys.stderr.write('----- Warnings -- count: {} -----\n'.format(
1591            len(gds_collector.get_messages()), ))
1592        gds_collector.write_messages(sys.stderr)
1593        sys.stderr.write(separator)
1594    return rootObj
1595
1596
1597def main():
1598    args = sys.argv[1:]
1599    if len(args) == 1:
1600        parse(args[0])
1601    else:
1602        usage()
1603
1604
1605if __name__ == '__main__':
1606    #import pdb; pdb.set_trace()
1607    main()
1608
1609RenameMappings_ = {
1610}
1611
1612#
1613# Mapping of namespaces to types defined in them
1614# and the file in which each is defined.
1615# simpleTypes are marked "ST" and complexTypes "CT".
1616NamespaceToDefMappings_ = {'http://www.w3.org/XML/1998/namespace': []}
1617
1618__all__ = [
1619    "CompoundType",
1620    "DoxygenType",
1621    "MemberType"
1622]
1623