Handling the presence or absence of a token in EBNF / Lark

I’m making early steps with the Lark library in Python and am really looking forward to replacing a lot of awful if statements with an EBNF parser..!

The task here is interpreting the times written in railway timetables. 12:34 means the train will stop, 12/34 means the train is not expected to stop, 12d34 means the train may stop to set down passengers only… and there’s at least four more variations like this. Times are to the half-minute: 12:34h means 12:34:30 and it’s that h I’m having trouble with.

I have a dataclass and enum to store the parsed values:

from dataclasses import dataclass
from enum import Enum, auto

@dataclass(frozen=True)
class TTime:
    class StopMode(Enum):
        STOPPING = auto()
        PASSING = auto()
        SET_DOWN = auto() # etc...

    hour: int
    minute: int
    second: int = 0
    stopmode: StopMode = StopMode.PASSING
from lark import Lark, Transformer

class TreeToTTime(Transformer):
    def hour(self, n):
        return int("".join(n))
    def minute(self, n):
        return int("".join(n))
    def stopmode(self, n):
        (n,) = n
        return n
    
    def stopping(self, _):
        return TTime.StopMode.STOPPING
    def passing(self, _):
        return TTime.StopMode.PASSING
    def setdown(self, _):
        return TTime.StopMode.SET_DOWN

    def halfminute(self, _):
        return True

    def ttime(self, args):
        hour, stopmode, minute, halfminute = args
        second = 30 if halfminute else 0

        return TTime(hour, minute, second, stopmode)
ttime_parser = Lark(
    r"""
ttime           :  hour stopmode minute halfminute?

hour            : ("0".."2")? DIGIT
minute          : ("0".."5") DIGIT

stopmode        : stopping | passing | setdown
stopping        : ":"
passing         : "/"
setdown         : "d"

halfminute      : "h" | "H"

%import common.DIGIT
%import common.WS
%ignore WS
""",
    start="ttime",
)

def parse_ttime(text):
    tree = ttime_parser.parse(text)
    return TreeToTTime().transform(tree)
import pytest
@pytest.mark.parametrize(
    "text,expected",
    [
        (" 0:00", TTime(0, 0, 0, TTime.StopMode.STOPPING)),
        ("13:20", TTime(13, 20, 0, TTime.StopMode.STOPPING)),
        ("00/00", TTime(0, 0, 0, TTime.StopMode.PASSING)),
        ("12d34", TTime(12, 34, 0, TTime.StopMode.SET_DOWN)),
        # ("01:23h", TTime(1, 23, 30, TTime.StopMode.STOPPING)),
    ],
)
def test_parse_times(text, expected):
    assert expected == parse_time(text)

The problem is the args passed to ttime. If halfminute is absent i.e. 12:34, args has three values: (12, StopMode.STOPPING, 34). If halfminute is present i.e. 12:34h it’s four values: (12, StopMode.STOPPING, 34, True).

How do I configure the transformer here to include the absence of a token? For 12:34 I’d like args to be [12, StopMode.STOPPING, 34, False] for example.

I could write:

hour, stopmode, minute, halfminute, *_ = args + (False,)

but I feel this is not the right approach – it only works because the halfminute token is the final token for example.

Any other pointers gratefully received – I feel I’ve made rapid progress this evening but there’s still a lot I’ll be missing!

The answer is to mark halfminute as optional with square brackets not a question mark:

ttime : hour stopmode minute [halfminute]

With the maybe_placeholder parser argument set to True (which is the default), [x] will parse as a token for x if matched or None if not.

A more minimal example:

from lark import Lark

grammar = """
start : [A] B?
A : "a"
B : "b"
"""

parser = Lark(grammar)

for x in ("a", "b", "ab", ""):
    print(parser.parse(x))

This outputs:

Tree(Token('RULE', 'start'), [Token('A', 'a')])
Tree(Token('RULE', 'start'), [None, Token('B', 'b')])
Tree(Token('RULE', 'start'), [Token('A', 'a'), Token('B', 'b')])
Tree(Token('RULE', 'start'), [None])

i.e. [A] is either present with a value or is None. B? is either present with a value or absent.

There’s a bunch of other problems with my code here which I’m still working out – however it does technically work 🙂


I’ve iterated on the grammar and the transformer to something I’m much happier with. (Previous iterations in the post history.)

time            :  HOUR stopmode MINUTE [HALFMINUTE]

HOUR            : ("0".."2")? DIGIT
MINUTE          : ("0".."5")? DIGIT
HALFMINUTE      : "h" | "H" | "½"

stopmode:       STOPPING | PASSING | SET_DOWN | IF_REQUIRED
                | REQUEST_STOP | DWELL_TIME | THROUGH_LINE

STOPPING        : ":"
PASSING         : "/"
SET_DOWN        : "d"
IF_REQUIRED     : "*"
REQUEST_STOP    : "r"
DWELL_TIME      : "w"
THROUGH_LINE    : "t"

%import common.DIGIT
%import common.WS
%ignore WS
class TreeToTTime(Transformer):
    def time(self, args):
        hour, stopmode, minute, second = args
        return TTime(hour, minute, second or 0, stopmode)

    def HOUR(self, n):
        return int("".join(n))

    def MINUTE(self, n):
        return int("".join(n))

    def HALFMINUTE(self, _):
        return 30
    
    def stopmode(self, args):
        (mode,) = args
        return getattr(TTime.StopMode, mode.type, TTime.StopMode.PASSING)

There is now only a coupling between the terminal names in the grammar and the enum value names in the domain object, which I think is quite acceptable!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật