so I’m making some basic programming language (just for exercise). I’ve made simple grammar using ANTLR.
Let’s use this as example of simple program.
begin
int a;
a = 3+4*4;
end
And let’s test if that runs with following java class.
public class Test {
public static void main(String[] args) throws RecognitionException {
CharStream charStream = new ANTLRStringStream("here goes the code");
LangLexer lexer = new LangLexer(charStream);
TokenStream tokeStream = new CommonTokenStream(lexer);
LangParser parser = new LangParser(tokeStream);
Lang.program();
System.out.println("done");
}
}
Now I’m stuck. I want to make, for example “input x” and “print x”. So that when you have “input x” in your code, the program wants you to enter some number, and stores given value in var X. And with print X it outputs that value in console.
begin
int a, b, c;
input a;
input b;
c = a + b;
print c;
end
Any ideas and suggestions?
Thanks!
How to do that exactly is hard to explain since you need a lot of underlying stuff (grammar, AST walker, scope/symbol-table, etc.).
I’ve written a blog that explains how to create a small programming language. If you read through it and/or download the zip of the last part, you only need to add a couple of things to support user-input. These are the changes you need to make:
In file TL.g:
In file TLTreeWalker.g:
Add the following class:
And if you now evaluate the input:
you will be prompted with the message
Enter a number:and this number is then added toaand will be printed to the console.