ImmediateFunctions.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. /*
  2. * Copyright (c) 2021, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "Formatter.h"
  7. #include "Shell.h"
  8. #include <LibRegex/Regex.h>
  9. namespace Shell {
  10. ErrorOr<RefPtr<AST::Node>> Shell::immediate_length_impl(AST::ImmediateExpression& invoking_node, NonnullRefPtrVector<AST::Node> const& arguments, bool across)
  11. {
  12. auto name = across ? "length_across" : "length";
  13. if (arguments.size() < 1 || arguments.size() > 2) {
  14. raise_error(ShellError::EvaluatedSyntaxError, DeprecatedString::formatted("Expected one or two arguments to `{}'", name), invoking_node.position());
  15. return nullptr;
  16. }
  17. enum {
  18. Infer,
  19. String,
  20. List,
  21. } mode { Infer };
  22. bool is_inferred = false;
  23. const AST::Node* expr_node;
  24. if (arguments.size() == 2) {
  25. // length string <expr>
  26. // length list <expr>
  27. auto& mode_arg = arguments.first();
  28. if (!mode_arg.is_bareword()) {
  29. raise_error(ShellError::EvaluatedSyntaxError, DeprecatedString::formatted("Expected a bareword (either 'string' or 'list') in the two-argument form of the `{}' immediate", name), mode_arg.position());
  30. return nullptr;
  31. }
  32. auto const& mode_name = static_cast<const AST::BarewordLiteral&>(mode_arg).text();
  33. if (mode_name == "list") {
  34. mode = List;
  35. } else if (mode_name == "string") {
  36. mode = String;
  37. } else if (mode_name == "infer") {
  38. mode = Infer;
  39. } else {
  40. raise_error(ShellError::EvaluatedSyntaxError, DeprecatedString::formatted("Expected either 'string' or 'list' (and not {}) in the two-argument form of the `{}' immediate", mode_name, name), mode_arg.position());
  41. return nullptr;
  42. }
  43. expr_node = &arguments[1];
  44. } else {
  45. expr_node = &arguments[0];
  46. }
  47. if (mode == Infer) {
  48. is_inferred = true;
  49. if (expr_node->is_list())
  50. mode = List;
  51. else if (expr_node->is_simple_variable()) // "Look inside" variables
  52. mode = TRY(TRY(const_cast<AST::Node*>(expr_node)->run(this))->resolve_without_cast(this))->is_list_without_resolution() ? List : String;
  53. else if (is<AST::ImmediateExpression>(expr_node))
  54. mode = List;
  55. else
  56. mode = String;
  57. }
  58. auto value_with_number = [&](auto number) -> ErrorOr<NonnullRefPtr<AST::Node>> {
  59. return AST::make_ref_counted<AST::BarewordLiteral>(invoking_node.position(), TRY(String::number(number)));
  60. };
  61. auto do_across = [&](StringView mode_name, auto& values) -> ErrorOr<RefPtr<AST::Node>> {
  62. if (is_inferred)
  63. mode_name = "infer"sv;
  64. // Translate to a list of applications of `length <mode_name>`
  65. Vector<NonnullRefPtr<AST::Node>> resulting_nodes;
  66. resulting_nodes.ensure_capacity(values.size());
  67. for (auto& entry : values) {
  68. // ImmediateExpression(length <mode_name> <entry>)
  69. resulting_nodes.unchecked_append(AST::make_ref_counted<AST::ImmediateExpression>(
  70. expr_node->position(),
  71. AST::NameWithPosition { TRY(String::from_utf8("length"sv)), invoking_node.function_position() },
  72. NonnullRefPtrVector<AST::Node> { Vector<NonnullRefPtr<AST::Node>> {
  73. static_cast<NonnullRefPtr<AST::Node>>(AST::make_ref_counted<AST::BarewordLiteral>(expr_node->position(), TRY(String::from_utf8(mode_name)))),
  74. AST::make_ref_counted<AST::SyntheticNode>(expr_node->position(), NonnullRefPtr<AST::Value>(entry)),
  75. } },
  76. expr_node->position()));
  77. }
  78. return AST::make_ref_counted<AST::ListConcatenate>(invoking_node.position(), move(resulting_nodes));
  79. };
  80. switch (mode) {
  81. default:
  82. case Infer:
  83. VERIFY_NOT_REACHED();
  84. case List: {
  85. auto value = TRY(const_cast<AST::Node*>(expr_node)->run(this));
  86. if (!value)
  87. return value_with_number(0);
  88. value = TRY(value->resolve_without_cast(this));
  89. if (auto list = dynamic_cast<AST::ListValue*>(value.ptr())) {
  90. if (across)
  91. return do_across("list"sv, list->values());
  92. return value_with_number(list->values().size());
  93. }
  94. auto list = TRY(value->resolve_as_list(this));
  95. if (!across)
  96. return value_with_number(list.size());
  97. dbgln("List has {} entries", list.size());
  98. auto values = AST::make_ref_counted<AST::ListValue>(move(list));
  99. return do_across("list"sv, values->values());
  100. }
  101. case String: {
  102. // 'across' will only accept lists, and '!across' will only accept non-lists here.
  103. if (expr_node->is_list()) {
  104. if (!across) {
  105. raise_no_list_allowed:;
  106. Formatter formatter { *expr_node };
  107. if (is_inferred) {
  108. raise_error(ShellError::EvaluatedSyntaxError,
  109. DeprecatedString::formatted("Could not infer expression type, please explicitly use `{0} string' or `{0} list'", name),
  110. invoking_node.position());
  111. return nullptr;
  112. }
  113. auto source = formatter.format();
  114. raise_error(ShellError::EvaluatedSyntaxError,
  115. source.is_empty()
  116. ? "Invalid application of `length' to a list"
  117. : DeprecatedString::formatted("Invalid application of `length' to a list\nperhaps you meant `{1}length \"{0}\"{2}' or `{1}length_across {0}{2}'?", source, "\x1b[32m", "\x1b[0m"),
  118. expr_node->position());
  119. return nullptr;
  120. }
  121. }
  122. auto value = TRY(const_cast<AST::Node*>(expr_node)->run(this));
  123. if (!value)
  124. return value_with_number(0);
  125. value = TRY(value->resolve_without_cast(*this));
  126. if (auto list = dynamic_cast<AST::ListValue*>(value.ptr())) {
  127. if (!across)
  128. goto raise_no_list_allowed;
  129. return do_across("string"sv, list->values());
  130. }
  131. if (across && !value->is_list()) {
  132. Formatter formatter { *expr_node };
  133. auto source = formatter.format();
  134. raise_error(ShellError::EvaluatedSyntaxError,
  135. DeprecatedString::formatted("Invalid application of `length_across' to a non-list\nperhaps you meant `{1}length {0}{2}'?", source, "\x1b[32m", "\x1b[0m"),
  136. expr_node->position());
  137. return nullptr;
  138. }
  139. // Evaluate the nodes and substitute with the lengths.
  140. auto list = TRY(value->resolve_as_list(this));
  141. if (!expr_node->is_list()) {
  142. if (list.size() == 1) {
  143. if (across)
  144. goto raise_no_list_allowed;
  145. // This is the normal case, the expression is a normal non-list expression.
  146. return value_with_number(list.first().bytes_as_string_view().length());
  147. }
  148. // This can be hit by asking for the length of a command list (e.g. `(>/dev/null)`)
  149. // raise an error about misuse of command lists for now.
  150. // FIXME: What's the length of `(>/dev/null)` supposed to be?
  151. raise_error(ShellError::EvaluatedSyntaxError, "Length of meta value (or command list) requested, this is currently not supported.", expr_node->position());
  152. return nullptr;
  153. }
  154. auto values = AST::make_ref_counted<AST::ListValue>(move(list));
  155. return do_across("string"sv, values->values());
  156. }
  157. }
  158. }
  159. ErrorOr<RefPtr<AST::Node>> Shell::immediate_length(AST::ImmediateExpression& invoking_node, NonnullRefPtrVector<AST::Node> const& arguments)
  160. {
  161. return immediate_length_impl(invoking_node, arguments, false);
  162. }
  163. ErrorOr<RefPtr<AST::Node>> Shell::immediate_length_across(AST::ImmediateExpression& invoking_node, NonnullRefPtrVector<AST::Node> const& arguments)
  164. {
  165. return immediate_length_impl(invoking_node, arguments, true);
  166. }
  167. ErrorOr<RefPtr<AST::Node>> Shell::immediate_regex_replace(AST::ImmediateExpression& invoking_node, NonnullRefPtrVector<AST::Node> const& arguments)
  168. {
  169. if (arguments.size() != 3) {
  170. raise_error(ShellError::EvaluatedSyntaxError, "Expected exactly 3 arguments to regex_replace", invoking_node.position());
  171. return nullptr;
  172. }
  173. auto pattern = TRY(const_cast<AST::Node&>(arguments[0]).run(this));
  174. auto replacement = TRY(const_cast<AST::Node&>(arguments[1]).run(this));
  175. auto value = TRY(TRY(const_cast<AST::Node&>(arguments[2]).run(this))->resolve_without_cast(this));
  176. if (!pattern->is_string()) {
  177. raise_error(ShellError::EvaluatedSyntaxError, "Expected the regex_replace pattern to be a string", arguments[0].position());
  178. return nullptr;
  179. }
  180. if (!replacement->is_string()) {
  181. raise_error(ShellError::EvaluatedSyntaxError, "Expected the regex_replace replacement string to be a string", arguments[1].position());
  182. return nullptr;
  183. }
  184. if (!value->is_string()) {
  185. raise_error(ShellError::EvaluatedSyntaxError, "Expected the regex_replace target value to be a string", arguments[2].position());
  186. return nullptr;
  187. }
  188. Regex<PosixExtendedParser> re { TRY(pattern->resolve_as_list(this)).first().to_deprecated_string() };
  189. auto result = re.replace(
  190. TRY(value->resolve_as_list(this))[0],
  191. TRY(replacement->resolve_as_list(this))[0],
  192. PosixFlags::Global | PosixFlags::Multiline | PosixFlags::Unicode);
  193. return AST::make_ref_counted<AST::StringLiteral>(invoking_node.position(), TRY(String::from_utf8(result)), AST::StringLiteral::EnclosureType::None);
  194. }
  195. ErrorOr<RefPtr<AST::Node>> Shell::immediate_remove_suffix(AST::ImmediateExpression& invoking_node, NonnullRefPtrVector<AST::Node> const& arguments)
  196. {
  197. if (arguments.size() != 2) {
  198. raise_error(ShellError::EvaluatedSyntaxError, "Expected exactly 2 arguments to remove_suffix", invoking_node.position());
  199. return nullptr;
  200. }
  201. auto suffix = TRY(const_cast<AST::Node&>(arguments[0]).run(this));
  202. auto value = TRY(TRY(const_cast<AST::Node&>(arguments[1]).run(this))->resolve_without_cast(this));
  203. if (!suffix->is_string()) {
  204. raise_error(ShellError::EvaluatedSyntaxError, "Expected the remove_suffix suffix string to be a string", arguments[0].position());
  205. return nullptr;
  206. }
  207. auto suffix_str = TRY(suffix->resolve_as_list(this))[0];
  208. auto values = TRY(value->resolve_as_list(this));
  209. Vector<NonnullRefPtr<AST::Node>> nodes;
  210. for (auto& value_str : values) {
  211. String removed = TRY(String::from_utf8(value_str));
  212. if (value_str.bytes_as_string_view().ends_with(suffix_str))
  213. removed = TRY(removed.substring_from_byte_offset(0, value_str.bytes_as_string_view().length() - suffix_str.bytes_as_string_view().length()));
  214. nodes.append(AST::make_ref_counted<AST::StringLiteral>(invoking_node.position(), move(removed), AST::StringLiteral::EnclosureType::None));
  215. }
  216. return AST::make_ref_counted<AST::ListConcatenate>(invoking_node.position(), move(nodes));
  217. }
  218. ErrorOr<RefPtr<AST::Node>> Shell::immediate_remove_prefix(AST::ImmediateExpression& invoking_node, NonnullRefPtrVector<AST::Node> const& arguments)
  219. {
  220. if (arguments.size() != 2) {
  221. raise_error(ShellError::EvaluatedSyntaxError, "Expected exactly 2 arguments to remove_prefix", invoking_node.position());
  222. return nullptr;
  223. }
  224. auto prefix = TRY(const_cast<AST::Node&>(arguments[0]).run(this));
  225. auto value = TRY(TRY(const_cast<AST::Node&>(arguments[1]).run(this))->resolve_without_cast(this));
  226. if (!prefix->is_string()) {
  227. raise_error(ShellError::EvaluatedSyntaxError, "Expected the remove_prefix prefix string to be a string", arguments[0].position());
  228. return nullptr;
  229. }
  230. auto prefix_str = TRY(prefix->resolve_as_list(this))[0];
  231. auto values = TRY(value->resolve_as_list(this));
  232. Vector<NonnullRefPtr<AST::Node>> nodes;
  233. for (auto& value_str : values) {
  234. String removed = TRY(String::from_utf8(value_str));
  235. if (value_str.bytes_as_string_view().starts_with(prefix_str))
  236. removed = TRY(removed.substring_from_byte_offset(prefix_str.bytes_as_string_view().length()));
  237. nodes.append(AST::make_ref_counted<AST::StringLiteral>(invoking_node.position(), move(removed), AST::StringLiteral::EnclosureType::None));
  238. }
  239. return AST::make_ref_counted<AST::ListConcatenate>(invoking_node.position(), move(nodes));
  240. }
  241. ErrorOr<RefPtr<AST::Node>> Shell::immediate_split(AST::ImmediateExpression& invoking_node, NonnullRefPtrVector<AST::Node> const& arguments)
  242. {
  243. if (arguments.size() != 2) {
  244. raise_error(ShellError::EvaluatedSyntaxError, "Expected exactly 2 arguments to split", invoking_node.position());
  245. return nullptr;
  246. }
  247. auto delimiter = TRY(const_cast<AST::Node&>(arguments[0]).run(this));
  248. auto value = TRY(TRY(const_cast<AST::Node&>(arguments[1]).run(this))->resolve_without_cast(this));
  249. if (!delimiter->is_string()) {
  250. raise_error(ShellError::EvaluatedSyntaxError, "Expected the split delimiter string to be a string", arguments[0].position());
  251. return nullptr;
  252. }
  253. auto delimiter_str = TRY(delimiter->resolve_as_list(this))[0];
  254. auto transform = [&](auto const& values) {
  255. // Translate to a list of applications of `split <delimiter>`
  256. Vector<NonnullRefPtr<AST::Node>> resulting_nodes;
  257. resulting_nodes.ensure_capacity(values.size());
  258. for (auto& entry : values) {
  259. // ImmediateExpression(split <delimiter> <entry>)
  260. resulting_nodes.unchecked_append(AST::make_ref_counted<AST::ImmediateExpression>(
  261. arguments[1].position(),
  262. invoking_node.function(),
  263. NonnullRefPtrVector<AST::Node> { Vector<NonnullRefPtr<AST::Node>> {
  264. arguments[0],
  265. AST::make_ref_counted<AST::SyntheticNode>(arguments[1].position(), NonnullRefPtr<AST::Value>(entry)),
  266. } },
  267. arguments[1].position()));
  268. }
  269. return AST::make_ref_counted<AST::ListConcatenate>(invoking_node.position(), move(resulting_nodes));
  270. };
  271. if (auto list = dynamic_cast<AST::ListValue*>(value.ptr())) {
  272. return transform(list->values());
  273. }
  274. // Otherwise, just resolve to a list and transform that.
  275. auto list = TRY(value->resolve_as_list(this));
  276. if (!value->is_list()) {
  277. if (list.is_empty())
  278. return AST::make_ref_counted<AST::ListConcatenate>(invoking_node.position(), NonnullRefPtrVector<AST::Node> {});
  279. auto& value = list.first();
  280. Vector<String> split_strings;
  281. if (delimiter_str.is_empty()) {
  282. StringBuilder builder;
  283. for (auto code_point : Utf8View { value }) {
  284. builder.append_code_point(code_point);
  285. split_strings.append(TRY(builder.to_string()));
  286. builder.clear();
  287. }
  288. } else {
  289. auto split = StringView { value }.split_view(delimiter_str, options.inline_exec_keep_empty_segments ? SplitBehavior::KeepEmpty : SplitBehavior::Nothing);
  290. split_strings.ensure_capacity(split.size());
  291. for (auto& entry : split)
  292. split_strings.append(TRY(String::from_utf8(entry)));
  293. }
  294. return AST::make_ref_counted<AST::SyntheticNode>(invoking_node.position(), AST::make_ref_counted<AST::ListValue>(move(split_strings)));
  295. }
  296. return transform(AST::make_ref_counted<AST::ListValue>(list)->values());
  297. }
  298. ErrorOr<RefPtr<AST::Node>> Shell::immediate_concat_lists(AST::ImmediateExpression& invoking_node, NonnullRefPtrVector<AST::Node> const& arguments)
  299. {
  300. NonnullRefPtrVector<AST::Node> result;
  301. for (auto& argument : arguments) {
  302. if (auto* list = dynamic_cast<const AST::ListConcatenate*>(&argument)) {
  303. result.extend(list->list());
  304. } else {
  305. auto list_of_values = TRY(TRY(const_cast<AST::Node&>(argument).run(this))->resolve_without_cast(this));
  306. if (auto* list = dynamic_cast<AST::ListValue*>(list_of_values.ptr())) {
  307. for (auto& entry : static_cast<Vector<NonnullRefPtr<AST::Value>>&>(list->values()))
  308. result.append(AST::make_ref_counted<AST::SyntheticNode>(argument.position(), entry));
  309. } else {
  310. auto values = TRY(list_of_values->resolve_as_list(this));
  311. for (auto& entry : values)
  312. result.append(AST::make_ref_counted<AST::StringLiteral>(argument.position(), entry, AST::StringLiteral::EnclosureType::None));
  313. }
  314. }
  315. }
  316. return AST::make_ref_counted<AST::ListConcatenate>(invoking_node.position(), move(result));
  317. }
  318. ErrorOr<RefPtr<AST::Node>> Shell::immediate_filter_glob(AST::ImmediateExpression& invoking_node, NonnullRefPtrVector<AST::Node> const& arguments)
  319. {
  320. // filter_glob string list
  321. if (arguments.size() != 2) {
  322. raise_error(ShellError::EvaluatedSyntaxError, "Expected exactly two arguments to filter_glob (<glob> <list>)", invoking_node.position());
  323. return nullptr;
  324. }
  325. auto glob_list = TRY(TRY(const_cast<AST::Node&>(arguments[0]).run(*this))->resolve_as_list(*this));
  326. if (glob_list.size() != 1) {
  327. raise_error(ShellError::EvaluatedSyntaxError, "Expected the <glob> argument to filter_glob to be a single string", arguments[0].position());
  328. return nullptr;
  329. }
  330. auto& glob = glob_list.first();
  331. auto& list_node = arguments[1];
  332. NonnullRefPtrVector<AST::Node> result;
  333. TRY(const_cast<AST::Node&>(list_node).for_each_entry(*this, [&](NonnullRefPtr<AST::Value> entry) -> ErrorOr<IterationDecision> {
  334. auto value = TRY(entry->resolve_as_list(*this));
  335. if (value.size() == 0)
  336. return IterationDecision::Continue;
  337. if (value.size() == 1) {
  338. if (!value.first().bytes_as_string_view().matches(glob))
  339. return IterationDecision::Continue;
  340. result.append(AST::make_ref_counted<AST::StringLiteral>(arguments[1].position(), value.first(), AST::StringLiteral::EnclosureType::None));
  341. return IterationDecision::Continue;
  342. }
  343. for (auto& entry : value) {
  344. if (entry.bytes_as_string_view().matches(glob)) {
  345. NonnullRefPtrVector<AST::Node> nodes;
  346. for (auto& string : value)
  347. nodes.append(AST::make_ref_counted<AST::StringLiteral>(arguments[1].position(), string, AST::StringLiteral::EnclosureType::None));
  348. result.append(AST::make_ref_counted<AST::ListConcatenate>(arguments[1].position(), move(nodes)));
  349. return IterationDecision::Continue;
  350. }
  351. }
  352. return IterationDecision::Continue;
  353. }));
  354. return AST::make_ref_counted<AST::ListConcatenate>(invoking_node.position(), move(result));
  355. }
  356. ErrorOr<RefPtr<AST::Node>> Shell::immediate_join(AST::ImmediateExpression& invoking_node, NonnullRefPtrVector<AST::Node> const& arguments)
  357. {
  358. if (arguments.size() != 2) {
  359. raise_error(ShellError::EvaluatedSyntaxError, "Expected exactly 2 arguments to join", invoking_node.position());
  360. return nullptr;
  361. }
  362. auto delimiter = TRY(const_cast<AST::Node&>(arguments[0]).run(this));
  363. if (!delimiter->is_string()) {
  364. raise_error(ShellError::EvaluatedSyntaxError, "Expected the join delimiter string to be a string", arguments[0].position());
  365. return nullptr;
  366. }
  367. auto value = TRY(TRY(const_cast<AST::Node&>(arguments[1]).run(this))->resolve_without_cast(this));
  368. if (!value->is_list()) {
  369. raise_error(ShellError::EvaluatedSyntaxError, "Expected the joined list to be a list", arguments[1].position());
  370. return nullptr;
  371. }
  372. auto delimiter_str = TRY(delimiter->resolve_as_list(this))[0];
  373. StringBuilder builder;
  374. builder.join(delimiter_str, TRY(value->resolve_as_list(*this)));
  375. return AST::make_ref_counted<AST::StringLiteral>(invoking_node.position(), TRY(builder.to_string()), AST::StringLiteral::EnclosureType::None);
  376. }
  377. ErrorOr<RefPtr<AST::Node>> Shell::immediate_value_or_default(AST::ImmediateExpression& invoking_node, NonnullRefPtrVector<AST::Node> const& arguments)
  378. {
  379. if (arguments.size() != 2) {
  380. raise_error(ShellError::EvaluatedSyntaxError, "Expected exactly 2 arguments to value_or_default", invoking_node.position());
  381. return nullptr;
  382. }
  383. auto name = TRY(TRY(const_cast<AST::Node&>(arguments.first()).run(*this))->resolve_as_string(*this));
  384. if (!TRY(local_variable_or(name, ""sv)).is_empty())
  385. return make_ref_counted<AST::SimpleVariable>(invoking_node.position(), name);
  386. return arguments.last();
  387. }
  388. ErrorOr<RefPtr<AST::Node>> Shell::immediate_assign_default(AST::ImmediateExpression& invoking_node, NonnullRefPtrVector<AST::Node> const& arguments)
  389. {
  390. if (arguments.size() != 2) {
  391. raise_error(ShellError::EvaluatedSyntaxError, "Expected exactly 2 arguments to assign_default", invoking_node.position());
  392. return nullptr;
  393. }
  394. auto name = TRY(TRY(const_cast<AST::Node&>(arguments.first()).run(*this))->resolve_as_string(*this));
  395. if (!TRY(local_variable_or(name, ""sv)).is_empty())
  396. return make_ref_counted<AST::SimpleVariable>(invoking_node.position(), name);
  397. auto value = TRY(TRY(const_cast<AST::Node&>(arguments.last()).run(*this))->resolve_without_cast(*this));
  398. set_local_variable(name.to_deprecated_string(), value);
  399. return make_ref_counted<AST::SyntheticNode>(invoking_node.position(), value);
  400. }
  401. ErrorOr<RefPtr<AST::Node>> Shell::immediate_error_if_empty(AST::ImmediateExpression& invoking_node, NonnullRefPtrVector<AST::Node> const& arguments)
  402. {
  403. if (arguments.size() != 2) {
  404. raise_error(ShellError::EvaluatedSyntaxError, "Expected exactly 2 arguments to error_if_empty", invoking_node.position());
  405. return nullptr;
  406. }
  407. auto name = TRY(TRY(const_cast<AST::Node&>(arguments.first()).run(*this))->resolve_as_string(*this));
  408. if (!TRY(local_variable_or(name, ""sv)).is_empty())
  409. return make_ref_counted<AST::SimpleVariable>(invoking_node.position(), name);
  410. auto error_value = TRY(TRY(const_cast<AST::Node&>(arguments.last()).run(*this))->resolve_as_string(*this));
  411. if (error_value.is_empty())
  412. error_value = TRY(String::formatted("Expected {} to be non-empty", name));
  413. raise_error(ShellError::EvaluatedSyntaxError, error_value.bytes_as_string_view(), invoking_node.position());
  414. return nullptr;
  415. }
  416. ErrorOr<RefPtr<AST::Node>> Shell::immediate_null_or_alternative(AST::ImmediateExpression& invoking_node, NonnullRefPtrVector<AST::Node> const& arguments)
  417. {
  418. if (arguments.size() != 2) {
  419. raise_error(ShellError::EvaluatedSyntaxError, "Expected exactly 2 arguments to null_or_alternative", invoking_node.position());
  420. return nullptr;
  421. }
  422. auto value = TRY(TRY(const_cast<AST::Node&>(arguments.first()).run(*this))->resolve_without_cast(*this));
  423. if ((value->is_string() && TRY(value->resolve_as_string(*this)).is_empty()) || (value->is_list() && TRY(value->resolve_as_list(*this)).is_empty()))
  424. return make_ref_counted<AST::SyntheticNode>(invoking_node.position(), value);
  425. return arguments.last();
  426. }
  427. ErrorOr<RefPtr<AST::Node>> Shell::immediate_defined_value_or_default(AST::ImmediateExpression& invoking_node, NonnullRefPtrVector<AST::Node> const& arguments)
  428. {
  429. if (arguments.size() != 2) {
  430. raise_error(ShellError::EvaluatedSyntaxError, "Expected exactly 2 arguments to defined_value_or_default", invoking_node.position());
  431. return nullptr;
  432. }
  433. auto name = TRY(TRY(const_cast<AST::Node&>(arguments.first()).run(*this))->resolve_as_string(*this));
  434. if (!find_frame_containing_local_variable(name))
  435. return arguments.last();
  436. return make_ref_counted<AST::SimpleVariable>(invoking_node.position(), name);
  437. }
  438. ErrorOr<RefPtr<AST::Node>> Shell::immediate_assign_defined_default(AST::ImmediateExpression& invoking_node, NonnullRefPtrVector<AST::Node> const& arguments)
  439. {
  440. if (arguments.size() != 2) {
  441. raise_error(ShellError::EvaluatedSyntaxError, "Expected exactly 2 arguments to assign_defined_default", invoking_node.position());
  442. return nullptr;
  443. }
  444. auto name = TRY(TRY(const_cast<AST::Node&>(arguments.first()).run(*this))->resolve_as_string(*this));
  445. if (find_frame_containing_local_variable(name))
  446. return make_ref_counted<AST::SimpleVariable>(invoking_node.position(), name);
  447. auto value = TRY(TRY(const_cast<AST::Node&>(arguments.last()).run(*this))->resolve_without_cast(*this));
  448. set_local_variable(name.to_deprecated_string(), value);
  449. return make_ref_counted<AST::SyntheticNode>(invoking_node.position(), value);
  450. }
  451. ErrorOr<RefPtr<AST::Node>> Shell::immediate_error_if_unset(AST::ImmediateExpression& invoking_node, NonnullRefPtrVector<AST::Node> const& arguments)
  452. {
  453. if (arguments.size() != 2) {
  454. raise_error(ShellError::EvaluatedSyntaxError, "Expected exactly 2 arguments to error_if_unset", invoking_node.position());
  455. return nullptr;
  456. }
  457. auto name = TRY(TRY(const_cast<AST::Node&>(arguments.first()).run(*this))->resolve_as_string(*this));
  458. if (find_frame_containing_local_variable(name))
  459. return make_ref_counted<AST::SimpleVariable>(invoking_node.position(), name);
  460. auto error_value = TRY(TRY(const_cast<AST::Node&>(arguments.last()).run(*this))->resolve_as_string(*this));
  461. if (error_value.is_empty())
  462. error_value = TRY(String::formatted("Expected {} to be set", name));
  463. raise_error(ShellError::EvaluatedSyntaxError, error_value.bytes_as_string_view(), invoking_node.position());
  464. return nullptr;
  465. }
  466. ErrorOr<RefPtr<AST::Node>> Shell::immediate_null_if_unset_or_alternative(AST::ImmediateExpression& invoking_node, NonnullRefPtrVector<AST::Node> const& arguments)
  467. {
  468. if (arguments.size() != 2) {
  469. raise_error(ShellError::EvaluatedSyntaxError, "Expected exactly 2 arguments to null_if_unset_or_alternative", invoking_node.position());
  470. return nullptr;
  471. }
  472. auto name = TRY(TRY(const_cast<AST::Node&>(arguments.first()).run(*this))->resolve_as_string(*this));
  473. if (!find_frame_containing_local_variable(name))
  474. return arguments.last();
  475. return make_ref_counted<AST::SimpleVariable>(invoking_node.position(), name);
  476. }
  477. ErrorOr<RefPtr<AST::Node>> Shell::immediate_reexpand(AST::ImmediateExpression& invoking_node, NonnullRefPtrVector<AST::Node> const& arguments)
  478. {
  479. if (arguments.size() != 1) {
  480. raise_error(ShellError::EvaluatedSyntaxError, "Expected exactly 1 argument to reexpand", invoking_node.position());
  481. return nullptr;
  482. }
  483. auto value = TRY(TRY(const_cast<AST::Node&>(arguments.first()).run(*this))->resolve_as_string(*this));
  484. return parse(value, m_is_interactive, false);
  485. }
  486. ErrorOr<RefPtr<AST::Node>> Shell::immediate_length_of_variable(AST::ImmediateExpression& invoking_node, NonnullRefPtrVector<AST::Node> const& arguments)
  487. {
  488. if (arguments.size() != 1) {
  489. raise_error(ShellError::EvaluatedSyntaxError, "Expected exactly 1 argument to length_of_variable", invoking_node.position());
  490. return nullptr;
  491. }
  492. auto name = TRY(TRY(const_cast<AST::Node&>(arguments.first()).run(*this))->resolve_as_string(*this));
  493. auto variable = make_ref_counted<AST::SimpleVariable>(invoking_node.position(), name);
  494. return immediate_length_impl(
  495. invoking_node,
  496. { move(variable) },
  497. false);
  498. }
  499. ErrorOr<RefPtr<AST::Node>> Shell::run_immediate_function(StringView str, AST::ImmediateExpression& invoking_node, NonnullRefPtrVector<AST::Node> const& arguments)
  500. {
  501. #define __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(name) \
  502. if (str == #name) \
  503. return immediate_##name(invoking_node, arguments);
  504. ENUMERATE_SHELL_IMMEDIATE_FUNCTIONS()
  505. #undef __ENUMERATE_SHELL_IMMEDIATE_FUNCTION
  506. raise_error(ShellError::EvaluatedSyntaxError, DeprecatedString::formatted("Unknown immediate function {}", str), invoking_node.position());
  507. return nullptr;
  508. }
  509. bool Shell::has_immediate_function(StringView str)
  510. {
  511. #define __ENUMERATE_SHELL_IMMEDIATE_FUNCTION(name) \
  512. if (str == #name) \
  513. return true;
  514. ENUMERATE_SHELL_IMMEDIATE_FUNCTIONS()
  515. #undef __ENUMERATE_SHELL_IMMEDIATE_FUNCTION
  516. return false;
  517. }
  518. }