feat: runtime boolean

This commit is contained in:
Dan Chen
2024-03-21 16:59:35 +08:00
parent 5e2d68230b
commit 0c34fd260f
6 changed files with 86 additions and 11 deletions

View File

@ -93,7 +93,7 @@ class Parser:
return self.current_token["type"]
def _is_literal(self):
return self.current_token["type"] in ["NUMBER", "STRING", "FLOAT"]
return self.current_token["type"] in ["NUMBER", "STRING", "FLOAT", "true", "false"]
# variable
def variable_statement(self):
@ -126,6 +126,8 @@ class Parser:
def literal(self):
token_type = self.current_token["type"]
if token_type == "true" or token_type == "false":
return self.boolean_literal()
if token_type == "NUMBER":
return self.numberic_literal()
if token_type == "STRING":
@ -134,6 +136,18 @@ class Parser:
return self.float_literal()
raise Exception("Unexpected token: " + token_type)
def boolean_literal(self):
if self.token_type() == "true":
self.eat('true')
value = "True"
else:
self.eat("false")
value = "False"
return {
"type": 'BooleanLiteral',
"value": value,
}
def numberic_literal(self):
token = self.eat('NUMBER')
return {

View File

@ -69,12 +69,14 @@ class Runtime:
return int(ast.get("value"))
elif ast.get("type") == "FloatLiteral":
return float(ast.get("value"))
elif ast.get("type") == "BooleanLiteral":
return bool(ast.get("value"))
def _is_identifier(self, ast):
return ast["type"] == "Identifier"
def _is_literal(self, ast):
return ast["type"] in ["NumericLiteral", "StringLiteral", "FloatLiteral"]
return ast["type"] in ["NumericLiteral", "StringLiteral", "FloatLiteral", "BooleanLiteral"]
def exec_return(self, ast):
v = ast.get("value")

View File

@ -7,10 +7,25 @@ specs = (
# Comments:
(re.compile(r"^//.*"), None),
# Symbols:
(re.compile(r"^\("), "("),
(re.compile(r"^\)"), ")"),
(re.compile(r"^\,"), ","),
(re.compile(r"^\{"), "{"),
(re.compile(r"^\}"), "}"),
(re.compile(r"^;"), ";"),
# Keywords:
(re.compile(r"^\blet\b"), "let"),
(re.compile(r"^\breturn\b"), "return"),
(re.compile(r"^;"), ";"),
(re.compile(r"^\bif\b"), "if"),
(re.compile(r"^\belse\b"), "else"),
(re.compile(r"^\bwhile\b"), "while"),
(re.compile(r"^\bfor\b"), "for"),
(re.compile(r"^\def\b"), "def"),
(re.compile(r"^\btrue\b"), "true"),
(re.compile(r"^\bfalse\b"), "false"),
# Floats:
(re.compile(r"^[-+]?[0-9]+\.[0-9]+"), "FLOAT"),
@ -27,13 +42,6 @@ specs = (
# Double-quoted strings
(re.compile(r"^\"[^\"]*\""), "STRING"),
# Symbols:
(re.compile(r"^\("), "("),
(re.compile(r"^\)"), ")"),
(re.compile(r"^\,"), ","),
(re.compile(r"^\{"), "{"),
(re.compile(r"^\}"), "}"),
)
class Tokenizer: