Module: Ruby::Merge

Extended by:
Merge
Included in:
Merge
Defined in:
lib/ruby/merge.rb,
lib/ruby/merge/version.rb

Defined Under Namespace

Modules: Version

Constant Summary collapse

PACKAGE_NAME =
"ruby-merge"
TREE_SITTER_BACKEND =
TreeHaver::KREUZBERG_LANGUAGE_PACK_BACKEND
DESTINATION_WINS_ARRAY_POLICY =
{ surface: "array", name: "destination_wins_array" }.freeze
DIRECTIVE_LINE =
/\A(?::nocov:|[\w-]+:(?:freeze|unfreeze))\z/
MAGIC_COMMENT_PREFIXES =
%w[coding encoding frozen_string_literal shareable_constant_value typed warn_indent].freeze
REQUIRE_PATTERN =
/^\s*require(?:_relative)?\s+["']([^"']+)["']/.freeze
DSL_CALL_PATTERN =
/^(?<name>source|gemspec|git_source|gem|eval_gemfile|platform|group|desc|task)\b/.freeze
RAKEFILE_DEFAULT_TASK_COMMENT =
"# Define a base default task early so other files can enhance it."
RAKEFILE_DEFAULT_TASK_DESC =
'desc "Default tasks aggregator"'
CLASS_PATTERN =
/^\s*class\s+([A-Z]\w*(?:::\w+)*)/.freeze
MODULE_PATTERN =
/^\s*module\s+([A-Z]\w*(?:::\w+)*)/.freeze
DEF_PATTERN =
/^\s*def\s+(?:self\.)?([a-zA-Z_]\w*[!?=]?)/.freeze
EXAMPLE_TAG =
/\A@example\b(?<rest>.*)\z/.freeze
TAG_PREFIX =
/\A@[a-z_]+\b/.freeze
VERSION =
Version::VERSION

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.analyze_ruby_document(source) ⇒ Object



308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
# File 'lib/ruby/merge.rb', line 308

def analyze_ruby_document(source)
  lines = normalize_source(source).split("\n", -1)
  requires = []
  declarations = []
  discovered_surfaces = []
  pending_comments = []

  lines.each_with_index do |line, index|
    line_number = index + 1
    stripped = line.strip

    if comment_line?(line)
      pending_comments << { line: line_number, raw: line }
      next
    end

    if stripped.empty?
      pending_comments = []
      next
    end

    if (match = REQUIRE_PATTERN.match(line))
      requires << {
        path: "/requires/#{requires.length}",
        owner_kind: "require",
        match_key: match[1]
      }
      pending_comments = []
      next
    end

    declaration = declaration_for_line(line)
    if declaration
      declarations << {
        path: "/declarations/#{declaration[:name]}",
        owner_kind: "declaration",
        match_key: declaration[:name]
      }
      surfaces = surfaces_for_owner(
        owner_name: declaration[:name],
        comment_entries: pending_comments
      )
      discovered_surfaces.concat(surfaces)
      pending_comments = []
      next
    end

    pending_comments = []
  end

  {
    kind: "ruby",
    dialect: "ruby",
    root_kind: "document",
    source: normalize_source(source),
    owners: (requires + declarations).sort_by { |owner| owner[:path] },
    discovered_surfaces: discovered_surfaces
  }
end

.apply_ruby_delegated_child_outputs(source, delegated_operations, apply_plan, applied_children) ⇒ Object



176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/ruby/merge.rb', line 176

def apply_ruby_delegated_child_outputs(source, delegated_operations, apply_plan, applied_children)
  lines = normalize_source(source).split("\n")
  operations_by_id = delegated_operations.to_h { |operation| [operation[:operation_id], operation] }
  outputs_by_id = applied_children.to_h { |entry| [entry[:operation_id], entry[:output]] }

  replacements = apply_plan[:entries].filter_map do |entry|
    operation = operations_by_id[entry.dig(:delegated_group, :child_operation_id)]
    output = outputs_by_id[entry.dig(:delegated_group, :child_operation_id)]
    span = operation&.dig(:surface, :span)
    next if operation.nil? || output.nil? || span.nil?

    { start: span[:start_line] - 1, finish: span[:end_line] - 1, output: output }
  end

  replacements.sort_by { |entry| -entry[:start] }.each do |entry|
    prefix = comment_prefix_for(lines[entry[:start]])
    replacement_lines = entry[:output].empty? ? [] : entry[:output].sub(/\n\z/, "").split("\n").map { |line| "#{prefix}#{line}" }
    lines[entry[:start]..entry[:finish]] = replacement_lines
  end

  {
    ok: true,
    diagnostics: [],
    output: "#{lines.join("\n").sub(/\n+\z/, "")}\n",
    policies: [DESTINATION_WINS_ARRAY_POLICY]
  }
end

.available_ruby_backendsObject



33
34
35
# File 'lib/ruby/merge.rb', line 33

def available_ruby_backends
  [TREE_SITTER_BACKEND]
end

.collect_ruby_declaration_entries(source) ⇒ Object



470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
# File 'lib/ruby/merge.rb', line 470

def collect_ruby_declaration_entries(source)
  lines = normalize_source(source).split("\n")
  entries = []
  pending_comments = []
  index = 0

  while index < lines.length
    line = lines[index]
    stripped = line.strip

    if comment_line?(line)
      pending_comments << index
      index += 1
      next
    end

    if stripped.empty?
      pending_comments = []
      index += 1
      next
    end

    if REQUIRE_PATTERN.match?(line)
      pending_comments = []
      index += 1
      next
    end

    declaration = declaration_for_line(line)
    unless declaration
      pending_comments = []
      index += 1
      next
    end

    start_index = pending_comments.first || index
    depth = 1
    cursor = index + 1
    while cursor < lines.length
      candidate = lines[cursor].strip
      depth += 1 if declaration_for_line(candidate)
      if candidate == "end"
        depth -= 1
        if depth.zero?
          cursor += 1
          break
        end
      end
      cursor += 1
    end

    entries << {
      path: "/declarations/#{declaration[:name]}",
      text: lines[start_index...cursor].join("\n").strip
    }
    pending_comments = []
    index = cursor
  end

  entries
end

.collect_ruby_require_entries(source) ⇒ Object



368
369
370
371
372
373
374
375
# File 'lib/ruby/merge.rb', line 368

def collect_ruby_require_entries(source)
  normalize_source(source).split("\n").filter_map do |line|
    match = REQUIRE_PATTERN.match(line)
    next unless match

    { path: "/requires/#{match[1]}", text: line.rstrip }
  end
end

.match_ruby_owners(template, destination) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
# File 'lib/ruby/merge.rb', line 80

def match_ruby_owners(template, destination)
  destination_paths = destination[:owners].to_h { |owner| [owner[:path], true] }
  template_paths = template[:owners].to_h { |owner| [owner[:path], true] }
  {
    matched: template[:owners]
      .filter { |owner| destination_paths[owner[:path]] }
      .map { |owner| { template_path: owner[:path], destination_path: owner[:path] } },
    unmatched_template: template[:owners].map { |owner| owner[:path] }.reject { |path| destination_paths[path] },
    unmatched_destination: destination[:owners].map { |owner| owner[:path] }.reject { |path| template_paths[path] }
  }
end

.merge_ruby(template_source, destination_source, dialect, merge_template_requires: false) ⇒ Object



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
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/ruby/merge.rb', line 92

def merge_ruby(template_source, destination_source, dialect, merge_template_requires: false)
  template = parse_ruby(template_source, dialect)
  return template unless template[:ok]

  destination = parse_ruby(destination_source, dialect)
  unless destination[:ok]
    return {
      ok: false,
      diagnostics: destination[:diagnostics].map do |diagnostic|
        diagnostic[:category] == "parse_error" ? diagnostic.merge(category: "destination_parse_error") : diagnostic
      end,
      policies: []
    }
  end

  destination_requires = collect_ruby_require_entries(destination.dig(:analysis, :source))
  template_requires = collect_ruby_require_entries(template.dig(:analysis, :source))
  destination_declarations = collect_ruby_declaration_entries(destination.dig(:analysis, :source))
  template_declarations = collect_ruby_declaration_entries(template.dig(:analysis, :source))
  destination_paths = destination_declarations.to_h { |entry| [entry[:path], true] }
  destination_dsl = collect_top_level_dsl_entries(destination.dig(:analysis, :source))
  template_dsl = collect_top_level_dsl_entries(template.dig(:analysis, :source))
  sections = []
  preamble = collect_ruby_preamble(destination.dig(:analysis, :source))
  sections << preamble unless preamble.empty?
  requires = merge_template_requires ? merge_ruby_requires(destination_requires, template_requires) : destination_requires
  require_block = requires.map { |entry| entry[:text] }.join("\n").strip
  sections << require_block unless require_block.empty?
  sections.concat(merge_top_level_dsl_entries(destination_dsl, template_dsl).map { |entry| entry[:text] })
  sections.concat(destination_declarations.map { |entry| entry[:text] })
  sections.concat(
    template_declarations.reject { |entry| destination_paths[entry[:path]] }.map { |entry| entry[:text] }
  )

  output = "#{sections.join("\n\n").strip}\n"

  {
    ok: true,
    diagnostics: [],
    output: normalize_rakefile_default_task_scaffold(output),
    policies: [DESTINATION_WINS_ARRAY_POLICY]
  }
end

.merge_ruby_with_nested_outputs(template_source, destination_source, dialect, nested_outputs) ⇒ Object



204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/ruby/merge.rb', line 204

def merge_ruby_with_nested_outputs(template_source, destination_source, dialect, nested_outputs)
  Ast::Merge.execute_nested_merge(
    nested_outputs,
    default_family: "ruby",
    request_id_prefix: "nested_ruby_child",
    merge_parent: -> { merge_ruby(template_source, destination_source, dialect) },
    discover_operations: lambda { |merged_output|
      analysis = parse_ruby(merged_output, dialect)
      next { ok: false, diagnostics: analysis[:diagnostics] || [] } unless analysis[:ok]

      {
        ok: true,
        diagnostics: [],
        operations: ruby_delegated_child_operations(analysis[:analysis])
      }
    },
    apply_resolved_outputs: lambda { |merged_output, operations, apply_plan, applied_children|
      apply_ruby_delegated_child_outputs(
        merged_output,
        operations,
        apply_plan,
        applied_children
      )
    }
  )
end

.merge_ruby_with_reviewed_nested_outputs(template_source, destination_source, dialect, review_state, applied_children) ⇒ Object



231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# File 'lib/ruby/merge.rb', line 231

def merge_ruby_with_reviewed_nested_outputs(template_source, destination_source, dialect, review_state, applied_children)
  Ast::Merge.execute_reviewed_nested_merge(
    review_state,
    "ruby",
    applied_children,
    merge_parent: -> { merge_ruby(template_source, destination_source, dialect) },
    discover_operations: lambda { |merged_output|
      analysis = parse_ruby(merged_output, dialect)
      next({ ok: false, diagnostics: analysis[:diagnostics] || [] }) unless analysis[:ok]

      {
        ok: true,
        diagnostics: [],
        operations: ruby_delegated_child_operations(analysis[:analysis])
      }
    },
    apply_resolved_outputs: lambda { |merged_output, operations, apply_plan, resolved_children|
      apply_ruby_delegated_child_outputs(
        merged_output,
        operations,
        apply_plan,
        resolved_children
      )
    }
  )
end

.merge_ruby_with_reviewed_nested_outputs_from_replay_bundle(template_source, destination_source, dialect, replay_bundle) ⇒ Object



258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/ruby/merge.rb', line 258

def merge_ruby_with_reviewed_nested_outputs_from_replay_bundle(template_source, destination_source, dialect, replay_bundle)
  execution = Array(replay_bundle[:reviewed_nested_executions]).find { |entry| entry[:family] == "ruby" }
  return { ok: false, diagnostics: [{ severity: "error", category: "configuration_error", message: "review replay bundle does not include a reviewed nested execution for ruby." }], policies: [] } unless execution

  merge_ruby_with_reviewed_nested_outputs(
    template_source,
    destination_source,
    dialect,
    execution[:review_state],
    execution[:applied_children]
  )
end

.merge_ruby_with_reviewed_nested_outputs_from_replay_bundle_envelope(template_source, destination_source, dialect, envelope) ⇒ Object



284
285
286
287
288
289
290
291
292
293
294
# File 'lib/ruby/merge.rb', line 284

def merge_ruby_with_reviewed_nested_outputs_from_replay_bundle_envelope(template_source, destination_source, dialect, envelope)
  replay_bundle, import_error = Ast::Merge.import_review_replay_bundle_envelope(envelope)
  return { ok: false, diagnostics: [{ severity: "error", category: import_error[:category], message: import_error[:message] }], policies: [] } if import_error

  merge_ruby_with_reviewed_nested_outputs_from_replay_bundle(
    template_source,
    destination_source,
    dialect,
    replay_bundle
  )
end

.merge_ruby_with_reviewed_nested_outputs_from_review_state(template_source, destination_source, dialect, review_state) ⇒ Object



271
272
273
274
275
276
277
278
279
280
281
282
# File 'lib/ruby/merge.rb', line 271

def merge_ruby_with_reviewed_nested_outputs_from_review_state(template_source, destination_source, dialect, review_state)
  execution = Array(review_state[:reviewed_nested_executions]).find { |entry| entry[:family] == "ruby" }
  return { ok: false, diagnostics: [{ severity: "error", category: "configuration_error", message: "review state does not include a reviewed nested execution for ruby." }], policies: [] } unless execution

  merge_ruby_with_reviewed_nested_outputs(
    template_source,
    destination_source,
    dialect,
    execution[:review_state],
    execution[:applied_children]
  )
end

.merge_ruby_with_reviewed_nested_outputs_from_review_state_envelope(template_source, destination_source, dialect, envelope) ⇒ Object



296
297
298
299
300
301
302
303
304
305
306
# File 'lib/ruby/merge.rb', line 296

def merge_ruby_with_reviewed_nested_outputs_from_review_state_envelope(template_source, destination_source, dialect, envelope)
  review_state, import_error = Ast::Merge.import_conformance_manifest_review_state_envelope(envelope)
  return { ok: false, diagnostics: [{ severity: "error", category: import_error[:category], message: import_error[:message] }], policies: [] } if import_error

  merge_ruby_with_reviewed_nested_outputs_from_review_state(
    template_source,
    destination_source,
    dialect,
    review_state
  )
end

.parse_ruby(source, dialect, backend: nil) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/ruby/merge.rb', line 62

def parse_ruby(source, dialect, backend: nil)
  requested = backend.to_s.empty? ? TREE_SITTER_BACKEND.id : backend.to_s
  return unsupported_feature_result("Unsupported Ruby dialect #{dialect}.") unless dialect == "ruby"
  return unsupported_feature_result("Unsupported Ruby backend #{requested}.") unless requested == TREE_SITTER_BACKEND.id

  syntax = TreeHaver.parse_with_language_pack(
    TreeHaver::ParserRequest.new(source: source, language: "ruby", dialect: dialect)
  )
  return { ok: false, diagnostics: syntax[:diagnostics], policies: [] } unless syntax[:ok]

  {
    ok: true,
    diagnostics: [],
    analysis: analyze_ruby_document(source),
    policies: []
  }
end

.ruby_backend_feature_profile(backend: nil) ⇒ Object



37
38
39
40
41
42
43
44
45
46
# File 'lib/ruby/merge.rb', line 37

def ruby_backend_feature_profile(backend: nil)
  requested = backend.to_s.empty? ? TREE_SITTER_BACKEND.id : backend.to_s
  return unsupported_feature_result("Unsupported Ruby backend #{requested}.") unless requested == TREE_SITTER_BACKEND.id

  ruby_feature_profile.merge(
    backend: requested,
    backend_ref: TREE_SITTER_BACKEND.to_h,
    supports_dialects: true
  )
end

.ruby_delegated_child_operations(analysis, parent_operation_id: "ruby-document-0") ⇒ Object



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/ruby/merge.rb', line 140

def ruby_delegated_child_operations(analysis, parent_operation_id: "ruby-document-0")
  surfaces = ruby_discovered_surfaces(analysis)
  doc_operation_ids = {}
  operations = []

  surfaces.each_with_index do |surface, index|
    next unless surface[:surface_kind] == "ruby_doc_comment"

    operation_id = "ruby-doc-comment-#{index}"
    doc_operation_ids[surface[:address]] = operation_id
    operations << Ast::Merge.delegated_child_operation(
      operation_id: operation_id,
      parent_operation_id: parent_operation_id,
      requested_strategy: "delegate_child_surface",
      language_chain: ["ruby", surface[:effective_language]],
      surface: surface
    )
  end

  example_index = 0
  surfaces.each do |surface|
    next unless surface[:surface_kind] == "yard_example_block"

    operations << Ast::Merge.delegated_child_operation(
      operation_id: "yard-example-#{example_index}",
      parent_operation_id: doc_operation_ids.fetch(surface[:parent_address], parent_operation_id),
      requested_strategy: "delegate_child_surface",
      language_chain: ["ruby", "yard", surface[:effective_language]],
      surface: surface
    )
    example_index += 1
  end

  operations
end

.ruby_discovered_surfaces(analysis) ⇒ Object



136
137
138
# File 'lib/ruby/merge.rb', line 136

def ruby_discovered_surfaces(analysis)
  analysis[:discovered_surfaces] || []
end

.ruby_feature_profileObject



25
26
27
28
29
30
31
# File 'lib/ruby/merge.rb', line 25

def ruby_feature_profile
  {
    family: "ruby",
    supported_dialects: ["ruby"],
    supported_policies: [DESTINATION_WINS_ARRAY_POLICY]
  }
end

.ruby_plan_context(backend: nil) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/ruby/merge.rb', line 48

def ruby_plan_context(backend: nil)
  profile = ruby_backend_feature_profile(backend: backend)
  return profile if profile[:ok] == false

  {
    family_profile: ruby_feature_profile,
    feature_profile: {
      backend: profile[:backend],
      supports_dialects: true,
      supported_policies: profile[:supported_policies]
    }
  }
end

.unsupported_feature_result(message) ⇒ Object



532
533
534
535
536
537
538
# File 'lib/ruby/merge.rb', line 532

def unsupported_feature_result(message)
  {
    ok: false,
    diagnostics: [{ severity: "error", category: "unsupported_feature", message: message }],
    policies: []
  }
end

Instance Method Details

#collect_ruby_preamble(source) ⇒ Object



377
378
379
380
381
382
383
384
385
386
# File 'lib/ruby/merge.rb', line 377

def collect_ruby_preamble(source)
  lines = normalize_source(source).split("\n")
  preamble = []
  lines.each do |line|
    break unless line.strip.empty? || comment_line?(line)

    preamble << line.rstrip
  end
  preamble.join("\n").strip
end

#collect_top_level_dsl_entries(source) ⇒ Object



388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
# File 'lib/ruby/merge.rb', line 388

def collect_top_level_dsl_entries(source)
  lines = normalize_source(source).split("\n")
  entries = []
  pending_comments = []
  index = 0

  while index < lines.length
    line = lines[index]
    stripped = line.strip
    if comment_line?(line)
      pending_comments << index
      index += 1
      next
    end
    if stripped.empty?
      pending_comments = []
      index += 1
      next
    end
    if REQUIRE_PATTERN.match?(line) || declaration_for_line(line)
      pending_comments = []
      index += 1
      next
    end

    if line.match?(/\Abegin\b/)
      start_index = pending_comments.first || index
      finish_index = ruby_block_finish_index(lines, index)
      text = lines[start_index..finish_index].join("\n").strip
      signature = begin_block_signature(text)
      entries << { path: "/dsl/#{signature}", name: "begin", signature: signature, text: text }
      pending_comments = []
      index = finish_index + 1
      next
    end

    match = DSL_CALL_PATTERN.match(line)
    unless match
      pending_comments = []
      index += 1
      next
    end

    name = match[:name]
    if name == "desc" && next_code_line_is_task?(lines, index + 1)
      pending_comments << index
      index += 1
      next
    end

    start_index = pending_comments.first || index
    finish_index = dsl_entry_finish_index(lines, index)
    text = lines[start_index..finish_index].join("\n").strip
    signature = dsl_entry_signature(name, line)
    entries << { path: "/dsl/#{signature}", name: name, signature: signature, text: text } if signature
    pending_comments = []
    index = finish_index + 1
  end

  entries
end

#merge_ruby_requires(destination_requires, template_requires) ⇒ Object



465
466
467
468
# File 'lib/ruby/merge.rb', line 465

def merge_ruby_requires(destination_requires, template_requires)
  destination_paths = destination_requires.to_h { |entry| [entry[:path], true] }
  destination_requires + template_requires.reject { |entry| destination_paths[entry[:path]] }
end

#merge_top_level_dsl_entries(destination_entries, template_entries) ⇒ Object



450
451
452
453
454
455
456
457
458
459
460
461
462
463
# File 'lib/ruby/merge.rb', line 450

def merge_top_level_dsl_entries(destination_entries, template_entries)
  destination_by_signature = destination_entries.to_h { |entry| [entry[:signature], entry] }
  template_singletons = template_entries.select { |entry| dsl_singleton_entry?(entry) }
  template_singleton_signatures = template_singletons.map { |entry| entry[:signature] }.to_h { |signature| [signature, true] }
  result = []
  result.concat(template_singletons)
  result.concat(destination_entries.reject { |entry| template_singleton_signatures[entry[:signature]] })
  result.concat(
    template_entries.reject do |entry|
      dsl_singleton_entry?(entry) || destination_by_signature[entry[:signature]]
    end
  )
  result
end