~radix/joybot/parsing-refactor

« back to all changes in this revision

Viewing changes to joybot/diceparser.py

  • Committer: Christopher Armstrong
  • Date: 2007-06-03 20:16:31 UTC
  • Revision ID: radix@twistedmatrix.com-20070603201631-fvr22vumdc4os15c
Move all parse specs from dice.py to diceparser.py! yay.
There's still something weird which uses joybot.parser.

Show diffs side-by-side

added added

removed removed

Lines of Context:
13
13
 
14
14
def parse(expr):
15
15
    expr = removeWhitespace(expr)
16
 
    p = parser.arithmetize(pyparsing.Or([t.spec for t in TOKEN_TYPES]))
 
16
    p = parser.arithmetize(pyparsing.Or(TOKEN_SPECS))
17
17
    p.setParseAction(lambda s, l, t: parser.infixToPrefix(t.asList()))
18
18
    p.setParseAction(lambda s, l, t: Combination.fromTree(t.asList()))
19
19
    try:
29
29
    return ''.join(expr.split())
30
30
 
31
31
 
32
 
TOKEN_TYPES = [Constant, SingleHighest, Highest, DiceGroup]
33
 
 
34
 
 
35
 
def parseSingle(cls, expr):
 
32
PositiveInteger = pyparsing.Word(pyparsing.nums)
 
33
PositiveInteger.setParseAction(lambda s, l, t: int(t[0]))
 
34
 
 
35
DiceGroupSpec = (
 
36
    pyparsing.Optional(PositiveInteger, default=1).setResultsName('numDice')
 
37
    + pyparsing.Literal('d').suppress()
 
38
    + PositiveInteger.setResultsName('dieType'))
 
39
DiceGroupSpec.setParseAction(
 
40
    lambda s, loc, toks: DiceGroup(toks.numDice, toks.dieType))
 
41
 
 
42
HighestSpec = (
 
43
    PositiveInteger.setResultsName('numDice')
 
44
    + pyparsing.Literal('d').suppress()
 
45
    + PositiveInteger.setResultsName('dieType')
 
46
    + pyparsing.Literal('[').suppress()
 
47
    + PositiveInteger.setResultsName('numHighest')
 
48
    + pyparsing.Literal(']').suppress())
 
49
HighestSpec.setParseAction(lambda s, l, t: Highest(*(t.asList())))
 
50
 
 
51
SingleHighestSpec = (
 
52
    PositiveInteger.setResultsName('numDice')
 
53
    + pyparsing.Literal('c').suppress()
 
54
    + PositiveInteger.setResultsName('dieType'))
 
55
SingleHighestSpec.setParseAction(
 
56
    lambda s, l, t: SingleHighest(t.numDice, t.dieType))
 
57
 
 
58
ConstantSpec = parser.Integer
 
59
 
 
60
TOKEN_SPECS = [DiceGroupSpec, HighestSpec, SingleHighestSpec, ConstantSpec]
 
61
 
 
62
 
 
63
def parseSingle(spec, expr):
36
64
    try:
37
 
        return cls.spec.parseString(expr)[0]
 
65
        return spec.parseString(expr)[0]
38
66
    except pyparsing.ParseException:
39
67
        raise BadDiceExpression("'%s' is not a valid dice expression" % (expr,))