File: values.py

package info (click to toggle)
python-enable 4.3.0-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 7,280 kB
  • ctags: 13,899
  • sloc: cpp: 48,447; python: 28,502; ansic: 9,004; makefile: 315; sh: 44
file content (45 lines) | stat: -rw-r--r-- 1,325 bytes parent folder | download | duplicates (3)
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
"""
Parser for various kinds of CSS values as per CSS2 spec section 4.3
"""
from pyparsing import Word, Combine, Optional, Literal, oneOf, CaselessLiteral, StringEnd, OneOrMore

def asInt(s,l,t):
    return int(t[0])

def asFloat(s,l,t):
    return float(t[0])

def asFloatOrInt(s,l,t):
    """ Return an int if possible, otherwise a float"""
    v = t[0]
    try:
        return int(v)
    except ValueError:
        return float(v)

integer = Word("0123456789").setParseAction(asInt)

number = Combine(
    Optional(Word("0123456789")) + Literal(".") + Word("01234567890")
    | integer
)
number.setName('number')


sign = oneOf("+ -")

signedNumber = Combine(Optional(sign) + number).setParseAction(asFloat)

lengthValue = Combine(Optional(sign) + number).setParseAction(asFloatOrInt)
lengthValue.setName('lengthValue')


lengthUnit = oneOf(['em', 'ex', 'px', 'pt', 'in', 'cm', 'mm', 'pc', '%'], caseless=True)
#the spec says that the unit is only optional for a 0 length, but
#there are just too many places where a default is permitted.
#TODO: Maybe should use a ctor like optional to let clients declare it?
length = lengthValue + Optional(lengthUnit, default=None) + StringEnd()
length.leaveWhitespace()

#set the parse action aftward so it doesn't "infect" the parsers that build on it
number.setParseAction(asFloat)