#!/usr/bin/env python
#
# Copyright 2015, Corey Richardson
# Copyright 2014, NICTA
#
# This software may be distributed and modified according to the terms of
# the BSD 2-Clause license. Note that NO WARRANTY is provided.
# See "LICENSE_BSD2.txt" for details.
#
# @TAG(NICTA_BSD)
#

# seL4 System Call ID Generator
# ==============================

import argparse
import re
import sys
# install tempita using sudo apt-get install python-tempita or similar for your distro
import tempita
import xml.dom.minidom

common_header = """

/* This header was generated by kernel/tools/syscall_header_gen.py.
 *
 * To add a system call number, edit kernel/include/api/syscall.xml
 *
 */"""

libsel4_header_template = \
"""/* @LICENSE(NICTA) */""" + common_header + """
#[repr(isize)]
pub enum SyscallId {
{{py:syscall_number = -1}}
{{for config, list in enum}}
    {{for syscall in list}}
    {{if len(config) > 0}}
    #[cfg(feature = "SEL4_{{config}}")]
    {{endif}}
    {{syscall}} = {{syscall_number}},
    {{py:syscall_number -= 1}}
    {{endfor}}
{{endfor}}
}
"""

def parse_args():
    parser = argparse.ArgumentParser(description="""Generate seL4 syscall API constants
                                                    and associated header files""")
    parser.add_argument('--xml', type=argparse.FileType('r'),
            help='Name of xml file with syscall name definitions', required=True)
    parser.add_argument('--dest', type=argparse.FileType('w'),
            help='Name of file to generate for librustsel4', required=True)

    result = parser.parse_args()

    return result

def parse_syscall_list(element):
    syscalls = []
    for config in element.getElementsByTagName("config"):
        config_name = config.getAttribute("name")
        config_syscalls = []
        for syscall in config.getElementsByTagName("syscall"):
            name = str(syscall.getAttribute("name"))
            config_syscalls.append(name)
        syscalls.append((config_name, config_syscalls))

    # sanity check
    assert len(syscalls) != 0

    return syscalls


def parse_xml(xml_file):
    # first check if the file is valid xml
    try:
        doc = xml.dom.minidom.parse(xml_file)
    except:
        print >>sys.stderr, "Error: invalid xml file."
        sys.exit(-1)

    api = doc.getElementsByTagName("api")
    if len(api) != 1:
        print >>sys.stderr, "Error: malformed xml. Only one api element allowed"
        sys.exit(-1)

    configs = api[0].getElementsByTagName("config")
    if len(configs) != 1:
        print >>sys.stderr, "Error: api element only supports 1 config element"
        sys.exit(-1)

    if len(configs[0].getAttribute("name")) != 0:
        print >>sys.stderr, "Error: api element config only supports an empty name"
        sys.exit(-1)

    # debug elements are optional
    debug = doc.getElementsByTagName("debug")
    if len(debug) != 1:
        debug_element = None
    else:
        debug_element = debug[0]

    api_elements = parse_syscall_list(api[0])
    debug = parse_syscall_list(debug_element)

    return (api_elements, debug)

def generate_libsel4_file(libsel4_header, syscalls):

    tmpl = tempita.Template(libsel4_header_template)
    libsel4_header.write(tmpl.substitute(enum=syscalls))

if __name__ == "__main__":
    args = parse_args()

    (api, debug) = parse_xml(args.xml)
    args.xml.close()

    generate_libsel4_file(args.dest, api + debug)
    args.dest.close()
