Class: MilkTea::PrettyPrinter::IRFormatter

Inherits:
BaseFormatter show all
Defined in:
lib/milk_tea/core/pretty_printer/ir_formatter.rb

Constant Summary collapse

IF_EXPRESSION_PRECEDENCE =
5
POSTFIX_PRECEDENCE =
90
UNARY_PRECEDENCE =
80

Constants inherited from BaseFormatter

BaseFormatter::INDENT

Instance Method Summary collapse

Methods inherited from BaseFormatter

#binding_name, #blank_line, #capture_lines, #finish, #initialize, #line, #precedence, #with_indent, #wrap

Constructor Details

This class inherits a constructor from MilkTea::PrettyPrinter::BaseFormatter

Instance Method Details

#emit_constant(constant) ⇒ Object



43
44
45
# File 'lib/milk_tea/core/pretty_printer/ir_formatter.rb', line 43

def emit_constant(constant)
  line("const #{binding_name(constant.name, constant.linkage_name)}: #{constant.type} = #{render_expression(constant.value)}")
end

#emit_enum(enum_decl) ⇒ Object



98
99
100
101
102
103
104
105
106
# File 'lib/milk_tea/core/pretty_printer/ir_formatter.rb', line 98

def emit_enum(enum_decl)
  kind = enum_decl.flags ? "flags" : "enum"
  line("#{kind} #{binding_name(enum_decl.name, enum_decl.linkage_name)}: #{enum_decl.backing_type}")
  with_indent do
    enum_decl.members.each do |member|
      line("#{binding_name(member.name, member.linkage_name)} = #{render_expression(member.value)}")
    end
  end
end

#emit_function(function) ⇒ Object



112
113
114
115
116
117
118
119
120
121
122
# File 'lib/milk_tea/core/pretty_printer/ir_formatter.rb', line 112

def emit_function(function)
  header = "fn #{binding_name(function.name || function.linkage_name, function.linkage_name)}(#{function.params.map { |param| render_param(param) }.join(', ')}) -> #{function.return_type}"
  header += " [entry]" if function.entry_point
  header += ":"
  line(header)
  with_indent do
    function.body.each do |statement|
      emit_statement(statement)
    end
  end
end

#emit_global(global) ⇒ Object



47
48
49
# File 'lib/milk_tea/core/pretty_printer/ir_formatter.rb', line 47

def emit_global(global)
  line("var #{binding_name(global.name, global.linkage_name)}: #{global.type} = #{render_expression(global.value)}")
end

#emit_opaque(opaque_decl) ⇒ Object



51
52
53
# File 'lib/milk_tea/core/pretty_printer/ir_formatter.rb', line 51

def emit_opaque(opaque_decl)
  line("opaque #{binding_name(opaque_decl.name, opaque_decl.linkage_name)}")
end

#emit_program(program) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/milk_tea/core/pretty_printer/ir_formatter.rb', line 15

def emit_program(program)
  module_name = program.module_name || "(anonymous)"
  line("program #{module_name}")
  emit_section("includes", program.includes) { |include_directive| line("include #{include_directive.header}") }
  emit_section("constants", program.constants) { |constant| emit_constant(constant) }
  emit_section("globals", program.globals) { |global_directive| emit_global(global_directive) }
  emit_section("opaques", program.opaques) { |opaque_declaration| emit_opaque(opaque_declaration) }
  emit_section("structs", program.structs) { |struct_decl| emit_struct(struct_decl) }
  emit_section("unions", program.unions) { |union_decl| emit_union(union_decl) }
  emit_section("enums", program.enums) { |enum_decl| emit_enum(enum_decl) }
  emit_section("variants", program.variants) { |variant_declaration| emit_variant(variant_declaration) }
  emit_section("static_asserts", program.static_asserts) { |static_assert| emit_static_assert(static_assert) }
  emit_section("functions", program.functions) { |function| emit_function(function) }
end

#emit_section(title, items) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/milk_tea/core/pretty_printer/ir_formatter.rb', line 30

def emit_section(title, items)
  return if items.empty?

  blank_line
  line("#{title}:")
  with_indent do
    items.each_with_index do |item, index|
      yield(item)
      blank_line if index < (items.length - 1)
    end
  end
end

#emit_statement(statement) ⇒ Object



129
130
131
132
133
134
135
136
137
138
139
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/milk_tea/core/pretty_printer/ir_formatter.rb', line 129

def emit_statement(statement)
  case statement
  when IR::LocalDecl
    line("let #{binding_name(statement.name, statement.linkage_name)}: #{statement.type} = #{render_expression(statement.value)}")
  when IR::Assignment
    line("#{render_expression(statement.target)} #{statement.operator} #{render_expression(statement.value)}")
  when IR::BlockStmt
    line("block:")
    with_indent do
      statement.body.each { |nested| emit_statement(nested) }
    end
  when IR::IfStmt
    line("if #{render_expression(statement.condition)}:")
    with_indent do
      statement.then_body.each { |nested| emit_statement(nested) }
    end
    if statement.else_body && !statement.else_body.empty?
      line("else:")
      with_indent do
        statement.else_body.each { |nested| emit_statement(nested) }
      end
    end
  when IR::SwitchStmt
    line("switch #{render_expression(statement.expression)}:")
    with_indent do
      statement.cases.each do |switch_case|
        if switch_case.is_a?(IR::SwitchDefaultCase)
          line("default:")
        else
          line("case #{render_expression(switch_case.value)}:")
        end
        with_indent do
          switch_case.body.each { |nested| emit_statement(nested) }
        end
      end
    end
  when IR::WhileStmt
    line("while #{render_expression(statement.condition)}:")
    with_indent do
      statement.body.each { |nested| emit_statement(nested) }
    end
  when IR::ForStmt
    init = render_for_clause_statement(statement.init)
    post = render_for_clause_statement(statement.post)
    line("for #{init}; #{render_expression(statement.condition)}; #{post}:")
    with_indent do
      statement.body.each { |nested| emit_statement(nested) }
    end
  when IR::BreakStmt
    line("break")
  when IR::ContinueStmt
    line("continue")
  when IR::GotoStmt
    line("goto #{statement.label}")
  when IR::LabelStmt
    line("label #{statement.name}")
  when IR::StaticAssert
    emit_static_assert(statement)
  when IR::ReturnStmt
    line(statement.value ? "return #{render_expression(statement.value)}" : "return")
  when IR::ExpressionStmt
    line(render_expression(statement.expression))
  else
    raise ArgumentError, "unsupported IR statement #{statement.class.name}"
  end
end

#emit_static_assert(static_assert) ⇒ Object



108
109
110
# File 'lib/milk_tea/core/pretty_printer/ir_formatter.rb', line 108

def emit_static_assert(static_assert)
  line("static_assert(#{render_expression(static_assert.condition)}, #{render_expression(static_assert.message)})")
end

#emit_struct(struct_decl) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/milk_tea/core/pretty_printer/ir_formatter.rb', line 69

def emit_struct(struct_decl)
  header = "struct #{binding_name(struct_decl.name, struct_decl.linkage_name)}"
  params = []
  if struct_decl.respond_to?(:lifetime_params) && struct_decl.lifetime_params&.any?
    params.push(*struct_decl.lifetime_params)
  end
  modifiers = []
  modifiers << "packed" if struct_decl.respond_to?(:packed) && struct_decl.packed
  modifiers << "align(#{struct_decl.alignment})" if struct_decl.respond_to?(:alignment) && struct_decl.alignment
  params.concat(modifiers) unless modifiers.empty?
  header += " [#{params.join(', ')}]" unless params.empty?
  header += ":"
  line(header)
  with_indent do
    struct_decl.fields.each do |field|
      line("#{field.name}: #{field.type}")
    end
  end
end

#emit_union(union_decl) ⇒ Object



89
90
91
92
93
94
95
96
# File 'lib/milk_tea/core/pretty_printer/ir_formatter.rb', line 89

def emit_union(union_decl)
  line("union #{binding_name(union_decl.name, union_decl.linkage_name)}:")
  with_indent do
    union_decl.fields.each do |field|
      line("#{field.name}: #{field.type}")
    end
  end
end

#emit_variant(variant_decl) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/milk_tea/core/pretty_printer/ir_formatter.rb', line 55

def emit_variant(variant_decl)
  line("variant #{binding_name(variant_decl.name, variant_decl.linkage_name)}:")
  with_indent do
    variant_decl.arms.each do |arm|
      text = binding_name(arm.name, arm.linkage_name)
      unless arm.fields.empty?
        field_texts = arm.fields.map { |f| "#{f.name}: #{f.type}" }
        text += "(#{field_texts.join(', ')})"
      end
      line(text)
    end
  end
end

#format(node) ⇒ Object



10
11
12
13
# File 'lib/milk_tea/core/pretty_printer/ir_formatter.rb', line 10

def format(node)
  emit_program(node)
  finish
end

#pointer_receiver_expression?(expression) ⇒ Boolean

Returns:

  • (Boolean)


291
292
293
# File 'lib/milk_tea/core/pretty_printer/ir_formatter.rb', line 291

def pointer_receiver_expression?(expression)
  (expression.is_a?(IR::Name) && expression.pointer) || (expression.respond_to?(:type) && pointer_type?(expression.type))
end

#pointer_type?(type) ⇒ Boolean

Returns:

  • (Boolean)


295
296
297
# File 'lib/milk_tea/core/pretty_printer/ir_formatter.rb', line 295

def pointer_type?(type)
  type.is_a?(Types::GenericInstance) && type.name == "ptr" && type.arguments.length == 1
end

#postfix_expression?(expression) ⇒ Boolean

Returns:

  • (Boolean)


287
288
289
# File 'lib/milk_tea/core/pretty_printer/ir_formatter.rb', line 287

def postfix_expression?(expression)
  expression.is_a?(IR::Name) || expression.is_a?(IR::Member) || expression.is_a?(IR::Index) || expression.is_a?(IR::Call)
end

#render_expression(expression, parent_precedence = 0) ⇒ Object



196
197
198
199
200
201
202
203
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
230
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
257
258
259
260
261
262
263
264
265
266
# File 'lib/milk_tea/core/pretty_printer/ir_formatter.rb', line 196

def render_expression(expression, parent_precedence = 0)
  case expression
  when IR::Name
    expression.name
  when IR::Member
    operator = pointer_receiver_expression?(expression.receiver) ? "->" : "."
    wrap("#{render_postfix(expression.receiver)}#{operator}#{expression.member}", parent_precedence, POSTFIX_PRECEDENCE)
  when IR::Index
    wrap("#{render_postfix(expression.receiver)}[#{render_expression(expression.index)}]", parent_precedence, POSTFIX_PRECEDENCE)
  when IR::CheckedIndex
    "checked_index<#{expression.receiver_type}>(#{render_expression(expression.receiver)}, #{render_expression(expression.index)})"
  when IR::CheckedSpanIndex
    "checked_span_index<#{expression.receiver_type}>(#{render_expression(expression.receiver)}, #{render_expression(expression.index)})"
  when IR::NullableIndex
    "nullable_index<#{expression.receiver_type}>(#{render_expression(expression.receiver)}, #{render_expression(expression.index)})"
  when IR::NullableSpanIndex
    "nullable_span_index<#{expression.receiver_type}>(#{render_expression(expression.receiver)}, #{render_expression(expression.index)})"
  when IR::Call
    wrap("#{expression.callee}(#{expression.arguments.map { |argument| render_expression(argument) }.join(', ')})", parent_precedence, POSTFIX_PRECEDENCE)
  when IR::Unary
    operand = render_expression(expression.operand, UNARY_PRECEDENCE)
    text = expression.operator == "not" ? "not #{operand}" : "#{expression.operator}#{operand}"
    wrap(text, parent_precedence, UNARY_PRECEDENCE)
  when IR::Binary
    current_precedence = precedence(expression.operator)
    left = render_expression(expression.left, current_precedence)
    right = render_expression(expression.right, current_precedence + 1)
    wrap("#{left} #{expression.operator} #{right}", parent_precedence, current_precedence)
  when IR::Conditional
    condition = render_expression(expression.condition, IF_EXPRESSION_PRECEDENCE)
    then_expression = render_expression(expression.then_expression, IF_EXPRESSION_PRECEDENCE)
    else_expression = render_expression(expression.else_expression, IF_EXPRESSION_PRECEDENCE)
    wrap("if #{condition}: #{then_expression} else: #{else_expression}", parent_precedence, IF_EXPRESSION_PRECEDENCE)
  when IR::ReinterpretExpr
    "reinterpret[#{expression.target_type} <- #{expression.source_type}](#{render_expression(expression.expression)})"
  when IR::SizeofExpr
    "size_of(#{expression.target_type})"
  when IR::AlignofExpr
    "align_of(#{expression.target_type})"
  when IR::OffsetofExpr
    "offset_of(#{expression.target_type}, #{expression.field})"
  when IR::IntegerLiteral, IR::FloatLiteral
    expression.value.to_s
  when IR::StringLiteral
    expression.cstring ? "c#{expression.value.inspect}" : expression.value.inspect
  when IR::BooleanLiteral
    expression.value ? "true" : "false"
  when IR::NullLiteral
    "null"
  when IR::ZeroInit
    "zero[#{expression.type}]"
  when IR::AddressOf
    wrap("&#{render_expression(expression.expression, UNARY_PRECEDENCE)}", parent_precedence, UNARY_PRECEDENCE)
  when IR::Cast
    "#{expression.target_type}<-#{render_expression(expression.expression)}"
  when IR::AggregateLiteral
    "#{expression.type}(#{expression.fields.map { |field| "#{field.name} = #{render_expression(field.value)}" }.join(', ')})"
  when IR::VariantLiteral
    if expression.fields.empty?
      "#{expression.type}.#{expression.arm_name}"
    else
      "#{expression.type}.#{expression.arm_name}(#{expression.fields.map { |field| "#{field.name} = #{render_expression(field.value)}" }.join(', ')})"
    end
  when IR::ArrayLiteral
    "#{expression.type}(#{expression.elements.map { |element| render_expression(element) }.join(', ')})"
  when IR::Assignment
    "#{render_expression(expression.target)} #{expression.operator} #{render_expression(expression.value)}"
  else
    raise ArgumentError, "unsupported IR expression #{expression.class.name}"
  end
end

#render_for_clause_statement(statement) ⇒ Object



268
269
270
271
272
273
274
275
276
277
278
279
# File 'lib/milk_tea/core/pretty_printer/ir_formatter.rb', line 268

def render_for_clause_statement(statement)
  case statement
  when IR::LocalDecl
    "#{statement.linkage_name}: #{statement.type} = #{render_expression(statement.value)}"
  when IR::Assignment
    "#{render_expression(statement.target)} #{statement.operator} #{render_expression(statement.value)}"
  when IR::ExpressionStmt
    render_expression(statement.expression)
  else
    raise ArgumentError, "unsupported for clause #{statement.class.name}"
  end
end

#render_param(param) ⇒ Object



124
125
126
127
# File 'lib/milk_tea/core/pretty_printer/ir_formatter.rb', line 124

def render_param(param)
  type = param.pointer ? "ptr[#{param.type}]" : param.type.to_s
  "#{binding_name(param.name, param.linkage_name)}: #{type}"
end

#render_postfix(expression) ⇒ Object



281
282
283
284
285
# File 'lib/milk_tea/core/pretty_printer/ir_formatter.rb', line 281

def render_postfix(expression)
  return render_expression(expression, POSTFIX_PRECEDENCE) if postfix_expression?(expression)

  "(#{render_expression(expression)})"
end