Class: Chelsy::Syntax::Constraint

Inherits:
Object
  • Object
show all
Defined in:
lib/chelsy/syntax.rb

Direct Known Subclasses

Any, Coercer

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ Constraint

Initialize instance. You must suply its name to debugging purpose.

Parameters:

  • name (String)

    the name of this constraint



9
10
11
# File 'lib/chelsy/syntax.rb', line 9

def initialize(name)
  @name = name.dup
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



4
5
6
# File 'lib/chelsy/syntax.rb', line 4

def name
  @name
end

Instance Method Details

#===(node) ⇒ Object



13
14
15
# File 'lib/chelsy/syntax.rb', line 13

def ===(node)
  accept?(node)
end

#accept?(node) ⇒ Boolean

Returns:

  • (Boolean)


17
18
19
20
21
22
23
24
25
# File 'lib/chelsy/syntax.rb', line 17

def accept?(node)
  # Most C program uses C preprocessor, so we must accept any C code snippet.
  case node
  when Chelsy::Raw
    true
  else
    false
  end
end

#coerce(obj) ⇒ Node

Try to coerce obj to acceptable node.

Parameters:

  • obj

    Any object to coerce

Returns:

  • (Node)

    A node or nil if it can't be coerced.



31
32
33
# File 'lib/chelsy/syntax.rb', line 31

def coerce(obj)
  nil
end

#ensure(node) ⇒ Object



35
36
37
38
39
40
41
42
43
# File 'lib/chelsy/syntax.rb', line 35

def ensure(node)
  if accept?(node)
    node
  else
    coerce(node).tap do |coerced|
      raise ArgumentError, "#{node.class.name} is not one of #{@name}" unless coerced
    end
  end
end