I am writing my own programming language using C# just for fun. It's called SPL. It has only 12 keywords/commands/instructions and nothing more. I know exactly what each command is going to do. This is the class diagram:
This is not finished of course. But the idea is, we have a runtime ISplRuntime
. All the things that the commands do, is done on the runtime. For example, the OutputCommand
outputs the stuff in ISplRuntime.Current
(This is just an object
) to ISplRuntime.Output
(This is a TextWriter
).
So far so good. But then I need to implement the IGotoCommand
which is just like the goto
keyword in C#. I am going to make three kinds of gotos. But I cannot figure out how to change the flow of the program.
Here's the ideas I tried:
Add a method called RunNextCommand()
in ISplRuntime
. And in the end of every command's Execute()
method, call RunNextCommand
. However, if the user writes a lot of SPL code, the stack trace will get larger and larger and result in a Stack Overflow.
Add a delegate to ISplRuntime
. Each time a command has finished executing, Invoke()
the delegate. The delegate will look for the next command to execute and call Execute()
on that ICommand
. But I am not sure if this will also result in a stack overflow. Will it result in a stack overflow?
I am still not very sure if this is the right way to do it. I just want an general answer about how to do this kind of thing as this is the first time for me to write a language. Also please tell me whether using delegates will cause a stack overflow.
Normally, you would just do a loop; within the loop, execute the command at the current line, then for all non-flow-control commands increment the current line. For goto, just set the current line to the parameter. There are no stack issues because the flow is not recursive - everything gets launched from the instruction loop (which would belong to the runtime, given your class diagram).