mug / dot-parse
AGENTS.md540 starsChanged 12 days agoApache-2.0View on GitHub
When generating or refactoring code using the dot-parse library, you MUST follow these rules to ensure safety, performance, and idiomatic style. - Always make the domain data model immutable (e.g., using Java records). - Use "wither" methods (methods that return a new instance with the updated property) for optional properties or modifiers. - Rule of thumb for withers: - The language to be parsed represents the user's mental model. - If in the mental model, the data can be expressed…
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.
Of the AGENTS.md files we read, the 35,266 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository3 other files it gives its agents.
The file
Show its rules and text
We split this AGENTS.md into the rules it gives an agent
17 rules. About 0 are common, 2 are distinctive, and 15 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
15
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 3
When generating or refactoring code using the dot-parse library, you MUST follow these rules to ensure safety, performance, and idiomatic …
- Distinctive: line 14
If in the mental model, the data can be expressed with or without a property (which usually has a default value), the data model should …
- Very specific: line 54
Do NOT use Parser.consecutive(), Parser.anyOf(), etc.
- Distinctive: line 118
Instead, consider these safe patterns:
- Very specific: line 299
Parsing Key-Value Pairs with Optional Trailing Comma: Use the static zeroOrMoreDelimited() method to parse pairs into a map, and use …
- Very specific: line 348
If after matching, you need the matched string, attach a .source() call.
- Very specific: line 359
Option 1 (Reduce Cardinality): If some rules don't produce a value (or the value is ignored), use .followedBy(unusedRule) or …
- Very specific: line 363
Option 2 (Custom Helper): Create the corresponding functional interface (assume it's named Fun6).
- Very specific: line 432
Minimize primitive-type parsers: Avoid creating top-level parsers that return primitive types like String or Integer unless they are …
- Very specific: line 471
Always: verify the existence of a method in Parser.java, Parsers.java, CharPredicate.java or CharacterSet.java, OperatorTable.java before …
- Very specific: line 505
If you need a method not listed above, you MUST open and read Parser.java or Parsers.java to check if it exists.
- Very specific: line 513
Never: use consecutive("abc"). Always use consecutive("[abc]").
- Very specific: line 519
Instead, attach the OrEmpty to an existing consuming Parser via sequence(), then(), followedBy() etc.
- Very specific: line 525
Example: If you want to parse a word ending with 's' (like "words"), word().followedBy("s") will fail because word() consumes the 's' and …
- Very specific: line 528
Predicate Names in Error Messages: When passing a CharPredicate to methods like one(), consecutive(), zeroOrMore(), or using suchThat(), …
- Very specific: line 535
Exception: If you use CharacterSet overloads like consecutive("[a-z]"), the character class string is automatically used, so you don't need …
- Very specific: line 547
Option 2: Use an explicit type witness, e.g., Parser.<SuperType>anyOf(subtypeParser1, subtypeParser2).
≈ “Common” is an estimate: at least 1 in 5 of the 45,344 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Rules for AI Agents Generating dot-parse Code
When generating or refactoring code using the dot-parse library, you MUST
follow these rules to ensure safety, performance, and idiomatic style.
1. Data Model Design
- Always make the domain data model immutable (e.g., using Java
records). - Use "wither" methods (methods that return a new instance with the updated property) for optional properties or modifiers.
Rule of thumb for withers:
- The language to be parsed represents the user's mental model.
- If in the mental model, the data can be expressed with or without a property (which usually has a default value), the data model should reflect that.
- The convenience factory method should assume that default value, and an incremental "wither" should be used to attach it optionally.
- This enables clean functional chaining using method references (e.g.,
AbcNote::withDuration) rather than lambdas. Prefer method references over lambdas when using withers in combinators like
optionallyFollowedBy()andsequence().public record AbcNote( Accidental accidental, char pitch, int octave, NoteDuration duration) { // Factory assumes default duration and octave = 0 public static AbcNote middle(char pitch) { return new AbcNote(null, pitch, 0, NoteDuration.of(1)); } // Factory assumes default duration and octave = 1 public static AbcNote high(char pitch) { return new AbcNote(null, pitch, 1, NoteDuration.of(1)); } // Wither attaches it optionally public AbcNote withDuration(NoteDuration duration) { return new AbcNote(accidental, pitch, octave, duration); } }- Prefer creating enums in the data model for reserved words, operators,
etc., with their
toString()returning the canonical form (e.g.,DOUBLE_SHARP("^^")). This enables building parsers cleanly using theanyOf(Enum[])overload (e.g.,anyOf(MyEnum.values())).
2. Static Import
- Always static import
dot-parsefactory methods from theParserclass andCharPredicateclasses. Do NOT use
Parser.consecutive(),Parser.anyOf(), etc. Useconsecutive(),anyOf()directly.import static com.google.common.labs.parse.Parser.anyOf; import static com.google.common.labs.parse.Parser.consecutive; import static com.google.common.labs.parse.Parser.string;
3. Safety against Infinite Loops (Zero-Width Parsers)
Unlike most parser combinator libraries, Dot-Parse deliberately outlaws zero-width parsers because it's too easy to shoot yourself in the foot, running into an infinite loop by sneakily nesting it within a repetition parser.
You don't see parser people talk about it often but when it happens, the
program hangs. And even if you manually kill the VM and take a thread dump,
the dump would only show that it failed in a loop deeply inside the many()
library method body, but giving you no idea which of your grammar had
incorrectly used a zero-width parser, because that parser object construction
code is somewhere in the wild, just not in the stack trace of the parse()
call! It's like saying: "Yeah man, you were dead. It was bad, death was
bad.", but just won't tell you what killed you.
The optional(), orElse() and zeroOrMore() are only to be used in safe
places like followedBy(), then(), between(), immediatelyBetween() etc.
where the composite parser is guaranteed to consume input.
Always attach optional Parser rules to a Parser that consumes input.
While it may feel tempting to want to do something like this:
// Won't compile!
Parser<String> parent = word().followedBy(".").orElse("this");
Parser<List<String>> ancestors = parent.atLeastOnce();It would have opened a can of worms named infinite loops, if the API had
allowed it. That's why in the Parser API, the code above would not compile
(because orElse() returns a special OrEmpty type, not a Parser). So
don't try it! You are forced to complete the fluent chain using methods on
OrEmpty that ensure safety.
- Chaining Optional Parsers: Optional parsers (e.g., from
.optional(),.orElse(),.zeroOrMore()) return aParser.OrEmptyinstance. You can chain them usingOrEmptymethods like.then(),.followedBy(), and.delimitedBy(), which continue to returnOrEmpty. - Exiting the Unsafe Zone: To convert an
OrEmptychain back into a standardParser, you must eventually attach it to a non-emptyParserusing methods likeParser.then(),Parser.followedBy(),Parser.sequence(Parser, Production...)orOrEmpty.between()/OrEmpty.immediatelyBetween(). This ensures the composite parser is guaranteed to consume input. - The
ProductionInterface: Represents either aParseror aParser.OrEmpty. Overloads likesequence(Parser, Production...)can take either type for the 2nd production rule and the remaining. - Common Combinators: The
Productioninterface defines common methods shared by bothParserandOrEmpty, includingbetween(),immediatelyBetween(),then(),followedBy(), andoptionallyFollowedBy(). Make sure to use them when dealing with either aParserorOrEmpty.
Instead, consider these safe patterns:
Prefer
optionallyFollowedBy()for an optional suffix that may be present zero or one time:Parser<String> wordAllowingTrailingComma = word().optionallyFollowedBy(","); Parser<Note> noteWithOptionalOctave = note.optionallyFollowedBy(octave, Note::withOctave);- Use
followedBy(suffix.zeroOrMore())for a suffix that may occur zero or many times. - Use
optionallyFollowedBy(suffixString)if an optional suffix string doesn't change the result. - Use
sequence(p1, p2, ..., pn)if you don't need the result instead ofp1.then(p2)...then(pn)for more readable code. Use
anyOf()to split the rule into two choices for an optional prefix:anyOf( sequence(accidental, note, (a, n) -> n.withAccidental(a)), // with prefix note) // without prefixThis works particularly well when you have incremental "withers" or overloaded constructor or factory methods. But remember to put the choice with the prefix first.
Alternatively, you could also use
sequence(optionalPrefix.orElse(defaultValue), suffix, (a, b) -> ...)if "wither" or overloaded constructors aren't good fit.Use
withPrefixes()if the prefix can show zero or more times, and each time incrementally modifies the result but returns the same type:note.withPrefixes(accidental, (a, n) -> n.withAccidental(a))Use
anyOf()again if the prefixes are supposed to be accumulated into a collection like aList:anyOf( sequence( accidental.atLeastOnce(), note, (a, n) -> n.withAccidentals(a)), // with non-empty prefixes note); // no prefix- Use
OperatorTableclass to define a grammar with prefixes, postfixes, and infix operators declaratively, particularly when they have different precedents.
4. Optional Suffixes
- Always prefer
optionallyFollowedBy(). It is not only more efficient (avoids backtracking), but it also produces more readable and intentional code than listing alternatives using
anyOf:// Good: Expresses intent clearly ("A number, optionally followed by a // denominator") NUM.map(NoteDuration::of) .optionallyFollowedBy(DURATION_DENOMINATOR, NoteDuration::withDenominator)
5. Left Recursion
Left recursion isn't supported. Use .optionallyFollowedBy() for optional
suffixes; use OperatorTable for prefix/postfix/infix.
A common left recursive grammar is like Java's instance method calls, where the method call is an expression and the method receiver is also an expression.
Or, Java's nested types: Enclosing.Nested is a Type, so is Enclosing
itself.
The typical way to parse these naturally left-recursive grammars is to model
it as a postfix unary operator. In the method call expression, the
.methodName(argExpressions) can be modeled as a postfix operator:
Parser<Expr> literal = anyOf(
quotedByWithEscapes('"', '"', chars(1)).map(StringLiteral::new),
digits().map(IntLiteral::new));
Parser<Expr> atomic = anyOf(word().map(Variable::new), literal);
Parser<Expr> expr = Parser.define(self ->
new OperatorTable<Expr>()
.postfix(
sequence(
string(".").then(word()),
self.zeroOrMoreDelimitedBy(",").between("(", ")"),
UnqualifiedMethodCall::new),
(receiver, call) -> call.withReceiver(receiver))
// ...
.build(atomic));Nested type parser:
Parser<TypeDecl> simpleType = word().map(TypeDecl::simple);
Parser<TypeDecl> typeDecl =
simpleType.followedByZeroOrMore(string(".").then(word()), TypeDecl::nested);6. Idiomatic Combinators
- Always use
.parseSkipping(CharPredicate, String)or.skipping(charPredicate).parse(String)to omit whitespace and comments. - Never try to skip them manually in the grammar (e.g., using
.followedBy(zeroOrMore(whitespace()))). - Prefer attaching
simplerParser.suchThat(customPredicate, name)over encoding a complex parser.- Example:
word().suchThat(w -> w.length() < 8, "short word"), as opposed to constructing a more complex parser.
- Example:
Prefer
thenReturn(value)over.map(unused -> value)when mapping a successful match to a constant.// Good string("true").thenReturn(true)Prefer the
anyOf(Enum[])overload (passingEnum.values()) when parsing a fixed set of enum values over manual alternation of string parsers usinganyOf(Parser...).- Example:
anyOf(Accidental.values()) - It automatically handles prefix matching by trying longer strings first (e.g., trying "++" before "+").
- Example:
Prefer the
anyOf(String, String, ...)overload when matching a fixed set of string values.- Example:
anyOf("http", "https", "ftp", "ssl") - It automatically handles prefix matching by trying longer strings first (e.g., trying "https" before "http").
- Example:
Use
quotedBy(before, after)andquotedByWithEscapes(before, after, escaped)to parse quoted strings instead of reinventing the wheel.quotedByis for simple cases where no escaping is needed.quotedByWithEscapeshandles backslash escapes. Theescapedparser parameter defines what happens after the backslash.Simple case (any character can be escaped): Pass
chars(1)as theescapedparser.quotedByWithEscapes('"', '"', chars(1))C-style escaping (handle
\n,\t,\retc.):Parser<String> cStyleEscape = anyOf( string("n").thenReturn("\n"), string("t").thenReturn("\t"), string("r").thenReturn("\r"), chars(1)); // fallback for other escaped chars Parser<String> quoted = quotedByWithEscapes('"', '"', cStyleEscape);Unicode escaping (e.g.,
\u1234): UsebmpCodeUnit()to parse the 4-digit hex code.Parser<String> unicodeEscape = string("u") .then(bmpCodeUnit()) .map(Character::toString); Parser<String> escaped = anyOf(unicodeEscape, chars(1)); Parser<String> quoted = quotedByWithEscapes('"', '"', escaped);
Prefer
parser.between("(", ")")over the more verbosestring("(").then(parser).followedBy(")")when parsing content enclosed in delimiters.- It is more readable and concise.
Example:
Parser<Expr> parenthesized = expr.between("(", ")");
Parsing Key-Value Pairs with Optional Trailing Comma: Use the static
zeroOrMoreDelimited()method to parse pairs into a map, and use.optionallyFollowedBy(",")to handle the trailing comma.- This is more idiomatic and concise when collecting into a map.
Example:
import static com.google.mu.util.stream.BiCollectors.toMap; Parser<Map<String, String>> mapParser = zeroOrMoreDelimited( word().followedBy(":"), quotedByWithEscapes('"', '"', chars(1)), ",", toMap()) .optionallyFollowedBy(",") .between("{", "}");Line-by-line breakdown:
zeroOrMoreDelimited(...): A static factory method specifically designed to parse pairs of items separated by a delimiter and collect them using aBiCollector.word().followedBy(":"): Parses the key (a word) and requires it to be followed by:. The:is ignored in the output, so this parser returns the key as aString.quotedByWithEscapes('"', '"', chars(1)): Parses the value as a quoted string, handling backslash escapes. It returns the content inside the quotes as aString.",": Specifies that the key-value pairs are separated by commas.BiCollectors.toMap(): collects the pairs into aMap<String, String>. You can also use method reference (not direct method calls) of standard JDK collectors as long as their signatures have two function parameters to extract the key and the value, such asCollectors::toUnmodifiableMap..optinallyFollowedBy(","): An optional suffix that allows a trailing comma after the last pair. Only if you need to support trailing comma..between("{", "}"): Ensures the entire map is enclosed in curly braces.
- Note on Whitespace: Whitespaces will be skipped automatically between
tokens when calling
parseSkipping(Character::isWhitespace, ...)orskipping(Character::isWhitespace). This is why the grammar above doesn't need to explicitly handle whitespace between tokens.
- Use
sequence(Parser, Production...)with no lambda when you don't need to the constituent parser rules' results but only need to express a pattern similar to regex. Example:sequence(digits(), dot, digits(), dot, digits()).- It's more efficient than chaining
then()or.followedBy()methods. - It's more readable too.
- If after matching, you need the matched string, attach a
.source()call.
- It's more efficient than chaining
- Use
then()withorElse(defaultValue)when a parser is followed by an optional component that should fall back to a default value if missing.- The
then()method accepts both a standardParserand aParser.OrEmpty(returned byorElse()). - Example:
string("/").then(NUM.orElse(2))
- The
- Prefer
Parser.sequence(...)static method over awkwardly plumbing data through chained.flatMap()when handling 2-4 sequential rules.- Example:
sequence(owner, nested, args, (o, n, a) -> ...);
- Example:
When handling more than 4 sequential rules, you have two options:
- Option 1 (Reduce Cardinality): If some rules don't produce a value
(or the value is ignored), use
.followedBy(unusedRule)orprefix.then(parser)to reduce the number of values passed tosequence(). Option 2 (Custom Helper): Create the corresponding functional interface (assume it's named
Fun6). Then create a customsequence()helper that nests calls usingMap::entryto pair up results, and then unpacks them in a final mapper.static <R> Parser<R> sequence( Parser<A> a, Parser<B> b, Parser<C> c, Parser<D> d, Parser<E> e, Parser<F> f, Fun6<? super A, ? super B, ? super C, ? super D, ? super E, ? super F, ? extends R> mapper) { return sequence( sequence(a, b, Map::entry), sequence(c, d, Map::entry), sequence(e, f, Map::entry), (p1, p2, p3) -> mapper.apply( p1.getKey(), p1.getValue(), p2.getKey(), p2.getValue(), p3.getKey(), p3.getValue())); }And then just use it (e.g., to parse a Java method definition):
sequence( modifier, access, returnType, methodName, args, throwsSpec, MethodDef::new);
- Option 1 (Reduce Cardinality): If some rules don't produce a value
(or the value is ignored), use
Use
Parser.followedBy(suffix)to ignore a suffix when nested in asequence()call. Then you won't need to declare an unused lambda parameter for that ignored suffix.// Good sequence(owner.followedBy("."), nested, args, (o, n, a) -> ...);- Use
prefix.then(parser)to ignore a prefix when nested in asequence()call. Use
Parser.sequence(Parser, Production...)for regex DFA-style rules when matching a sequence of rules as a single whole. This is cleaner and less error-prone than awkwardly chaining.then()and.followedBy().For example:
// Good: Clear, linear representation of the sequential components Parser<String> usPhoneNumber = sequence(digits(3), string("-"), digits(3), string("-"), digits(4)) .source();It avoids the syntactic clutter and cognitive load of chaining combinators:
// Bad: Harder to read and verify due to alternating then/followedBy calls Parser<String> usPhoneNumber = digits(3) .followedBy("-") .then(digits(3)) .followedBy("-") .then(digits(4)) .source();- Minimize top-level parsers per domain type: Ideally, create at most one canonical parser per domain type to ensure consistency and avoid misuse.
- Minimize primitive-type parsers: Avoid creating top-level parsers that
return primitive types like
StringorIntegerunless they are explicitly needed for reuse. Map them to domain types as early as possible to leverage strong typing. - Minimize the lambda body of recursive parsers: In
Parser.define(self -> ...), keep the lambda body as small as possible. Extract out sub-parsers that do not depend on the fixed pointself.
7. Coding Style
- Avoid long lambdas. Consider if the lambda or the majority of the lambda body should live in the domain record itself (often the logic benefits direct callers even when not parsing).
8. Performance
- Always Use
consecutive(characterClass)orconsecutive(charPredicate, name)overone(charPredicate, name).atLeastOnce(joining()). The latter is substantially more expensive. - Always Use
zeroOrMore(characterClass)orzeroOrMore(charPredicate, name)overone(charPredicate, name).zeroOrMore(joining()). The latter is substantially more expensive. - Prefer
consecutive("[a-fA-F0-9]")overconsecutive(CharPredicate predicate, String name)because the latter is more verbose and doesn't enable prefix-based pruning. - Prefer
p1.optionallyFollowedBy(p2, The::wither)overanyOf(sequence(p1, p2, ...), p1).optionallyFollowedBy()is both more readable and more efficient. - Prefer
string("c")orone('c')overone(is('c')). They avoid parse-time allocation (they just return the passed-in string as is) and are more friendly to prefix-based pruning.
9. Avoiding API Hallucination
- Never guess or invent methods on
Parser. AI agents tend to hallucinate methods likemany()orsepBy1()from other libraries. Indot-parse, useatLeastOnce(),atLeastOnceDelimitedBy(),zeroOrMore()andzeroOrMoreDelimitedBy()instance methods, andconsecutive()andzeroOrMore()static factory methods. - Always verify the existence of a method in
Parser.java,Parsers.java,CharPredicate.javaorCharacterSet.java,OperatorTable.javabefore generating code using it. Whitelist of Common Methods to keep you grounded:
- Use primitives:
string(s),one(char),one(characterClass),digits(),word(),consecutive(characterClass) - Use number constants in
Parsers:UNSIGNED_INTEGER(e.g.15,0),UNSIGNED_DECIMAL(e.g.1.23,15) andSIGNED_DOUBLE(e.g.-1.23e+4).UNSIGNED_INTEGERandUNSIGNED_DECIMALproduceString, so map them, e.g.UNSIGNED_INTEGER.map(Long::parseLong).SIGNED_DOUBLEproducesDouble; call.source()for the raw text, e.g.SIGNED_DOUBLE.source().map(BigDecimal::new). Use
Parsers.regex(pattern)for leaf-level tokens that are easier to express in regex than with combinators (e.g. fixed-width or intricate lexical formats). Use the capture-group overloads to extract group values:regex(pattern, g1 -> ...),regex(pattern, (g1, g2) -> ...), up to 8 groups. The number of capturing groups must equal the mapper arity; unmatched optional groups are passed asnull. Keep regex at the leaf level; compose structure (nesting, recursion, delimiters) with combinators. Pre-create and reuse the returned parser since the pattern is compiled on each call.Parser<PhoneNumber> phoneNumber = regex( "\\((?<areaCode>\\d{3})\\) \\d{3}-\\d{4}(?: x(?<extension>\\d+))?", (areaCode, extension) -> new PhoneNumber(areaCode, extension));- Use combinators:
anyOf(...),sequence(...),zeroOrMore(),atLeastOnce(),zeroOrMoreDelimitedBy(),atLeastOnceDelimitedBy() - Use safe optionals:
optionallyFollowedBy(...),withPrefixes(...),followedByZeroOrMore(...) - Use boundaries:
between(...),immediatelyBetween(...),followedBy(...),then(...)
- Use primitives:
- If you need a method not listed above, you MUST open and read
Parser.javaorParsers.javato check if it exists.
10. Common Pitfalls & Guardrails
CharacterSet Syntax:
Parser.consecutive(String)expects a string enclosed in square brackets, mimicking regex character classes.- Never use
consecutive("abc"). Always useconsecutive("[abc]").
- Never use
- Don't Abuse notEmpty():
notEmpty()shouldn't be abused as an escape hatch so you can "cast" anOrEmptytoParser. The only legit use case fornotEmpty()is if you have multipleOrEmptyinstances being sequenced together and the grammar dictates that the sequence cannot match empty even when every individual component is optional. Instead, attach theOrEmptyto an existing consumingParserviasequence(),then(),followedBy()etc. Greedy Matching:
zeroOrMoreandatLeastOnceare greedy. They will consume as much as possible and do not automatically backtrack to give back characters to a suffix parser.- Example: If you want to parse a word ending with 's' (like "words"),
word().followedBy("s")will fail becauseword()consumes the 's' and leaves nothing forfollowedBy("s").
- Example: If you want to parse a word ending with 's' (like "words"),
Predicate Names in Error Messages: When passing a
CharPredicateto methods likeone(),consecutive(),zeroOrMore(), or usingsuchThat(), you must provide a descriptive name parameter for error messages.- Example:
consecutive(Character::isDigit, "digit")orsuchThat(p -> p.isValid(), "valid item"). - Exception: If you use
CharacterSetoverloads likeconsecutive("[a-z]"), the character class string is automatically used, so you don't need to pass a name parameter.
- Example:
- Covariance in
anyOf()andParser.or(): BothanyOf()and theParser.or()collector support covariance.- PREFER defining a parser of a subtype as
Parser<Subtype>instead of widening it toParser<SuperType>. - AVOID using type casts or
.map(sub -> (SuperType) sub)to satisfy type inference. - To resolve type inference issues in
anyOf()when mixing subtypes:- Option 1: Explicitly define the local variable holding the result,
e.g.,
Parser<SuperType> p = anyOf(subtypeParser1, subtypeParser2);. - Option 2: Use an explicit type witness, e.g.,
Parser.<SuperType>anyOf(subtypeParser1, subtypeParser2).
- Option 1: Explicitly define the local variable holding the result,
e.g.,
- PREFER defining a parser of a subtype as
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

