【问题标题】:Is there a golang library similar to Python's construct? [closed]是否有类似于 Python 构造的 golang 库? [关闭]
【发布时间】:2016-09-09 12:59:11
【问题描述】:

我真的很喜欢 Python 构造模块用于定义双向(二进制|文本)解析器/构建器的声明性语法。

我最近开始关注 golang,想知道是否有人看过(或者可能是受人尊敬的作者)类似的 golang 库。

如果您从未使用过 construct 模块,那么您基本上构建了一个 Python 对象的声明性树,您可以将 Python 对象树提供给它并获取二进制 blob,或者将二进制 blob 解析为 Python 对象树。

构建网页中的一个简单示例:

>>> PascalString2 = ExprAdapter(PascalString,
...     encoder = lambda obj, ctx: Container(length = len(obj), data = obj),
...     decoder = lambda obj, ctx: obj.data
... )
>>> PascalString2.parse("\x05hello")
'hello'
>>> PascalString2.build("i'm a long string")
"\x11i'm a long string"

来自显示硬盘驱动器 MBR 解析器的源代码中的稍微复杂一点的示例。

mbr = Struct("mbr",
    HexDumpAdapter(Bytes("bootloader_code", 446)),
    Array(4,
        Struct("partitions",
            Enum(Byte("state"),
                INACTIVE = 0x00,
                ACTIVE = 0x80,
            ),
            BitStruct("beginning",
                Octet("head"),
                Bits("sect", 6),
                Bits("cyl", 10),
            ),
            Enum(UBInt8("type"),
                Nothing = 0x00,
                FAT12 = 0x01,
                XENIX_ROOT = 0x02,
                XENIX_USR = 0x03,
                FAT16_old = 0x04,
                Extended_DOS = 0x05,
                FAT16 = 0x06,
                FAT32 = 0x0b,
                FAT32_LBA = 0x0c,
                NTFS = 0x07,
                LINUX_SWAP = 0x82,
                LINUX_NATIVE = 0x83,
                _default_ = Pass,
            ),
            BitStruct("ending",
                Octet("head"),
                Bits("sect", 6),
                Bits("cyl", 10),
            ),
            UBInt32("sector_offset"), # offset from MBR in sectors
            UBInt32("size"), # in sectors
        )
    ),
    Const("signature", b"\x55\xAA"),
)

有一个TCP/IP stack 示例真正展示了构造模型的强大功能,能够将一小段定义块组合成一个解析器/生成器。

我知道有 PEG / EBNF 解析器生成器,但我希望看到一些更漂亮的东西。

【问题讨论】:

  • 嗨,@synthesizerpatel!我有类似的问题。不知道你有没有发现什么有用的东西?

标签: parsing go data-structures declarative


【解决方案1】:

这和 Python 的 Construct 包不一样,但是 Go 有一个 Yacc 的版本:

Yacc 的语法和 EBNF 类似,所以可能不符合你的标准,但是被广泛使用和理解,所以我觉得值得一提。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-25
    • 2010-09-24
    • 2011-01-08
    • 1970-01-01
    • 2011-11-14
    • 1970-01-01
    • 2015-08-20
    • 2015-04-09
    相关资源
    最近更新 更多