Allow 'as' keyword in binary pattern match expressions

pull/844/head
Michael Davis 2023-09-29 14:35:52 +07:00
parent 4ccb13e253
commit aa987f8b7a
No known key found for this signature in database
2 changed files with 88 additions and 3 deletions

@ -613,7 +613,10 @@ module.exports = grammar({
alias($._pattern_binary_expression, $.binary_expression)
),
_pattern_binary_expression: ($) =>
binaryExpr(prec.left, 1, "<>", $._pattern_expression),
choice(
binaryExpr(prec.left, 1, "<>", $._pattern_expression),
binaryExpr(prec.left, 1, "as", $.string, $.identifier)
),
_pattern: ($) =>
seq(
$._pattern_expression,
@ -859,9 +862,13 @@ function series_of(rule, separator) {
// A binary expression with a left-hand side, infix operator, and then right-hand-side
// https://github.com/elixir-lang/tree-sitter-elixir/blob/de20391afe5cb03ef1e8a8e43167e7b58cc52869/grammar.js#L850-L859
function binaryExpr(assoc, precedence, operator, expr) {
function binaryExpr(assoc, precedence, operator, left, right = null) {
return assoc(
precedence,
seq(field("left", expr), field("operator", operator), field("right", expr))
seq(
field("left", left),
field("operator", operator),
field("right", right || left)
)
);
}

@ -108,3 +108,81 @@ pub fn listed(names: List(String), person: Person) -> String {
(list_pattern)))
(record
(constructor_name))))))))
================================================================================
Pattern matching binaries with 'as'
================================================================================
// From https://gleam.run/news/v0.31-keeping-dependencies-explicit/#quality-of-life-improvements
case tag {
"category " as key <> value
| "region " as key <> value
| "priority " as key <> value -> {
let key = string.trim(key)
Ok(Tag(key, value))
}
_ -> Error(Nil)
}
--------------------------------------------------------------------------------
(source_file
(comment)
(case
(case_subjects
(identifier))
(case_clauses
(case_clause
(case_clause_patterns
(case_clause_pattern
(binary_expression
(binary_expression
(string
(quoted_content))
(identifier))
(identifier)))
(case_clause_pattern
(binary_expression
(binary_expression
(string
(quoted_content))
(identifier))
(identifier)))
(case_clause_pattern
(binary_expression
(binary_expression
(string
(quoted_content))
(identifier))
(identifier))))
(block
(let
(identifier)
(function_call
(field_access
(identifier)
(label))
(arguments
(argument
(identifier)))))
(record
(constructor_name)
(arguments
(argument
(record
(constructor_name)
(arguments
(argument
(identifier))
(argument
(identifier)))))))))
(case_clause
(case_clause_patterns
(case_clause_pattern
(discard)))
(record
(constructor_name)
(arguments
(argument
(record
(constructor_name)))))))))