summaryrefslogtreecommitdiff
path: root/examples/macroExpander.py
diff options
context:
space:
mode:
authorPaul McGuire <ptmcg@users.noreply.github.com>2018-01-06 23:38:53 -0600
committerGitHub <noreply@github.com>2018-01-06 23:38:53 -0600
commit430c5ad767cc946e9da7cd5f4673a4e3bd135a3c (patch)
tree5a7df11e0fd52ab320b0ef3e670e260f315ca9ae /examples/macroExpander.py
parentf1d12567a8da4d254e6d62bb0d650c87c7d0bb89 (diff)
parentd953150a6db3ac247a64b047edc2df7156f3e56b (diff)
downloadpyparsing-git-430c5ad767cc946e9da7cd5f4673a4e3bd135a3c.tar.gz
Merge pull request #1 from cngkaygusuz/master
Add Scrutinizer-CI configuration and other niceties
Diffstat (limited to 'examples/macroExpander.py')
-rw-r--r--examples/macroExpander.py60
1 files changed, 60 insertions, 0 deletions
diff --git a/examples/macroExpander.py b/examples/macroExpander.py
new file mode 100644
index 0000000..327976c
--- /dev/null
+++ b/examples/macroExpander.py
@@ -0,0 +1,60 @@
+# 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)