romshark / llparser

A universal LL top-down parser written in Go
BSD 3-Clause "New" or "Revised" License
45 stars 1 forks source link

[FTR] FragmentKind translation in PrintFragment #12

Closed romshark closed 4 years ago

romshark commented 4 years ago

Currently, llparser.PrintFragment prints the token kind as a number in a non human-readable way:

2(test.boolexp: 1:1-1:5 'true') {
  3(test.boolexp: 1:1-1:5 'true')
}

Proposal

llparser.PrintFragment should take an optional lambda function as an additional parameter mapping kind-identifiers to their corresponding names:

func PrintFragment(
    fragment Fragment,
    out io.Writer,
    indent string,
    kindTranslator func(FragmentKind) string,
) (bytesWritten int, err error)

If kindTranslator != nil then the returned string should be used for the token kind instead of the numeric id:

func PrintFragment(
    frag,
    os.Stdout,
    "  ",
    func(kind FragmentKind) string {
        switch kind {
        case 2:
            return "Second"
        case 3:
            return "Third"
        }
        return ""
    },
)

Should print:

Second (test.boolexp: 1:1-1:5 'true') {
  Third (test.boolexp: 1:1-1:5 'true')
}