Module: Loxxy::Ast::ASTVisitee
- Included in:
- LoxNode
- Defined in:
- lib/loxxy/ast/ast_visitee.rb
Overview
Mix-in module that relies on meta-programming to add a method
called accept to the host class (an AST node).
That method fulfills the expected behavior of the visitee in
the Visitor design pattern.
Instance Method Summary collapse
-
#define_accept ⇒ Object
This method adds a method named
acceptthat takes a visitor The visitor is expected to implement a method named: visit + class name (without the Lox prefix) in snake case Example: class name = LoxClassStmt => visit method = visit_class_stmt. -
#snake_case(aName) ⇒ String
Convert the input string into a snake case string.
Instance Method Details
#define_accept ⇒ Object
This method adds a method named accept that takes a visitor
The visitor is expected to implement a method named:
visit + class name (without the Lox prefix) in snake case
Example: class name = LoxClassStmt => visit method = visit_class_stmt
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/loxxy/ast/ast_visitee.rb', line 36 def define_accept return if instance_methods(false).include?(:accept) base_name = name.split('::').last name_suffix = snake_case(base_name).sub(/^lox/, '') accept_body = " # Part of the 'visitee' role in Visitor design pattern.\n # @param visitor [Ast::ASTVisitor] the visitor\n def accept(aVisitor)\n aVisitor.visit\#{name_suffix}(self)\n end\n MTH_END\n\n class_eval(accept_body)\nend\n" |
#snake_case(aName) ⇒ String
Convert the input string into a snake case string. Example: ClassExpr => class_expr
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/loxxy/ast/ast_visitee.rb', line 14 def snake_case(aName) converted = +'' down = false aName.each_char do |ch| lower = ch.downcase if lower == ch converted << ch down = true else converted << '_' if down && converted[-1] != '_' converted << lower down = false end end converted end |