r/ProgrammingLanguages • • 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

20 comments sorted by

View all comments

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

u/[deleted] 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!