Starlib: How to write your main program

These steps show how to write a main program using the starlib.


#includes

Every module in a starlib-using program should contain the following includes:
	#include <fstream.h>
	#include <stdio.h>
        #include "ast.h"
	#include "parser.h"
	#include "scanner.h"
    

Global variables

There must exist the following two global variables in the program:
        StarFileNode  *AST;   // StarFileNode is defined in "ast.h"
	ofstream      *os;    // ofstream is in the standard libc++.
    

Initialization

The global variables mentioned above are used like this:

This is an example of code to illustrate all the above steps

This code will parse in a star file called "input.star", and write it out under the name "output.star". The example doesn't do anything else, but you can use it as a skeleton from which to base your own code.

Don't be overwhelmed if you don't understand everything here, but you should be able to understand the use of *os, *AST, and yyin.


#include <fstream.h>
#include <stdio.h>
#include "ast.h"
#include "parser.h"
#include "scanner.h"

    StarFileNode  *AST;   // StarFileNode is defined in "ast.h"
    ofstream      *os;    // ofstream is in the standard libc++.

int main( void )
{

    yyin = fopen( "input.star", "r" );
    if( yyin == NULL )
    {   cerr << "Error opening input.star\n";
	return 2;
    }

    if( yyparse() == 0 )  // yyparse returns nonzero on error.
    {
	// It was successfully parsed, now *AST contains the
	// file in memory.  For this simple example, we will
	// just Unparse it right away and quit.
	// -------------------------------------------------
        os = new ofstream( "output.star" );
	if( os == NULL )
	{   cerr << "Error opening output.star\n";
	    return 1;
	}
	AST->Unparse(0); // Unparse takes 1 arg: the indent level:

	delete os;   // C++ streams are closed by calling the delete
	             // operator.  If you do not close it, it might
		     // not flush the last line or two of the output.
	delete AST;
    }
    else
    {   cerr << "Syntax error while parsing file.\n";
	return 3;
    }

    return 0;
}
    

- previous topic - - next topic -