Skip to content

Release v3.8.0-alpha1

Pre-release
Pre-release

Choose a tag to compare

@b3b00 b3b00 released this 12 Feb 20:02
3974f0f

Ambiguous grammars

This alpha version is an attempt to allow ambiguous grammars.

CSLY now supports ambiguous grammars via parse forest capture and configurable resolution strategies. By default, behavior is unchanged.

  • Opt-in capture: set ParserConfiguration.CaptureAmbiguities = true to collect all optimal parses for ambiguous points.
  • Parse forest exposure: ParseResult.Forest provides multiple alternative syntax trees; ParseResult.SyntaxTree remains the main tree for backward compatibility.
  • Strategies: AmbiguityResolutionStrategy defines how the parser selects or surfaces alternatives:
    • First: pick the first successful derivation (legacy behavior).
    • All: keep all alternatives in Forest, no automatic visit.
    • ThrowException: raise when ambiguity is detected.
    • Longest: choose the derivation that consumes the most tokens (max end position).

Detection scope: ambiguity is detected when multiple alternatives succeed with the same maximum end position.

Ambiguity resolution strategy may be set in two ways :

  1. programatically by setting the parser.Configuration :

2 properties need to be set :

  1. CpatureAmbiguity : true id ambiguity must be managed, false otherwise
  2. AmbiguityResolutionStrategy : the resolution strategy AmbiguityResolutionStrategy enum.
parser.Configuration.CaptureAmbiguities = true;
parser.Configuration.AmbiguityStrategy = AmbiguityResolutionStrategy.All;

var result = parser.Parse(source);
if (result.IsAmbiguous)
{
    // inspect result.Forest.Trees
}
  1. Using attributes on parser definition :

Available attributes are :

  • [FirstDerivation] : first derivation strategy
  • [AllDerivation] : all derivation strategy
  • [LongestDerivation] : longest derivation strategy
  • [ThrowsErrorOnAmbiguity] : raise exception on ambiguity
 [BroadenTokenWindow]
    [ParserRoot("root")]
     [FirstDerivation]
    // [AllDerivation]
    // [LongestDerivation]
    // [ThrowsErrorOnAmbiguity]
    public class MyGrammar
    {
       // my grammar definition
    }