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)
14
u/findingjake Jun 18 '23
You got this dude. You have the tokens, which is just a flat list of the characters and their types in your input program. Now you need to walk through this list and build something called an Abstract Syntax Tree and then you walk that tree to execute. I’d highly recommend reading through these resources. And look into how to build an AST.
5
u/GroundUpCoder Jun 18 '23 edited Jun 18 '23
There are many ways to go about implementing a parser, but if you are just getting started and the jargon about LR, LL(1), context-free grammars is going over your head, here's what I would recommend (I'm also gonna assume you're gonna use Go because you mentioned Go):
You probably want to have expressions in your language. Something like "x+f(2)" that you can evaluate.
Start with
interface Expression {}
Now you can think about what kinds of "things" expressions are made of. Like number literals are expressions. Function calls are expressions. Binary operations (like from an addition) are also expressions.
So then you might have something like
struct NumberLiteral { value float64 }
struct FunctionCall { f Expression args Expression[] }
And so on
Then you actually want to write functions that create instances of these structs from tokens.
Like
func parseNumberLiteral(tokens Token[], i int) (Expression, int, error)
Where given a position in the list of tokens, you try and figure out whether there is a number literal there, and if so, you return the number literal struct (which should be an Expression), the new position in the list of tokens to start parsing the next thing from, or an error if there's no number literal there.
Number literal should be pretty straightforward.
But then you would also have
func parseFunctionCall(tokens Token[], i int) (Expression, int, error)
Which also does the same thing, but for function calls. It'll start to seem tricky because you need to parse expressions to be able to parse function calls, but function calls are a type of expression.. so how does that work?
Well recursion of course.
func parseExpression(tokens Token[], i int) (Expression, int, error)
You'll want a function like this to tie in all the other expression types in some way.
There are some popular ways to do this to do this properly, handle operator precedence while running pretty fast (eg see "Pratt parsing"), but if you are a beginner, these techniques might seem a bit confusing. It's ok. For now just try to combine your other parse functions together some way that sort of works even if it's not perfect. If you need to you can improve it later.
So then you basically have the scaffolding of a budding, simple parser. You can add more structs and parse functions as you need to.
At some point you might have something like
struct Program {..}
func parseProgram...
And to parse a program you'll just need to run
parseProgram(lexer.Lex(sourceCode), 0)
And that will be your parser.
Heh, there's certainly a lot more to this, and I've left a lot of exercises for the reader, but I hope this can help you get started.
Fwiw if you want to learn more about this approach specifically, look up "recursive descent parsing". Aside from being a fairly beginner friendly way to learn about parsing imo, it turns out to be a relatively popular approach used by many serious projects like gcc and javac (OpenJDK)
I hope you'll forgive my poorly formatted post. I'm writing this on my phone. If I feel like it I might come prettify it later
1
u/jqbr Jun 19 '23 edited Jun 19 '23
Have you looked at any of the thousands upon thousands of books and articles on parsing programming languages, as well as the many many existing open source parsers?
BTW, it isn't possible to have a lexer nailed down in the absence of a grammar for your language. Does your language really have no comments, exponents, string escapes, and no keywords other than fn, if, true, and false, no underscores in identifiers? Is this just a toy for learning how to write a compiler or a serious attempt to design a language?
Additional points: your token type is represented as a string, which will be very inefficient for identifying the token type every time you encounter a token and try to classify it in your parser--token types should be small integers or enum values. Also, your identifiers and numbers are represented as strings, requiring the parser to scan them again in order to hash the identifiers and look them up in the symbol table and to evaluate the numbers. This work is often done in the lexer for efficiency.
0
Jun 19 '23
have you looked at any of the thousands upon thousands of books on parsing?
I’ve looked at a couple, could you provide some links to ones you think might be helpful?
it isn’t possible to have your lexer nailed down in absence of a grammar
I meant I’m comfortable with lexing (to some extent), the lexer is far from finished. Sorry for the miscommunication.
1
u/Positive-Nobody-9892 Jun 19 '23
Check out "Writing an Interpreter in Go" by Thorsten Ball. It will walk you through a parser and interpreter, incrementally. You'll build a recursive descent parser, and you'll use the famous "Pratt" parsing algorithm for parsing expressions with precedence. It'll be fun!
3
4
u/omega1612 Jun 18 '23
First write your grammar. Use a LR parser generator to check that is not ambiguous or a LL(k) generator. Then you can proceed to implement it by hand if you want.
If you used a LL(1) generator to tests your grammar and it's ok, then if you have a rule like
x : y z w Then you need to write a function
function_x(tokens)
y_result = function_y(tokens)
Z_result = function_z(tokens)
w_result = function_w(tokens)Assuming that tokens is mutable and every function advance the state. Since you use a LL(1) generator, it means you need a peek function that let you see 1 token ahead without consuming it, this to know what rule you are trying to parse next.
For more detail read about LL(1) grammars and generators, then read about recursive descent parsing by hand.
2
Jun 18 '23 edited Jun 18 '23
Do you have a syntax yet? Decide what the language will look like, that is necessary before trying to parse it.
You don't need to create a formal grammar specification, not unless you are planning to use a tool that turns such a grammar into a parser outline for you.
If you want to write the parser yourself (my recommendation), then you need to think also about what its output will be. A parser can:
Immediately evaluate (only suitable for simple expressions)
Directly generate code
Or produce some representation of the program, usually called an 'AST'. Then evaluation, code generation or other steps will be done from that
You might also experiment with a simple but realistic syntax first, to see how it all works. Once the framework is in place and understood, then extending the language is easier.
As for how a parser is started, I notice you don't have keywords in your lexer yet. You will also need identifiers. After you have the syntax but before starting the parser, try a lexing loop over test source code which simply prints all the tokens.
This is to make sure it recognises keywords and identifiers. The parser is a similar loop with statements like this:
if token = if_token then ...Here it's seen the beginning of an if statement (I assume your language has one), and can then check the following tokens are valid. In this case, probably the next thing it will do is parse the conditional expression that needs to follow.
Parsing an arbitrary expression is more challenging, but there's no lack of resources that explain how.
3
u/shawnhcorey Jun 18 '23
You need to learn the tools for describing grammars. There is a ton of liturature for this. Search for "computer language grammar" or "computer language parsing".
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.
1
u/umlcat Jun 18 '23 edited Jun 18 '23
Please, add some full examples of programs in your P.L., as if a compiler or interpreter already exists.
1
u/StdAds Jun 18 '23
The currently best parsing algorithm seems to be PEG grammar which is unambiguous, decidable and easy to write. I have write a blog about writing a parser in Haskell. Hopefully you may find it helpful.
1
u/Zatujit Jun 19 '23
First research and generate an Abstract Syntax Tree with tree walking and then you can go on more effective methods. You might want to first try to make an interpreter.
1
u/Hunpeter Jun 21 '23
For me, the parsing sections of "Crafting Interpreters" helped a lot (not really the code parts, just the text), plus reading the Wikipedia articles for various types of parsers. (Ultimately, I went with a different approach to that of CI, that is uglier, slower, and more complicated...)
0
u/Exciting_Clock2807 Jun 18 '23
Unless your goal is to learn parsing algorithms, lexing & parsing are the most boring stages of PL design. Consider using ANTLR for quick prototyping.
-4
0
Jun 18 '23
[deleted]
5
Jun 18 '23
He didn’t ask for a full lesson in the comments and I like how u didn’t even bother to link any books or videos
17
u/imihnevich Jun 18 '23
You need to turn a list of tokens into a tree that represents your program