Added code to parse method access in parser

This commit is contained in:
nocturn9x 2020-07-31 12:54:09 +02:00
parent 1d6a9f30da
commit 8f4fe11813
5 changed files with 34 additions and 4 deletions

View File

@ -1,6 +1,7 @@
import operator
from typing import List
from .types.callable import Callable
from .types.japlclass import JAPLClass
from .meta.environment import Environment
from .meta.tokentype import TokenType
from .types.native import Clock, Type, JAPLFunction, Truthy, Stringify
@ -159,6 +160,9 @@ class Interpreter(Expression.Visitor, Statement.Visitor):
def visit_class(self, stmt: Class):
"""Visits a class declaration"""
self.environment.define(stmt.name.lexeme, None)
klass = JAPLClass(stmt.name.lexeme)
self.environment.assign(stmt.name, klass)
def visit_while(self, statement: While):
"""

View File

@ -112,3 +112,11 @@ class Call(Expression):
def accept(self, visitor):
return visitor.visit_call_expr(self)
@dataclass
class Get(Expression):
object: Expression
name: Token
def accept(self, visitor):
return visitor.visit_get(self)

View File

@ -1,9 +1,8 @@
from .meta.exceptions import ParseError
from .meta.tokentype import TokenType
from .meta.tokenobject import Token
from typing import List, Union
from .meta.expression import Variable, Assignment, Logical, Call, Binary, Unary, Literal, Grouping, Expression
from .meta.expression import Variable, Assignment, Logical, Call, Binary, Unary, Literal, Grouping, Expression, Get
from .meta.statement import Print, StatementExpr, Var, Del, Block, If, While, Break, Function, Return, Class
@ -133,6 +132,9 @@ class Parser(object):
while True:
if self.match(TokenType.LP):
expr = self.finish_call(expr)
elif self.match(TokenType.DOT):
name = self.consume(TokenType.ID, "Expecting property after '.'")
expr = Get(expr, name)
else:
break
return expr

8
JAPL/types/instance.py Normal file
View File

@ -0,0 +1,8 @@
class JAPLInstance:
"""A class instance"""
def __init__(self, klass):
self.klass = klass
def __repr__(self):
return f"<instance of '{self.klass.name}'>"

View File

@ -1,8 +1,16 @@
class JAPLClass(object):
from .callable import Callable
from .instance import JAPLInstance
class JAPLClass(Callable):
"""A JAPL class"""
def __init__(self, name: str):
self.name = name
self.arity = 0
def __repr__(self):
return self.name
return f"<class '{self.name}'>"
def call(self, interpreter, arguments):
return JAPLInstance(self)