Source

Kong / kong / ast.py

  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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
""":mod:`kong.ast` --- Abstract Syntax Tree
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

"""
import numbers
import collections
import itertools
import re


class Node(object):
    """An abstract base class for syntax tree."""


class ExpressionList(tuple):
    """An abstract base class for :class:`Expression` list."""

    def __new__(cls, expressions):
        def arg():
            for expr in expressions:
                if isinstance(expr, Expression):
                    yield expr
                else:
                    args = cls.__module__, cls.__name__, expr
                    raise TypeError('{0}.{1} accepts only '
                                    'kong.ast.Expression objects as elements, '
                                    'not {2!r}'.format(*args))
        return tuple.__new__(cls, arg())

    def __repr__(self):
        r = tuple.__repr__(self)[1:-1]
        if r.endswith(','):
            r = r[:-1]
        cls = type(self)
        return '{0}.{1}([{2}])'.format(cls.__module__, cls.__name__, r)


class Program(Node, ExpressionList):
    r"""A program node.

    .. productionlist::
       program: (`expr` `terminate`)* [`expr`]
       terminate: (";" | `newline`)+
       newline: ["\r"] "\n"

    .. sourcecode:: pycon

       >>> Program([Identifier(u'abc')])
       kong.ast.Program([kong.ast.Identifier(u'abc')])
       >>> print unicode(_)
       abc

    :param expressions: :class:`Expression` list
    :type expressions: :class:`collections.Iterable`

    """

    def __unicode__(self):
        return u'\n'.join(itertools.imap(unicode, self))


class Expression(Node):
    """An expression node. It is an abstract class.

    .. productionlist::
       expr: "(" `expr` ")" | `literal` | `id` | `attr` |
             `apply` | `operator` | `define`

    """


class Identifier(Expression, unicode):
    """An identifier node.

    .. productionlist::
       id: /[^[:digit:][:space:]][^[:space:]]*/ except "<-"

    :param identifier: an identifier string

    """

    __slots__ = ()

    def __new__(cls, string, *args, **kwargs):
        ident = unicode.__new__(cls, string, *args, **kwargs)
        if ident == u'':
            raise ValueError('identifier cannot be empty')
        elif re.search(ur'<-|[\s.,:(){}]', ident) or ident.isdigit():
            s = unicode(ident)
            raise ValueError('invalid identifier: {0!r}'.format(s))
        return ident

    def __repr__(self):
        cls = type(self)
        repr = unicode.__repr__(self)
        return '{0}.{1}({2})'.format(cls.__module__, cls.__name__, repr)


class Application(Expression):
    """An application (call) node.

    .. productionlist::
       apply: `expr` "(" `args` ")" | `expr` `args`
       args: (`expr` ",")* [`expr`]

    .. sourcecode:: pycon

       >>> app = Application(Identifier('func'),
       ...                   [Identifier('a'), Identifier('b')])
       >>> app  # doctest: +NORMALIZE_WHITESPACE
       kong.ast.Application(kong.ast.Identifier(u'func'),
                            [kong.ast.Identifier(u'a'),
                             kong.ast.Identifier(u'b')])
       >>> print unicode(app)
       func(a, b)

    :param function: a function to apply
    :type function: :class:`Expression`
    :param arguments: a :class:`Expresion` list
    :type arguments: :class:`collections.Iterable`

    """

    __slots__ = 'function', 'arguments'

    def __init__(self, function, arguments):
        if not isinstance(function, Expression):
            raise TypeError('function must be a kong.ast.Expression object, '
                            'not ' + repr(function))
        elif not isinstance(arguments, collections.Iterable):
            raise TypeError('arguments must be iterable')
        def args():
            for arg in arguments:
                if isinstance(arg, Expression):
                    yield arg
                else:
                    raise TypeError('arguments must consist of only kong.'
                                    'ast.Expression, not ' + repr(arg))
        self.function = function
        self.arguments = tuple(args())

    def __eq__(self, operand):
        return (isinstance(operand, Application) and
                self.function == operand.function and
                self.arguments == operand.arguments)

    def __ne__(self, operand):
        return not (self == operand)

    def __unicode__(self):
        args = u', '.join(itertools.imap(unicode, self.arguments))
        return u'{0}({1})'.format(unicode(self.function), args)

    def __repr__(self):
        cls = type(self)
        vals = (cls.__module__, cls.__name__,
                self.function, list(self.arguments))
        return '{0}.{1}({2!r}, {3!r})'.format(*vals)


class Attribute(Application):
    """A pseudo-attribute node.

    .. productionlist::
       attr: `expr` "." (`id` | `number`)

    .. sourcecode:: pycon

       >>> attr = Attribute(Identifier('obj'), attribute=Identifier('attr'))
       >>> attr  # doctest: +NORMALIZE_WHITESPACE
       kong.ast.Attribute(kong.ast.Identifier(u'obj'),
                          attribute=kong.ast.Identifier(u'attr'))
       >>> print unicode(attr)
       obj.attr

    :param function: a function to apply
    :type function: :class:`Expression`
    :param arguments: a :class:`Expresion` list
    :type arguments: :class:`collections.Iterable`
    :param attribute: an attribute name
    :type attribute: :class:`Identifier`, :class:`numbers.Integral`

    Arguments ``attribute`` and ``arguments`` are exclusive but one of them
    is required.

    """

    def __init__(self, function, arguments=None, attribute=None):
        if arguments is None and attribute is None:
            raise TypeError('one of arguments or attribute must be passed')
        elif arguments is not None and attribute is not None:
            raise TypeError('only one of arguments or attribute are accepted')
        elif isinstance(attribute, (numbers.Integral, Identifier)):
            arguments = StringLiteral(attribute),
        elif attribute is not None:
            raise TypeError('attribute must be an integer or kong.ast.'
                            'Identifier, not ' + repr(attribute))
        else:
            try:
                arguments = tuple(arguments)
            except TypeError:
                raise TypeError('arguments must be iterable')
        if len(arguments) != 1:
            raise TypeError('attribute takes only one string argument')
        elif not isinstance(arguments[0], StringLiteral):
            raise TypeError('argument must be a kong.ast.StringLiteral, not ' +
                            repr(arguments[0]))
        Application.__init__(self, function, arguments)

    @property
    def attribute(self):
        """(:class:`Identifier`, :class:`numbers.Integral`) Attribute name.

        .. sourcecode:: pycon

           >>> attr = Attribute(Identifier('a'), [StringLiteral(12)])
           >>> attr.attribute
           12
           >>> attr2 = Attribute(Identifier('a'), [StringLiteral(u'b')])
           >>> attr2.attribute
           kong.ast.Identifier(u'b')

        """
        s = self.arguments[0].string
        return int(s) if s.isdigit() else Identifier(s)

    def __unicode__(self):
        return u'{0}.{1}'.format(self.function, self.arguments[0].string)

    def __repr__(self):
        cls = type(self)
        attr = Identifier(self.arguments[0].string)
        f = u'{0}.{1}({2!r}, attribute={3!r})'
        return f.format(cls.__module__, cls.__name__, self.function, attr)


class Operator(Application):
    """A pseudo-operator node.

    .. productionlist::
       operator: `expr` `id` `expr`

    .. sourcecode:: pycon

       >>> op = Operator(operator=Identifier('+'),
       ...               operands=[StringLiteral(1), StringLiteral(2)])
       >>> op.function  # doctest: +NORMALIZE_WHITESPACE
       kong.ast.Attribute(kong.ast.StringLiteral(1),
                          attribute=kong.ast.Identifier(u'+'))
       >>> op.arguments
       (kong.ast.StringLiteral(2),)
       >>> print unicode(op)
       1 + 2

    There are two signatures. One is the same to :class:`Application`'s:

    :param function: a function to apply
    :type function: :class:`Expression`
    :param arguments: a :class:`Expresion` list
    :type arguments: :class:`collections.Iterable`

    Other one takes ``operator`` and ``operands`` (by keywords only):

    :param operator: an operator name
    :type operator: :class:`Identifier`
    :param operands: pair of :class:`Expression`
    :type operands: :class:`collections.Iterable`

    """

    def __init__(self, function=None, arguments=None,
                 operator=None, operands=None):
        if not (function is not None and arguments is not None or
                operator is not None and operands is not None):
            raise TypeError('it takes function and arguments both or '
                            'operator and operands both')
        if (function is not None or arguments is not None) and \
           (operator is not None or operands is not None):
            raise TypeError('two available signatures (function, arguments) '
                            'and (operator, operands) are exclusive')
        if operator is not None:
            if operands is None:
                raise TypeError('operands are required')
            elif not isinstance(operator, Identifier):
                raise TypeError('operator must be a kong.ast.Identifier, not '
                                + repr(operator))
            if not isinstance(operands, list):
                try:
                    operands = list(operands)
                except TypeError:
                    raise TypeError('operands must be iterable')
            if len(operands) != 2:
                raise TypeError('binary operator takes only two arguments')
            function = Attribute(operands.pop(0), attribute=operator)
            arguments = operands
        if not (isinstance(function, Attribute) or
                isinstance(function, Application) and
                len(function.arguments) == 1 and
                isinstance(function.arguments[0], StringLiteral)):
            raise TypeError('function must be kong.ast.Attribute or '
                            'equivalent kong.ast.Application, not ' +
                            repr(function))
        if isinstance(arguments, (tuple, list)):
            try:
                arguments = tuple(arguments)
            except TypeError:
                raise TypeError('arguments must be iterable')
        if len(arguments) != 1:
            raise TypeError('operator takes only one argument')
        Application.__init__(self, function, arguments)

    @property
    def operator(self):
        """(:class:`Identifier`) Operator name.

        .. sourcecode:: pycon

           >>> op = Operator(Attribute(Identifier('a'),
           ...                         attribute=Identifier('-')),
           ...               [StringLiteral(123)])
           >>> op.operator
           kong.ast.Identifier(u'-')

        """
        return Identifier(self.function.arguments[0].string)

    @property
    def operands(self):
        """(:class:`tuple`) Pair of two operands.

        .. sourcecode:: pycon

           >>> op = Operator(Attribute(Identifier('a'),
           ...                         attribute=Identifier('-')),
           ...               [StringLiteral(123)])
           >>> op.operands
           (kong.ast.Identifier(u'a'), kong.ast.StringLiteral(123))

        """
        return self.function.function, self.arguments[0]

    def __unicode__(self):
        a, b = self.operands
        forms = a, self.operator, b
        return u' '.join(itertools.imap(unicode, forms))

    def __repr__(self):
        cls = type(self)
        f = u'{0}.{1}(operator={2!r}, operands={3!r})'
        return f.format(cls.__module__, cls.__name__,
                        self.operator, list(self.operands))


class Definition(Expression):
    """An abstract class for definition nodes.

    .. productionlist::
       define: `lvalue` "<-" `expr`
       lvalue: ["."] `id` | `attr`

    """

    #: (:class:`Identifier`, :class:`Attribute`) Lvalue expression.
    lvalue = NotImplemented

    #: (:class:`Expression`) Rvalue expression.
    rvalue = NotImplemented

    def __eq__(self, operand):
        return (type(operand) is type(self) and
                self.lvalue == operand.lvalue and
                self.rvalue == operand.rvalue)

    def __ne__(self, operand):
        return not (self == operand)

    def __unicode__(self):
        args = self.lvalue, '<-', self.rvalue
        return u' '.join(itertools.imap(unicode, args))

    def __repr__(self):
        cls = type(self)
        args = cls.__module__, cls.__name__, self.lvalue, self.rvalue
        return '{0}.{1}(lvalue={2!r}, rvalue={3!r})'.format(*args)


class IdentifierDefinition(Definition):
    """An abstract class for identifier definition nodes."""

    __slots__ = 'lvalue', 'rvalue'

    def __init__(self, lvalue, rvalue):
        if not isinstance(lvalue, Identifier):
            raise TypeError('lvalue must be a kong.ast.Identifier, not ' +
                            repr(lvalue))
        elif not isinstance(rvalue, Expression):
            raise TypeError('rvalue must be a kong.ast.Expression, not ' +
                            repr(rvalue))
        self.lvalue = lvalue
        self.rvalue = rvalue


class IdentifierLocalDefinition(IdentifierDefinition):
    """Local identifier definition node.

    .. sourcecode:: pycon

       >>> set = IdentifierLocalDefinition(lvalue=Identifier('abc'),
       ...                                 rvalue=Identifier('def'))
       >>> print unicode(set)
       abc <- def

    :param lvalue: lvalue identifier
    :type lvalue: :class:`Identifier`
    :param rvalue: rvalue expression
    :type rvalue: :class:`Expression`

    """


class IdentifierAssignment(IdentifierDefinition):
    """Identifier assignment node.

    .. sourcecode:: pycon

       >>> set = IdentifierAssignment(lvalue=Identifier('abc'),
       ...                            rvalue=Identifier('def'))
       >>> print unicode(set)
       .abc <- def

    :param lvalue: lvalue identifier
    :type lvalue: :class:`Identifier`
    :param rvalue: rvalue expression
    :type rvalue: :class:`Expression`

    """

    def __unicode__(self):
        return '.' + IdentifierDefinition.__unicode__(self)


class AttributeDefinition(Definition, Application):
    """A definition node of attribute. Attribute definitions are just
    two arguments application under the hood. For example, following
    two expressions are equivalent:

    .. sourcecode:: tofu

       obj.attr = value
       obj('attr', value)

    .. sourcecode:: pycon

       >>> attr = Attribute(Identifier('abc'), attribute=Identifier('def'))
       >>> set = AttributeDefinition(lvalue=attr, rvalue=StringLiteral(123))
       >>> set.function
       kong.ast.Identifier(u'abc')
       >>> set.arguments
       (kong.ast.StringLiteral(u'def'), kong.ast.StringLiteral(123))
       >>> print unicode(set)
       abc.def <- 123

    There are two signatures. One is the same to :class:`Application`'s:

    :param function: a function to apply
    :type function: :class:`Expression`
    :param arguments: a :class:`Expresion` list
    :type arguments: :class:`collections.Iterable`

    Other one is the same to :class:`Definition` or :class:`Assignment`'s
    (but only by keywords):

    :param lvalue: lvalue attribute
    :type lvalue: :class:`Attribute`, :class:`Application`
    :param rvalue: rvalue expression
    :type rvalue: :class:`Expression`

    """

    def __init__(self, function=None, arguments=None, lvalue=None, rvalue=None):
        if not (function is not None and arguments is not None or
                lvalue is not None and lvalue is not None):
            raise TypeError('it takes function and arguments both or '
                            'lvalue and rvalue both')
        if (function is not None or arguments is not None) and \
           (lvalue is not None or rvalue is not None):
            raise TypeError('two available signatures (function, arguments) '
                            'and (lvalue, rvalue) are exclusive')
        if lvalue is not None:
            if rvalue is None:
                raise TypeError('rvalue is required')
            elif not (isinstance(lvalue, Attribute) or
                      isinstance(lvalue, Application) and
                      len(lvalue.arguments) == 1 and
                      isinstance(lvalue.arguments[0], StringLiteral)):
                raise TypeError('lvalue must be a kong.ast.Attribute or an '
                                'equivalent kong.ast.Application, not ' +
                                repr(lvalue))
            elif not isinstance(rvalue, Expression):
                raise TypeError('rvalue must be a kong.ast.Expression, not '
                                + repr(rvalue))
            function = lvalue.function
            arguments = lvalue.arguments[0], rvalue
        if len(arguments) != 2:
            raise TypeError('only two arguments are accepted')
        elif not isinstance(arguments[0], StringLiteral):
            raise TypeError('arguments[0] must be a kong.ast.StringLiteral, '
                            'not ' + repr(arguments[0]))
        Application.__init__(self, function, arguments)

    @property
    def lvalue(self):
        """(:class:`Attribute`) Lvalue attribute.

        .. sourcecode:: pycon

           >>> args = StringLiteral(u'attr'), StringLiteral(u'value')
           >>> set = AttributeDefinition(Identifier('obj'), args)
           >>> set.lvalue  # doctest: +NORMALIZE_WHITESPACE
           kong.ast.Attribute(kong.ast.Identifier(u'obj'),
                              attribute=kong.ast.Identifier(u'attr'))

        """
        return Attribute(self.function, self.arguments[:1])

    @property
    def rvalue(self):
        """(:class:`Expression`) Rvalue expression.

        .. sourcecode:: pycon

           >>> args = StringLiteral(u'attr'), StringLiteral(u'value')
           >>> set = AttributeDefinition(Identifier('obj'), args)
           >>> set.rvalue
           kong.ast.StringLiteral(u'value')

        """
        return self.arguments[1]

    def __eq__(self, operand):
        if isinstance(operand, Definition):
            return Definition.__eq__(self, operand)
        return Application.__eq__(self, operand)

    def __ne__(self, operand):
        return not (self == operand)


class Literal(Expression):
    """A literal node. It is an abstract class.

    .. productionlist::
       literal: `str_literal` | `dict_literal` | `func_def` | `list_literal`

    """


class ListLiteral(Literal, ExpressionList):
    """A list literal node.

    .. productionlist::
       list_literal: "[" (`expr` ",")* [`expr`] "]"

    :param expressions: :class:`Expression` list
    :type expressions: :class:`collections.Iterable`

    """

    def __unicode__(self):
        return u'[{0}]'.format(u', '.join(itertools.imap(unicode, self)))


class DictionaryLiteral(Literal):
    """A dictionary literal node.

    .. productionlist::
       dict_literal: "{" `program` "}"

    .. sourcecode:: pycon

       >>> prog = Program([
       ...     IdentifierLocalDefinition(Identifier('a'), StringLiteral(123)),
       ...     IdentifierLocalDefinition(Identifier('b'), StringLiteral(456))
       ... ])
       >>> d = DictionaryLiteral(prog)
       >>> print unicode(d)
       { a <- 123; b <- 456 }
       >>> print unicode(DictionaryLiteral([]))
       {}

    :param program: :class:`Expression` list
    :type program: :class:`Program`, :class:`ExpressionList`,
                   :class:`collections.Iterable`

    """

    __slots__ = 'program',

    def __init__(self, program):
        if not isinstance(program, collections.Iterable):
            raise TypeError('program must be iterable')
        elif not isinstance(program, Program):
            program = Program(program)
        self.program = program

    def __eq__(self, operand):
        return (isinstance(operand, type(self)) and
                self.program == operand.program)

    def __ne__(self, operand):
        return not (self == operand)

    def __unicode__(self):
        if self.program:
            blk = u'; '.join(itertools.imap(unicode, self.program))
            return u'{{ {0} }}'.format(blk)
        return u'{}'


class FunctionLiteral(Literal):
    """A function literal node.

    .. productionlist::
       func_def: "(" `params` ")" ":" `dict_literal`
       params: (`id` ",")* [`id`]

    .. sourcecode:: pycon

       >>> params = Identifier('a'), Identifier('b')
       >>> prog = Program([Operator(operator=Identifier('+'),
       ...                          operands=params)])
       >>> f = FunctionLiteral(params, prog)
       >>> print unicode(f)
       (a, b): { a + b }

    :param parameters: :class:`Identifier` list
    :type parameters: :class:`collections.Iterable`
    :param program: a program body :class:`Expression` list
    :type program: :class:`Program`, :class:`ExpressionList`,
                   :class:`collections.Iterable`

    """

    __slots__ = 'parameters', 'program'

    def __init__(self, parameters, program):
        if not isinstance(parameters, collections.Iterable):
            raise TypeError('parameters must be iterable')
        elif not isinstance(program, collections.Iterable):
            raise TypeError('program must be iterable')
        elif not isinstance(program, Program):
            program = Program(program)
        self.parameters = tuple(parameters)
        self.program = program

    def __eq__(self, operand):
        return (isinstance(operand, type(self)) and
                self.parameters == operand.parameters and
                self.program == operand.program)

    def __ne__(self, operand):
        return not (self == operand)

    def __unicode__(self):
        params = u', '.join(itertools.imap(unicode, self.parameters))
        blk = u'; '.join(itertools.imap(unicode, self.program))
        return u'({0}): {{ {1} }}'.format(params, blk)

    def __repr__(self):
        cls = type(self)
        args = (cls.__module__, cls.__name__,
                list(self.parameters), self.program)
        return '{0}.{1}({2!r}, program={3!r})'.format(*args)


class StringLiteral(Literal):
    """A string literal node.

    .. sourcecode:: pycon

       >>> s = StringLiteral(u'string literal')
       >>> s
       kong.ast.StringLiteral(u'string literal')
       >>> print unicode(s)
       "string literal"
       >>> n = StringLiteral(u'123')
       >>> n
       kong.ast.StringLiteral(123)
       >>> print unicode(n)
       123

    .. productionlist::
       str_literal: `number` | /"([^"]|\\.)*"/
       number: `digit`+
       digit: "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"

    :param string: a string
    :type string: :class:`unicode`, :class:`numbers.Integral`

    """

    __slots__ = 'string',

    def __init__(self, string):
        if isinstance(string, numbers.Integral):
            string = unicode(string)
        elif not isinstance(string, unicode):
            raise TypeError('string must be an unicode string or an integer, '
                            'not ' + repr(string))
        self.string = string if type(string) is unicode else unicode(string)

    def __eq__(self, operand):
        return (isinstance(operand, type(self)) and
                self.string == operand.string)

    def __ne__(self, operand):
        return not (self == operand)

    def __hash__(self):
        return hash(self.string)

    def __unicode__(self):
        if self.string.isdigit():
            return self.string
        s = u''.join(u'\\\\' if c == u'\\' else c for c in self.string)
        return u'"{0}"'.format(s)

    def __repr__(self):
        cls = type(self)
        s = self.string if self.string.isdigit() else repr(self.string)
        return '{0}.{1}({2})'.format(cls.__module__, cls.__name__, s)