summaryrefslogtreecommitdiffstats
path: root/confparse.py
blob: 0885299771c56cc50b96218b8247c9f7b0fb11d1 (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
# -*- coding: utf-8 -*-

from category import Category
from pattern import Pattern

class ParseError(Exception):
    """
    Raised when there is an error while parsing. Duh.
    """
    pass

class HaltedError(Exception):
    """
    Raised when we try to add to a token list that we have already "closed"
    (informed that we had reached the end of the token stream).
    """
    pass

class Token:
    """
    A single token. This class is essentially abstract. We never instantiate a
    generic token.
    """

    def __repr__(self):
        """
        The representation of a Token is, by default, the value of its
        item variable.
        """
        return self.item

    def isnewline(self):
        """
        Is this token a newline token?
        """
        return False

    def iswhitespace(self):
        """
        Is this token a whitespace token?
        """
        return False

    def isword(self, val=None):
        """
        Is this token a word token? Is the word the same as in the string `val`?
        """
        return False

    def isoper(self, val=None):
        """
        Is this token an operator token? Is the word the same as in the string
        `val`?
        """
        return False

class WhitespaceToken(Token):
    """
    Whitespace tokens come from any number of unquoted space or tab characters.
    """
    def __init__(self):
        self.item = "whitespace"

    def iswhitespace(self):
        """
        Always True for this class.
        """
        return True

class NewlineToken(Token):
    """
    Token yielded by a single newline character.
    """
    def __init__(self):
        self.item = "newline"

    def isnewline(self):
        """
        Always True for this class.
        """
        return True

class OperToken(Token):
    """
    Token yielded by a single non-word (alphanumeric and _) character.
    """
    def __init__(self, item):
        """
        `item` specifies the operator character this token will represent.
        """
        self.item = item

    def isoper(self, item = None):
        """
        Always True if item is None, otherwise true if `item` is the operator
        character represented by this token.
        """
        if item == None:
            return True
        return self.item == item

class WordToken(Token):
    """
    Represents a string of word characters (alphanumeric or _) or the contents
    of a quoted string.
    """
    def __init__(self, word):
        """
        `word` is the text this token will represent.
        """
        self.word = word

    def __repr__(self):
        """
        Our representation is a bit different, and consists of the word we
        represent, quoted.
        """
        return "`%s`" % self.word

    def isword(self, item = None):
        """
        Always True if item is None, otherwise true if `item` is the word
        represented by this token.
        """
        if item == None:
            return True
        return self.word == item

class TokenList:
    """
    This class contains a list of tokens. It is a list-like object, but is
    read-only until it is `close`d. It is populated by passing characters to
    the constructor or the `add` method. Calling `close` indicates all
    characters have been passed and the TokenList should now behave as a
    regular list.
    """
    class CloseSignal:
        """
        Passed to the current state instead of a character to indicate we're
        done receiving characters.
        """
        pass

    def __init__(self, data=None):
        """
        `data` is a set of initial characters which are passed to `add`
        immediately after initialization.
        """
        self.tokens = []
        self.state = self.s_expect_word
        self.current_token = ""

        self.__getitem__ = self.tokens.__getitem__
        self.__len__ = self.tokens.__len__
        if data != None:
            self.add(data)

    def __repr__(self):
        """
        Our representation is simply the representation of our processed
        tokens joined by spaces. If we have an unfinalized token, it is
        shown last in parenthesis.
        """
        ret = " ".join([ str(x) for x in self.tokens])
        if len(self.current_token) > 0:
            ret += "(%s)" % self.current_token
        return ret

    def add(self, data):
        """
        Add characters to the token list. State is persistent between adds such
        that calling:
            tl.add(str1)
            tl.add(str2)
        is the same as calling:
            tl.add(str1 + str2)
        in all cases
        """
        for char in data:
            self.state(char)

    def s_expect_word(self, char):
        """
        Handle the next character of input while we are expecting to see
        a word.
        """
        if char.__class__ == TokenList.CloseSignal:
            self.close_token()
            self.state = self.s_accept
        elif char == "\n":
            self.close_token()
            self.tokens.append(NewlineToken())
        elif char.isspace():
            self.close_token()
            self.tokens.append(WhitespaceToken())
            self.state = self.s_skip_space
        elif char == '"':
            self.close_token()
            self.state = self.s_in_quote
        elif char == "#":
            self.close_token()
            self.state = self.s_in_comment
        elif char.isalnum() or char == "_":
            self.current_token += char
        else:
            self.close_token()
            self.tokens.append(OperToken(char))

    def s_skip_space(self, char):
        """
        Handle the next character while we are skipping a block of whitespace.
        """
        if char.__class__ == TokenList.CloseSignal:
            self.state = self.s_accept
        elif not char.isspace():
            self.state = self.s_expect_word
            self.state(char)

    def s_in_quote(self, char):
        """
        Handle the next character while we are in a quoted string.
        """
        if char.__class__ == TokenList.CloseSignal:
            raise ParseError('`"` expected')
        elif char == "\\":
            self.state = self.s_always_quote
        elif char == '"':
            self.close_token()
            self.state = self.s_expect_word
        else:
            self.current_token += char

    def s_always_quote(self, char):
        """
        Handle the next character, which the previous character has escaped.
        """
        if char.__class__ == TokenList.CloseSignal:
            raise ParseError('`"` expected')
        else:
            self.current_token += char
            self.state = self.s_in_quote

    def s_in_comment(self, char):
        """
        Handle the next character while we are in a comment.
        """
        if char.__class__ == TokenList.CloseSignal:
            self.state = self.s_accept
        elif char == "\n":
            self.state = self.s_expect_word

    def s_accept(self, char):
        """
        Handle the next character when there aren't supposed to be any more
        characters (this function getting called is an error.
        """
        raise HaltedError("Data given to TokenList when no more expected")

    def assert_full(self):
        """
        Raise an error if there are no tokens in the list.
        """
        if len(self.tokens) == 0:
            raise ParseError("Expected Token")

    def trim_leading_whitespace(self):
        """
        Delete any whitespace at the beginning of the list, and raise an error
        if this empties the string.
        """
        self.assert_full()
        while self[0].iswhitespace():
            del self[0]
        self.assert_full()

    def close(self):
        """
        Consider the last added character to be the final character of the
        input. Further calls to `add` will yield an error. Items in the list
        may now be changed and deleted.
        """
        self.__setitem__ = self.tokens.__setitem__
        self.__delitem__ = self.tokens.__delitem__
        self.state(TokenList.CloseSignal())

    def close_token(self):
        """
        Mark the token currently being processed as complete and add it to the
        final list.
        """
        if len(self.current_token) > 0:
            self.tokens.append(WordToken(self.current_token))
        self.current_token = ""

class ParseTreeNode:
    """
    A node in the final parse tree we generate of a given set of config data.
    """
    def __repr__(self):
        """
        We represent ourselves as an S-expression
        """
        return "%s (%s)" % (self.__class__,
                ") (".join([str(x) for x in self.children()]))

class Conf(ParseTreeNode):
    """
    A set of configuration items.
    """
    def __init__(self, string):
        """
        `string` is the text configuration which defines the new Conf object.
        """
        toks = TokenList(string)
        toks.close()
        self.propmatches = []
        while len(toks) > 0:
            self.propmatches.append(PropMatch(toks))

    def children(self):
        """
        List of child nodes of this parse tree node
        """
        return self.propmatches

    def __repr__(self):
        """
        Since we're ostensibly the top of the tree, we get an extra set of
        parens.
        """
        return "(%s)" % ParseTreeNode.__repr__(self)

class PropMatch(ParseTreeNode):
    """
    A property match block. These blocks specify, textually, a category, and
    several properties which apply to it. The text form is:
        name property
    or
        name() property
    or
        name(args)
            property
    or
        name(args): property
    etc.
    """
    def __init__(self, toks):
        """
        `toks` is a token lists. The tokens at the beginning thereof which
        define a property match block will be removed.
        """
        self.properties = []
        while True:
            toks.trim_leading_whitespace()
            if not toks[0].isnewline():
                break
            del toks[0]
        self.pattern = CatSpec(toks)
        if toks[0].isoper(":"):
            del toks[0]
        while len(toks) > 0:
            if toks[0].iswhitespace():
                del toks[0]
            elif toks[0].isnewline():
                del toks[0]
                if len(toks) == 0 or not toks[0].iswhitespace():
                    break
            else:
                self.properties.append(PropSpec(toks))
        if len(self.properties) == 0:
            raise ParseError("Property expected")

    def children(self):
        """
        List of child nodes of this parse tree node
        """
        return [self.pattern] + self.properties

class CatSpec(ParseTreeNode):
    """
    A category specification. Parsed from a textual specification of a category
    of the form:
        name
    or
        name()
    or
        name(args)
    """
    def __init__(self, toks):
        """
        `toks` is a token stream. The tokens at the beginning thereof which
        define a CatSpec will be removed.
        """
        while len(toks) > 0 and toks[0].iswhitespace():
            del toks[0]
        toks.assert_full()
        if not toks[0].isword():
            raise ParseError("State name expected")
        self.name = toks[0]
        del toks[0]
        self.args = ArgSpec(toks)

    def to_category(self):
        """
        convert this catspec to a category object.
        """
        return Category(self.name.word, **self.args.to_hash())

    def children(self):
        """
        List of child nodes of this parse tree node
        """
        if len(self.args.items) == 0:
            return [self.name]
        return [self.name, self.args]

class ArgSpec(ParseTreeNode):
    """
    Argument specification. Represents a textual argument list of the form:
    (key: value, key2: value2, ...)
    """
    def __init__(self, toks):
        """
        `toks` is a token stream. The tokens at the beginning thereof which
        define an ArgSpec will be removed. NOTE: if there is no ArgSpec at the
        start of the stream, no error is yielded and the created ArgSpec is
        empty (equivalent to "()")
        """
        self.items = []
        toks.assert_full()
        if not toks[0].isoper('('):
            return
        del toks[0]
        expect_arg = True
        while len(toks) > 0:
            if toks[0].iswhitespace():
                del toks[0]
            elif toks[0].isoper(")"):
                del toks[0]
                return
            elif expect_arg:
                self.items.append(KVPair(toks))
                expect_arg = False
            elif toks[0].isoper(","):
                del toks[0]
                expect_arg = True
            else:
                raise ParseError("Unexpected %s token" % toks[0])

    def to_hash(self):
        """
        convert `self` to an actual hash object
        """
        ret = {}
        for i in self.items:
            ret[i.name.word] = Pattern(i.truth, i.value.word)
        return ret

    def children(self):
        """
        List of child nodes of this parse tree node
        """
        return self.items

class KVPair(ParseTreeNode):
    """
    A key value pair, specified in the form:
        key: value
    or:
        key: ! value
    """
    def __init__(self, toks):
        """
        `toks` is a token stream. The tokens at the beginning thereof which
        define a KVPair will be removed.
        """
        toks.trim_leading_whitespace()
        if not toks[0].isword():
            raise ParseError("Expected name before %s token" % toks[0])
        self.name = toks[0]
        self.truth = True
        del toks[0]
        toks.assert_full()
        if not toks[0].isoper(":"):
            raise ParseError("Expected `:` before %s token" % toks[0])
        del toks[0]
        toks.trim_leading_whitespace()
        if toks[0].isoper("!"):
            self.truth = False
            del toks[0]
            toks.trim_leading_whitespace()
        if not toks[0].isword():
            raise ParseError("Expected value before %s token" % toks[0])
        self.value = toks[0]
        del toks[0]

    def children(self):
        """
        List of child nodes of this parse tree node
        """
        return [self.name, self.value]

class PropSpec(ParseTreeNode):
    """
    A property specification, specified textually as one of:
        on someevent
        when somestate
        auto
        exec somecommand
    """
    def __init__(self, toks):
        """
        `toks` is a token stream. The tokens at the beginning thereof which
        define a PropSpec will be removed.
        """
        toks.trim_leading_whitespace()
        if toks[0].isword("when"):
            self.spec = WhenSpec(toks)
        elif toks[0].isword("on"):
            self.spec = OnSpec(toks)
        elif toks[0].isword("auto"):
            toks[0:1] = [WordToken("on"), WhitespaceToken(), WordToken("ε")]
            self.spec = OnSpec(toks)
        elif toks[0].isword("exec"):
            self.spec = ExecSpec(toks)
        else:
            raise ParseError("Expected keyword before %s token" % toks[0])

    def children(self):
        """
        List of child nodes of this parse tree node
        """
        return [self.spec]

class WhenSpec(ParseTreeNode):
    """
    A specification of a when relationship. Defined textually as:
        when CatSpec
    """
    def __init__(self, toks):
        if not toks[0].isword("when"):
            raise Exception("Impossible condition in parser")
        del toks[0]
        toks.trim_leading_whitespace()
        if not toks[0].isword():
            raise Exception("Expected name before %s token" % toks[0])
        self.waiting_for = CatSpec(toks)

    def children(self):
        """
        List of child nodes of this parse tree node
        """
        return [self.waiting_for]

class OnSpec(ParseTreeNode):
    """
    A specification of an event trigger. Defined textually as:
        on CatSpec
    """
    def __init__(self, toks):
        if not toks[0].isword("on"):
            raise Exception("Impossible condition in parser")
        del toks[0]
        toks.trim_leading_whitespace()
        if not toks[0].isword():
            raise Exception("Expected name before %s token" % toks[0])
        self.waiting_for = CatSpec(toks)

    def children(self):
        """
        List of child nodes of this parse tree node
        """
        return [self.waiting_for]

class ExecSpec(ParseTreeNode):
    """
    A specification of a service to run. Defined textually as:
        exec script
    """
    def __init__(self, toks):
        if not toks[0].isword("exec"):
            raise Exception("Impossible condition in parser")
        del toks[0]
        self.script_toks = []
        while not toks[0].isnewline():
            self.script_toks.append(toks[0])
            del toks[0]

    def children(self):
        """
        List of child nodes of this parse tree node
        """
        return [self.script_toks]