1 # Licensed under the Apache License, Version 2.0 (the "License");
2 # you may not use this file except in compliance with the License.
3 # You may obtain a copy of the License at:
5 # http://www.apache.org/licenses/LICENSE-2.0
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS,
9 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 # See the License for the specific language governing permissions and
11 # limitations under the License.
13 import cgi, pyparsing as pp
15 # Some useful primitives
16 ident = pp.Word(pp.alphas + "_", pp.alphas + pp.nums + "_")
17 intNum = pp.Word(pp.nums)
18 hexNum = pp.Literal("0x") + pp.Word(pp.hexnums)
19 octalNum = pp.Literal("0") + pp.Word("01234567")
20 integer = (hexNum | octalNum | intNum) + \
21 pp.Optional(pp.Literal("ULL") | pp.Literal("LL") | pp.Literal("L"))
22 floatNum = pp.Regex(r'\d+(\.\d*)?([eE]\d+)?') + pp.Optional(pp.Literal("f"))
23 char = pp.Literal("'") + pp.Word(pp.printables, exact=1) + pp.Literal("'")
24 arrayIndex = integer | ident
26 lbracket = pp.Literal("(").suppress()
27 rbracket = pp.Literal(")").suppress()
28 lbrace = pp.Literal("{").suppress()
29 rbrace = pp.Literal("}").suppress()
30 comma = pp.Literal(",").suppress()
31 equals = pp.Literal("=").suppress()
32 dot = pp.Literal(".").suppress()
33 semicolon = pp.Literal(";").suppress()
35 # initializer := { [member = ] (variable | expression | { initializer } ) }
38 typeSpec = pp.Optional("unsigned") + \
39 pp.oneOf("int long short float double char u8 i8 void") + \
40 pp.Optional(pp.Word("*"), default="")
41 typeCast = pp.Combine( "(" + ( typeSpec | typeName ) + ")" ).suppress()
43 string = pp.Combine(pp.OneOrMore(pp.QuotedString(quoteChar='"',
44 escChar='\\', multiline=True)), adjacent=False)
45 literal = pp.Optional(typeCast) + (integer | floatNum | char | string)
46 var = pp.Combine(pp.Optional(typeCast) + varName +
47 pp.Optional("[" + arrayIndex + "]"))
49 # This could be more complete, but suffices for our uses
50 expr = (literal | var)
52 """Parse and render a block of text into a Python dictionary."""
54 """Compiled PyParsing BNF"""
58 super(Parser, self).__init__()
59 self._parser = self.BNF()
62 raise NotImplementedError
65 raise NotImplementedError
67 def parse(self, input):
68 item = self._parser.parseString(input).asList()
69 return self.item(item)
72 """Parser for function-like macros - without the closing semi-colon."""
73 class ParserFunctionMacro(Parser):
75 # VLIB_CONFIG_FUNCTION (unix_config, "unix")
77 params = pp.Group(pp.ZeroOrMore(expr + comma) + expr)
78 macroParams = lbracket + params + rbracket
80 return macroName + macroParams
86 "function": item[1][0],
92 """Parser for function-like macros with a closing semi-colon."""
93 class ParseFunctionMacroStmt(ParserFunctionMacro):
95 # VLIB_CONFIG_FUNCTION (unix_config, "unix");
96 function_macro = super(ParseFunctionMacroStmt, self).BNF()
97 mi = function_macro + semicolon
98 mi.ignore(pp.cppStyleComment)
104 Parser for our struct initializers which are composed from a
105 function-like macro, equals sign, and then a normal C struct initalizer
108 class MacroInitializer(ParserFunctionMacro):
110 # VLIB_CLI_COMMAND (show_sr_tunnel_command, static) = {
111 # .path = "show sr tunnel",
112 # .short_help = "show sr tunnel [name <sr-tunnel-name>]",
113 # .function = show_sr_tunnel_fn,
118 member = pp.Combine(dot + varName + pp.Optional("[" + arrayIndex + "]"),
122 entry = pp.Group(pp.Optional(member + equals, default="") + value)
123 entries = (pp.ZeroOrMore(entry + comma) + entry + pp.Optional(comma)) | \
124 (pp.ZeroOrMore(entry + comma))
126 cs << (lbrace + entries + rbrace)
129 params = pp.Group(pp.ZeroOrMore(expr + comma) + expr)
130 macroParams = lbracket + params + rbracket
132 function_macro = super(MacroInitializer, self).BNF()
133 mi = function_macro + equals + pp.Group(cs) + semicolon
134 mi.ignore(pp.cppStyleComment)
138 def item(self, item):
146 for param in item[2]:
147 r["value"][param[0]] = cgi.escape(param[1])