kaitai-io / kaitai_struct

Kaitai Struct: declarative language to generate binary data parsers in C++ / C# / Go / Java / JavaScript / Lua / Nim / Perl / PHP / Python / Ruby
https://kaitai.io
4k stars 196 forks source link

Nested switch-on support #386

Open hakanai opened 6 years ago

hakanai commented 6 years ago

A .ksy file I found for parsing apfs filesystems has a construct like this:

type:
  switch-on: '(((_parent.node_type & 2) == 0) ? 256 : 0) + _parent._parent.hdr.o_subtype.to_i * (((_parent.node_type & 2) == 0) ? 0 : 1)'
  cases:
    256: pointer_record # applies to all pointer records, i.e. any entry val in index nodes
    obj_subtype::location.to_i: location_record
    obj_subtype::files.to_i: file_record
    ...

Though I do think that the expression they wrote was not the most compact option, it seems like it would be much neater if we could instead write:

type:
  switch-on: _parent.node_type & 2
  cases:
    0: pointer_record # applies to all pointer records, i.e. any entry val in index nodes
    1:
      switch-on: _parent._parent.hdr.o_subtype
      cases:
        obj_subtype::location.to_i: location_record
        obj_subtype::files.to_i: file_record
    ...

I'm about to add an additional level of hierarchy to this decision tree, which is going to make it much messier than it is already.

GreyCat commented 6 years ago

A good idea, but would probably require some time to be implemented.

As a workaround I might propose splitting that complex logic into separate types, i.e. something like:

type:
  switch-on: first_condition
  cases:
    0: first_0
    1: first_1
# ...
types:
  first_1:
    seq:
      - id: value
        type:
          switch-on: second_condition
          cases:
            0: first_1_second_0
            1: first_1_second_1
# etc