1#!/usr/bin/env python3 2# ex: set filetype=python: 3 4"""Translate an XDR specification into executable code that 5can be compiled for the Linux kernel.""" 6 7import logging 8 9from argparse import Namespace 10from lark import logger 11from lark.exceptions import UnexpectedInput 12 13from generators.constant import XdrConstantGenerator 14from generators.enum import XdrEnumGenerator 15from generators.header_bottom import XdrHeaderBottomGenerator 16from generators.header_top import XdrHeaderTopGenerator 17from generators.pointer import XdrPointerGenerator 18from generators.program import XdrProgramGenerator 19from generators.typedef import XdrTypedefGenerator 20from generators.struct import XdrStructGenerator 21from generators.union import XdrUnionGenerator 22 23from xdr_ast import transform_parse_tree, _RpcProgram, Specification 24from xdr_ast import _XdrConstant, _XdrEnum, _XdrPointer 25from xdr_ast import _XdrTypedef, _XdrStruct, _XdrUnion 26from xdr_parse import xdr_parser, set_xdr_annotate 27 28logger.setLevel(logging.INFO) 29 30 31def emit_header_declarations( 32 root: Specification, language: str, peer: str 33) -> None: 34 """Emit header declarations""" 35 for definition in root.definitions: 36 if isinstance(definition.value, _XdrEnum): 37 gen = XdrEnumGenerator(language, peer) 38 elif isinstance(definition.value, _XdrPointer): 39 gen = XdrPointerGenerator(language, peer) 40 elif isinstance(definition.value, _XdrTypedef): 41 gen = XdrTypedefGenerator(language, peer) 42 elif isinstance(definition.value, _XdrStruct): 43 gen = XdrStructGenerator(language, peer) 44 elif isinstance(definition.value, _XdrUnion): 45 gen = XdrUnionGenerator(language, peer) 46 elif isinstance(definition.value, _RpcProgram): 47 gen = XdrProgramGenerator(language, peer) 48 else: 49 continue 50 gen.emit_declaration(definition.value) 51 52 53def handle_parse_error(e: UnexpectedInput) -> bool: 54 """Simple parse error reporting, no recovery attempted""" 55 print(e) 56 return True 57 58 59def subcmd(args: Namespace) -> int: 60 """Generate definitions and declarations""" 61 62 set_xdr_annotate(args.annotate) 63 parser = xdr_parser() 64 with open(args.filename, encoding="utf-8") as f: 65 parse_tree = parser.parse(f.read(), on_error=handle_parse_error) 66 ast = transform_parse_tree(parse_tree) 67 68 gen = XdrHeaderTopGenerator(args.language, args.peer) 69 gen.emit_declaration(args.filename, ast) 70 71 emit_header_declarations(ast, args.language, args.peer) 72 73 gen = XdrHeaderBottomGenerator(args.language, args.peer) 74 gen.emit_declaration(args.filename, ast) 75 76 return 0 77