summaryrefslogtreecommitdiff
path: root/config/makeprops.py
blob: 2937d551b41773d1faa7481c7f36258897e9dfb4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
#!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2009 ZeroC, Inc. All rights reserved.
#
# This copy of Ice is licensed to you under the terms described in the
# ICE_LICENSE file included in this distribution.
#
# **********************************************************************

import os, sys, shutil, re, signal, time, string, pprint

from xml.sax import make_parser
from xml.sax.handler import feature_namespaces
from xml.sax.handler import ContentHandler
from xml.sax import saxutils
from xml.sax import SAXException

from xml.dom.minidom import parse

progname = os.path.basename(sys.argv[0])
contentHandler = None
propertyClasses = {}

commonPreamble = """// **********************************************************************
//
// Copyright (c) 2003-2009 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************

//
""" 
commonPreamble = commonPreamble + "// Generated by " + progname + " from file %(inputfile)s, " + time.ctime()
commonPreamble = commonPreamble + """

// IMPORTANT: Do not edit this file -- any edits made here will be lost!
"""

cppHeaderPreamble = commonPreamble + """
#ifndef ICE_INTERNAL_%(classname)s_H
#define ICE_INTERNAL_%(classname)s_H

#include <Ice/Config.h>

namespace IceInternal
{

struct Property
{
    const char* pattern;
    bool deprecated;
    const char* deprecatedBy;

    Property(const char* n, bool d, const char* b) :
	pattern(n),
	deprecated(d),
	deprecatedBy(b)
    {
    }

    Property() :
        pattern(0),
        deprecated(false),
        deprecatedBy(0)
    {
    }

};

struct PropertyArray
{
    const Property* properties;
    const int length;

    PropertyArray(const Property* p, int len) :
        properties(p),
        length(len)
    {
    }
};

class %(classname)s
{
public:

"""

cppHeaderPostamble = """
    static const PropertyArray validProps[];
    static const char * clPropNames[];
};

}

#endif
"""

cppSrcPreamble = commonPreamble + """
#include <Ice/%(classname)s.h>

"""

javaPreamble = commonPreamble + """
package IceInternal;

public final class %(classname)s
{
"""

csPreamble = commonPreamble + """
namespace IceInternal
{
    public sealed class %(classname)s
    {
"""

def usage():
    global progname
    print >> sys.stderr, "Usage: " + progname + " [--{cpp|java|cs} file]"

def progError(msg):
    global progname
    print >> sys.stderr, progname + ": " + msg

#
# Currently the processing of PropertyNames.xml is going to take place
# in two parts. One is using DOM to extract the property 'classes' such
# as 'proxy', 'objectadapter', etc. The other part uses SAX to create
# the language mapping source code.
# 

class PropertyClass:
    def __init__(self, prefixOnly , childProperties):
        self.prefixOnly = prefixOnly 
        self.childProperties = childProperties

    def getChildren(self):
        return self.childProperties

    def isPrefixOnly(self):
        return self.prefixOnly

    def __repr__(self):
        return repr((repr(self.preifxOnly), repr(self.childProperties)))

def initPropertyClasses(filename):
    doc = parse(filename)
    propertyClassNodes = doc.getElementsByTagName("class")
    global propertyClasses
    propertyClasses = {}
    for n in propertyClassNodes:
        className = n.attributes["name"].nodeValue
        classType = n.attributes["prefix-only"].nodeValue
        properties = []
        for a in n.childNodes:
            if a.localName == "suffix" and a.hasAttributes():
                """Convert minidom maps to hashtables """
                attmap = {}
                for i in range(0, a.attributes.length):
                    attmap[a.attributes.item(i).name] = a.attributes.item(i).value
                properties.append(attmap)

        propertyClasses[className] = PropertyClass(classType.lower() == "true", properties)

#
# SAX part.
#

def handler(signum, frame):
    """Installed as signal handler. Should cause an files that are in
    use to be closed and removed"""
    global contentHandler
    contentHandler.cleanup()
    sys.exit(128 + signum)

class UnknownElementException(Exception):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)

class PropertyHandler(ContentHandler):

    def __init__(self, inputfile, className):
        self.start = False
        self.properties = {}
        self.inputfile = inputfile
        self.className = className
        self.currentSection = None
        self.sectionPropertyCount = 0
        self.sections = []
        self.cmdLineOptions = []

    def cleanup(self):
        """Needs to be overridden in derived class"""
        pass

    def startFiles(self):
        """Needs to be overridden in derived class"""
        pass

    def closeFiles(self):
        """Needs to be overridden in derived class"""
        pass

    def deprecatedImpl(self, propertyName):
        """Needs to be overridden in derived class"""
        pass

    def deprecatedImplWithReplacementImpl(self, propertyName, deprecatedBy):
        """Needs to be overridden in derived class"""
        pass

    def propertyImpl(self, propertyName):
        """Needs to be overridden in derived class"""
        pass

    def newSection(self, sectionName):
        """Needs to be overridden in derived class"""
        pass

    def moveFiles(self, location):
        """Needs to be overridden in derived class"""
        pass

    def handleNewSection(self, sectionName, noCmdLine):
        self.currentSection = sectionName
        self.sectionPropertyCount = 0
        if noCmdLine == "false":
            self.cmdLineOptions.append(sectionName)
        self.sections.append(sectionName)
        self.newSection()
        
    def handleDeprecated(self, propertyName):
        self.properties[propertyName] = None
        self.deprecatedImpl(propertyName)
        
    def handleDeprecatedWithReplacement(self, propertyName, deprecatedBy):
        self.properties[propertyName] = deprecatedBy
        self.deprecatedImplWithReplacementImpl(propertyName, deprecatedBy)

    def handleProperty(self, propertyName):
        self.properties[propertyName] = ""
        self.propertyImpl(propertyName)

    def startElement(self, name, attrs):
        if name == "properties":
            self.start = True
            self.startFiles()
            return

        if not self.start:
            return
        
        if name == "section":
            noCmdLine = attrs.get("noCmdLine", "false")
            self.handleNewSection(attrs.get("name"), noCmdLine)
        
        elif name == "property":
            propertyName = attrs.get("name", None)
            if attrs.has_key("class"):
                c = propertyClasses[attrs["class"]]
                for p in c.getChildren():
                    if propertyName == None:
                        self.startElement(name, p)
                    else:
                        t = dict(p) 

                        # deprecatedBy properties in property classes
                        # are special. deprecatedBy attributes are
                        # usually absolute or 'raw', but in the case of
                        # a property class, they need to be expanded.
                        if t.has_key("deprecatedBy"):
                            t["deprecatedBy"] = "%s.%s.%s" % (self.currentSection, propertyName, t["deprecatedBy"])
                        t['name'] =  "%s.%s" % (propertyName, p['name'])
                        self.startElement(name, t) 
                if c.isPrefixOnly():
                    return

            #
            # != None implies deprecated == true
            #
            deprecatedBy = attrs.get("deprecatedBy", None)
            if deprecatedBy != None:
                self.handleDeprecatedWithReplacement(propertyName, deprecatedBy)
            elif attrs.get("deprecated", "false").lower() == "true" :
                self.handleDeprecated(propertyName)
            else:
                self.handleProperty(propertyName)

    def endElement(self, name):
        if name == "properties":
            self.closeFiles()
        elif name == "section":
            self.closeSection()

class CppPropertyHandler(PropertyHandler):

    def __init__(self, inputfile, c):
        PropertyHandler.__init__(self, inputfile, c)
        self.hFile = None
        self.cppFile = None

    def cleanup(self):
        if self.hFile != None:
            self.hFile.close()
            if os.path.exists(self.className + ".h"):
                os.remove(self.className + ".h")
        if self.cppFile != None:
            self.cppFile.close()
            if os.path.exists(self.className + ".cpp"):
                os.remove(self.className + ".cpp")

    def startFiles(self):
        self.hFile = open(self.className + ".h", "w")
        self.cppFile = open(self.className + ".cpp", "w")
        self.hFile.write(cppHeaderPreamble % {'inputfile' : self.inputfile, 'classname' : self.className})
        self.cppFile.write(cppSrcPreamble % {'inputfile' : self.inputfile, 'classname' : self.className})

    def closeFiles(self):
        self.hFile.write(cppHeaderPostamble % {'classname' : self.className})
        self.cppFile.write("\nconst IceInternal::PropertyArray "\
                        "IceInternal::%(classname)s::validProps[] =\n" % \
                {'classname' : self.className})

        self.cppFile.write("{\n")
        for s in self.sections:
            self.cppFile.write("    %sProps,\n" % s)
        self.cppFile.write("    IceInternal::PropertyArray(0,0)\n");
        self.cppFile.write("};\n\n")

        self.cppFile.write("\nconst char* IceInternal::%(classname)s::clPropNames[] =\n" % \
                {'classname' : self.className})
        self.cppFile.write("{\n")
        for s in self.cmdLineOptions:
            self.cppFile.write("    \"%s\",\n" % s)
        self.cppFile.write("    0\n")
        self.cppFile.write("};\n\n")
        self.hFile.close()
        self.cppFile.close()

    def fix(self, propertyName):
        return string.replace(propertyName, "[any]", "*")

    def deprecatedImpl(self, propertyName):
        self.cppFile.write("    IceInternal::Property(\"%s.%s\", true, 0),\n" % (self.currentSection, \
                self.fix(propertyName)))

    def deprecatedImplWithReplacementImpl(self, propertyName, deprecatedBy):
        self.cppFile.write("    IceInternal::Property(\"%s.%s\", true, \"%s\"),\n" % (self.currentSection, \
                self.fix(propertyName), deprecatedBy))

    def propertyImpl(self, propertyName):
        self.cppFile.write("    IceInternal::Property(\"%s.%s\", false, 0),\n" % \
                (self.currentSection, self.fix(propertyName)))

    def newSection(self):
        self.hFile.write("    static const PropertyArray %sProps;\n" % self.currentSection)
        self.cppFile.write("const IceInternal::Property %sPropsData[] = \n" % self.currentSection)
        self.cppFile.write("{\n")
        
    def closeSection(self):
        self.cppFile.write("};\n")
        self.cppFile.write("""
const IceInternal::PropertyArray
    IceInternal::%(className)s::%(section)sProps(%(section)sPropsData,
                                                sizeof(%(section)sPropsData)/sizeof(%(section)sPropsData[0]));

""" % { 'className' : self.className, 'section': self.currentSection })

    def moveFiles(self, location):
        shutil.move(self.className + ".h", os.path.join(location, "cpp", "src", "Ice"))
        shutil.move(self.className + ".cpp", os.path.join(location, "cpp", "src", "Ice"))

class JavaPropertyHandler(PropertyHandler):
    def __init__(self, inputfile, c):
        PropertyHandler.__init__(self, inputfile, c)
        self.srcFile = None

    def cleanup(self):
        if self.srcFile != None:
            self.srcFile.close()
            if os.path.exists(self.className + ".java"):
                os.remove(self.className + ".java")

    def startFiles(self):
        self.srcFile = file(self.className + ".java", "w")
        self.srcFile.write(javaPreamble % {'inputfile' : self.inputfile, 'classname' : self.className})

    def closeFiles(self):
        self.srcFile.write("\n    public static final Property[] validProps[] =\n")

        self.srcFile.write("    {\n")
        for s in self.sections:
            self.srcFile.write("        %sProps,\n" % s)
        self.srcFile.write("        null\n")
        self.srcFile.write("    };\n")

        self.srcFile.write("\n    public static final String clPropNames[] =\n")
        self.srcFile.write("    {\n")
        for s in self.cmdLineOptions:
            self.srcFile.write("        \"%s\",\n" % s)
        self.srcFile.write("        null\n")
        self.srcFile.write("    };\n")
        self.srcFile.write("}\n")
        self.srcFile.close()

    def fix(self, propertyName):
        #
        # The Java property strings are actually regexp's that will be passed to Java's regexp facitlity.
        #
        propertyName = string.replace(propertyName, ".", "\\\\.")
        return string.replace(propertyName, "[any]", "[^\\\\s]+")

    def deprecatedImpl(self, propertyName):
        self.srcFile.write("        new Property(\"%(section)s\\\\.%(pattern)s\", " \
                "true, null),\n" % \
                {"section" : self.currentSection, "pattern": self.fix(propertyName)})

    def deprecatedImplWithReplacementImpl(self, propertyName, deprecatedBy):
        self.srcFile.write("        new Property(\"%(section)s\\\\.%(pattern)s\", "\
                "true, \"%(deprecatedBy)s\"),\n"  % \
                {"section" : self.currentSection, "pattern": self.fix(propertyName),
                    "deprecatedBy" : deprecatedBy})

    def propertyImpl(self, propertyName):
        self.srcFile.write("        new Property(\"%(section)s\\\\.%(pattern)s\", " \
                "false, null),\n" % \
                {"section" : self.currentSection, "pattern": self.fix(propertyName)} )

    def newSection(self):
        self.srcFile.write("    public static final Property %sProps[] = \n" % self.currentSection)
        self.srcFile.write("    {\n")
            
    def closeSection(self):
        self.srcFile.write("        null\n")
        self.srcFile.write("    };\n\n")

    def moveFiles(self, location):
        shutil.move(self.className + ".java", os.path.join(location, "java", "src", "IceInternal"))

class CSPropertyHandler(PropertyHandler):
    def __init__(self, inputfile, c):
        PropertyHandler.__init__(self, inputfile, c)
        self.srcFile = None

    def cleanup(self):
        if self.srcFile != None:
            self.srcFile.close()
            if os.path.exists(self.className + ".cs"):
                os.remove(self.className + ".cs")

    def startFiles(self):
        self.srcFile = file(self.className + ".cs", "w")
        self.srcFile.write(csPreamble % {'inputfile' : self.inputfile, 'classname' : self.className})

    def closeFiles(self):
        self.srcFile.write("        public static Property[][] validProps =\n")

        self.srcFile.write("        {\n")
        for s in self.sections:
            self.srcFile.write("            %sProps,\n" % s)
        self.srcFile.write("            null\n")
        self.srcFile.write("        };\n\n")

        self.srcFile.write("        public static string[] clPropNames =\n")
        self.srcFile.write("        {\n")
        for s in self.cmdLineOptions:
            self.srcFile.write("            \"%s\",\n" % s)
        self.srcFile.write("            null\n")
        self.srcFile.write("        };\n")
        self.srcFile.write("    }\n")
        self.srcFile.write("}\n")
        self.srcFile.close()

    def fix(self, propertyName):
        propertyName = string.replace(propertyName, ".", "\\.")
        return string.replace(propertyName, "[any]", "[^\\s]+")

    def deprecatedImpl(self, propertyName):
        self.srcFile.write("             new Property(@\"^%s\.%s$\", true, null),\n" % (self.currentSection, \
                self.fix(propertyName)))

    def deprecatedImplWithReplacementImpl(self, propertyName, deprecatedBy):
        self.srcFile.write("             new Property(@\"^%s\.%s$\", true, @\"%s\"),\n" % \
                (self.currentSection, self.fix(propertyName), deprecatedBy))

    def propertyImpl(self, propertyName):
        self.srcFile.write("             new Property(@\"^%s\.%s$\", false, null),\n" % (self.currentSection, \
                self.fix(propertyName)))

    def newSection(self):
        self.srcFile.write("        public static Property[] %sProps =\n" % self.currentSection);
        self.srcFile.write("        {\n")
            
    def closeSection(self):
        self.srcFile.write("             null\n")
        self.srcFile.write("        };\n")
        self.srcFile.write("\n")

    def moveFiles(self, location):
        shutil.move(self.className + ".cs", os.path.join(location, "cs", "src", "Ice"))

class MultiHandler(PropertyHandler):
    def __init__(self, inputfile, c):
        self.handlers = []
        PropertyHandler.__init__(self, inputfile, c)

    def cleanup(self):
        for f in self.handlers:
            f.cleanup()

    def addHandlers(self, handlers):
        self.handlers.extend(handlers)

    def startFiles(self):
        for f in self.handlers:
            f.startFiles()

    def closeFiles(self):
        for f in self.handlers:
            f.closeFiles()

    def newSection(self):
        for f in self.handlers:
            f.newSection()
            
    def closeSection(self):
        for f in self.handlers:
            f.closeSection()

    def handleNewSection(self, sectionName, cmdLine):
        for f in self.handlers:
            f.handleNewSection(sectionName, cmdLine)
        
    def handleDeprecated(self, propertyName):
        for f in self.handlers:
            f.handleDeprecated(propertyName)
        
    def handleDeprecatedWithReplacement(self, propertyName, deprecatedBy):
        for f in self.handlers:
            f.handleDeprecatedWithReplacement(propertyName, deprecatedBy)

    def handleProperty(self, propertyName):
        for f in self.handlers:
            f.handleProperty(propertyName)

    def startElement(self, name, attrs):
        for f in self.handlers:
            f.startElement(name, attrs)

    def moveFiles(self, location):
        for f in self.handlers:
            f.moveFiles(location)

def main():
    if len(sys.argv) != 1 and len(sys.argv) != 3:
        usage()
        sys.exit(1)

    infile = None
    lang = None

    #
    # Find the root of the tree.
    #
    for toplevel in [".", "..", "../..", "../../..", "../../../.."]:
        toplevel = os.path.normpath(toplevel)
        if os.path.exists(os.path.join(toplevel, "config", "makeprops.py")):
            break
    else:
        progError("cannot find top-level directory")
        sys.exit(1)

    if len(sys.argv) == 1:
        infile = os.path.join(toplevel, "config", "PropertyNames.xml")
    else:
        option = sys.argv[1]
        if option == "--cpp":
            lang = "cpp"
        elif option == "--java":
            lang = "java"
        elif option == "--cs":
            lang = "cs"
        elif option in ["-h", "--help", "-?"]:
            usage()
            sys.exit(0)
        else:
            usage()
            sys.exit(1)
        infile = sys.argv[2]

    className, ext = os.path.splitext(os.path.basename(infile))
    global contentHandler
    if lang == None:
        contentHandler = MultiHandler(infile, "")
        contentHandler.addHandlers([CppPropertyHandler(infile, className), 
            JavaPropertyHandler(infile, className),
            CSPropertyHandler(infile, className)])
    else:
        if lang == "cpp":
            contentHandler = CppPropertyHandler(infile, className)
        elif lang == "java":
            contentHandler = JavaPropertyHandler(infile, className)
        elif lang == "cs":
            contentHandler = CSPropertyHandler(infile, className)

    #
    # Install signal handler so we can remove the output files if we are interrupted.
    #
    signal.signal(signal.SIGINT, handler)
    # signal.signal(signal.SIGHUP, handler)
    signal.signal(signal.SIGTERM, handler)
    initPropertyClasses(infile)

    parser = make_parser()
    parser.setFeature(feature_namespaces, 0)
    parser.setContentHandler(contentHandler)
    pf = file(infile)
    try:
        parser.parse(pf)
        contentHandler.moveFiles(toplevel)
    except IOError, ex:
        progError(str(ex))
        contentHandler.cleanup()
    except SAXException, ex:
        progError(str(ex))
        contentHandler.cleanup()

if __name__ == "__main__":
    main()