Module: Jade::Codegen

Extended by:
Codegen, Context, Emitter, Helpers
Included in:
Codegen
Defined in:
lib/jade/codegen.rb,
lib/jade/codegen/inline.rb,
lib/jade/codegen/pretty.rb,
lib/jade/codegen/context.rb,
lib/jade/codegen/emitter.rb,
lib/jade/codegen/helpers.rb,
lib/jade/codegen/inlines.rb,
lib/jade/codegen/boundary.rb,
lib/jade/codegen/method_names.rb,
lib/jade/codegen/port_decoder.rb,
lib/jade/codegen/function_call.rb,
lib/jade/codegen/boundary/cache.rb,
lib/jade/codegen/implementation.rb,
lib/jade/codegen/pattern/constructor.rb,
lib/jade/codegen/variant_declaration.rb,
lib/jade/codegen/boundary/specialized.rb,
lib/jade/codegen/function_declaration.rb,
lib/jade/codegen/transforms/self_call.rb,
lib/jade/codegen/transforms/tail_call.rb,
lib/jade/codegen/constructor_reference.rb,
lib/jade/codegen/transforms/fold_shape.rb,
lib/jade/codegen/boundary/specialized/list.rb,
lib/jade/codegen/boundary/specialized/maybe.rb,
lib/jade/codegen/boundary/specialized/record.rb,
lib/jade/codegen/boundary/specialized/scalar.rb

Defined Under Namespace

Modules: Boundary, ConstructorReference, Context, Emitter, FunctionCall, FunctionDeclaration, Helpers, Implementation, Inline, Inlines, MethodNames, Pattern, PortDecoder, Pretty, Transforms, VariantDeclaration

Constant Summary

Constants included from Helpers

Helpers::NATIVE_RUBY_CLASSES

Instance Method Summary collapse

Methods included from Emitter

emit

Methods included from Helpers

data_define, dict_constraints, dict_synthetic_name, fn_constraints, fn_impl_synthetic_name, generate_many, generate_node, impl_synthetic_name, param_synthetic_name, resolve_callee_symbol, ruby_classes_for_type, to_qualified

Methods included from Context

boundary_cache, dict_env, dispatched_methods, hoist_records?, self_var_name, with_boundary_cache, with_dict_env, with_dispatched_methods, with_hoisted_records, with_self_var_name

Instance Method Details

#collect_dispatched_methods(body, registry) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/jade/codegen.rb', line 47

def collect_dispatched_methods(body, registry)
  body.expressions
    .filter { it.is_a?(AST::Implementation) }
    .filter { MethodNames.operator_interface?(it.symbol.interface.qualified_name) }
    .flat_map do |node|
      methods = Implementation.method_bodies_for(node, registry)
      ruby_classes_for_type(node.symbol.type, registry).map { [it, methods] }
    end
    .group_by(&:first)
    .transform_values { |pairs| pairs.flat_map(&:last) }
end

#collect_record_shapes(node, shapes = ::Set.new) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/jade/codegen.rb', line 35

def collect_record_shapes(node, shapes = ::Set.new)
  shapes << node.fields.map(&:key).sort if node.is_a?(AST::RecordLiteral)

  if node.is_a?(AST::Node)
    node.members.each do |m|
      [*node.public_send(m)].each { collect_record_shapes(it, shapes) if it.is_a?(AST::Node) }
    end
  end

  shapes
end

#data_define_with_methods(name, fields, ruby_class) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/jade/codegen.rb', line 59

def data_define_with_methods(name, fields, ruby_class)
  methods = dispatched_methods[ruby_class] || []
  base    = data_define(fields)

  if methods.empty?
    "#{name} = #{base}"
  else
    methods
      .join(Pretty.newline(2))
      .then { Pretty.block("#{name} = #{base} do", it) }
  end
end

#generate(node, registry, depth: 0) ⇒ Object



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
123
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
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
195
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'lib/jade/codegen.rb', line 82

def generate(node, registry, depth: 0)
  case node
  in AST::Module(name:, body:)
    preamble = [
      "require 'jade/runtime'",
      *Stdlib.requires(name),
      *namespace_setup_lines(name),
    ].reject(&:empty?).join(Pretty.newline)

    shape_consts = collect_record_shapes(body)
      .sort
      .map { |keys|
        "#{record_shape_constant(keys)} = Data.define(#{keys.map { ":#{it}" }.join(', ')})"
      }

    boundary_cache   = Boundary::Cache.collect(body, registry)
    boundary_consts  = Boundary::Cache.constants(boundary_cache, registry)
    boundary_helpers = Boundary::Specialized.collect_helpers(body, registry)
      .then { Boundary::Specialized.emit_helpers(it, registry) }

    outer, inner, wrappers =
      with_boundary_cache(boundary_cache) do
        with_dispatched_methods(collect_dispatched_methods(body, registry)) do
          with_hoisted_records do
            partition_module_body(body.expressions, registry, name.count('.'))
          end
        end
      end

    inner_module = ["extend self", *inner]
      .join(Pretty.newline(2))
      .then { Pretty.block("module Internal", it) }

    [
      "extend self",
      *shape_consts,
      *outer,
      inner_module,
      *boundary_consts,
      *boundary_helpers,
      *wrappers,
    ]
      .reject(&:empty?)
      .join(Pretty.newline(2))
      .then { Pretty.block("module #{to_qualified(name)}", it) }
      .then { [preamble, it].reject(&:empty?).join(Pretty.newline(2)) }

  in AST::ImportDeclaration(module_name:)
    entry = registry.get(module_name)
    if Stdlib.is_stdlib?(entry)
      ""
    else
      entry.path
        .then { relative_require(it, depth) }
        .then { "require_relative '#{it}'" }
    end

  in AST::InteropImportDeclaration(module: mod)
    Pretty.block("begin", "require '#{mod.name.gsub('::', '/').downcase}'\nrescue LoadError")

  in AST::Implementation
    Implementation.generate(node, registry)

  in AST::Body(expressions:)
    expressions
      .map { generate(it, registry, depth:) }
      .reject(&:empty?)
      .join("\n")

  in AST::VariableReference(name:) if name == self_var_name
    'self'

  in AST::VariableReference(symbol: ref, name:, dictionaries:)
    resolved = ref.is_a?(Symbol::ValueRef) ? registry.lookup(ref) : ref

    reference_emission(resolved, dictionaries, registry) do
      case resolved
      in Symbol::InteropFunction => sym
        registry
          .lookup(sym.to_ref)
          .then { PortDecoder.task_call(it, registry) }

      in Symbol::StdlibFunction(codegen:)
        codegen

      in Symbol::Function => fn
        "#{to_qualified(fn.module_name)}::Internal.method(:#{fn.name})"

      else
        name
      end
    end

  in AST::Assign(pattern:, expression:)
    case pattern
    in AST::Pattern::Binding(name:)
      "#{name} = #{generate(expression, registry)}"
    in AST::Pattern::Wildcard
      generate(expression, registry)
    else
      "#{generate(expression, registry)} => #{generate(pattern, registry)}"
    end

  in AST::Literal(value:)
    emit(value)

  in AST::CharLiteral(value:)
    emit(value)

  in AST::FunctionDeclaration
    FunctionDeclaration.generate(node, registry)

  in AST::FunctionDeclarationParam(name:)
    name

  in AST::FunctionCall
    FunctionCall.generate(node, registry)

  in AST::ConstructorReference
    ConstructorReference.generate(node, registry)

  in AST::TypeDeclaration(variants:)
    variants
      .map { VariantDeclaration.generate(it, variants.map(&:name)) }
      .join(Pretty.newline(2))

  in AST::StructDeclaration(name:, record_type:, symbol:)
    data_define_with_methods(name, record_type.fields.keys, "::#{to_qualified(symbol.qualified_name)}")

  in AST::InterfaceDeclaration
    ""

  in AST::QualifiedAccess(symbol:, dictionaries:)
    resolved = registry.lookup(symbol)

    reference_emission(resolved, dictionaries, registry) do
      case resolved
      in Symbol::StdlibFunction(codegen:)
        codegen

      in Symbol::Function => fn
        "#{to_qualified(fn.module_name)}::Internal.method(:#{fn.name})"

      in Symbol::Constructor => sym
        ConstructorReference.from_symbol(sym)
      end
    end

  in AST::IfThenElse(condition:, if_branch:, else_branch:)
    [
      "if (#{generate(condition, registry)})",
      Pretty.indent(generate(if_branch, registry)),
      "else",
      Pretty.indent(generate(else_branch, registry)),
      "end",
    ].join(Pretty.newline)

  in AST::CaseOf(expression:, branches:)
    branches
      .map { generate(it, registry) }
      .join("\n")
      .then { "case #{generate(expression, registry)}\n#{it}\nend" }

  in AST::CaseOfBranch(pattern:, body:)
    pat  = generate(pattern, registry)
    body = generate(body, registry)

    Pretty.multiline?(body) \
      ? "in #{pat} then\n#{Pretty.indent(body)}"
      : "in #{pat} then #{body}"

  in AST::Pattern::Literal(literal:)
    generate(literal, registry)

  in AST::Pattern::Wildcard
    "_"

  in AST::Pattern::Binding(name:)
    name

  in AST::Pattern::Record(fields:)
    generate_many(fields, registry)
      .then { "{ #{it} }"}

  in AST::Pattern::RecordField(name:, pattern:)
      "#{name}: #{generate(pattern, registry)}"

  in AST::Pattern::List(patterns:, rest:)
    rest_part =
      case rest
      in AST::Pattern::Binding(name:) then ["*#{name}"]
      in AST::Pattern::Wildcard then ["*"]
      in nil then []
      end

    Pretty.array(patterns.map { generate(it, registry) } + rest_part)

  in AST::Pattern::Constructor
    Pattern::Constructor.generate(node, registry)

  in AST::Lambda(params:, body:)
    param_strs = params.zip(0..).map { |p, i| param_name(p, i) }

    params
      .zip(0..)
      .filter_map { |p, i| "#{param_synthetic_name(i)} => #{generate(p, registry)}" unless simple_pattern?(p) }
      .then { (it + [generate(body, registry)]).join("\n") }
      .then { Pretty.lambda(param_strs.join(', '), it) }

  in AST::Grouping(expression:)
    "(#{generate(expression, registry)})"

  in AST::List(items:)
    Pretty.array(items.map { generate(it, registry) })

  in AST::RecordLiteral(fields:)
    fields.sort_by(&:key).then do |sorted|
      keys   = sorted.map(&:key)
      values = generate_many(sorted.map(&:value), registry)

      hoist_records? \
        ? "#{record_shape_constant(keys)}[#{values}]"
        : "Jade::Runtime.record(#{keys.map { ":#{it}" }.join(', ')})[#{values}]"
    end

  in AST::RecordField(key:, value:)
    "#{key}: #{generate(value, registry)}"

  in AST::RecordAccess(target:, name:)
    if self_var_name && target.is_a?(AST::VariableReference) && target.name == self_var_name
      name.name
    else
      "#{generate(target, registry)}.#{name.name}"
    end

  in AST::RecordUpdate(base:, fields:)
    generate_many(fields, registry)
      .then { "#{generate(base, registry)}.with(#{it})" }
  end
end

#generate_entry(entry, registry) ⇒ Object



72
73
74
75
76
# File 'lib/jade/codegen.rb', line 72

def generate_entry(entry, registry)
  generate(entry.ast, registry)
    .then { entry.entry ? "#{load_path}\n#{it}" : it }
    .then { entry.with(generated: it) }
end

#record_shape_constant(keys) ⇒ Object



31
32
33
# File 'lib/jade/codegen.rb', line 31

def record_shape_constant(keys)
  "Record_#{keys.join('_')}"
end

#reference_emission(resolved, dictionaries, registry, &fallback) ⇒ Object



78
79
80
# File 'lib/jade/codegen.rb', line 78

def reference_emission(resolved, dictionaries, registry, &fallback)
  FunctionCall.reference_with_dictionaries(resolved, dictionaries, registry) || fallback.call
end