Skip to content

Commit

Permalink
More example updates, PEP-8 names, f-strings.
Browse files Browse the repository at this point in the history
  • Loading branch information
ptmcg committed Jun 3, 2023
1 parent 85c2ef1 commit 40babe0
Show file tree
Hide file tree
Showing 6 changed files with 172 additions and 167 deletions.
12 changes: 6 additions & 6 deletions examples/bf.py
Expand Up @@ -98,27 +98,27 @@ def execute(self, bf_engine: BFEngine):


class DecrPtr(Instruction):
def execute(self, bf_engine):
def execute(self, bf_engine: BFEngine):
bf_engine.ptr -= 1


class IncrPtrValue(Instruction):
def execute(self, bf_engine):
def execute(self, bf_engine: BFEngine):
bf_engine.at_ptr += 1


class DecrPtrValue(Instruction):
def execute(self, bf_engine):
def execute(self, bf_engine: BFEngine):
bf_engine.at_ptr -= 1


class OutputPtrValue(Instruction):
def execute(self, bf_engine):
def execute(self, bf_engine: BFEngine):
bf_engine.output_value_at_ptr()


class InputPtrValue(Instruction):
def execute(self, bf_engine):
def execute(self, bf_engine: BFEngine):
bf_engine.input_value()


Expand All @@ -127,7 +127,7 @@ def __init__(self, tokens):
super().__init__(tokens)
self.instructions = self.tokens[0][1:-1]

def execute(self, bf_engine):
def execute(self, bf_engine: BFEngine):
while bf_engine.at_ptr:
for i in self.instructions:
i.execute(bf_engine)
Expand Down
60 changes: 30 additions & 30 deletions examples/excel_expr.py
Expand Up @@ -7,32 +7,32 @@
import pyparsing as pp
ppc = pp.common

pp.ParserElement.enablePackrat()
pp.ParserElement.enable_packrat()

EQ, LPAR, RPAR, COLON, COMMA = pp.Suppress.using_each("=():,")
EXCL, DOLLAR = pp.Literal.using_each("!$")
sheetRef = pp.Word(pp.alphas, pp.alphanums) | pp.QuotedString("'", escQuote="''")
colRef = pp.Opt(DOLLAR) + pp.Word(pp.alphas, max=2)
rowRef = pp.Opt(DOLLAR) + pp.Word(pp.nums)
cellRef = pp.Combine(
pp.Group(pp.Opt(sheetRef + EXCL)("sheet") + colRef("col") + rowRef("row"))
sheet_ref = pp.Word(pp.alphas, pp.alphanums) | pp.QuotedString("'", escQuote="''")
col_ref = pp.Opt(DOLLAR) + pp.Word(pp.alphas, max=2)
row_ref = pp.Opt(DOLLAR) + pp.Word(pp.nums)
cell_ref = pp.Combine(
pp.Group(pp.Opt(sheet_ref + EXCL)("sheet") + col_ref("col") + row_ref("row"))
)

cellRange = (
pp.Group(cellRef("start") + COLON + cellRef("end"))("range")
| cellRef
| pp.Word(pp.alphas, pp.alphanums)
cell_range = (
pp.Group(cell_ref("start") + COLON + cell_ref("end"))("range")
| cell_ref
| pp.Word(pp.alphas, pp.alphanums)
)

expr = pp.Forward()

COMPARISON_OP = pp.one_of("< = > >= <= != <>")
condExpr = expr + COMPARISON_OP + expr
cond_expr = expr + COMPARISON_OP + expr

ifFunc = (
if_func = (
pp.CaselessKeyword("if")
- LPAR
+ pp.Group(condExpr)("condition")
+ pp.Group(cond_expr)("condition")
+ COMMA
+ pp.Group(expr)("if_true")
+ COMMA
Expand All @@ -45,33 +45,33 @@ def stat_function(name):
return pp.Group(pp.CaselessKeyword(name) + pp.Group(LPAR + pp.DelimitedList(expr) + RPAR))


sumFunc = stat_function("sum")
minFunc = stat_function("min")
maxFunc = stat_function("max")
aveFunc = stat_function("ave")
funcCall = ifFunc | sumFunc | minFunc | maxFunc | aveFunc
sum_func = stat_function("sum")
min_func = stat_function("min")
max_func = stat_function("max")
ave_func = stat_function("ave")
func_call = if_func | sum_func | min_func | max_func | ave_func

multOp = pp.one_of("* /")
addOp = pp.one_of("+ -")
numericLiteral = ppc.number
operand = numericLiteral | funcCall | cellRange | cellRef
arithExpr = pp.infix_notation(
mult_op = pp.one_of("* /")
add_op = pp.one_of("+ -")
numeric_literal = ppc.number
operand = numeric_literal | func_call | cell_range | cell_ref
arith_expr = pp.infix_notation(
operand,
[
(multOp, 2, pp.OpAssoc.LEFT),
(addOp, 2, pp.OpAssoc.LEFT),
(mult_op, 2, pp.OpAssoc.LEFT),
(add_op, 2, pp.OpAssoc.LEFT),
],
)

textOperand = pp.dblQuotedString | cellRef
textExpr = pp.infix_notation(
textOperand,
text_operand = pp.dbl_quoted_string | cell_ref
text_expr = pp.infix_notation(
text_operand,
[
("&", 2, pp.OpAssoc.LEFT),
],
)

expr <<= arithExpr | textExpr
expr <<= arith_expr | text_expr


def main():
Expand All @@ -90,4 +90,4 @@ def main():


if __name__ == '__main__':
main()
main()
56 changes: 0 additions & 56 deletions examples/linenoExample.py

This file was deleted.

56 changes: 56 additions & 0 deletions examples/lineno_example.py
@@ -0,0 +1,56 @@
#
# lineno_example.py
#
# an example of using the location value returned by pyparsing to
# extract the line and column number of the location of the matched text,
# or to extract the entire line of text.
#
# Copyright (c) 2006, Paul McGuire
#
import pyparsing as pp

data = """Now is the time
for all good men
to come to the aid
of their country."""


# demonstrate use of lineno, line, and col in a parse action
def report_long_words(st, locn, toks):
word = toks[0]
if len(word) > 3:
print(
f"Found {word!r} on line {pp.lineno(locn, st)} at column {pp.col(locn, st)}"
)
print("The full line of text was:")
print(f"{pp.line(locn, st)!r}")
print(f" {'^':>{pp.col(locn, st)}}")
print()


wd = pp.Word(pp.alphas).set_parse_action(report_long_words)
wd[1, ...].parse_string(data)


# demonstrate returning an object from a parse action, containing more information
# than just the matching token text
class Token:
def __init__(self, st, locn, tok_string):
self.token_string = tok_string
self.locn = locn
self.source_line = pp.line(locn, st)
self.line_no = pp.lineno(locn, st)
self.col = pp.col(locn, st)

def __str__(self):
return f"{self.token_string!r} (line: {self.line_no}, col: {self.col})"


def create_token_object(st, locn, toks):
return Token(st, locn, toks[0])


wd = pp.Word(pp.alphas).set_parse_action(create_token_object)

for token_obj in wd[1, ...].parse_string(data):
print(token_obj)
125 changes: 64 additions & 61 deletions examples/macroExpander.py → examples/macro_expander.py
@@ -1,61 +1,64 @@
# macroExpander.py
#
# Example pyparsing program for performing macro expansion, similar to
# the C pre-processor. This program is not as fully-featured, simply
# processing macros of the form:
# #def xxx yyyyy
# and replacing xxx with yyyyy in the rest of the input string. Macros
# can also be composed using other macros, such as
# #def zzz xxx+1
# Since xxx was previously defined as yyyyy, then zzz will be replaced
# with yyyyy+1.
#
# Copyright 2007 by Paul McGuire
#
from pyparsing import *

# define the structure of a macro definition (the empty term is used
# to advance to the next non-whitespace character)
identifier = Word(alphas + "_", alphanums + "_")
macroDef = "#def" + identifier("macro") + empty + restOfLine("value")

# define a placeholder for defined macros - initially nothing
macroExpr = Forward()
macroExpr << NoMatch()

# global dictionary for macro definitions
macros = {}

# parse action for macro definitions
def processMacroDefn(s, l, t):
macroVal = macroExpander.transformString(t.value)
macros[t.macro] = macroVal
macroExpr << MatchFirst(map(Keyword, macros.keys()))
return "#def " + t.macro + " " + macroVal


# parse action to replace macro references with their respective definition
def processMacroRef(s, l, t):
return macros[t[0]]


# attach parse actions to expressions
macroExpr.setParseAction(processMacroRef)
macroDef.setParseAction(processMacroDefn)

# define pattern for scanning through the input string
macroExpander = macroExpr | macroDef


# test macro substitution using transformString
testString = """
#def A 100
#def ALEN A+1
char Astring[ALEN];
char AA[A];
typedef char[ALEN] Acharbuf;
"""

print(macroExpander.transformString(testString))
print(macros)
# macro_expander.py
#
# Example pyparsing program for performing macro expansion, similar to
# the C pre-processor. This program is not as fully-featured, simply
# processing macros of the form:
# #def xxx yyyyy
# and replacing xxx with yyyyy in the rest of the input string. Macros
# can also be composed using other macros, such as
# #def zzz xxx+1
# Since xxx was previously defined as yyyyy, then zzz will be replaced
# with yyyyy+1.
#
# Copyright 2007, 2023 by Paul McGuire
#
import pyparsing as pp

# define the structure of a macro definition (the empty term is used
# to advance to the next non-whitespace character)
identifier = pp.common.identifier
macro_def = "#def" + identifier("macro") + pp.empty + pp.restOfLine("value")

# define a placeholder for defined macros - initially nothing
macro_expr = pp.Forward()
macro_expr << pp.NoMatch()

# global dictionary for macro definitions
macros = {}


# parse action for macro definitions
def process_macro_defn(t):
macro_val = macro_expander.transform_string(t.value)
macros[t.macro] = macro_val
macro_expr << pp.MatchFirst(map(pp.Keyword, macros))
return f"#def {t.macro} {macro_val}"


# parse action to replace macro references with their respective definition
def process_macro_ref(t):
return macros[t[0]]


# attach parse actions to expressions
macro_expr.set_parse_action(process_macro_ref)
macro_def.set_parse_action(process_macro_defn)

# define pattern for scanning through the input string
macro_expander = macro_expr | macro_def


# test macro substitution using transformString
test_string = """
#def A 100
#def ALEN A+1
char Astring[ALEN];
char AA[A];
typedef char[ALEN] Acharbuf;
"""

print(test_string)
print("-" * 40)
print(macro_expander.transform_string(test_string))
print(macros)

0 comments on commit 40babe0

Please sign in to comment.