File: macro_expander.py

package info (click to toggle)
pyparsing 3.1.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,928 kB
  • sloc: python: 25,633; ansic: 422; makefile: 22
file content (64 lines) | stat: -rw-r--r-- 1,813 bytes parent folder | download | duplicates (2)
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
# 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)