Class: Calyx::Grammar

Inherits:
Object
  • Object
show all
Defined in:
lib/calyx/grammar.rb,
lib/calyx/file_converter.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(seed = nil, &block) ⇒ Grammar

Returns a new instance of Grammar.



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/calyx/grammar.rb', line 37

def initialize(seed=nil, &block)
  @seed = seed || Random.new_seed
  srand(@seed)

  if block_given?
    @registry = Registry.new
    @registry.instance_eval(&block)
  else
    @registry = self.class.registry
  end
end

Class Method Details

.filter(name, &block) ⇒ Object



16
17
18
# File 'lib/calyx/grammar.rb', line 16

def filter(name, &block)
  registry.mapping(name, &block)
end

.inherit_registry(child_registry) ⇒ Object



28
29
30
# File 'lib/calyx/grammar.rb', line 28

def inherit_registry(child_registry)
  registry.combine(child_registry) unless child_registry.nil?
end

.inherited(subclass) ⇒ Object



32
33
34
# File 'lib/calyx/grammar.rb', line 32

def inherited(subclass)
  subclass.inherit_registry(registry)
end

.load(filename) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
# File 'lib/calyx/file_converter.rb', line 7

def load(filename)
  file = File.read(filename)
  extension = File.extname(filename)
  if extension == ".yml"
    load_yml(file)
  elsif extension == ".json"
    load_json(file)
  else
    raise "Cannot convert #{extension} files."
  end
end

.load_json(file) ⇒ Object



24
25
26
27
# File 'lib/calyx/file_converter.rb', line 24

def load_json(file)
  json = JSON.parse(file)
  build_grammar(json)
end

.load_yml(file) ⇒ Object



19
20
21
22
# File 'lib/calyx/file_converter.rb', line 19

def load_yml(file)
  yaml = YAML.load(file)
  build_grammar(yaml)
end

.mapping(name, pairs) ⇒ Object



12
13
14
# File 'lib/calyx/grammar.rb', line 12

def mapping(name, pairs)
  registry.mapping(name, pairs)
end

.method_missing(name, *productions) ⇒ Object



24
25
26
# File 'lib/calyx/grammar.rb', line 24

def method_missing(name, *productions)
  registry.rule(name, *productions)
end

.modifier(name) ⇒ Object



8
9
10
# File 'lib/calyx/grammar.rb', line 8

def modifier(name)
  registry.modifier(name)
end

.registryObject



4
5
6
# File 'lib/calyx/grammar.rb', line 4

def registry
  @registry ||= Registry.new
end

.rule(name, *productions) ⇒ Object



20
21
22
# File 'lib/calyx/grammar.rb', line 20

def rule(name, *productions)
  registry.rule(name, *productions)
end

Instance Method Details

#evaluate(*args) ⇒ Object



57
58
59
60
61
# File 'lib/calyx/grammar.rb', line 57

def evaluate(*args)
  start_symbol, rules_map = map_default_args(*args)

  @registry.evaluate(start_symbol, rules_map)
end

#generate(*args) ⇒ Object



49
50
51
52
53
54
55
# File 'lib/calyx/grammar.rb', line 49

def generate(*args)
  start_symbol, rules_map = map_default_args(*args)

  @registry.evaluate(start_symbol, rules_map).flatten.reject do |obj|
    obj.is_a?(Symbol)
  end.join(''.freeze)
end