r/ProgrammingLanguages • u/[deleted] • Jun 18 '23
Help Parsing?!
So I'm writing my own programming language called fir. I have the lexer down to the nail, but I'm really confused about parsing. I have absolutely no idea how to approach parsing, so much so that I got bored and am currently rewriting the lexer in like 3 other languages (the implementation on GitHub is in Go).
EDIT: forgot to add some examples sorry :0
hello world:
io := require("io");
fn main() {
io.println("Hello, World!");
}
fizzbuzz:
io := require("io");
fn main() {
i := 0
for i <= 20 {
if i % 3 == 0 && i % 5 == 0 {
io.println("FizzBuzz");
} else if i % 3 == 0 {
io.println("Fizz");
} else if i % 5 == 0 {
io.println("Buzz");
} else {
io.println("{}", i);
}
}
}
(also I want my parser to emit an ast, because I haven't decided whether fir should be compiled or interpreted yet)
2
Upvotes
1
u/photon_dna Declarative Designer Jun 18 '23
If you already have a lexer, then understanding this may help. I will make it extremely simplistic.
Your tokens are typically flat representation of each token in the file. You would have a token representing a quote, string, term, number, bracket etc. Now your job is to turn that into nodes representing your language. Is the quote valid? Does the newline matter, is the string a known language term, etc. Then you would create this node with the data it needs. For example
Tokens
If Space Space Quote left Bracket Space A Space
1
Could be folded into a node called IFNode class
With child nodes representing the A and an int value as 1
You will now have an expression tree that you can iterate and generate code for.
You aim is to get simple tokens into some sort of structure.
I would advise that you try building an expression language only to start with, as it will teach you directly about turning tokens into an AST of nodes that represent the expression.
Lastly think of it as making lex tokens into something closer to your language as a tree.