summaryrefslogtreecommitdiff
path: root/cpp/config/makeprops.py
blob: 79de04f36adb9fa647a7ce63f8de270553e2bbf1 (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
#!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2005 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

progname = os.path.basename(sys.argv[0])
infile = ""
classname = ""
lineNum = 0
errors = 0
outputFiles = [] 

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

def fileError(msg):
    global progname, infile, lineNum, errors
    print >> sys.stderr, progname + ": " + infile + ':' + str(lineNum) + ": " + msg
    errors += 1

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

def removeOutputFiles():
    global outputFiles
    for entry in outputFiles:
	try:
	    if os.path.exists(entry[0]):
		os.remove(entry[0])
	except EnvironmentError, ex:
	    progError("warning: could not unlink `" + entry[0] + "': " + ex.strerror + \
	    	" -- generated file contains errors");

def handler(signum, frame):
    removeOutputFiles()
    sys.exit(128 + signum)

def openOutputFile(filename):
    global outputFiles
    try:
        outfile = file(filename, 'w')
	outputFiles.append([filename, outfile])
    except IOError, ex:
        progError("cannot open `" + filename + "' for writing: " + ex.strerror)
	removeOutputFiles()
	sys.exit(1)

def writePreamble(lang):
    global progname
    global infile
    global outputFiles
    global classname

    for entry in outputFiles:
	file = entry[1]
	file.write("// **********************************************************************\n")
	file.write("//\n")
	file.write("// Copyright (c) 2003-2005 ZeroC, Inc. All rights reserved.\n")
	file.write("//\n")
	file.write("// This copy of Ice is licensed to you under the terms described in the\n")
	file.write("// ICE_LICENSE file included in this distribution.\n")
	file.write("//\n")
	file.write("// **********************************************************************\n")
	file.write("\n")
	file.write("// Generated by " + progname + " from file `" + infile + "', " + time.ctime() + "\n")
	file.write("\n")
	file.write("// IMPORTANT: Do not edit this file -- any edits made here will be lost!\n");
	if lang == "cpp":
	    continue
	if lang == "java":
	    file.write("\n");
	    file.write("package IceInternal;\n")
	    file.write("\n")
	    file.write("public final class " + classname + '\n');
	    file.write("{\n")
	    continue
	if lang == "cs":
	    file.write("\n");
	    file.write("namespace IceInternal\n")
	    file.write("{\n")
	    file.write("    public sealed class " + classname + '\n')
	    file.write("    {\n");
	    continue
	progError("Internal error: impossible language: `" + lang + "'")
	sys.exit(1)

    if lang == "cpp":
        header = outputFiles[1][1]
	header.write("\n");
	header.write("#ifndef ICE_INTERNAL_" + classname + "_H\n");
	header.write("#define ICE_INTERNAL_" + classname + "_H\n");
	header.write("\n")
	header.write("#include <Ice/Config.h>")
	header.write("\n")
	header.write("namespace IceInternal\n")
	header.write("{\n")
	header.write("\n")
	header.write("class " + classname + '\n')
	header.write("{\n")
	header.write("public:\n")
	header.write("\n")
	file = outputFiles[0][1]
	file.write("\n");
	file.write("#include <Ice/" + classname + ".h>\n")

def writePostamble(lang, labels, commandLineLabels):
    file = outputFiles[0][1]
    if lang == "cpp":
        header = outputFiles[1][1]
	header.write("\n")

	header.write("    static const char* const* validProps[];\n")
	file.write("\n");
        file.write("const char* const* IceInternal::" + classname + "::validProps[] =\n")
	file.write("{\n")
	for label, line in labels.iteritems():
	    file.write("    " + label + "Props,\n")
	file.write("    0\n");
	file.write("};\n")

	header.write("    static const char* clPropNames[];\n")
	file.write("\n");
        file.write("const char* IceInternal::" + classname + "::clPropNames[] =\n")
	file.write("{\n")
	for label in commandLineLabels:
	    file.write("    \"" + label + "\",\n")
	file.write("    0\n");
	file.write("};\n")

	header.write("};\n")
	header.write("\n")
	header.write("}\n")
	header.write("\n")
	header.write("#endif\n");
	return
    if lang == "java":
        file.write("    public static final String[] validProps[] =\n")
	file.write("    {\n")
	for label, line in labels.iteritems():
	    file.write("        " + label + "Props,\n")
	file.write("        null\n")
	file.write("    };\n\n");

        file.write("    public static final String clPropNames[] =\n")
	file.write("    {\n")
	for label in commandLineLabels:
	    file.write("        \"" + label + "\",\n")
	file.write("        null\n")
	file.write("    };\n");
        file.write("}\n");
        return
    if lang == "cs":
        file.write("        public static string[][] validProps =\n")
	file.write("        {\n")
	for label, line in labels.iteritems():
	    file.write("            " + label + "Props,\n")
	file.write("            null\n")
	file.write("        };\n\n");

        file.write("        public static string[] clPropNames =\n")
	file.write("        {\n")
	for label in commandLineLabels:
	    file.write("            \"" + label + "\",\n")
	file.write("            null\n")
	file.write("        };\n");
        file.write("    }\n");
        file.write("}\n");
        return

def startSection(lang, label):
    if lang == "cpp":
        header = outputFiles[1][1]
	header.write("    static const char* " + label + "Props[];\n")

    file = outputFiles[0][1]
    if lang == "cpp":
	file.write("\n");
        file.write("const char* IceInternal::" + classname + "::" + label + "Props[] =\n")
        file.write("{\n");
	return
    if lang == "java":
        file.write("    public static final String " + label + "Props[] =\n");
	file.write("    {\n")
	return
    if lang == "cs":
        file.write("        public static string[] " + label + "Props =\n");
	file.write("        {\n")
        return

def endSection(lang):
    file = outputFiles[0][1]
    if lang == "cpp":
        file.write("    0\n");
        file.write("};\n");
	return
    if lang == "java":
	file.write("        null\n");
	file.write("    };\n");
        file.write("\n")
	return
    if lang == "cs":
	file.write("            null\n");
	file.write("        };\n");
        file.write("\n")
	return

wildcard = re.compile(".*<any>.*")

def writeEntry(lang, label, entry):
    file = outputFiles[0][1]
    if lang == "cpp":
	file.write("    \"" + label + '.' + string.replace(entry, "<any>", "*") + "\",\n")
    elif lang == "java":
	pattern = string.replace(entry, ".", "\\\\.")
	pattern = string.replace(pattern, "<any>", "[^\\\\s.]+")
	file.write("        " + "\"^" + label + "\\\\." + pattern + "$\",\n")
    elif lang == "cs":
	pattern = string.replace(entry, ".", "\\.")
	pattern = string.replace(pattern, "<any>", "[^\\s.]+")
	file.write("            " + "@\"^" + label + "\\." + pattern + "$\",\n")

def processFile(lang):

    #
    # Open input file.
    #
    global infile
    try:
	f = file(infile, 'r')
    except IOError, ex:
	progError("cannot open `" + infile + "': " + ex.strerror)
	sys.exit(1)

    #
    # Set up regular expressions for empty and comment lines, section headings, and entry lines.
    #
    ignore = re.compile("^\s*(?:#.*)?$") 			                # Empty line or comment line
    section = re.compile("^\s*([a-zA-Z_]\w*)\s*:\s*([a-zA-Z]\w*)?\s*$")        # Section heading
    entry = re.compile("^\s*([^ \t\n\r\f\v#]+)(?:\s*#.*)?$")	                # Any non-whitespace character sequence, except for #

    #
    # 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)

    #
    # Open output files.
    #
    global classname
    classname, ext = os.path.splitext(os.path.basename(infile))
    openOutputFile(classname + '.' + lang)
    if(lang == "cpp"):
	openOutputFile(classname + ".h")

    labels = {}		   # Records the line number on which each label is defined
    commandLineLabels = [] # The set of labels which are command line processing is enabled
    atSectionStart = 0	   # True for the line on which a label is defined
    seenSection = 0	   # Set to true (and the remains as true) once the first label is defined
    numEntries = 0	   # Number of entries within a section
    errors = 0		   # Number of syntax errors in the input file

    #
    # Write preamble.
    #
    writePreamble(lang)

    #
    # Loop over lines in input file.
    #
    global lineNum
    lines = f.readlines()
    for l in lines:
	lineNum += 1

	#
	# Ignore empty lines and comments.
	#
	if ignore.match(l) != None:
	    continue

	#
	# Start of section.
	#
	labelMatch = section.match(l)
	if labelMatch != None:
	    if atSectionStart:
		fileError("section `" + label + "' must have at least one entry")
	    label = labelMatch.group(1)
	    try:
		badLine = labels[label]
		fileError("duplicate section heading: `" + label + "': previously defined on line " + badLine)
	    except KeyError:
		pass
	    if label == "validProps":
	       fileError("`validProps' is reserved and cannot be used as a section heading")
            if labelMatch.group(2) != "false":
                commandLineLabels.append(label)
	    labels[label] = lineNum
	    if seenSection:
		endSection(lang)
	    numEntries = 0
	    startSection(lang, label)
	    seenSection = 1
	    atSectionStart = 1
	    continue

	entryMatch = entry.match(l)
	if entryMatch != None:
	    writeEntry(lang, label, entryMatch.group(1))
	    atSectionStart = 0
	    numEntries += 1
	    continue

	fileError("syntax error")

    if len(labels) == 0:
	fileError("input must define at least one section");

    #
    # End the final section.
    #
    if numEntries == 0:
	fileError("section `" + label + "' must have at least one entry")
    endSection(lang)

    #
    # End the source files.
    #
    writePostamble(lang, labels, commandLineLabels)

    global outputFiles
    for entry in outputFiles:
        entry[1].close()

    #
    # Remove the output files if anything went wrong, so we don't leave partically written files behind.
    #
    if errors != 0:
	removeOutputFiles()
	sys.exit(1)
    outputFiles = []

#
# Check arguments.
#
if len(sys.argv) != 1 and len(sys.argv) != 3:
    usage()
    sys.exit(1)

lang = ""
if len(sys.argv) == 1:
    #
    # Find where the root of the tree is.
    #
    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)

    infile = os.path.join(toplevel, "config", "PropertyNames.def")
    lang = "all"

else:
    option = sys.argv[1]
    if option == "--cpp":
	lang = "cpp"
    elif option == "--java":
	lang = "java"
    elif option == "--cs":
	lang = "cs"
    elif option == "-h" or option == "--help" or option == "-?":
	usage()
	sys.exit(0)
    else:
	usage()
	sys.exit(1)
    infile = sys.argv[2]

if lang == "all":
    processFile("cpp")
    shutil.move("PropertyNames.cpp", os.path.join(toplevel, "src", "Ice"))
    shutil.move("PropertyNames.h", os.path.join(toplevel, "src", "Ice"))
    processFile("java")
    if os.path.exists(os.path.join(toplevel, "..", "icej")):
        shutil.move("PropertyNames.java", os.path.join(toplevel, "..", "icej", "src", "IceInternal"));
    processFile("cs")
    if os.path.exists(os.path.join(toplevel, "..", "icecs")):
        shutil.move("PropertyNames.cs", os.path.join(toplevel, "..", "icecs", "src", "Ice"));
else:
    processFile(lang)


sys.exit(0)