Class: MilkTea::Build

Inherits:
Object
  • Object
show all
Defined in:
lib/milk_tea/tooling/build.rb

Defined Under Namespace

Classes: FrontendModule, Result, RubyFrontend

Constant Summary collapse

DEFAULT_WASM_SHELL_TEMPLATE_PATH =
File.expand_path("templates/wasm_shell.html", __dir__).freeze
WASM_SHELL_SCRIPT_PLACEHOLDER =
"{{{ SCRIPT }}}".freeze
WASM_SHELL_CANVAS_PLACEHOLDER =
"{{{ MILK_TEA_CANVAS }}}".freeze
WASM_SHELL_OUTPUT_PLACEHOLDER =
"{{{ MILK_TEA_OUTPUT }}}".freeze
WASM_SHELL_BOOTSTRAP_PLACEHOLDER =
"{{{ MILK_TEA_BOOTSTRAP }}}".freeze
WASM_SHELL_TEMPLATE =
File.read(DEFAULT_WASM_SHELL_TEMPLATE_PATH).freeze
WASM_SHELL_CANVAS_TEMPLATE =
<<~HTML.freeze
  <canvas id="canvas" oncontextmenu="event.preventDefault()" tabindex="-1"></canvas>
HTML
WASM_SHELL_OUTPUT_TEMPLATE =
<<~HTML.freeze
  <pre id="output"></pre>
HTML
WASM_SHELL_BOOTSTRAP_TEMPLATE =
<<~HTML.freeze
  <script>
    var Module = {
      print: (function() {
        var element = document.getElementById('output');
        if (element) element.textContent = '';
        return function(text) {
          if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
          console.log(text);
          if (element) {
            element.textContent += text + "\\n";
            element.scrollTop = element.scrollHeight;
          }
        };
      })(),
      printErr: (function() {
        var element = document.getElementById('output');
        return function(text) {
          if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
          console.error(text);
          if (element) {
            element.textContent += "[err] " + text + "\\n";
            element.scrollTop = element.scrollHeight;
          }
        };
      })(),
      canvas: (function() {
        return document.getElementById('canvas');
      })()
    };
  </script>
HTML

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, output_path:, cc:, keep_c_path:, raw_bindings:, module_roots: nil, package_graph: nil, frontend: nil, debug: false, profile: nil, platform: nil, bundle: false, archive: false, no_cache: false, sanitize: false, kind: :executable, debug_guards: nil) ⇒ Build

Returns a new instance of Build.



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
# File 'lib/milk_tea/tooling/build.rb', line 132

def initialize(path, output_path:, cc:, keep_c_path:, raw_bindings:, module_roots: nil, package_graph: nil, frontend: nil, debug: false, profile: nil, platform: nil, bundle: false, archive: false, no_cache: false, sanitize: false, kind: :executable, debug_guards: nil)
  @kind = case kind
          when :executable, :static, :shared then kind
          else raise BuildError, "unknown build kind #{kind}; expected executable|static|shared"
          end
  @explicit_output_path = !output_path.nil?
  resolved_source = use_package_build_for?(path)
  if resolved_source
    @package_build = true
    manifest = resolved_source[:manifest]
    @source_path = manifest.source_path
    @project_root = manifest.root_dir
    @package_name = manifest.package_name
    @archive = archive
    @bundle = bundle || archive
    if manifest.package_kind == :library && @kind == :executable
      raise BuildError, "cannot build library package #{manifest.package_name} as an executable"
    end
    unless @source_path
      raise BuildError, "application package #{manifest.package_name} has no build entry; set build.entry or create src/main.mt"
    end
    @profile = normalize_profile(profile || manifest.profile || (debug ? :debug : :debug))
    @platform = normalize_platform(platform || manifest.platform || host_platform)
    @resolved_source_path = ModuleLoader.resolve_source_path(@source_path, platform: @platform, error_class: BuildError)
    validate_bundle_mode!
    @manifest_output_path = manifest.output_path
    if @bundle
      @bundle_root = File.expand_path(output_path || manifest.output_path || default_package_bundle_root)
      @output_path = File.join(@bundle_root, "#{@package_name}#{artifact_extension}")
    else
      @bundle_root = nil
      resolved_output = output_path || manifest.output_path || default_package_output_path
      @output_path = normalize_output_path(File.expand_path(resolved_output))
    end
    @assets_paths = manifest.assets_paths
    @html_template_path = manifest.html_template_path
  else
    @package_build = false
    @source_path = File.expand_path(path)
    @project_root = File.dirname(@source_path)
    @package_name = File.basename(@project_root).tr("-", "_")
    @archive = archive
    @bundle = bundle || archive
    @profile = normalize_profile(profile || (debug ? :debug : :debug))
    @platform = normalize_platform(platform || host_platform)
    @resolved_source_path = ModuleLoader.resolve_source_path(@source_path, platform: @platform, error_class: BuildError)
    validate_bundle_mode!
    @manifest_output_path = nil
    @bundle_root = nil
    @output_path = normalize_output_path(File.expand_path(output_path || default_source_output_path(@source_path)))
    @assets_paths = []
    @html_template_path = nil
  end
  @cc = resolve_compiler(cc)
  @keep_c_path = keep_c_path ? File.expand_path(keep_c_path) : nil
  @raw_bindings = raw_bindings
  @package_graph = package_graph
  @module_roots = (module_roots || @package_graph&.source_roots || MilkTea::ModuleRoots.roots_for_path(@source_path)).dup
  @frontend = frontend || RubyFrontend.new
  @no_cache = no_cache || sanitize
  @sanitize = sanitize
  @debug = debug
  @debug_guards = debug_guards
end

Class Method Details

.build(path, output_path: nil, cc: ENV.fetch("CC", "cc"), keep_c_path: nil, raw_bindings: nil, module_roots: nil, package_graph: nil, frontend: nil, debug: false, profile: nil, platform: nil, bundle: false, archive: false, no_cache: false, sanitize: false, kind: :executable, debug_guards: nil) ⇒ Object



73
74
75
76
# File 'lib/milk_tea/tooling/build.rb', line 73

def self.build(path, output_path: nil, cc: ENV.fetch("CC", "cc"), keep_c_path: nil, raw_bindings: nil, module_roots: nil, package_graph: nil, frontend: nil, debug: false, profile: nil, platform: nil, bundle: false, archive: false, no_cache: false, sanitize: false, kind: :executable, debug_guards: nil)
  raw_bindings ||= default_raw_bindings
  new(path, output_path:, cc:, keep_c_path:, raw_bindings:, module_roots:, package_graph:, frontend:, debug:, profile:, platform:, bundle:, archive:, no_cache:, sanitize:, kind:, debug_guards:).build
end

.clean(path, output_path: nil, profile: nil, platform: nil, bundle: false, archive: false) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/milk_tea/tooling/build.rb', line 78

def self.clean(path, output_path: nil, profile: nil, platform: nil, bundle: false, archive: false)
  new(
    path,
    output_path:,
    cc: ENV.fetch("CC", "cc"),
    keep_c_path: nil,
    raw_bindings: nil,
    module_roots: nil,
    debug: false,
    profile:,
    platform:,
    bundle:,
    archive:
  ).clean
end

.ensure_program_has_entrypoint!(program, ir_program) ⇒ Object

Raises:



654
655
656
657
658
659
660
661
662
663
# File 'lib/milk_tea/tooling/build.rb', line 654

def self.ensure_program_has_entrypoint!(program, ir_program)
  return if ir_program.functions.any?(&:entry_point)
  return if program.is_a?(IR::Program)

  if program.root_analysis.functions.key?("main")
    raise BuildError, "root main is not a valid executable entrypoint; expected `function main() -> int|void`, `function main(argc: int, argv: ptr[cstr]) -> int|void`, `function main(argc: int, argv: ptr[ptr[char]]) -> int|void`, or `function main(args: span[str]) -> int|void`"
  end

  raise BuildError, "no executable entrypoint found; define `main` with one of the supported executable signatures"
end

.frontend_build_artifacts(program, emit_line_directives: false, binary_path: nil, debug_guards: false) ⇒ Object



94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/milk_tea/tooling/build.rb', line 94

def self.frontend_build_artifacts(program, emit_line_directives: false, binary_path: nil, debug_guards: false)
  ir_program = program.is_a?(IR::Program) ? program : Lowering.lower(program)
  ensure_program_has_entrypoint!(program, ir_program)
  compiled_c = CBackend.emit(ir_program, emit_line_directives:, debug_guards:)
  saved_c = emit_line_directives ? nil : compiled_c

  {
    ir_program: ir_program,
    compiled_c: compiled_c,
    saved_c: saved_c,
    debug_map: binary_path ? DebugMap.from_ir(ir_program, binary_path:) : nil,
    modules: frontend_modules(program),
  }
end

Instance Method Details

#buildObject



232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/milk_tea/tooling/build.rb', line 232

def build
  Types::Registry.reset!
  ensure_compiler_available!
  ensure_supported_backend!

  return build_static_library if @kind == :static
  return build_shared_library if @kind == :shared

  if @frontend.is_a?(RubyFrontend) && !@no_cache
    build_cached
  else
    build_uncached
  end
end

#cleanObject



213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/milk_tea/tooling/build.rb', line 213

def clean
  target_path = clean_target_path
  if File.directory?(target_path)
    FileUtils.rm_rf(target_path)
  else
    clean_output_artifacts(target_path)
    clean_staged_runtime_assets(target_path)
    FileUtils.rm_f(DebugMap.sidecar_path_for(@output_path))
  end
  clean_bundle_archive
  clean_cache
  target_path
end

#clean_cacheObject



227
228
229
230
# File 'lib/milk_tea/tooling/build.rb', line 227

def clean_cache
  cache_dir = File.join(MilkTea.data_root.to_s, "tmp", "mtc-cache")
  FileUtils.rm_rf(cache_dir) if File.exist?(cache_dir)
end

#use_package_build_for?(path) ⇒ Boolean

Returns:

  • (Boolean)


197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/milk_tea/tooling/build.rb', line 197

def use_package_build_for?(path)
  manifest = PackageManifest.load(path)
  return nil unless manifest&.source_path

  manifest_source = File.expand_path(manifest.source_path, manifest.root_dir)
  given_source = File.expand_path(path)
  return nil unless manifest_source == given_source || File.directory?(path)

  { manifest: }
rescue PackageManifestError => e
  if PackageManifest.manifest_exists_for?(path)
    raise BuildError, e.message
  end
  nil
end