New language development project !
Hey people ! If you are following along with the new series of tutorials on youtube "how to make your own programing language", then you know that we are at part 5 - the parser. The parser is where the non terminals that we defined in the BNF and EBNF form come into play.
<- yea its rated as a five star !
Based on the videos in part 5 the code below is an example of what the language would look like when we're done.
Var x = 0;
Print "Hello world !";
Parse_obj x;
The code above is fine for a basic language. But there are some problems. For instance, when the user goes to exit the program by pressing enter, the program will fail. The reason for this is partly due to some code in the code generator. But it is also caused by some code in the parser. To fix this there are three things that we need to do. The first step to fixing this is to go into the Ast.cs file and to add a public class called string.
And withen this you need to add a public string and give it the name "Ident". After that add a public Expr and give it the name of "Expr". Here is the source code:
public class String : Stmt
{
public string Ident;public Expr Expr;}
The second step to fix this problem is to go into the Parser.cs file and add the code below for the "String" non terminal.
else if (this.tokens[this.index].Equals("String")){
this.index++;String String = new String();if (this.index < this.tokens.Count &&this.tokens[this.index] is string){
String.Ident = (string)this.tokens[this.index];}
else
{
throw new System.Exception("expected variable name after 'string'");}
this.index++;if (this.index == this.tokens.Count ||this.tokens[this.index] != Scanner.Equal){
throw new System.Exception("expected = after 'string ident'");}
this.index++;String.Expr = this.ParseExpr();result = String;
}
What the code above does is it adds a the ability to put strings into your source code. The last step is to add The code to read strings to the parser. Here is the source code for that:
else if (this.tokens[this.index].Equals("Read_str")){
this.index++;ReadString ReadString = new ReadString();if (this.index < this.tokens.Count &&this.tokens[this.index] is string){
ReadString.Ident = (string)this.tokens[this.index++];result = ReadString;
}
else
{
throw new System.Exception("expected variable name after 'Read_str'");}
}
The "ReadString" class that you see in the code above is another part of the Ast.cs file. To add this, just add a public class to the ast, and withen this add a public string and call it "Ident". Here is the source code:
public class ReadString : Stmt
{
public string Ident;}
And that will solve the problem of the program failing after the user presses enter to exit. Here is what the new programming language's source code looks like after the changes are made:
String x = "";
Print "Hello world !";
Read_str x;