xref: /linux/tools/net/sunrpc/xdrgen/generators/enum.py (revision 9ad8d22f2f3fad7a366c9772362795ef6d6a2d51)
1#!/usr/bin/env python3
2# ex: set filetype=python:
3
4"""Generate code to handle XDR enum types"""
5
6from generators import SourceGenerator, create_jinja2_environment
7from xdr_ast import _XdrEnum, public_apis, big_endian, get_header_name
8
9
10class XdrEnumGenerator(SourceGenerator):
11    """Generate source code for XDR enum types"""
12
13    def __init__(self, language: str, peer: str):
14        """Initialize an instance of this class"""
15        self.environment = create_jinja2_environment(language, "enum")
16        self.peer = peer
17
18    def emit_declaration(self, node: _XdrEnum) -> None:
19        """Emit one declaration pair for an XDR enum type"""
20        if node.name in public_apis:
21            template = self.environment.get_template("declaration/enum.j2")
22            print(template.render(name=node.name))
23
24    def emit_definition(self, node: _XdrEnum) -> None:
25        """Emit one definition for an XDR enum type"""
26        template = self.environment.get_template("definition/open.j2")
27        print(template.render(name=node.name))
28
29        template = self.environment.get_template("definition/enumerator.j2")
30        for enumerator in node.enumerators:
31            print(template.render(name=enumerator.name, value=enumerator.value))
32
33        if node.name in big_endian:
34            template = self.environment.get_template("definition/close_be.j2")
35        else:
36            template = self.environment.get_template("definition/close.j2")
37        print(template.render(name=node.name))
38
39    def emit_decoder(self, node: _XdrEnum) -> None:
40        """Emit one decoder function for an XDR enum type"""
41        if node.name in big_endian:
42            template = self.environment.get_template("decoder/enum_be.j2")
43        else:
44            template = self.environment.get_template("decoder/enum.j2")
45        print(template.render(name=node.name))
46
47    def emit_encoder(self, node: _XdrEnum) -> None:
48        """Emit one encoder function for an XDR enum type"""
49        if node.name in big_endian:
50            template = self.environment.get_template("encoder/enum_be.j2")
51        else:
52            template = self.environment.get_template("encoder/enum.j2")
53        print(template.render(name=node.name))
54
55    def emit_maxsize(self, node: _XdrEnum) -> None:
56        """Emit one maxsize macro for an XDR enum type"""
57        macro_name = get_header_name().upper() + "_" + node.name + "_sz"
58        template = self.environment.get_template("maxsize/enum.j2")
59        print(
60            template.render(
61                macro=macro_name,
62                width=" + ".join(node.symbolic_width()),
63            )
64        )
65