Class: SyntaxTree::Pattern
- Inherits:
-
Object
- Object
- SyntaxTree::Pattern
- Defined in:
- lib/syntax_tree/pattern.rb
Overview
A pattern is an object that wraps a Ruby pattern matching expression. The expression would normally be passed to an ‘in` clause within a `case` expression or a rightward assignment expression. For example, in the following snippet:
case node
in Const[value: "SyntaxTree"]
end
the pattern is the ‘Const[value: “SyntaxTree”]` expression. Within Syntax Tree, every node generates these kinds of expressions using the #construct_keys method.
The pattern gets compiled into an object that responds to call by running the #compile method. This method itself will run back through Syntax Tree to parse the expression into a tree, then walk the tree to generate the necessary callable objects. For example, if you wanted to compile the expression above into a callable, you would:
callable = SyntaxTree::Pattern.new("Const[value: 'SyntaxTree']").compile
callable.call(node)
The callable object returned by #compile is guaranteed to respond to #call with a single argument, which is the node to match against. It also is guaranteed to respond to #===, which means it itself can be used in a ‘case` expression, as in:
case node
when callable
end
If the query given to the initializer cannot be compiled into a valid matcher (either because of a syntax error or because it is using syntax we do not yet support) then a SyntaxTree::Pattern::CompilationError will be raised.
Defined Under Namespace
Classes: CompilationError
Instance Attribute Summary collapse
-
#query ⇒ Object
readonly
Returns the value of attribute query.
Instance Method Summary collapse
- #compile ⇒ Object
-
#initialize(query) ⇒ Pattern
constructor
A new instance of Pattern.
Constructor Details
#initialize(query) ⇒ Pattern
Returns a new instance of Pattern.
61 62 63 |
# File 'lib/syntax_tree/pattern.rb', line 61 def initialize(query) @query = query end |
Instance Attribute Details
#query ⇒ Object (readonly)
Returns the value of attribute query.
59 60 61 |
# File 'lib/syntax_tree/pattern.rb', line 59 def query @query end |
Instance Method Details
#compile ⇒ Object
65 66 67 68 69 70 71 72 73 74 |
# File 'lib/syntax_tree/pattern.rb', line 65 def compile program = begin SyntaxTree.parse("case nil\nin #{query}\nend") rescue Parser::ParseError raise CompilationError, query end compile_node(program.statements.body.first.consequent.pattern) end |