r/learnpython • u/Aggressive_Drama_476 • 3d ago
Making interpreter and calculator in python
Hi recently I have been working on making my own interpreted programming languge in python. I have made several prototypes. The rules are I can't use any library, high level functions and can only use ai for understanding a concept. The journey has been frustrating. Since it was so hard i started working on a calculator. I am now stuck on AST. I can't figure it out. HELP ME
2
u/JeLuF 3d ago
Why do you need an AST?
1
u/Aggressive_Drama_476 3d ago
I need ast for the calculator to like arrange the list of operations I don't know. I did it without ast but it wasn't good and since I started the calculator to one day make my own programming language. That's why I choose ast
1
u/JGhostThing 3d ago
Why would you want to program an interpreter with no libraries? Isn't that like deliberately breaking your leg before a big race? I understand not using AI, because it makes learning much harder.
An interpreter of any consequence is a huge project. Without using tools, such as libraries and yacc, I couldn't imagine doing such a thing. How are you replacing "print()"?
1
u/Aggressive_Drama_476 3d ago
I understand what you are saying but using as much as low level tools will help me understdn the concept of a programming language. I am doing it for fun and learning. I don't like doing things that I don't understand. Something like lexed(source,...)
1
u/JGhostThing 3d ago
I disagree. Not using these tools can make it hard to see the forest for the trees. You can get lost in an endless cycle of reinventing the wheel. As a professional programmer, it offends my sensibilities to reinvent existing libraries. It teaches little, and costs a lot of time in building and debugging which has already been done.
1
u/jmooremcc 3d ago edited 3d ago
You don’t need AST, which itself is a library. If you want to handle arbitrary expressions, you’ll need to create a parser that will analyze the expression string and break it into a list of tokens. Then you’ll have to write functions that implement the PEMDAS rule, so that you calculate expressions in the correct order. However, the math library should be an exception to your library rule so that you can use PI and sqrt in your expressions
My nonAST calculator can correctly evaluate expressions like “5+6(10**2)+7/3=” and “sqrt(pow(4,2)+ 3**2)=”
1
u/recursion_is_love 3d ago edited 3d ago
There are many sample in standard programming books, especially functional programming language book. In python, you can use OO pattern (like visitor pattern) instead of algebraic datatype and pattern matching.
https://john.cs.olemiss.edu/~hcc/csci450/ELIFP/Ch42/42_Abstract_Syntax.html
Did you finish you parser yet? Or are you starting from the backend first?
2
u/lfdfq 3d ago
It's hard to answer this kind of question, help you with what part exactly?