Newer
Older
NewLang / src / syntax.py
# SPDX-License-Identifier: LGPL-2.1-only
# Copyright 2022 Jookia <contact@jookia.org>

import enum


# The type of syntax
class SyntaxType(enum.Enum):
    TOKEN = enum.auto()  # pragma: no mutate
    TEXT = enum.auto()  # pragma: no mutate
    BOOL = enum.auto()  # pragma: no mutate


# Represents a syntax node
class Syntax:
    def __init__(self, value, location, type):
        self.value = value
        self.location = location
        self.type = type

    def __repr__(self):
        return "Syntax(value %s, location %s, type %s)" % (  # pragma: no mutate
            repr(self.value),
            repr(self.location),
            str(self.type),
        )

    def __eq__(self, other):
        return (
            self.type == other.type
            and self.value == other.value
            and self.location == other.location
        )


# Location of a syntax node
class SyntaxLocation:
    def __init__(self, line, offset, file):
        self.line = line
        self.offset = offset
        self.file = file

    def __repr__(self):
        return "SyntaxLocation(line %i, offset %i, file '%s')" % (  # pragma: no mutate
            self.line,
            self.offset,
            self.file,
        )

    def __eq__(self, other):
        return (
            self.line == other.line
            and self.offset == other.offset
            and self.file == other.file
        )


# Represents a stream of consumable syntax nodes
class SyntaxStream:
    def __init__(self, nodes):
        self.nodes = nodes

    def __repr__(self):
        return "SyntaxStream(%s)" % (self.nodes)  # pragma: no mutate

    def pop(self):
        if self.nodes:
            return self.nodes.pop(0)
        else:
            return None

    def peek(self):
        if self.nodes:
            return self.nodes[0]
        else:
            return None