diff --git a/grammar.js b/grammar.js index 2f38ecf1d..763e9f6c9 100644 --- a/grammar.js +++ b/grammar.js @@ -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) + ) ); } diff --git a/test/corpus/cases.txt b/test/corpus/cases.txt index 95cf2f70f..0f8dc3bb6 100644 --- a/test/corpus/cases.txt +++ b/test/corpus/cases.txt @@ -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)))))))))