/
server.ex
389 lines (328 loc) · 11.5 KB
/
server.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
defmodule IEx.Server do
@moduledoc """
The IEx.Server.
The server responsibilities include:
* reading input from the group leader and writing to the group leader
* sending messages to the evaluator
* taking over the evaluator process when using `IEx.pry/0` or setting up breakpoints
"""
@doc false
defstruct parser_state: "",
counter: 1,
prefix: "iex",
on_eof: :stop_evaluator,
evaluator_options: [],
expand_fun: nil
@doc """
Starts a new IEx server session.
The accepted options are:
* `:prefix` - the IEx prefix
* `:env` - the `Macro.Env` used for the evaluator
* `:binding` - an initial set of variables for the evaluator
* `:on_eof` - if it should `:stop_evaluator` (default) or `:halt` the system
"""
@doc since: "1.8.0"
@spec run(keyword) :: :ok
def run(opts) when is_list(opts) do
IEx.Broker.register(self())
run_without_registration(init_state(opts), opts, nil)
end
## Private APIs
# Starts IEx to run directly from the Erlang shell.
#
# The server is spawned only after the callback is done.
#
# If there is any takeover during the callback execution
# we spawn a new server for it without waiting for its
# conclusion.
@doc false
@spec run_from_shell(keyword, {module, atom, [any]}) :: :ok
def run_from_shell(opts, {m, f, a}) do
opts[:register] && IEx.Broker.register(self())
Process.flag(:trap_exit, true)
{pid, ref} = spawn_monitor(m, f, a)
shell_loop(opts, pid, ref)
end
defp shell_loop(opts, pid, ref) do
receive do
{:take_over, take_pid, take_ref, take_location, take_whereami, take_opts} ->
if take_over?(take_pid, take_ref, take_location, take_whereami, take_opts, 1) do
run_without_registration(init_state(opts), take_opts, nil)
else
shell_loop(opts, pid, ref)
end
{:DOWN, ^ref, :process, ^pid, :normal} ->
run_without_registration(init_state(opts), opts, nil)
{:DOWN, ^ref, :process, ^pid, _reason} ->
:ok
end
end
# Since we want to register only once, this function is the
# reentrant point for starting a new shell (instead of run/run_from_shell).
defp run_without_registration(state, opts, input) do
Process.flag(:trap_exit, true)
Process.link(Process.group_leader())
IO.puts(
"Interactive Elixir (#{System.version()}) - press Ctrl+C to exit (type h() ENTER for help)"
)
evaluator = start_evaluator(state.counter, Keyword.merge(state.evaluator_options, opts))
loop(state, :ok, evaluator, Process.monitor(evaluator), input)
end
# Starts an evaluator using the provided options.
# Made public but undocumented for testing.
@doc false
def start_evaluator(counter, opts) do
args = [:ack, self(), Process.group_leader(), counter, opts]
evaluator = opts[:evaluator] || :proc_lib.start(IEx.Evaluator, :init, args)
Process.put(:evaluator, evaluator)
evaluator
end
## Helpers
defp stop_evaluator(evaluator, evaluator_ref) do
Process.delete(:evaluator)
Process.demonitor(evaluator_ref, [:flush])
send(evaluator, {:done, self(), false})
:ok
end
defp rerun(state, opts, evaluator, evaluator_ref, input) do
IO.puts("")
stop_evaluator(evaluator, evaluator_ref)
state = reset_state(state)
run_without_registration(state, opts, input)
end
defp loop(state, status, evaluator, evaluator_ref, input) do
:io.setopts(expand_fun: state.expand_fun)
input = input || io_get(prompt(status, state.prefix, state.counter))
wait_input(state, evaluator, evaluator_ref, input)
end
defp wait_input(state, evaluator, evaluator_ref, input) do
receive do
{:io_reply, ^input, code} when is_binary(code) ->
:io.setopts(expand_fun: fn _ -> {:yes, [], []} end)
send(evaluator, {:eval, self(), code, state.counter, state.parser_state})
wait_eval(state, evaluator, evaluator_ref)
{:io_reply, ^input, :eof} ->
case state.on_eof do
:halt -> System.halt(0)
:stop_evaluator -> stop_evaluator(evaluator, evaluator_ref)
end
# Triggered by pressing "i" as the job control switch
{:io_reply, ^input, {:error, :interrupted}} ->
io_error("** (EXIT) interrupted")
loop(%{state | parser_state: ""}, :ok, evaluator, evaluator_ref, nil)
# Unknown IO message
{:io_reply, ^input, msg} ->
io_error("** (EXIT) unknown IO message: #{inspect(msg)}")
loop(%{state | parser_state: ""}, :ok, evaluator, evaluator_ref, nil)
# Triggered when IO dies while waiting for input
{:DOWN, ^input, _, _, _} ->
stop_evaluator(evaluator, evaluator_ref)
msg ->
handle_take_over(msg, state, evaluator, evaluator_ref, input, fn state ->
wait_input(state, evaluator, evaluator_ref, input)
end)
end
end
defp wait_eval(state, evaluator, evaluator_ref) do
receive do
{:evaled, ^evaluator, status, parser_state} ->
counter = if(status == :ok, do: state.counter + 1, else: state.counter)
state = %{state | counter: counter, parser_state: parser_state}
loop(state, status, evaluator, evaluator_ref, nil)
msg ->
handle_take_over(msg, state, evaluator, evaluator_ref, nil, fn state ->
wait_eval(state, evaluator, evaluator_ref)
end)
end
end
defp wait_take_over(state, evaluator, evaluator_ref, input) do
receive do
msg ->
handle_take_over(msg, state, evaluator, evaluator_ref, input, fn state ->
wait_take_over(state, evaluator, evaluator_ref, input)
end)
end
end
# Take process.
#
# A take process may also happen if the evaluator dies,
# then a new evaluator is created to replace the dead one.
defp handle_take_over(
{:take_over, take_pid, take_ref, take_location, take_whereami, take_opts},
state,
evaluator,
evaluator_ref,
input,
callback
) do
cond do
evaluator == take_opts[:evaluator] ->
IO.puts(IEx.color(:eval_interrupt, "Break reached: #{take_location}#{take_whereami}"))
if take_over?(take_pid, take_ref, state.counter + 1, true) do
# Since we are in process, also bump the counter
state = reset_state(bump_counter(state))
loop(state, :ok, evaluator, evaluator_ref, input)
else
callback.(state)
end
take_over?(take_pid, take_ref, take_location, take_whereami, take_opts, state.counter) ->
rerun(state, take_opts, evaluator, evaluator_ref, input)
true ->
callback.(state)
end
end
# User did ^G while the evaluator was busy or stuck
defp handle_take_over(
{:EXIT, _pid, :interrupt},
state,
evaluator,
evaluator_ref,
input,
_callback
) do
io_error("** (EXIT) interrupted")
Process.exit(evaluator, :kill)
rerun(state, [], evaluator, evaluator_ref, input)
end
defp handle_take_over(
{:EXIT, pid, reason},
state,
evaluator,
evaluator_ref,
_input,
callback
) do
if pid == Process.group_leader() do
stop_evaluator(evaluator, evaluator_ref)
exit(reason)
else
callback.(state)
end
end
defp handle_take_over({:respawn, evaluator}, state, evaluator, evaluator_ref, input, _callback) do
rerun(bump_counter(state), [], evaluator, evaluator_ref, input)
end
defp handle_take_over(
{:continue, evaluator, next?},
state,
evaluator,
evaluator_ref,
input,
_callback
) do
send(evaluator, {:done, self(), next?})
wait_take_over(state, evaluator, evaluator_ref, input)
end
defp handle_take_over(
{:DOWN, evaluator_ref, :process, evaluator, :normal},
state,
evaluator,
evaluator_ref,
input,
_callback
) do
rerun(state, [], evaluator, evaluator_ref, input)
end
defp handle_take_over(
{:DOWN, evaluator_ref, :process, evaluator, reason},
state,
evaluator,
evaluator_ref,
input,
_callback
) do
try do
io_error(
"** (EXIT from #{inspect(evaluator)}) shell process exited with reason: " <>
Exception.format_exit(reason)
)
catch
type, detail ->
io_error("** (IEx.Error) #{type} when printing EXIT message: #{inspect(detail)}")
end
rerun(state, [], evaluator, evaluator_ref, input)
end
defp handle_take_over(_, state, _evaluator, _evaluator_ref, _input, callback) do
callback.(state)
end
defp take_over?(take_pid, take_ref, take_location, take_whereami, take_opts, counter) do
evaluator = take_opts[:evaluator]
message = "Request to pry #{inspect(evaluator)} at #{take_location}#{take_whereami}"
interrupt = IEx.color(:eval_interrupt, "#{message}\nAllow? [Yn] ")
take_over?(take_pid, take_ref, counter, yes?(IO.gets(:stdio, interrupt)))
end
defp take_over?(take_pid, take_ref, counter, response) when is_boolean(response) do
case IEx.Broker.respond(take_pid, take_ref, counter, response) do
:ok ->
true
{:error, :refused} ->
false
{:error, :already_accepted} ->
io_error("** session was already accepted elsewhere")
false
end
end
defp yes?(string) do
is_binary(string) and String.trim(string) in ["", "y", "Y", "yes", "YES", "Yes"]
end
## State
defp init_state(opts) do
prefix = Keyword.get(opts, :prefix, "iex")
on_eof = Keyword.get(opts, :on_eof, :stop_evaluator)
gl = Process.group_leader()
expand_fun =
if node(gl) != node() do
IEx.Autocomplete.remsh(node())
else
&IEx.Autocomplete.expand/1
end
%IEx.Server{
prefix: prefix,
on_eof: on_eof,
expand_fun: expand_fun,
evaluator_options: Keyword.take(opts, [:dot_iex_path])
}
end
# For the state, reset only reset the parser state.
# The counter will continue going up as the input process is shared.
# The opts can also set "dot_iex_path" and the "evaluator" itself,
# but those are not stored: they are temporary to whatever is rerunning.
# Once the rerunning session restarts, we keep the same evaluator_options
# and rollback to a new evaluator.
defp reset_state(state) do
%{state | parser_state: ""}
end
defp bump_counter(state) do
update_in(state.counter, &(&1 + 1))
end
## IO
defp io_get(prompt) do
gl = Process.group_leader()
ref = Process.monitor(gl)
send(gl, {:io_request, self(), ref, {:get_line, :unicode, prompt}})
ref
end
defp prompt(status, prefix, counter) do
{mode, prefix} =
if Node.alive?() do
{prompt_mode(status, :alive), default_prefix(status, prefix)}
else
{prompt_mode(status, :default), default_prefix(status, prefix)}
end
prompt =
apply(IEx.Config, mode, [])
|> String.replace("%counter", to_string(counter))
|> String.replace("%prefix", to_string(prefix))
|> String.replace("%node", to_string(node()))
[prompt, " "]
end
defp default_prefix(:incomplete, _prefix), do: "..."
defp default_prefix(_ok_or_error, prefix), do: prefix
defp prompt_mode(:incomplete, :default), do: :continuation_prompt
defp prompt_mode(:incomplete, :alive), do: :alive_continuation_prompt
defp prompt_mode(_ok_or_error, :default), do: :default_prompt
defp prompt_mode(_ok_or_error, :alive), do: :alive_prompt
defp io_error(result) do
IO.puts(:stdio, IEx.color(:eval_error, result))
end
end