Module: Dogfood::DSL::Compiler

Defined in:
lib/dogfood/dsl/compiler.rb

Overview

Compiles a validated scenario YAML hash into an anonymous Class(Dogfood::StoryBase). See SPEC.md 4.9 and 4.7.

Constant Summary collapse

TERMINAL_STATUSES =
%i[paid declined voided].freeze
BUILTIN_NAMES =
%i[update_state manual_step wait_for note set_binding].freeze

Class Method Summary collapse

Class Method Details

.collect_block_names(steps) ⇒ Object



249
250
251
252
253
254
255
256
257
# File 'lib/dogfood/dsl/compiler.rb', line 249

def self.collect_block_names(steps)
  steps.flat_map do |step|
    if step[:type] == :maybe
      collect_block_names(step[:then]) + collect_block_names(step[:else])
    else
      [step[:name]]
    end
  end
end

.collect_call_names(ast) ⇒ Object



233
234
235
# File 'lib/dogfood/dsl/compiler.rb', line 233

def self.collect_call_names(ast)
  ast[:stages].flat_map { |s| collect_stage_names(s[:steps]) }
end

.collect_stage_names(steps) ⇒ Object



237
238
239
240
241
242
243
244
245
246
247
# File 'lib/dogfood/dsl/compiler.rb', line 237

def self.collect_stage_names(steps)
  steps.flat_map do |step|
    case step[:type]
    when :call then [step[:name]]
    when :when
      collect_block_names(step[:then]) + collect_block_names(step[:else])
    when :maybe then collect_block_names(step[:then]) + collect_block_names(step[:else])
    else []
    end
  end
end

.compile(yaml, pack:) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/dogfood/dsl/compiler.rb', line 10

def self.compile(yaml, pack:)
  ast = parse_ast(yaml)
  validate_calls(ast, pack)

  klass = Class.new(Dogfood::StoryBase) do
    include Dogfood::Steps::Builtins
    pack.step_modules.each { |m| include(m) }
    pack.mixin_modules.each { |m| include(m) }
    define_singleton_method(:compiled_ast) { ast }
    define_singleton_method(:compiled_pools) { pack.pools }
    define_singleton_method(:compiled_faker) { Dogfood::FakerProxy.new }
  end

  klass.define_method(:title) { yaml["title"] }

  klass.define_method(:advance) do |day_index:|
    @current_day = day_index
    @bindings ||= {}
    @branch_for ||= {}
    @next_stage ||= nil

    stages.each do |stage_spec|
      next unless @next_stage.nil? || @next_stage == stage_spec[:stage]
      run_stage(stage_spec)
      @next_stage = next_stage_after(stage_spec[:stage])
    end

    terminal = TERMINAL_STATUSES.include?(@state[:status])
    {
      id: id,
      steps: @steps,
      state: @state,
      terminal: terminal,
      resume_on: terminal ? nil : next_resume_day
    }
  end

  klass.define_method(:stages) { self.class.compiled_ast[:stages] }

  klass.define_method(:next_stage_after) do |stage|
    idx = self.class.compiled_ast[:stages].index { |s| s[:stage] == stage }
    nxt = self.class.compiled_ast[:stages][idx + 1]
    nxt && nxt[:stage]
  end

  klass.define_method(:run_stage) do |stage_spec|
    branch = resolve_branch(stage_spec)
    stage_spec[:steps].each do |step_spec|
      run_step(step_spec, branch)
    end
  end

  klass.define_method(:resolve_branch) do |stage_spec|
    weights = stage_spec[:branch_weights]
    return nil unless weights
    @branch_for[stage_spec[:stage]] ||= @rng.branch(weights)
  end

  klass.define_method(:run_step) do |step_spec, branch|
    case step_spec[:type]
    when :call
      return if step_spec[:when_branch] && step_spec[:when_branch] != branch
      call_step(step_spec)
    when :when
      list = eval_expr(step_spec[:expr]) ? step_spec[:then] : step_spec[:else]
      (list || []).each { |c| run_step(c, nil) }
    when :maybe
      if @rng.rand < step_spec[:prob]
        step_spec[:then].each { |c| run_step(c, nil) }
      else
        step_spec[:else].each { |c| run_step(c, nil) }
      end
    end
  end

  klass.define_method(:call_step) do |call_spec|
    args = eval_with(call_spec[:with])
    ret = send(call_spec[:name], **args)
    bind_out(call_spec[:out], ret)
  end

  klass.define_method(:eval_with) do |with_hash|
    (with_hash || {}).each_with_object({}) do |(k, v), acc|
      acc[k.to_sym] = Dogfood::DSL::Evaluator.eval(v, bindings: @bindings, state: @state, rng: @rng,
        self_object: self, pools: self.class.compiled_pools, faker: self.class.compiled_faker)
    end
  end

  klass.define_method(:eval_expr) do |expr|
    Dogfood::DSL::Evaluator.eval(expr, bindings: @bindings, state: @state, rng: @rng,
      self_object: self, pools: self.class.compiled_pools, faker: self.class.compiled_faker)
  end

  klass.define_method(:bind_out) do |out, ret|
    return unless out
    if out.is_a?(Array)
      if ret.is_a?(Hash)
        out.each { |name| @bindings[name.to_sym] = ret[name.to_sym] }
      else
        out.each_with_index { |name, i| @bindings[name.to_sym] = ret[i] }
      end
    else
      @bindings[out.to_sym] = ret
    end
  end

  klass.define_method(:next_resume_day) do
    resume = self.class.compiled_ast[:resume]
    resume && resume[:after_await] == :same_day ? @current_day : @current_day + 1
  end

  klass
end

.normalize_out(out) ⇒ Object



213
214
215
216
217
218
219
# File 'lib/dogfood/dsl/compiler.rb', line 213

def self.normalize_out(out)
  case out
  when Array then out.map(&:to_sym)
  when String then out.to_sym
  else nil
  end
end

.parse_ast(yaml) ⇒ Object



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/dogfood/dsl/compiler.rb', line 124

def self.parse_ast(yaml)
  stages = yaml["stages"].map(&:to_sym)
  branches = (yaml["branches"] || {}).each_with_object({}) do |(stage, weights), acc|
    acc[stage.to_sym] = weights.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
  end

  stage_list = stages.map do |stage|
    steps = yaml["stages_def"][stage.to_s].map { |s| parse_step(s, stage.to_s) }
    {
      stage: stage,
      branch_weights: branches[stage],
      steps: steps
    }
  end

  resume = if yaml["resume"] && yaml["resume"]["after_await"]
             { after_await: yaml["resume"]["after_await"].to_sym }
           end

  {
    name: yaml["name"].to_sym,
    title: yaml["title"],
    stages: stage_list,
    delays: (yaml["delays"] || {}).keys.map(&:to_sym),
    resume: resume
  }
end

.parse_block_step(step, stage) ⇒ Object

A step inside a when/then/else block may be a call or a maybe probability step, but never another when. This is the depth-1 limit (SPEC.md 4.7).



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/dogfood/dsl/compiler.rb', line 197

def self.parse_block_step(step, stage)
  if step.key?("when")
    raise Dogfood::NestingTooDeep, "nesting too deep at stage #{stage}: when blocks may not nest"
  end
  if step.key?("maybe")
    {
      type: :maybe,
      prob: step["maybe"],
      then: step["then"].map { |c| parse_call(c, stage) },
      else: step["else"] ? step["else"].map { |c| parse_call(c, stage) } : []
    }
  else
    parse_call(step, stage)
  end
end

.parse_call(step, stage) ⇒ Object



181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/dogfood/dsl/compiler.rb', line 181

def self.parse_call(step, stage)
  unless step.key?("call")
    raise Dogfood::NestingTooDeep, "nesting too deep at stage #{stage}: only call steps allowed in blocks"
  end
  {
    type: :call,
    name: step["call"].to_sym,
    when_branch: nil,
    with: step["with"] || {},
    out: normalize_out(step["out"])
  }
end

.parse_step(step, stage) ⇒ Object



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/dogfood/dsl/compiler.rb', line 152

def self.parse_step(step, stage)
  if step.key?("call")
    out = step["out"]
    {
      type: :call,
      name: step["call"].to_sym,
      when_branch: step["when_branch"]&.to_sym,
      with: step["with"] || {},
      out: normalize_out(out)
    }
  elsif step.key?("when")
    {
      type: :when,
      expr: step["when"],
      then: step["then"].map { |c| parse_block_step(c, stage) },
      else: step["else"] ? step["else"].map { |c| parse_block_step(c, stage) } : []
    }
  elsif step.key?("maybe")
    {
      type: :maybe,
      prob: step["maybe"],
      then: step["then"].map { |c| parse_call(c, stage) },
      else: step["else"] ? step["else"].map { |c| parse_call(c, stage) } : []
    }
  else
    raise Dogfood::NestingTooDeep, "invalid step in stage #{stage}"
  end
end

.validate_calls(ast, pack) ⇒ Object



223
224
225
226
227
228
229
230
231
# File 'lib/dogfood/dsl/compiler.rb', line 223

def self.validate_calls(ast, pack)
  names = collect_call_names(ast).uniq
  names.each do |name|
    next if BUILTIN_NAMES.include?(name)
    found = pack.step_modules.any? { |m| m.instance_methods.include?(name) } ||
            pack.mixin_modules.any? { |m| m.instance_methods.include?(name) }
    raise Dogfood::Pack::UnknownScenario, "call :#{name} does not resolve to a pack step module" unless found
  end
end