Compare commits
40 Commits
left-assoc
...
add-polyph
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aca6e6bb55 | ||
|
|
a7de7f0279 | ||
|
|
7e55fe4c1a | ||
|
|
8abae7c2ff | ||
|
|
07f08b0557 | ||
|
|
13b069dc7d | ||
|
|
73ea88d8d9 | ||
|
|
a5875425fc | ||
|
|
0dcf5287e1 | ||
|
|
75dcacce67 | ||
|
|
70687ddc02 | ||
|
|
d802c58eee | ||
|
|
c9a3fc070b | ||
|
|
b126f83824 | ||
|
|
6dc503ba86 | ||
|
|
6222dccaac | ||
|
|
0657214aa3 | ||
|
|
3feec0839b | ||
|
|
56ca69246d | ||
|
|
5a2508e804 | ||
|
|
ea28ab6235 | ||
|
|
6e9e252b86 | ||
|
|
17ef5be057 | ||
|
|
44e63ed18d | ||
|
|
83c7b92741 | ||
|
|
79a7b8bb1d | ||
|
|
2737139962 | ||
|
|
c5435e66ff | ||
|
|
460deb4981 | ||
|
|
69bac69946 | ||
|
|
6bd8046346 | ||
|
|
e70b5fa71a | ||
|
|
44d234d36a | ||
|
|
78ea26ea08 | ||
|
|
b6983df2d3 | ||
|
|
86cf5d01f3 | ||
|
|
a07b226edb | ||
|
|
9ae9da089b | ||
|
|
4f2058eaac | ||
|
|
a68f870037 |
@@ -27,6 +27,10 @@ class IntegerLiteral(Atom):
|
||||
pass
|
||||
|
||||
|
||||
class FloatLiteral(Atom):
|
||||
pass
|
||||
|
||||
|
||||
class StringLiteral(Atom):
|
||||
pass
|
||||
|
||||
@@ -47,6 +51,10 @@ def IntegerParser(input):
|
||||
return Parser.terminal(TokenType.INTEGER, createNode=IntegerLiteral.withValue)(input)
|
||||
|
||||
|
||||
def FloatParser(input):
|
||||
return Parser.terminal(TokenType.FLOAT, createNode=FloatLiteral.withValue)(input)
|
||||
|
||||
|
||||
def StringParser(input):
|
||||
return Parser.terminal(TokenType.STRING, createNode=StringLiteral.withValue)(input)
|
||||
|
||||
@@ -66,6 +74,7 @@ def TypeLiteralParser(input):
|
||||
def LiteralParser(input):
|
||||
return Parser.oneOf(
|
||||
IntegerParser,
|
||||
FloatParser,
|
||||
StringParser,
|
||||
NoteParser,
|
||||
BoolParser,
|
||||
@@ -78,8 +87,18 @@ def AtomParser(input):
|
||||
from smnp.ast.node.identifier import IdentifierParser
|
||||
from smnp.ast.node.list import ListParser
|
||||
from smnp.ast.node.map import MapParser
|
||||
from smnp.ast.node.expression import ExpressionParser
|
||||
|
||||
parentheses = Parser.allOf(
|
||||
Parser.terminal(TokenType.OPEN_PAREN),
|
||||
Parser.doAssert(ExpressionParser, "expression"),
|
||||
Parser.terminal(TokenType.CLOSE_PAREN),
|
||||
createNode=lambda open, expr, close: expr,
|
||||
name="grouping parentheses"
|
||||
)
|
||||
|
||||
return Parser.oneOf(
|
||||
parentheses,
|
||||
LiteralParser,
|
||||
IdentifierParser,
|
||||
ListParser,
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
from smnp.ast.node.operator import BinaryOperator
|
||||
from smnp.ast.node.model import Node
|
||||
from smnp.ast.node.none import NoneNode
|
||||
from smnp.ast.node.operator import BinaryOperator, Operator
|
||||
from smnp.ast.node.term import TermParser
|
||||
from smnp.ast.parser import Parser
|
||||
from smnp.token.type import TokenType
|
||||
@@ -20,7 +22,43 @@ class Or(BinaryOperator):
|
||||
pass
|
||||
|
||||
|
||||
def ExpressionParser(input):
|
||||
class Loop(BinaryOperator):
|
||||
def __init__(self, pos):
|
||||
super().__init__(pos)
|
||||
self.children.extend([NoneNode(), NoneNode()])
|
||||
|
||||
@property
|
||||
def parameters(self):
|
||||
return self[3]
|
||||
|
||||
@parameters.setter
|
||||
def parameters(self, value):
|
||||
self[3] = value
|
||||
|
||||
@property
|
||||
def filter(self):
|
||||
return self[4]
|
||||
|
||||
@filter.setter
|
||||
def filter(self, value):
|
||||
self[4] = value
|
||||
|
||||
@classmethod
|
||||
def loop(cls, left, parameters, operator, right, filter):
|
||||
node = cls(left.pos)
|
||||
node.left = left
|
||||
node.parameters = parameters
|
||||
node.operator = operator
|
||||
node.right = right
|
||||
node.filter = filter
|
||||
return node
|
||||
|
||||
|
||||
class LoopParameters(Node):
|
||||
pass
|
||||
|
||||
|
||||
def ExpressionWithoutLoopParser(input):
|
||||
expr1 = Parser.leftAssociativeOperatorParser(
|
||||
TermParser,
|
||||
[TokenType.PLUS, TokenType.MINUS],
|
||||
@@ -49,3 +87,42 @@ def ExpressionParser(input):
|
||||
lambda left, op, right: Or.withValues(left, op, right)
|
||||
)(input)
|
||||
|
||||
|
||||
def LoopParser(input):
|
||||
from smnp.ast.node.identifier import IdentifierLiteralParser
|
||||
from smnp.ast.node.iterable import abstractIterableParser
|
||||
from smnp.ast.node.statement import StatementParser
|
||||
|
||||
loopParameters = Parser.allOf(
|
||||
Parser.terminal(TokenType.AS),
|
||||
Parser.oneOf(
|
||||
Parser.wrap(IdentifierLiteralParser, lambda id: LoopParameters.withChildren([id], id.pos)),
|
||||
abstractIterableParser(LoopParameters, TokenType.OPEN_PAREN, TokenType.CLOSE_PAREN, IdentifierLiteralParser)
|
||||
),
|
||||
createNode=lambda asKeyword, parameters: parameters,
|
||||
name="loop parameters"
|
||||
)
|
||||
|
||||
loopFilter = Parser.allOf(
|
||||
Parser.terminal(TokenType.PERCENT),
|
||||
Parser.doAssert(ExpressionWithoutLoopParser, "filter as bool expression"),
|
||||
createNode=lambda percent, expr: expr,
|
||||
name="loop filter"
|
||||
)
|
||||
|
||||
return Parser.allOf(
|
||||
ExpressionWithoutLoopParser,
|
||||
Parser.optional(loopParameters),
|
||||
Parser.terminal(TokenType.DASH, createNode=Operator.withValue),
|
||||
StatementParser,
|
||||
Parser.optional(loopFilter),
|
||||
createNode=Loop.loop,
|
||||
name="dash-loop"
|
||||
)(input)
|
||||
|
||||
|
||||
def ExpressionParser(input):
|
||||
return Parser.oneOf(
|
||||
LoopParser,
|
||||
ExpressionWithoutLoopParser
|
||||
)(input)
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
from smnp.ast.node.iterable import abstractIterableParser
|
||||
from smnp.ast.node.model import Node
|
||||
from smnp.ast.node.none import NoneNode
|
||||
from smnp.ast.node.operator import BinaryOperator, Operator, UnaryOperator
|
||||
from smnp.ast.node.unit import UnitParser
|
||||
from smnp.ast.parser import Parser
|
||||
@@ -13,57 +10,12 @@ class NotOperator(UnaryOperator):
|
||||
class Power(BinaryOperator):
|
||||
pass
|
||||
|
||||
|
||||
class Loop(BinaryOperator):
|
||||
def __init__(self, pos):
|
||||
super().__init__(pos)
|
||||
self.children.append(NoneNode())
|
||||
|
||||
@property
|
||||
def parameters(self):
|
||||
return self[3]
|
||||
|
||||
@parameters.setter
|
||||
def parameters(self, value):
|
||||
self[3] = value
|
||||
|
||||
@classmethod
|
||||
def loop(cls, left, parameters, operator, right):
|
||||
node = cls(left.pos)
|
||||
node.left = left
|
||||
node.parameters = parameters
|
||||
node.operator = operator
|
||||
node.right = right
|
||||
return node
|
||||
|
||||
|
||||
class LoopParameters(Node):
|
||||
pass
|
||||
|
||||
|
||||
def FactorParser(input):
|
||||
from smnp.ast.node.expression import ExpressionParser
|
||||
from smnp.ast.node.statement import StatementParser
|
||||
from smnp.ast.node.identifier import IdentifierLiteralParser
|
||||
|
||||
parentheses = Parser.allOf(
|
||||
Parser.terminal(TokenType.OPEN_PAREN),
|
||||
Parser.doAssert(ExpressionParser, "expression"),
|
||||
Parser.terminal(TokenType.CLOSE_PAREN),
|
||||
createNode=lambda open, expr, close: expr,
|
||||
name="grouping parentheses"
|
||||
)
|
||||
|
||||
factorOperands = Parser.oneOf(
|
||||
parentheses,
|
||||
UnitParser,
|
||||
name="factor operands"
|
||||
)
|
||||
|
||||
powerFactor = Parser.leftAssociativeOperatorParser(
|
||||
factorOperands,
|
||||
UnitParser,
|
||||
[TokenType.DOUBLE_ASTERISK],
|
||||
factorOperands,
|
||||
UnitParser,
|
||||
lambda left, op, right: Power.withValues(left, op, right),
|
||||
name="power operator"
|
||||
)
|
||||
@@ -75,27 +27,7 @@ def FactorParser(input):
|
||||
name="not"
|
||||
)
|
||||
|
||||
loopParameters = Parser.allOf(
|
||||
Parser.terminal(TokenType.AS),
|
||||
Parser.oneOf(
|
||||
Parser.wrap(IdentifierLiteralParser, lambda id: LoopParameters.withChildren([id], id.pos)),
|
||||
abstractIterableParser(LoopParameters, TokenType.OPEN_PAREN, TokenType.CLOSE_PAREN, IdentifierLiteralParser)
|
||||
),
|
||||
createNode=lambda asKeyword, parameters: parameters,
|
||||
name="loop parameters"
|
||||
)
|
||||
|
||||
loopFactor = Parser.allOf(
|
||||
powerFactor,
|
||||
Parser.optional(loopParameters),
|
||||
Parser.terminal(TokenType.DASH, createNode=Operator.withValue),
|
||||
StatementParser,
|
||||
createNode=Loop.loop,
|
||||
name="dash-loop"
|
||||
)
|
||||
|
||||
return Parser.oneOf(
|
||||
loopFactor,
|
||||
notOperator,
|
||||
powerFactor,
|
||||
name="factor"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from smnp.ast.node.block import BlockParser
|
||||
from smnp.ast.node.expression import ExpressionParser
|
||||
from smnp.ast.node.identifier import IdentifierLiteralParser
|
||||
from smnp.ast.node.iterable import abstractIterableParser
|
||||
from smnp.ast.node.model import Node
|
||||
@@ -16,7 +17,7 @@ class Argument(Node):
|
||||
|
||||
def __init__(self, pos):
|
||||
super().__init__(pos)
|
||||
self.children = [NoneNode(), NoneNode(), False]
|
||||
self.children = [NoneNode(), NoneNode(), False, NoneNode()]
|
||||
|
||||
@property
|
||||
def type(self):
|
||||
@@ -48,6 +49,14 @@ class Argument(Node):
|
||||
self[2] = value
|
||||
|
||||
|
||||
@property
|
||||
def optionalValue(self):
|
||||
return self[3]
|
||||
|
||||
@optionalValue.setter
|
||||
def optionalValue(self, value):
|
||||
self[3] = value
|
||||
|
||||
class VarargNode(Node):
|
||||
pass
|
||||
|
||||
@@ -90,7 +99,7 @@ class FunctionDefinition(Node):
|
||||
return node
|
||||
|
||||
|
||||
def ArgumentParser(input):
|
||||
def RegularArgumentParser(input):
|
||||
def createNode(type, variable, vararg):
|
||||
pos = type.pos if isinstance(type, Type) else variable.pos
|
||||
node = Argument(pos)
|
||||
@@ -104,6 +113,33 @@ def ArgumentParser(input):
|
||||
Parser.doAssert(IdentifierLiteralParser, "argument name"),
|
||||
Parser.optional(Parser.terminal(TokenType.DOTS, lambda val, pos: True)),
|
||||
createNode=createNode,
|
||||
name="regular function argument"
|
||||
)(input)
|
||||
|
||||
|
||||
def OptionalArgumentParser(input):
|
||||
def createNode(type, variable, _, optional):
|
||||
pos = type.pos if isinstance(type, Type) else variable.pos
|
||||
node = Argument(pos)
|
||||
node.type = type
|
||||
node.variable = variable
|
||||
node.optionalValue = optional
|
||||
return node
|
||||
|
||||
return Parser.allOf(
|
||||
Parser.optional(TypeParser),
|
||||
Parser.doAssert(IdentifierLiteralParser, "argument name"),
|
||||
Parser.terminal(TokenType.ASSIGN),
|
||||
Parser.doAssert(ExpressionParser, "expression"),
|
||||
createNode=createNode,
|
||||
name="optional function argument"
|
||||
)(input)
|
||||
|
||||
|
||||
def ArgumentParser(input):
|
||||
return Parser.oneOf(
|
||||
OptionalArgumentParser,
|
||||
RegularArgumentParser,
|
||||
name="function argument"
|
||||
)(input)
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from smnp.ast.node.atom import LiteralParser
|
||||
from smnp.ast.node.identifier import IdentifierLiteralParser
|
||||
from smnp.ast.node.iterable import abstractIterableParser
|
||||
from smnp.ast.node.model import Node
|
||||
from smnp.ast.node.operator import BinaryOperator, Operator
|
||||
@@ -31,12 +32,15 @@ class Map(Node):
|
||||
|
||||
def MapParser(input):
|
||||
from smnp.ast.node.expression import ExpressionParser
|
||||
keyParser = LiteralParser
|
||||
keyParser = Parser.oneOf(
|
||||
LiteralParser,
|
||||
IdentifierLiteralParser
|
||||
)
|
||||
valueParser = ExpressionParser
|
||||
|
||||
mapEntryParser = Parser.allOf(
|
||||
keyParser,
|
||||
Parser.terminal(TokenType.ARROW, createNode=Operator.withValue, doAssert=True),
|
||||
Parser.terminal(TokenType.ARROW, createNode=Operator.withValue),
|
||||
Parser.doAssert(valueParser, "expression"),
|
||||
createNode=MapEntry.withValues
|
||||
)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from smnp.ast.node.model import Node
|
||||
from smnp.ast.parser import Parser
|
||||
from smnp.token.type import TokenType
|
||||
|
||||
|
||||
class Statement(Node):
|
||||
@@ -10,12 +11,27 @@ def StatementParser(input):
|
||||
from smnp.ast.node.block import BlockParser
|
||||
from smnp.ast.node.condition import IfElseStatementParser
|
||||
from smnp.ast.node.expression import ExpressionParser
|
||||
|
||||
from smnp.ast.node.ret import ReturnParser
|
||||
return Parser.oneOf(
|
||||
IfElseStatementParser,
|
||||
ExpressionParser,
|
||||
BlockParser,
|
||||
ReturnParser,
|
||||
name="statement"
|
||||
)(input)
|
||||
from smnp.ast.node.throw import ThrowParser
|
||||
|
||||
return withSemicolon(
|
||||
Parser.oneOf(
|
||||
IfElseStatementParser,
|
||||
ExpressionParser, # Must be above BlockParser because of Map's syntax with curly braces
|
||||
BlockParser,
|
||||
ReturnParser,
|
||||
ThrowParser,
|
||||
name="statement"
|
||||
), optional=True)(input)
|
||||
|
||||
|
||||
def withSemicolon(parser, optional=False, doAssert=False):
|
||||
semicolonParser = Parser.optional(Parser.terminal(TokenType.SEMICOLON)) if optional else Parser.terminal(
|
||||
TokenType.SEMICOLON, doAssert=doAssert)
|
||||
|
||||
return Parser.allOf(
|
||||
parser,
|
||||
semicolonParser,
|
||||
createNode=lambda stmt, semicolon: stmt,
|
||||
name="semicolon" + "?" if optional else ""
|
||||
)
|
||||
|
||||
17
smnp/ast/node/throw.py
Normal file
17
smnp/ast/node/throw.py
Normal file
@@ -0,0 +1,17 @@
|
||||
from smnp.ast.node.expression import ExpressionParser
|
||||
from smnp.ast.node.valuable import Valuable
|
||||
from smnp.ast.parser import Parser
|
||||
from smnp.token.type import TokenType
|
||||
|
||||
|
||||
class Throw(Valuable):
|
||||
pass
|
||||
|
||||
|
||||
def ThrowParser(input):
|
||||
return Parser.allOf(
|
||||
Parser.terminal(TokenType.THROW),
|
||||
Parser.doAssert(ExpressionParser, "error message as string"),
|
||||
createNode=lambda throw, message: Throw.withValue(message, throw.pos),
|
||||
name="throw"
|
||||
)(input)
|
||||
@@ -1,17 +1,19 @@
|
||||
from smnp.error.function import FunctionNotFoundException, MethodNotFoundException, IllegalFunctionInvocationException
|
||||
from smnp.error.runtime import RuntimeException
|
||||
from smnp.function.tools import argsTypesToString
|
||||
from smnp.runtime.evaluators.function import BodyEvaluator
|
||||
from smnp.runtime.evaluators.function import BodyEvaluator, Return
|
||||
from smnp.type.model import Type
|
||||
|
||||
|
||||
class Environment():
|
||||
def __init__(self, scopes, functions, methods):
|
||||
def __init__(self, scopes, functions, methods, source):
|
||||
self.scopes = scopes
|
||||
self.functions = functions
|
||||
self.methods = methods
|
||||
self.customFunctions = []
|
||||
self.customMethods = []
|
||||
self.callStack = []
|
||||
self.source = source
|
||||
|
||||
def invokeMethod(self, object, name, args):
|
||||
builtinMethodResult = self._invokeBuiltinMethod(object, name, args)
|
||||
@@ -38,10 +40,15 @@ class Environment():
|
||||
if method.typeSignature.check([object])[0] and method.name == name: #Todo sprawdzic sygnature typu
|
||||
signatureCheckresult = method.signature.check(args)
|
||||
if signatureCheckresult[0]:
|
||||
self.scopes.append({argName: argValue for argName, argValue in zip(method.arguments, list(signatureCheckresult[1:]))})
|
||||
self.scopes.append(method.defaultArgs)
|
||||
self.scopes[-1].update({argName: argValue for argName, argValue in zip(method.arguments, list(signatureCheckresult[1:]))})
|
||||
self.scopes[-1][method.alias] = object
|
||||
self.callStack.append(CallStackItem(name))
|
||||
result = BodyEvaluator.evaluate(method.body, self).value # TODO check if it isn't necessary to verify 'result' attr of EvaluatioNResult
|
||||
result = Type.void()
|
||||
try:
|
||||
BodyEvaluator.evaluate(method.body, self).value # TODO check if it isn't necessary to verify 'result' attr of EvaluatioNResult
|
||||
except Return as r:
|
||||
result = r.value
|
||||
self.callStack.pop(-1)
|
||||
self.scopes.pop(-1)
|
||||
return (True, result)
|
||||
@@ -74,20 +81,27 @@ class Environment():
|
||||
if function.name == name:
|
||||
signatureCheckresult = function.signature.check(args)
|
||||
if signatureCheckresult[0]:
|
||||
self.scopes.append({ argName: argValue for argName, argValue in zip(function.arguments, list(signatureCheckresult[1:])) })
|
||||
self.appendScope(function.defaultArgs)
|
||||
appendedScopeIndex = len(self.scopes)-1
|
||||
self.scopes[-1].update({ argName: argValue for argName, argValue in zip(function.arguments, list(signatureCheckresult[1:])) })
|
||||
self.callStack.append(CallStackItem(name))
|
||||
result = BodyEvaluator.evaluate(function.body, self).value #TODO check if it isn't necessary to verify 'result' attr of EvaluatioNResult
|
||||
result = Type.void()
|
||||
try:
|
||||
BodyEvaluator.evaluate(function.body, self).value #TODO check if it isn't necessary to verify 'result' attr of EvaluatioNResult
|
||||
except Return as r:
|
||||
result = r.value
|
||||
self.callStack.pop(-1)
|
||||
self.scopes.pop(-1)
|
||||
self.popScope(mergeVariables=False)
|
||||
self.removeScopesAfter(appendedScopeIndex)
|
||||
return (True, result)
|
||||
raise IllegalFunctionInvocationException(f"{function.name}{function.signature.string}", f"{name}{argsTypesToString(args)}")
|
||||
return (False, None)
|
||||
|
||||
def addCustomFunction(self, name, signature, arguments, body):
|
||||
def addCustomFunction(self, name, signature, arguments, body, defaultArguments):
|
||||
if len([fun for fun in self.functions + self.customFunctions if fun.name == name]) > 0:
|
||||
raise RuntimeException(f"Cannot redeclare function '{name}'", None)
|
||||
|
||||
self.customFunctions.append(CustomFunction(name, signature, arguments, body))
|
||||
self.customFunctions.append(CustomFunction(name, signature, arguments, body, defaultArguments))
|
||||
|
||||
# TODO:
|
||||
# There is still problem with checking existing of generic types, like lists:
|
||||
@@ -98,14 +112,14 @@ class Environment():
|
||||
# function foo() { return 2 }
|
||||
# }
|
||||
# Then calling [1, 2, 3, 4].foo() will produce 1, when the second method is more suitable
|
||||
def addCustomMethod(self, typeSignature, alias, name, signature, arguments, body):
|
||||
def addCustomMethod(self, typeSignature, alias, name, signature, arguments, body, defaultArguments):
|
||||
if len([m for m in self.methods if m.name == name and m.signature.matchers[0] == typeSignature.matchers[0]]) > 0:
|
||||
raise RuntimeException(f"Cannot redeclare method '{name}' for type '{typeSignature.matchers[0]}'", None)
|
||||
|
||||
if len([m for m in self.customMethods if m.name == name and m.typeSignature.matchers[0] == typeSignature.matchers[0]]) > 0:
|
||||
raise RuntimeException(f"Cannot redeclare method '{name}' for type '{typeSignature.matchers[0]}'", None)
|
||||
|
||||
self.customMethods.append(CustomMethod(typeSignature, alias, name, signature, arguments, body))
|
||||
self.customMethods.append(CustomMethod(typeSignature, alias, name, signature, arguments, body, defaultArguments))
|
||||
|
||||
def findVariable(self, name, type=None, pos=None):
|
||||
for scope in reversed(self.scopes):
|
||||
@@ -128,6 +142,20 @@ class Environment():
|
||||
else:
|
||||
return scope
|
||||
|
||||
def appendScope(self, variables=None):
|
||||
if variables is None:
|
||||
variables = {}
|
||||
|
||||
self.scopes.append(variables)
|
||||
|
||||
def popScope(self, mergeVariables=True):
|
||||
lastScope = self.scopes.pop(-1)
|
||||
if mergeVariables:
|
||||
self.scopes[-1].update(lastScope)
|
||||
|
||||
def removeScopesAfter(self, index):
|
||||
del self.scopes[index:]
|
||||
|
||||
def scopesToString(self):
|
||||
return "Scopes:\n" + ("\n".join([ f" [{i}]: {scope}" for i, scope in enumerate(self.scopes) ]))
|
||||
|
||||
@@ -162,22 +190,23 @@ class Environment():
|
||||
class CallStackItem:
|
||||
def __init__(self, function):
|
||||
self.function = function
|
||||
self.value = None
|
||||
|
||||
|
||||
class CustomFunction:
|
||||
def __init__(self, name, signature, arguments, body):
|
||||
def __init__(self, name, signature, arguments, body, defaultArgs):
|
||||
self.name = name
|
||||
self.signature = signature
|
||||
self.arguments = arguments
|
||||
self.body = body
|
||||
self.defaultArgs = defaultArgs
|
||||
|
||||
|
||||
class CustomMethod:
|
||||
def __init__(self, typeSignature, alias, name, signature, arguments, body):
|
||||
def __init__(self, typeSignature, alias, name, signature, arguments, body, defaultArgs):
|
||||
self.typeSignature = typeSignature
|
||||
self.alias = alias
|
||||
self.name = name
|
||||
self.signature = signature
|
||||
self.arguments = arguments
|
||||
self.body = body
|
||||
self.body = body
|
||||
self.defaultArgs = defaultArgs
|
||||
@@ -1,7 +1,3 @@
|
||||
from smnp.environment.environment import Environment
|
||||
from smnp.module import functions, methods
|
||||
|
||||
|
||||
def createEnvironment():
|
||||
return Environment([{}], functions, methods)
|
||||
return
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ class SmnpException(Exception):
|
||||
def __init__(self, msg, pos):
|
||||
self.msg = msg
|
||||
self.pos = pos
|
||||
self.file = None
|
||||
|
||||
def _title(self):
|
||||
pass
|
||||
@@ -10,7 +11,10 @@ class SmnpException(Exception):
|
||||
return ""
|
||||
|
||||
def _position(self):
|
||||
return "" if self.pos is None else f" [line {self.pos[0]+1}, col {self.pos[1]+1}]"
|
||||
return "" if self.pos is None else f"[line {self.pos[0]+1}, col {self.pos[1]+1}]"
|
||||
|
||||
def _file(self):
|
||||
return "" if self.file is None else f"File: {self.file}"
|
||||
|
||||
def message(self):
|
||||
return f"{self._title()}{self._position()}:\n{self.msg}\n{self._postMessage()}"
|
||||
return f"{self._title()}\n{self._file()} {self._position()}\n\n{self.msg}\n{self._postMessage()}"
|
||||
|
||||
12
smnp/error/custom.py
Normal file
12
smnp/error/custom.py
Normal file
@@ -0,0 +1,12 @@
|
||||
from smnp.error.runtime import RuntimeException
|
||||
|
||||
|
||||
class CustomException(RuntimeException):
|
||||
def __init__(self, message, pos):
|
||||
super().__init__(message, pos)
|
||||
|
||||
def _title(self):
|
||||
return "Execution Error"
|
||||
|
||||
def _postMessage(self):
|
||||
return "\n" + self.environment.callStackToString() if len(self.environment.callStack) > 0 else ""
|
||||
@@ -12,6 +12,9 @@ class Signature:
|
||||
|
||||
def varargSignature(varargMatcher, *basicSignature, wrapVarargInValue=False):
|
||||
def check(args):
|
||||
if any([ matcher.optional for matcher in [ varargMatcher, *basicSignature ]]):
|
||||
raise RuntimeError("Vararg signature can't have optional arguments")
|
||||
|
||||
if len(basicSignature) > len(args):
|
||||
return doesNotMatchVararg(basicSignature)
|
||||
|
||||
@@ -38,7 +41,7 @@ def doesNotMatchVararg(basicSignature):
|
||||
|
||||
def signature(*signature):
|
||||
def check(args):
|
||||
if len(signature) != len(args):
|
||||
if len(args) > len(signature) or len(args) < len([ matcher for matcher in signature if not matcher.optional ]):
|
||||
return doesNotMatch(signature)
|
||||
|
||||
for s, a in zip(signature, args):
|
||||
@@ -52,6 +55,12 @@ def signature(*signature):
|
||||
return Signature(check, string, signature)
|
||||
|
||||
|
||||
def optional(matcher):
|
||||
matcher.optional = True
|
||||
matcher.string += "?"
|
||||
return matcher
|
||||
|
||||
|
||||
def doesNotMatch(sign):
|
||||
return (False, *[None for n in sign])
|
||||
|
||||
|
||||
@@ -5,5 +5,5 @@ from smnp.program.interpreter import Interpreter
|
||||
|
||||
def loadStandardLibrary():
|
||||
mainSource = resource_string('smnp.library.code', 'main.mus').decode("utf-8")
|
||||
env = Interpreter.interpretString(mainSource)
|
||||
env = Interpreter.interpretString(mainSource, "<stdlib>")
|
||||
return env
|
||||
|
||||
@@ -9,9 +9,6 @@ def main():
|
||||
try:
|
||||
stdLibraryEnv = loadStandardLibrary()
|
||||
Interpreter.interpretFile(sys.argv[1], printTokens=False, printAst=False, execute=True, baseEnvironment=stdLibraryEnv)
|
||||
#draft()
|
||||
#tokens = tokenize(['function a(b...) { x+y}'])
|
||||
#FunctionDefinitionParser(tokens).node.print()
|
||||
|
||||
except SmnpException as e:
|
||||
print(e.message())
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from smnp.module import system, mic, note, iterable, sound, synth, string, util
|
||||
from smnp.module import system, mic, note, iterable, sound, synth, string, util, integer, float
|
||||
|
||||
functions = [ *system.functions, *mic.functions, *note.functions, *iterable.functions, *sound.functions, *synth.functions, *string.functions, *util.functions ]
|
||||
methods = [ *system.methods, *mic.methods, *note.methods, *iterable.methods, *sound.methods, *synth.methods, *string.functions, *util.methods ]
|
||||
functions = [ *system.functions, *mic.functions, *note.functions, *iterable.functions, *sound.functions, *synth.functions, *string.functions, *util.functions, *integer.functions, *float.functions ]
|
||||
methods = [ *system.methods, *mic.methods, *note.methods, *iterable.methods, *sound.methods, *synth.methods, *string.methods, *util.methods, *integer.methods, *float.methods ]
|
||||
4
smnp/module/float/__init__.py
Normal file
4
smnp/module/float/__init__.py
Normal file
@@ -0,0 +1,4 @@
|
||||
from smnp.module.float.function import float
|
||||
|
||||
functions = [ float.function ]
|
||||
methods = []
|
||||
0
smnp/module/float/function/__init__.py
Normal file
0
smnp/module/float/function/__init__.py
Normal file
26
smnp/module/float/function/float.py
Normal file
26
smnp/module/float/function/float.py
Normal file
@@ -0,0 +1,26 @@
|
||||
from smnp.function.model import CombinedFunction, Function
|
||||
from smnp.function.signature import signature
|
||||
from smnp.type.model import Type
|
||||
from smnp.type.signature.matcher.type import ofType
|
||||
|
||||
_signature1 = signature(ofType(Type.INTEGER))
|
||||
def _function1(env, value):
|
||||
return Type.float(float(value.value))
|
||||
|
||||
|
||||
_signature2 = signature(ofType(Type.STRING))
|
||||
def _function2(env, value):
|
||||
return Type.float(float(value.value))
|
||||
|
||||
|
||||
_signature3 = signature(ofType(Type.FLOAT))
|
||||
def _function3(env, value):
|
||||
return value
|
||||
|
||||
|
||||
function = CombinedFunction(
|
||||
'Float',
|
||||
Function(_signature1, _function1),
|
||||
Function(_signature2, _function2),
|
||||
Function(_signature3, _function3),
|
||||
)
|
||||
4
smnp/module/integer/__init__.py
Normal file
4
smnp/module/integer/__init__.py
Normal file
@@ -0,0 +1,4 @@
|
||||
from smnp.module.integer.function import integer
|
||||
|
||||
functions = [ integer.function ]
|
||||
methods = []
|
||||
0
smnp/module/integer/function/__init__.py
Normal file
0
smnp/module/integer/function/__init__.py
Normal file
25
smnp/module/integer/function/integer.py
Normal file
25
smnp/module/integer/function/integer.py
Normal file
@@ -0,0 +1,25 @@
|
||||
from smnp.function.model import CombinedFunction, Function
|
||||
from smnp.function.signature import signature
|
||||
from smnp.type.model import Type
|
||||
from smnp.type.signature.matcher.type import ofType
|
||||
|
||||
_signature1 = signature(ofType(Type.FLOAT))
|
||||
def _function1(env, value):
|
||||
return Type.integer(int(value.value))
|
||||
|
||||
|
||||
_signature2 = signature(ofType(Type.STRING))
|
||||
def _function2(env, value):
|
||||
return Type.integer(int(value.value))
|
||||
|
||||
|
||||
_signature3 = signature(ofType(Type.INTEGER))
|
||||
def _function3(env, value):
|
||||
return value
|
||||
|
||||
function = CombinedFunction(
|
||||
'Integer',
|
||||
Function(_signature1, _function1),
|
||||
Function(_signature2, _function2),
|
||||
Function(_signature3, _function3),
|
||||
)
|
||||
@@ -1,4 +1,4 @@
|
||||
from smnp.module.iterable.function import combine, map, range, get
|
||||
from smnp.module.iterable.function import map, get
|
||||
|
||||
functions = [ combine.function, map.function, range.function ]
|
||||
functions = [ map.function ]
|
||||
methods = [ get.function ]
|
||||
@@ -1,18 +0,0 @@
|
||||
from functools import reduce
|
||||
|
||||
from smnp.function.model import Function
|
||||
from smnp.function.signature import varargSignature
|
||||
from smnp.type.model import Type
|
||||
from smnp.type.signature.matcher.type import ofTypes
|
||||
|
||||
_signature = varargSignature(ofTypes(Type.LIST))
|
||||
def _function(env, vararg):
|
||||
if len(vararg) == 1:
|
||||
return vararg[0]
|
||||
|
||||
combined = reduce(lambda x, y: x.value + y.value, vararg)
|
||||
return Type.list(combined)
|
||||
|
||||
|
||||
function = Function(_signature, _function, 'combine')
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
from smnp.function.model import CombinedFunction, Function
|
||||
from smnp.function.signature import signature
|
||||
from smnp.note.model import Note
|
||||
from smnp.type.model import Type
|
||||
from smnp.type.signature.matcher.type import ofType
|
||||
|
||||
_signature1 = signature(ofType(Type.INTEGER))
|
||||
def _function1(env, upper):
|
||||
return Type.list([ Type.integer(i) for i in range(upper.value + 1)])
|
||||
|
||||
|
||||
_signature2 = signature(ofType(Type.INTEGER), ofType(Type.INTEGER))
|
||||
def _function2(env, lower, upper):
|
||||
return Type.list([ Type.integer(i) for i in range(lower.value, upper.value + 1)])
|
||||
|
||||
|
||||
_signature3 = signature(ofType(Type.INTEGER), ofType(Type.INTEGER), ofType(Type.INTEGER))
|
||||
def _function3(env, lower, upper, step):
|
||||
return Type.list([ Type.integer(i) for i in range(lower.value, upper.value + 1, step.value)])
|
||||
|
||||
|
||||
_signature4 = signature(ofType(Type.NOTE), ofType(Type.NOTE))
|
||||
def _function4(env, lower, upper):
|
||||
return Type.list([Type.note(n) for n in Note.range(lower.value, upper.value)])
|
||||
|
||||
|
||||
# TODO
|
||||
# signature5 = range(note lower, note upper, integer step) OR step = "diatonic" | "chromatic" | "augmented" | "diminish"
|
||||
|
||||
function = CombinedFunction(
|
||||
'range',
|
||||
Function(_signature1, _function1),
|
||||
Function(_signature2, _function2),
|
||||
Function(_signature3, _function3),
|
||||
Function(_signature4, _function4),
|
||||
)
|
||||
@@ -1,4 +1,4 @@
|
||||
from smnp.module.note.function import tuplet, transpose, semitones, octave, duration, interval
|
||||
from smnp.module.note.function import note
|
||||
|
||||
functions = [ semitones.function, interval.function, transpose.function, tuplet.function ]
|
||||
methods = [ duration.function, octave.function ]
|
||||
functions = [ note.function ]
|
||||
methods = []
|
||||
@@ -1,11 +0,0 @@
|
||||
from smnp.function.model import Function
|
||||
from smnp.function.signature import signature
|
||||
from smnp.type.model import Type
|
||||
from smnp.type.signature.matcher.type import ofType
|
||||
|
||||
_signature = signature(ofType(Type.NOTE), ofType(Type.INTEGER))
|
||||
def _function(env, note, duration):
|
||||
return Type.note(note.value.withDuration(duration.value))
|
||||
|
||||
|
||||
function = Function(_signature, _function, 'withDuration')
|
||||
@@ -1,27 +0,0 @@
|
||||
from smnp.function.model import Function, CombinedFunction
|
||||
from smnp.function.signature import varargSignature
|
||||
from smnp.note.interval import intervalToString
|
||||
from smnp.note.model import Note
|
||||
from smnp.type.model import Type
|
||||
from smnp.type.signature.matcher.list import listOf
|
||||
from smnp.type.signature.matcher.type import ofTypes
|
||||
|
||||
_signature1 = varargSignature(ofTypes(Type.NOTE, Type.INTEGER))
|
||||
def _function1(env, vararg):
|
||||
withoutPauses = [note.value for note in vararg if note.type == Type.NOTE]
|
||||
if len(withoutPauses) < 2:
|
||||
return Type.list([])
|
||||
semitones = [Note.checkInterval(withoutPauses[i-1], withoutPauses[i]) for i in range(1, len(withoutPauses))]
|
||||
return Type.list([Type.string(intervalToString(s)) for s in semitones]).decompose()
|
||||
|
||||
|
||||
_signature2 = varargSignature(listOf(Type.NOTE, Type.INTEGER))
|
||||
def _function2(env, vararg):
|
||||
return Type.list([_function1(env, arg.value) for arg in vararg]).decompose()
|
||||
|
||||
|
||||
function = CombinedFunction(
|
||||
'interval',
|
||||
Function(_signature1, _function1),
|
||||
Function(_signature2, _function2)
|
||||
)
|
||||
11
smnp/module/note/function/note.py
Normal file
11
smnp/module/note/function/note.py
Normal file
@@ -0,0 +1,11 @@
|
||||
from smnp.function.model import Function
|
||||
from smnp.function.signature import signature
|
||||
from smnp.note.model import Note
|
||||
from smnp.type.model import Type
|
||||
from smnp.type.signature.matcher.type import ofType
|
||||
|
||||
_signature = signature(ofType(Type.STRING), ofType(Type.INTEGER), ofType(Type.INTEGER), ofType(Type.BOOL))
|
||||
def _function(env, note, octave, duration, dot):
|
||||
return Type.note(Note(note.value, octave.value, duration.value, dot.value))
|
||||
|
||||
function = Function(_signature, _function, 'Note')
|
||||
@@ -1,11 +0,0 @@
|
||||
from smnp.function.model import Function
|
||||
from smnp.function.signature import signature
|
||||
from smnp.type.model import Type
|
||||
from smnp.type.signature.matcher.type import ofType
|
||||
|
||||
_signature = signature(ofType(Type.NOTE), ofType(Type.INTEGER))
|
||||
def _function(env, note, octave):
|
||||
return Type.note(note.value.withOctave(octave.value))
|
||||
|
||||
|
||||
function = Function(_signature, _function, 'withOctave')
|
||||
@@ -1,25 +0,0 @@
|
||||
from smnp.function.model import Function, CombinedFunction
|
||||
from smnp.function.signature import varargSignature
|
||||
from smnp.note.model import Note
|
||||
from smnp.type.model import Type
|
||||
from smnp.type.signature.matcher.list import listOf
|
||||
from smnp.type.signature.matcher.type import ofTypes
|
||||
|
||||
_signature1 = varargSignature(ofTypes(Type.NOTE, Type.INTEGER))
|
||||
def _function1(env, vararg):
|
||||
withoutPauses = [note.value for note in vararg if note.type == Type.NOTE]
|
||||
if len(withoutPauses) < 2:
|
||||
return Type.list([])
|
||||
return Type.list([Type.integer(Note.checkInterval(withoutPauses[i-1], withoutPauses[i])) for i in range(1, len(withoutPauses))]).decompose()
|
||||
|
||||
|
||||
_signature2 = varargSignature(listOf(Type.NOTE, Type.INTEGER))
|
||||
def _function2(env, vararg):
|
||||
return Type.list([_function1(env, arg.value) for arg in vararg]).decompose()
|
||||
|
||||
|
||||
function = CombinedFunction(
|
||||
"semitones",
|
||||
Function(_signature1, _function1),
|
||||
Function(_signature2, _function2),
|
||||
)
|
||||
@@ -1,22 +0,0 @@
|
||||
from smnp.function.model import CombinedFunction, Function
|
||||
from smnp.function.signature import varargSignature
|
||||
from smnp.type.model import Type
|
||||
from smnp.type.signature.matcher.list import listOf
|
||||
from smnp.type.signature.matcher.type import ofTypes
|
||||
|
||||
_signature1 = varargSignature(ofTypes(Type.INTEGER, Type.NOTE), ofTypes(Type.INTEGER))
|
||||
def _function1(env, value, vararg):
|
||||
transposed = [Type.note(arg.value.transpose(value.value)) if arg.type == Type.NOTE else arg for arg in vararg]
|
||||
return Type.list(transposed).decompose()
|
||||
|
||||
|
||||
_signature2 = varargSignature(listOf(Type.INTEGER, Type.NOTE), ofTypes(Type.INTEGER))
|
||||
def _function2(env, value, vararg):
|
||||
return Type.list([_function1(env, value, arg.value) for arg in vararg]).decompose()
|
||||
|
||||
|
||||
function = CombinedFunction(
|
||||
'transpose',
|
||||
Function(_signature1, _function1),
|
||||
Function(_signature2, _function2)
|
||||
)
|
||||
@@ -1,23 +0,0 @@
|
||||
from smnp.function.model import CombinedFunction, Function
|
||||
from smnp.function.signature import signature, varargSignature
|
||||
from smnp.type.model import Type
|
||||
from smnp.type.signature.matcher.list import listOf
|
||||
from smnp.type.signature.matcher.type import ofTypes
|
||||
|
||||
_signature1 = varargSignature(ofTypes(Type.NOTE), ofTypes(Type.INTEGER), ofTypes(Type.INTEGER))
|
||||
def _function1(env, n, m, vararg):
|
||||
t = [Type.note(arg.value.withDuration(int(arg.value.duration * n.value / m.value))) for arg in vararg]
|
||||
return Type.list(t).decompose()
|
||||
|
||||
|
||||
|
||||
_signature2 = signature(ofTypes(Type.INTEGER), ofTypes(Type.INTEGER), listOf(Type.NOTE))
|
||||
def _function2(env, n, m, notes):
|
||||
return _function1(env, n, m, notes.value)
|
||||
|
||||
|
||||
function = CombinedFunction(
|
||||
'tuplet',
|
||||
Function(_signature1, _function1),
|
||||
Function(_signature2, _function2)
|
||||
)
|
||||
@@ -1,4 +1,4 @@
|
||||
from smnp.module.string.function import concat
|
||||
from smnp.module.string.function import stringify
|
||||
|
||||
functions = [ concat.function ]
|
||||
methods = []
|
||||
functions = []
|
||||
methods = [ stringify.function ]
|
||||
@@ -1,11 +0,0 @@
|
||||
from smnp.function.model import Function
|
||||
from smnp.function.signature import varargSignature
|
||||
from smnp.type.model import Type
|
||||
from smnp.type.signature.matcher.type import ofType
|
||||
|
||||
_signature = varargSignature(ofType(Type.STRING))
|
||||
def _function(env, vararg):
|
||||
return Type.string("".join([ arg.value for arg in vararg ]))
|
||||
|
||||
|
||||
function = Function(_signature, _function, 'concat')
|
||||
10
smnp/module/string/function/stringify.py
Normal file
10
smnp/module/string/function/stringify.py
Normal file
@@ -0,0 +1,10 @@
|
||||
from smnp.function.model import Function
|
||||
from smnp.function.signature import signature
|
||||
from smnp.type.model import Type
|
||||
from smnp.type.signature.matcher.type import allTypes
|
||||
|
||||
_signature = signature(allTypes())
|
||||
def _function(env, object):
|
||||
return Type.string(object.stringify())
|
||||
|
||||
function = Function(_signature, _function, 'toString')
|
||||
@@ -1,4 +1,4 @@
|
||||
from smnp.module.synth.function import synth, pause
|
||||
from smnp.module.synth.function import synth, pause, plot, compile
|
||||
|
||||
functions = [ synth.function, pause.function ]
|
||||
functions = [ synth.function, pause.function, plot.function, compile.function ]
|
||||
methods = []
|
||||
141
smnp/module/synth/function/compile.py
Normal file
141
smnp/module/synth/function/compile.py
Normal file
@@ -0,0 +1,141 @@
|
||||
from smnp.error.runtime import RuntimeException
|
||||
from smnp.function.model import Function, CombinedFunction
|
||||
from smnp.function.signature import varargSignature
|
||||
from smnp.module.synth.lib.wave import compilePolyphony
|
||||
|
||||
from smnp.type.model import Type
|
||||
from smnp.type.signature.matcher.list import listOf
|
||||
from smnp.type.signature.matcher.type import ofTypes, ofType
|
||||
|
||||
|
||||
DEFAULT_BPM = 120
|
||||
DEFAULT_OVERTONES = [0.4, 0.3, 0.1, 0.1, 0.1]
|
||||
DEFAULT_DECAY = 4
|
||||
DEFAULT_ATTACK = 100
|
||||
|
||||
|
||||
def getBpm(config):
|
||||
key = Type.string("bpm")
|
||||
if key in config.value:
|
||||
bpm = config.value[key]
|
||||
if bpm.type != Type.INTEGER or bpm.value <= 0:
|
||||
raise RuntimeException("The 'bpm' property must be positive integer", None)
|
||||
|
||||
return bpm.value
|
||||
|
||||
return DEFAULT_BPM
|
||||
|
||||
|
||||
def getOvertones(config):
|
||||
key = Type.string("overtones")
|
||||
if key in config.value:
|
||||
overtones = config.value[key]
|
||||
rawOvertones = [overtone.value for overtone in overtones.value]
|
||||
if overtones.type != Type.LIST or not all(overtone.type in [Type.FLOAT, Type.INTEGER] for overtone in overtones.value):
|
||||
raise RuntimeException("The 'overtones' property must be list of floats", None)
|
||||
|
||||
if len(rawOvertones) < 1:
|
||||
raise RuntimeException("The 'overtones' property must contain one overtone at least", None)
|
||||
|
||||
if any(overtone < 0 for overtone in rawOvertones):
|
||||
raise RuntimeException("The 'overtones' property mustn't contain negative values", None)
|
||||
|
||||
if sum(rawOvertones) > 1.0:
|
||||
raise RuntimeException("The 'overtones' property must contain overtones which sum is not greater than 1.0", None)
|
||||
|
||||
return rawOvertones
|
||||
|
||||
return DEFAULT_OVERTONES
|
||||
|
||||
|
||||
def getDecay(config):
|
||||
key = Type.string("decay")
|
||||
if key in config.value:
|
||||
decay = config.value[key]
|
||||
if not decay.type in [Type.INTEGER, Type.FLOAT] or decay.value < 0:
|
||||
raise RuntimeException("The 'decay' property must be non-negative integer or float", None)
|
||||
|
||||
return decay.value
|
||||
|
||||
return DEFAULT_DECAY
|
||||
|
||||
|
||||
def getAttack(config):
|
||||
key = Type.string("attack")
|
||||
if key in config.value:
|
||||
attack = config.value[key]
|
||||
if not attack.type in [Type.INTEGER, Type.FLOAT] or attack.value < 0:
|
||||
raise RuntimeException("The 'attack' property must be non-negative integer or float", None)
|
||||
|
||||
return attack.value
|
||||
|
||||
return DEFAULT_ATTACK
|
||||
|
||||
|
||||
class Config:
|
||||
def __init__(self, bpm, overtones, decay, attack):
|
||||
self.bpm = bpm
|
||||
self.overtones = overtones
|
||||
self.decay = decay
|
||||
self.attack = attack
|
||||
|
||||
@staticmethod
|
||||
def default():
|
||||
return Config(DEFAULT_BPM, DEFAULT_OVERTONES, DEFAULT_DECAY, DEFAULT_ATTACK)
|
||||
|
||||
|
||||
_signature1 = varargSignature(listOf(Type.NOTE, Type.INTEGER))
|
||||
def _function1(env, notes):
|
||||
return Type.list([Type.float(float(m)) for m in __function1(notes)])
|
||||
|
||||
|
||||
def __function1(notes):
|
||||
return compilePolyphony([note.value for note in notes], Config.default())
|
||||
|
||||
|
||||
_signature2 = varargSignature(ofTypes(Type.NOTE, Type.INTEGER))
|
||||
def _function2(env, notes):
|
||||
return Type.list([Type.float(float(m)) for m in __function2(notes)])
|
||||
|
||||
|
||||
def __function2(notes):
|
||||
return compilePolyphony([ notes ], Config.default())
|
||||
|
||||
|
||||
_signature3 = varargSignature(listOf(Type.NOTE, Type.INTEGER), ofType(Type.MAP))
|
||||
def _function3(env, config, notes):
|
||||
return Type.list([ Type.float(float(m)) for m in __function3(config, notes) ])
|
||||
|
||||
|
||||
def __function3(config, notes):
|
||||
rawNotes = [note.value for note in notes]
|
||||
|
||||
bpm = getBpm(config)
|
||||
overtones = getOvertones(config)
|
||||
decay = getDecay(config)
|
||||
attack = getAttack(config)
|
||||
|
||||
return compilePolyphony(rawNotes, Config(bpm, overtones, decay, attack))
|
||||
|
||||
|
||||
_signature4 = varargSignature(ofTypes(Type.NOTE, Type.INTEGER), ofType(Type.MAP))
|
||||
def _function4(env, config, notes):
|
||||
return Type.list([ Type.float(float(m)) for m in __function4(config, notes) ])
|
||||
|
||||
|
||||
def __function4(config, notes):
|
||||
bpm = getBpm(config)
|
||||
overtones = getOvertones(config)
|
||||
decay = getDecay(config)
|
||||
attack = getAttack(config)
|
||||
|
||||
return compilePolyphony([ notes ], Config(bpm, overtones, decay, attack))
|
||||
|
||||
|
||||
function = CombinedFunction(
|
||||
'wave',
|
||||
Function(_signature1, _function1),
|
||||
Function(_signature2, _function2),
|
||||
Function(_signature3, _function3),
|
||||
Function(_signature4, _function4),
|
||||
)
|
||||
@@ -1,13 +1,13 @@
|
||||
from smnp.function.model import Function
|
||||
from smnp.function.signature import signature
|
||||
from smnp.module.synth.lib import player
|
||||
from smnp.module.synth.lib.wave import pause
|
||||
from smnp.type.model import Type
|
||||
from smnp.type.signature.matcher.type import ofTypes
|
||||
|
||||
_signature = signature(ofTypes(Type.INTEGER))
|
||||
def _function(env, value):
|
||||
bpm = env.findVariable('bpm')
|
||||
player.pause(value.value, bpm.value)
|
||||
pause(value.value, bpm.value)
|
||||
|
||||
|
||||
function = Function(_signature, _function, 'pause')
|
||||
13
smnp/module/synth/function/plot.py
Normal file
13
smnp/module/synth/function/plot.py
Normal file
@@ -0,0 +1,13 @@
|
||||
from smnp.function.model import Function
|
||||
from smnp.function.signature import signature
|
||||
from smnp.module.synth.lib.wave import plot
|
||||
from smnp.type.model import Type
|
||||
from smnp.type.signature.matcher.list import listOf
|
||||
|
||||
_signature = signature(listOf(Type.FLOAT))
|
||||
def _function(env, wave):
|
||||
rawWave = [ m.value for m in wave.value ]
|
||||
plot(rawWave)
|
||||
|
||||
|
||||
function = Function(_signature, _function, 'plotWave')
|
||||
@@ -1,25 +1,47 @@
|
||||
from smnp.function.model import CombinedFunction, Function
|
||||
from smnp.function.model import Function, CombinedFunction
|
||||
from smnp.function.signature import varargSignature
|
||||
from smnp.module.synth.lib.player import playNotes
|
||||
from smnp.module.synth.function import compile
|
||||
from smnp.module.synth.lib.wave import play
|
||||
from smnp.type.model import Type
|
||||
from smnp.type.signature.matcher.list import listOf
|
||||
from smnp.type.signature.matcher.type import ofTypes
|
||||
from smnp.type.signature.matcher.type import ofTypes, ofType
|
||||
|
||||
_signature1 = varargSignature(ofTypes(Type.NOTE, Type.INTEGER))
|
||||
def _function1(env, vararg):
|
||||
notes = [arg.value for arg in vararg]
|
||||
bpm = env.findVariable('bpm')
|
||||
playNotes(notes, bpm.value)
|
||||
_signature1 = varargSignature(listOf(Type.NOTE, Type.INTEGER))
|
||||
def _function1(env, notes):
|
||||
wave = compile.__function1(notes)
|
||||
play(wave)
|
||||
|
||||
|
||||
_signature2 = varargSignature(listOf(Type.NOTE, Type.INTEGER))
|
||||
def _function2(env, vararg):
|
||||
for arg in vararg:
|
||||
_function1(env, arg.value)
|
||||
_signature2 = varargSignature(ofTypes(Type.NOTE, Type.INTEGER))
|
||||
def _function2(env, notes):
|
||||
wave = compile.__function2(notes)
|
||||
play(wave)
|
||||
|
||||
|
||||
_signature3 = varargSignature(listOf(Type.NOTE, Type.INTEGER), ofType(Type.MAP))
|
||||
def _function3(env, config, notes):
|
||||
wave = compile.__function3(config, notes)
|
||||
play(wave)
|
||||
|
||||
|
||||
_signature4 = varargSignature(ofTypes(Type.NOTE, Type.INTEGER), ofType(Type.MAP))
|
||||
def _function4(env, config, notes):
|
||||
wave = compile.__function4(config, notes)
|
||||
play(wave)
|
||||
|
||||
|
||||
_signature5 = varargSignature(listOf(Type.FLOAT))
|
||||
def _function5(env, waves):
|
||||
for wave in waves:
|
||||
rawWave = [m.value for m in wave.value]
|
||||
play(rawWave)
|
||||
|
||||
|
||||
function = CombinedFunction(
|
||||
'synth',
|
||||
Function(_signature1, _function1),
|
||||
Function(_signature2, _function2)
|
||||
)
|
||||
Function(_signature2, _function2),
|
||||
Function(_signature3, _function3),
|
||||
Function(_signature4, _function4),
|
||||
Function(_signature5, _function5)
|
||||
)
|
||||
@@ -1,24 +0,0 @@
|
||||
import time
|
||||
|
||||
from smnp.module.synth.lib.wave import sine
|
||||
from smnp.note.model import Note
|
||||
|
||||
|
||||
def playNotes(notes, bpm):
|
||||
for note in notes:
|
||||
{
|
||||
Note: play,
|
||||
int: pause
|
||||
}[type(note)](note, bpm)
|
||||
|
||||
|
||||
def play(note, bpm):
|
||||
frequency = note.toFrequency()
|
||||
duration = 60 * 4 / note.duration / bpm
|
||||
duration *= 1.5 if note.dot else 1
|
||||
sine(frequency, duration)
|
||||
|
||||
|
||||
def pause(value, bpm):
|
||||
time.sleep(60 * 4 / value / bpm)
|
||||
|
||||
@@ -1,12 +1,78 @@
|
||||
import time
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import sounddevice as sd
|
||||
|
||||
from smnp.type.model import Type
|
||||
|
||||
FS = 44100
|
||||
|
||||
|
||||
def pause(value, bpm):
|
||||
time.sleep(60 * 4 / value / bpm)
|
||||
|
||||
|
||||
def plot(wave):
|
||||
X = np.arange(len(wave))
|
||||
plt.plot(X, wave)
|
||||
plt.show()
|
||||
|
||||
|
||||
def play(wave):
|
||||
sd.play(wave)
|
||||
time.sleep(len(wave) / FS)
|
||||
|
||||
|
||||
def compilePolyphony(notes, config):
|
||||
compiledLines = [1 / len(notes) * compileNotes(line, config) for line in notes]
|
||||
return sum(adjustSize(compiledLines))
|
||||
|
||||
|
||||
def adjustSize(compiledLines):
|
||||
maxSize = max(len(line) for line in compiledLines)
|
||||
|
||||
return [np.concatenate([line, np.zeros(maxSize - len(line))]) for line in compiledLines]
|
||||
|
||||
|
||||
def compileNotes(notes, config):
|
||||
dispatcher = {
|
||||
Type.NOTE: lambda note, overtones: sineForNote(note.value, config),
|
||||
Type.INTEGER: lambda note, overtones: silenceForPause(note.value, config)
|
||||
}
|
||||
|
||||
return np.concatenate([dispatcher[note.type](note, config) for note in notes])
|
||||
|
||||
|
||||
def sineForNote(note, config):
|
||||
frequency = note.toFrequency()
|
||||
duration = 60 * 4 / note.duration / config.bpm
|
||||
duration *= 1.5 if note.dot else 1
|
||||
return sound(frequency, duration, config)
|
||||
|
||||
|
||||
def sound(frequency, duration, config):
|
||||
return attack(decay(sum(overtone * sine((i+1) * frequency, duration) for i, overtone in enumerate(config.overtones) if overtone > 0), config), config)
|
||||
|
||||
|
||||
def decay(wave, config):
|
||||
magnitude = np.exp(-config.decay/len(wave) * np.arange(len(wave)))
|
||||
|
||||
return magnitude * wave
|
||||
|
||||
|
||||
def attack(wave, config):
|
||||
magnitude = -np.exp(-config.attack / len(wave) * np.arange(len(wave)))+1 \
|
||||
if config.attack > 0 \
|
||||
else np.ones(len(wave))
|
||||
|
||||
return magnitude * wave
|
||||
|
||||
|
||||
def sine(frequency, duration):
|
||||
samples = (np.sin(2*np.pi*np.arange(FS*duration)*frequency/FS)).astype(np.float32)
|
||||
sd.play(samples, FS)
|
||||
time.sleep(duration)
|
||||
return (np.sin(2 * np.pi * np.arange(FS * duration) * frequency / FS)).astype(np.float32)
|
||||
|
||||
|
||||
def silenceForPause(value, config):
|
||||
duration = 60 * 4 / value / config.bpm
|
||||
return np.zeros(int(FS * duration))
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from smnp.module.system.function import sleep, display, debug, exit, type
|
||||
from smnp.module.system.function import sleep, display, displayln, debug, exit, type, read
|
||||
|
||||
functions = [ debug.function, display.function, exit.function, sleep.function, type.function ]
|
||||
functions = [ debug.function, display.function, displayln.function, exit.function, sleep.function, type.function, read.function ]
|
||||
methods = []
|
||||
@@ -4,7 +4,7 @@ from smnp.type.signature.matcher.type import allTypes
|
||||
|
||||
_signature = varargSignature(allTypes())
|
||||
def _function(env, vararg):
|
||||
print("".join([arg.stringify() for arg in vararg]))
|
||||
print("".join([arg.stringify() for arg in vararg]), end="")
|
||||
|
||||
|
||||
function = Function(_signature, _function, 'print')
|
||||
10
smnp/module/system/function/displayln.py
Normal file
10
smnp/module/system/function/displayln.py
Normal file
@@ -0,0 +1,10 @@
|
||||
from smnp.function.model import Function
|
||||
from smnp.function.signature import varargSignature
|
||||
from smnp.type.signature.matcher.type import allTypes
|
||||
|
||||
_signature = varargSignature(allTypes())
|
||||
def _function(env, vararg):
|
||||
print("".join([arg.stringify() for arg in vararg]))
|
||||
|
||||
|
||||
function = Function(_signature, _function, 'println')
|
||||
@@ -1,3 +1,72 @@
|
||||
from smnp.error.runtime import RuntimeException
|
||||
from smnp.function.model import CombinedFunction, Function
|
||||
from smnp.function.signature import signature
|
||||
from smnp.token.tokenizers.bool import boolTokenizer
|
||||
from smnp.token.tokenizers.note import noteTokenizer
|
||||
from smnp.type.model import Type
|
||||
from smnp.type.signature.matcher.type import ofType
|
||||
|
||||
_signature1 = signature()
|
||||
def _function1(env):
|
||||
value = input()
|
||||
return Type.string(value)
|
||||
|
||||
|
||||
_signature2 = signature(ofType(Type.STRING))
|
||||
def _function2(env, prompt):
|
||||
print(prompt.value, end="")
|
||||
value = input()
|
||||
return Type.string(value)
|
||||
|
||||
|
||||
_signature3 = signature(ofType(Type.TYPE))
|
||||
def _function3(env, type):
|
||||
value = input()
|
||||
return getValueAccordingToType(value, type)
|
||||
|
||||
|
||||
def getValueAccordingToType(value, type):
|
||||
try:
|
||||
if type.value == Type.STRING:
|
||||
return Type.string(value)
|
||||
|
||||
if type.value == Type.INTEGER:
|
||||
return Type.integer(int(value))
|
||||
|
||||
if type.value == Type.BOOL:
|
||||
consumedChars, token = boolTokenizer(value, 0, 0)
|
||||
if consumedChars > 0:
|
||||
return Type.bool(token.value)
|
||||
|
||||
return ValueError()
|
||||
|
||||
if type.value == Type.NOTE:
|
||||
consumedChars, token = noteTokenizer(value, 0, 0)
|
||||
if consumedChars > 0:
|
||||
return Type.note(token.value)
|
||||
|
||||
raise ValueError()
|
||||
|
||||
raise RuntimeException(f"Type {type.value.name.lower()} is not suuported", None)
|
||||
|
||||
except ValueError:
|
||||
raise RuntimeException(f"Invalid value '{value}' for type {type.value.name.lower()}", None)
|
||||
|
||||
|
||||
_signature4 = signature(ofType(Type.STRING), ofType(Type.TYPE))
|
||||
def _function4(env, prompt, type):
|
||||
print(prompt.value, end="")
|
||||
value = input()
|
||||
return getValueAccordingToType(value, type)
|
||||
|
||||
|
||||
function = CombinedFunction(
|
||||
'read',
|
||||
Function(_signature1, _function1),
|
||||
Function(_signature2, _function2),
|
||||
Function(_signature3, _function3),
|
||||
Function(_signature4, _function4)
|
||||
)
|
||||
|
||||
# TODO read function
|
||||
# def read(args, env):
|
||||
|
||||
@@ -1,29 +1,12 @@
|
||||
import random as r
|
||||
import random
|
||||
|
||||
from smnp.error.function import IllegalArgumentException
|
||||
from smnp.function.model import Function, CombinedFunction
|
||||
from smnp.function.signature import varargSignature
|
||||
from smnp.function.model import Function
|
||||
from smnp.function.signature import signature
|
||||
from smnp.type.model import Type
|
||||
from smnp.type.signature.matcher.list import listMatches
|
||||
from smnp.type.signature.matcher.type import ofTypes
|
||||
from smnp.type.signature.matcher.type import ofType
|
||||
|
||||
_signature = signature(ofType(Type.INTEGER), ofType(Type.INTEGER))
|
||||
def _function(env, min, max):
|
||||
return Type.integer(random.randint(min.value, max.value))
|
||||
|
||||
def forType(t):
|
||||
_signature = varargSignature(listMatches(ofTypes(Type.PERCENT), ofTypes(t)))
|
||||
def _function(env, vararg):
|
||||
choice = r.random()
|
||||
acc = 0
|
||||
if sum(arg.value[0].value for arg in vararg) != 1.0:
|
||||
raise IllegalArgumentException("Sum of all percentage values must be equal 100%")
|
||||
for arg in vararg:
|
||||
percent, item = arg.value
|
||||
acc += percent.value
|
||||
if choice <= acc:
|
||||
return item
|
||||
|
||||
return Function(_signature, _function)
|
||||
|
||||
|
||||
function = CombinedFunction('random', *[ forType(t) for t in Type if t != Type.VOID ])
|
||||
|
||||
#TODO: sample
|
||||
function = Function(_signature, _function, 'rand')
|
||||
@@ -16,7 +16,7 @@ class NotePitch(Enum):
|
||||
A = 9
|
||||
AIS = 10
|
||||
H = 11
|
||||
|
||||
|
||||
def toFrequency(self):
|
||||
return {
|
||||
NotePitch.C: 16.35,
|
||||
@@ -32,19 +32,23 @@ class NotePitch(Enum):
|
||||
NotePitch.AIS: 29.17,
|
||||
NotePitch.H: 30.87
|
||||
}[self]
|
||||
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
|
||||
|
||||
def __repr__(self):
|
||||
return self.__str__()
|
||||
|
||||
|
||||
@staticmethod
|
||||
def toPitch(string):
|
||||
try:
|
||||
if string.lower() in stringToPitch:
|
||||
return stringToPitch[string.lower()]
|
||||
except KeyError as e:
|
||||
raise NoteException(f"Note '{string}' does not exist")
|
||||
|
||||
if string.upper() in NotePitch.__members__:
|
||||
return NotePitch[string.upper()]
|
||||
|
||||
raise NoteException(f"Note '{string}' does not exist")
|
||||
|
||||
|
||||
stringToPitch = {
|
||||
'cb': NotePitch.H,
|
||||
@@ -67,4 +71,4 @@ stringToPitch = {
|
||||
'a#': NotePitch.AIS,
|
||||
'b': NotePitch.AIS,
|
||||
'h': NotePitch.H
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from smnp.ast.parser import parse
|
||||
from smnp.environment.factory import createEnvironment
|
||||
from smnp.environment.environment import Environment
|
||||
from smnp.error.runtime import RuntimeException
|
||||
from smnp.module import functions, methods
|
||||
from smnp.program.FileReader import readLines
|
||||
from smnp.runtime.evaluator import evaluate
|
||||
from smnp.token.tokenizer import tokenize
|
||||
@@ -9,16 +10,31 @@ from smnp.token.tokenizer import tokenize
|
||||
class Interpreter:
|
||||
|
||||
@staticmethod
|
||||
def interpretString(string, printTokens=False, printAst=False, execute=True, baseEnvironment=None):
|
||||
return Interpreter._interpret(string.splitlines(), printTokens, printAst, execute, baseEnvironment)
|
||||
def interpretString(string, source, printTokens=False, printAst=False, execute=True, baseEnvironment=None):
|
||||
return Interpreter._interpret(
|
||||
string.splitlines(),
|
||||
source,
|
||||
printTokens,
|
||||
printAst,
|
||||
execute,
|
||||
baseEnvironment,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def interpretFile(file, printTokens=False, printAst=False, execute=True, baseEnvironment=None):
|
||||
return Interpreter._interpret(readLines(file), printTokens, printAst, execute, baseEnvironment)
|
||||
def interpretFile(file, printTokens=False, printAst=False, execute=True, baseEnvironment=None, source=None):
|
||||
return Interpreter._interpret(
|
||||
readLines(file),
|
||||
source if source is not None else file,
|
||||
printTokens,
|
||||
printAst,
|
||||
execute,
|
||||
baseEnvironment,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _interpret(lines, printTokens=False, printAst=False, execute=True, baseEnvironment=None):
|
||||
environment = createEnvironment()
|
||||
def _interpret(lines, source, printTokens=False, printAst=False, execute=True, baseEnvironment=None):
|
||||
environment = Environment([{}], functions, methods, source=source)
|
||||
|
||||
if baseEnvironment is not None:
|
||||
environment.extend(baseEnvironment)
|
||||
|
||||
@@ -37,4 +53,5 @@ class Interpreter:
|
||||
return environment
|
||||
except RuntimeException as e:
|
||||
e.environment = environment
|
||||
e.file = environment.source
|
||||
raise e
|
||||
@@ -5,6 +5,7 @@ from smnp.ast.node.function import FunctionDefinition
|
||||
from smnp.ast.node.imports import Import
|
||||
from smnp.ast.node.program import Program
|
||||
from smnp.ast.node.ret import Return
|
||||
from smnp.ast.node.throw import Throw
|
||||
from smnp.error.runtime import RuntimeException
|
||||
from smnp.type.model import Type
|
||||
|
||||
@@ -69,7 +70,6 @@ class EvaluationResult():
|
||||
|
||||
def evaluate(node, environment):
|
||||
from smnp.runtime.evaluators.program import ProgramEvaluator
|
||||
|
||||
from smnp.runtime.evaluators.expression import expressionEvaluator
|
||||
from smnp.runtime.evaluators.condition import IfElseStatementEvaluator
|
||||
from smnp.runtime.evaluators.block import BlockEvaluator
|
||||
@@ -77,6 +77,8 @@ def evaluate(node, environment):
|
||||
from smnp.runtime.evaluators.function import FunctionDefinitionEvaluator
|
||||
from smnp.runtime.evaluators.function import ReturnEvaluator
|
||||
from smnp.runtime.evaluators.extend import ExtendEvaluator
|
||||
from smnp.runtime.evaluators.throw import ThrowEvaluator
|
||||
|
||||
result = Evaluator.oneOf(
|
||||
Evaluator.forNodes(ProgramEvaluator.evaluate, Program),
|
||||
Evaluator.forNodes(IfElseStatementEvaluator.evaluate, IfElse),
|
||||
@@ -85,6 +87,7 @@ def evaluate(node, environment):
|
||||
Evaluator.forNodes(FunctionDefinitionEvaluator.evaluate, FunctionDefinition),
|
||||
Evaluator.forNodes(ReturnEvaluator.evaluate, Return),
|
||||
Evaluator.forNodes(ExtendEvaluator.evaluate, Extend),
|
||||
Evaluator.forNodes(ThrowEvaluator.evaluate, Throw),
|
||||
#Evaluator.forNodes(ImportEvaluator.evaluate, ImportNode),
|
||||
#Evaluator.forNodes(FunctionDefinitionEvaluator.evaluate, FunctionDefinitionNode),
|
||||
#Evaluator.forNodes(ExtendEvaluator.evaluate, ExtendNode),
|
||||
|
||||
@@ -8,11 +8,7 @@ class AssignmentEvaluator(Evaluator):
|
||||
def evaluator(cls, node, environment):
|
||||
target = node.left.value
|
||||
value = expressionEvaluator(doAssert=True)(node.right, environment).value #TODO check if it isn't necessary to verify 'result' attr of EvaluatioNResult
|
||||
scopeOfExistingVariable = environment.findVariableScope(target)
|
||||
if scopeOfExistingVariable is None:
|
||||
environment.scopes[-1][target] = value
|
||||
else:
|
||||
scopeOfExistingVariable[target] = value
|
||||
environment.scopes[-1][target] = value
|
||||
|
||||
return value
|
||||
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
from smnp.ast.node.identifier import Identifier
|
||||
from smnp.runtime.evaluator import evaluate, Evaluator, EvaluationResult
|
||||
from smnp.runtime.evaluators.expression import expressionEvaluator
|
||||
from smnp.type.model import Type
|
||||
|
||||
|
||||
class AsteriskEvaluator(Evaluator):
|
||||
|
||||
@classmethod
|
||||
def evaluator(cls, node, environment):
|
||||
iterator = expressionEvaluator(doAssert=True)(node.iterator, environment).value #TODO check if it isn't necessary to verify 'result' attr of EvaluatioNResult
|
||||
return Evaluator.oneOf(
|
||||
cls._numberIteratorAsteriskEvaluator(iterator),
|
||||
cls._listIteratorAsteriskEvaluator(iterator),
|
||||
cls._mapIteratorAsteriskEvaluator(iterator)
|
||||
)(node, environment).value #TODO check if it isn't necessary to verify 'result' attr of EvaluatioNResult
|
||||
|
||||
@classmethod
|
||||
def _numberIteratorAsteriskEvaluator(cls, evaluatedIterator):
|
||||
def evaluator(node, environment):
|
||||
if evaluatedIterator.type == Type.INTEGER:
|
||||
results = []
|
||||
automaticVariable = cls._automaticNamedVariable(node.iterator, environment, "_")
|
||||
for i in range(evaluatedIterator.value):
|
||||
environment.scopes[-1][automaticVariable] = Type.integer(i + 1)
|
||||
result = evaluate(node.statement, environment).value #TODO check if it isn't necessary to verify 'result' attr of EvaluatioNResult
|
||||
if result is None or result.type == Type.VOID:
|
||||
results = None
|
||||
|
||||
if results is not None:
|
||||
results.append(result)
|
||||
|
||||
del environment.scopes[-1][automaticVariable]
|
||||
|
||||
return EvaluationResult.OK(Type.list(results).decompose() if results is not None else Type.void())
|
||||
|
||||
return EvaluationResult.FAIL()
|
||||
|
||||
return evaluator
|
||||
|
||||
@classmethod
|
||||
def _automaticNamedVariable(cls, iteratorNode, environment, prefix=''):
|
||||
if type(iteratorNode) == Identifier:
|
||||
return cls._automaticVariableName(environment, prefix, iteratorNode.value, False)
|
||||
else:
|
||||
return cls._automaticVariableName(environment, prefix, '', True)
|
||||
|
||||
@classmethod
|
||||
def _automaticVariableName(cls, environment, prefix='', suffix='', startWithNumber=False):
|
||||
number = 1 if startWithNumber else ''
|
||||
variableName = lambda x: f"{prefix}{x}{suffix}"
|
||||
while environment.findVariableScope(variableName(number)) is not None:
|
||||
if number == '':
|
||||
number = 1
|
||||
else:
|
||||
number += 1
|
||||
|
||||
return variableName(number)
|
||||
|
||||
@classmethod
|
||||
def _listIteratorAsteriskEvaluator(cls, evaluatedIterator):
|
||||
def evaluator(node, environment):
|
||||
if evaluatedIterator.type == Type.LIST:
|
||||
results = []
|
||||
automaticVariableKey = cls._automaticNamedVariable(node.iterator, environment, "_")
|
||||
automaticVariableValue = cls._automaticNamedVariable(node.iterator, environment, "__")
|
||||
for i, v in enumerate(evaluatedIterator.value):
|
||||
environment.scopes[-1][automaticVariableKey] = Type.integer(i + 1)
|
||||
environment.scopes[-1][automaticVariableValue] = v
|
||||
result = evaluate(node.statement, environment).value # TODO check if it isn't necessary to verify 'result' attr of EvaluatioNResult
|
||||
if result is not None and result.type != Type.VOID:
|
||||
results.append(result)
|
||||
|
||||
del environment.scopes[-1][automaticVariableKey]
|
||||
del environment.scopes[-1][automaticVariableValue]
|
||||
|
||||
return EvaluationResult.OK(Type.list(results).decompose())
|
||||
|
||||
return EvaluationResult.FAIL()
|
||||
|
||||
return evaluator
|
||||
|
||||
@classmethod
|
||||
def _mapIteratorAsteriskEvaluator(cls, evaluatedIterator):
|
||||
def evaluator(node, environment):
|
||||
if evaluatedIterator.type == Type.MAP:
|
||||
results = []
|
||||
automaticVariableKey = cls._automaticNamedVariable(node.iterator, environment, "_")
|
||||
automaticVariableValue = cls._automaticNamedVariable(node.iterator, environment, "__")
|
||||
for k, v in evaluatedIterator.value.items():
|
||||
environment.scopes[-1][automaticVariableKey] = k
|
||||
environment.scopes[-1][automaticVariableValue] = v
|
||||
result = evaluate(node.statement, environment).value # TODO check if it isn't necessary to verify 'result' attr of EvaluatioNResult
|
||||
if result is not None and result.type != Type.VOID:
|
||||
results.append(result)
|
||||
|
||||
del environment.scopes[-1][automaticVariableKey]
|
||||
del environment.scopes[-1][automaticVariableValue]
|
||||
|
||||
return EvaluationResult.OK(Type.list(results).decompose())
|
||||
|
||||
return EvaluationResult.FAIL()
|
||||
|
||||
return evaluator
|
||||
@@ -1,10 +1,11 @@
|
||||
from smnp.ast.node.atom import StringLiteral, IntegerLiteral, NoteLiteral, BoolLiteral, TypeLiteral
|
||||
from smnp.ast.node.atom import StringLiteral, IntegerLiteral, NoteLiteral, BoolLiteral, TypeLiteral, FloatLiteral
|
||||
from smnp.ast.node.identifier import Identifier
|
||||
from smnp.ast.node.list import List
|
||||
from smnp.ast.node.map import Map
|
||||
from smnp.error.runtime import RuntimeException
|
||||
from smnp.runtime.evaluator import Evaluator
|
||||
from smnp.runtime.evaluator import Evaluator, EvaluationResult
|
||||
from smnp.runtime.evaluators.expression import expressionEvaluator
|
||||
from smnp.runtime.evaluators.float import FloatEvaluator
|
||||
from smnp.runtime.evaluators.iterable import abstractIterableEvaluator
|
||||
from smnp.runtime.tools.error import updatePos
|
||||
from smnp.type.model import Type
|
||||
@@ -58,12 +59,15 @@ class MapEvaluator(Evaluator):
|
||||
@classmethod
|
||||
def evaluator(cls, node, environment):
|
||||
map = {}
|
||||
exprEvaluator = expressionEvaluator(doAssert=True)
|
||||
keyEvaluator = Evaluator.oneOf(
|
||||
Evaluator.forNodes(lambda node, environment: EvaluationResult.OK(Type.string(node.value)), Identifier),
|
||||
expressionEvaluator(doAssert=True)
|
||||
)
|
||||
for entry in node.children:
|
||||
key = exprEvaluator(entry.key, environment).value
|
||||
key = keyEvaluator(entry.key, environment).value
|
||||
if key in map:
|
||||
raise RuntimeException(f"Duplicated key '{key.stringify()}' found in map", entry.pos)
|
||||
map[key] = exprEvaluator(entry.value, environment).value
|
||||
map[key] = expressionEvaluator(doAssert=True)(entry.value, environment).value
|
||||
|
||||
return Type.map(map)
|
||||
|
||||
@@ -85,6 +89,7 @@ class AtomEvaluator(Evaluator):
|
||||
return Evaluator.oneOf(
|
||||
Evaluator.forNodes(StringEvaluator.evaluate, StringLiteral),
|
||||
Evaluator.forNodes(IntegerEvaluator.evaluate, IntegerLiteral),
|
||||
Evaluator.forNodes(FloatEvaluator.evaluate, FloatLiteral),
|
||||
Evaluator.forNodes(NoteEvaluator.evaluate, NoteLiteral),
|
||||
Evaluator.forNodes(BoolEvaluator.evaluate, BoolLiteral),
|
||||
Evaluator.forNodes(TypeEvaluator.evaluate, TypeLiteral),
|
||||
|
||||
@@ -5,12 +5,12 @@ class BlockEvaluator(Evaluator):
|
||||
|
||||
@classmethod
|
||||
def evaluator(cls, node, environment):
|
||||
environment.scopes.append({})
|
||||
environment.appendScope()
|
||||
|
||||
for child in node.children:
|
||||
evaluate(child, environment)
|
||||
|
||||
environment.scopes.pop(-1)
|
||||
environment.popScope()
|
||||
|
||||
#
|
||||
# def evaluateBlock(block, environment):
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from smnp.ast.node.condition import IfElse
|
||||
from smnp.ast.node.expression import Sum, Relation
|
||||
from smnp.ast.node.factor import NotOperator, Power, Loop
|
||||
from smnp.ast.node.expression import Sum, Relation, And, Or, Loop
|
||||
from smnp.ast.node.factor import NotOperator, Power
|
||||
from smnp.ast.node.identifier import FunctionCall, Assignment
|
||||
from smnp.ast.node.term import Product
|
||||
from smnp.ast.node.unit import MinusOperator, Access
|
||||
@@ -24,6 +24,8 @@ def expressionEvaluator(doAssert=False):
|
||||
from smnp.runtime.evaluators.sum import SumEvaluator
|
||||
from smnp.runtime.evaluators.relation import RelationEvaluator
|
||||
from smnp.runtime.evaluators.condition import IfElseEvaluator
|
||||
from smnp.runtime.evaluators.logic import AndEvaluator
|
||||
from smnp.runtime.evaluators.logic import OrEvaluator
|
||||
result = Evaluator.oneOf(
|
||||
Evaluator.forNodes(FunctionCallEvaluator.evaluate, FunctionCall),
|
||||
Evaluator.forNodes(MinusEvaluator.evaluate, MinusOperator),
|
||||
@@ -36,6 +38,8 @@ def expressionEvaluator(doAssert=False):
|
||||
Evaluator.forNodes(SumEvaluator.evaluate, Sum),
|
||||
Evaluator.forNodes(RelationEvaluator.evaluate, Relation),
|
||||
Evaluator.forNodes(IfElseEvaluator.evaluate, IfElse),
|
||||
Evaluator.forNodes(AndEvaluator.evaluate, And),
|
||||
Evaluator.forNodes(OrEvaluator.evaluate, Or),
|
||||
AtomEvaluator.evaluate
|
||||
)(node, environment)
|
||||
|
||||
@@ -46,3 +50,15 @@ def expressionEvaluator(doAssert=False):
|
||||
|
||||
|
||||
return evaluateExpression
|
||||
|
||||
|
||||
def expressionEvaluatorWithMatcher(matcher, exceptionProvider, doAssert=True):
|
||||
def evaluate(node, environment):
|
||||
value = expressionEvaluator(doAssert=doAssert)(node, environment).value
|
||||
|
||||
if not matcher.match(value):
|
||||
raise exceptionProvider(value)
|
||||
|
||||
return value
|
||||
|
||||
return evaluate
|
||||
@@ -32,8 +32,8 @@ class ExtendEvaluator(Evaluator):
|
||||
@classmethod
|
||||
def _evaluateMethodDefinition(cls, node, environment, type, variable):
|
||||
name = node.name.value
|
||||
signature = argumentsNodeToMethodSignature(node.arguments)
|
||||
defaultArguments, signature = argumentsNodeToMethodSignature(node.arguments, environment)
|
||||
arguments = [arg.variable.value for arg in node.arguments]
|
||||
body = node.body
|
||||
environment.addCustomMethod(type, variable, name, signature, arguments, body)
|
||||
environment.addCustomMethod(type, variable, name, signature, arguments, body, defaultArguments)
|
||||
|
||||
|
||||
9
smnp/runtime/evaluators/float.py
Normal file
9
smnp/runtime/evaluators/float.py
Normal file
@@ -0,0 +1,9 @@
|
||||
from smnp.runtime.evaluator import Evaluator
|
||||
from smnp.type.model import Type
|
||||
|
||||
|
||||
class FloatEvaluator(Evaluator):
|
||||
|
||||
@classmethod
|
||||
def evaluator(cls, node, environment):
|
||||
return Type.float(node.value)
|
||||
@@ -4,6 +4,7 @@ from smnp.runtime.evaluators.expression import expressionEvaluator
|
||||
from smnp.runtime.evaluators.iterable import abstractIterableEvaluator
|
||||
from smnp.runtime.tools.error import updatePos
|
||||
from smnp.runtime.tools.signature import argumentsNodeToMethodSignature
|
||||
from smnp.type.model import Type
|
||||
|
||||
|
||||
class FunctionCallEvaluator(Evaluator):
|
||||
@@ -24,10 +25,10 @@ class FunctionDefinitionEvaluator(Evaluator):
|
||||
def evaluator(cls, node, environment):
|
||||
try:
|
||||
name = node.name.value
|
||||
signature = argumentsNodeToMethodSignature(node.arguments)
|
||||
defaultArguments, signature = argumentsNodeToMethodSignature(node.arguments, environment)
|
||||
arguments = [ arg.variable.value for arg in node.arguments ]
|
||||
body = node.body
|
||||
environment.addCustomFunction(name, signature, arguments, body)
|
||||
environment.addCustomFunction(name, signature, arguments, body, defaultArguments)
|
||||
except RuntimeException as e:
|
||||
raise updatePos(e, node)
|
||||
|
||||
@@ -38,8 +39,6 @@ class BodyEvaluator(Evaluator):
|
||||
def evaluator(cls, node, environment):
|
||||
for child in node.children:
|
||||
evaluate(child, environment)
|
||||
if environment.callStack[-1].value is not None:
|
||||
return environment.callStack[-1].value
|
||||
|
||||
|
||||
class ReturnEvaluator(Evaluator):
|
||||
@@ -47,7 +46,21 @@ class ReturnEvaluator(Evaluator):
|
||||
@classmethod
|
||||
def evaluator(cls, node, environment):
|
||||
if len(environment.callStack) > 0:
|
||||
returnValue = expressionEvaluator(doAssert=True)(node.value, environment)
|
||||
environment.callStack[-1].value = returnValue.value
|
||||
returnValue = expressionEvaluator()(node.value, environment).value
|
||||
raise Return(returnValue)
|
||||
# Disclaimer
|
||||
# Exception system usage to control program execution flow is really bad idea.
|
||||
# However because of lack of 'goto' instruction equivalent in Python
|
||||
# there is to need to use some mechanism to break function execution on 'return' statement
|
||||
# and immediately go to Environment's method 'invokeFunction()' or 'invokeMethod()',
|
||||
# which can handle value that came with exception and return it to code being executed.
|
||||
else:
|
||||
raise RuntimeException("Cannot use 'return' statement outside a function or method", node.pos, environment)
|
||||
|
||||
|
||||
class Return(Exception):
|
||||
def __init__(self, value):
|
||||
if value is None:
|
||||
value = Type.void()
|
||||
|
||||
self.value = value
|
||||
21
smnp/runtime/evaluators/logic.py
Normal file
21
smnp/runtime/evaluators/logic.py
Normal file
@@ -0,0 +1,21 @@
|
||||
from smnp.runtime.evaluator import Evaluator
|
||||
from smnp.runtime.evaluators.expression import expressionEvaluator
|
||||
from smnp.type.model import Type
|
||||
|
||||
|
||||
class AndEvaluator(Evaluator):
|
||||
|
||||
@classmethod
|
||||
def evaluator(cls, node, environment):
|
||||
left = expressionEvaluator(doAssert=True)(node.left, environment).value
|
||||
right = expressionEvaluator(doAssert=True)(node.right, environment).value
|
||||
return Type.bool(left.value and right.value)
|
||||
|
||||
|
||||
class OrEvaluator(Evaluator):
|
||||
|
||||
@classmethod
|
||||
def evaluator(cls, node, environment):
|
||||
left = expressionEvaluator(doAssert=True)(node.left, environment).value
|
||||
right = expressionEvaluator(doAssert=True)(node.right, environment).value
|
||||
return Type.bool(left.value or right.value)
|
||||
@@ -13,23 +13,23 @@ class LoopEvaluator(Evaluator):
|
||||
parameters = [ identifier.value for identifier in node.parameters ] if type(node.parameters) != NoneNode() else []
|
||||
|
||||
try:
|
||||
environment.scopes.append({})
|
||||
environment.appendScope()
|
||||
|
||||
output = {
|
||||
Type.INTEGER: cls.numberEvaluator,
|
||||
Type.BOOL: cls.boolEvaluator,
|
||||
Type.LIST: cls.listEvaluator,
|
||||
Type.MAP: cls.mapEvaluator
|
||||
}[iterator.type](node, environment, iterator, parameters)
|
||||
}[iterator.type](node, environment, iterator, parameters, node.filter)
|
||||
|
||||
environment.scopes.pop(-1)
|
||||
environment.popScope()
|
||||
except KeyError:
|
||||
raise RuntimeException(f"The {iterator.type.name.lower()} type cannot stand as an iterator for loop statement", node.left.pos)
|
||||
|
||||
return Type.list(output)
|
||||
|
||||
@classmethod
|
||||
def numberEvaluator(cls, node, environment, evaluatedIterator, parameters):
|
||||
def numberEvaluator(cls, node, environment, evaluatedIterator, parameters, filter):
|
||||
output = []
|
||||
|
||||
|
||||
@@ -40,14 +40,28 @@ class LoopEvaluator(Evaluator):
|
||||
if len(parameters) > 0:
|
||||
environment.scopes[-1][parameters[0]] = Type.integer(i)
|
||||
|
||||
output.append(evaluate(node.right, environment).value)
|
||||
if cls.doFilter(filter, environment):
|
||||
output.append(evaluate(node.right, environment).value)
|
||||
|
||||
|
||||
|
||||
return output
|
||||
|
||||
@classmethod
|
||||
def boolEvaluator(cls, node, environment, evaluatedIterator, parameters):
|
||||
def doFilter(cls, filter, environment):
|
||||
if type(filter) is not NoneNode:
|
||||
evaluation = expressionEvaluator(doAssert=True)(filter, environment).value
|
||||
if evaluation.type != Type.BOOL:
|
||||
raise RuntimeException(f"Expected {Type.BOOL.name.lower()} as filter expression, found {evaluation.type.name.lower()}", filter.pos)
|
||||
|
||||
return evaluation.value
|
||||
|
||||
return True
|
||||
|
||||
|
||||
|
||||
@classmethod
|
||||
def boolEvaluator(cls, node, environment, evaluatedIterator, parameters, filter):
|
||||
output = []
|
||||
|
||||
if len(parameters) > 0:
|
||||
@@ -55,13 +69,14 @@ class LoopEvaluator(Evaluator):
|
||||
|
||||
condition = evaluatedIterator
|
||||
while condition.value:
|
||||
output.append(evaluate(node.right, environment).value)
|
||||
if cls.doFilter(filter, environment):
|
||||
output.append(evaluate(node.right, environment).value)
|
||||
condition = expressionEvaluator(doAssert=True)(node.left, environment).value
|
||||
|
||||
return output
|
||||
|
||||
@classmethod
|
||||
def listEvaluator(cls, node, environment, evaluatedIterator, parameters):
|
||||
def listEvaluator(cls, node, environment, evaluatedIterator, parameters, filter):
|
||||
output = []
|
||||
|
||||
if len(parameters) > 2:
|
||||
@@ -74,13 +89,14 @@ class LoopEvaluator(Evaluator):
|
||||
environment.scopes[-1][parameters[0]] = Type.integer(i)
|
||||
environment.scopes[-1][parameters[1]] = value
|
||||
|
||||
output.append(evaluate(node.right, environment).value)
|
||||
if cls.doFilter(filter, environment):
|
||||
output.append(evaluate(node.right, environment).value)
|
||||
|
||||
return output
|
||||
|
||||
|
||||
@classmethod
|
||||
def mapEvaluator(cls, node, environment, evaluatedIterator, parameters):
|
||||
def mapEvaluator(cls, node, environment, evaluatedIterator, parameters, filter):
|
||||
output = []
|
||||
|
||||
if len(parameters) > 3:
|
||||
@@ -99,6 +115,7 @@ class LoopEvaluator(Evaluator):
|
||||
environment.scopes[-1][parameters[2]] = value
|
||||
i += 1
|
||||
|
||||
output.append(evaluate(node.right, environment).value)
|
||||
if cls.doFilter(filter, environment):
|
||||
output.append(evaluate(node.right, environment).value)
|
||||
|
||||
return output
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
from smnp.error.runtime import RuntimeException
|
||||
from smnp.runtime.evaluator import Evaluator
|
||||
from smnp.runtime.evaluators.expression import expressionEvaluator
|
||||
from smnp.type.model import Type
|
||||
|
||||
|
||||
class MapEvaluator(Evaluator):
|
||||
|
||||
@classmethod
|
||||
def evaluator(cls, node, environment):
|
||||
map = {}
|
||||
exprEvaluator = expressionEvaluator(doAssert=True)
|
||||
for entry in node.children:
|
||||
key = exprEvaluator(entry.key, environment).value
|
||||
if key in map:
|
||||
raise RuntimeException(f"Duplicated key '{key.stringify()}' found in map", entry.pos)
|
||||
map[key] = exprEvaluator(entry.value, environment).value
|
||||
|
||||
return Type.map(map)
|
||||
@@ -11,6 +11,7 @@ class MinusEvaluator(Evaluator):
|
||||
try:
|
||||
return {
|
||||
Type.INTEGER: cls.evaluateForInteger,
|
||||
Type.FLOAT: cls.evaluateForFloat,
|
||||
Type.STRING: cls.evaluateForString,
|
||||
Type.LIST: cls.evaluateForList
|
||||
}[value.type](value.value)
|
||||
@@ -19,9 +20,12 @@ class MinusEvaluator(Evaluator):
|
||||
|
||||
@classmethod
|
||||
def evaluateForInteger(cls, value):
|
||||
|
||||
return Type.integer(-value)
|
||||
|
||||
@classmethod
|
||||
def evaluateForFloat(cls, value):
|
||||
return Type.float(-value)
|
||||
|
||||
@classmethod
|
||||
def evaluateForString(cls, value):
|
||||
return Type.string(value[::-1])
|
||||
|
||||
@@ -10,11 +10,12 @@ class PowerEvaluator(Evaluator):
|
||||
def evaluator(cls, node, environment):
|
||||
left = expressionEvaluator(doAssert=True)(node.left, environment).value
|
||||
right = expressionEvaluator(doAssert=True)(node.right, environment).value
|
||||
supportedTypes = [Type.INTEGER, Type.FLOAT]
|
||||
|
||||
if left.type != Type.INTEGER:
|
||||
raise RuntimeException( f"Operator '{node.operator.value}' is supported only by {Type.INTEGER.name.lower()} type", node.left.pos)
|
||||
if not left.type in supportedTypes:
|
||||
raise RuntimeException(f"Operator '{node.operator.value}' is supported only by {Type.INTEGER.name.lower()} type", node.left.pos)
|
||||
|
||||
if right.type != Type.INTEGER:
|
||||
raise RuntimeException( f"Operator '{node.operator.value}' is supported only by {Type.INTEGER.name.lower()} type", node.right.pos)
|
||||
if not right.type in supportedTypes:
|
||||
raise RuntimeException(f"Operator '{node.operator.value}' is supported only by {[t.name.lower() for t in supportedTypes]} type", node.right.pos)
|
||||
|
||||
return Type.integer(int(left.value ** right.value))
|
||||
@@ -10,22 +10,36 @@ class ProductEvaluator(Evaluator):
|
||||
def evaluator(cls, node, environment):
|
||||
left = expressionEvaluator(doAssert=True)(node.left, environment).value
|
||||
right = expressionEvaluator(doAssert=True)(node.right, environment).value
|
||||
supportedTypes = [Type.INTEGER, Type.FLOAT]
|
||||
|
||||
if left.type != Type.INTEGER:
|
||||
if not left.type in supportedTypes:
|
||||
raise RuntimeException(
|
||||
f"Operator '{node.operator.value}' is supported only by {Type.INTEGER.name.lower()} type", node.left.pos)
|
||||
f"Operator '{node.operator.value}' is supported only by {[t.name.lower() for t in supportedTypes]} type", node.left.pos)
|
||||
|
||||
if right.type != Type.INTEGER:
|
||||
if not right.type in supportedTypes:
|
||||
raise RuntimeException(
|
||||
f"Operator '{node.operator.value}' is supported only by {Type.INTEGER.name.lower()} type", node.right.pos)
|
||||
f"Operator '{node.operator.value}' is supported only by {[t.name.lower() for t in supportedTypes]} type", node.right.pos)
|
||||
|
||||
if node.operator.value == "*":
|
||||
return Type.integer(int(left.value * right.value))
|
||||
return getProperTypeProvider(left.value * right.value)
|
||||
|
||||
if node.operator.value == "/":
|
||||
if right.value == 0:
|
||||
raise RuntimeException("Attempt to divide by 0", node.right.pos)
|
||||
return Type.integer(int(left.value / right.value))
|
||||
|
||||
value = left.value / right.value
|
||||
|
||||
if left.type == right.type == Type.INTEGER and int(value) == value:
|
||||
return Type.integer(int(value))
|
||||
|
||||
return getProperTypeProvider(value)
|
||||
|
||||
raise RuntimeError("This line should never be reached")
|
||||
|
||||
|
||||
def getProperTypeProvider(value):
|
||||
return {
|
||||
int: lambda v: Type.integer(v),
|
||||
float: lambda v: Type.float(v)
|
||||
}[type(value)](value)
|
||||
|
||||
|
||||
@@ -21,15 +21,21 @@ class RelationEvaluator(Evaluator):
|
||||
|
||||
@classmethod
|
||||
def equalOperatorEvaluator(cls, left, operator, right):
|
||||
return Type.bool(left.value == right.value)
|
||||
if left.type in [Type.INTEGER, Type.FLOAT] and right.type in [Type.INTEGER, Type.FLOAT]:
|
||||
return Type.bool(left.value == right.value)
|
||||
|
||||
return Type.bool(left.type == right.type and left.value == right.value)
|
||||
|
||||
@classmethod
|
||||
def notEqualOperatorEvaluator(cls, left, operator, right):
|
||||
return Type.bool(left.value != right.value)
|
||||
if left.type in [Type.INTEGER, Type.FLOAT] and right.type in [Type.INTEGER, Type.FLOAT]:
|
||||
return Type.bool(left.value != right.value)
|
||||
|
||||
return Type.bool(left.type != right.type or left.value != right.value)
|
||||
|
||||
@classmethod
|
||||
def otherRelationOperatorsEvaluator(cls, left, operator, right):
|
||||
if left.type == right.type == Type.INTEGER:
|
||||
if left.type in [Type.INTEGER, Type.FLOAT] and right.type in [Type.INTEGER, Type.FLOAT]:
|
||||
if operator.value == ">":
|
||||
return Type.bool(left.value > right.value)
|
||||
|
||||
@@ -40,7 +46,7 @@ class RelationEvaluator(Evaluator):
|
||||
return Type.bool(left.value < right.value)
|
||||
|
||||
if operator.value == "<=":
|
||||
return Type.bool(left.value < right.value)
|
||||
return Type.bool(left.value <= right.value)
|
||||
|
||||
raise RuntimeException(f"Operator {operator.value} is not supported by {left.type.name.lower()} and {right.type.name.lower()} types", operator.pos)
|
||||
|
||||
|
||||
@@ -11,8 +11,8 @@ class SumEvaluator(Evaluator):
|
||||
left = expressionEvaluator(doAssert=True)(node.left, environment).value
|
||||
right = expressionEvaluator(doAssert=True)(node.right, environment).value
|
||||
|
||||
if left.type == right.type == Type.INTEGER:
|
||||
return cls.integerEvaluator(left, node.operator, right)
|
||||
if left.type in [Type.INTEGER, Type.FLOAT] and right.type in [Type.INTEGER, Type.FLOAT]:
|
||||
return cls.numberEvaluator(left, node.operator, right)
|
||||
|
||||
if left.type == right.type == Type.STRING:
|
||||
return cls.stringEvaluator(left, node.operator, right)
|
||||
@@ -23,15 +23,17 @@ class SumEvaluator(Evaluator):
|
||||
if left.type == right.type == Type.MAP:
|
||||
return cls.mapEvaluator(left, node.operator, right)
|
||||
|
||||
raise RuntimeException(f"Operator {node.operator.value} is not supported by {left.type.name.lower()} and {right.type.name.lower()} types", node.operator.pos)
|
||||
raise RuntimeException(
|
||||
f"Operator {node.operator.value} is not supported by {left.type.name.lower()} and {right.type.name.lower()} types",
|
||||
node.operator.pos)
|
||||
|
||||
@classmethod
|
||||
def integerEvaluator(cls, left, operator, right):
|
||||
def numberEvaluator(cls, left, operator, right):
|
||||
if operator.value == "+":
|
||||
return Type.integer(left.value + right.value)
|
||||
return getProperTypeProvider(left.value + right.value)
|
||||
|
||||
if operator.value == "-":
|
||||
return Type.integer(left.value - right.value)
|
||||
return getProperTypeProvider(left.value - right.value)
|
||||
|
||||
raise RuntimeError("This line should never be reached")
|
||||
|
||||
@@ -63,4 +65,11 @@ class SumEvaluator(Evaluator):
|
||||
if operator.value == "-":
|
||||
raise RuntimeException(f"Operator {operator.value} is not supported by map types", operator.pos)
|
||||
|
||||
raise RuntimeError("This line should never be reached")
|
||||
raise RuntimeError("This line should never be reached")
|
||||
|
||||
|
||||
def getProperTypeProvider(value):
|
||||
return {
|
||||
int: lambda v: Type.integer(v),
|
||||
float: lambda v: Type.float(v)
|
||||
}[type(value)](value)
|
||||
|
||||
17
smnp/runtime/evaluators/throw.py
Normal file
17
smnp/runtime/evaluators/throw.py
Normal file
@@ -0,0 +1,17 @@
|
||||
from smnp.error.custom import CustomException
|
||||
from smnp.error.runtime import RuntimeException
|
||||
from smnp.runtime.evaluator import Evaluator
|
||||
from smnp.runtime.evaluators.expression import expressionEvaluator
|
||||
from smnp.type.model import Type
|
||||
|
||||
|
||||
class ThrowEvaluator(Evaluator):
|
||||
|
||||
@classmethod
|
||||
def evaluator(cls, node, environment):
|
||||
string = expressionEvaluator(doAssert=True)(node.value, environment).value
|
||||
|
||||
if string.type != Type.STRING:
|
||||
raise RuntimeException(f"Only {Type.STRING.name.lower()} types can be thrown", node.value.pos)
|
||||
|
||||
raise CustomException(string.value, node.pos)
|
||||
@@ -2,7 +2,8 @@ from smnp.ast.node import type as ast
|
||||
from smnp.ast.node.none import NoneNode
|
||||
from smnp.ast.node.type import TypesList
|
||||
from smnp.error.runtime import RuntimeException
|
||||
from smnp.function.signature import varargSignature, signature
|
||||
from smnp.function.signature import varargSignature, signature, optional
|
||||
from smnp.runtime.evaluators.expression import expressionEvaluator, expressionEvaluatorWithMatcher
|
||||
from smnp.runtime.tools.error import updatePos
|
||||
from smnp.type.model import Type
|
||||
from smnp.type.signature.matcher.list import listOfMatchers
|
||||
@@ -10,11 +11,19 @@ from smnp.type.signature.matcher.map import mapOfMatchers
|
||||
from smnp.type.signature.matcher.type import allTypes, oneOf, ofType
|
||||
|
||||
|
||||
def argumentsNodeToMethodSignature(node):
|
||||
def evaluateDefaultArguments(node, environment):
|
||||
defaultValues = { arg.variable.value: expressionEvaluator(doAssert=True)(arg.optionalValue, environment).value for arg in node.children if type(arg.optionalValue) != NoneNode }
|
||||
|
||||
return defaultValues
|
||||
|
||||
|
||||
def argumentsNodeToMethodSignature(node, environment):
|
||||
try:
|
||||
sign = []
|
||||
vararg = None
|
||||
argumentsCount = len(node.children)
|
||||
checkPositionOfOptionalArguments(node)
|
||||
defaultArgs = {}
|
||||
for i, child in enumerate(node.children):
|
||||
matchers = {
|
||||
ast.Type: (lambda c: c.type, typeMatcher),
|
||||
@@ -22,19 +31,34 @@ def argumentsNodeToMethodSignature(node):
|
||||
TypesList: (lambda c: c, multipleTypeMatcher)
|
||||
}
|
||||
evaluatedMatcher = matchers[type(child.type)][1](matchers[type(child.type)][0](child))
|
||||
|
||||
if child.vararg:
|
||||
if i != argumentsCount - 1:
|
||||
raise RuntimeException("Vararg must be the last argument in signature", child.pos)
|
||||
vararg = evaluatedMatcher
|
||||
else:
|
||||
if type(child.optionalValue) != NoneNode:
|
||||
defaultArgs[child.variable.value] = expressionEvaluatorWithMatcher(
|
||||
evaluatedMatcher,
|
||||
exceptionProvider=lambda value: RuntimeException(
|
||||
f"Value '{value.stringify()}' doesn't match declared type: {evaluatedMatcher.string}", child.optionalValue.pos)
|
||||
)(child.optionalValue, environment)
|
||||
evaluatedMatcher = optional(evaluatedMatcher)
|
||||
sign.append(evaluatedMatcher)
|
||||
|
||||
|
||||
return varargSignature(vararg, *sign, wrapVarargInValue=True) if vararg is not None else signature(*sign)
|
||||
return defaultArgs, (varargSignature(vararg, *sign, wrapVarargInValue=True) if vararg is not None else signature(*sign))
|
||||
except RuntimeException as e:
|
||||
raise updatePos(e, node)
|
||||
|
||||
|
||||
def checkPositionOfOptionalArguments(node):
|
||||
firstOptional = next((i for i, v in enumerate(node.children) if type(v.optionalValue) != NoneNode), None) #next(filter(lambda arg: type(arg.optionalValue) != NoneNode, node.children), None)
|
||||
if firstOptional is not None:
|
||||
regularAfterOptional = next((i for i, v in enumerate(node.children[firstOptional:]) if type(v.optionalValue) == NoneNode), None)
|
||||
if regularAfterOptional is not None:
|
||||
raise RuntimeException(f"Optional arguments should be declared at the end of the arguments list", node.children[regularAfterOptional].pos)
|
||||
|
||||
|
||||
def multipleTypeMatcher(typeNode):
|
||||
subSignature = []
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ from smnp.error.syntax import SyntaxException
|
||||
from smnp.token.model import TokenList
|
||||
from smnp.token.tokenizers.bool import boolTokenizer
|
||||
from smnp.token.tokenizers.comment import commentTokenizer
|
||||
from smnp.token.tokenizers.float import floatTokenizer
|
||||
from smnp.token.tokenizers.identifier import identifierTokenizer
|
||||
from smnp.token.tokenizers.keyword import typeTokenizer
|
||||
from smnp.token.tokenizers.note import noteTokenizer
|
||||
@@ -27,7 +28,9 @@ tokenizers = (
|
||||
defaultTokenizer(TokenType.CLOSE_SQUARE),
|
||||
defaultTokenizer(TokenType.OPEN_ANGLE),
|
||||
defaultTokenizer(TokenType.CLOSE_ANGLE),
|
||||
defaultTokenizer(TokenType.SEMICOLON),
|
||||
defaultTokenizer(TokenType.ASTERISK),
|
||||
defaultTokenizer(TokenType.PERCENT),
|
||||
defaultTokenizer(TokenType.ASSIGN),
|
||||
defaultTokenizer(TokenType.COMMA),
|
||||
defaultTokenizer(TokenType.SLASH),
|
||||
@@ -39,6 +42,7 @@ tokenizers = (
|
||||
defaultTokenizer(TokenType.DOT),
|
||||
|
||||
# Types
|
||||
separated(floatTokenizer),
|
||||
mapValue(separated(regexPatternTokenizer(TokenType.INTEGER, r'\d')), int),
|
||||
stringTokenizer,
|
||||
noteTokenizer,
|
||||
@@ -50,6 +54,7 @@ tokenizers = (
|
||||
separated(defaultTokenizer(TokenType.RETURN)),
|
||||
separated(defaultTokenizer(TokenType.EXTEND)),
|
||||
separated(defaultTokenizer(TokenType.IMPORT)),
|
||||
separated(defaultTokenizer(TokenType.THROW)),
|
||||
separated(defaultTokenizer(TokenType.FROM)),
|
||||
separated(defaultTokenizer(TokenType.WITH)),
|
||||
separated(defaultTokenizer(TokenType.ELSE)),
|
||||
|
||||
17
smnp/token/tokenizers/float.py
Normal file
17
smnp/token/tokenizers/float.py
Normal file
@@ -0,0 +1,17 @@
|
||||
from smnp.token.model import Token
|
||||
from smnp.token.tools import regexPatternTokenizer, keywordTokenizer, allOf
|
||||
from smnp.token.type import TokenType
|
||||
|
||||
|
||||
def createToken(pos, beforeDot, dot, afterDot):
|
||||
rawValue = f"{beforeDot.value}.{afterDot.value}"
|
||||
value = float(rawValue)
|
||||
return Token(TokenType.FLOAT, value, pos, rawValue)
|
||||
|
||||
|
||||
floatTokenizer = allOf(
|
||||
regexPatternTokenizer(TokenType.INTEGER, r'\d'),
|
||||
keywordTokenizer(None, "."),
|
||||
regexPatternTokenizer(TokenType.INTEGER, r'\d'),
|
||||
createToken=createToken
|
||||
)
|
||||
@@ -61,3 +61,19 @@ def mapValue(tokenizer, mapper):
|
||||
return (0, None)
|
||||
|
||||
return tokenize
|
||||
|
||||
def allOf(*tokenizers, createToken):
|
||||
def combinedTokenizer(input, current, line):
|
||||
consumedChars = 0
|
||||
tokens = []
|
||||
for tokenizer in tokenizers:
|
||||
consumed, token = tokenizer(input, current+consumedChars, line)
|
||||
if consumed > 0:
|
||||
consumedChars += consumed
|
||||
tokens.append(token)
|
||||
else:
|
||||
return (0, None)
|
||||
|
||||
return (consumedChars, createToken((current, line), *tokens))
|
||||
|
||||
return combinedTokenizer
|
||||
@@ -12,7 +12,9 @@ class TokenType(Enum):
|
||||
CLOSE_SQUARE = ']'
|
||||
OPEN_ANGLE = '<'
|
||||
CLOSE_ANGLE = '>'
|
||||
SEMICOLON = ';'
|
||||
ASTERISK = '*'
|
||||
PERCENT = '%'
|
||||
ASSIGN = '='
|
||||
ARROW = '->'
|
||||
COMMA = ','
|
||||
@@ -28,6 +30,7 @@ class TokenType(Enum):
|
||||
NOT = 'not'
|
||||
INTEGER = 'integer'
|
||||
STRING = 'string'
|
||||
FLOAT = 'float'
|
||||
NOTE = 'note'
|
||||
BOOL = 'bool'
|
||||
TYPE = 'type'
|
||||
@@ -35,6 +38,7 @@ class TokenType(Enum):
|
||||
RETURN = 'return'
|
||||
EXTEND = 'extend'
|
||||
IMPORT = 'import'
|
||||
THROW = 'throw'
|
||||
FROM = 'from'
|
||||
WITH = 'with'
|
||||
ELSE = 'else'
|
||||
@@ -42,7 +46,6 @@ class TokenType(Enum):
|
||||
AS = 'as'
|
||||
IDENTIFIER = 'identifier'
|
||||
COMMENT = 'comment'
|
||||
PERCENT = 'percent'
|
||||
|
||||
@property
|
||||
def key(self):
|
||||
|
||||
@@ -8,10 +8,10 @@ from smnp.type.value import Value
|
||||
|
||||
class Type(Enum):
|
||||
INTEGER = (int, lambda x: str(x))
|
||||
FLOAT = (float, lambda x: str(x))
|
||||
STRING = (str, lambda x: x)
|
||||
LIST = (list, lambda x: f"[{', '.join([e.stringify() for e in x])}]")
|
||||
MAP = (dict, lambda x: '{' + ', '.join(f"'{k.stringify()}' -> '{v.stringify()}'" for k, v in x.items()) + '}')
|
||||
PERCENT = (float, lambda x: f"{int(x * 100)}%")
|
||||
NOTE = (Note, lambda x: x.note.name)
|
||||
BOOL = (bool, lambda x: str(x).lower())
|
||||
SOUND = (Sound, lambda x: x.file)
|
||||
@@ -25,6 +25,10 @@ class Type(Enum):
|
||||
def integer(value):
|
||||
return Value(Type.INTEGER, value, {})
|
||||
|
||||
@staticmethod
|
||||
def float(value):
|
||||
return Value(Type.FLOAT, value, {})
|
||||
|
||||
@staticmethod
|
||||
def string(value):
|
||||
return Value(Type.STRING, value, {
|
||||
@@ -51,7 +55,7 @@ class Type(Enum):
|
||||
"pitch": Type.string(str(value.note)),
|
||||
"octave": Type.integer(value.octave),
|
||||
"duration": Type.integer(value.duration),
|
||||
"dot": Type.string('.' if value.dot else '')
|
||||
"dot": Type.bool(value.dot)
|
||||
})
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -3,6 +3,7 @@ class Matcher:
|
||||
self.type = objectType
|
||||
self.matcher = matcher
|
||||
self.string = string
|
||||
self.optional = False
|
||||
|
||||
def match(self, value):
|
||||
if self.type is not None and self.type != value.type:
|
||||
|
||||
@@ -25,4 +25,4 @@ def oneOf(*matchers):
|
||||
def check(value):
|
||||
return any(matcher.match(value) for matcher in matchers)
|
||||
|
||||
return Matcher(None, check, f"<{', '.join(m.string for m in matchers)}>")
|
||||
return Matcher(None, check, f"<{', '.join(m.string for m in matchers)}>")
|
||||
|
||||
Reference in New Issue
Block a user