Skip to content

Using -switch may lead to dead code and the Go compiler complaining #181

Description

@Necoro

I noticed that when using -switch that the resulting code seems to be sub-par and does checks multiple times. For instance, I see

switch buffer[position] {
// [...]
case ' ':
	if buffer[position] != rune(' ') {
		goto l0
	}
	position++

The if is completely redundant (and slightly removes the point of switch if the ifs are just kept but now inside a switch :))

There are other, more involved examples:

switch buffer[position] {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
	{
		position5, tokenIndex5 := position, tokenIndex
		if c := buffer[position]; c < rune('0') || c > rune('9') {
			goto l6
		}
		position++
		goto l5
	l6:
		position, tokenIndex = position5, tokenIndex5
		if c := buffer[position]; c < rune('0') || c > rune('9') {
			goto l0
		}
		position++
	}
	l5:
		break

Here the whole code except for position++ is superfluous.

Example PEG:

package minimal

type Parser Peg {
}

OtherAttr <- [[A-Z_ 0-9]]+ _ ':' [^\n]*

_ <- [ \t]*

Activity

  1. Necoro commented on Jun 22, 2025

    @Necoro
    Author

    Ah! Trying the main branch this issue no longer exists.
    Time to cut a new release? And/or update the README to motivate people to install @main instead of @latest? :)

  2. Necoro commented on Jun 22, 2025

    @Necoro
    Author

    Reopening: The issue is not completely gone in main. The second block sometimes still exists and leads to the go compiler complain about unused labels:

    case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
    	{
    		position39, tokenIndex39 := position, tokenIndex
    		position++
    		goto l39
    	l40:
    		position, tokenIndex = position39, tokenIndex39
    		if c := buffer[position]; c < '0' || c > '9' {
    			goto l34
    		}
    		position++
    	}
    l39:
    	break

    Here, l40 and the code it references is dead.

  3. reopened this on Jun 22, 2025
  4. changed the title [-]Using -switch may check each rune multiple times[/-] [+]Using -switch may lead to dead code and the Go compiler complaining[/+] on Jun 22, 2025
  5. dolmen commented on May 22, 2026

    @dolmen
    Contributor

    @Necoro Could you provide a grammar that allows to reproduce your issue?

  6. Necoro commented on May 22, 2026

    @Necoro
    Author

    @Necoro Could you provide a grammar that allows to reproduce your issue?

    I provided one in the issue description. Although I haven't checked since then whether the issue still exists.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions