Coverage Report

Created: 2025-08-28 06:26

/src/serenity/Userland/Libraries/LibShell/AST.cpp
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright (c) 2020, the SerenityOS developers.
3
 *
4
 * SPDX-License-Identifier: BSD-2-Clause
5
 */
6
7
#include "AST.h"
8
#include "Highlight.h"
9
#include "Shell.h"
10
#include <AK/Find.h>
11
#include <AK/MemoryStream.h>
12
#include <AK/ScopeGuard.h>
13
#include <AK/ScopedValueRollback.h>
14
#include <AK/String.h>
15
#include <AK/StringBuilder.h>
16
#include <LibCore/EventLoop.h>
17
#include <LibFileSystem/FileSystem.h>
18
#include <errno.h>
19
#include <fcntl.h>
20
#include <signal.h>
21
#include <unistd.h>
22
23
ErrorOr<void> AK::Formatter<Shell::AST::Command>::format(FormatBuilder& builder, Shell::AST::Command const& value)
24
0
{
25
0
    if (m_sign_mode != FormatBuilder::SignMode::Default)
26
0
        VERIFY_NOT_REACHED();
27
0
    if (m_alternative_form)
28
0
        VERIFY_NOT_REACHED();
29
0
    if (m_zero_pad)
30
0
        VERIFY_NOT_REACHED();
31
0
    if (m_mode != Mode::Default && m_mode != Mode::String)
32
0
        VERIFY_NOT_REACHED();
33
0
    if (m_width.has_value())
34
0
        VERIFY_NOT_REACHED();
35
0
    if (m_precision.has_value())
36
0
        VERIFY_NOT_REACHED();
37
38
0
    if (value.argv.is_empty()) {
39
0
        TRY(builder.put_literal("(ShellInternal)"sv));
40
0
    } else {
41
0
        bool first = true;
42
0
        for (auto& arg : value.argv) {
43
0
            if (!first)
44
0
                TRY(builder.put_literal(" "sv));
45
0
            first = false;
46
0
            TRY(builder.put_literal(arg));
47
0
        }
48
0
    }
49
50
0
    for (auto& redir : value.redirections) {
51
0
        TRY(builder.put_padding(' ', 1));
52
0
        if (redir->is_path_redirection()) {
53
0
            auto path_redir = static_cast<Shell::AST::PathRedirection const*>(redir.ptr());
54
0
            TRY(builder.put_i64(path_redir->fd));
55
0
            switch (path_redir->direction) {
56
0
            case Shell::AST::PathRedirection::Read:
57
0
                TRY(builder.put_literal("<"sv));
58
0
                break;
59
0
            case Shell::AST::PathRedirection::Write:
60
0
                TRY(builder.put_literal(">"sv));
61
0
                break;
62
0
            case Shell::AST::PathRedirection::WriteAppend:
63
0
                TRY(builder.put_literal(">>"sv));
64
0
                break;
65
0
            case Shell::AST::PathRedirection::ReadWrite:
66
0
                TRY(builder.put_literal("<>"sv));
67
0
                break;
68
0
            }
69
0
            TRY(builder.put_literal(path_redir->path));
70
0
        } else if (redir->is_fd_redirection()) {
71
0
            auto* fdredir = static_cast<Shell::AST::FdRedirection const*>(redir.ptr());
72
0
            TRY(builder.put_i64(fdredir->new_fd));
73
0
            TRY(builder.put_literal(">"sv));
74
0
            TRY(builder.put_i64(fdredir->old_fd));
75
0
        } else if (redir->is_close_redirection()) {
76
0
            auto close_redir = static_cast<Shell::AST::CloseRedirection const*>(redir.ptr());
77
0
            TRY(builder.put_i64(close_redir->fd));
78
0
            TRY(builder.put_literal(">&-"sv));
79
0
        } else {
80
0
            VERIFY_NOT_REACHED();
81
0
        }
82
0
    }
83
84
0
    if (!value.next_chain.is_empty()) {
85
0
        for (auto& command : value.next_chain) {
86
0
            switch (command.action) {
87
0
            case Shell::AST::NodeWithAction::And:
88
0
                TRY(builder.put_literal(" && "sv));
89
0
                break;
90
0
            case Shell::AST::NodeWithAction::Or:
91
0
                TRY(builder.put_literal(" || "sv));
92
0
                break;
93
0
            case Shell::AST::NodeWithAction::Sequence:
94
0
                TRY(builder.put_literal("; "sv));
95
0
                break;
96
0
            }
97
98
0
            TRY(builder.put_literal("("sv));
99
0
            TRY(builder.put_literal(command.node->class_name()));
100
0
            TRY(builder.put_literal("...)"sv));
101
0
        }
102
0
    }
103
0
    if (!value.should_wait)
104
0
        TRY(builder.put_literal("&"sv));
105
0
    return {};
106
0
}
107
108
namespace Shell::AST {
109
110
template<typename... Args>
111
static inline void print_indented(int indent, CheckedFormatString<Args...> format, Args&&... args)
112
0
{
113
0
    auto str = ByteString::formatted(format.view(), forward<Args>(args)...);
114
0
    dbgln("{: >{}}", str, str.length() + indent * 2);
115
0
}
Unexecuted instantiation: AST.cpp:void Shell::AST::print_indented<unsigned long const&>(int, AK::Format::Detail::CheckedFormatString<AK::Detail::__IdentityType<unsigned long const&>::Type>, unsigned long const&)
Unexecuted instantiation: AST.cpp:void Shell::AST::print_indented<AK::ByteString const&>(int, AK::Format::Detail::CheckedFormatString<AK::Detail::__IdentityType<AK::ByteString const&>::Type>, AK::ByteString const&)
Unexecuted instantiation: AST.cpp:void Shell::AST::print_indented<AK::StringView, unsigned long const&, unsigned long const&, unsigned long const&, unsigned long const&, unsigned long const&, unsigned long const&>(int, AK::Format::Detail::CheckedFormatString<AK::Detail::__IdentityType<AK::StringView>::Type, AK::Detail::__IdentityType<unsigned long const&>::Type, AK::Detail::__IdentityType<unsigned long const&>::Type, AK::Detail::__IdentityType<unsigned long const&>::Type, AK::Detail::__IdentityType<unsigned long const&>::Type, AK::Detail::__IdentityType<unsigned long const&>::Type, AK::Detail::__IdentityType<unsigned long const&>::Type>, AK::StringView&&, unsigned long const&, unsigned long const&, unsigned long const&, unsigned long const&, unsigned long const&, unsigned long const&)
Unexecuted instantiation: AST.cpp:void Shell::AST::print_indented<AK::String const&>(int, AK::Format::Detail::CheckedFormatString<AK::Detail::__IdentityType<AK::String const&>::Type>, AK::String const&)
Unexecuted instantiation: AST.cpp:void Shell::AST::print_indented<>(int, AK::Format::Detail::CheckedFormatString<>)
Unexecuted instantiation: AST.cpp:void Shell::AST::print_indented<int const&>(int, AK::Format::Detail::CheckedFormatString<AK::Detail::__IdentityType<int const&>::Type>, int const&)
Unexecuted instantiation: AST.cpp:void Shell::AST::print_indented<Shell::AST::Command const&>(int, AK::Format::Detail::CheckedFormatString<AK::Detail::__IdentityType<Shell::AST::Command const&>::Type>, Shell::AST::Command const&)
Unexecuted instantiation: AST.cpp:void Shell::AST::print_indented<AK::StringView>(int, AK::Format::Detail::CheckedFormatString<AK::Detail::__IdentityType<AK::StringView>::Type>, AK::StringView&&)
Unexecuted instantiation: AST.cpp:void Shell::AST::print_indented<int const&, int const&>(int, AK::Format::Detail::CheckedFormatString<AK::Detail::__IdentityType<int const&>::Type, AK::Detail::__IdentityType<int const&>::Type>, int const&, int const&)
Unexecuted instantiation: AST.cpp:void Shell::AST::print_indented<bool const&>(int, AK::Format::Detail::CheckedFormatString<AK::Detail::__IdentityType<bool const&>::Type>, bool const&)
Unexecuted instantiation: AST.cpp:void Shell::AST::print_indented<unsigned long const&, AK::String const&>(int, AK::Format::Detail::CheckedFormatString<AK::Detail::__IdentityType<unsigned long const&>::Type, AK::Detail::__IdentityType<AK::String const&>::Type>, unsigned long const&, AK::String const&)
Unexecuted instantiation: AST.cpp:void Shell::AST::print_indented<char const&>(int, AK::Format::Detail::CheckedFormatString<AK::Detail::__IdentityType<char const&>::Type>, char const&)
116
117
static inline Optional<Position> merge_positions(Optional<Position> const& left, Optional<Position> const& right)
118
0
{
119
0
    if (!left.has_value())
120
0
        return right;
121
122
0
    if (!right.has_value())
123
0
        return left;
124
125
0
    return Position {
126
0
        .start_offset = left->start_offset,
127
0
        .end_offset = right->end_offset,
128
0
        .start_line = left->start_line,
129
0
        .end_line = right->end_line,
130
0
    };
131
0
}
132
133
static inline Vector<Command> join_commands(Vector<Command> left, Vector<Command> right)
134
0
{
135
0
    Command command;
136
137
0
    auto last_in_left = left.take_last();
138
0
    auto first_in_right = right.take_first();
139
140
0
    command.argv.extend(last_in_left.argv);
141
0
    command.argv.extend(first_in_right.argv);
142
143
0
    command.redirections.extend(last_in_left.redirections);
144
0
    command.redirections.extend(first_in_right.redirections);
145
146
0
    command.should_wait = first_in_right.should_wait && last_in_left.should_wait;
147
0
    command.is_pipe_source = first_in_right.is_pipe_source;
148
0
    command.should_notify_if_in_background = first_in_right.should_notify_if_in_background || last_in_left.should_notify_if_in_background;
149
150
0
    command.position = merge_positions(last_in_left.position, first_in_right.position);
151
152
0
    Vector<Command> commands;
153
0
    commands.extend(left);
154
0
    commands.append(command);
155
0
    commands.extend(right);
156
157
0
    return commands;
158
0
}
159
160
static ErrorOr<String> resolve_slices(RefPtr<Shell> shell, String&& input_value, Vector<NonnullRefPtr<Slice>> slices)
161
0
{
162
0
    if (slices.is_empty())
163
0
        return move(input_value);
164
165
0
    for (auto& slice : slices) {
166
0
        auto value = TRY(slice->run(shell));
167
0
        if (shell && shell->has_any_error())
168
0
            break;
169
170
0
        if (!value) {
171
0
            shell->raise_error(Shell::ShellError::InvalidSliceContentsError, "Invalid slice contents", slice->position());
172
0
            return move(input_value);
173
0
        }
174
175
0
        auto index_values = TRY(value->resolve_as_list(shell));
176
0
        Vector<size_t> indices;
177
0
        indices.ensure_capacity(index_values.size());
178
179
0
        size_t i = 0;
180
0
        for (auto& value : index_values) {
181
0
            auto maybe_index = value.bytes_as_string_view().to_number<int>();
182
0
            if (!maybe_index.has_value()) {
183
0
                shell->raise_error(Shell::ShellError::InvalidSliceContentsError, ByteString::formatted("Invalid value in slice index {}: {} (expected a number)", i, value), slice->position());
184
0
                return move(input_value);
185
0
            }
186
0
            ++i;
187
188
0
            auto index = maybe_index.value();
189
0
            auto original_index = index;
190
0
            if (index < 0)
191
0
                index += input_value.bytes_as_string_view().length();
192
193
0
            if (index < 0 || (size_t)index >= input_value.bytes_as_string_view().length()) {
194
0
                shell->raise_error(Shell::ShellError::InvalidSliceContentsError, ByteString::formatted("Slice index {} (evaluated as {}) out of value bounds [0-{})", index, original_index, input_value.bytes_as_string_view().length()), slice->position());
195
0
                return move(input_value);
196
0
            }
197
0
            indices.unchecked_append(index);
198
0
        }
199
200
0
        StringBuilder builder { indices.size() };
201
0
        for (auto& index : indices)
202
0
            builder.append(input_value.bytes_as_string_view()[index]);
203
204
0
        input_value = TRY(builder.to_string());
205
0
    }
206
207
0
    return move(input_value);
208
0
}
209
210
static ErrorOr<Vector<String>> resolve_slices(RefPtr<Shell> shell, Vector<String>&& values, Vector<NonnullRefPtr<Slice>> slices)
211
0
{
212
0
    if (slices.is_empty())
213
0
        return move(values);
214
215
0
    for (auto& slice : slices) {
216
0
        auto value = TRY(slice->run(shell));
217
0
        if (shell && shell->has_any_error())
218
0
            break;
219
220
0
        if (!value) {
221
0
            shell->raise_error(Shell::ShellError::InvalidSliceContentsError, "Invalid slice contents", slice->position());
222
0
            return move(values);
223
0
        }
224
225
0
        auto index_values = TRY(value->resolve_as_list(shell));
226
0
        Vector<size_t> indices;
227
0
        indices.ensure_capacity(index_values.size());
228
229
0
        size_t i = 0;
230
0
        for (auto& value : index_values) {
231
0
            auto maybe_index = value.to_number<int>();
232
0
            if (!maybe_index.has_value()) {
233
0
                shell->raise_error(Shell::ShellError::InvalidSliceContentsError, ByteString::formatted("Invalid value in slice index {}: {} (expected a number)", i, value), slice->position());
234
0
                return move(values);
235
0
            }
236
0
            ++i;
237
238
0
            auto index = maybe_index.value();
239
0
            auto original_index = index;
240
0
            if (index < 0)
241
0
                index += values.size();
242
243
0
            if (index < 0 || (size_t)index >= values.size()) {
244
0
                shell->raise_error(Shell::ShellError::InvalidSliceContentsError, ByteString::formatted("Slice index {} (evaluated as {}) out of value bounds [0-{})", index, original_index, values.size()), slice->position());
245
0
                return move(values);
246
0
            }
247
0
            indices.unchecked_append(index);
248
0
        }
249
250
0
        Vector<String> result;
251
0
        result.ensure_capacity(indices.size());
252
0
        for (auto& index : indices)
253
0
            result.unchecked_append(values[index]);
254
255
0
        values = move(result);
256
0
    }
257
258
0
    return move(values);
259
0
}
260
261
void Node::clear_syntax_error()
262
568
{
263
568
    m_syntax_error_node->clear_syntax_error();
264
568
}
265
266
void Node::set_is_syntax_error(SyntaxError& error_node)
267
4.32M
{
268
4.32M
    if (!m_syntax_error_node) {
269
4.12M
        m_syntax_error_node = error_node;
270
4.12M
    } else {
271
198k
        m_syntax_error_node->set_is_syntax_error(error_node);
272
198k
    }
273
4.32M
}
274
275
bool Node::is_syntax_error() const
276
25.7M
{
277
25.7M
    return m_syntax_error_node && m_syntax_error_node->is_syntax_error();
278
25.7M
}
279
280
ErrorOr<void> Node::for_each_entry(RefPtr<Shell> shell, Function<ErrorOr<IterationDecision>(NonnullRefPtr<Value>)> callback)
281
0
{
282
0
    auto value = TRY(TRY(run(shell))->resolve_without_cast(shell));
283
0
    if (shell && shell->has_any_error())
284
0
        return {};
285
286
0
    if (value->is_job()) {
287
0
        TRY(callback(value));
288
0
        return {};
289
0
    }
290
291
0
    if (value->is_list_without_resolution()) {
292
0
        auto list = TRY(value->resolve_without_cast(shell));
293
0
        for (auto& element : static_cast<ListValue*>(list.ptr())->values()) {
294
0
            if (TRY(callback(element)) == IterationDecision::Break)
295
0
                break;
296
0
        }
297
0
        return {};
298
0
    }
299
300
0
    auto list = TRY(value->resolve_as_list(shell));
301
0
    for (auto& element : list) {
302
0
        if (TRY(callback(make_ref_counted<StringValue>(move(element)))) == IterationDecision::Break)
303
0
            break;
304
0
    }
305
306
0
    return {};
307
0
}
308
309
ErrorOr<Vector<Command>> Node::to_lazy_evaluated_commands(RefPtr<Shell> shell)
310
0
{
311
0
    if (would_execute()) {
312
        // Wrap the node in a "should immediately execute next" command.
313
0
        return Vector {
314
0
            Command { {}, {}, true, false, true, true, {}, { NodeWithAction(*this, NodeWithAction::Sequence) }, position() }
315
0
        };
316
0
    }
317
318
0
    return TRY(TRY(run(shell))->resolve_as_commands(shell));
319
0
}
320
321
ErrorOr<void> Node::dump(int level) const
322
0
{
323
0
    print_indented(level,
324
0
        "{} at {}:{} (from {}.{} to {}.{})",
325
0
        class_name(),
326
0
        m_position.start_offset,
327
0
        m_position.end_offset,
328
0
        m_position.start_line.line_number,
329
0
        m_position.start_line.line_column,
330
0
        m_position.end_line.line_number,
331
0
        m_position.end_line.line_column);
332
333
0
    return {};
334
0
}
335
336
Node::Node(Position position)
337
31.1M
    : m_position(position)
338
31.1M
{
339
31.1M
}
340
341
ErrorOr<Vector<Line::CompletionSuggestion>> Node::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result) const
342
0
{
343
0
    auto matching_node = hit_test_result.matching_node;
344
0
    if (matching_node) {
345
0
        auto kind = matching_node->kind();
346
0
        StringLiteral::EnclosureType enclosure_type = StringLiteral::EnclosureType::None;
347
0
        if (kind == Kind::StringLiteral)
348
0
            enclosure_type = static_cast<StringLiteral const*>(matching_node.ptr())->enclosure_type();
349
350
0
        auto set_results_trivia = [enclosure_type](Vector<Line::CompletionSuggestion>&& suggestions) {
351
0
            if (enclosure_type != StringLiteral::EnclosureType::None) {
352
0
                for (auto& entry : suggestions)
353
0
                    entry.trailing_trivia = String::from_code_point(static_cast<u32>(enclosure_type == StringLiteral::EnclosureType::SingleQuotes ? '\'' : '"'));
354
0
            }
355
0
            return suggestions;
356
0
        };
357
0
        if (kind == Kind::BarewordLiteral || kind == Kind::StringLiteral) {
358
0
            Shell::EscapeMode escape_mode;
359
0
            StringView text;
360
0
            size_t corrected_offset;
361
0
            if (kind == Kind::BarewordLiteral) {
362
0
                auto* node = static_cast<BarewordLiteral const*>(matching_node.ptr());
363
0
                text = node->text();
364
0
                escape_mode = Shell::EscapeMode::Bareword;
365
0
                corrected_offset = find_offset_into_node(text, offset - matching_node->position().start_offset, escape_mode);
366
0
            } else {
367
0
                auto* node = static_cast<StringLiteral const*>(matching_node.ptr());
368
0
                text = node->text();
369
0
                escape_mode = enclosure_type == StringLiteral::EnclosureType::SingleQuotes ? Shell::EscapeMode::SingleQuotedString : Shell::EscapeMode::DoubleQuotedString;
370
0
                corrected_offset = find_offset_into_node(text, offset - matching_node->position().start_offset + 1, escape_mode);
371
0
            }
372
373
0
            if (corrected_offset > text.length())
374
0
                return Vector<Line::CompletionSuggestion> {};
375
376
            // If the literal isn't an option, treat it as a path.
377
0
            if (!(text.starts_with('-') || text == "--" || text == "-"))
378
0
                return set_results_trivia(shell.complete_path(""sv, text, corrected_offset, Shell::ExecutableOnly::No, hit_test_result.closest_command_node.ptr(), hit_test_result.matching_node, escape_mode));
379
380
            // If the literal is an option, we have to know the program name
381
            // should we have no way to get that, bail early.
382
383
0
            if (!hit_test_result.closest_command_node)
384
0
                return Vector<Line::CompletionSuggestion> {};
385
386
0
            auto program_name_node = hit_test_result.closest_command_node->leftmost_trivial_literal();
387
0
            if (!program_name_node)
388
0
                return Vector<Line::CompletionSuggestion> {};
389
390
0
            String program_name;
391
0
            if (program_name_node->is_bareword())
392
0
                program_name = static_cast<BarewordLiteral const*>(program_name_node.ptr())->text();
393
0
            else
394
0
                program_name = static_cast<StringLiteral const*>(program_name_node.ptr())->text();
395
396
0
            return set_results_trivia(shell.complete_option(program_name, text, corrected_offset, hit_test_result.closest_command_node.ptr(), hit_test_result.matching_node));
397
0
        }
398
0
        return Vector<Line::CompletionSuggestion> {};
399
0
    }
400
0
    auto result = hit_test_position(offset);
401
0
    if (!result.matching_node)
402
0
        return shell.complete_path(""sv, ""sv, 0, Shell::ExecutableOnly::No, result.closest_command_node.ptr(), nullptr, Shell::EscapeMode::Bareword);
403
404
0
    auto node = result.matching_node;
405
0
    if (node->is_bareword() || node != result.closest_node_with_semantic_meaning)
406
0
        node = result.closest_node_with_semantic_meaning;
407
408
0
    if (!node)
409
0
        return Vector<Line::CompletionSuggestion> {};
410
411
0
    return node->complete_for_editor(shell, offset, result);
412
0
}
413
414
ErrorOr<Vector<Line::CompletionSuggestion>> Node::complete_for_editor(Shell& shell, size_t offset)
415
0
{
416
0
    return Node::complete_for_editor(shell, offset, { nullptr, nullptr, nullptr });
417
0
}
418
419
ErrorOr<void> And::dump(int level) const
420
0
{
421
0
    TRY(Node::dump(level));
422
0
    TRY(m_left->dump(level + 1));
423
0
    TRY(m_right->dump(level + 1));
424
0
    return {};
425
0
}
426
427
ErrorOr<RefPtr<Value>> And::run(RefPtr<Shell> shell)
428
0
{
429
0
    auto commands = TRY(m_left->to_lazy_evaluated_commands(shell));
430
0
    if (shell && shell->has_any_error())
431
0
        return make_ref_counted<ListValue>({});
432
433
0
    commands.last().next_chain.append(NodeWithAction { *m_right, NodeWithAction::And });
434
0
    return make_ref_counted<CommandSequenceValue>(move(commands));
435
0
}
436
437
ErrorOr<void> And::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
438
0
{
439
0
    metadata.is_first_in_list = true;
440
0
    TRY(m_left->highlight_in_editor(editor, shell, metadata));
441
0
    TRY(m_right->highlight_in_editor(editor, shell, metadata));
442
0
    return {};
443
0
}
444
445
HitTestResult And::hit_test_position(size_t offset) const
446
0
{
447
0
    auto result = m_left->hit_test_position(offset);
448
0
    if (result.matching_node) {
449
0
        if (!result.closest_command_node)
450
0
            result.closest_command_node = m_right;
451
0
        return result;
452
0
    }
453
454
0
    result = m_right->hit_test_position(offset);
455
0
    if (!result.closest_command_node)
456
0
        result.closest_command_node = m_right;
457
0
    return result;
458
0
}
459
460
And::And(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right, Position and_position)
461
44.6k
    : Node(move(position))
462
44.6k
    , m_left(move(left))
463
44.6k
    , m_right(move(right))
464
44.6k
    , m_and_position(and_position)
465
44.6k
{
466
44.6k
    if (m_left->is_syntax_error())
467
31.3k
        set_is_syntax_error(m_left->syntax_error_node());
468
13.3k
    else if (m_right->is_syntax_error())
469
12.2k
        set_is_syntax_error(m_right->syntax_error_node());
470
44.6k
}
471
472
ErrorOr<void> ListConcatenate::dump(int level) const
473
0
{
474
0
    TRY(Node::dump(level));
475
0
    for (auto& element : m_list)
476
0
        TRY(element->dump(level + 1));
477
478
0
    return {};
479
0
}
480
481
ErrorOr<RefPtr<Value>> ListConcatenate::run(RefPtr<Shell> shell)
482
0
{
483
0
    RefPtr<Value> result = nullptr;
484
485
0
    for (auto& element : m_list) {
486
0
        if (shell && shell->has_any_error())
487
0
            break;
488
0
        if (!result) {
489
0
            result = make_ref_counted<ListValue>({ TRY(TRY(element->run(shell))->resolve_without_cast(shell)) });
490
0
            continue;
491
0
        }
492
0
        auto element_value = TRY(TRY(element->run(shell))->resolve_without_cast(shell));
493
0
        if (shell && shell->has_any_error())
494
0
            break;
495
496
0
        if (result->is_command() || element_value->is_command()) {
497
0
            auto joined_commands = join_commands(
498
0
                TRY(result->resolve_as_commands(shell)),
499
0
                TRY(element_value->resolve_as_commands(shell)));
500
501
0
            if (joined_commands.size() == 1) {
502
0
                auto& command = joined_commands[0];
503
0
                command.position = position();
504
0
                result = make_ref_counted<CommandValue>(command);
505
0
            } else {
506
0
                result = make_ref_counted<CommandSequenceValue>(move(joined_commands));
507
0
            }
508
0
        } else {
509
0
            Vector<NonnullRefPtr<Value>> values;
510
511
0
            if (result->is_list_without_resolution()) {
512
0
                values.extend(static_cast<ListValue*>(result.ptr())->values());
513
0
            } else {
514
0
                for (auto& result : TRY(result->resolve_as_list(shell)))
515
0
                    values.append(make_ref_counted<StringValue>(result));
516
0
            }
517
518
0
            values.append(element_value);
519
520
0
            result = make_ref_counted<ListValue>(move(values));
521
0
        }
522
0
    }
523
0
    if (!result)
524
0
        return make_ref_counted<ListValue>({});
525
526
0
    return result;
527
0
}
528
529
ErrorOr<void> ListConcatenate::for_each_entry(RefPtr<Shell> shell, Function<ErrorOr<IterationDecision>(NonnullRefPtr<Value>)> callback)
530
0
{
531
0
    for (auto& entry : m_list) {
532
0
        auto value = TRY(entry->run(shell));
533
0
        if (shell && shell->has_any_error())
534
0
            break;
535
0
        if (!value)
536
0
            continue;
537
0
        if (TRY(callback(value.release_nonnull())) == IterationDecision::Break)
538
0
            break;
539
0
    }
540
541
0
    return {};
542
0
}
543
544
ErrorOr<void> ListConcatenate::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
545
0
{
546
0
    auto first = metadata.is_first_in_list;
547
0
    metadata.is_first_in_list = false;
548
549
0
    metadata.is_first_in_list = first;
550
0
    for (auto& element : m_list) {
551
0
        TRY(element->highlight_in_editor(editor, shell, metadata));
552
0
        metadata.is_first_in_list = false;
553
0
    }
554
555
0
    return {};
556
0
}
557
558
HitTestResult ListConcatenate::hit_test_position(size_t offset) const
559
0
{
560
0
    bool first = true;
561
0
    for (auto& element : m_list) {
562
0
        auto result = element->hit_test_position(offset);
563
0
        if (!result.closest_node_with_semantic_meaning && !first)
564
0
            result.closest_node_with_semantic_meaning = this;
565
0
        if (result.matching_node)
566
0
            return result;
567
0
        first = false;
568
0
    }
569
570
0
    return {};
571
0
}
572
573
RefPtr<Node const> ListConcatenate::leftmost_trivial_literal() const
574
0
{
575
0
    if (m_list.is_empty())
576
0
        return nullptr;
577
578
0
    return m_list.first()->leftmost_trivial_literal();
579
0
}
580
581
ListConcatenate::ListConcatenate(Position position, Vector<NonnullRefPtr<Node>> list)
582
3.79M
    : Node(move(position))
583
3.79M
    , m_list(move(list))
584
3.79M
{
585
5.20M
    for (auto& element : m_list) {
586
5.20M
        if (element->is_syntax_error()) {
587
154k
            set_is_syntax_error(element->syntax_error_node());
588
154k
            break;
589
154k
        }
590
5.20M
    }
591
3.79M
}
592
593
ErrorOr<void> Background::dump(int level) const
594
0
{
595
0
    TRY(Node::dump(level));
596
0
    TRY(m_command->dump(level + 1));
597
0
    return {};
598
0
}
599
600
ErrorOr<RefPtr<Value>> Background::run(RefPtr<Shell> shell)
601
0
{
602
0
    auto commands = TRY(m_command->to_lazy_evaluated_commands(shell));
603
0
    for (auto& command : commands)
604
0
        command.should_wait = false;
605
606
0
    return make_ref_counted<CommandSequenceValue>(move(commands));
607
0
}
608
609
ErrorOr<void> Background::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
610
0
{
611
0
    return m_command->highlight_in_editor(editor, shell, metadata);
612
0
}
613
614
HitTestResult Background::hit_test_position(size_t offset) const
615
0
{
616
0
    return m_command->hit_test_position(offset);
617
0
}
618
619
Background::Background(Position position, NonnullRefPtr<Node> command)
620
201k
    : Node(move(position))
621
201k
    , m_command(move(command))
622
201k
{
623
201k
    if (m_command->is_syntax_error())
624
96.6k
        set_is_syntax_error(m_command->syntax_error_node());
625
201k
}
626
627
ErrorOr<void> BarewordLiteral::dump(int level) const
628
0
{
629
0
    TRY(Node::dump(level));
630
0
    print_indented(level + 1, "{}", m_text);
631
0
    return {};
632
0
}
633
634
ErrorOr<RefPtr<Value>> BarewordLiteral::run(RefPtr<Shell>)
635
0
{
636
0
    return make_ref_counted<StringValue>(m_text);
637
0
}
638
639
ErrorOr<void> BarewordLiteral::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
640
0
{
641
0
    if (metadata.is_first_in_list) {
642
0
        auto posibly_runnable = shell.runnable_path_for(m_text);
643
0
        if (posibly_runnable.has_value()) {
644
0
            Line::Style style = Line::Style::Bold;
645
646
0
            auto runnable = posibly_runnable.release_value();
647
648
#if defined(AK_OS_SERENITY)
649
            if (runnable.kind == Shell::RunnablePath::Kind::Executable || runnable.kind == Shell::RunnablePath::Kind::Alias)
650
                style = highlight_runnable(shell, runnable).value_or(Line::Style::Bold);
651
#endif
652
653
0
            editor.stylize({ m_position.start_offset, m_position.end_offset }, style);
654
0
        } else if (auto suggestions = shell.complete_program_name(m_text, m_text.bytes().size()); !suggestions.is_empty()) {
655
0
            editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
656
0
        } else {
657
0
            editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Red) });
658
0
        }
659
660
0
        return {};
661
0
    }
662
663
0
    if (m_text.starts_with('-')) {
664
0
        if (m_text == "--"sv) {
665
0
            editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Green) });
666
0
            return {};
667
0
        }
668
0
        if (m_text == "-"sv)
669
0
            return {};
670
671
0
        if (m_text.starts_with_bytes("--"sv)) {
672
0
            auto index = m_text.find_byte_offset('=').value_or(m_text.bytes_as_string_view().length() - 1) + 1;
673
0
            editor.stylize({ m_position.start_offset, m_position.start_offset + index }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan) });
674
0
        } else {
675
0
            editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan) });
676
0
        }
677
0
    }
678
679
0
    if (FileSystem::exists(m_text)) {
680
0
        TRY(highlight_filesystem_path(m_text, editor, shell, m_position.start_offset, m_position.end_offset));
681
0
    }
682
683
0
    return {};
684
0
}
685
686
BarewordLiteral::BarewordLiteral(Position position, String text)
687
6.08M
    : Node(move(position))
688
6.08M
    , m_text(move(text))
689
6.08M
{
690
6.08M
}
691
692
ErrorOr<void> BraceExpansion::dump(int level) const
693
0
{
694
0
    TRY(Node::dump(level));
695
0
    for (auto& entry : m_entries)
696
0
        TRY(entry->dump(level + 1));
697
0
    return {};
698
0
}
699
700
ErrorOr<RefPtr<Value>> BraceExpansion::run(RefPtr<Shell> shell)
701
0
{
702
0
    Vector<NonnullRefPtr<Value>> values;
703
0
    for (auto& entry : m_entries) {
704
0
        if (shell && shell->has_any_error())
705
0
            break;
706
0
        auto value = TRY(entry->run(shell));
707
0
        if (value)
708
0
            values.append(value.release_nonnull());
709
0
    }
710
711
0
    return make_ref_counted<ListValue>(move(values));
712
0
}
713
714
HitTestResult BraceExpansion::hit_test_position(size_t offset) const
715
0
{
716
0
    for (auto& entry : m_entries) {
717
0
        auto result = entry->hit_test_position(offset);
718
0
        if (result.matching_node) {
719
0
            if (!result.closest_command_node)
720
0
                result.closest_command_node = entry;
721
0
            return result;
722
0
        }
723
0
    }
724
725
0
    return {};
726
0
}
727
728
ErrorOr<void> BraceExpansion::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
729
0
{
730
0
    for (auto& entry : m_entries) {
731
0
        TRY(entry->highlight_in_editor(editor, shell, metadata));
732
0
        metadata.is_first_in_list = false;
733
0
    }
734
735
0
    return {};
736
0
}
737
738
BraceExpansion::BraceExpansion(Position position, Vector<NonnullRefPtr<Node>> entries)
739
90.7k
    : Node(move(position))
740
90.7k
    , m_entries(move(entries))
741
90.7k
{
742
2.63M
    for (auto& entry : m_entries) {
743
2.63M
        if (entry->is_syntax_error()) {
744
86.7k
            set_is_syntax_error(entry->syntax_error_node());
745
86.7k
            break;
746
86.7k
        }
747
2.63M
    }
748
90.7k
}
749
750
ErrorOr<void> CastToCommand::dump(int level) const
751
0
{
752
0
    TRY(Node::dump(level));
753
0
    TRY(m_inner->dump(level + 1));
754
0
    return {};
755
0
}
756
757
ErrorOr<RefPtr<Value>> CastToCommand::run(RefPtr<Shell> shell)
758
0
{
759
0
    if (m_inner->is_command())
760
0
        return m_inner->run(shell);
761
762
0
    auto value = TRY(TRY(m_inner->run(shell))->resolve_without_cast(shell));
763
0
    if (shell && shell->has_any_error())
764
0
        return make_ref_counted<ListValue>({});
765
766
0
    if (value->is_command())
767
0
        return value;
768
769
0
    auto argv = TRY(value->resolve_as_list(shell));
770
0
    return make_ref_counted<CommandValue>(move(argv), position());
771
0
}
772
773
ErrorOr<void> CastToCommand::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
774
0
{
775
0
    return m_inner->highlight_in_editor(editor, shell, metadata);
776
0
}
777
778
HitTestResult CastToCommand::hit_test_position(size_t offset) const
779
0
{
780
0
    auto result = m_inner->hit_test_position(offset);
781
0
    if (!result.closest_node_with_semantic_meaning)
782
0
        result.closest_node_with_semantic_meaning = this;
783
0
    if (!result.closest_command_node && position().contains(offset))
784
0
        result.closest_command_node = this;
785
0
    return result;
786
0
}
787
788
ErrorOr<Vector<Line::CompletionSuggestion>> CastToCommand::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result) const
789
0
{
790
0
    auto matching_node = hit_test_result.matching_node;
791
0
    if (!matching_node || !matching_node->is_bareword())
792
0
        return Vector<Line::CompletionSuggestion> {};
793
794
0
    auto corrected_offset = offset - matching_node->position().start_offset;
795
0
    auto* node = static_cast<BarewordLiteral const*>(matching_node.ptr());
796
797
0
    if (corrected_offset > node->text().bytes_as_string_view().length())
798
0
        return Vector<Line::CompletionSuggestion> {};
799
800
0
    return shell.complete_program_name(node->text(), corrected_offset);
801
0
}
802
803
RefPtr<Node const> CastToCommand::leftmost_trivial_literal() const
804
0
{
805
0
    return m_inner->leftmost_trivial_literal();
806
0
}
807
808
CastToCommand::CastToCommand(Position position, NonnullRefPtr<Node> inner)
809
3.59M
    : Node(move(position))
810
3.59M
    , m_inner(move(inner))
811
3.59M
{
812
3.59M
    if (m_inner->is_syntax_error())
813
111k
        set_is_syntax_error(m_inner->syntax_error_node());
814
3.59M
}
815
816
ErrorOr<void> CastToList::dump(int level) const
817
0
{
818
0
    TRY(Node::dump(level));
819
0
    if (m_inner)
820
0
        TRY(m_inner->dump(level + 1));
821
0
    else
822
0
        print_indented(level + 1, "(empty)");
823
0
    return {};
824
0
}
825
826
ErrorOr<RefPtr<Value>> CastToList::run(RefPtr<Shell> shell)
827
0
{
828
0
    if (!m_inner)
829
0
        return make_ref_counted<ListValue>({});
830
831
0
    auto inner_value = TRY(TRY(m_inner->run(shell))->resolve_without_cast(shell));
832
0
    if (shell && shell->has_any_error())
833
0
        return make_ref_counted<ListValue>({});
834
835
0
    if (inner_value->is_command() || inner_value->is_list())
836
0
        return inner_value;
837
838
0
    auto values = TRY(inner_value->resolve_as_list(shell));
839
0
    Vector<NonnullRefPtr<Value>> cast_values;
840
0
    for (auto& value : values)
841
0
        cast_values.append(make_ref_counted<StringValue>(value));
842
843
0
    return make_ref_counted<ListValue>(cast_values);
844
0
}
845
846
ErrorOr<void> CastToList::for_each_entry(RefPtr<Shell> shell, Function<ErrorOr<IterationDecision>(NonnullRefPtr<Value>)> callback)
847
0
{
848
0
    if (m_inner)
849
0
        TRY(m_inner->for_each_entry(shell, move(callback)));
850
0
    return {};
851
0
}
852
853
ErrorOr<void> CastToList::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
854
0
{
855
0
    if (m_inner)
856
0
        TRY(m_inner->highlight_in_editor(editor, shell, metadata));
857
0
    return {};
858
0
}
859
860
HitTestResult CastToList::hit_test_position(size_t offset) const
861
0
{
862
0
    if (!m_inner)
863
0
        return {};
864
865
0
    return m_inner->hit_test_position(offset);
866
0
}
867
868
RefPtr<Node const> CastToList::leftmost_trivial_literal() const
869
0
{
870
0
    return m_inner->leftmost_trivial_literal();
871
0
}
872
873
CastToList::CastToList(Position position, RefPtr<Node> inner)
874
24.6k
    : Node(move(position))
875
24.6k
    , m_inner(move(inner))
876
24.6k
{
877
24.6k
    if (m_inner && m_inner->is_syntax_error())
878
456
        set_is_syntax_error(m_inner->syntax_error_node());
879
24.6k
}
880
881
ErrorOr<void> CloseFdRedirection::dump(int level) const
882
0
{
883
0
    TRY(Node::dump(level));
884
0
    print_indented(level, "{} -> Close", m_fd);
885
0
    return {};
886
0
}
887
888
ErrorOr<RefPtr<Value>> CloseFdRedirection::run(RefPtr<Shell>)
889
0
{
890
0
    Command command;
891
0
    command.position = position();
892
0
    command.redirections.append(adopt_ref(*new CloseRedirection(m_fd)));
893
0
    return make_ref_counted<CommandValue>(move(command));
894
0
}
895
896
ErrorOr<void> CloseFdRedirection::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
897
0
{
898
0
    editor.stylize({ m_position.start_offset, m_position.end_offset - 1 }, { Line::Style::Foreground(0x87, 0x9b, 0xcd) }); // 25% Darkened Periwinkle
899
0
    editor.stylize({ m_position.end_offset - 1, m_position.end_offset }, { Line::Style::Foreground(0xff, 0x7e, 0x00) });   // Amber
900
0
    return {};
901
0
}
902
903
CloseFdRedirection::CloseFdRedirection(Position position, int fd)
904
13.7k
    : Node(move(position))
905
13.7k
    , m_fd(fd)
906
13.7k
{
907
13.7k
}
908
909
CloseFdRedirection::~CloseFdRedirection()
910
13.7k
{
911
13.7k
}
912
913
ErrorOr<void> CommandLiteral::dump(int level) const
914
0
{
915
0
    TRY(Node::dump(level));
916
0
    print_indented(level + 1, "(Generated command literal: {})", m_command);
917
0
    return {};
918
0
}
919
920
ErrorOr<RefPtr<Value>> CommandLiteral::run(RefPtr<Shell>)
921
0
{
922
0
    return make_ref_counted<CommandValue>(m_command);
923
0
}
924
925
CommandLiteral::CommandLiteral(Position position, Command command)
926
0
    : Node(move(position))
927
0
    , m_command(move(command))
928
0
{
929
0
}
930
931
CommandLiteral::~CommandLiteral()
932
0
{
933
0
}
934
935
ErrorOr<void> Comment::dump(int level) const
936
0
{
937
0
    TRY(Node::dump(level));
938
0
    print_indented(level + 1, "{}", m_text);
939
0
    return {};
940
0
}
941
942
ErrorOr<RefPtr<Value>> Comment::run(RefPtr<Shell>)
943
0
{
944
0
    return make_ref_counted<ListValue>({});
945
0
}
946
947
ErrorOr<void> Comment::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
948
0
{
949
0
    editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(150, 150, 150) }); // Light gray
950
0
    return {};
951
0
}
952
953
Comment::Comment(Position position, String text)
954
73.3k
    : Node(move(position))
955
73.3k
    , m_text(move(text))
956
73.3k
{
957
73.3k
}
958
959
Comment::~Comment()
960
73.3k
{
961
73.3k
}
962
963
ErrorOr<void> ContinuationControl::dump(int level) const
964
0
{
965
0
    TRY(Node::dump(level));
966
0
    print_indented(level + 1, "{}", m_kind == Continue ? "(Continue)"sv : "(Break)"sv);
967
0
    return {};
968
0
}
969
970
ErrorOr<RefPtr<Value>> ContinuationControl::run(RefPtr<Shell> shell)
971
0
{
972
0
    if (m_kind == Break)
973
0
        shell->raise_error(Shell::ShellError::InternalControlFlowBreak, {}, position());
974
0
    else if (m_kind == Continue)
975
0
        shell->raise_error(Shell::ShellError::InternalControlFlowContinue, {}, position());
976
0
    else
977
0
        VERIFY_NOT_REACHED();
978
0
    return make_ref_counted<ListValue>({});
979
0
}
980
981
ErrorOr<void> ContinuationControl::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
982
0
{
983
0
    editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
984
0
    return {};
985
0
}
986
987
ErrorOr<void> DoubleQuotedString::dump(int level) const
988
0
{
989
0
    TRY(Node::dump(level));
990
0
    TRY(m_inner->dump(level + 1));
991
0
    return {};
992
0
}
993
994
ErrorOr<RefPtr<Value>> DoubleQuotedString::run(RefPtr<Shell> shell)
995
0
{
996
0
    StringBuilder builder;
997
0
    auto values = TRY(TRY(m_inner->run(shell))->resolve_as_list(shell));
998
999
0
    builder.join(""sv, values);
1000
1001
0
    return make_ref_counted<StringValue>(TRY(builder.to_string()));
1002
0
}
1003
1004
ErrorOr<void> DoubleQuotedString::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
1005
0
{
1006
0
    Line::Style style { Line::Style::Foreground(Line::Style::XtermColor::Yellow) };
1007
0
    if (metadata.is_first_in_list)
1008
0
        style.unify_with({ Line::Style::Bold });
1009
1010
0
    editor.stylize({ m_position.start_offset, m_position.end_offset }, style);
1011
0
    metadata.is_first_in_list = false;
1012
0
    return m_inner->highlight_in_editor(editor, shell, metadata);
1013
0
}
1014
1015
HitTestResult DoubleQuotedString::hit_test_position(size_t offset) const
1016
0
{
1017
0
    return m_inner->hit_test_position(offset);
1018
0
}
1019
1020
DoubleQuotedString::DoubleQuotedString(Position position, RefPtr<Node> inner)
1021
70.1k
    : Node(move(position))
1022
70.1k
    , m_inner(move(inner))
1023
70.1k
{
1024
70.1k
    if (m_inner->is_syntax_error())
1025
7.56k
        set_is_syntax_error(m_inner->syntax_error_node());
1026
70.1k
}
1027
1028
DoubleQuotedString::~DoubleQuotedString()
1029
70.1k
{
1030
70.1k
}
1031
1032
ErrorOr<void> DynamicEvaluate::dump(int level) const
1033
0
{
1034
0
    TRY(Node::dump(level));
1035
0
    TRY(m_inner->dump(level + 1));
1036
0
    return {};
1037
0
}
1038
1039
ErrorOr<RefPtr<Value>> DynamicEvaluate::run(RefPtr<Shell> shell)
1040
0
{
1041
0
    auto result = TRY(TRY(m_inner->run(shell))->resolve_without_cast(shell));
1042
0
    if (shell && shell->has_any_error())
1043
0
        return make_ref_counted<ListValue>({});
1044
1045
    // Dynamic Evaluation behaves differently between strings and lists.
1046
    // Strings are treated as variables, and Lists are treated as commands.
1047
0
    if (result->is_string()) {
1048
0
        auto name_part = TRY(result->resolve_as_list(shell));
1049
0
        VERIFY(name_part.size() == 1);
1050
0
        return make_ref_counted<SimpleVariableValue>(name_part[0]);
1051
0
    }
1052
1053
    // If it's anything else, we're just gonna cast it to a list.
1054
0
    auto list = TRY(result->resolve_as_list(shell));
1055
0
    return make_ref_counted<CommandValue>(move(list), position());
1056
0
}
1057
1058
ErrorOr<void> DynamicEvaluate::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
1059
0
{
1060
0
    editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
1061
0
    return m_inner->highlight_in_editor(editor, shell, metadata);
1062
0
}
1063
1064
HitTestResult DynamicEvaluate::hit_test_position(size_t offset) const
1065
0
{
1066
0
    return m_inner->hit_test_position(offset);
1067
0
}
1068
1069
DynamicEvaluate::DynamicEvaluate(Position position, NonnullRefPtr<Node> inner)
1070
40.1k
    : Node(move(position))
1071
40.1k
    , m_inner(move(inner))
1072
40.1k
{
1073
40.1k
    if (m_inner->is_syntax_error())
1074
38.3k
        set_is_syntax_error(m_inner->syntax_error_node());
1075
40.1k
}
1076
1077
DynamicEvaluate::~DynamicEvaluate()
1078
40.1k
{
1079
40.1k
}
1080
1081
ErrorOr<void> Fd2FdRedirection::dump(int level) const
1082
0
{
1083
0
    TRY(Node::dump(level));
1084
0
    print_indented(level, "{} -> {}", m_old_fd, m_new_fd);
1085
0
    return {};
1086
0
}
1087
1088
ErrorOr<RefPtr<Value>> Fd2FdRedirection::run(RefPtr<Shell>)
1089
0
{
1090
0
    Command command;
1091
0
    command.position = position();
1092
0
    command.redirections.append(FdRedirection::create(m_new_fd, m_old_fd, Rewiring::Close::None));
1093
0
    return make_ref_counted<CommandValue>(move(command));
1094
0
}
1095
1096
ErrorOr<void> Fd2FdRedirection::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
1097
0
{
1098
0
    editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(0x87, 0x9b, 0xcd) }); // 25% Darkened Periwinkle
1099
0
    return {};
1100
0
}
1101
1102
Fd2FdRedirection::Fd2FdRedirection(Position position, int src, int dst)
1103
48.0k
    : Node(move(position))
1104
48.0k
    , m_old_fd(src)
1105
48.0k
    , m_new_fd(dst)
1106
48.0k
{
1107
48.0k
}
1108
1109
Fd2FdRedirection::~Fd2FdRedirection()
1110
48.0k
{
1111
48.0k
}
1112
1113
ErrorOr<void> FunctionDeclaration::dump(int level) const
1114
0
{
1115
0
    TRY(Node::dump(level));
1116
0
    print_indented(level + 1, "(name: {})\n", m_name.name);
1117
0
    print_indented(level + 1, "(argument names)");
1118
0
    for (auto& arg : m_arguments)
1119
0
        print_indented(level + 2, "(name: {})\n", arg.name);
1120
1121
0
    print_indented(level + 1, "(body)");
1122
0
    if (m_block)
1123
0
        TRY(m_block->dump(level + 2));
1124
0
    else
1125
0
        print_indented(level + 2, "(null)");
1126
0
    return {};
1127
0
}
1128
1129
ErrorOr<RefPtr<Value>> FunctionDeclaration::run(RefPtr<Shell> shell)
1130
0
{
1131
0
    Vector<ByteString> args;
1132
0
    for (auto& arg : m_arguments)
1133
0
        args.append(arg.name.to_byte_string());
1134
1135
0
    shell->define_function(m_name.name.to_byte_string(), move(args), m_block);
1136
1137
0
    return make_ref_counted<ListValue>({});
1138
0
}
1139
1140
ErrorOr<void> FunctionDeclaration::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
1141
0
{
1142
0
    editor.stylize({ m_name.position.start_offset, m_name.position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Blue) });
1143
1144
0
    for (auto& arg : m_arguments)
1145
0
        editor.stylize({ arg.position.start_offset, arg.position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Blue), Line::Style::Italic });
1146
1147
0
    metadata.is_first_in_list = true;
1148
0
    if (m_block)
1149
0
        TRY(m_block->highlight_in_editor(editor, shell, metadata));
1150
0
    return {};
1151
0
}
1152
1153
HitTestResult FunctionDeclaration::hit_test_position(size_t offset) const
1154
0
{
1155
0
    if (!m_block)
1156
0
        return {};
1157
1158
0
    auto result = m_block->hit_test_position(offset);
1159
0
    if (result.matching_node && result.matching_node->is_simple_variable())
1160
0
        result.closest_node_with_semantic_meaning = this;
1161
0
    return result;
1162
0
}
1163
1164
ErrorOr<Vector<Line::CompletionSuggestion>> FunctionDeclaration::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result) const
1165
0
{
1166
0
    auto matching_node = hit_test_result.matching_node;
1167
0
    if (!matching_node)
1168
0
        return Vector<Line::CompletionSuggestion> {};
1169
1170
0
    if (!matching_node->is_simple_variable())
1171
0
        return matching_node->complete_for_editor(shell, offset, hit_test_result);
1172
1173
0
    auto corrected_offset = offset - matching_node->position().start_offset - 1; // Skip the first '$'
1174
0
    auto* node = static_cast<SimpleVariable const*>(matching_node.ptr());
1175
1176
0
    auto name = node->name().bytes_as_string_view().substring_view(0, corrected_offset);
1177
1178
0
    Vector<Line::CompletionSuggestion> results;
1179
0
    for (auto& arg : m_arguments) {
1180
0
        if (arg.name.starts_with_bytes(name))
1181
0
            results.append(arg.name.to_byte_string());
1182
0
    }
1183
1184
0
    results.extend(TRY(matching_node->complete_for_editor(shell, offset, hit_test_result)));
1185
1186
0
    return results;
1187
0
}
1188
1189
FunctionDeclaration::FunctionDeclaration(Position position, NameWithPosition name, Vector<NameWithPosition> arguments, RefPtr<AST::Node> body)
1190
92
    : Node(move(position))
1191
92
    , m_name(move(name))
1192
92
    , m_arguments(arguments)
1193
92
    , m_block(move(body))
1194
92
{
1195
92
    if (m_block && m_block->is_syntax_error())
1196
10
        set_is_syntax_error(m_block->syntax_error_node());
1197
92
}
1198
1199
FunctionDeclaration::~FunctionDeclaration()
1200
92
{
1201
92
}
1202
1203
ErrorOr<void> ForLoop::dump(int level) const
1204
0
{
1205
0
    TRY(Node::dump(level));
1206
0
    if (m_variable.has_value())
1207
0
        print_indented(level + 1, "iterating with {} in", m_variable->name);
1208
0
    if (m_index_variable.has_value())
1209
0
        print_indented(level + 1, "with index name {} in", m_index_variable->name);
1210
0
    if (m_iterated_expression)
1211
0
        TRY(m_iterated_expression->dump(level + 2));
1212
0
    else
1213
0
        print_indented(level + 2, "(ever)");
1214
0
    print_indented(level + 1, "Running");
1215
0
    if (m_block)
1216
0
        TRY(m_block->dump(level + 2));
1217
0
    else
1218
0
        print_indented(level + 2, "(null)");
1219
0
    return {};
1220
0
}
1221
1222
ErrorOr<RefPtr<Value>> ForLoop::run(RefPtr<Shell> shell)
1223
0
{
1224
0
    if (!m_block)
1225
0
        return make_ref_counted<ListValue>({});
1226
1227
0
    size_t consecutive_interruptions = 0;
1228
0
    auto run = [&](auto& block_value) {
1229
0
        if (shell->has_error(Shell::ShellError::InternalControlFlowBreak) || shell->has_error(Shell::ShellError::InternalControlFlowReturn)) {
1230
0
            shell->take_error();
1231
0
            return IterationDecision::Break;
1232
0
        }
1233
1234
0
        if (shell->has_error(Shell::ShellError::InternalControlFlowContinue)) {
1235
0
            shell->take_error();
1236
0
            return IterationDecision::Continue;
1237
0
        }
1238
1239
0
        if (shell->has_any_error() && !shell->has_error(Shell::ShellError::InternalControlFlowInterrupted))
1240
0
            return IterationDecision::Break;
1241
1242
0
        if (block_value->is_job()) {
1243
0
            auto job = static_cast<JobValue*>(block_value.ptr())->job();
1244
0
            if (!job || job->is_running_in_background())
1245
0
                return IterationDecision::Continue;
1246
0
            shell->block_on_job(job);
1247
1248
0
            if (shell->has_any_error()) {
1249
0
                if (shell->has_error(Shell::ShellError::InternalControlFlowInterrupted))
1250
0
                    ++consecutive_interruptions;
1251
1252
0
                if (shell->has_error(Shell::ShellError::InternalControlFlowKilled))
1253
0
                    return IterationDecision::Break;
1254
0
            }
1255
0
        }
1256
0
        return IterationDecision::Continue;
1257
0
    };
1258
1259
0
    if (m_iterated_expression) {
1260
0
        auto variable_name = m_variable.has_value() ? m_variable->name : "it"_string;
1261
0
        Optional<StringView> index_name = m_index_variable.has_value() ? Optional<StringView>(m_index_variable->name) : Optional<StringView>();
1262
0
        size_t i = 0;
1263
0
        TRY(m_iterated_expression->for_each_entry(shell, [&](auto value) -> ErrorOr<IterationDecision> {
1264
0
            if (consecutive_interruptions >= 2)
1265
0
                return IterationDecision::Break;
1266
1267
0
            if (shell) {
1268
0
                if (shell->has_error(Shell::ShellError::InternalControlFlowInterrupted))
1269
0
                    shell->take_error();
1270
1271
0
                if (shell->has_any_error())
1272
0
                    return IterationDecision::Break;
1273
0
            }
1274
1275
0
            RefPtr<Value> block_value;
1276
1277
0
            {
1278
0
                auto frame = shell->push_frame(ByteString::formatted("for ({})", this));
1279
0
                shell->set_local_variable(variable_name.bytes_as_string_view(), value, true);
1280
1281
0
                if (index_name.has_value())
1282
0
                    shell->set_local_variable(index_name.value(), make_ref_counted<AST::StringValue>(String::number(i)), true);
1283
1284
0
                ++i;
1285
1286
0
                block_value = TRY(m_block->run(shell));
1287
0
            }
1288
1289
0
            return run(block_value);
1290
0
        }));
1291
0
    } else {
1292
0
        for (;;) {
1293
0
            if (consecutive_interruptions >= 2)
1294
0
                break;
1295
1296
0
            if (shell) {
1297
0
                if (shell->has_error(Shell::ShellError::InternalControlFlowInterrupted))
1298
0
                    shell->take_error();
1299
1300
0
                if (shell->has_any_error())
1301
0
                    break;
1302
0
            }
1303
1304
0
            RefPtr<Value> block_value = TRY(m_block->run(shell));
1305
0
            if (run(block_value) == IterationDecision::Break)
1306
0
                break;
1307
0
        }
1308
0
    }
1309
1310
0
    return make_ref_counted<ListValue>({});
1311
0
}
1312
1313
ErrorOr<void> ForLoop::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
1314
0
{
1315
0
    auto is_loop = m_iterated_expression.is_null();
1316
0
    editor.stylize({ m_position.start_offset, m_position.start_offset + (is_loop ? 4 : 3) }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
1317
0
    if (!is_loop) {
1318
0
        if (m_in_kw_position.has_value())
1319
0
            editor.stylize({ m_in_kw_position.value().start_offset, m_in_kw_position.value().end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
1320
1321
0
        if (m_index_kw_position.has_value())
1322
0
            editor.stylize({ m_index_kw_position.value().start_offset, m_index_kw_position.value().end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
1323
1324
0
        metadata.is_first_in_list = false;
1325
0
        TRY(m_iterated_expression->highlight_in_editor(editor, shell, metadata));
1326
0
    }
1327
1328
0
    if (m_index_variable.has_value())
1329
0
        editor.stylize({ m_index_variable->position.start_offset, m_index_variable->position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Blue), Line::Style::Italic });
1330
1331
0
    if (m_variable.has_value())
1332
0
        editor.stylize({ m_variable->position.start_offset, m_variable->position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Blue), Line::Style::Italic });
1333
1334
0
    metadata.is_first_in_list = true;
1335
0
    if (m_block)
1336
0
        TRY(m_block->highlight_in_editor(editor, shell, metadata));
1337
0
    return {};
1338
0
}
1339
1340
HitTestResult ForLoop::hit_test_position(size_t offset) const
1341
0
{
1342
0
    if (m_iterated_expression) {
1343
0
        if (auto result = m_iterated_expression->hit_test_position(offset); result.matching_node)
1344
0
            return result;
1345
0
    }
1346
1347
0
    if (!m_block)
1348
0
        return {};
1349
1350
0
    return m_block->hit_test_position(offset);
1351
0
}
1352
1353
ForLoop::ForLoop(Position position, Optional<NameWithPosition> variable, Optional<NameWithPosition> index_variable, RefPtr<AST::Node> iterated_expr, RefPtr<AST::Node> block, Optional<Position> in_kw_position, Optional<Position> index_kw_position)
1354
667k
    : Node(move(position))
1355
667k
    , m_variable(move(variable))
1356
667k
    , m_index_variable(move(index_variable))
1357
667k
    , m_iterated_expression(move(iterated_expr))
1358
667k
    , m_block(move(block))
1359
667k
    , m_in_kw_position(move(in_kw_position))
1360
667k
    , m_index_kw_position(move(index_kw_position))
1361
667k
{
1362
667k
    if (m_iterated_expression && m_iterated_expression->is_syntax_error())
1363
273
        set_is_syntax_error(m_iterated_expression->syntax_error_node());
1364
667k
    else if (m_block && m_block->is_syntax_error())
1365
667k
        set_is_syntax_error(m_block->syntax_error_node());
1366
667k
}
1367
1368
ForLoop::~ForLoop()
1369
667k
{
1370
667k
}
1371
1372
ErrorOr<void> Glob::dump(int level) const
1373
0
{
1374
0
    TRY(Node::dump(level));
1375
0
    print_indented(level + 1, "{}", m_text);
1376
0
    return {};
1377
0
}
1378
1379
ErrorOr<RefPtr<Value>> Glob::run(RefPtr<Shell>)
1380
0
{
1381
0
    return make_ref_counted<GlobValue>(m_text, position());
1382
0
}
1383
1384
ErrorOr<void> Glob::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata metadata)
1385
0
{
1386
0
    Line::Style style { Line::Style::Foreground(Line::Style::XtermColor::Cyan) };
1387
0
    if (metadata.is_first_in_list)
1388
0
        style.unify_with({ Line::Style::Bold });
1389
0
    editor.stylize({ m_position.start_offset, m_position.end_offset }, move(style));
1390
0
    return {};
1391
0
}
1392
1393
Glob::Glob(Position position, String text)
1394
430k
    : Node(move(position))
1395
430k
    , m_text(move(text))
1396
430k
{
1397
430k
}
1398
1399
Glob::~Glob()
1400
430k
{
1401
430k
}
1402
1403
ErrorOr<void> Heredoc::dump(int level) const
1404
0
{
1405
0
    TRY(Node::dump(level));
1406
0
    print_indented(level + 1, "(End Key)");
1407
0
    print_indented(level + 2, "{}", m_end);
1408
0
    print_indented(level + 1, "(Allows Interpolation)");
1409
0
    print_indented(level + 2, "{}", m_allows_interpolation);
1410
0
    if (!evaluates_to_string()) {
1411
0
        print_indented(level + 1, "(Target FD)");
1412
0
        print_indented(level + 2, "{}", *m_target_fd);
1413
0
    }
1414
0
    print_indented(level + 1, "(Contents)");
1415
0
    if (m_contents)
1416
0
        TRY(m_contents->dump(level + 2));
1417
0
    else
1418
0
        print_indented(level + 2, "(null)");
1419
0
    return {};
1420
0
}
1421
1422
ErrorOr<RefPtr<Value>> Heredoc::run(RefPtr<Shell> shell)
1423
0
{
1424
0
    if (shell && shell->posix_mode() && !m_contents) {
1425
0
        m_contents = make_ref_counted<StringLiteral>(position(), ""_string, StringLiteral::EnclosureType::None);
1426
0
    }
1427
1428
0
    if (!m_contents) {
1429
0
        if (shell)
1430
0
            shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "Attempt to evaluate an unresolved heredoc"sv, position());
1431
0
        return nullptr;
1432
0
    }
1433
1434
0
    auto value = TRY([&]() -> ErrorOr<RefPtr<Value>> {
1435
0
        if (!m_deindent)
1436
0
            return TRY(m_contents->run(shell));
1437
1438
        // To deindent, first split to lines...
1439
0
        auto value = TRY(m_contents->run(shell));
1440
0
        if (shell && shell->has_any_error())
1441
0
            return make_ref_counted<ListValue>({});
1442
1443
0
        if (!value)
1444
0
            return value;
1445
0
        auto list = TRY(value->resolve_as_list(shell));
1446
        // The list better have one entry, otherwise we've put the wrong kind of node inside this heredoc
1447
0
        VERIFY(list.size() == 1);
1448
0
        auto lines = list.first().bytes_as_string_view().split_view('\n');
1449
1450
        // Now just trim each line and put them back in a string
1451
0
        StringBuilder builder { list.first().bytes_as_string_view().length() };
1452
0
        for (auto& line : lines) {
1453
0
            builder.append(line.trim_whitespace(TrimMode::Left));
1454
0
            builder.append('\n');
1455
0
        }
1456
1457
0
        return make_ref_counted<StringValue>(TRY(builder.to_string()));
1458
0
    }());
1459
1460
0
    if (evaluates_to_string())
1461
0
        return value;
1462
1463
0
    int fds[2];
1464
0
    auto rc = pipe(fds);
1465
0
    if (rc != 0) {
1466
        // pipe() failed for {}
1467
0
        if (shell)
1468
0
            shell->raise_error(Shell::ShellError::PipeFailure, ByteString::formatted("heredoc: {}", strerror(errno)), position());
1469
0
        return nullptr;
1470
0
    }
1471
1472
0
    auto read_end = fds[0];
1473
0
    auto write_end = fds[1];
1474
1475
    // Dump all of 'value' into the pipe.
1476
0
    auto* file = fdopen(write_end, "wb");
1477
0
    if (!file) {
1478
0
        if (shell)
1479
0
            shell->raise_error(Shell::ShellError::OpenFailure, "heredoc"sv, position());
1480
0
        return nullptr;
1481
0
    }
1482
1483
0
    auto text = TRY(value->resolve_as_string(shell));
1484
0
    auto bytes = text.bytes();
1485
1486
0
    auto written = fwrite(bytes.data(), 1, bytes.size(), file);
1487
0
    fflush(file);
1488
0
    if (written != bytes.size()) {
1489
0
        if (shell)
1490
0
            shell->raise_error(Shell::ShellError::WriteFailure, "heredoc"sv, position());
1491
0
    }
1492
0
    fclose(file);
1493
1494
0
    Command command;
1495
0
    command.position = position();
1496
0
    command.redirections.append(FdRedirection::create(read_end, *target_fd(), Rewiring::Close::None));
1497
0
    return make_ref_counted<CommandValue>(move(command));
1498
0
}
1499
1500
ErrorOr<void> Heredoc::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
1501
0
{
1502
0
    Line::Style content_style { Line::Style::Foreground(Line::Style::XtermColor::Yellow) };
1503
0
    if (metadata.is_first_in_list)
1504
0
        content_style.unify_with({ Line::Style::Bold });
1505
1506
0
    if (!m_contents)
1507
0
        content_style.unify_with({ Line::Style::Foreground(Line::Style::XtermColor::Red) }, true);
1508
1509
0
    editor.stylize({ m_position.start_offset, m_position.end_offset }, content_style);
1510
0
    if (m_contents)
1511
0
        TRY(m_contents->highlight_in_editor(editor, shell, metadata));
1512
0
    return {};
1513
0
}
1514
1515
HitTestResult Heredoc::hit_test_position(size_t offset) const
1516
0
{
1517
0
    if (!m_contents)
1518
0
        return {};
1519
1520
0
    return m_contents->hit_test_position(offset);
1521
0
}
1522
1523
Heredoc::Heredoc(Position position, String end, bool allow_interpolation, bool deindent, Optional<int> target_fd)
1524
314k
    : Node(move(position))
1525
314k
    , m_end(move(end))
1526
314k
    , m_allows_interpolation(allow_interpolation)
1527
314k
    , m_deindent(deindent)
1528
314k
    , m_target_fd(target_fd)
1529
314k
{
1530
314k
}
1531
1532
Heredoc::~Heredoc()
1533
314k
{
1534
314k
}
1535
1536
ErrorOr<void> HistoryEvent::dump(int level) const
1537
0
{
1538
0
    TRY(Node::dump(level));
1539
0
    print_indented(level + 1, "Event Selector");
1540
0
    switch (m_selector.event.kind) {
1541
0
    case HistorySelector::EventKind::IndexFromStart:
1542
0
        print_indented(level + 2, "IndexFromStart");
1543
0
        break;
1544
0
    case HistorySelector::EventKind::IndexFromEnd:
1545
0
        print_indented(level + 2, "IndexFromEnd");
1546
0
        break;
1547
0
    case HistorySelector::EventKind::ContainingStringLookup:
1548
0
        print_indented(level + 2, "ContainingStringLookup");
1549
0
        break;
1550
0
    case HistorySelector::EventKind::StartingStringLookup:
1551
0
        print_indented(level + 2, "StartingStringLookup");
1552
0
        break;
1553
0
    }
1554
0
    print_indented(level + 3, "{}({})", m_selector.event.index, m_selector.event.text);
1555
1556
0
    print_indented(level + 1, "Word Selector");
1557
0
    auto print_word_selector = [&](HistorySelector::WordSelector const& selector) {
1558
0
        switch (selector.kind) {
1559
0
        case HistorySelector::WordSelectorKind::Index:
1560
0
            print_indented(level + 3, "Index {}", selector.selector);
1561
0
            break;
1562
0
        case HistorySelector::WordSelectorKind::Last:
1563
0
            print_indented(level + 3, "Last");
1564
0
            break;
1565
0
        }
1566
0
    };
1567
1568
0
    if (m_selector.word_selector_range.end.has_value()) {
1569
0
        print_indented(level + 2, "Range Start");
1570
0
        print_word_selector(m_selector.word_selector_range.start);
1571
0
        print_indented(level + 2, "Range End");
1572
0
        print_word_selector(m_selector.word_selector_range.end.value());
1573
0
    } else {
1574
0
        print_indented(level + 2, "Direct Address");
1575
0
        print_word_selector(m_selector.word_selector_range.start);
1576
0
    }
1577
1578
0
    return {};
1579
0
}
1580
1581
ErrorOr<RefPtr<Value>> HistoryEvent::run(RefPtr<Shell> shell)
1582
0
{
1583
0
    if (!shell)
1584
0
        return make_ref_counted<AST::ListValue>({});
1585
1586
0
    auto editor = shell->editor();
1587
0
    if (!editor) {
1588
0
        shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "No history available!", position());
1589
0
        return make_ref_counted<AST::ListValue>({});
1590
0
    }
1591
0
    auto& history = editor->history();
1592
1593
    // First, resolve the event itself.
1594
0
    ByteString resolved_history;
1595
0
    switch (m_selector.event.kind) {
1596
0
    case HistorySelector::EventKind::IndexFromStart:
1597
0
        if (m_selector.event.index >= history.size()) {
1598
0
            shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "History event index out of bounds", m_selector.event.text_position);
1599
0
            return make_ref_counted<AST::ListValue>({});
1600
0
        }
1601
0
        resolved_history = history[m_selector.event.index].entry;
1602
0
        break;
1603
0
    case HistorySelector::EventKind::IndexFromEnd:
1604
0
        if (m_selector.event.index >= history.size()) {
1605
0
            shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "History event index out of bounds", m_selector.event.text_position);
1606
0
            return make_ref_counted<AST::ListValue>({});
1607
0
        }
1608
0
        resolved_history = history[history.size() - m_selector.event.index - 1].entry;
1609
0
        break;
1610
0
    case HistorySelector::EventKind::ContainingStringLookup: {
1611
0
        auto it = find_if(history.rbegin(), history.rend(), [&](auto& entry) { return entry.entry.contains(m_selector.event.text); });
1612
0
        if (it.is_end()) {
1613
0
            shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "History event did not match any entry", m_selector.event.text_position);
1614
0
            return make_ref_counted<AST::ListValue>({});
1615
0
        }
1616
0
        resolved_history = it->entry;
1617
0
        break;
1618
0
    }
1619
0
    case HistorySelector::EventKind::StartingStringLookup: {
1620
0
        auto it = find_if(history.rbegin(), history.rend(), [&](auto& entry) { return entry.entry.starts_with(m_selector.event.text); });
1621
0
        if (it.is_end()) {
1622
0
            shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "History event did not match any entry", m_selector.event.text_position);
1623
0
            return make_ref_counted<AST::ListValue>({});
1624
0
        }
1625
0
        resolved_history = it->entry;
1626
0
        break;
1627
0
    }
1628
0
    }
1629
1630
    // Then, split it up to "words".
1631
0
    auto nodes = Parser { resolved_history }.parse_as_multiple_expressions();
1632
1633
    // Now take the "words" as described by the word selectors.
1634
0
    bool is_range = m_selector.word_selector_range.end.has_value();
1635
0
    if (is_range) {
1636
0
        auto start_index = m_selector.word_selector_range.start.resolve(nodes.size());
1637
0
        auto end_index = m_selector.word_selector_range.end->resolve(nodes.size());
1638
0
        if (start_index >= nodes.size()) {
1639
0
            shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "History word index out of bounds", m_selector.word_selector_range.start.position);
1640
0
            return make_ref_counted<AST::ListValue>({});
1641
0
        }
1642
0
        if (end_index >= nodes.size()) {
1643
0
            shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "History word index out of bounds", m_selector.word_selector_range.end->position);
1644
0
            return make_ref_counted<AST::ListValue>({});
1645
0
        }
1646
1647
0
        decltype(nodes) resolved_nodes;
1648
0
        resolved_nodes.append(nodes.data() + start_index, end_index - start_index + 1);
1649
0
        NonnullRefPtr<AST::Node> list = make_ref_counted<AST::ListConcatenate>(position(), move(resolved_nodes));
1650
0
        return list->run(shell);
1651
0
    }
1652
1653
0
    auto index = m_selector.word_selector_range.start.resolve(nodes.size());
1654
0
    if (index >= nodes.size()) {
1655
0
        shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "History word index out of bounds", m_selector.word_selector_range.start.position);
1656
0
        return make_ref_counted<AST::ListValue>({});
1657
0
    }
1658
0
    return nodes[index]->run(shell);
1659
0
}
1660
1661
ErrorOr<void> HistoryEvent::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata metadata)
1662
0
{
1663
0
    Line::Style style { Line::Style::Foreground(Line::Style::XtermColor::Green) };
1664
0
    if (metadata.is_first_in_list)
1665
0
        style.unify_with({ Line::Style::Bold });
1666
0
    editor.stylize({ m_position.start_offset, m_position.end_offset }, move(style));
1667
0
    return {};
1668
0
}
1669
1670
HistoryEvent::HistoryEvent(Position position, HistorySelector selector)
1671
0
    : Node(move(position))
1672
0
    , m_selector(move(selector))
1673
0
{
1674
0
    if (m_selector.word_selector_range.start.syntax_error_node)
1675
0
        set_is_syntax_error(*m_selector.word_selector_range.start.syntax_error_node);
1676
0
    else if (m_selector.word_selector_range.end.has_value() && m_selector.word_selector_range.end->syntax_error_node)
1677
0
        set_is_syntax_error(*m_selector.word_selector_range.end->syntax_error_node);
1678
0
}
1679
1680
HistoryEvent::~HistoryEvent()
1681
0
{
1682
0
}
1683
1684
ErrorOr<void> Execute::dump(int level) const
1685
0
{
1686
0
    TRY(Node::dump(level));
1687
0
    if (m_capture_stdout)
1688
0
        print_indented(level + 1, "(Capturing stdout)");
1689
0
    TRY(m_command->dump(level + 1));
1690
1691
0
    return {};
1692
0
}
1693
1694
ErrorOr<void> Execute::for_each_entry(RefPtr<Shell> shell, Function<ErrorOr<IterationDecision>(NonnullRefPtr<Value>)> callback)
1695
0
{
1696
0
    if (m_command->would_execute())
1697
0
        return m_command->for_each_entry(shell, move(callback));
1698
1699
0
    auto unexpanded_commands = TRY(TRY(m_command->run(shell))->resolve_as_commands(shell));
1700
0
    if (shell && shell->has_any_error())
1701
0
        return {};
1702
1703
0
    if (!shell)
1704
0
        return {};
1705
1706
0
    auto commands = TRY(shell->expand_aliases(move(unexpanded_commands)));
1707
1708
0
    if (m_capture_stdout) {
1709
        // Make sure that we're going to be running _something_.
1710
0
        auto has_one_command = false;
1711
0
        for (auto& command : commands) {
1712
0
            if (command.argv.is_empty() && !command.pipeline && command.next_chain.is_empty())
1713
0
                continue;
1714
0
            has_one_command = true;
1715
0
            break;
1716
0
        }
1717
1718
0
        if (!has_one_command) {
1719
0
            shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "Cannot capture standard output when no command is being executed", m_position);
1720
0
            return {};
1721
0
        }
1722
0
        int pipefd[2];
1723
0
        int rc = pipe(pipefd);
1724
0
        if (rc < 0) {
1725
0
            dbgln("Error: cannot pipe(): {}", strerror(errno));
1726
0
            return {};
1727
0
        }
1728
0
        auto& last_in_commands = commands.last();
1729
1730
0
        last_in_commands.redirections.prepend(FdRedirection::create(pipefd[1], STDOUT_FILENO, Rewiring::Close::Old));
1731
0
        last_in_commands.should_wait = false;
1732
0
        last_in_commands.should_notify_if_in_background = false;
1733
0
        last_in_commands.is_pipe_source = false;
1734
1735
0
        Core::EventLoop loop;
1736
1737
0
        auto notifier = Core::Notifier::construct(pipefd[0], Core::Notifier::Type::Read);
1738
0
        AllocatingMemoryStream stream;
1739
1740
0
        enum CheckResult {
1741
0
            Continue,
1742
0
            Break,
1743
0
            NothingLeft,
1744
0
        };
1745
0
        auto check_and_call = [&]() -> ErrorOr<CheckResult> {
1746
0
            auto ifs = TRY(shell->local_variable_or("IFS"sv, "\n"sv));
1747
1748
0
            if (auto offset = TRY(stream.offset_of(ifs.bytes())); offset.has_value()) {
1749
0
                auto line_end = offset.value();
1750
0
                if (line_end == 0) {
1751
0
                    TRY(stream.discard(ifs.length()));
1752
1753
0
                    if (shell->options.inline_exec_keep_empty_segments)
1754
0
                        if (TRY(callback(make_ref_counted<StringValue>(String {}))) == IterationDecision::Break) {
1755
0
                            loop.quit(Break);
1756
0
                            notifier->set_enabled(false);
1757
0
                            return Break;
1758
0
                        }
1759
0
                } else {
1760
0
                    auto entry_result = ByteBuffer::create_uninitialized(line_end + ifs.length());
1761
0
                    if (entry_result.is_error()) {
1762
0
                        loop.quit(Break);
1763
0
                        notifier->set_enabled(false);
1764
0
                        return Break;
1765
0
                    }
1766
0
                    auto entry = entry_result.release_value();
1767
0
                    TRY(stream.read_until_filled(entry));
1768
1769
0
                    auto str = TRY(String::from_utf8(StringView(entry.data(), entry.size() - ifs.length())));
1770
0
                    if (TRY(callback(make_ref_counted<StringValue>(move(str)))) == IterationDecision::Break) {
1771
0
                        loop.quit(Break);
1772
0
                        notifier->set_enabled(false);
1773
0
                        return Break;
1774
0
                    }
1775
0
                }
1776
1777
0
                return Continue;
1778
0
            }
1779
1780
0
            return NothingLeft;
1781
0
        };
1782
1783
0
        notifier->on_activation = [&]() -> void {
1784
0
            constexpr static auto buffer_size = 16;
1785
0
            u8 buffer[buffer_size];
1786
0
            size_t remaining_size = buffer_size;
1787
1788
0
            for (;;) {
1789
0
                notifier->set_type(Core::Notifier::Type::None);
1790
0
                bool should_enable_notifier = false;
1791
1792
0
                ScopeGuard notifier_enabler { [&] {
1793
0
                    if (should_enable_notifier)
1794
0
                        notifier->set_type(Core::Notifier::Type::Read);
1795
0
                } };
1796
1797
0
                if (check_and_call().release_value_but_fixme_should_propagate_errors() == Break) {
1798
0
                    loop.quit(Break);
1799
0
                    return;
1800
0
                }
1801
1802
0
                auto read_size = read(pipefd[0], buffer, remaining_size);
1803
0
                if (read_size < 0) {
1804
0
                    int saved_errno = errno;
1805
0
                    if (saved_errno == EINTR) {
1806
0
                        should_enable_notifier = true;
1807
0
                        continue;
1808
0
                    }
1809
0
                    if (saved_errno == 0)
1810
0
                        continue;
1811
0
                    dbgln("read() failed: {}", strerror(saved_errno));
1812
0
                    break;
1813
0
                }
1814
0
                if (read_size == 0)
1815
0
                    break;
1816
1817
0
                should_enable_notifier = true;
1818
0
                stream.write_until_depleted({ buffer, (size_t)read_size }).release_value_but_fixme_should_propagate_errors();
1819
0
            }
1820
1821
0
            loop.quit(NothingLeft);
1822
0
        };
1823
1824
0
        auto jobs = shell->run_commands(commands);
1825
0
        ScopeGuard kill_jobs_if_around { [&] {
1826
0
            for (auto& job : jobs) {
1827
0
                if (job->is_running_in_background() && !job->exited() && !job->signaled()) {
1828
0
                    job->set_should_announce_signal(false); // We're explicitly killing it here.
1829
0
                    shell->kill_job(job, SIGTERM);
1830
0
                }
1831
0
            }
1832
0
        } };
1833
1834
0
        auto exit_reason = loop.exec();
1835
1836
0
        notifier->on_activation = nullptr;
1837
1838
0
        if (close(pipefd[0]) < 0) {
1839
0
            dbgln("close() failed: {}", strerror(errno));
1840
0
        }
1841
1842
0
        if (exit_reason != Break && !stream.is_eof()) {
1843
0
            auto action = Continue;
1844
0
            do {
1845
0
                action = TRY(check_and_call());
1846
0
                if (action == Break)
1847
0
                    return {};
1848
0
            } while (action == Continue);
1849
1850
0
            if (!stream.is_eof()) {
1851
0
                auto entry_result = ByteBuffer::create_uninitialized(stream.used_buffer_size());
1852
0
                if (entry_result.is_error()) {
1853
0
                    shell->raise_error(Shell::ShellError::OutOfMemory, {}, position());
1854
0
                    return {};
1855
0
                }
1856
0
                auto entry = entry_result.release_value();
1857
0
                TRY(stream.read_until_filled(entry));
1858
0
                TRY(callback(make_ref_counted<StringValue>(TRY(String::from_utf8(entry)))));
1859
0
            }
1860
0
        }
1861
1862
0
        return {};
1863
0
    }
1864
1865
0
    auto jobs = shell->run_commands(commands);
1866
1867
0
    if (!jobs.is_empty())
1868
0
        TRY(callback(make_ref_counted<JobValue>(jobs.last())));
1869
1870
0
    return {};
1871
0
}
1872
1873
ErrorOr<RefPtr<Value>> Execute::run(RefPtr<Shell> shell)
1874
0
{
1875
0
    if (shell && shell->has_any_error())
1876
0
        return make_ref_counted<ListValue>({});
1877
1878
0
    if (m_command->would_execute())
1879
0
        return m_command->run(shell);
1880
1881
0
    Vector<NonnullRefPtr<Value>> values;
1882
0
    TRY(for_each_entry(shell, [&](auto value) {
1883
0
        values.append(*value);
1884
0
        return IterationDecision::Continue;
1885
0
    }));
1886
1887
0
    if (values.size() == 1 && values.first()->is_job())
1888
0
        return values.first();
1889
1890
0
    return make_ref_counted<ListValue>(move(values));
1891
0
}
1892
1893
ErrorOr<void> Execute::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
1894
0
{
1895
0
    if (m_capture_stdout)
1896
0
        editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Green) });
1897
0
    metadata.is_first_in_list = true;
1898
0
    return m_command->highlight_in_editor(editor, shell, metadata);
1899
0
}
1900
1901
HitTestResult Execute::hit_test_position(size_t offset) const
1902
0
{
1903
0
    auto result = m_command->hit_test_position(offset);
1904
0
    if (!result.closest_node_with_semantic_meaning)
1905
0
        result.closest_node_with_semantic_meaning = this;
1906
0
    if (!result.closest_command_node)
1907
0
        result.closest_command_node = m_command;
1908
0
    return result;
1909
0
}
1910
1911
ErrorOr<Vector<Line::CompletionSuggestion>> Execute::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result) const
1912
0
{
1913
0
    auto matching_node = hit_test_result.matching_node;
1914
0
    if (!matching_node || !matching_node->is_bareword())
1915
0
        return Vector<Line::CompletionSuggestion> {};
1916
1917
0
    auto corrected_offset = offset - matching_node->position().start_offset;
1918
0
    auto* node = static_cast<BarewordLiteral const*>(matching_node.ptr());
1919
1920
0
    if (corrected_offset > node->text().bytes_as_string_view().length())
1921
0
        return Vector<Line::CompletionSuggestion> {};
1922
1923
0
    return shell.complete_program_name(node->text(), corrected_offset);
1924
0
}
1925
1926
Execute::Execute(Position position, NonnullRefPtr<Node> command, bool capture_stdout)
1927
1.18M
    : Node(move(position))
1928
1.18M
    , m_command(move(command))
1929
1.18M
    , m_capture_stdout(capture_stdout)
1930
1.18M
{
1931
1.18M
    if (m_command->is_syntax_error())
1932
411k
        set_is_syntax_error(m_command->syntax_error_node());
1933
1.18M
}
1934
1935
Execute::~Execute()
1936
1.18M
{
1937
1.18M
}
1938
1939
ErrorOr<void> IfCond::dump(int level) const
1940
0
{
1941
0
    TRY(Node::dump(level));
1942
0
    print_indented(++level, "Condition");
1943
0
    TRY(m_condition->dump(level + 1));
1944
0
    print_indented(level, "True Branch");
1945
0
    if (m_true_branch)
1946
0
        TRY(m_true_branch->dump(level + 1));
1947
0
    else
1948
0
        print_indented(level + 1, "(empty)");
1949
0
    print_indented(level, "False Branch");
1950
0
    if (m_false_branch)
1951
0
        TRY(m_false_branch->dump(level + 1));
1952
0
    else
1953
0
        print_indented(level + 1, "(empty)");
1954
1955
0
    return {};
1956
0
}
1957
1958
ErrorOr<RefPtr<Value>> IfCond::run(RefPtr<Shell> shell)
1959
0
{
1960
0
    auto cond = TRY(TRY(m_condition->run(shell))->resolve_without_cast(shell));
1961
0
    if (shell && shell->has_any_error())
1962
0
        return make_ref_counted<ListValue>({});
1963
1964
    // The condition could be a builtin, in which case it has already run and exited.
1965
0
    if (cond->is_job()) {
1966
0
        auto cond_job_value = static_cast<JobValue const*>(cond.ptr());
1967
0
        auto cond_job = cond_job_value->job();
1968
1969
0
        shell->block_on_job(cond_job);
1970
0
    }
1971
0
    if (shell->last_return_code == 0) {
1972
0
        if (m_true_branch)
1973
0
            return m_true_branch->run(shell);
1974
0
    } else {
1975
0
        if (m_false_branch)
1976
0
            return m_false_branch->run(shell);
1977
0
    }
1978
1979
0
    return make_ref_counted<ListValue>({});
1980
0
}
1981
1982
ErrorOr<void> IfCond::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
1983
0
{
1984
0
    metadata.is_first_in_list = true;
1985
1986
0
    editor.stylize({ m_position.start_offset, m_position.start_offset + 2 }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
1987
0
    if (m_else_position.has_value())
1988
0
        editor.stylize({ m_else_position.value().start_offset, m_else_position.value().start_offset + 4 }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
1989
1990
0
    TRY(m_condition->highlight_in_editor(editor, shell, metadata));
1991
0
    if (m_true_branch)
1992
0
        TRY(m_true_branch->highlight_in_editor(editor, shell, metadata));
1993
0
    if (m_false_branch)
1994
0
        TRY(m_false_branch->highlight_in_editor(editor, shell, metadata));
1995
0
    return {};
1996
0
}
1997
1998
HitTestResult IfCond::hit_test_position(size_t offset) const
1999
0
{
2000
0
    if (auto result = m_condition->hit_test_position(offset); result.matching_node)
2001
0
        return result;
2002
2003
0
    if (m_true_branch) {
2004
0
        if (auto result = m_true_branch->hit_test_position(offset); result.matching_node)
2005
0
            return result;
2006
0
    }
2007
2008
0
    if (m_false_branch) {
2009
0
        if (auto result = m_false_branch->hit_test_position(offset); result.matching_node)
2010
0
            return result;
2011
0
    }
2012
2013
0
    return {};
2014
0
}
2015
2016
IfCond::IfCond(Position position, Optional<Position> else_position, NonnullRefPtr<Node> condition, RefPtr<Node> true_branch, RefPtr<Node> false_branch)
2017
44.6k
    : Node(move(position))
2018
44.6k
    , m_condition(move(condition))
2019
44.6k
    , m_true_branch(move(true_branch))
2020
44.6k
    , m_false_branch(move(false_branch))
2021
44.6k
    , m_else_position(move(else_position))
2022
44.6k
{
2023
44.6k
    if (m_condition->is_syntax_error())
2024
12.1k
        set_is_syntax_error(m_condition->syntax_error_node());
2025
32.4k
    else if (m_true_branch && m_true_branch->is_syntax_error())
2026
2.64k
        set_is_syntax_error(m_true_branch->syntax_error_node());
2027
29.7k
    else if (m_false_branch && m_false_branch->is_syntax_error())
2028
2.05k
        set_is_syntax_error(m_false_branch->syntax_error_node());
2029
2030
44.6k
    m_condition = make_ref_counted<AST::Execute>(m_condition->position(), m_condition);
2031
2032
44.6k
    if (m_true_branch) {
2033
44.6k
        auto true_branch = m_true_branch.release_nonnull();
2034
44.6k
        if (true_branch->is_execute())
2035
2.81k
            m_true_branch = static_ptr_cast<AST::Execute>(true_branch)->command();
2036
41.8k
        else
2037
41.8k
            m_true_branch = move(true_branch);
2038
44.6k
    }
2039
2040
44.6k
    if (m_false_branch) {
2041
4.87k
        auto false_branch = m_false_branch.release_nonnull();
2042
4.87k
        if (false_branch->is_execute())
2043
0
            m_false_branch = static_ptr_cast<AST::Execute>(false_branch)->command();
2044
4.87k
        else
2045
4.87k
            m_false_branch = move(false_branch);
2046
4.87k
    }
2047
44.6k
}
2048
2049
IfCond::~IfCond()
2050
44.6k
{
2051
44.6k
}
2052
2053
ErrorOr<void> ImmediateExpression::dump(int level) const
2054
0
{
2055
0
    TRY(Node::dump(level));
2056
0
    print_indented(level + 1, "(function)"sv);
2057
0
    print_indented(level + 2, "{}", m_function.name);
2058
0
    print_indented(level + 1, "(arguments)");
2059
0
    for (auto& argument : arguments())
2060
0
        TRY(argument->dump(level + 2));
2061
2062
0
    return {};
2063
0
}
2064
2065
ErrorOr<RefPtr<Value>> ImmediateExpression::run(RefPtr<Shell> shell)
2066
0
{
2067
0
    auto node = TRY(shell->run_immediate_function(m_function.name, *this, arguments()));
2068
0
    if (node)
2069
0
        return node->run(shell);
2070
2071
0
    return make_ref_counted<ListValue>({});
2072
0
}
2073
2074
ErrorOr<void> ImmediateExpression::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
2075
0
{
2076
    // '${' - FIXME: This could also be '$\\\n{'
2077
0
    editor.stylize({ m_position.start_offset, m_position.start_offset + 2 }, { Line::Style::Foreground(Line::Style::XtermColor::Green) });
2078
2079
    // Function name
2080
0
    Line::Style function_style { Line::Style::Foreground(Line::Style::XtermColor::Red) };
2081
0
    if (shell.has_immediate_function(function_name()))
2082
0
        function_style = { Line::Style::Foreground(Line::Style::XtermColor::Green) };
2083
0
    editor.stylize({ m_function.position.start_offset, m_function.position.end_offset }, move(function_style));
2084
2085
    // Arguments
2086
0
    for (auto& argument : m_arguments) {
2087
0
        metadata.is_first_in_list = false;
2088
0
        TRY(argument->highlight_in_editor(editor, shell, metadata));
2089
0
    }
2090
2091
    // Closing brace
2092
0
    if (m_closing_brace_position.has_value())
2093
0
        editor.stylize({ m_closing_brace_position->start_offset, m_closing_brace_position->end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Green) });
2094
2095
0
    return {};
2096
0
}
2097
2098
ErrorOr<Vector<Line::CompletionSuggestion>> ImmediateExpression::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result) const
2099
0
{
2100
0
    auto matching_node = hit_test_result.matching_node;
2101
0
    if (!matching_node || matching_node != this)
2102
0
        return Vector<Line::CompletionSuggestion> {};
2103
2104
0
    auto corrected_offset = offset - m_function.position.start_offset;
2105
2106
0
    if (corrected_offset > m_function.name.bytes_as_string_view().length())
2107
0
        return Vector<Line::CompletionSuggestion> {};
2108
2109
0
    return shell.complete_immediate_function_name(m_function.name, corrected_offset);
2110
0
}
2111
2112
HitTestResult ImmediateExpression::hit_test_position(size_t offset) const
2113
0
{
2114
0
    if (m_function.position.contains(offset))
2115
0
        return { this, this, this };
2116
2117
0
    for (auto& argument : m_arguments) {
2118
0
        if (auto result = argument->hit_test_position(offset); result.matching_node)
2119
0
            return result;
2120
0
    }
2121
2122
0
    return {};
2123
0
}
2124
2125
ImmediateExpression::ImmediateExpression(Position position, NameWithPosition function, Vector<NonnullRefPtr<AST::Node>> arguments, Optional<Position> closing_brace_position)
2126
868k
    : Node(move(position))
2127
868k
    , m_arguments(move(arguments))
2128
868k
    , m_function(move(function))
2129
868k
    , m_closing_brace_position(move(closing_brace_position))
2130
868k
{
2131
868k
    if (is_syntax_error())
2132
0
        return;
2133
2134
868k
    for (auto& argument : m_arguments) {
2135
868k
        if (argument->is_syntax_error()) {
2136
34.5k
            set_is_syntax_error(argument->syntax_error_node());
2137
34.5k
            return;
2138
34.5k
        }
2139
868k
    }
2140
868k
}
2141
2142
ImmediateExpression::~ImmediateExpression()
2143
868k
{
2144
868k
}
2145
2146
ErrorOr<void> Join::dump(int level) const
2147
0
{
2148
0
    TRY(Node::dump(level));
2149
0
    TRY(m_left->dump(level + 1));
2150
0
    TRY(m_right->dump(level + 1));
2151
0
    return {};
2152
0
}
2153
2154
ErrorOr<RefPtr<Value>> Join::run(RefPtr<Shell> shell)
2155
0
{
2156
0
    auto left = TRY(m_left->to_lazy_evaluated_commands(shell));
2157
0
    if (shell && shell->has_any_error())
2158
0
        return make_ref_counted<ListValue>({});
2159
2160
0
    if (left.last().should_wait && !left.last().next_chain.is_empty()) {
2161
        // Join (C0s*; C1) X -> (C0s*; Join C1 X)
2162
0
        auto& lhs_node = left.last().next_chain.last().node;
2163
0
        lhs_node = make_ref_counted<Join>(m_position, lhs_node, m_right);
2164
0
        return make_ref_counted<CommandSequenceValue>(move(left));
2165
0
    }
2166
2167
0
    auto right = TRY(m_right->to_lazy_evaluated_commands(shell));
2168
0
    if (shell && shell->has_any_error())
2169
0
        return make_ref_counted<ListValue>({});
2170
2171
0
    return make_ref_counted<CommandSequenceValue>(join_commands(move(left), move(right)));
2172
0
}
2173
2174
ErrorOr<void> Join::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
2175
0
{
2176
0
    TRY(m_left->highlight_in_editor(editor, shell, metadata));
2177
0
    if (m_left->is_list() || m_left->is_command())
2178
0
        metadata.is_first_in_list = false;
2179
0
    return m_right->highlight_in_editor(editor, shell, metadata);
2180
0
}
2181
2182
HitTestResult Join::hit_test_position(size_t offset) const
2183
0
{
2184
0
    auto result = m_left->hit_test_position(offset);
2185
0
    if (result.matching_node)
2186
0
        return result;
2187
2188
0
    return m_right->hit_test_position(offset);
2189
0
}
2190
2191
RefPtr<Node const> Join::leftmost_trivial_literal() const
2192
0
{
2193
0
    if (auto value = m_left->leftmost_trivial_literal())
2194
0
        return value;
2195
0
    return m_right->leftmost_trivial_literal();
2196
0
}
2197
2198
Join::Join(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right)
2199
421k
    : Node(move(position))
2200
421k
    , m_left(move(left))
2201
421k
    , m_right(move(right))
2202
421k
{
2203
421k
    if (m_left->is_syntax_error())
2204
302k
        set_is_syntax_error(m_left->syntax_error_node());
2205
119k
    else if (m_right->is_syntax_error())
2206
22.1k
        set_is_syntax_error(m_right->syntax_error_node());
2207
421k
}
2208
2209
Join::~Join()
2210
421k
{
2211
421k
}
2212
2213
ErrorOr<void> MatchExpr::dump(int level) const
2214
0
{
2215
0
    TRY(Node::dump(level));
2216
0
    print_indented(level + 1, "(expression: {})", m_expr_name);
2217
0
    TRY(m_matched_expr->dump(level + 2));
2218
0
    print_indented(level + 1, "(named: {})", m_expr_name);
2219
0
    print_indented(level + 1, "(entries)");
2220
0
    for (auto& entry : m_entries) {
2221
0
        StringBuilder builder;
2222
0
        builder.append("(match"sv);
2223
0
        if (entry.match_names.has_value()) {
2224
0
            builder.append(" to names ("sv);
2225
0
            bool first = true;
2226
0
            for (auto& name : entry.match_names.value()) {
2227
0
                if (!first)
2228
0
                    builder.append(' ');
2229
0
                first = false;
2230
0
                builder.append(name);
2231
0
            }
2232
0
            builder.append("))"sv);
2233
2234
0
        } else {
2235
0
            builder.append(')');
2236
0
        }
2237
0
        print_indented(level + 2, "{}", builder.string_view());
2238
0
        TRY(entry.options.visit(
2239
0
            [&](Vector<NonnullRefPtr<Node>> const& options) -> ErrorOr<void> {
2240
0
                for (auto& option : options)
2241
0
                    TRY(option->dump(level + 3));
2242
0
                return {};
2243
0
            },
2244
0
            [&](Vector<Regex<ECMA262>> const& options) -> ErrorOr<void> {
2245
0
                for (auto& option : options)
2246
0
                    print_indented(level + 3, "(regex: {})", option.pattern_value);
2247
0
                return {};
2248
0
            }));
2249
0
        print_indented(level + 2, "(execute)");
2250
0
        if (entry.body)
2251
0
            TRY(entry.body->dump(level + 3));
2252
0
        else
2253
0
            print_indented(level + 3, "(nothing)"sv);
2254
0
    }
2255
0
    return {};
2256
0
}
2257
2258
ErrorOr<RefPtr<Value>> MatchExpr::run(RefPtr<Shell> shell)
2259
0
{
2260
0
    auto value = TRY(TRY(m_matched_expr->run(shell))->resolve_without_cast(shell));
2261
0
    if (shell && shell->has_any_error())
2262
0
        return make_ref_counted<ListValue>({});
2263
2264
0
    auto list = TRY(value->resolve_as_list(shell));
2265
2266
0
    auto list_matches = [&](auto&& pattern, auto& spans) -> ErrorOr<bool> {
2267
0
        if constexpr (IsSame<RemoveCVReference<decltype(pattern)>, Regex<ECMA262>>) {
2268
0
            if (list.size() != 1)
2269
0
                return false;
2270
0
            auto& subject = list.first();
2271
0
            auto match = pattern.match(subject);
2272
0
            if (!match.success)
2273
0
                return false;
2274
2275
0
            spans.ensure_capacity(match.n_capture_groups);
2276
0
            for (size_t i = 0; i < match.n_capture_groups; ++i) {
2277
0
                auto& capture = match.capture_group_matches[0][i];
2278
0
                spans.append(TRY(capture.view.to_string()));
2279
0
            }
2280
0
            return true;
2281
0
        } else {
2282
0
            if (pattern.size() != list.size())
2283
0
                return false;
2284
2285
0
            for (size_t i = 0; i < pattern.size(); ++i) {
2286
0
                Vector<AK::MaskSpan> mask_spans;
2287
0
                if (!list[i].bytes_as_string_view().matches(pattern[i], mask_spans))
2288
0
                    return false;
2289
0
                for (auto& span : mask_spans)
2290
0
                    spans.append(TRY(list[i].substring_from_byte_offset(span.start, span.length)));
2291
0
            }
2292
2293
0
            return true;
2294
0
        }
2295
0
    };
Unexecuted instantiation: AST.cpp:AK::ErrorOr<bool, AK::Error> Shell::AST::MatchExpr::run(AK::RefPtr<Shell::Shell>)::$_2::operator()<AK::Vector<AK::String, 0ul>, AK::Vector<AK::String, 0ul> >(AK::Vector<AK::String, 0ul>&&, AK::Vector<AK::String, 0ul>&) const
Unexecuted instantiation: AST.cpp:AK::ErrorOr<bool, AK::Error> Shell::AST::MatchExpr::run(AK::RefPtr<Shell::Shell>)::$_2::operator()<regex::Regex<regex::ECMA262Parser>, AK::Vector<AK::String, 0ul> >(regex::Regex<regex::ECMA262Parser>&&, AK::Vector<AK::String, 0ul>&) const
2296
2297
0
    auto resolve_pattern = [&](auto& option) -> decltype(auto) {
2298
0
        if constexpr (IsSame<RemoveCVReference<decltype(option)>, Regex<ECMA262>>) {
2299
0
            return ErrorOr<Regex<ECMA262>>(move(option));
2300
0
        } else {
2301
0
            Vector<String> pattern;
2302
0
            if (option->is_glob()) {
2303
0
                pattern.append(static_cast<Glob const*>(option.ptr())->text());
2304
0
            } else if (option->is_bareword()) {
2305
0
                pattern.append(static_cast<BarewordLiteral const*>(option.ptr())->text());
2306
0
            } else {
2307
0
                auto list_or_error = option->run(shell);
2308
0
                if (list_or_error.is_error() || (shell && shell->has_any_error()))
2309
0
                    return ErrorOr<Vector<String>>(move(pattern));
2310
2311
0
                auto list = list_or_error.release_value();
2312
0
                auto result = option->for_each_entry(shell, [&](auto&& value) -> ErrorOr<IterationDecision> {
2313
0
                    pattern.extend(TRY(value->resolve_as_list(nullptr))); // Note: 'nullptr' incurs special behavior,
2314
                                                                          //       asking the node for a 'raw' value.
2315
0
                    return IterationDecision::Continue;
2316
0
                });
2317
2318
0
                if (result.is_error())
2319
0
                    return ErrorOr<Vector<String>>(result.release_error());
2320
0
            }
2321
2322
0
            return ErrorOr<Vector<String>>(move(pattern));
2323
0
        }
2324
0
    };
Unexecuted instantiation: AST.cpp:decltype(auto) Shell::AST::MatchExpr::run(AK::RefPtr<Shell::Shell>)::$_1::operator()<AK::NonnullRefPtr<Shell::AST::Node> >(AK::NonnullRefPtr<Shell::AST::Node>&) const
Unexecuted instantiation: AST.cpp:decltype(auto) Shell::AST::MatchExpr::run(AK::RefPtr<Shell::Shell>)::$_1::operator()<regex::Regex<regex::ECMA262Parser> >(regex::Regex<regex::ECMA262Parser>&) const
2325
2326
0
    auto frame = shell->push_frame(ByteString::formatted("match ({})", this));
2327
0
    if (!m_expr_name.is_empty())
2328
0
        shell->set_local_variable(m_expr_name.to_byte_string(), value, true);
2329
2330
0
    for (auto& entry : m_entries) {
2331
0
        auto result = TRY(entry.options.visit([&](auto& options) -> ErrorOr<Variant<IterationDecision, RefPtr<Value>>> {
2332
0
            for (auto& option : options) {
2333
0
                Vector<String> spans;
2334
0
                if (TRY(list_matches(TRY(resolve_pattern(option)), spans))) {
2335
0
                    if (entry.body) {
2336
0
                        if (entry.match_names.has_value()) {
2337
0
                            size_t i = 0;
2338
0
                            for (auto& name : entry.match_names.value()) {
2339
0
                                if (spans.size() > i)
2340
0
                                    shell->set_local_variable(name.to_byte_string(), make_ref_counted<AST::StringValue>(spans[i]), true);
2341
0
                                ++i;
2342
0
                            }
2343
0
                        }
2344
0
                        return TRY(entry.body->run(shell));
2345
0
                    }
2346
0
                    return RefPtr<Value>(make_ref_counted<AST::ListValue>({}));
2347
0
                }
2348
0
            }
2349
0
            return IterationDecision::Continue;
2350
0
        }));
2351
0
        if (result.has<IterationDecision>() && result.get<IterationDecision>() == IterationDecision::Break)
2352
0
            break;
2353
2354
0
        if (result.has<RefPtr<Value>>())
2355
0
            return move(result).get<RefPtr<Value>>();
2356
0
    }
2357
2358
    // Non-exhaustive 'case' statements are valid in POSIX.
2359
0
    if (!shell || !shell->posix_mode())
2360
0
        shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "Non-exhaustive match rules!", position());
2361
0
    return make_ref_counted<AST::ListValue>({});
2362
0
}
2363
2364
ErrorOr<void> MatchExpr::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
2365
0
{
2366
0
    editor.stylize({ m_position.start_offset, m_position.start_offset + 5 }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
2367
0
    if (m_as_position.has_value())
2368
0
        editor.stylize({ m_as_position.value().start_offset, m_as_position.value().end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
2369
2370
0
    metadata.is_first_in_list = false;
2371
0
    TRY(m_matched_expr->highlight_in_editor(editor, shell, metadata));
2372
2373
0
    for (auto& entry : m_entries) {
2374
0
        metadata.is_first_in_list = false;
2375
0
        TRY(entry.options.visit(
2376
0
            [&](Vector<NonnullRefPtr<Node>>& node_options) -> ErrorOr<void> {
2377
0
                for (auto& option : node_options)
2378
0
                    TRY(option->highlight_in_editor(editor, shell, metadata));
2379
0
                return {};
2380
0
            },
2381
0
            [](auto&) -> ErrorOr<void> { return {}; }));
2382
2383
0
        metadata.is_first_in_list = true;
2384
0
        if (entry.body)
2385
0
            TRY(entry.body->highlight_in_editor(editor, shell, metadata));
2386
2387
0
        for (auto& position : entry.pipe_positions)
2388
0
            editor.stylize({ position.start_offset, position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
2389
2390
0
        if (entry.match_as_position.has_value())
2391
0
            editor.stylize({ entry.match_as_position.value().start_offset, entry.match_as_position.value().end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
2392
0
    }
2393
2394
0
    return {};
2395
0
}
2396
2397
HitTestResult MatchExpr::hit_test_position(size_t offset) const
2398
0
{
2399
0
    auto result = m_matched_expr->hit_test_position(offset);
2400
0
    if (result.matching_node)
2401
0
        return result;
2402
2403
0
    for (auto& entry : m_entries) {
2404
0
        if (!entry.body)
2405
0
            continue;
2406
0
        auto result = entry.body->hit_test_position(offset);
2407
0
        if (result.matching_node)
2408
0
            return result;
2409
0
    }
2410
2411
0
    return {};
2412
0
}
2413
2414
MatchExpr::MatchExpr(Position position, NonnullRefPtr<Node> expr, String name, Optional<Position> as_position, Vector<MatchEntry> entries)
2415
38.9k
    : Node(move(position))
2416
38.9k
    , m_matched_expr(move(expr))
2417
38.9k
    , m_expr_name(move(name))
2418
38.9k
    , m_as_position(move(as_position))
2419
38.9k
    , m_entries(move(entries))
2420
38.9k
{
2421
38.9k
    if (m_matched_expr->is_syntax_error()) {
2422
36.4k
        set_is_syntax_error(m_matched_expr->syntax_error_node());
2423
36.4k
    } else {
2424
2.45k
        for (auto& entry : m_entries) {
2425
2.44k
            if (!entry.body)
2426
0
                continue;
2427
2.44k
            if (entry.body->is_syntax_error()) {
2428
2.44k
                set_is_syntax_error(entry.body->syntax_error_node());
2429
2.44k
                break;
2430
2.44k
            }
2431
2.44k
        }
2432
2.45k
    }
2433
38.9k
}
2434
2435
MatchExpr::~MatchExpr()
2436
38.9k
{
2437
38.9k
}
2438
2439
ErrorOr<void> Or::dump(int level) const
2440
0
{
2441
0
    TRY(Node::dump(level));
2442
0
    TRY(m_left->dump(level + 1));
2443
0
    TRY(m_right->dump(level + 1));
2444
0
    return {};
2445
0
}
2446
2447
ErrorOr<RefPtr<Value>> Or::run(RefPtr<Shell> shell)
2448
0
{
2449
0
    auto commands = TRY(m_left->to_lazy_evaluated_commands(shell));
2450
0
    if (shell && shell->has_any_error())
2451
0
        return make_ref_counted<ListValue>({});
2452
2453
0
    commands.last().next_chain.empend(*m_right, NodeWithAction::Or);
2454
0
    return make_ref_counted<CommandSequenceValue>(move(commands));
2455
0
}
2456
2457
ErrorOr<void> Or::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
2458
0
{
2459
0
    TRY(m_left->highlight_in_editor(editor, shell, metadata));
2460
0
    return m_right->highlight_in_editor(editor, shell, metadata);
2461
0
}
2462
2463
HitTestResult Or::hit_test_position(size_t offset) const
2464
0
{
2465
0
    auto result = m_left->hit_test_position(offset);
2466
0
    if (result.matching_node) {
2467
0
        if (!result.closest_command_node)
2468
0
            result.closest_command_node = m_right;
2469
0
        return result;
2470
0
    }
2471
2472
0
    result = m_right->hit_test_position(offset);
2473
0
    if (!result.closest_command_node)
2474
0
        result.closest_command_node = m_right;
2475
0
    return result;
2476
0
}
2477
2478
Or::Or(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right, Position or_position)
2479
397k
    : Node(move(position))
2480
397k
    , m_left(move(left))
2481
397k
    , m_right(move(right))
2482
397k
    , m_or_position(or_position)
2483
397k
{
2484
397k
    if (m_left->is_syntax_error())
2485
320k
        set_is_syntax_error(m_left->syntax_error_node());
2486
76.3k
    else if (m_right->is_syntax_error())
2487
75.6k
        set_is_syntax_error(m_right->syntax_error_node());
2488
397k
}
2489
2490
Or::~Or()
2491
397k
{
2492
397k
}
2493
2494
ErrorOr<void> Pipe::dump(int level) const
2495
0
{
2496
0
    TRY(Node::dump(level));
2497
0
    TRY(m_left->dump(level + 1));
2498
0
    TRY(m_right->dump(level + 1));
2499
0
    return {};
2500
0
}
2501
2502
ErrorOr<RefPtr<Value>> Pipe::run(RefPtr<Shell> shell)
2503
0
{
2504
0
    auto left = TRY(m_left->to_lazy_evaluated_commands(shell));
2505
0
    if (shell && shell->has_any_error())
2506
0
        return make_ref_counted<ListValue>({});
2507
2508
0
    auto right = TRY(m_right->to_lazy_evaluated_commands(shell));
2509
0
    if (shell && shell->has_any_error())
2510
0
        return make_ref_counted<ListValue>({});
2511
2512
0
    auto last_in_left = left.take_last();
2513
0
    auto first_in_right = right.take_first();
2514
2515
0
    auto pipe_read_end = FdRedirection::create(-1, STDIN_FILENO, Rewiring::Close::Old);
2516
0
    auto pipe_write_end = FdRedirection::create(-1, STDOUT_FILENO, pipe_read_end, Rewiring::Close::RefreshOld);
2517
2518
0
    auto insert_at_start_or_after_last_pipe = [&](auto& pipe, auto& command) {
2519
0
        size_t insert_index = 0;
2520
0
        auto& redirections = command.redirections;
2521
0
        for (ssize_t i = redirections.size() - 1; i >= 0; --i) {
2522
0
            auto& redirection = redirections[i];
2523
0
            if (!redirection->is_fd_redirection())
2524
0
                continue;
2525
0
            auto& fd_redirection = static_cast<FdRedirection&>(*redirection);
2526
0
            if (fd_redirection.old_fd == -1) {
2527
0
                insert_index = i;
2528
0
                break;
2529
0
            }
2530
0
        }
2531
2532
0
        redirections.insert(insert_index, pipe);
2533
0
    };
2534
2535
0
    insert_at_start_or_after_last_pipe(pipe_read_end, first_in_right);
2536
0
    insert_at_start_or_after_last_pipe(pipe_write_end, last_in_left);
2537
2538
0
    last_in_left.should_wait = false;
2539
0
    last_in_left.is_pipe_source = true;
2540
2541
0
    if (first_in_right.pipeline) {
2542
0
        last_in_left.pipeline = first_in_right.pipeline;
2543
0
    } else {
2544
0
        auto pipeline = make_ref_counted<Pipeline>();
2545
0
        last_in_left.pipeline = pipeline;
2546
0
        first_in_right.pipeline = pipeline;
2547
0
    }
2548
2549
0
    Vector<Command> commands;
2550
0
    commands.extend(left);
2551
0
    commands.append(last_in_left);
2552
0
    commands.append(first_in_right);
2553
0
    commands.extend(right);
2554
2555
0
    return make_ref_counted<CommandSequenceValue>(move(commands));
2556
0
}
2557
2558
ErrorOr<void> Pipe::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
2559
0
{
2560
0
    TRY(m_left->highlight_in_editor(editor, shell, metadata));
2561
0
    return m_right->highlight_in_editor(editor, shell, metadata);
2562
0
}
2563
2564
HitTestResult Pipe::hit_test_position(size_t offset) const
2565
0
{
2566
0
    auto result = m_left->hit_test_position(offset);
2567
0
    if (result.matching_node) {
2568
0
        if (!result.closest_command_node)
2569
0
            result.closest_command_node = m_right;
2570
0
        return result;
2571
0
    }
2572
2573
0
    result = m_right->hit_test_position(offset);
2574
0
    if (!result.closest_command_node)
2575
0
        result.closest_command_node = m_right;
2576
0
    return result;
2577
0
}
2578
2579
Pipe::Pipe(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right)
2580
868k
    : Node(move(position))
2581
868k
    , m_left(move(left))
2582
868k
    , m_right(move(right))
2583
868k
{
2584
868k
    if (m_left->is_syntax_error())
2585
519k
        set_is_syntax_error(m_left->syntax_error_node());
2586
348k
    else if (m_right->is_syntax_error())
2587
2.71k
        set_is_syntax_error(m_right->syntax_error_node());
2588
868k
}
2589
2590
Pipe::~Pipe()
2591
868k
{
2592
868k
}
2593
2594
PathRedirectionNode::PathRedirectionNode(Position position, int fd, NonnullRefPtr<Node> path)
2595
764k
    : Node(move(position))
2596
764k
    , m_fd(fd)
2597
764k
    , m_path(move(path))
2598
764k
{
2599
764k
}
2600
2601
ErrorOr<void> PathRedirectionNode::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
2602
0
{
2603
0
    editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(0x87, 0x9b, 0xcd) }); // 25% Darkened Periwinkle
2604
0
    metadata.is_first_in_list = false;
2605
0
    TRY(m_path->highlight_in_editor(editor, shell, metadata));
2606
2607
0
    if (m_path->is_bareword()) {
2608
0
        auto path_text = TRY(TRY(m_path->run(nullptr))->resolve_as_list(nullptr));
2609
0
        VERIFY(path_text.size() == 1);
2610
        // Apply a URL to the path.
2611
0
        auto& position = m_path->position();
2612
0
        auto& path = path_text[0];
2613
0
        if (!path.starts_with('/'))
2614
0
            path = TRY(String::formatted("{}/{}", shell.cwd, path));
2615
0
        TRY(highlight_filesystem_path_without_resolving(path, editor, shell, position.start_offset, position.end_offset));
2616
0
    }
2617
2618
0
    return {};
2619
0
}
2620
2621
HitTestResult PathRedirectionNode::hit_test_position(size_t offset) const
2622
0
{
2623
0
    auto result = m_path->hit_test_position(offset);
2624
0
    if (!result.closest_node_with_semantic_meaning)
2625
0
        result.closest_node_with_semantic_meaning = this;
2626
0
    return result;
2627
0
}
2628
2629
ErrorOr<Vector<Line::CompletionSuggestion>> PathRedirectionNode::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result) const
2630
0
{
2631
0
    auto matching_node = hit_test_result.matching_node;
2632
0
    if (!matching_node || !matching_node->is_bareword())
2633
0
        return Vector<Line::CompletionSuggestion> {};
2634
2635
0
    auto corrected_offset = offset - matching_node->position().start_offset;
2636
0
    auto* node = static_cast<BarewordLiteral const*>(matching_node.ptr());
2637
2638
0
    if (corrected_offset > node->text().bytes_as_string_view().length())
2639
0
        return Vector<Line::CompletionSuggestion> {};
2640
2641
0
    return shell.complete_path(""sv, node->text(), corrected_offset, Shell::ExecutableOnly::No, nullptr, nullptr);
2642
0
}
2643
2644
PathRedirectionNode::~PathRedirectionNode()
2645
764k
{
2646
764k
}
2647
2648
ErrorOr<void> Range::dump(int level) const
2649
0
{
2650
0
    TRY(Node::dump(level));
2651
0
    print_indented(level + 1, "(From)");
2652
0
    TRY(m_start->dump(level + 2));
2653
0
    print_indented(level + 1, "(To)");
2654
0
    TRY(m_end->dump(level + 2));
2655
0
    return {};
2656
0
}
2657
2658
ErrorOr<RefPtr<Value>> Range::run(RefPtr<Shell> shell)
2659
0
{
2660
0
    auto interpolate = [position = position()](RefPtr<Value> start, RefPtr<Value> end, RefPtr<Shell> shell) -> ErrorOr<Vector<NonnullRefPtr<Value>>> {
2661
0
        Vector<NonnullRefPtr<Value>> values;
2662
2663
0
        if (start->is_string() && end->is_string()) {
2664
0
            auto start_str = TRY(start->resolve_as_list(shell))[0];
2665
0
            auto end_str = TRY(end->resolve_as_list(shell))[0];
2666
2667
0
            Utf8View start_view { start_str }, end_view { end_str };
2668
0
            if (start_view.validate() && end_view.validate()) {
2669
0
                if (start_view.length() == 1 && end_view.length() == 1) {
2670
                    // Interpolate between two code points.
2671
0
                    auto start_code_point = *start_view.begin();
2672
0
                    auto end_code_point = *end_view.begin();
2673
0
                    auto step = start_code_point > end_code_point ? -1 : 1;
2674
0
                    StringBuilder builder;
2675
0
                    for (u32 code_point = start_code_point; code_point != end_code_point; code_point += step) {
2676
0
                        builder.clear();
2677
0
                        builder.append_code_point(code_point);
2678
0
                        values.append(make_ref_counted<StringValue>(TRY(builder.to_string())));
2679
0
                    }
2680
                    // Append the ending code point too, most shells treat this as inclusive.
2681
0
                    builder.clear();
2682
0
                    builder.append_code_point(end_code_point);
2683
0
                    values.append(make_ref_counted<StringValue>(TRY(builder.to_string())));
2684
0
                } else {
2685
                    // Could be two numbers?
2686
0
                    auto start_int = start_str.to_number<int>();
2687
0
                    auto end_int = end_str.to_number<int>();
2688
0
                    if (start_int.has_value() && end_int.has_value()) {
2689
0
                        auto start = start_int.value();
2690
0
                        auto end = end_int.value();
2691
0
                        auto step = start > end ? -1 : 1;
2692
0
                        for (int value = start; value != end; value += step)
2693
0
                            values.append(make_ref_counted<StringValue>(String::number(value)));
2694
                        // Append the range end too, most shells treat this as inclusive.
2695
0
                        values.append(make_ref_counted<StringValue>(String::number(end)));
2696
0
                    } else {
2697
0
                        goto yield_start_end;
2698
0
                    }
2699
0
                }
2700
0
            } else {
2701
0
            yield_start_end:;
2702
0
                shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, ByteString::formatted("Cannot interpolate between '{}' and '{}'!", start_str, end_str), position);
2703
                // We can't really interpolate between the two, so just yield both.
2704
0
                values.append(make_ref_counted<StringValue>(move(start_str)));
2705
0
                values.append(make_ref_counted<StringValue>(move(end_str)));
2706
0
            }
2707
2708
0
            return values;
2709
0
        }
2710
2711
0
        warnln("Shell: Cannot apply the requested interpolation");
2712
0
        return values;
2713
0
    };
2714
2715
0
    auto start_value = TRY(m_start->run(shell));
2716
0
    if (shell && shell->has_any_error())
2717
0
        return make_ref_counted<ListValue>({});
2718
2719
0
    auto end_value = TRY(m_end->run(shell));
2720
0
    if (shell && shell->has_any_error())
2721
0
        return make_ref_counted<ListValue>({});
2722
2723
0
    if (!start_value || !end_value)
2724
0
        return make_ref_counted<ListValue>({});
2725
2726
0
    return make_ref_counted<ListValue>(TRY(interpolate(*start_value, *end_value, shell)));
2727
0
}
2728
2729
ErrorOr<void> Range::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
2730
0
{
2731
0
    TRY(m_start->highlight_in_editor(editor, shell, metadata));
2732
2733
    // Highlight the '..'
2734
0
    editor.stylize({ m_start->position().end_offset, m_end->position().start_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
2735
2736
0
    metadata.is_first_in_list = false;
2737
0
    return m_end->highlight_in_editor(editor, shell, metadata);
2738
0
}
2739
2740
HitTestResult Range::hit_test_position(size_t offset) const
2741
0
{
2742
0
    auto result = m_start->hit_test_position(offset);
2743
0
    if (result.matching_node) {
2744
0
        if (!result.closest_command_node)
2745
0
            result.closest_command_node = m_start;
2746
0
        return result;
2747
0
    }
2748
2749
0
    result = m_end->hit_test_position(offset);
2750
0
    if (!result.closest_command_node)
2751
0
        result.closest_command_node = m_end;
2752
0
    return result;
2753
0
}
2754
2755
Range::Range(Position position, NonnullRefPtr<Node> start, NonnullRefPtr<Node> end)
2756
8.35k
    : Node(move(position))
2757
8.35k
    , m_start(move(start))
2758
8.35k
    , m_end(move(end))
2759
8.35k
{
2760
8.35k
    if (m_start->is_syntax_error())
2761
3.12k
        set_is_syntax_error(m_start->syntax_error_node());
2762
5.22k
    else if (m_end->is_syntax_error())
2763
5.22k
        set_is_syntax_error(m_end->syntax_error_node());
2764
8.35k
}
2765
2766
Range::~Range()
2767
8.35k
{
2768
8.35k
}
2769
2770
ErrorOr<void> ReadRedirection::dump(int level) const
2771
0
{
2772
0
    TRY(Node::dump(level));
2773
0
    TRY(m_path->dump(level + 1));
2774
0
    print_indented(level + 1, "To {}", m_fd);
2775
0
    return {};
2776
0
}
2777
2778
ErrorOr<RefPtr<Value>> ReadRedirection::run(RefPtr<Shell> shell)
2779
0
{
2780
0
    Command command;
2781
0
    auto path_segments = TRY(TRY(m_path->run(shell))->resolve_as_list(shell));
2782
0
    if (shell && shell->has_any_error())
2783
0
        return make_ref_counted<ListValue>({});
2784
2785
0
    StringBuilder builder;
2786
0
    builder.join(' ', path_segments);
2787
2788
0
    command.redirections.append(PathRedirection::create(TRY(builder.to_string()), m_fd, PathRedirection::Read));
2789
0
    return make_ref_counted<CommandValue>(move(command));
2790
0
}
2791
2792
ReadRedirection::ReadRedirection(Position position, int fd, NonnullRefPtr<Node> path)
2793
394k
    : PathRedirectionNode(move(position), fd, move(path))
2794
394k
{
2795
394k
}
2796
2797
ReadRedirection::~ReadRedirection()
2798
{
2799
}
2800
2801
ErrorOr<void> ReadWriteRedirection::dump(int level) const
2802
0
{
2803
0
    TRY(Node::dump(level));
2804
0
    TRY(m_path->dump(level + 1));
2805
0
    print_indented(level + 1, "To/From {}", m_fd);
2806
0
    return {};
2807
0
}
2808
2809
ErrorOr<RefPtr<Value>> ReadWriteRedirection::run(RefPtr<Shell> shell)
2810
0
{
2811
0
    Command command;
2812
0
    auto path_segments = TRY(TRY(m_path->run(shell))->resolve_as_list(shell));
2813
0
    if (shell && shell->has_any_error())
2814
0
        return make_ref_counted<ListValue>({});
2815
2816
0
    StringBuilder builder;
2817
0
    builder.join(' ', path_segments);
2818
2819
0
    command.redirections.append(PathRedirection::create(TRY(builder.to_string()), m_fd, PathRedirection::ReadWrite));
2820
0
    return make_ref_counted<CommandValue>(move(command));
2821
0
}
2822
2823
ReadWriteRedirection::ReadWriteRedirection(Position position, int fd, NonnullRefPtr<Node> path)
2824
25
    : PathRedirectionNode(move(position), fd, move(path))
2825
25
{
2826
25
}
2827
2828
ReadWriteRedirection::~ReadWriteRedirection()
2829
{
2830
}
2831
2832
ErrorOr<void> Sequence::dump(int level) const
2833
0
{
2834
0
    TRY(Node::dump(level));
2835
0
    for (auto& entry : m_entries)
2836
0
        TRY(entry->dump(level + 1));
2837
0
    return {};
2838
0
}
2839
2840
ErrorOr<RefPtr<Value>> Sequence::run(RefPtr<Shell> shell)
2841
0
{
2842
0
    Vector<Command> all_commands;
2843
0
    Command* last_command_in_sequence = nullptr;
2844
0
    for (auto& entry : m_entries) {
2845
0
        if (shell && shell->has_any_error())
2846
0
            break;
2847
0
        if (!last_command_in_sequence) {
2848
0
            auto commands = TRY(entry->to_lazy_evaluated_commands(shell));
2849
0
            all_commands.extend(move(commands));
2850
0
            last_command_in_sequence = &all_commands.last();
2851
0
            continue;
2852
0
        }
2853
2854
0
        if (last_command_in_sequence->should_wait) {
2855
0
            last_command_in_sequence->next_chain.append(NodeWithAction { entry, NodeWithAction::Sequence });
2856
0
        } else {
2857
0
            all_commands.extend(TRY(entry->to_lazy_evaluated_commands(shell)));
2858
0
            last_command_in_sequence = &all_commands.last();
2859
0
        }
2860
0
    }
2861
2862
0
    return make_ref_counted<CommandSequenceValue>(move(all_commands));
2863
0
}
2864
2865
ErrorOr<void> Sequence::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
2866
0
{
2867
0
    for (auto& entry : m_entries)
2868
0
        TRY(entry->highlight_in_editor(editor, shell, metadata));
2869
0
    return {};
2870
0
}
2871
2872
HitTestResult Sequence::hit_test_position(size_t offset) const
2873
0
{
2874
0
    for (auto& entry : m_entries) {
2875
0
        auto result = entry->hit_test_position(offset);
2876
0
        if (result.matching_node) {
2877
0
            if (!result.closest_command_node)
2878
0
                result.closest_command_node = entry;
2879
0
            return result;
2880
0
        }
2881
0
    }
2882
2883
0
    return {};
2884
0
}
2885
2886
RefPtr<Node const> Sequence::leftmost_trivial_literal() const
2887
0
{
2888
0
    for (auto& entry : m_entries) {
2889
0
        if (auto node = entry->leftmost_trivial_literal())
2890
0
            return node;
2891
0
    }
2892
0
    return nullptr;
2893
0
}
2894
2895
Sequence::Sequence(Position position, Vector<NonnullRefPtr<Node>> entries, Vector<Position> separator_positions)
2896
1.41M
    : Node(move(position))
2897
1.41M
    , m_entries(move(entries))
2898
1.41M
    , m_separator_positions(separator_positions)
2899
1.41M
{
2900
2.08M
    for (auto& entry : m_entries) {
2901
2.08M
        if (entry->is_syntax_error()) {
2902
126k
            set_is_syntax_error(entry->syntax_error_node());
2903
126k
            break;
2904
126k
        }
2905
2.08M
    }
2906
1.41M
}
2907
2908
Sequence::~Sequence()
2909
1.41M
{
2910
1.41M
}
2911
2912
ErrorOr<void> Subshell::dump(int level) const
2913
0
{
2914
0
    TRY(Node::dump(level));
2915
0
    if (m_block)
2916
0
        TRY(m_block->dump(level + 1));
2917
0
    return {};
2918
0
}
2919
2920
ErrorOr<RefPtr<Value>> Subshell::run(RefPtr<Shell> shell)
2921
0
{
2922
0
    if (!m_block)
2923
0
        return make_ref_counted<ListValue>({});
2924
2925
0
    return make_ref_counted<AST::CommandSequenceValue>(TRY(m_block->to_lazy_evaluated_commands(shell)));
2926
0
}
2927
2928
ErrorOr<void> Subshell::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
2929
0
{
2930
0
    metadata.is_first_in_list = true;
2931
0
    if (m_block)
2932
0
        TRY(m_block->highlight_in_editor(editor, shell, metadata));
2933
0
    return {};
2934
0
}
2935
2936
HitTestResult Subshell::hit_test_position(size_t offset) const
2937
0
{
2938
0
    if (m_block)
2939
0
        return m_block->hit_test_position(offset);
2940
2941
0
    return {};
2942
0
}
2943
2944
Subshell::Subshell(Position position, RefPtr<Node> block)
2945
217k
    : Node(move(position))
2946
217k
    , m_block(block)
2947
217k
{
2948
217k
    if (m_block && m_block->is_syntax_error())
2949
83.7k
        set_is_syntax_error(m_block->syntax_error_node());
2950
217k
}
2951
2952
Subshell::~Subshell()
2953
217k
{
2954
217k
}
2955
2956
ErrorOr<void> Slice::dump(int level) const
2957
0
{
2958
0
    TRY(Node::dump(level));
2959
0
    TRY(m_selector->dump(level + 1));
2960
0
    return {};
2961
0
}
2962
2963
ErrorOr<RefPtr<Value>> Slice::run(RefPtr<Shell> shell)
2964
0
{
2965
0
    return m_selector->run(shell);
2966
0
}
2967
2968
ErrorOr<void> Slice::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
2969
0
{
2970
0
    return m_selector->highlight_in_editor(editor, shell, metadata);
2971
0
}
2972
2973
HitTestResult Slice::hit_test_position(size_t offset) const
2974
0
{
2975
0
    return m_selector->hit_test_position(offset);
2976
0
}
2977
2978
ErrorOr<Vector<Line::CompletionSuggestion>> Slice::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result) const
2979
0
{
2980
    // TODO: Maybe intercept this, and suggest values in range?
2981
0
    return m_selector->complete_for_editor(shell, offset, hit_test_result);
2982
0
}
2983
2984
Slice::Slice(Position position, NonnullRefPtr<AST::Node> selector)
2985
38.6k
    : Node(move(position))
2986
38.6k
    , m_selector(move(selector))
2987
38.6k
{
2988
38.6k
    if (m_selector->is_syntax_error())
2989
38.0k
        set_is_syntax_error(m_selector->syntax_error_node());
2990
38.6k
}
2991
2992
Slice::~Slice()
2993
38.6k
{
2994
38.6k
}
2995
2996
ErrorOr<void> SimpleVariable::dump(int level) const
2997
0
{
2998
0
    TRY(Node::dump(level));
2999
0
    print_indented(level + 1, "(Name)");
3000
0
    print_indented(level + 2, "{}", m_name);
3001
0
    print_indented(level + 1, "(Slice)");
3002
0
    if (m_slice)
3003
0
        TRY(m_slice->dump(level + 2));
3004
0
    else
3005
0
        print_indented(level + 2, "(None)");
3006
0
    return {};
3007
0
}
3008
3009
ErrorOr<RefPtr<Value>> SimpleVariable::run(RefPtr<Shell>)
3010
0
{
3011
0
    NonnullRefPtr<Value> value = make_ref_counted<SimpleVariableValue>(m_name);
3012
0
    if (m_slice)
3013
0
        value = TRY(value->with_slices(*m_slice));
3014
0
    return value;
3015
0
}
3016
3017
ErrorOr<void> SimpleVariable::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
3018
0
{
3019
0
    Line::Style style { Line::Style::Foreground(214, 112, 214) };
3020
0
    if (metadata.is_first_in_list)
3021
0
        style.unify_with({ Line::Style::Bold });
3022
0
    editor.stylize({ m_position.start_offset, m_position.end_offset }, move(style));
3023
0
    if (m_slice)
3024
0
        TRY(m_slice->highlight_in_editor(editor, shell, metadata));
3025
0
    return {};
3026
0
}
3027
3028
HitTestResult SimpleVariable::hit_test_position(size_t offset) const
3029
0
{
3030
0
    if (!position().contains(offset))
3031
0
        return {};
3032
3033
0
    if (m_slice && m_slice->position().contains(offset))
3034
0
        return m_slice->hit_test_position(offset);
3035
3036
0
    return { this, this, nullptr };
3037
0
}
3038
3039
ErrorOr<Vector<Line::CompletionSuggestion>> SimpleVariable::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result) const
3040
0
{
3041
0
    auto matching_node = hit_test_result.matching_node;
3042
0
    if (!matching_node)
3043
0
        return Vector<Line::CompletionSuggestion> {};
3044
3045
0
    if (matching_node != this)
3046
0
        return Vector<Line::CompletionSuggestion> {};
3047
3048
0
    auto corrected_offset = offset - matching_node->position().start_offset - 1;
3049
3050
0
    if (corrected_offset > m_name.bytes_as_string_view().length() + 1)
3051
0
        return Vector<Line::CompletionSuggestion> {};
3052
3053
0
    return shell.complete_variable(m_name, corrected_offset);
3054
0
}
3055
3056
SimpleVariable::SimpleVariable(Position position, String name)
3057
623k
    : VariableNode(move(position))
3058
623k
    , m_name(move(name))
3059
623k
{
3060
623k
}
3061
3062
SimpleVariable::~SimpleVariable()
3063
623k
{
3064
623k
}
3065
3066
ErrorOr<void> SpecialVariable::dump(int level) const
3067
0
{
3068
0
    TRY(Node::dump(level));
3069
0
    print_indented(level + 1, "(Name)");
3070
0
    print_indented(level + 1, "{:c}", m_name);
3071
0
    print_indented(level + 1, "(Slice)");
3072
0
    if (m_slice)
3073
0
        TRY(m_slice->dump(level + 2));
3074
0
    else
3075
0
        print_indented(level + 2, "(None)");
3076
0
    return {};
3077
0
}
3078
3079
ErrorOr<RefPtr<Value>> SpecialVariable::run(RefPtr<Shell>)
3080
0
{
3081
0
    NonnullRefPtr<Value> value = make_ref_counted<SpecialVariableValue>(m_name);
3082
0
    if (m_slice)
3083
0
        value = TRY(value->with_slices(*m_slice));
3084
0
    return value;
3085
0
}
3086
3087
ErrorOr<void> SpecialVariable::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
3088
0
{
3089
0
    editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(214, 112, 214) });
3090
0
    if (m_slice)
3091
0
        TRY(m_slice->highlight_in_editor(editor, shell, metadata));
3092
0
    return {};
3093
0
}
3094
3095
ErrorOr<Vector<Line::CompletionSuggestion>> SpecialVariable::complete_for_editor(Shell&, size_t, HitTestResult const&) const
3096
0
{
3097
0
    return Vector<Line::CompletionSuggestion> {};
3098
0
}
3099
3100
HitTestResult SpecialVariable::hit_test_position(size_t offset) const
3101
0
{
3102
0
    if (m_slice && m_slice->position().contains(offset))
3103
0
        return m_slice->hit_test_position(offset);
3104
3105
0
    return { this, this, nullptr };
3106
0
}
3107
3108
SpecialVariable::SpecialVariable(Position position, char name)
3109
130k
    : VariableNode(move(position))
3110
130k
    , m_name(name)
3111
130k
{
3112
130k
}
3113
3114
SpecialVariable::~SpecialVariable()
3115
130k
{
3116
130k
}
3117
3118
ErrorOr<void> Juxtaposition::dump(int level) const
3119
0
{
3120
0
    TRY(Node::dump(level));
3121
0
    TRY(m_left->dump(level + 1));
3122
0
    TRY(m_right->dump(level + 1));
3123
0
    return {};
3124
0
}
3125
3126
ErrorOr<RefPtr<Value>> Juxtaposition::run(RefPtr<Shell> shell)
3127
0
{
3128
0
    auto left_value = TRY(TRY(m_left->run(shell))->resolve_without_cast(shell));
3129
0
    if (shell && shell->has_any_error())
3130
0
        return make_ref_counted<ListValue>({});
3131
3132
0
    auto right_value = TRY(TRY(m_right->run(shell))->resolve_without_cast(shell));
3133
0
    if (shell && shell->has_any_error())
3134
0
        return make_ref_counted<ListValue>({});
3135
3136
0
    auto left = TRY(left_value->resolve_as_list(shell));
3137
0
    auto right = TRY(right_value->resolve_as_list(shell));
3138
3139
0
    if (m_mode == Mode::StringExpand) {
3140
0
        Vector<String> result;
3141
0
        result.ensure_capacity(left.size() + right.size());
3142
3143
0
        for (auto& left_item : left)
3144
0
            result.append(left_item);
3145
3146
0
        if (!result.is_empty() && !right.is_empty()) {
3147
0
            auto& last = result.last();
3148
0
            last = TRY(String::formatted("{}{}", last, right.first()));
3149
0
            right.take_first();
3150
0
        }
3151
0
        for (auto& right_item : right)
3152
0
            result.append(right_item);
3153
3154
0
        return make_ref_counted<ListValue>(move(result));
3155
0
    }
3156
3157
0
    if (left_value->is_string() && right_value->is_string()) {
3158
3159
0
        VERIFY(left.size() == 1);
3160
0
        VERIFY(right.size() == 1);
3161
3162
0
        StringBuilder builder;
3163
0
        builder.append(left[0]);
3164
0
        builder.append(right[0]);
3165
3166
0
        return make_ref_counted<StringValue>(TRY(builder.to_string()));
3167
0
    }
3168
3169
    // Otherwise, treat them as lists and create a list product (or just append).
3170
0
    if (left.is_empty() || right.is_empty())
3171
0
        return make_ref_counted<ListValue>({});
3172
3173
0
    Vector<String> result;
3174
0
    result.ensure_capacity(left.size() * right.size());
3175
3176
0
    StringBuilder builder;
3177
0
    for (auto& left_element : left) {
3178
0
        for (auto& right_element : right) {
3179
0
            builder.append(left_element);
3180
0
            builder.append(right_element);
3181
0
            result.append(TRY(builder.to_string()));
3182
0
            builder.clear();
3183
0
        }
3184
0
    }
3185
3186
0
    return make_ref_counted<ListValue>(move(result));
3187
0
}
3188
3189
ErrorOr<void> Juxtaposition::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
3190
0
{
3191
0
    TRY(m_left->highlight_in_editor(editor, shell, metadata));
3192
3193
    // '~/foo/bar' is special, we have to actually resolve the tilde
3194
    // since that resolution is a pure operation, we can just go ahead
3195
    // and do it to get the value :)
3196
0
    if (m_right->is_bareword() && m_left->is_tilde()) {
3197
0
        auto tilde_value = TRY(TRY(m_left->run(shell))->resolve_as_list(shell))[0];
3198
0
        auto bareword_value = TRY(TRY(m_right->run(shell))->resolve_as_list(shell))[0];
3199
3200
0
        StringBuilder path_builder;
3201
0
        path_builder.append(tilde_value);
3202
0
        path_builder.append('/');
3203
0
        path_builder.append(bareword_value);
3204
0
        auto path = path_builder.to_byte_string();
3205
3206
0
        if (FileSystem::exists(path)) {
3207
0
            TRY(highlight_filesystem_path(path, editor, shell, m_position.start_offset, m_position.end_offset));
3208
0
        }
3209
3210
0
    } else {
3211
0
        TRY(m_right->highlight_in_editor(editor, shell, metadata));
3212
0
    }
3213
3214
0
    return {};
3215
0
}
3216
3217
ErrorOr<Vector<Line::CompletionSuggestion>> Juxtaposition::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result) const
3218
0
{
3219
0
    auto matching_node = hit_test_result.matching_node;
3220
0
    if (m_left->would_execute() || m_right->would_execute()) {
3221
0
        return Vector<Line::CompletionSuggestion> {};
3222
0
    }
3223
3224
    // '~/foo/bar' is special, we have to actually resolve the tilde
3225
    // then complete the bareword with that path prefix.
3226
0
    auto left_values = TRY(TRY(m_left->run(shell))->resolve_as_list(shell));
3227
3228
0
    if (left_values.is_empty())
3229
0
        return m_right->complete_for_editor(shell, offset, hit_test_result);
3230
3231
0
    auto& left_value = left_values.first();
3232
3233
0
    auto right_values = TRY(TRY(m_right->run(shell))->resolve_as_list(shell));
3234
0
    StringView right_value {};
3235
3236
0
    auto corrected_offset = offset - matching_node->position().start_offset;
3237
3238
0
    if (!right_values.is_empty())
3239
0
        right_value = right_values.first();
3240
3241
0
    if (m_left->is_tilde() && !right_value.is_empty()) {
3242
0
        right_value = right_value.substring_view(1);
3243
0
        corrected_offset--;
3244
0
    }
3245
3246
0
    if (corrected_offset > right_value.length())
3247
0
        return Vector<Line::CompletionSuggestion> {};
3248
3249
0
    return shell.complete_path(left_value, right_value, corrected_offset, Shell::ExecutableOnly::No, hit_test_result.closest_command_node.ptr(), hit_test_result.matching_node);
3250
0
}
3251
3252
HitTestResult Juxtaposition::hit_test_position(size_t offset) const
3253
0
{
3254
0
    auto result = m_left->hit_test_position(offset);
3255
0
    if (!result.closest_node_with_semantic_meaning)
3256
0
        result.closest_node_with_semantic_meaning = this;
3257
0
    if (result.matching_node)
3258
0
        return result;
3259
3260
0
    result = m_right->hit_test_position(offset);
3261
0
    if (!result.closest_node_with_semantic_meaning)
3262
0
        result.closest_node_with_semantic_meaning = this;
3263
0
    return result;
3264
0
}
3265
3266
Juxtaposition::Juxtaposition(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right, Juxtaposition::Mode mode)
3267
1.94M
    : Node(move(position))
3268
1.94M
    , m_left(move(left))
3269
1.94M
    , m_right(move(right))
3270
1.94M
    , m_mode(mode)
3271
1.94M
{
3272
1.94M
    if (m_left->is_syntax_error())
3273
401k
        set_is_syntax_error(m_left->syntax_error_node());
3274
1.54M
    else if (m_right->is_syntax_error())
3275
89.8k
        set_is_syntax_error(m_right->syntax_error_node());
3276
1.94M
}
3277
3278
Juxtaposition::~Juxtaposition()
3279
1.94M
{
3280
1.94M
}
3281
3282
ErrorOr<void> StringLiteral::dump(int level) const
3283
0
{
3284
0
    TRY(Node::dump(level));
3285
0
    print_indented(level + 1, "{}", m_text);
3286
0
    return {};
3287
0
}
3288
3289
ErrorOr<RefPtr<Value>> StringLiteral::run(RefPtr<Shell>)
3290
0
{
3291
0
    return make_ref_counted<StringValue>(m_text);
3292
0
}
3293
3294
ErrorOr<void> StringLiteral::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata metadata)
3295
0
{
3296
0
    if (m_text.is_empty())
3297
0
        return {};
3298
3299
0
    Line::Style style { Line::Style::Foreground(Line::Style::XtermColor::Yellow) };
3300
0
    if (metadata.is_first_in_list)
3301
0
        style.unify_with({ Line::Style::Bold });
3302
0
    editor.stylize({ m_position.start_offset, m_position.end_offset }, move(style));
3303
3304
0
    return {};
3305
0
}
3306
3307
StringLiteral::StringLiteral(Position position, String text, EnclosureType enclosure_type)
3308
4.16M
    : Node(move(position))
3309
4.16M
    , m_text(move(text))
3310
4.16M
    , m_enclosure_type(enclosure_type)
3311
4.16M
{
3312
4.16M
}
3313
3314
StringLiteral::~StringLiteral()
3315
4.16M
{
3316
4.16M
}
3317
3318
ErrorOr<void> StringPartCompose::dump(int level) const
3319
0
{
3320
0
    TRY(Node::dump(level));
3321
0
    TRY(m_left->dump(level + 1));
3322
0
    TRY(m_right->dump(level + 1));
3323
0
    return {};
3324
0
}
3325
3326
ErrorOr<RefPtr<Value>> StringPartCompose::run(RefPtr<Shell> shell)
3327
0
{
3328
0
    auto left = TRY(TRY(m_left->run(shell))->resolve_as_list(shell));
3329
0
    if (shell && shell->has_any_error())
3330
0
        return make_ref_counted<ListValue>({});
3331
3332
0
    auto right = TRY(TRY(m_right->run(shell))->resolve_as_list(shell));
3333
0
    if (shell && shell->has_any_error())
3334
0
        return make_ref_counted<ListValue>({});
3335
3336
0
    StringBuilder builder;
3337
0
    builder.join(' ', left);
3338
0
    builder.join(' ', right);
3339
3340
0
    return make_ref_counted<StringValue>(TRY(builder.to_string()));
3341
0
}
3342
3343
ErrorOr<void> StringPartCompose::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
3344
0
{
3345
0
    TRY(m_left->highlight_in_editor(editor, shell, metadata));
3346
0
    return m_right->highlight_in_editor(editor, shell, metadata);
3347
0
}
3348
3349
HitTestResult StringPartCompose::hit_test_position(size_t offset) const
3350
0
{
3351
0
    auto result = m_left->hit_test_position(offset);
3352
0
    if (result.matching_node)
3353
0
        return result;
3354
0
    return m_right->hit_test_position(offset);
3355
0
}
3356
3357
StringPartCompose::StringPartCompose(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right)
3358
22.5k
    : Node(move(position))
3359
22.5k
    , m_left(move(left))
3360
22.5k
    , m_right(move(right))
3361
22.5k
{
3362
22.5k
    if (m_left->is_syntax_error())
3363
3.03k
        set_is_syntax_error(m_left->syntax_error_node());
3364
19.5k
    else if (m_right->is_syntax_error())
3365
10.5k
        set_is_syntax_error(m_right->syntax_error_node());
3366
22.5k
}
3367
3368
StringPartCompose::~StringPartCompose()
3369
22.5k
{
3370
22.5k
}
3371
3372
ErrorOr<void> SyntaxError::dump(int level) const
3373
0
{
3374
0
    TRY(Node::dump(level));
3375
0
    print_indented(level + 1, "(Error text)");
3376
0
    print_indented(level + 2, "{}", m_syntax_error_text);
3377
0
    print_indented(level + 1, "(Can be recovered from)");
3378
0
    print_indented(level + 2, "{}", m_is_continuable);
3379
0
    return {};
3380
0
}
3381
3382
ErrorOr<RefPtr<Value>> SyntaxError::run(RefPtr<Shell> shell)
3383
0
{
3384
0
    shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, m_syntax_error_text.to_byte_string(), position());
3385
0
    return make_ref_counted<StringValue>(String {});
3386
0
}
3387
3388
ErrorOr<void> SyntaxError::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
3389
0
{
3390
0
    editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Red), Line::Style::Bold });
3391
0
    return {};
3392
0
}
3393
3394
SyntaxError::SyntaxError(Position position, String error, bool is_continuable)
3395
2.42M
    : Node(move(position))
3396
2.42M
    , m_syntax_error_text(move(error))
3397
2.42M
    , m_is_continuable(is_continuable)
3398
2.42M
{
3399
2.42M
}
3400
3401
SyntaxError& SyntaxError::syntax_error_node()
3402
924k
{
3403
924k
    return *this;
3404
924k
}
3405
3406
SyntaxError::~SyntaxError()
3407
2.42M
{
3408
2.42M
}
3409
3410
ErrorOr<void> SyntheticNode::dump(int level) const
3411
0
{
3412
0
    TRY(Node::dump(level));
3413
0
    return {};
3414
0
}
3415
3416
ErrorOr<RefPtr<Value>> SyntheticNode::run(RefPtr<Shell>)
3417
0
{
3418
0
    return m_value;
3419
0
}
3420
3421
ErrorOr<void> SyntheticNode::highlight_in_editor(Line::Editor&, Shell&, HighlightMetadata)
3422
0
{
3423
0
    return {};
3424
0
}
3425
3426
SyntheticNode::SyntheticNode(Position position, NonnullRefPtr<Value> value)
3427
0
    : Node(move(position))
3428
0
    , m_value(move(value))
3429
0
{
3430
0
}
3431
3432
ErrorOr<void> Tilde::dump(int level) const
3433
0
{
3434
0
    TRY(Node::dump(level));
3435
0
    print_indented(level + 1, "{}", m_username);
3436
0
    return {};
3437
0
}
3438
3439
ErrorOr<RefPtr<Value>> Tilde::run(RefPtr<Shell>)
3440
0
{
3441
0
    return make_ref_counted<TildeValue>(m_username);
3442
0
}
3443
3444
ErrorOr<void> Tilde::highlight_in_editor(Line::Editor&, Shell&, HighlightMetadata)
3445
0
{
3446
0
    return {};
3447
0
}
3448
3449
HitTestResult Tilde::hit_test_position(size_t offset) const
3450
0
{
3451
0
    if (!position().contains(offset))
3452
0
        return {};
3453
3454
0
    return { this, this, nullptr };
3455
0
}
3456
3457
ErrorOr<Vector<Line::CompletionSuggestion>> Tilde::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result) const
3458
0
{
3459
0
    auto matching_node = hit_test_result.matching_node;
3460
0
    if (!matching_node)
3461
0
        return Vector<Line::CompletionSuggestion> {};
3462
3463
0
    if (matching_node != this)
3464
0
        return Vector<Line::CompletionSuggestion> {};
3465
3466
0
    auto corrected_offset = offset - matching_node->position().start_offset - 1;
3467
3468
0
    if (corrected_offset > m_username.bytes_as_string_view().length() + 1)
3469
0
        return Vector<Line::CompletionSuggestion> {};
3470
3471
0
    return shell.complete_user(m_username, corrected_offset);
3472
0
}
3473
3474
String Tilde::text() const
3475
1
{
3476
1
    StringBuilder builder;
3477
1
    builder.append('~');
3478
1
    builder.append(m_username);
3479
1
    return builder.to_string().release_value_but_fixme_should_propagate_errors();
3480
1
}
3481
3482
Tilde::Tilde(Position position, String username)
3483
8.49k
    : Node(move(position))
3484
8.49k
    , m_username(move(username))
3485
8.49k
{
3486
8.49k
}
3487
3488
Tilde::~Tilde()
3489
8.49k
{
3490
8.49k
}
3491
3492
ErrorOr<void> WriteAppendRedirection::dump(int level) const
3493
0
{
3494
0
    TRY(Node::dump(level));
3495
0
    TRY(m_path->dump(level + 1));
3496
0
    print_indented(level + 1, "From {}", m_fd);
3497
0
    return {};
3498
0
}
3499
3500
ErrorOr<RefPtr<Value>> WriteAppendRedirection::run(RefPtr<Shell> shell)
3501
0
{
3502
0
    Command command;
3503
0
    auto path_segments = TRY(TRY(m_path->run(shell))->resolve_as_list(shell));
3504
0
    if (shell && shell->has_any_error())
3505
0
        return make_ref_counted<ListValue>({});
3506
3507
0
    StringBuilder builder;
3508
0
    builder.join(' ', path_segments);
3509
3510
0
    command.redirections.append(PathRedirection::create(TRY(builder.to_string()), m_fd, PathRedirection::WriteAppend));
3511
0
    return make_ref_counted<CommandValue>(move(command));
3512
0
}
3513
3514
WriteAppendRedirection::WriteAppendRedirection(Position position, int fd, NonnullRefPtr<Node> path)
3515
10.6k
    : PathRedirectionNode(move(position), fd, move(path))
3516
10.6k
{
3517
10.6k
}
3518
3519
WriteAppendRedirection::~WriteAppendRedirection()
3520
{
3521
}
3522
3523
ErrorOr<void> WriteRedirection::dump(int level) const
3524
0
{
3525
0
    TRY(Node::dump(level));
3526
0
    TRY(m_path->dump(level + 1));
3527
0
    print_indented(level + 1, "From {}", m_fd);
3528
0
    return {};
3529
0
}
3530
3531
ErrorOr<RefPtr<Value>> WriteRedirection::run(RefPtr<Shell> shell)
3532
0
{
3533
0
    Command command;
3534
0
    auto path_segments = TRY(TRY(m_path->run(shell))->resolve_as_list(shell));
3535
0
    if (shell && shell->has_any_error())
3536
0
        return make_ref_counted<ListValue>({});
3537
3538
0
    StringBuilder builder;
3539
0
    builder.join(' ', path_segments);
3540
3541
0
    command.redirections.append(PathRedirection::create(TRY(builder.to_string()), m_fd, PathRedirection::Write));
3542
0
    return make_ref_counted<CommandValue>(move(command));
3543
0
}
3544
3545
WriteRedirection::WriteRedirection(Position position, int fd, NonnullRefPtr<Node> path)
3546
359k
    : PathRedirectionNode(move(position), fd, move(path))
3547
359k
{
3548
359k
}
3549
3550
WriteRedirection::~WriteRedirection()
3551
{
3552
}
3553
3554
ErrorOr<void> VariableDeclarations::dump(int level) const
3555
0
{
3556
0
    TRY(Node::dump(level));
3557
0
    for (auto& var : m_variables) {
3558
0
        print_indented(level + 1, "Set");
3559
0
        TRY(var.name->dump(level + 2));
3560
0
        TRY(var.value->dump(level + 2));
3561
0
    }
3562
0
    return {};
3563
0
}
3564
3565
ErrorOr<RefPtr<Value>> VariableDeclarations::run(RefPtr<Shell> shell)
3566
0
{
3567
0
    for (auto& var : m_variables) {
3568
0
        auto name_value = TRY(TRY(var.name->run(shell))->resolve_as_list(shell));
3569
0
        if (shell && shell->has_any_error())
3570
0
            break;
3571
3572
0
        VERIFY(name_value.size() == 1);
3573
0
        auto name = name_value[0];
3574
0
        auto value = TRY(var.value->run(shell));
3575
0
        if (shell && shell->has_any_error())
3576
0
            break;
3577
0
        value = TRY(value->resolve_without_cast(shell));
3578
3579
0
        shell->set_local_variable(name.to_byte_string(), value.release_nonnull());
3580
0
    }
3581
3582
0
    return make_ref_counted<ListValue>({});
3583
0
}
3584
3585
ErrorOr<void> VariableDeclarations::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
3586
0
{
3587
0
    metadata.is_first_in_list = false;
3588
0
    for (auto& var : m_variables) {
3589
0
        TRY(var.name->highlight_in_editor(editor, shell, metadata));
3590
        // Highlight the '='.
3591
0
        editor.stylize({ var.name->position().end_offset - 1, var.name->position().end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Blue) });
3592
0
        TRY(var.value->highlight_in_editor(editor, shell, metadata));
3593
0
    }
3594
3595
0
    return {};
3596
0
}
3597
3598
HitTestResult VariableDeclarations::hit_test_position(size_t offset) const
3599
0
{
3600
0
    for (auto decl : m_variables) {
3601
0
        auto result = decl.value->hit_test_position(offset);
3602
0
        if (result.matching_node)
3603
0
            return result;
3604
0
    }
3605
3606
0
    return { nullptr, nullptr, nullptr };
3607
0
}
3608
3609
VariableDeclarations::VariableDeclarations(Position position, Vector<Variable> variables)
3610
18.3k
    : Node(move(position))
3611
18.3k
    , m_variables(move(variables))
3612
18.3k
{
3613
61.4k
    for (auto& decl : m_variables) {
3614
61.4k
        if (decl.name->is_syntax_error()) {
3615
0
            set_is_syntax_error(decl.name->syntax_error_node());
3616
0
            break;
3617
0
        }
3618
61.4k
        if (decl.value->is_syntax_error()) {
3619
3.90k
            set_is_syntax_error(decl.value->syntax_error_node());
3620
3.90k
            break;
3621
3.90k
        }
3622
61.4k
    }
3623
18.3k
}
3624
3625
VariableDeclarations::~VariableDeclarations()
3626
18.3k
{
3627
18.3k
}
3628
3629
Value::~Value()
3630
0
{
3631
0
}
3632
3633
ErrorOr<String> Value::resolve_as_string(RefPtr<Shell> shell)
3634
0
{
3635
0
    if (shell)
3636
0
        shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "Conversion to string not allowed");
3637
0
    return String {};
3638
0
}
3639
3640
ErrorOr<Vector<AST::Command>> Value::resolve_as_commands(RefPtr<Shell> shell)
3641
0
{
3642
0
    Command command;
3643
0
    command.argv = TRY(resolve_as_list(shell));
3644
0
    return Vector { move(command) };
3645
0
}
3646
3647
ListValue::ListValue(Vector<String> values)
3648
0
{
3649
0
    if (values.is_empty())
3650
0
        return;
3651
0
    m_contained_values.ensure_capacity(values.size());
3652
0
    for (auto& str : values)
3653
0
        m_contained_values.append(adopt_ref(*new StringValue(move(str))));
3654
0
}
3655
3656
ErrorOr<NonnullRefPtr<Value>> Value::with_slices(NonnullRefPtr<Slice> slice) const&
3657
0
{
3658
0
    auto value = TRY(clone());
3659
0
    value->m_slices.append(move(slice));
3660
0
    return value;
3661
0
}
3662
3663
ErrorOr<NonnullRefPtr<Value>> Value::with_slices(Vector<NonnullRefPtr<Slice>> slices) const&
3664
0
{
3665
0
    auto value = TRY(clone());
3666
0
    value->m_slices.extend(move(slices));
3667
0
    return value;
3668
0
}
3669
3670
ListValue::~ListValue()
3671
0
{
3672
0
}
3673
3674
ErrorOr<Vector<String>> ListValue::resolve_as_list(RefPtr<Shell> shell)
3675
0
{
3676
0
    Vector<String> values;
3677
0
    for (auto& value : m_contained_values)
3678
0
        values.extend(TRY(value->resolve_as_list(shell)));
3679
3680
0
    return resolve_slices(shell, move(values), m_slices);
3681
0
}
3682
3683
ErrorOr<String> ListValue::resolve_as_string(RefPtr<Shell> shell)
3684
0
{
3685
0
    if (!shell || !shell->posix_mode())
3686
0
        return Value::resolve_as_string(shell);
3687
3688
0
    if (m_contained_values.is_empty())
3689
0
        return resolve_slices(shell, String {}, m_slices);
3690
3691
0
    return resolve_slices(shell, TRY(m_contained_values[0]->resolve_as_string(shell)), m_slices);
3692
0
}
3693
3694
ErrorOr<NonnullRefPtr<Value>> ListValue::resolve_without_cast(RefPtr<Shell> shell)
3695
0
{
3696
0
    Vector<NonnullRefPtr<Value>> values;
3697
0
    for (auto& value : m_contained_values)
3698
0
        values.append(TRY(value->resolve_without_cast(shell)));
3699
3700
0
    NonnullRefPtr<Value> value = make_ref_counted<ListValue>(move(values));
3701
0
    if (!m_slices.is_empty())
3702
0
        value = TRY(value->with_slices(m_slices));
3703
0
    return value;
3704
0
}
3705
3706
CommandValue::~CommandValue()
3707
0
{
3708
0
}
3709
3710
CommandSequenceValue::~CommandSequenceValue()
3711
0
{
3712
0
}
3713
3714
ErrorOr<Vector<String>> CommandSequenceValue::resolve_as_list(RefPtr<Shell> shell)
3715
0
{
3716
0
    shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "Unexpected cast of a command sequence to a list");
3717
0
    return Vector<String> {};
3718
0
}
3719
3720
ErrorOr<Vector<Command>> CommandSequenceValue::resolve_as_commands(RefPtr<Shell>)
3721
0
{
3722
0
    return m_contained_values;
3723
0
}
3724
3725
ErrorOr<Vector<String>> CommandValue::resolve_as_list(RefPtr<Shell>)
3726
0
{
3727
0
    return m_command.argv;
3728
0
}
3729
3730
ErrorOr<Vector<Command>> CommandValue::resolve_as_commands(RefPtr<Shell>)
3731
0
{
3732
0
    return Vector { m_command };
3733
0
}
3734
3735
JobValue::~JobValue()
3736
0
{
3737
0
}
3738
3739
StringValue::~StringValue()
3740
0
{
3741
0
}
3742
3743
ErrorOr<String> StringValue::resolve_as_string(RefPtr<Shell> shell)
3744
0
{
3745
0
    if (m_split.is_empty())
3746
0
        return TRY(resolve_slices(shell, String { m_string }, m_slices));
3747
0
    return Value::resolve_as_string(shell);
3748
0
}
3749
3750
ErrorOr<Vector<String>> StringValue::resolve_as_list(RefPtr<Shell> shell)
3751
0
{
3752
0
    if (is_list()) {
3753
0
        auto parts = StringView(m_string).split_view(m_split, m_keep_empty ? SplitBehavior::KeepEmpty : SplitBehavior::Nothing);
3754
0
        Vector<String> result;
3755
0
        result.ensure_capacity(parts.size());
3756
0
        for (auto& part : parts)
3757
0
            result.append(TRY(String::from_utf8(part)));
3758
0
        return resolve_slices(shell, move(result), m_slices);
3759
0
    }
3760
3761
0
    return Vector<String> { TRY(resolve_slices(shell, String { m_string }, m_slices)) };
3762
0
}
3763
3764
ErrorOr<NonnullRefPtr<Value>> StringValue::resolve_without_cast(RefPtr<Shell> shell)
3765
0
{
3766
0
    if (is_list())
3767
0
        return try_make_ref_counted<AST::ListValue>(TRY(resolve_as_list(shell))); // No need to reapply the slices.
3768
3769
0
    return *this;
3770
0
}
3771
3772
GlobValue::~GlobValue()
3773
0
{
3774
0
}
3775
3776
ErrorOr<Vector<String>> GlobValue::resolve_as_list(RefPtr<Shell> shell)
3777
0
{
3778
0
    if (!shell)
3779
0
        return resolve_slices(shell, Vector { m_glob }, m_slices);
3780
3781
0
    auto results = TRY(shell->expand_globs(m_glob, shell->cwd));
3782
0
    if (results.is_empty())
3783
0
        shell->raise_error(Shell::ShellError::InvalidGlobError, "Glob did not match anything!", m_generation_position);
3784
3785
0
    Vector<String> strings;
3786
0
    TRY(strings.try_ensure_capacity(results.size()));
3787
0
    for (auto& entry : results) {
3788
0
        TRY(strings.try_append(TRY(String::from_byte_string(entry))));
3789
0
    }
3790
3791
0
    return resolve_slices(shell, move(strings), m_slices);
3792
0
}
3793
3794
SimpleVariableValue::~SimpleVariableValue()
3795
0
{
3796
0
}
3797
3798
ErrorOr<String> SimpleVariableValue::resolve_as_string(RefPtr<Shell> shell)
3799
0
{
3800
0
    if (!shell)
3801
0
        return resolve_slices(shell, String {}, m_slices);
3802
3803
0
    if (auto value = TRY(resolve_without_cast(shell)); value != this)
3804
0
        return resolve_slices(shell, TRY(value->resolve_as_string(shell)), m_slices);
3805
3806
0
    auto name = m_name.to_byte_string();
3807
0
    char const* env_value = getenv(name.characters());
3808
0
    if (!env_value)
3809
0
        env_value = "";
3810
3811
0
    return resolve_slices(shell, TRY(String::from_utf8(StringView { env_value, strlen(env_value) })), m_slices);
3812
0
}
3813
3814
ErrorOr<Vector<String>> SimpleVariableValue::resolve_as_list(RefPtr<Shell> shell)
3815
0
{
3816
0
    if (!shell)
3817
0
        return resolve_slices(shell, Vector<String> {}, m_slices);
3818
3819
0
    if (auto value = TRY(resolve_without_cast(shell)); value != this)
3820
0
        return value->resolve_as_list(shell);
3821
3822
0
    auto name = m_name.to_byte_string();
3823
0
    char* env_value = getenv(name.characters());
3824
0
    if (env_value == nullptr)
3825
0
        return { resolve_slices(shell, Vector { String {} }, m_slices) };
3826
3827
0
    return Vector<String> { TRY(resolve_slices(shell, TRY(String::from_utf8(StringView { env_value, strlen(env_value) })), m_slices)) };
3828
0
}
3829
3830
ErrorOr<NonnullRefPtr<Value>> SimpleVariableValue::resolve_without_cast(RefPtr<Shell> shell)
3831
0
{
3832
0
    VERIFY(shell);
3833
3834
0
    if (auto value = TRY(shell->look_up_local_variable(m_name))) {
3835
0
        auto result = value.release_nonnull();
3836
        // If a slice is applied, add it.
3837
0
        if (!m_slices.is_empty())
3838
0
            result = TRY(result->with_slices(m_slices));
3839
3840
0
        return const_cast<Value&>(*result);
3841
0
    }
3842
3843
0
    return *this;
3844
0
}
3845
3846
SpecialVariableValue::~SpecialVariableValue()
3847
{
3848
}
3849
3850
ErrorOr<String> SpecialVariableValue::resolve_as_string(RefPtr<Shell> shell)
3851
0
{
3852
0
    if (!shell)
3853
0
        return String {};
3854
3855
0
    auto result = TRY(resolve_as_list(shell));
3856
0
    if (result.size() == 1)
3857
0
        return result[0];
3858
3859
0
    if (result.is_empty())
3860
0
        return String {};
3861
3862
0
    return Value::resolve_as_string(shell);
3863
0
}
3864
3865
ErrorOr<Vector<String>> SpecialVariableValue::resolve_as_list(RefPtr<Shell> shell)
3866
0
{
3867
0
    if (!shell)
3868
0
        return Vector<String> {};
3869
3870
0
    switch (m_name) {
3871
0
    case '?':
3872
0
        return { resolve_slices(shell, Vector { String::number(shell->last_return_code.value_or(0)) }, m_slices) };
3873
0
    case '$':
3874
0
        return { resolve_slices(shell, Vector { String::number(getpid()) }, m_slices) };
3875
0
    case '*':
3876
0
        if (auto argv = TRY(shell->look_up_local_variable("ARGV"sv)))
3877
0
            return resolve_slices(shell, TRY(const_cast<Value&>(*argv).resolve_as_list(shell)), m_slices);
3878
0
        return resolve_slices(shell, Vector<String> {}, m_slices);
3879
0
    case '#':
3880
0
        if (auto argv = TRY(shell->look_up_local_variable("ARGV"sv))) {
3881
0
            if (argv->is_list()) {
3882
0
                auto list_argv = static_cast<AST::ListValue const*>(argv.ptr());
3883
0
                return { resolve_slices(shell, Vector { String::number(list_argv->values().size()) }, m_slices) };
3884
0
            }
3885
0
            return { resolve_slices(shell, Vector { "1"_string }, m_slices) };
3886
0
        }
3887
0
        return { resolve_slices(shell, Vector { "0"_string }, m_slices) };
3888
0
    default:
3889
0
        return { resolve_slices(shell, Vector { String {} }, m_slices) };
3890
0
    }
3891
0
}
3892
3893
ErrorOr<NonnullRefPtr<Value>> SpecialVariableValue::resolve_without_cast(RefPtr<Shell> shell)
3894
0
{
3895
0
    if (!shell)
3896
0
        return *this;
3897
3898
0
    return try_make_ref_counted<ListValue>(TRY(resolve_as_list(shell)));
3899
0
}
3900
3901
TildeValue::~TildeValue()
3902
0
{
3903
0
}
3904
3905
ErrorOr<String> TildeValue::resolve_as_string(RefPtr<Shell> shell)
3906
0
{
3907
0
    return TRY(resolve_as_list(shell)).first();
3908
0
}
3909
3910
ErrorOr<Vector<String>> TildeValue::resolve_as_list(RefPtr<Shell> shell)
3911
0
{
3912
0
    StringBuilder builder;
3913
0
    builder.append('~');
3914
0
    builder.append(m_username);
3915
3916
0
    if (!shell)
3917
0
        return { resolve_slices(shell, Vector { TRY(builder.to_string()) }, m_slices) };
3918
3919
0
    return { resolve_slices(shell, Vector { TRY(String::from_byte_string(shell->expand_tilde(builder.to_byte_string()))) }, m_slices) };
3920
0
}
3921
3922
ErrorOr<NonnullRefPtr<Rewiring>> CloseRedirection::apply() const
3923
0
{
3924
0
    return adopt_nonnull_ref_or_enomem(new (nothrow) Rewiring(fd, fd, Rewiring::Close::ImmediatelyCloseNew));
3925
0
}
3926
3927
CloseRedirection::~CloseRedirection()
3928
0
{
3929
0
}
3930
3931
ErrorOr<NonnullRefPtr<Rewiring>> PathRedirection::apply() const
3932
0
{
3933
0
    auto check_fd_and_return = [my_fd = this->fd](int fd, String const& path) -> ErrorOr<NonnullRefPtr<Rewiring>> {
3934
0
        if (fd < 0) {
3935
0
            auto error = Error::from_errno(errno);
3936
0
            dbgln("open() failed for '{}' with {}", path, error);
3937
0
            return error;
3938
0
        }
3939
0
        return adopt_nonnull_ref_or_enomem(new (nothrow) Rewiring(fd, my_fd, Rewiring::Close::Old));
3940
0
    };
3941
3942
0
    auto path_string = path.to_byte_string();
3943
0
    switch (direction) {
3944
0
    case AST::PathRedirection::WriteAppend:
3945
0
        return check_fd_and_return(open(path_string.characters(), O_WRONLY | O_CREAT | O_APPEND, 0666), path);
3946
3947
0
    case AST::PathRedirection::Write:
3948
0
        return check_fd_and_return(open(path_string.characters(), O_WRONLY | O_CREAT | O_TRUNC, 0666), path);
3949
3950
0
    case AST::PathRedirection::Read:
3951
0
        return check_fd_and_return(open(path_string.characters(), O_RDONLY), path);
3952
3953
0
    case AST::PathRedirection::ReadWrite:
3954
0
        return check_fd_and_return(open(path_string.characters(), O_RDWR | O_CREAT, 0666), path);
3955
0
    }
3956
3957
0
    VERIFY_NOT_REACHED();
3958
0
}
3959
3960
PathRedirection::~PathRedirection()
3961
0
{
3962
0
}
3963
3964
FdRedirection::~FdRedirection()
3965
0
{
3966
0
}
3967
3968
Redirection::~Redirection()
3969
0
{
3970
0
}
3971
3972
}