summaryrefslogtreecommitdiff
path: root/toolkit/src2xml/source/srcparser.py
blob: b25d39ecb66e330a3da9620a64a00dcb8550a6af (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
import sys
from globals import *
import srclexer

# simple name translation map
postTransMap = {"ok-button": "okbutton", 
                "cancel-button": "cancelbutton",
                "help-button": "helpbutton"}

def transName (name):
    """Translate a mixed-casing name to dash-separated name.

Translate a mixed-casing name (e.g. MyLongName) to a dash-separated name
(e.g. my-long-name).
"""
    def isUpper (c):
        return c >= 'A' and c <= 'Z'

    newname = ''
    parts = []
    buf = ''
    for c in name:
        if isUpper(c) and len(buf) > 1:
            parts.append(buf)
            buf = c
        else:
            buf += c

    if len(buf) > 0:
        parts.append(buf)

    first = True
    for part in parts:
        if first:
            first = False
        else:
            newname += '-'
        newname += part.lower()

    # special-case mapping ...
    if 0: #postTransMap.has_key(newname):
        newname = postTransMap[newname]

    return newname


def transValue (value):
    """Translate certain values.

Examples of translated values include TRUE -> true, FALSE -> false.
"""
    if value.lower() in ["true", "false"]:
        value = value.lower()
    return value


def renameAttribute (name, elemName):

    # TODO: all manner of evil special cases ...
    if elemName == 'metric-field' and name == 'spin-size':
        return 'step-size'

    return name


class Statement(object):
    """Container to hold information for a single statement.

Each statement consists of the left-hand-side token(s), and right-hand-side
tokens, separated by a '=' token.  This class stores the information on the
left-hand-side tokens.
"""
    def __init__ (self):
        self.leftTokens = []
        self.leftScope = None


class MacroExpander(object):
    def __init__ (self, tokens, defines):
        self.tokens = tokens
        self.defines = defines

    def expand (self):
        self.pos = 0
        while self.pos < len(self.tokens):
            self.expandToken()

    def expandToken (self):
        token = self.tokens[self.pos]
        if not self.defines.has_key(token):
            self.pos += 1
            return

        macro = self.defines[token]
        nvars = len(macro.vars.keys())
        if nvars == 0:
            # Simple expansion
            self.tokens[self.pos:self.pos+1] = macro.tokens
            return
        else:
            # Expansion with arguments.
            values, lastPos = self.parseValues()
            newtokens = []
            for mtoken in macro.tokens:
                if macro.vars.has_key(mtoken):
                    # variable
                    pos = macro.vars[mtoken]
                    valtokens = values[pos]
                    for valtoken in valtokens:
                        newtokens.append(valtoken)
                else:
                    # not a variable
                    newtokens.append(mtoken)

            self.tokens[self.pos:self.pos+lastPos+1] = newtokens


    def parseValues (self):
        """Parse tokens to get macro function variable values.

Be aware that there is an implicit quotes around the text between the open 
paren, the comma(s), and the close paren.  For instance, if a macro is defined 
as FOO(a, b) and is used as FOO(one two three, and four), then the 'a' must be 
replaced with 'one two three', and the 'b' replaced with 'and four'.  In other 
words, whitespace does not end a token.  

"""
        values = []
        i = 1
        scope = 0
        value = []
        while True:
            try:
                tk = self.tokens[self.pos+i]
            except IndexError:
                progress ("error parsing values (%d)\n"%i)
                for j in xrange(0, i):
                    print self.tokens[self.pos+j],
                print ''
                srclexer.dumpTokens(self.tokens)
                srclexer.dumpTokens(self.newtokens)
                print "tokens expanded so far:"
                for tk in self.expandedTokens:
                    print "-"*20
                    print tk
                    srclexer.dumpTokens(self.defines[tk].tokens)
                sys.exit(1)
            if tk == '(':
                value = []
                scope += 1
            elif tk == ',':
                values.append(value)
                value = []
            elif tk == ')':
                scope -= 1
                values.append(value)
                value = []
                if scope == 0:
                    break
                else:
                    raise ParseError ('')
            else:
                value.append(tk)
            i += 1

        return values, i

    def getTokens (self):
        return self.tokens


class SrcParser(object):

    def __init__ (self, tokens, defines = None):
        self.tokens = tokens
        self.defines = defines
        self.debug = False
        self.onlyExpandMacros = False

    def init (self):
        self.elementStack = [RootNode()]
        self.stmtData = Statement()
        self.tokenBuf = []
        self.leftTokens = []

        # Expand defined macros.
        if self.debug:
            progress ("-"*68+"\n")
            for key in self.defines.keys():
                progress ("define: %s\n"%key)

        self.expandMacro()
        self.tokenSize = len(self.tokens)

    def expandMacro (self):
        macroExp = MacroExpander(self.tokens, self.defines)
        macroExp.expand()
        self.tokens = macroExp.getTokens()
        if self.onlyExpandMacros:
            srclexer.dumpTokens(self.tokens)
            sys.exit(0)

    def parse (self):
        """Parse it!

This is the main loop for the parser.  This is where it all begins and ends.
"""
        self.init()

        i = 0
        while i < self.tokenSize:
            tk = self.tokens[i]
            if tk == '{':
                i = self.openBrace(i)
            elif tk == '}':
                i = self.closeBrace(i)
            elif tk == ';':
                i = self.semiColon(i)
            elif tk == '=':
                i = self.assignment(i)
            else:
                self.tokenBuf.append(tk)

            i += 1

        return self.elementStack[0]

    #-------------------------------------------------------------------------
    # Token Handlers

    """
Each token handler takes the current token position and returns the position 
of the last token processed.  For the most part, the current token position 
and the last processed token are one and the same, in which case the handler 
can simply return the position value it receives without incrementing it.  

If you need to read ahead to process more tokens than just the current token, 
make sure that the new token position points to the last token that has been 
processed, not the next token that has not yet been processed.  This is 
because the main loop increments the token position when it returns from the 
handler.
""" 

    # assignment token '='
    def assignment (self, i):
        self.leftTokens = self.tokenBuf[:]
        if self.stmtData.leftScope == None:
            # Keep track of lhs data in case of compound statement.
            self.stmtData.leftTokens = self.tokenBuf[:]
            self.stmtData.leftScope = len(self.elementStack) - 1

        self.tokenBuf = []
        return i
    
    # open brace token '{'
    def openBrace (self, i):
        bufSize = len(self.tokenBuf)
        leftSize = len(self.leftTokens)
        obj = None
        if bufSize == 0 and leftSize > 0:
            # Name = { ...
            obj = Element(self.leftTokens[0])

        elif bufSize > 0 and leftSize == 0:
            # Type Name { ...
            wgtType = self.tokenBuf[0]
            wgtRID = None
            if bufSize >= 2:
                wgtRID = self.tokenBuf[1]
            obj = Element(wgtType, wgtRID)

        else:
            # LeftName = Name { ...
            obj = Element(self.leftTokens[0])
            obj.setAttr("type", self.tokenBuf[0])

        obj.name = transName(obj.name)

        if obj.name == 'string-list':
            i = self.parseStringList(i)
        elif obj.name == 'filter-list':
            i = self.parseFilterList(i, obj)
        else:
            self.elementStack[-1].appendChild(obj)
            self.elementStack.append(obj)

        self.tokenBuf = []
        self.leftTokens = []

        return i

    # close brace token '}'
    def closeBrace (self, i):
        if len(self.tokenBuf) > 0:
            if self.debug:
                print self.tokenBuf
            raise ParseError ('')
        self.elementStack.pop()
        return i

    # semi colon token ';'
    def semiColon (self, i):
        stackSize = len(self.elementStack)
        scope = stackSize - 1
        if len(self.tokenBuf) == 0:
            pass
        elif scope == 0:
            # We are not supposed to have any statment in global scope.  
            # Just ignore this statement.
            pass
        else:
            # Statement within a scope.  Import it as an attribute for the 
            # current element.
            elem = self.elementStack[-1]

            name = "none"
            if len(self.leftTokens) > 0:
                # Use the leftmost token as the name for now.  If we need to
                # do more complex parsing of lhs, add more code here.
                name = self.leftTokens[0]
                name = transName(name)

            if name == 'pos':
                i = self.parsePosAttr(i)
            elif name == 'size':
                i = self.parseSizeAttr(i)
            elif len (self.tokenBuf) == 1:
                # Simple value
                value = transValue(self.tokenBuf[0])
                name = renameAttribute(name, elem.name)
                elem.setAttr(name, value)

            if not self.stmtData.leftScope == None and self.stmtData.leftScope < scope:
                # This is a nested scope within a statement.  Do nothing for now.
                pass

        if self.stmtData.leftScope == scope:
            # end of (nested) statement.
            self.stmtData.leftScope = None

        self.tokenBuf = []
        self.leftTokens = []

        return i

    def parseStringList (self, i):

        i += 1
        while i < self.tokenSize:
            tk = self.tokens[i]
            if tk == '}':
                break
            i += 1

        return i

    def parseFilterList (self, i, obj):
        self.elementStack[-1].appendChild(obj)
        self.elementStack.append(obj)

        return i

    def parsePosAttr (self, i):

        # MAP_APPFONT ( 6 , 5 )
        elem = self.elementStack[-1]
        x, y = self.parseMapAppfont(self.tokenBuf)
        elem.setAttr("x", x)
        elem.setAttr("y", y)

        return i

    def parseSizeAttr (self, i):

        # MAP_APPFONT ( 6 , 5 )
        elem = self.elementStack[-1]
        width, height = self.parseMapAppfont(self.tokenBuf)
        elem.setAttr("width", width)
        elem.setAttr("height", height)

        return i

    def parseMapAppfont (self, tokens):
        values = []
        scope = 0
        val = ''
        for tk in tokens:
            if tk == '(':
                scope += 1
                if scope == 1:
                    val = ''
                else:
                    val += tk
            elif tk == ')':
                scope -= 1
                if scope == 0:
                    if len(val) == 0:
                        raise ParseError ('')
                    values.append(val)
                    break
                else:
                    val += tk
            elif tk == ',':
                if len(val) == 0:
                    raise ParseError ('')
                values.append(val)
                val = ''
            elif scope > 0:
                val += tk

        if len(values) != 2:
            raise ParseError ('')

        return eval(values[0]), eval(values[1])