Module: Sloprb::Typoeater

Defined in:
lib/sloprb/typoeater.rb

Constant Summary collapse

SYSTEM_PROMPT =
<<~PROMPT
  You are a Ruby syntax error fixer. You will be given a Ruby source file that has a syntax error, along with the error message.
  Your job is to fix the syntax error and return the corrected source file.

  Rules:
  - Return ONLY the complete corrected Ruby source file
  - Do not include any explanation, comments about the fix, or markdown formatting
  - Do not change any logic or behavior — only fix the syntax error
  - Preserve all existing comments, whitespace style, and formatting
PROMPT

Class Method Summary collapse

Class Method Details

.call(path, error, chat: nil) ⇒ Object



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
# File 'lib/sloprb/typoeater.rb', line 19

def call(path, error, chat: nil)
  chat ||= default_chat

  source = File.read(path)
  error_context = error.respond_to?(:detailed_message) ? error.detailed_message(highlight: false) : error.message

  user_prompt = <<~PROMPT
    Here is the Ruby source file with a syntax error:

    ```ruby
    #{source}
    ```

    Syntax error:
    #{error_context}

    Return the complete corrected Ruby source file.
  PROMPT

  response = chat.with_instructions(SYSTEM_PROMPT).ask(user_prompt)
  corrected = strip_fences(response.content)
  corrected << "\n" unless corrected.end_with?("\n")

  result = Prism.parse(corrected)
  return if result.errors.any?

  corrected
rescue
  nil
end

.register_hookObject



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/sloprb/typoeater.rb', line 50

def register_hook
  require "require-hooks/setup"

  RequireHooks.around_load do |path, &load_block|
    result = begin
      load_block.call
    rescue ::SyntaxError => original_error
      corrected = Typoeater.call(path, original_error)
      raise original_error unless corrected

      File.write(path, corrected)

      warn "[sloprb] auto-corrected syntax error in #{path}"

      begin
        load_block.call
      rescue ::SyntaxError
        raise original_error
      end
    end
    result
  end
end