Compare commits
8
Commits
74ac9c5381
...
ae02bab030
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ae02bab030
|
||
|
|
7581a35be4
|
||
|
|
6f0c0ce326
|
||
|
|
1b1fbb834e
|
||
|
|
f41c757838
|
||
|
|
453c72af6d
|
||
|
|
ee308fe223
|
||
|
|
3f199ff134
|
No files matched your search
@@ -288,3 +288,73 @@ class MidasAstPrinter(AstPrinter, m.Expr.Visitor[None], m.Stmt.Visitor[None]):
|
||||
self._write_line("LiteralExpr")
|
||||
with self._child_level():
|
||||
self._write_line(f"value: {expr.value}", last=True)
|
||||
|
||||
class MidasPrinter(m.Expr.Visitor[str], m.Stmt.Visitor[str]):
|
||||
def __init__(self, indent: int = 4):
|
||||
self.indent: int = indent
|
||||
self.level: int = 0
|
||||
|
||||
def indented(self, text: str) -> str:
|
||||
return " " * (self.level * self.indent) + text
|
||||
|
||||
def print(self, expr: m.Expr | m.Stmt):
|
||||
self.level = 0
|
||||
return expr.accept(self)
|
||||
|
||||
def visit_type_stmt(self, stmt: m.TypeStmt):
|
||||
bases: list[str] = [
|
||||
b.accept(self)
|
||||
for b in stmt.bases
|
||||
]
|
||||
|
||||
res: str = self.indented(f"type {stmt.name.lexeme}<{', '.join(bases)}>")
|
||||
if stmt.body is not None:
|
||||
res += " {\n"
|
||||
self.level += 1
|
||||
res += stmt.body.accept(self)
|
||||
self.level -= 1
|
||||
res += "\n" + self.indented("}")
|
||||
|
||||
return res
|
||||
|
||||
def visit_property_stmt(self, stmt: m.PropertyStmt):
|
||||
return f"{stmt.name.lexeme}: {stmt.type.accept(self)}"
|
||||
|
||||
def visit_op_stmt(self, stmt: m.OpStmt):
|
||||
left: str = stmt.left.accept(self)
|
||||
op: str = stmt.op.lexeme
|
||||
right: str = stmt.right.accept(self)
|
||||
result: str = stmt.result.accept(self)
|
||||
return self.indented(f"op <{left}> {op} <{right}> = <{result}>")
|
||||
|
||||
def visit_constraint_stmt(self, stmt: m.ConstraintStmt):
|
||||
name: str = stmt.name.lexeme
|
||||
constraint: str = stmt.constraint.accept(self)
|
||||
return self.indented(f"constraint {name} = {constraint}")
|
||||
|
||||
def visit_type_expr(self, expr: m.TypeExpr):
|
||||
parts: list[str] = [expr.name.lexeme]
|
||||
for constraint in expr.constraints:
|
||||
parts.append("(" + constraint.accept(self) + ")")
|
||||
return " + ".join(parts)
|
||||
|
||||
def visit_constraint_expr(self, expr: m.ConstraintExpr):
|
||||
parts: list[str] = [
|
||||
expr.left.accept(self),
|
||||
expr.op.lexeme,
|
||||
expr.right.accept(self),
|
||||
]
|
||||
return " ".join(parts)
|
||||
|
||||
def visit_type_body_expr(self, expr: m.TypeBodyExpr):
|
||||
properties: list[str] = [
|
||||
self.indented(prop.accept(self))
|
||||
for prop in expr.properties
|
||||
]
|
||||
return "\n".join(properties)
|
||||
|
||||
def visit_wildcard_expr(self, expr: m.WildcardExpr):
|
||||
return "_"
|
||||
|
||||
def visit_literal_expr(self, expr: m.LiteralExpr):
|
||||
return str(expr.value)
|
||||
@@ -7,7 +7,7 @@ from __future__ import annotations
|
||||
df: Frame[
|
||||
verified: bool,
|
||||
birth_year: int,
|
||||
height: float,
|
||||
height: float + ( _ > 0 ) + ( _ < 250 ),
|
||||
name: str,
|
||||
date: datetime,
|
||||
float, # unnamed
|
||||
|
||||
@@ -16,7 +16,7 @@ op <Latitude> - <Latitude> = <LatitudeDiff>
|
||||
op <Longitude> - <Longitude> = <LongitudeDiff>
|
||||
|
||||
// Simple custom type with a constraint
|
||||
type Age<int + (0 <= _ < 150)>
|
||||
type Age<int + (0 <= _) + (_ < 150)>
|
||||
|
||||
// Predefined custom constraints that can be referenced in other definitions
|
||||
constraint Positive = _ >= 0
|
||||
|
||||
@@ -28,7 +28,7 @@ class AnnotationLexer(Lexer):
|
||||
TokenType.EQUAL_EQUAL if self.match("=") else TokenType.EQUAL
|
||||
)
|
||||
case "!":
|
||||
if self.peek() == "=":
|
||||
if self.match("="):
|
||||
self.add_token(TokenType.BANG_EQUAL)
|
||||
else:
|
||||
self.error("Unexpected single bang. Did you mean '!=' ?")
|
||||
|
||||
+1
-1
@@ -32,7 +32,7 @@ class MidasLexer(Lexer):
|
||||
TokenType.EQUAL_EQUAL if self.match("=") else TokenType.EQUAL
|
||||
)
|
||||
case "!":
|
||||
if self.peek() == "=":
|
||||
if self.match("="):
|
||||
self.add_token(TokenType.BANG_EQUAL)
|
||||
else:
|
||||
self.error("Unexpected single bang. Did you mean '!=' ?")
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from lexer.annotations import AnnotationLexer
|
||||
from lexer.token import Token, TokenType
|
||||
|
||||
|
||||
def scan(source: str) -> list[Token]:
|
||||
return AnnotationLexer(source).process()
|
||||
|
||||
|
||||
def assert_n_tokens(tokens: list[Token], n: int):
|
||||
assert len(tokens) == n + 1
|
||||
assert tokens[-1].type == TokenType.EOF
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"src,expected",
|
||||
[
|
||||
("(", TokenType.LEFT_PAREN),
|
||||
(")", TokenType.RIGHT_PAREN),
|
||||
("[", TokenType.LEFT_BRACKET),
|
||||
("]", TokenType.RIGHT_BRACKET),
|
||||
(":", TokenType.COLON),
|
||||
(",", TokenType.COMMA),
|
||||
("_", TokenType.UNDERSCORE),
|
||||
],
|
||||
)
|
||||
def test_punctuation(src: str, expected: TokenType):
|
||||
tokens: list[Token] = scan(src)
|
||||
assert_n_tokens(tokens, 1)
|
||||
assert tokens[0].type == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"src,expected",
|
||||
[
|
||||
("+", TokenType.PLUS),
|
||||
(">", TokenType.GREATER),
|
||||
(">=", TokenType.GREATER_EQUAL),
|
||||
("<", TokenType.LESS),
|
||||
("<=", TokenType.LESS_EQUAL),
|
||||
("=", TokenType.EQUAL),
|
||||
("==", TokenType.EQUAL_EQUAL),
|
||||
("!=", TokenType.BANG_EQUAL),
|
||||
],
|
||||
)
|
||||
def test_operators(src: str, expected: TokenType):
|
||||
tokens: list[Token] = scan(src)
|
||||
assert_n_tokens(tokens, 1)
|
||||
assert tokens[0].type == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"src,expected",
|
||||
[
|
||||
("a", TokenType.IDENTIFIER),
|
||||
("foo", TokenType.IDENTIFIER),
|
||||
("foo1", TokenType.IDENTIFIER),
|
||||
("foo_", TokenType.IDENTIFIER),
|
||||
("foo_bar1_baz2", TokenType.IDENTIFIER),
|
||||
("FOO_BAR1_BAZ2", TokenType.IDENTIFIER),
|
||||
("True", TokenType.TRUE),
|
||||
("False", TokenType.FALSE),
|
||||
("None", TokenType.NONE),
|
||||
],
|
||||
)
|
||||
def test_identifiers_keywords(src: str, expected: TokenType):
|
||||
tokens: list[Token] = scan(src)
|
||||
assert_n_tokens(tokens, 1)
|
||||
assert tokens[0].type == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"src,expected",
|
||||
[
|
||||
("#", TokenType.COMMENT),
|
||||
("# This is a comment", TokenType.COMMENT),
|
||||
(" ", TokenType.WHITESPACE),
|
||||
("\t", TokenType.WHITESPACE),
|
||||
("\r", TokenType.WHITESPACE),
|
||||
(" \t \t", TokenType.WHITESPACE),
|
||||
("\n", TokenType.NEWLINE),
|
||||
],
|
||||
)
|
||||
def test_misc(src: str, expected: TokenType):
|
||||
tokens: list[Token] = scan(src)
|
||||
assert_n_tokens(tokens, 1)
|
||||
assert tokens[0].type == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"src,expected_type,expected_value",
|
||||
[
|
||||
("0", TokenType.NUMBER, 0),
|
||||
("0.0", TokenType.NUMBER, 0),
|
||||
("1234.56", TokenType.NUMBER, 1234.56),
|
||||
],
|
||||
)
|
||||
def test_literals(src: str, expected_type: TokenType, expected_value: Any):
|
||||
tokens: list[Token] = scan(src)
|
||||
assert_n_tokens(tokens, 1)
|
||||
assert tokens[0].type == expected_type
|
||||
assert tokens[0].value == expected_value
|
||||
|
||||
|
||||
def test_single_bang_error():
|
||||
with pytest.raises(SyntaxError):
|
||||
scan("!")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"src",
|
||||
[
|
||||
"-",
|
||||
"*",
|
||||
"/",
|
||||
"{",
|
||||
"}",
|
||||
"@",
|
||||
'"',
|
||||
"'",
|
||||
".",
|
||||
],
|
||||
)
|
||||
def test_unexpected_character(src: str):
|
||||
with pytest.raises(SyntaxError):
|
||||
scan(src)
|
||||
@@ -0,0 +1,130 @@
|
||||
from typing import Optional
|
||||
|
||||
import pytest
|
||||
|
||||
from core.ast.annotations import (
|
||||
AnnotationStmt,
|
||||
ConstraintExpr,
|
||||
Expr,
|
||||
LiteralExpr,
|
||||
SchemaElementExpr,
|
||||
SchemaExpr,
|
||||
Stmt,
|
||||
TypeExpr,
|
||||
WildcardExpr,
|
||||
)
|
||||
from lexer.annotations import AnnotationLexer
|
||||
from lexer.position import Position
|
||||
from lexer.token import Token
|
||||
from parser.annotations import AnnotationParser
|
||||
|
||||
|
||||
class AstSerializer(Stmt.Visitor[str], Expr.Visitor[str]):
|
||||
def serialize(self, stmt: Stmt):
|
||||
return stmt.accept(self)
|
||||
|
||||
def visit_annotation_stmt(self, stmt: AnnotationStmt) -> str:
|
||||
schema: str = ""
|
||||
if stmt.schema is not None:
|
||||
schema = " " + stmt.schema.accept(self)
|
||||
return f"(annotation {stmt.name.lexeme}{schema})"
|
||||
|
||||
def visit_schema_expr(self, expr: SchemaExpr) -> str:
|
||||
elements: list[str] = [elmt.accept(self) for elmt in expr.elements]
|
||||
return f"(schema {' '.join(elements)})"
|
||||
|
||||
def visit_schema_element_expr(self, expr: SchemaElementExpr) -> str:
|
||||
name: str = expr.name.lexeme if expr.name is not None else "_"
|
||||
type: str = expr.type.accept(self) if expr.type is not None else "_"
|
||||
return f"({name} {type})"
|
||||
|
||||
def visit_type_expr(self, expr: TypeExpr) -> str:
|
||||
res: str = f"({expr.name.lexeme}"
|
||||
for constraint in expr.constraints:
|
||||
res += " " + constraint.accept(self)
|
||||
res += ")"
|
||||
return res
|
||||
|
||||
def visit_constraint_expr(self, expr: ConstraintExpr) -> str:
|
||||
return f"(constraint {expr.left.accept(self)} {expr.op.lexeme} {expr.right.accept(self)})"
|
||||
|
||||
def visit_wildcard_expr(self, expr: WildcardExpr) -> str:
|
||||
return "(_)"
|
||||
|
||||
def visit_literal_expr(self, expr: LiteralExpr) -> str:
|
||||
return f"({expr.value})"
|
||||
|
||||
|
||||
def parse(source: str) -> Optional[Stmt]:
|
||||
tokens: list[Token] = AnnotationLexer(source).process()
|
||||
return AnnotationParser(tokens).parse()
|
||||
|
||||
|
||||
def must_parse(source: str) -> Stmt:
|
||||
stmt: Optional[Stmt] = parse(source)
|
||||
assert stmt is not None
|
||||
return stmt
|
||||
|
||||
|
||||
def ast_str(source: str) -> str:
|
||||
stmt: Stmt = must_parse(source)
|
||||
return AstSerializer().serialize(stmt)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"src,expected",
|
||||
[
|
||||
("Type", "(annotation Type)"),
|
||||
("Type[]", "(annotation Type (schema ))"),
|
||||
(
|
||||
"""
|
||||
Frame[
|
||||
verified: bool,
|
||||
birth_year: int,
|
||||
height: float + ( _ > 0 ) + ( _ < 250 ),
|
||||
name: str,
|
||||
date: datetime,
|
||||
float, # unnamed
|
||||
unknown: _, # untyped
|
||||
_ # unnamed and untyped
|
||||
]
|
||||
""",
|
||||
"(annotation Frame (schema (verified (bool)) (birth_year (int)) (height (float (constraint (_) > (0.0)) (constraint (_) < (250.0)))) (name (str)) (date (datetime)) (_ (float)) (unknown _) (_ _)))",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_expressions(src: str, expected: str):
|
||||
assert ast_str(src) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"src,pos,should_fail",
|
||||
[
|
||||
("", (1, 1), True),
|
||||
("42", (1, 1), True),
|
||||
("True", (1, 1), True),
|
||||
("Type[", (1, 6), True),
|
||||
("Type[] Type2", (1, 8), False),
|
||||
("Type[bool:]", (1, 11), True),
|
||||
("Type[3]", (1, 6), True),
|
||||
("Type[bool float]", (1, 11), True),
|
||||
("Type[bool (_ < 2)]", (1, 11), True),
|
||||
("Type[bool + _ < 2)]", (1, 13), True),
|
||||
("Type[bool + (_ < 2]", (1, 19), True),
|
||||
("Type[bool + (< 2)]", (1, 14), True),
|
||||
("Type[bool + (_ + 2)]", (1, 16), True),
|
||||
("Type[bool + (Foo + Bar)]", (1, 14), True),
|
||||
# ("Type[bool,]", (1, 11), True), # trailing comma is accepted, TODO: update parser or EBNF
|
||||
("Type[bool, Type[]]", (1, 16), True),
|
||||
("Type[foo: 3]", (1, 11), True),
|
||||
],
|
||||
)
|
||||
def test_parsing_error(src: str, pos: tuple[int, int], should_fail: bool):
|
||||
tokens: list[Token] = AnnotationLexer(src).process()
|
||||
parser: AnnotationParser = AnnotationParser(tokens)
|
||||
stmt: Optional[Stmt] = parser.parse()
|
||||
if should_fail:
|
||||
assert stmt is None
|
||||
assert len(parser.errors) != 0
|
||||
error_pos: Position = parser.errors[0].token.position
|
||||
assert (error_pos.line, error_pos.column) == pos
|
||||
Reference in new issue
Block a user