#!/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 Invocation ID Generator
# ============================

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

COMMON_HEADER = """
/* @LICENSE(NICTA) */

/* This header was generated by kernel/tools/invocation_header_gen.py.
 *
 * To add an invocation call number, edit libsel4/include/interfaces/sel4.xml.
 *
 */"""

INVOCATION_TEMPLATE = COMMON_HEADER + """
#[repr(C)]
pub enum InvocationLabel {
    InvalidInvocation = 0,
    {{for loop, label in looper(invocations)}}
    {{label}} = {{loop.index+1}},
    {{endfor}}
}
"""

def parse_args():
    parser = argparse.ArgumentParser(description='Generate seL4 invocation API \
        constants and header files')
    parser.add_argument('--dest', type=argparse.FileType('w'),
            help='Name of file to create', required=True)
    parser.add_argument('files', nargs='+', help='XML files to parse invocations from')

    return parser.parse_args()

def parse_xml(xml_file):
    try:
        doc = xml.dom.minidom.parse(xml_file)
    except:
        print >> sys.stderr, "Error: invalid xml file"
        sys.exit(-1)

    invocation_labels = []
    for method in doc.getElementsByTagName("method"):
        invocation_labels.append(str(method.getAttribute("id")))

    return invocation_labels

def generate(args, invocations):

    header_title = "LIBRUSTSEL4"

    template = tempita.Template(INVOCATION_TEMPLATE)

    args.dest.write(template.substitute(header_title=header_title,
        invocations=invocations))

    args.dest.close()

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

    invocations = chain.from_iterable(parse_xml(xml) for xml in args.files)

    generate(args, invocations)

