Module: Oppen::Mixins

Included in:
Oppen, Printer, ScanStack
Defined in:
lib/oppen/mixins.rb

Overview

Mixins.

Instance Method Summary collapse

Instance Method Details

#tokens_to_wadler(tokens, base_indent: 0, printer_name: 'out', width: tokens.length * 3) ⇒ String

Returns:

  • (String)


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
# File 'lib/oppen/mixins.rb', line 26

def tokens_to_wadler(tokens, base_indent: 0, printer_name: 'out', width: tokens.length * 3)
  printer = Oppen::Wadler.new(base_indent:, indent: 2, width:)

  handle_break_token = ->(token) {
    if token.offset.positive?
      printer
        .text("#{printer_name}.nest(indent: #{token.offset}) {")
        .nest_open
        .break
    end

    printer.text(
      case token
      in Token::LineBreak
        "#{printer_name}.break(line_continuation: #{token.line_continuation.inspect})"
      in Token::Break
        "#{printer_name}.breakable(#{token.str.inspect}, width: #{token.width}, " \
        "line_continuation: #{token.line_continuation.inspect})"
      end,
    )

    printer.nest_close.break.text '}' if token.offset.positive?
  }

  tokens.each_with_index do |token, idx|
    case token
    in Token::String
      printer.text "#{printer_name}.text(#{token.value.inspect}, width: #{token.width})"
    in Token::Break
      handle_break_token.(token)
    in Token::Begin
      printer
        .text("#{printer_name}.group(#{token.break_type.inspect}, indent: #{token.offset}) {")
        .nest_open
    in Token::End
      printer.nest_close.break.text '}'
    in Token::EOF
      nil
    end
    printer.break if !tokens[idx + 1].is_a?(Token::End)
  end

  printer.output
end