davidcallanan / py-myopl-code Goto Github PK
View Code? Open in Web Editor NEWInterpreter for the BASIC language written in Python 3
License: MIT License
Interpreter for the BASIC language written in Python 3
License: MIT License
Not really a problem, but if you add it then people could make improvements to the code and basically turn it into an actual programming language. Thoughts, anyone?
help "RTError" is not defined Pylance(reportUndefinedVariable)
So, I just finished with the code for the first video. I have made a lot of changes in the code, so my code may seem to be different than yours. The following error is raised:
Traceback (most recent call last):
File "main.py", line 135, in <module>
tokens, error = lexer.make_tokens()
File "main.py", line 65, in make_tokens
tokens.append(self.make_number())
File "main.py", line 88, in make_number
self.advance()
File "main.py", line 54, in advance
if self.character in " \t":
TypeError: 'in <string>' requires string as left operand, not NoneType
And my code is the following:
operators = {
"+" : "ADDITION",
"-" : "SUBTRACTION",
"*" : "MULTIPLICATION",
"/" : "DIVISION",
"(" : "PARENTHESIS_LEFT",
")" : "PARENTHESIS_RIGHT"
}
class Exception:
def __init__(self, name, details, inp):
self.name = name + "Error"
self.details = details.format(inp=inp)
def __repr__(self):
return f"{self.name}: {self.details}"
class InvalidCharacter(Exception):
def __init__(self, character):
super().__init__("InvalidCharacter", "\"{inp}\" is not a valid number, integer or decimal", character)
class Token:
def __init__(self, type_of, value):
self.type_of = type_of
self.value = value
def __repr__(self):
if (self.value != "") and (self.type_of != ""):
return "{type_of} :: {value}".format(
type_of = self.type_of,
value = self.value
)
else:
return self.type_of
class Lexer:
def __init__(self, text):
self.text = text
self.position = -1
self.character = None
self.advance()
def advance(self):
self.position += 1
if self.position < len(self.text):
self.character = self.text[self.position]
else:
self.character = None
if self.character in " \t":
self.advance()
def make_tokens(self):
tokens = []
while self.character != None:
if self.character in "+-*/()":
tokens.append(Token("OPERATOR", operators[self.character]))
self.advance()
elif self.character in "0123456789":
tokens.append(self.make_number())
self.advance()
else:
self.advance()
return ([], InvalidCharacter(self.character))
return (tokens, None)
def make_number(self):
num_string = ""
dot_count = 0
while self.character != None:
if self.character in "0123456789.":
if self.character == ".":
if dot_count > 0:
break
dot_count += 1
num_string += "."
else:
num_string += self.character
self.advance()
elif self.character in " \t":
self.advance()
self.advance()
if dot_count == 0:
return Token("INTEGER", int(num_string))
elif dot_count == 1:
return Token("DECIMAL", float(num_string))
else:
return "Something went very wrong. Here is your number: " + num_string
def zero_pad(n, width):
out = str(n)
while len(out) < width:
out = "0" + out
return out
def array_pad(arr):
out = ""
if not(arr):
return None
out += "["
for el in arr:
out += "\n\t" + el + ","
out += "\n]"
return out
n = 1
while True:
inp = input(f"[{zero_pad(n, 3)}] >>> ")
n += 1
lexer = Lexer(inp)
tokens, error = lexer.make_tokens()
if error:
print(repr(error))
else:
print(array_pad(tokens))
I know that I probably appear as some kind of snob to you, but I would really appreciate it anyone bothered to help me out.
The Import Basic Doesnt Work Idk Why I litellarry just copy and Pasted it
var animal = random(1, 3)
if animal = 1 then
print("You have Pikachu!")
elif animal = 2 then
print("You have Charmander!")
else then
print("You have Squirtle!")
end
I made the keywords lowercase and added a random function, but it says the if is causing an InvalidSyntaxError, the example works, and I don't know what I did differently, it says a token can't appear after another token.
So lets say that when I type "5 +" for example on episode to at the 17:04 timestamp instead of giving the error it will print
"(INT:5, PLUS, None)" my code is here: https://github.com/penguinpolarDOTnet/Penguin-Bullet---Programming-Language
i want my 'AND' keyword to be '&&' but whenever I use && the code pops out it as illegal: '&' BTW the code works fine when I use 'AND' as an keyword. i also tried using '&&' still didn't work
where do i download the module basic for the program?
whenever I use PRINT or any other built in function, it returns , it seems that the repr function of the BuiltInFunction is running but I don't know why
class BaseFunction(Value):
def __init__(self, name):
super().__init__()
self.name = name or "<anonymous>"
def generate_new_context(self):
new_context = Context(self.name, self.context, self.pos_start)
new_context.symbol_table = SymbolTable(new_context.parent.symbol_table)
return new_context
def check_args(self, arg_names, args):
res = RTResult()
if len(args) > len(arg_names):
return res.failure(RTError(
self.pos_start, self.pos_end,
f"{len(args) - len(arg_names)} too many args passed into {self}",
self.context
))
if len(args) < len(arg_names):
return res.failure(RTError(
self.pos_start, self.pos_end,
f"{len(arg_names) - len(args)} too few args passed into {self}",
self.context
))
return res.success(None)
def populate_args(self, arg_names, args, exec_ctx):
for i in range(len(args)):
arg_name = arg_names[i]
arg_value = args[i]
arg_value.set_context(exec_ctx)
exec_ctx.symbol_table.set(arg_name, arg_value)
def check_and_populate_args(self, arg_names, args, exec_ctx):
res = RTResult()
res.register(self.check_args(arg_names, args))
if res.should_return(): return res
self.populate_args(arg_names, args, exec_ctx)
return res.success(None)
class Function(BaseFunction):
def __init__(self, name, body_node, arg_names, should_auto_return):
super().__init__(name)
self.body_node = body_node
self.arg_names = arg_names
self.should_auto_return = should_auto_return
def execute(self, args):
res = RTResult()
interpreter = Interpreter()
exec_ctx = self.generate_new_context()
res.register(self.check_and_populate_args(self.arg_names, args, exec_ctx))
if res.should_return(): return res
value = res.register(interpreter.visit(self.body_node, exec_ctx))
if res.should_return() and res.func_return_value == None: return res
ret_value = (value if self.should_auto_return else None) or res.func_return_value or Number.null
return res.success(ret_value)
def copy(self):
copy = Function(self.name, self.body_node, self.arg_names, self.should_auto_return)
copy.set_context(self.context)
copy.set_pos(self.pos_start, self.pos_end)
return copy
def __repr__(self):
return f"<function {self.name}>"
class BuiltInFunction(BaseFunction):
def __init__(self, name):
super().__init__(name)
def execute(self, args):
res = RTResult()
exec_ctx = self.generate_new_context()
method_name = f'execute_{self.name}'
method = getattr(self, method_name, self.no_visit_method)
res.register(self.check_and_populate_args(method.arg_names, args, exec_ctx))
if res.should_return(): return res
return_value = res.register(method(exec_ctx))
if res.should_return(): return res
return res.success(return_value)
def no_visit_method(self, node, context):
raise Exception(f'No execute_{self.name} method defined')
def copy(self):
copy = BuiltInFunction(self.name)
copy.set_context(self.context)
copy.set_pos(self.pos_start, self.pos_end)
return copy
def __repr__(self):
return f"<built-in function {self.name}>"
#####################################`
Hey there! I need some help with data conversion. I am learning from your youtube videos to build interpreters but what I found in your interpreter after completing it is that if I take INPUT()
it returns as a string which I cant change to integer, can I?
How i can run a example.myopl with this programing launguae?
please add network request :)
First off, I just wanted to say that this tutorial is AMAZING!!!! I only have one "issue"/question, which is: how would I go about making an import statement in this language? All of the other stuff I wanted to do could be based off something, but import is kinda different. My apologies if this shouldn't be an issue, I didn't really know how to ask.
The following code in the dived_by
method in episodes 3-14 is non-pythonic and can be fixed
Sorry if I'm rude: I'm new to GitHub:
if other.value == 0:
return None, RTError(
other.pos_start, other.pos_end,
'Division by zero',
self.context
)
return Number(self.value / other.value).set_context(self.context), None
to
try:
return Number(self.value / other.value).set_context(self.context), None
except ZeroDivisionError:
return None, RTError(
other.pos_start, other.pos_end,
'Division by zero',
self.context
)
If I want to get an item from a list, I can't.
For example, I can't do list[2]
.
Please add this feature.
I tried the program after doing the comparison operator but when I type 2 == 2, It shows a syntax error (Not python)
INPUT >> 2 == 2
OUTPUT >> (SyntaxError: Expected + blah blah)
It's not only with ==, it's also with every operator.
When I do something like this:
1+2
it returns:
INT:2
Not anything else.
IDK what's causing it.
Also, what does tok.type
do? It gives me a syntax error, and the syntax seems weird.
how do i make it that 5(2+3) works as 5*(2+3) and (2+3)5 as (2+3)*5 so that if a number is directly connected to a parentheses it multiplies with the end value of the parentheses
So I don't understand why but when I started to do some errors it gave me that:
Error:
Traceback (most recent call last):
File "c:\Users\..\Desktop\Real\shell.py", line 6, in <module>
if error: print(error.as_string())
File "c:\Users\..\Desktop\Real\basic.py", line 10, in as_string
res += f'File {self.pos_start.fn}, line {self.pos_start.ln + 1}'
AttributeError: 'IllegalChar' object has no attribute 'pos_start'
class Error:
def __init__(self, pos_start, pos_end,error, error_desc):
self.start = pos_start
self.end = pos_end
self.error = error
self.desc = error_desc
def as_string(self):
res = f'{self.error}: {self.desc}'
res += f'File {self.pos_start.fn}, line {self.pos_start.ln + 1}'
return res
class IllegalChar(Error):
def __init__(self, pos_start, pos_end, desc):
super().__init__(pos_start, pos_end, 'Illegal Character', desc)
I would like to know how I can add the following system:
input > PRINT("Hello World", 2)
output > Hello World 2
I debugged episode 14 code. In terminal there was “>>>” and should be “Basic > “. When I typed “1 + 2” I got “3” as answer. So it worked. Your code does not work for me. It can’t run .myopl files. 😕
Can you fix your code?
Yes when I type an = I somehow have too put a =
Code here: https://github.com/penguinpolarDOTnet/Penguin-Bullet---Programming-Language
Error message:
File "basic.py", line 1410, in register
self.error = res.error
AttributeError: 'Number' object has no attribute 'error'
Trying to get example.myopl
to run but I've no idea how. Is there a specific command to execute via shell CLI? Or a way to get it to run through the Python CLI?
Firstly, thank you for making this wonderful series, I hope to make my own language one day and this is a great starting point. I have had an issue with my interpreter in video three in the series. When I type a digit or an operation, it states invalid syntax (attached to this issue). My code linked to this issue as well. Before this issue, everything was going well but now my language doesn't function properly. Any help would be appreciated.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.