named: Add a semantic name to a parser for better error messages

View source: R/parsers_error.R

namedR Documentation

Add a semantic name to a parser for better error messages

Description

named() wraps a parser and provides a meaningful name that will be shown in error messages when the parser fails. This is particularly useful for user-defined parsers to make error messages more informative.

Usage

named(p, name)

Arguments

p

a parser.

name

a character string describing what the parser expects.

Value

A parser.

Examples

# Define a parser with a semantic name
Nucleotide <- function() {
  named(
    satisfy(function(x) grepl("^[GATC]+$", x)),
    "nucleotide sequence"
  )
}

# When this parser fails, the error will say "Expected: nucleotide sequence"
try(reporter(Nucleotide() %then% eof())(c("GATCxTC")))

# Combine named parsers with %or% to get helpful "Expected one of:" messages
Nucleotide_or_Protein <- function() {
  named(satisfy(function(x) grepl("^[GATC]+$", x)), "nucleotide") %or%
    named(satisfy(function(x) grepl("^[ARNDCQEGHILKMFPSTWYV]+$", x)), "protein")
}

try(reporter(Nucleotide_or_Protein() %then% eof())(c("Some text")))


parcr documentation built on Feb. 15, 2026, 5:07 p.m.