Skip to content

Features of a pattern matching syntax #337

Open

Description

@zspitz

Note The latest version of the design based on these principles can be found here.

What features / attributes should a VB.NET pattern matching syntax have?

I propose the following:

  • Allow the same syntax for patterns in a boolean-returning expression (introduced with a dedicated keyword), as for patterns in a Case clause. This enables patterns to be used as the condition of If ... Then, Do While ... blocks and the like.
  • Allows the pattern to introduce variables into the child scope -- this will be either the Case block or the block following the match expression
  • Pattern-neutral, not oriented specifically to a type-checking pattern
  • Allow When clauses for additional conditions
  • Allows for nested patterns -- certain pattern types can contain other patterns

I've written some examples, and a proposed spec in line with these goals here. But the purpose of this issue is to discuss whether these goals are valid and relevant.

Activity

  1. zspitz commented on Dec 15, 2018

    @zspitz
    Author

    One other point:

  2. ericmutta commented on Dec 15, 2018

    @ericmutta

    @zspitz I've written some examples, and a proposed spec in line with these goals here.

    Thanks for thinking about this feature in detail and going as far as writing a grammar!

    I think the goals are reasonable though I would add one more: keep it really really really simple.

    The simplicity goal matters a lot because every feature is a product: it needs a spec, it has to be implemented in the compiler, implemented in the IDE, tested in all scenarios, documented (with samples) and then supported forever. This is a lot of work!

    So to keep it simple, we should find the minimum viable functionality for this feature, hope that gets implemented and then expand from there in the future (otherwise none of it will ever get done in our lifetime).

    From my own experience with the feature in C#, the type checking pattern is really all we need (and the C# docs seem to focus on mostly that). And we could probably do it without adding a new keyword and sticking to Is, so borrowing from some of the examples you gave:

    'test the type without introducing a variable (not strictly necessary but...)
    If obj Is String Then Console.WriteLine("obj is a string")
    
    'test the type and introduce a variable.
    If obj Is s As String Then Console.WriteLine(s.Length)
    
    'can also assign the boolean result to a local variable
    '(useful for extending scope of variable "s" beyond block that checks test1/test2).
    Dim test1 = obj Is String
    Dim test2 = obj is s As String
    
    'we should probably use AndAlso instead of When for simplicity.
    If obj Is s As String AndAlso s.Length > 5 Then Console.WriteLine(s.Length)
    
    'can do the above with Select too:
    Select Case obj
      Case Is String
        Console.WriteLine("obj is a string")
      Case Is s As String
        Console.WriteLine(s.Length)
      Case Is s As String AndAlso s.Length > 5
        Console.WriteLine(s.Length)
    End Select
    
    '...and in loops that expect a boolean condition:
    Do While obj Is s As String
     Process(s)
     obj = GetNextObject()
    Loop
    
    Do Until obj Is s As String
      ProcessObjectsThatAreNotStrings(obj)
    Loop

    In short:

    1. We are introducing a boolean-valued type checking and (optional) conversion expression.
    2. It returns false if the type check fails and sets any introduced variable to Nothing.
    3. It returns true if the conversion succeeds and assigns the converted value to the introduced variable.
    4. The introduced variable (if any) is scoped to the block containing the expression.

    If for example the above functionality is all we got in order to keep things as simple as possible, does anyone feel something critical is missing? Remember: we can get really fancy with this, but if we do, it is unlikely to ever get implemented because it will be too much work!

    CC: @KathleenDollard some food for thought here for the LDM as you consider this feature.

  3. paul1956 commented on Dec 16, 2018

    @paul1956

    Generally I love it and would use this functionality constantly it would dramatically simplify code.
    Questions
    Can "If obj Is s As String Then Console.WriteLine(s.Length)" have an else case? If not, then how would "sets any introduced variable to Nothing", ever be tested or be useful? The variable would not be in scope. If there is an else what Type is "s" certainty not String.

    In the Do Until, once you fall out of the loop "s" is not in scope so the assignment seems useless, so I am not sure if the assignment feature is useful or could be tested.

  4. ericmutta commented on Dec 16, 2018

    @ericmutta

    @paul1956 Can "If obj Is s As String Then Console.WriteLine(s.Length)" have an else case? If not, then how would "sets any introduced variable to Nothing", ever be tested or be useful? The variable would not be in scope. If there is an else what Type is "s" certainty not String.

    I imagine it should work like this:

    If obj Is s As String Then 
      'can use variable "s" here and it will be a non-null string.
    Else
      'can't use variable "s" here because it is not in scope.
    End If

    @paul1956 In the Do Until, once you fall out of the loop "s" is not in scope so the assignment seems useless,

    That's a good point! It would be allowed for completeness much like assigning a variable to itself is allowed and equally useless. Though there could be some utility in the version that doesn't introduce a variable:

    Do Until obj Is String
      ProcessNonStringObject(obj)
      obj = GetNextObject()
    Loop
  5. zspitz commented on Dec 16, 2018

    @zspitz
    Author

    (An updated version is here.)

    @ericmutta In thinking about what the minimum viable functionality would look like, I've reached the following conclusions (I apologize for the length).

    TL;DR

    1. Extend Is and Case for pattern matching -- <expression> Is <pattern> and Case <pattern>; instead of a dedicated keyword that introduces a pattern.

    2. The same syntax should work with both <expression> Is <pattern> and Case <pattern>

      2a. Is should be extended to allow all current Case syntax -- Case <expression> To <expression>, Case <expression>, <expression>; and should use value equality where available

      2b. Case should be extended for all current Is syntax -- Case <expression> should support reference equality and comparison against Nothing (Select Case on identity (reference equality) #119)

    3. Since Case and Is already support simple expressions, anything until the end of the condition / Case clause must be considered part of the pattern, to prevent ambiguity.

      3a. The only way to allow for additional logic AFAICT is to wrap it in a single-per-pattern-expression When clause.

      3b. Trying to reuse AndAlso for this purpose will only increase complexity.

    4. Case should continue to not require Is.

    (Possible grammar at the end.)


    If pattern matching is just another type-checking syntax (admittedly also allowing introduced variables), then I don't think the feature can possibly justify itself. (In fact, the compiler could do the same thing without any additional syntax.)

    But pattern matching is so much more than type-checking -- it's saying:

    • does the expression on the left match the pattern expressed by some syntax on the right?
    • if it does, assign parts of whatever is being matched to new identifiers

    From my own experience with the feature in C#, the type checking pattern is really all we need (and the C# docs seem to focus on mostly that).

    Pattern matching in C# is still in its infancy; see the F# documentation for a better idea of the range of potential patterns.

    Having said that, you are quite correct -- it's going to be harder to add all the possible patterns right at the beginning. However, any first steps in pattern matching must specify at least two things:

    • What syntax introduces a pattern? Also, where does the pattern end?
    • One "killer app" pattern, e.g. the variable-as-type pattern

    It also should allow for the goals outlined above, even if these goals aren't implemented immediately; and should also be compatible and consistent with existing syntax.


    AFAICT there are two possible ways to insert pattern matching into the language:

    • Introduce a new dedicated keyword (e.g. Matches)
    • Extend the behavior of the existing Case and Is

    I prefer extending Case/Is, because:

    • Case already has a (albeit very limited) form of pattern matching
    • Having a new keyword means users of the language have to remeber yet another syntax
    • There is already an inverse for Is in the conditions of If statements and the like: IsNot. For a dedicated keyword, it would be necessary to choose between no inverse -- If Not o Matches String Then -- or something equally awkward..

    although a dedicated keyword might be simpler to implement, because we wouldn't have to deal with the historical usages of Is and Case.


    If we extend Case/Is, we shouldn't require Is for patterns in Case clauses. Forcing Is to be required, would result in three different rules for whether Case needs to be followed by Is:

    • Case <expression> -- the Is cannot be used, per the spec
    • Case Is <operator> <operand> -- the Is is optional, also per the spec
    • Case Is <pattern> -- the Is is required

    which I think would be very confusing.


    Also, assuming we extend Case/Is, since VB.NET already supports both Case <expression> and Is <expression>, any other expressions until the end of the condition / Case clause must be considered part of the pattern. Otherwise the following would be ambiguous:

    Dim o As Object
    Dim foo As Boolean
    Dim bar As Boolean
    If o Is foo AndAlso bar Then

    Should foo AndAlso bar be evaluated first? Or should o Is foo be evaluated first?

    C# doesn't have this problem, because C# doesn't allow case with an expression, so the following:

    object o = null;
    bool bar = true;
    if (o is bool b && bar)

    is unambiguous -- first perform the pattern match, then the logical AND.

    (NB. OTOH, this does simplify things a little, because we don't need an explicit literal pattern.)


    If a pattern expressions must be greedy (i.e. go to the end of the condition / Case clause), then extra logic at the end of the pattern cannot use a simple boolean expression; we need a special clause for this purpose. C# introduces this clause with the when keyword.

    Specifically in VB.NET, we can't simply reuse an existing keyword such as AndAlso to introduce this clause, because AndAlso might be part of the expression in the pattern.

    We could make up all sorts of complicated rules to disambiguate, but the simplest would be to introduce a new keyword -- When.

    (NB. A similar usage of When already exists in VB.NET, when applying a condition to a Catch exception.)


    Taking into account the need to define the following from the start:

    • where a pattern expresion (an expression containing a pattern match) can be used,
    • what are the parts of a pattern expression,
    • patterns that cover the existing behaviors of both Case and Is
    • the additional new variable+typecheck pattern

    I think the following is the "minimum viable functionality":

    Where a pattern expression can be used:

    BooleanOrPatternExpression
        : BooleanExpression
        | Expression 'Is' PatternExpression
        ;
    
    
    // If...Then..ElseIf blocks
    
    BlockIfStatement
        : 'If' BooleanOrPatternExpression 'Then'? StatementTerminator
          Block?
          ElseIfStatement*
          ElseStatement?
          'End' 'If' StatementTerminator
        ;
    
    ElseIfStatement
        : ElseIf BooleanOrPatternExpression 'Then'? StatementTerminator
          Block?
        ;
    
    LineIfThenStatement
        : 'If' BooleanOrPatternExpression 'Then' Statements ( 'Else' Statements )? StatementTerminator
        ;
    
    
    // Loops
    
    WhileStatement
        : 'While' BooleanOrPatternExpression StatementTerminator
          Block?
          'End' 'While' StatementTerminator
        ;
    
    DoTopLoopStatement
        : 'Do' ( WhileOrUntil BooleanOrPatternExpression )? StatementTerminator
          Block?
          'Loop' StatementTerminator
        ;
    
    // cannot introduce variables in to child scope here
    DoBottomLoopStatement
        : 'Do' StatementTerminator
          Block?
          'Loop' WhileOrUntil BooleanOrPatternExpression StatementTerminator
        ;
    
    ConditionalExpression
        : 'If' OpenParenthesis BooleanOrPatternExpression Comma Expression Comma Expression CloseParenthesis
        | 'If' OpenParenthesis Expression Comma Expression CloseParenthesis
        ;
    
    
    // Within a Case clause
    
    CaseStatement
        : 'Case' PatternExpression StatementTerminator
          Block?
        ;

    What are the parts of a pattern expression?

    PatternExpression
        : Pattern ('When' BooleanExpression)?
        ;

    What patterns should be supported from the start?

    Pattern
        // patterns with subpatterns
        : Pattern ',' Pattern                    // OR pattern (already supported in Case)
    
        // patterns without subpatterns
        | 'Of' TypeName                          // Type check pattern -- matches when subject is of TypeName
        | Identifier 'As' TypeName               // Variable pattern -- introduces a new variable in child scope
        | 'Is'? ComparisonOperator Expression    // Comparison pattern
        | 'Like' StringExpression                // Like pattern
        | Expression 'To' Expression             // Range pattern
        | Expression                             // Equality pattern -- value/reference equality test against Expression
        ;
  6. zspitz commented on Dec 16, 2018

    @zspitz
    Author
  7. paul1956 commented on Dec 17, 2018

    @paul1956

    If the powers in charge can agree on a grammar and ultimate feature set, it would be nice to get "Is TypeName" and "Is Identifier As TypeName" out first. If all the things being proposed this is the one thing needed yesterday and would simplify lots of VB Code..

  8. ericmutta commented on Dec 17, 2018

    @ericmutta

    @zspitz Otherwise the following would be ambiguous:

    Dim o As Object
    Dim foo As Boolean
    Dim bar As Boolean
    If o Is foo AndAlso bar Then

    It isn't ambiguous because it doesn't compile at all! Compiler says Is operator does not accept operands of type Boolean. Operands must be reference or nullable types.

    Ultimately the choice between AndAlso and When is likely to be a matter of preference, mainly because both keywords already exist in the language so nothing new is being added, regardless of which you choose. I personally prefer 'AndAlso' mainly because it makes clear the short-circuiting nature of the expression (i.e the part to the right of AndAlso will not run if the type-check and conversion on the left did not succeed).

    @zspitz I've reached the following conclusions (I apologize for the length).

    I believe that when it comes down to implementing this, the team will appreciate the level of detail in your comments, it is clear you have given this a lot of thought! 👍 👍

  9. zspitz commented on Dec 17, 2018

    @zspitz
    Author

    @ericmutta

    Thanks for the kind words; I hope you're right, and this will enable the team to move forward on pattern matching that much faster.

    It isn't ambiguous because it doesn't compile at all!

    If o Is foo currently doesn't compile, as you've noted. But if we extend Is to follow everything Case does today, then If o Is foo Then would compile just fine.

    But even then, trying to push more boolean expressions onto the pattern would be ambiguous.

  10. bandleader commented on Dec 17, 2018

    @bandleader

    o Is foo AndAlso bar -- It isn't ambiguous because it doesn't compile at all! Compiler says Is operator does not accept operands of type Boolean. Operands must be reference or nullable types.

    @ericmutta In addition to what @zspitz noted above -- it's nevertheless ambiguous in parsing. The fact that bar is Boolean is not known until the binding stage of the compiler. (Also, compilers should anyway never parse differently based on semantics.)

    This distinction (between lexical and semantic analysis -- done by the parser and binder respectively) is often overlooked in these discussions. More about that later.

  11. bandleader commented on Dec 17, 2018

    @bandleader
    1. Another issue with extending Is to work with patterns and supporting an expression as a pattern: Is currently checks for reference equality, whereas expressions would presumably check for equality including IEquatable equality/.Equals (and it would have to because that's what Case does as well). So obj Is otherObjWhichEquatesToObj would suddenly have to return True. Aside from breaking existing code, there's also the fact that VB does need a reference equality operator.
  12. bandleader commented on Dec 17, 2018

    @bandleader
    1. Problem: Case x currently does a value check. Case x As String is being proposed to do a typecheck-and-assign. This is very non-intuitive.

    (For comparison, the following two lines do the same thing both lexically and in human understanding, just with specific types vs. type inference. This is critical for intuition and should be a hard requirement for any VB syntax which can take an As T or skip it.)

    For Each x In collection
    For Each x As String In collection

    Same for:

    Dim x = expr
    Dim x As String = expr

    I have some more thoughts against re-using Select Case and Is as-is for pattern matching, or at least for this pattern (typecheck-and-assign), even while realizing the similarity between them and the desire to mesh it all together. I'll try to post later.

  13. bandleader commented on Dec 18, 2018

    @bandleader

    @zspitz Most importantly -- thank you for your amazing efforts in moving this forward. Here's hoping MS will take notice and reciprocate!

  14. zspitz commented on Dec 18, 2018

    @zspitz
    Author

    Another issue with extending Is to work with patterns and supporting an expression as a pattern: Is currently checks for reference equality, whereas expressions would presumably check for equality including IEquatable equality/.Equals (and it would have to because that's what Case does as well). So obj Is otherObjWhichEquatesToObj would suddenly have to return True. Aside from breaking existing code, there's also the fact that VB does need a reference equality operator.

    Agreed. I think we'd need a dedicated keyword for boolean contexts If <expression> Matches <pattern> Then, Do While <expression> Matches <pattern> etc. (I'll update my original post accordingly.)

    But I still think we should extend Select Case to patterns in general, without an additional keyword. Otherwise users will have to decide whether to use Case Matches <pattern> or Case <expression>, each with its own limitations.

  15. KathleenDollard commented on Dec 18, 2018

    @KathleenDollard
    Contributor

    In general, I like letting the discussion flow without interrupting it.

    This has been a great discussion. I appreciate everyone's work, and wanted to be sure you all didn't think you were talking into a void. It's also the start of Christmas holidays, which means a lot of folks are out until the first of the year.

  16. 12 remaining items

  17. zspitz commented on Mar 22, 2020

    @zspitz
    Author

    @Happypig375 Yes, but not Not( ... ).

  18. zspitz commented on Mar 22, 2020

    @zspitz
    Author

    @Happypig375 It's really a broader question -- which takes precedence, an expression or a pattern? I guess in order to avoid breaking changes, an expression should take precedence.

    At least for Not, there is another possible resolution; allow NoneOf to apply to a single pattern as well, with the same effect.

    Alternatively, even though Not(0) is a breaking change, it's a very small one.

  19. ericmutta commented on Mar 22, 2020

    @ericmutta

    @zspitz this is a very lively and thorough discussion which would be awesome if any of it had a chance of being implemented, especially given the recent announcement that there are no plans to evolve the language anymore.

    Until we as a community figure out the language evolution problem, I am afraid the vblang repo won't have much use and any discussions will be purely theoretical!

  20. zspitz commented on Mar 22, 2020

    @zspitz
    Author

    @ericmutta Agreed. But I hope things will be resolved eventually for the better, and at that point this discussion will become very useful. Also, I need to get the details of pattern matching out of my system, so I can continue working on something else.

  21. ericmutta commented on Mar 23, 2020

    @ericmutta

    @zspitz But I hope things will be resolved eventually for the better...

    I salute your optimism 💪

    I've been thinking about the way TypeScript is implemented (it compiles down to JavaScript) and perhaps we as a community could develop a VB pre-processor that compiles *.vbx files. These files would contain a superset of VB that is translated into the current VB language which is then compiled by Rosyln.

    Much of the stuff we would like to see in VB (including this pattern matching business) boils down to syntactic sugar that could be implemented "the TypeScript way" (i.e by a pre-processor extension). If others like this concept perhaps we can create a seperate issue and discuss further 👍

  22. tverweij commented on Mar 24, 2020

    @tverweij

    @ericmutta That will also need editor support and tooling support.

  23. ericmutta commented on Mar 24, 2020

    @ericmutta

    @tverweij indeed! I am glad you read the comment above, I was trying to tag you yesterday but it didn't work when commenting from my phone.

    I remember you have started working with a company that has experience with programming languages and tools development. Perhaps this is something they could consider?

    Rather than an entirely new IDE and change in name and a $500 price tag, if they could do it "the TypeScript way" (i.e as a Visual Studio extension that pre-processes VBX into VB) and charge say $99, I reckon most people would just buy the extension without thinking too hard.

    The extension shouldn't introduce complex changes (e.g. the type system should be left alone), it should leverage Rosyln as much as possible, and the focus should be on the syntax sugar stuff like the pattern matching being discussed here.

    Please talk to RemObjects and let us know whether this makes business sense for them 👍 🙏

  24. tverweij commented on Mar 24, 2020

    @tverweij

    @ericmutta: I read everything here. And see what we can adopt and what not.

    The extensible Idea from @VBAndCs and now from you is a nice idea, but almost not implementable. At least not for us in the existing toolchain where Mercury is being added.

    But three things:
    First: we are going to extend the language - much. What is added and what not is not decided yet. But this one has a really big chance although it will be implanted the same as the C# implementation.
    Second: We have AOP for all languages for custom code generation. So this will work for Mercury too.
    Third: With Mercury, forget about Roslyn. This is not a Microsoft language, so there is no Roslyn compiler.

    But first we have to come to the point where we are on par with Visual Basic. We are working hard on that now.

  25. tverweij commented on Mar 24, 2020

    @tverweij

    @ericmutta: That idea would also destroy the reason of the Mercury project. We started well before Microsoft declared VB dead/zombie.
    The goal of the project is 2-fold:

    1. Remove all limitations from Visual Basic
    2. Make sure that you can compile it for any target / platform

    Your idea would solve 1. but not 2. as the compiler would still be the limited Roslyn VB compiler.
    So adding thing like unsafe, inline, lazy and reference returns would still be impossible.

  26. tverweij commented on Mar 24, 2020

    @tverweij

    @ericmutta - last part, I promise :-)

    About 2. - We are already compiling for MacOs (Cacoa), Linux (native), Windows (native), .Net, .NetCore and WebAssembly with the partial implemented version.

  27. bandleader commented on Mar 24, 2020

    @bandleader

    Much of the stuff we would like to see in VB (including this pattern matching business) boils down to syntactic sugar that could be implemented "the TypeScript way" (i.e by a pre-processor extension).

    @ericmutta A pre-processor like Typescript needs a lexer, parser, [binder,] lowerers, and a source emitter. In other words, much of the components of a compiler like Roslyn, with the most significant difference being a source emitter instead of an IL emitter. Thus, such a pre-processor should likely re-use Roslyn for the lexing, parsing, binding, etc. Once doing that, why not build your changes into Roslyn -- isn't that less difficult?

    Of course the difficulty would be getting MS to accept those changes, when it wants to minimize the resources it spends on VB. I'm not sure they could be convinced to let the community maintain VB (including docs, etc.) just like F#.

    Another option would be simply forking Roslyn and configuring VS to use that forked version. @AnthonyDGreen once described how to do that here.

  28. zspitz commented on Mar 24, 2020

    @zspitz
    Author

    Another option would be simply forking Roslyn and configuring VS to use that forked version. @AnthonyDGreen once described how to do that here.

    Or build a language server that could choose between the original and the fork, and use VS Code or some other editor.

  29. ericmutta commented on Mar 24, 2020

    @ericmutta

    @tverweij ...last part, I promise :-)

    Many thanks for the clarification :-) I see the goals for Mercury are much broader than what I was thinking about and it would be interesting to see how that works out (competing against popular, high quality free tools from a trillion dollar corporation is not going to be easy but somebody has to try :-))

    @bandleader A pre-processor like Typescript needs a lexer, parser, [binder,] lowerers, and a source emitter.

    That's the trouble with this whole situation: language tools need a lot of work and its highly unlikely to be done (effectively) on a part-time basis by people who have day jobs, mortgages and no experience in the field of compilers. The barriers to entry are high even before worrying about what Microsoft will or will not accept.

    Unless @AnthonyDGreen's articles (thanks @aarondglover for sharing) miraculously reach the powers that be and convince them to keep evolving VB, I think the course taken by @tverweij with project Mercury is the only potential alternative for now. So hustle hard @tverweij you may very well save the day 💪

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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions