/* byte-comp.c: -*- C -*-  DESCRIPTIVE TEXT. */

/*  Copyright (c) 1996 Universal Access Inc.
    Author: E. B. Gamble Jr. (ebg@ai.mit.edu) Thu Oct 10 23:40:06 1996.  */

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <assert.h>

#include "compile.h"

void
fail (void) 
{
  abort ();
}

#if defined (WITH_METAHTML) 

/* Metahtml specific */
#include <bprintf/bprintf.h>
#include <xmalloc/xmalloc.h>
#include "pages.h"
#include "symbols.h"
#include "forms.h"
#include "pagefuncs.h"

static void pf_compile (PFunArgs);

PFunDesc compiler_func_table[] = {
  { "COMPILE",	         0, 0, pf_compile },
  { (char *) NULL,	 0, 0, (PFunHandler *) NULL }
};

PACKAGE_INITIALIZER (initialize_compiler_functions)

void
initialize_compiler_functions (Package *package)
{
  register int i;
  Symbol *sym;

  extern void bc_parse_install (void);
  
  bc_expand_install ();
  bc_parse_install ();
  
  for (i = 0; compiler_func_table[i].tag != (char *)NULL; i++)
    {
      sym = symbol_intern_in_package (package, compiler_func_table[i].tag);
      sym->type = symtype_FUNCTION;
      sym->values = (char **)(& compiler_func_table[i]);
    }
}


static void
pf_compile (PFunArgs)
{
  char *string = get_positional_arg (vars, i);
  
  bc_parse_t    parse;
  bc_core_t     core;
  bc_function_t func;
  bc_object_t   object;

  parse = bc_parse (string);
  printf ("\n\nParse of %s:\n", string);
  bc_parse_show (parse);

  core = bc_expand (parse, bc_current_package);
  core = bc_optimize (core);
  printf ("\n\nCore of %s:\n", name);
  bc_core_show (core);

  func = bc_generate (core, "TOP-LEVEL");
  bc_function_disassemble (func, (FILE *) NULL);

  object = bc_welcome_to_the_machine (func);
  printf ("\n\nResult of %s:\n", (char *) object);

  bprintf_insert (page, start, "%s", (char *) object);
  *newstart = start = strlen ((char *)object);
}

#endif /* defined (WITH_METAHTML) */

/*************************************************************************
 *
 *  COMPILE
 *
 *
 */
bc_function_t 
bc_compile (bc_string_t string)
{
  bc_parse_t    parse;
  bc_core_t     core;
  bc_function_t func;

  /* Decide what is destructive and where to 'free' */

  parse = bc_parse (string);

  core = bc_expand (parse, bc_current_package);

  core = bc_optimize (core);

  func = bc_generate (core, "TOP-LEVEL");

  return (func);
}

