/
parallel_compiler.ex
348 lines (287 loc) · 11.4 KB
/
parallel_compiler.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
defmodule Kernel.ParallelCompiler do
@moduledoc """
A module responsible for compiling files in parallel.
"""
@doc """
Compiles the given files.
Those files are compiled in parallel and can automatically
detect dependencies between them. Once a dependency is found,
the current file stops being compiled until the dependency is
resolved.
If there is an error during compilation or if `warnings_as_errors`
is set to `true` and there is a warning, this function will fail
with an exception.
This function accepts the following options:
* `:each_file` - for each file compiled, invokes the callback passing the
file
* `:each_long_compilation` - for each file that takes more than a given
timeout (see the `:long_compilation_threshold` option) to compile, invoke
this callback passing the file as its argument
* `:long_compilation_threshold` - the timeout (in seconds) after the
`:each_long_compilation` callback is invoked; defaults to `10`
* `:each_module` - for each module compiled, invokes the callback passing
the file, module and the module bytecode
* `:each_warning` - for each warning, invokes the callback passing
the file, line number, and warning message
* `:dest` - the destination directory for the BEAM files. When using `files/2`,
this information is only used to properly annotate the BEAM files before
they are loaded into memory. If you want a file to actually be written to
`dest`, use `files_to_path/3` instead.
Returns the modules generated by each compiled file.
"""
def files(files, options \\ [])
def files(files, options) when is_list(options) do
spawn_compilers(files, nil, options)
end
@doc """
Compiles the given files to the given path.
Read `files/2` for more information.
"""
def files_to_path(files, path, options \\ [])
def files_to_path(files, path, options) when is_binary(path) and is_list(options) do
spawn_compilers(files, path, options)
end
defp spawn_compilers(files, path, options) do
true = Code.ensure_loaded?(Kernel.ErrorHandler)
compiler_pid = self()
:elixir_code_server.cast({:reset_warnings, compiler_pid})
schedulers = max(:erlang.system_info(:schedulers_online), 2)
result = spawn_compilers(%{
entries: files,
original: files,
output: path,
options: options,
waiting: [],
queued: [],
schedulers: schedulers,
result: [],
})
# In case --warning-as-errors is enabled and there was a warning,
# compilation status will be set to error.
case :elixir_code_server.call({:compilation_status, compiler_pid}) do
:ok ->
result
:error ->
IO.puts :stderr, "Compilation failed due to warnings while using the --warnings-as-errors option"
exit({:shutdown, 1})
end
end
# We already have n=schedulers currently running, don't spawn new ones
defp spawn_compilers(%{queued: queued, waiting: waiting, schedulers: schedulers} = state)
when length(queued) - length(waiting) >= schedulers do
wait_for_messages(state)
end
# Release waiting processes
defp spawn_compilers(%{entries: [{ref, found} | t], waiting: waiting} = state) do
waiting =
case List.keytake(waiting, ref, 2) do
{{_kind, pid, ^ref, _on, _defining}, waiting} ->
send pid, {ref, found}
waiting
nil ->
waiting
end
spawn_compilers(%{state | entries: t, waiting: waiting})
end
defp spawn_compilers(%{entries: [file | files], queued: queued, output: output, options: options} = state) do
parent = self()
{pid, ref} =
:erlang.spawn_monitor fn ->
# Set the elixir_compiler_pid used by our custom Kernel.ErrorHandler.
:erlang.put(:elixir_compiler_pid, parent)
:erlang.put(:elixir_compiler_file, file)
:erlang.process_flag(:error_handler, Kernel.ErrorHandler)
result =
try do
_ = if output do
:elixir_compiler.file_to_path(file, output)
else
:elixir_compiler.file(file, Keyword.get(options, :dest))
end
:ok
catch
kind, reason ->
{kind, reason, System.stacktrace}
end
send(parent, {:file_compiled, self(), file, result})
exit(:shutdown)
end
timeout = Keyword.get(options, :long_compilation_threshold, 10) * 1_000
timer_ref = Process.send_after(self(), {:timed_out, pid}, timeout)
new_queued = [{pid, ref, file, timer_ref} | queued]
spawn_compilers(%{state | entries: files, queued: new_queued})
end
# No more files, nothing waiting, queue is empty, we are done
defp spawn_compilers(%{entries: [], waiting: [], queued: [], result: result}) do
for {:module, mod} <- result, do: mod
end
# Queued x, waiting for x: POSSIBLE ERROR! Release processes so we get the failures
defp spawn_compilers(%{entries: [], waiting: waiting, queued: queued} = state) when length(waiting) == length(queued) do
entries = for {pid, _, _, _} <- queued,
entry = waiting_on_without_definition(waiting, pid),
{_, _, ref, on, _} = entry,
do: {on, {ref, :not_found}}
# Instead of releasing all files at once, we release them in groups
# based on the module they are waiting on. We pick the module being
# depended on with less edges, as it is the mostly likely source of
# error (for example, someone made a typo). This may not always be
# true though: for example, if there is a macro injecting code into
# multiple modules and such code becomes faulty, now multiple modules
# are waiting on the same module required by the faulty code. However,
# since we need to pick something to be first, the one with fewer edges
# sounds like a sane choice.
entries
|> Enum.group_by(&elem(&1, 0), &elem(&1, 1))
|> Enum.sort_by(&length(elem(&1, 1)))
|> case do
[{_on, refs} | _] -> spawn_compilers(%{state | entries: refs})
[] -> handle_deadlock(waiting, queued)
end
end
# No more files, but queue and waiting are not full or do not match
defp spawn_compilers(%{entries: []} = state) do
wait_for_messages(state)
end
defp waiting_on_without_definition(waiting, pid) do
{_, ^pid, _, on, _} = entry = List.keyfind(waiting, pid, 1)
if Enum.any?(waiting, fn {_, _, _, _, defining} -> on in defining end) do
nil
else
entry
end
end
# Wait for messages from child processes
defp wait_for_messages(state) do
%{entries: entries, options: options, waiting: waiting, queued: queued, result: result} = state
receive do
{:struct_available, module} ->
available = for {:struct, _, ref, waiting_module, _defining} <- waiting,
module == waiting_module,
do: {ref, :found}
spawn_compilers(%{state | entries: available ++ entries, result: [{:struct, module} | result]})
{:module_available, child, ref, file, module, binary} ->
if callback = Keyword.get(options, :each_module) do
callback.(file, module, binary)
end
# Release the module loader which is waiting for an ack
send child, {ref, :ack}
available = for {:module, _, ref, waiting_module, _defining} <- waiting,
module == waiting_module,
do: {ref, :found}
cancel_waiting_timer(queued, child)
spawn_compilers(%{state | entries: available ++ entries, result: [{:module, module} | result]})
{:waiting, kind, child, ref, on, defining} ->
# Oops, we already got it, do not put it on waiting.
# Alternatively, we're waiting on ourselves,
# send :found so that we can crash with a better error.
waiting =
if :lists.any(&match?({^kind, ^on}, &1), result) or on in defining do
send child, {ref, :found}
waiting
else
[{kind, child, ref, on, defining} | waiting]
end
spawn_compilers(%{state | waiting: waiting})
{:timed_out, child} ->
callback = Keyword.get(options, :each_long_compilation)
case List.keyfind(queued, child, 0) do
{^child, _, file, _} when not is_nil(callback) ->
callback.(file)
_ ->
:ok
end
spawn_compilers(state)
{:warning, file, line, message} ->
if callback = Keyword.get(options, :each_warning) do
callback.(file, line, message)
end
wait_for_messages(state)
{:file_compiled, child_pid, file, :ok} ->
discard_down(child_pid)
if callback = Keyword.get(options, :each_file) do
callback.(file)
end
cancel_waiting_timer(queued, child_pid)
# Sometimes we may have spurious entries in the waiting
# list because someone invoked try/rescue UndefinedFunctionError
new_entries = List.delete(entries, child_pid)
new_queued = List.keydelete(queued, child_pid, 0)
new_waiting = List.keydelete(waiting, child_pid, 1)
spawn_compilers(%{state | entries: new_entries, waiting: new_waiting, queued: new_queued})
{:file_compiled, child_pid, file, {kind, reason, stack}} ->
discard_down(child_pid)
print_error(file, kind, reason, stack)
terminate(queued)
{:DOWN, ref, :process, _pid, reason} ->
handle_down(queued, ref, reason)
wait_for_messages(state)
end
end
defp discard_down(pid) do
receive do
{:DOWN, _, :process, ^pid, _} -> :ok
end
end
defp handle_down(_queued, _ref, :normal) do
:ok
end
defp handle_down(queued, ref, reason) do
case List.keyfind(queued, ref, 1) do
{_child, ^ref, file, _timer_ref} ->
print_error(file, :exit, reason, [])
terminate(queued)
_ ->
:ok
end
end
defp handle_deadlock(waiting, queued) do
deadlock =
for {pid, _, file, _} <- queued do
{:current_stacktrace, stacktrace} = Process.info(pid, :current_stacktrace)
Process.exit(pid, :kill)
{_kind, ^pid, _, on, _} = List.keyfind(waiting, pid, 1)
error = CompileError.exception(description: "deadlocked waiting on module #{inspect on}",
file: nil, line: nil)
print_error(file, :error, error, stacktrace)
{file, on}
end
IO.puts """
Compilation failed because of a deadlock between files.
The following files depended on the following modules:
"""
max =
deadlock
|> Enum.map(& &1 |> elem(0) |> String.length)
|> Enum.max
for {file, mod} <- deadlock do
IO.puts [" ", String.pad_leading(file, max), " => " | inspect(mod)]
end
IO.puts ""
exit({:shutdown, 1})
end
defp terminate(queued) do
for {pid, _, _, _} <- queued do
Process.exit(pid, :kill)
end
exit({:shutdown, 1})
end
defp print_error(file, kind, reason, stack) do
IO.write ["\n== Compilation error in file #{Path.relative_to_cwd(file)} ==\n",
Kernel.CLI.format_error(kind, reason, stack)]
end
defp cancel_waiting_timer(queued, child_pid) do
case List.keyfind(queued, child_pid, 0) do
{^child_pid, _ref, _file, timer_ref} ->
Process.cancel_timer(timer_ref)
# Let's flush the message in case it arrived before we canceled the
# timeout.
receive do
{:timed_out, ^child_pid} -> :ok
after
0 -> :ok
end
nil ->
:ok
end
end
end