
/*
 * $Id: parsergen.c 44 2006-08-25 19:38:03Z kulibali $
 *
 * Copyright (c) 2006, The Narwhal Project 
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *    * Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 *    * Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 *    * Neither the name of the Narwhal Project nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "parsergen.h"
#include "peg_parser.h"
#include "internal.h"
#include "c_generator.h"

#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <wchar.h>
#include <errno.h>

/** \name Syntax Node Functions */
/*@{*/

syntax_node *syntax_node_create(int type, int begin, int end)
{
    syntax_node *res = (syntax_node *) calloc(1, sizeof(syntax_node));
    res->type  = type;
    res->begin = begin;
    res->end   = end;
    res->first_line = -1;
    res->last_line  = -1;
    res->children = 0;
    return res;
} /* syntax_node_create() */

syntax_node *syntax_node_copy(syntax_node *node)
{
    syntax_node *copy = 0, **cur;
    int i, len;

    if (node)
    {
        copy = syntax_node_create(node->type, node->begin, node->end);
        copy->begin = node->begin;
        copy->end = node->end;
        copy->first_line = node->first_line;
        copy->last_line = node->last_line;

        len = 0;
        if (node->children)
            for (cur = node->children; *cur; ++cur)
                ++len;

        if (len)
        {
            copy->children = (syntax_node **) calloc(len+1, sizeof(syntax_node *));

            for (i = 0; i < len; ++i)
                copy->children[i] = syntax_node_copy(node->children[i]);
        }
    }

    return copy;
} /* syntax_node_copy() */

void syntax_node_destroy(syntax_node *node)
{
    syntax_node **cur;

    assert(node);

    if (node->children)
        for (cur = node->children; *cur; ++cur)
            syntax_node_destroy(*cur);

    free(node);
} /* syntax_node_destroy() */


void syntax_node_traverse_inorder(syntax_node *root, void *data, syntax_node_process_ft process)
{
    if (root)
    {
        syntax_node **cur;

        if (process(root, data))
            return;

        if (root->children)
            for (cur = root->children; *cur; ++cur)
                syntax_node_traverse_inorder(*cur, data, process);
    }
} /* syntax_node_traverse_inorder() */

/*@}*/

/*************************************************/

/* \name Utilities for assigning line numbers to syntax tree nodes. */
/*@{*/

/** Goes through and finds the lengths of all the line endings in the input buffer (in bytes). */
static void find_line_endings(dynarray *end_offsets, input_buffer *ib, int start_pos)
{
    wchar_t ch, eol_pos = 0;
    int pos;

    input_buffer_setpos(ib, start_pos);

    do
    {
        ch = input_buffer_read_char(ib);

        if (ch == L'\n')
        {
            pos = input_buffer_getpos(ib);
            array_add(end_offsets, &pos);
            eol_pos = 0;
        }
        else if (ch == L'\r')
        {
            eol_pos = input_buffer_getpos(ib);
        }
        else
        {
            if (eol_pos > 0)
            {
                pos = eol_pos;
                array_add(end_offsets, &pos);
            }

            eol_pos = 0;
        }
    }
    while (ch != WEOF);

    pos = input_buffer_getpos(ib);
    array_add(end_offsets, &pos);
} /* find_line_lengths() */

/** Given a particular character offset, figures out which lines it's on. */
static int find_line(int pos, dynarray *line_endings)
{
    int n, i, len = array_size(line_endings);
    for (i = 0; i < len; ++i)
    {
        n = * (int *) array_item(line_endings, i);
        if (pos < n)
            return i+1;
    }

    if (pos == n)
        return len;
    else
        return -1;
} /* find_line() */

/** Assigns line numbers to the node.  The data parameter should be a pointer to the array of lines generated by find_line_endings(). */
static int assign_line_number(syntax_node *node, void *data)
{
    dynarray *line_endings = (dynarray *) data;

    if (node->begin >= node->end)
    {
        node->first_line = node->last_line = find_line(node->begin, line_endings);
    }
    else
    {
        node->first_line = find_line(node->begin, line_endings);
        node->last_line = find_line(node->end-1, line_endings);
    }

    return 0;
} /* assign_line_number() */

/** Assigns line numbers to a syntax tree. */
static void assign_line_numbers(input_buffer *ib, syntax_node *node, dynarray *line_endings)
{
    /* assign line numbers to the nodes */
    syntax_node_traverse_inorder(node, line_endings, assign_line_number);
} /* assign_line_numbers() */

/*@}*/

/** \name Error handling functions. */
/*@{*/

void add_error(dynarray *errs, int pos, wchar_t *str)
{
    error_rec rec;
    rec.pos = pos;
    rec.str = wcsdup(str);

    array_add(errs, &rec);
} /* add_error() */

void delete_errors(dynarray *errors, int start_index)
{
    int i, len = array_size(errors);
    for (i = start_index; i < len; ++i)
    {
        error_rec *rec = (error_rec *) array_item(errors, i);
        free(rec->str);
    }
    errors->num = start_index;
} /* add_error() */

static void print_errors(dynarray *errors, int num, input_buffer *ib, dynarray *lines)
{
    int i, len = array_size(errors);
    len = num < len ? num : len;

    for (i = 0; i < len; ++i)
    {
        error_rec *rec = (error_rec *) array_item(errors, i);
        int line = find_line(rec->pos, lines), line_pos = 0, caret_pos = 0, index = 0, i;
        dynarray error_line;
        wchar_t ch;

        fprintf(stderr, "%s:%d: error: %ls\n", ib->name, line, rec->str);
        fprintf(stderr, ">>> ");

        if (line > 1)
            line_pos = * (int *) array_item(lines, line-2);

        array_init(&error_line, sizeof(wchar_t), 0);
        input_buffer_setpos(ib, line_pos);
        ch = input_buffer_read_char(ib);
        while (ch != WEOF && ch != '\n' && ch != '\r')
        {
            array_add(&error_line, &ch);
            if (input_buffer_getpos(ib) == rec->pos)
                caret_pos = index;

            index++;
            ch = input_buffer_read_char(ib);
        }
        ch = 0;
        array_add(&error_line, &ch);

        fprintf(stderr, "%ls\n>>> ", (wchar_t *) error_line.data);
        for (i = 0; i < caret_pos+1; ++i)
        {
            fprintf(stderr, " ");
        }
        fprintf(stderr, "^\n");

        array_deinit(&error_line);
    }
} /* print_errors() */

/*@}*/

/*************************************************/

typedef struct _peg_options
{
    char *input_fname;
    char *output_prefix;
}
peg_options;

static void get_options(int argc, char **argv, peg_options *ops)
{
    char buf[128];

    if (argc == 2)
    {
        snprintf(buf, 128, "%s.peg", argv[1]);
        ops->input_fname = strdup(buf);

        snprintf(buf, 128, "%s", argv[1]);
        ops->output_prefix = strdup(buf);
    }
    else
    {
        fprintf(stderr, "usage: parsergen file_prefix\n");
        exit(1);
    }
} /* get_options() */

static int open_file(char *fname, char *mode, FILE **file)
{
    assert(fname);
    assert(mode);
    assert(file);

    *file = fopen(fname, mode);

    if (!*file)
    {
        fprintf(stderr, "unable to open %s: %s\n", fname, strerror(errno));
        return 0;
    }
    else
    {
        return 1;
    }
} /* open_file() */

#define BUF_LEN 128

int main(int argc, char **argv)
{
    peg_options ops;
    FILE *input_file = 0;
    input_buffer *ib;
    dynarray errors, line_endings, rule_records;
    syntax_node *parsed_spec;
    int i, len, res = 0;
    wchar_t buf[BUF_LEN];

    /* get options and open files */
    get_options(argc, argv, &ops);

    if (!open_file(ops.input_fname, "r", &input_file))
    {
        res = 1;
        goto cleanup_files;
    }

    /* parse specification file */
    ib = input_buffer_create(ops.input_fname, input_file);
    array_init(&errors, sizeof(error_rec), 0);
    array_init(&line_endings, sizeof(int), 0);

    parsed_spec = parse_peg_spec(ib, &errors);
    find_line_endings(&line_endings, ib, parsed_spec ? parsed_spec->begin : 0);

    if (!parsed_spec)
    {
        print_errors(&errors, 1, ib, &line_endings);
        res = 1;
        goto cleanup_parse;
    }

    assign_line_numbers(ib, parsed_spec, &line_endings);
    //syntax_node_print(ib, parsed_spec, 0);

    /* assemble internal representation */
    array_init(&rule_records, sizeof(rule_rec *), 0);
    get_internal_representation(parsed_spec, ib, &rule_records, &line_endings, &errors);

    if (array_size(&errors))
    {
        print_errors(&errors, 1, ib, &line_endings);
        res = 1;
        goto cleanup_rules;
    }

    print_rules(&rule_records);

    /* generate C parser */
    if (1)
    {
        char obuf[128], *header_fname = 0, *src_fname = 0;
        FILE *header_file = 0, *src_file = 0;

        snprintf(obuf, 128, "%s.h", ops.output_prefix);
        header_fname = strdup(obuf);

        if (!open_file(header_fname, "w", &header_file))
        {
            res = 1;
            goto cleanup_outputs;
        }

        snprintf(obuf, 128, "%s.c", ops.output_prefix);
        src_fname = strdup(obuf);

        if (!open_file(src_fname, "w", &src_file))
        {
            res = 1;
            goto cleanup_outputs;
        }

        swprintf(buf, BUF_LEN, L"%hs", ops.output_prefix);
        generate_c_parser(buf, header_fname, header_file, src_fname, src_file, &rule_records, ib, &line_endings);

        /* clean up */
cleanup_outputs:
        free(header_fname);
        free(src_fname);

        if (header_file)
            fclose(header_file);
        if (src_file)
            fclose(src_file);
    }

cleanup_rules:    
    len = array_size(&rule_records);
    for (i = 0; i < len; ++i)
        cleanup_rule(*(rule_rec **) array_item(&rule_records, i));
    array_deinit(&rule_records);

cleanup_parse:
    array_deinit(&line_endings);
    
    delete_errors(&errors, 0);
    array_deinit(&errors);

    if (parsed_spec)
        syntax_node_destroy(parsed_spec);

    if (ib)
        input_buffer_destroy(ib);

cleanup_files:
    if (input_file)
        fclose(input_file);

    free(ops.input_fname);
    free(ops.output_prefix);

    return res;
}
