This file is indexed.

/usr/lib/python2.7/dist-packages/cssutils/prodparser.py is in python-cssutils 1.0.2-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
# -*- coding: utf-8 -*-
"""Productions parser used by css and stylesheets classes to parse
test into a cssutils.util.Seq and at the same time retrieving
additional specific cssutils.util.Item objects for later use.

TODO:
    - ProdsParser
        - handle EOF or STOP?
        - handle unknown @rules
        - handle S: maybe save to Seq? parameterized?
        - store['_raw']: always?

    - Sequence:
        - opt first(), naive impl for now

"""
__all__ = ['ProdParser', 'Sequence', 'Choice', 'Prod', 'PreDef']
__docformat__ = 'restructuredtext'
__version__ = '$Id: parse.py 1418 2008-08-09 19:27:50Z cthedot $'

from helper import pushtoken
import cssutils
import itertools
import re
import string
import sys
import types


class ParseError(Exception):
    """Base Exception class for ProdParser (used internally)."""
    pass

class Done(ParseError):
    """Raised if Sequence or Choice is finished and no more Prods left."""
    pass

class Exhausted(ParseError):
    """Raised if Sequence or Choice is finished but token is given."""
    pass

class Missing(ParseError):
    """Raised if Sequence or Choice is not finished but no matching token given."""
    pass

class NoMatch(ParseError):
    """Raised if nothing in Sequence or Choice does match."""
    pass


class Choice(object):
    """A Choice of productions (Sequence or single Prod)."""

    def __init__(self, *prods, **options):
        """
        *prods
            Prod or Sequence objects
        options:
            optional=False
        """
        self._prods = prods

        try:
            self.optional = options['optional']
        except KeyError, e:
            for p in self._prods:
                if p.optional:
                    self.optional = True
                    break
            else:
                self.optional = False

        self.reset()

    def reset(self):
        """Start Choice from zero"""
        self._exhausted = False

    def matches(self, token):
        """Check if token matches"""
        for prod in self._prods:
            if prod.matches(token):
                return True
        return False

    def nextProd(self, token):
        """
        Return:

        - next matching Prod or Sequence
        - ``None`` if any Prod or Sequence is optional and no token matched
        - raise ParseError if nothing matches and all are mandatory
        - raise Exhausted if choice already done

        ``token`` may be None but this occurs when no tokens left."""
        #print u'TEST for %s in %s' % (token, self)
        if not self._exhausted:
            optional = False
            for p in self._prods:
                if p.matches(token):
                    self._exhausted = True
                    p.reset()
                    #print u'FOUND for %s: %s' % (token, p);#print
                    return p
                elif p.optional:
                    optional = True
            else:
                if not optional:
                    # None matched but also None is optional
                    raise NoMatch(u'No match for %s in %s' % (token, self))
                    #raise ParseError(u'No match in %s for %s' % (self, token))
        elif token:
            raise Exhausted(u'Extra token')

    def __repr__(self):
        return "<cssutils.prodsparser.%s object sequence=%r optional=%r at 0x%x>" % (
                self.__class__.__name__, self.__str__(), self.optional, id(self))

    def __str__(self):
        return u'Choice(%s)' % u', '.join([str(x) for x in self._prods])


class Sequence(object):
    """A Sequence of productions (Choice or single Prod)."""
    def __init__(self, *prods, **options):
        """
        *prods
            Prod or Choice or Sequence objects
        **options:
            minmax = lambda: (1, 1)
                callback returning number of times this sequence may run
        """
        self._prods = prods
        try:
            minmax = options['minmax']
        except KeyError:
            minmax = lambda: (1, 1)

        self._min, self._max = minmax()
        if self._max is None:
            # unlimited
            try:
                # py2.6/3
                self._max = sys.maxsize
            except AttributeError:
                # py<2.6
                self._max = sys.maxint

        self._prodcount = len(self._prods)
        self.reset()

    def matches(self, token):
        """Called by Choice to try to find if Sequence matches."""
        for prod in self._prods:
            if prod.matches(token):
                return True
            try:
                if not prod.optional:
                    break
            except AttributeError:
                pass
        return False

    def reset(self):
        """Reset this Sequence if it is nested."""
        self._roundstarted = False
        self._i = 0
        self._round = 0

    def _currentName(self):
        """Return current element of Sequence, used by name"""
        # TODO: current impl first only if 1st if an prod!
        for prod in self._prods[self._i:]:
            if not prod.optional:
                return str(prod)
        else:
            return 'Sequence'

    optional = property(lambda self: self._min == 0)

    def nextProd(self, token):
        """Return

        - next matching Prod or Choice
        - raises ParseError if nothing matches
        - raises Exhausted if sequence already done
        """
        #print u'TEST for %s in %s' % (token, self)
        while self._round < self._max:

            # for this round
            i = self._i
            round = self._round
            p = self._prods[i]
            if i == 0:
                self._roundstarted = False

            # for next round
            self._i += 1
            if self._i == self._prodcount:
                self._round += 1
                self._i = 0

            if p.matches(token):
                self._roundstarted = True
                # reset nested Choice or Prod to use from start
                p.reset()
                #print u'FOUND for %s: %s' % (token, p);#print
                return p

            elif p.optional:
                continue

            elif round < self._min or self._roundstarted: #or (round == 0 and self._min == 0):
                raise Missing(u'Missing token for production %s' % p)

            elif not token:
                if self._roundstarted:
                    raise Missing(u'Missing token for production %s' % p)
                else:
                    raise Done()

            else:
                raise NoMatch(u'No match for %s in %s' % (token, self))

        if token:
            raise Exhausted(u'Extra token')

    def __repr__(self):
        return "<cssutils.prodsparser.%s object sequence=%r optional=%r at 0x%x>" % (
                self.__class__.__name__, self.__str__(), self.optional, id(self))

    def __str__(self):
        return u'Sequence(%s)' % u', '.join([str(x) for x in self._prods])



class Prod(object):
    """Single Prod in Sequence or Choice."""
    def __init__(self, name, match, optional=False,
                 toSeq=None, toStore=None,
                 stop=False, stopAndKeep=False,
                 stopIfNoMoreMatch=False,
                 nextSor=False, mayEnd=False,
                 storeToken=None,
                 exception=None):
        """
        name
            name used for error reporting
        match callback
            function called with parameters tokentype and tokenvalue
            returning True, False or raising ParseError
        toSeq callback (optional) or False
            calling toSeq(token, tokens) returns (type_, val) == (token[0], token[1])
            to be appended to seq else simply unaltered (type_, val)

            if False nothing is added

        toStore (optional)
            key to save util.Item to store or callback(store, util.Item)
        optional = False
            whether Prod is optional or not
        stop = False
            if True stop parsing of tokens here
        stopAndKeep
            if True stop parsing of tokens here but return stopping
            token in unused tokens
        stopIfNoMoreMatch = False
            stop even if more tokens available, similar to stop and keep but with
            condition no more matches
        nextSor=False
            next is S or other like , or / (CSSValue)
        mayEnd = False
            no token must follow even defined by Sequence.
            Used for operator ',/ ' currently only

        storeToken = None
            if True toStore saves simple token tuple and not and Item object
            to store. Old style processing, TODO: resolve

        exception = None
            exception to be raised in case of error, normaly SyntaxErr
        """
        self._name = name
        self.match = match
        self.optional = optional
        self.stop = stop
        self.stopAndKeep = stopAndKeep
        self.stopIfNoMoreMatch = stopIfNoMoreMatch
        self.nextSor = nextSor
        self.mayEnd = mayEnd
        self.storeToken = storeToken
        self.exception = exception

        def makeToStore(key):
            "Return a function used by toStore."
            def toStore(store, item):
                "Set or append store item."
                if key in store:
                    _v = store[key]
                    if not isinstance(_v, list):
                        store[key] = [_v]
                    store[key].append(item)
                else:
                    store[key] = item
            return toStore

        if toSeq or toSeq is False:
            # called: seq.append(toSeq(value))
            self.toSeq = toSeq
        else:
            self.toSeq = lambda t, tokens: (t[0], t[1])

        if hasattr(toStore, '__call__'):
            self.toStore = toStore
        elif toStore:
            self.toStore = makeToStore(toStore)
        else:
            # always set!
            self.toStore = None

    def matches(self, token):
        """Return if token matches."""
        if not token:
            return False
        type_, val, line, col = token
        return self.match(type_, val)

    def reset(self):
        pass

    def __str__(self):
        return self._name

    def __repr__(self):
        return "<cssutils.prodsparser.%s object name=%r at 0x%x>" % (
                self.__class__.__name__, self._name, id(self))


# global tokenizer as there is only one!
tokenizer = cssutils.tokenize2.Tokenizer()

# global: saved from subProds
savedTokens = []


class ProdParser(object):
    """Productions parser."""
    def __init__(self, clear=True):
        self.types = cssutils.cssproductions.CSSProductions
        self._log = cssutils.log
        if clear:
            tokenizer.clear()
   
    def _texttotokens(self, text):
        """Build a generator which is the only thing that is parsed!
        old classes may use lists etc
        """
        if isinstance(text, basestring):
            # DEFAULT, to tokenize strip space
            return tokenizer.tokenize(text.strip())

        elif type(text) == types.GeneratorType:
            # DEFAULT, already tokenized, should be generator
            return text

        elif isinstance(text, tuple):
            # OLD: (token, tokens) or a single token
            if len(text) == 2:
                # (token, tokens)
                chain([token], tokens)
            else:
                # single token
                return iter([text])

        elif isinstance(text, list):
            # OLD: generator from list
            return iter(text)

        else:
            # ?
            return text

    def _SorTokens(self, tokens, until=',/'):
        """New tokens generator which has S tokens removed,
        if followed by anything in ``until``, normally a ``,``."""
        for token in tokens:
            if token[0] == self.types.S:
                try:
                    next_ = tokens.next()
                except StopIteration:
                    yield token
                else:
                    if next_[1] in until:
                        # omit S as e.g. ``,`` has been found
                        yield next_
                    elif next_[0] == self.types.COMMENT:
                        # pass COMMENT
                        yield next_
                    else:
                        yield token
                        yield next_

            elif token[0] == self.types.COMMENT:
                # pass COMMENT
                yield token
            else:
                yield token
                break
        # normal mode again
        for token in tokens:
            yield token


    def parse(self, text, name, productions, keepS=False, checkS=False, store=None,
              emptyOk=False, debug=False):
        """
        text (or token generator)
            to parse, will be tokenized if not a generator yet

            may be:
            - a string to be tokenized
            - a single token, a tuple
            - a tuple of (token, tokensGenerator)
            - already tokenized so a tokens generator

        name
            used for logging
        productions
            used to parse tokens
        keepS
            if WS should be added to Seq or just be ignored
        store  UPDATED
            If a Prod defines ``toStore`` the key defined there
            is a key in store to be set or if store[key] is a list
            the next Item is appended here.

            TODO: NEEDED? :
            Key ``raw`` is always added and holds all unprocessed
            values found
        emptyOk
            if True text may be empty, hard to test before as may be generator

        returns
            :wellformed: True or False
            :seq: a filled cssutils.util.Seq object which is NOT readonly yet
            :store: filled keys defined by Prod.toStore
            :unusedtokens: token generator containing tokens not used yet
        """
        tokens = self._texttotokens(text)

        if not tokens:
            self._log.error(u'No content to parse.')
            return False, [], None, None

        seq = cssutils.util.Seq(readonly=False)
        if not store: # store for specific values
            store = {}
        prods = [productions] # stack of productions
        wellformed = True
        # while no real token is found any S are ignored
        started = False
        stopall = False
        prod = None
        # flag if default S handling should be done
        defaultS = True

        stopIfNoMoreMatch = False
        stopIfNoMoreMatchNow = False

        while True:
            # get from savedTokens or normal tokens
            try:
                #print debug, "SAVED", savedTokens
                token = savedTokens.pop()
            except IndexError, e:
                try:
                    token = tokens.next()
                except StopIteration:
                    break

            #print debug, token, stopIfNoMoreMatch

            type_, val, line, col = token

            # default productions
            if type_ == self.types.COMMENT:
                # always append COMMENT
                seq.append(cssutils.css.CSSComment(val),
                           cssutils.css.CSSComment, line, col)

            elif defaultS and type_ == self.types.S and not checkS:
                # append S (but ignore starting ones)
                if not keepS or not started:
                    continue
                else:
                    seq.append(val, type_, line, col)

#            elif type_ == self.types.ATKEYWORD:
#                # @rule
#                r = cssutils.css.CSSUnknownRule(cssText=val)
#                seq.append(r, type(r), line, col)
            elif type_ == self.types.INVALID:
                # invalidate parse
                wellformed = False
                self._log.error(u'Invalid token: %r' % (token,))
                break

            elif type_ == 'EOF':
                # do nothing? (self.types.EOF == True!)
                stopall = True

            else:
                started = True # check S now
                nextSor = False # reset

                try:
                    while True:
                        # find next matching production
                        try:
                            prod = prods[-1].nextProd(token)
                        except (Exhausted, NoMatch), e:
                            # try next
                            prod = None

                        if isinstance(prod, Prod):
                            # found actual Prod, not a Choice or Sequence
                            break
                        elif prod:
                            # nested Sequence, Choice
                            prods.append(prod)
                        else:
                            # nested exhausted, try in parent
                            if len(prods) > 1:
                                prods.pop()
                            else:
                                raise NoMatch('No match')

                except NoMatch, e:
                    if stopIfNoMoreMatch: # and token:
                        #print "\t1stopIfNoMoreMatch", e, token, prod, 'PUSHING'
                        #tokenizer.push(token)
                        savedTokens.append(token)
                        stopIfNoMoreMatchNow = True
                        stopall = True

                    else:
                        wellformed = False
                        self._log.error(u'%s: %s: %r' % (name, e, token))
                    break

                except ParseError, e:
                    # needed???
                    if stopIfNoMoreMatch: # and token:
                        #print "\t2stopIfNoMoreMatch", e, token, prod
                        tokenizer.push(token)
                        stopIfNoMoreMatchNow = True
                        stopall = True

                    else:
                        wellformed = False
                        self._log.error(u'%s: %s: %r' % (name, e, token))
                    break

                else:
                    #print '\t1', debug, 'PROD', prod

                    # may stop next time, once set stays
                    stopIfNoMoreMatch = prod.stopIfNoMoreMatch or stopIfNoMoreMatch 

                    # process prod
                    if prod.toSeq and not prod.stopAndKeep:
                        type_, val = prod.toSeq(token, tokens)
                        if val is not None:
                            seq.append(val, type_, line, col)
                            if prod.toStore:
                                if not prod.storeToken:
                                    prod.toStore(store, seq[-1])
                                else:
                                    # workaround for now for old style token
                                    # parsing!
                                    # TODO: remove when all new style
                                    prod.toStore(store, token)

                    if prod.stop: 
                        # stop here and ignore following tokens
                        # EOF? or end of e.g. func ")"
                        break

                    if prod.stopAndKeep: # e.g. ;
                        # stop here and ignore following tokens
                        # but keep this token for next run
                        
                        # TODO: CHECK!!!!
                        tokenizer.push(token) 
                        tokens = itertools.chain(token, tokens)
                                               
                        stopall = True
                        break

                    if prod.nextSor:
                        # following is S or other token (e.g. ",")?
                        # remove S if
                        tokens = self._SorTokens(tokens, ',/')
                        defaultS = False
                    else:
                        defaultS = True
        
        lastprod = prod
        #print debug, 'parse done', token, stopall, '\n'
        if not stopall:
            # stop immediately

            while True:
                # all productions exhausted?
                try:
                    prod = prods[-1].nextProd(token=None)
                except Done, e:
                    # ok
                    prod = None

                except Missing, e:
                    prod = None
                    # last was a S operator which may End a Sequence, then ok
                    if hasattr(lastprod, 'mayEnd') and not lastprod.mayEnd:
                        wellformed = False
                        self._log.error(u'%s: %s' % (name, e))

                except ParseError, e:
                    prod = None
                    wellformed = False
                    self._log.error(u'%s: %s' % (name, e))

                else:
                    if prods[-1].optional:
                        prod = None
                    elif prod and prod.optional:
                        # ignore optional
                        continue

                if prod and not prod.optional:
                    wellformed = False
                    self._log.error(u'%s: Missing token for production %r'
                                    % (name, str(prod)))
                    break
                elif len(prods) > 1:
                    # nested exhausted, next in parent
                    prods.pop()
                else:
                    break

            if not emptyOk and not len(seq):
                self._log.error(u'No content to parse.')
                return False, [], None, None

        # trim S from end
        seq.rstrip()
        return wellformed, seq, store, tokens


class PreDef(object):
    """Predefined Prod definition for use in productions definition
    for ProdParser instances.
    """
    types = cssutils.cssproductions.CSSProductions
    reHexcolor = re.compile(r'^\#(?:[0-9abcdefABCDEF]{3}|[0-9abcdefABCDEF]{6})$')

    @staticmethod
    def calc(toSeq=None, nextSor=False):
        return Prod(name=u'calcfunction',
                    match=lambda t, v: u'calc(' == cssutils.helper.normalize(v),
                    toSeq=toSeq,
                    nextSor=nextSor)

    @staticmethod
    def char(name='char', char=u',', toSeq=None,
             stop=False, stopAndKeep=False, mayEnd=False, 
             stopIfNoMoreMatch=False,
             optional=False, # WAS: optional=True, 
             nextSor=False):
        "any CHAR"
        return Prod(name=name, match=lambda t, v: v == char, toSeq=toSeq,
                    stop=stop, stopAndKeep=stopAndKeep, mayEnd=mayEnd,
                    stopIfNoMoreMatch=stopIfNoMoreMatch,
                    optional=optional,
                    nextSor=nextSor)

    @staticmethod
    def comma(optional=False, toSeq=None):
        return PreDef.char(u'comma', u',', optional=optional, toSeq=toSeq)

    @staticmethod
    def comment(parent=None):
        return Prod(name=u'comment',
                    match=lambda t, v: t == 'COMMENT',
                    toSeq=lambda t, tokens: (t[0], cssutils.css.CSSComment([1], 
                                                                           parentRule=parent)),
                    optional=True
                    )


    @staticmethod
    def dimension(nextSor=False, stop=False):
        return Prod(name=u'dimension',
                    match=lambda t, v: t == PreDef.types.DIMENSION,
                    toSeq=lambda t, tokens: (t[0], cssutils.helper.normalize(t[1])),
                    stop=stop,
                    nextSor=nextSor)

    @staticmethod
    def function(toSeq=None, nextSor=False, toStore=None):
        return Prod(name=u'function',
                    match=lambda t, v: t == PreDef.types.FUNCTION,
                    toStore=toStore,
                    toSeq=toSeq,
                    nextSor=nextSor)

    @staticmethod
    def funcEnd(stop=False, mayEnd=False):
        ")"
        return PreDef.char(u'end FUNC ")"', u')', stop=stop, mayEnd=mayEnd)

    @staticmethod
    def hexcolor(stop=False, nextSor=False):
        "#123 or #123456"
        return Prod(name='HEX color',
                    match=lambda t, v: (
                        t == PreDef.types.HASH and
                        PreDef.reHexcolor.match(v)
                    ),
                    stop=stop,
                    nextSor=nextSor)

    @staticmethod
    def ident(stop=False, toStore=None, nextSor=False):
        return Prod(name=u'ident',
                    match=lambda t, v: t == PreDef.types.IDENT,
                    stop=stop,
                    toStore=toStore,
                    nextSor=nextSor)

    @staticmethod
    def number(stop=False, toSeq=None, nextSor=False):
        return Prod(name=u'number',
                    match=lambda t, v: t == PreDef.types.NUMBER,
                    stop=stop,
                    toSeq=toSeq,
                    nextSor=nextSor)

    @staticmethod
    def percentage(stop=False, toSeq=None, nextSor=False):
        return Prod(name=u'percentage',
                    match=lambda t, v: t == PreDef.types.PERCENTAGE,
                    stop=stop,
                    toSeq=toSeq,
                    nextSor=nextSor)

    @staticmethod
    def string(stop=False, nextSor=False):
        "string delimiters are removed by default"
        return Prod(name=u'string',
                    match=lambda t, v: t == PreDef.types.STRING,
                    toSeq=lambda t, tokens: (t[0], cssutils.helper.stringvalue(t[1])),
                    stop=stop,
                    nextSor=nextSor)

    @staticmethod
    def S(name=u'whitespace', toSeq=None, optional=False):
        return Prod(name=name,
                    match=lambda t, v: t == PreDef.types.S,
                    toSeq=toSeq,
                    optional=optional,
                    mayEnd=True)

    @staticmethod
    def unary(stop=False, toSeq=None, nextSor=False):
        "+ or -"
        return Prod(name=u'unary +-', match=lambda t, v: v in (u'+', u'-'),
                    optional=True,
                    stop=stop,
                    toSeq=toSeq,
                    nextSor=nextSor)

    @staticmethod
    def uri(stop=False, nextSor=False):
        "'url(' and ')' are removed and URI is stripped"
        return Prod(name=u'URI',
                    match=lambda t, v: t == PreDef.types.URI,
                    toSeq=lambda t, tokens: (t[0], cssutils.helper.urivalue(t[1])),
                    stop=stop,
                    nextSor=nextSor)

    @staticmethod
    def unicode_range(stop=False, nextSor=False):
        "u+123456-abc normalized to lower `u`"
        return Prod(name='unicode-range',
                    match=lambda t, v: t == PreDef.types.UNICODE_RANGE,
                    toSeq=lambda t, tokens: (t[0], t[1].lower()),
                    stop=stop,
                    nextSor=nextSor
                    )

    @staticmethod
    def variable(toSeq=None, stop=False, nextSor=False, toStore=None):
        return Prod(name=u'variable',
                    match=lambda t, v: u'var(' == cssutils.helper.normalize(v),
                    toSeq=toSeq,
                    toStore=toStore,
                    stop=stop,
                    nextSor=nextSor)

    # used for MarginRule for now:
    @staticmethod
    def unknownrule(name=u'@', toStore=None):
        """@rule dummy (matches ATKEYWORD to remove unknown rule tokens from
        stream::

            @x;
            @x {...}

        no nested yet!
        """
        def rule(tokens):
            saved = []
            for t in tokens:
                saved.append(t)
                if (t[1] == u'}' or t[1] == u';'):
                    return cssutils.css.CSSUnknownRule(saved)

        return Prod(name=name,
                    match=lambda t, v: t == u'ATKEYWORD',
                    toSeq=lambda t, tokens: (u'CSSUnknownRule',
                                             rule(pushtoken(t, tokens))
                                             ),
                    toStore=toStore
                    )