/********************************************************************
   Program :  Recursive Descent Compiler for PL/0
   Module  :  PL0CODE - Intermediate code generator
   File    :  pl0code.c
   Compiler:  Borland C 3.1 - 4.5, GNU C 2.7.1
   Author  :  H. Weber
   Revision:  Aug. 1998
********************************************************************/

#include <stdio.h>
#include "pl0code.h"
#define  codemax 5000         /* maximum size of code array */


extern FILE *intcode;

char *codemnemo[] = {
        "NUL",  "ADD",  "SUB", "MPY", "DVD",
	"NEG",  "ODD",  "EQL", "NEQ", "LSS",
	"GTR",  "LEQ",  "GEQ", "LIT", "RET",
        "CAL",  "LOD",  "STO", "INT", "JPU",
        "JPC",  "INP",  "PRN", "ASC", "PRS",
        "PRL"
   };

struct instr {
     int o;     /* opcode */
     int l;     /* level of declaration */
     int a;     /* rel. address in DSA */
   };

struct instr code [codemax];   /* intermediate code array */
int    codeindex = 0;          /* intermediate code index */


void emit(int opc, int lv, int addr)
/*----------------------------------------------------
 emit generates intermediate code statements and
 and stores them in the code array
-----------------------------------------------------*/
{
   if (codeindex == codemax) error(31);
   code[codeindex].o = opc;
   code[codeindex].l = lv;
   code[codeindex].a = addr;
   codeindex++;
}

void fixup(int ci, int addr)
/* patch address into code array at
   specified code index */
{
   code[ci].a = addr;
}

int cdindex()
{
   return codeindex;
}

void writecode()
{
   int i;

   for (i=0; i<codeindex; i++)
      fprintf(intcode, "%03d  %s %2d %5d\n", i,
	      codemnemo[code[i].o], code[i].l,
              code[i].a);
}
