next up previous contents
Next: Parameters Up: Procedure and Function Previous: Procedure and Function

How to Compile a Procedure or Function

 

A procedure or function is compiled as if it was a method of the program class. For a method we need to put the following items in the class file:

In a Pascal program there are normal declarations of procedures and functions, and there are forward declarations, followed by a definition later in the program.

Normal declarations and forward declarations both cause the entries in the constant_pool[] and the entry in the methods[] table to be created. The function in the compiler that does this returns a pointer to the m_f structure in the m list, containing the entry in the methods[] table. By returning this pointer, later on when instructions have to be added to the code[] array of the current method, you do not have to search through the list of m_f structures to find the right one. Instead you pass the pointer as a parameter to every procedure or function in the compiler that needs it.

In case of a forward declaration, there is no need to keep the pointer, as you know that the definition of the function or procedure will not follow until later. When the definition of a forward declared procedure or function is encountered, the m list is searched for the m_f structure of the method to which a pointer is returned so it can be passed as a parameter in the compiler the same way as for a normal declaration.

The descriptor of the method has to be constructed when the list of parameters has been read by the parser. I do this by adding the descriptor of every parameter to a list that in the end contains the complete descriptor of the method. The elements of the list are the following structure:

    struct descr {
        char            *elt;
        struct descr    *next;
    }

The list is initialized by creating a first entry containing the string `` (''. After all the entries containing the descriptors of the variables are added, the list is ended by an entry containing the string `` )'' and an entry containing the string `` V'' in case of a procedure, or an entry containing the descriptor of the return type in case of a function. How the descriptors of the parameters and the descriptor of the return type look, will be discussed in the next subsection.

The function in the compiler that adds the method to the class file constructs a single string containing the complete descriptor of the method out of the list, and stores it in a CONSTANT_Utf8_info entry in the constant_pool[].

The code of the method has to be ended by an instruction to return from the method. For a procedure this is the return instruction. How functions return will be discussed in section 10.7.



next up previous contents
Next: Parameters Up: Procedure and Function Previous: Procedure and Function



mark@bottom.xs4all.nl