Stack-based virtual machine implementation for a subset of C

Hi everyone, I am currently implementing a simple programming language for learning, but I need some advice. I am currently developing my own interpreter and am having a problem.

My language is a subset of C, and I have a problem with implementing a stack interpreter. The following language will be compiled in the following language:

somefunc () { 1 + 2; } main () { somefunc (); } 

Now this is good, but when "1 + 2" is computed, the result is pushed onto the stack, and then the function returns, but the stack still has a number, and this should not be. How can I get around this problem?

I was thinking about saving the β€œstate” of the stack before calling the function and restoring the β€œstate” after calling the function. For example, keeping the number of elements on the stack, then execute the function code, go back, and then put it from the stack until we have the same number of elements as before (or maybe +1 if the function returned something).

Any ideas? Thanks for any tips!

+7
c ++ interpreter vm-implementation
source share
3 answers

Great question! One of my hobbies is to write compilers for toy languages, so it will come in handy for your excellent programming.

Expression operator is one where the code in an expression is just an expression. This means any of the form <expression> ; , which includes functions such as assignments and function calls, but not if s, while s or return s. Any expression statement will have a value on the left of the stack at the end, which you must cancel.

1 + 2 is an expression operator, but also:

  • x = 5;
    An assignment expression leaves a value of 5 on the stack, as the result of the assignment is the value of the left operand. After completing the instruction, you delete the unused value 5.

  • printf("hello world!\n");
    printf () returns the number of characters to print. You will leave this value on the stack, so place it when the instruction ends.

Effectively, each expression statement will leave a value on the stack if the type of the expression is not void . In this case, you either special case-expressions void , or type nothing after that, or push the pretending value "void" onto the stack so that you can always pop the value.

+8
source share

You need a smart parser. When you see an expression whose value is not used, you need to fix the POP.

+2
source share

This is an important opportunity to optimize learning. you have a function that performs a number, but integer math, the result of the calculation cannot be used in any way, form or form.

Due to the fact that your compiler optimizes the function, you will reduce the number of generated and executable bytecodes!

0
source share

All Articles