Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor pattern matching to be static & stand alone #82

Merged
merged 3 commits into from
Apr 5, 2021

Conversation

atifaziz
Copy link
Collaborator

@atifaziz atifaziz commented Apr 5, 2021

This PR refactors pattern matching from the virtual Match/SingleMatch dispatches into a stand-alone static method with a consolidated implementation. This moves away from an object-oriented approach. The rationale for the new approach is that all the patterns are essentially a closed set of discriminated unions. The Pattern and subclasses are internal implementation details. They are not designed for extensibility so the open-close principal doesn't come into play here. Having a consolidated implementation that pattern-matches through a switch table simplifies things greatly (including for understanding). For example, all branch patterns now just boil down to this:

class Required : BranchPattern
{
    public Required(params Pattern[] patterns) : base(patterns) { }
}

class Optional : BranchPattern
{
    public Optional(params Pattern[] patterns) : base(patterns) { }
}

// Marker/placeholder for [options] shortcut.
class OptionsShortcut : Optional { }

class Either : BranchPattern
{
    public Either(params Pattern[] patterns) : base(patterns) { }
}

class OneOrMore : BranchPattern
{
    public OneOrMore(params Pattern[] patterns) : base(patterns) { }
}

A less obvious motivation is that this simplification will potentially also help with static source code generation being explored in #77. While this can't be proven, the PR hopefully has merits on its own.

@atifaziz atifaziz requested a review from voieducode April 5, 2021 12:55
{
var coll = collected ?? new List<LeafPattern>();

switch (pattern)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Much easier to understand now that it is in a single place!

@voieducode voieducode merged commit ed57edb into docopt:master Apr 5, 2021
@atifaziz atifaziz deleted the standalone-pattern-matching branch April 26, 2021 07:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants