aboutsummaryrefslogtreecommitdiff
path: root/smash/builtin.c
diff options
context:
space:
mode:
authorNathan P. Reiner <nathan@nathanreiner.xyz>2022-12-15 18:20:33 +0100
committerNathan P. Reiner <nathan@nathanreiner.xyz>2022-12-15 18:20:33 +0100
commit828dd435725ea315abd2ea9875325ee3b17041a9 (patch)
tree72d80411d5cecc8758fc87867521374e90caa44d /smash/builtin.c
parent7536d000ac9a5188378f2749ecfd7f0ccb437573 (diff)
did this while lecture (builtins, parsing, exec and env by stdlib)
Diffstat (limited to 'smash/builtin.c')
-rw-r--r--smash/builtin.c86
1 files changed, 86 insertions, 0 deletions
diff --git a/smash/builtin.c b/smash/builtin.c
new file mode 100644
index 0000000..ad9c839
--- /dev/null
+++ b/smash/builtin.c
@@ -0,0 +1,86 @@
+#include "builtin.h"
+
+#include "../lib/sys/exit.h"
+#include "../lib/cstr/cstr.h"
+#include "../lib/sys/io.h"
+
+u64 __find_builtin_function_by_name(const char *name);
+
+int __builtin_fn_exit(int argc, const char **argv);
+int __builtin_fn_cd(int argc, const char **argv);
+int __builtin_fn_help(int argc, const char **argv);
+
+char *builtin_names[] = {
+ "exit",
+ "cd",
+ "help",
+ 0
+};
+
+int (*builtin_functions[])(int argc, const char **argv) = {
+ __builtin_fn_exit,
+ __builtin_fn_cd,
+ __builtin_fn_help
+};
+
+int __builtin_fn_exit(int argc, const char **argv)
+{
+ exit(0);
+}
+
+int __builtin_fn_cd(int argc, const char **argv)
+{
+ /* TODO: Implement */
+}
+
+int __builtin_fn_help(int argc, const char **argv)
+{
+ write(STDOUT_FD, "This is the help page...\n", 25);
+ write(STDOUT_FD, "TODO: help page\n", 16);
+ return 0;
+}
+
+u64 __find_builtin_function_by_name(const char *name)
+{
+ char **p = builtin_names;
+
+ while (*p) {
+ if (cstr_compare(*p, name) == 0)
+ return p - builtin_names;
+ ++p;
+ }
+
+ return -1;
+
+}
+
+u8 has_builtin_with_name(const char *name)
+{
+ return __find_builtin_function_by_name(name) != -1;
+}
+
+int run_builtin(const char *name, const char **argv)
+{
+ int argc = 0;
+ u64 builtin_index = __find_builtin_function_by_name(name);
+ const char **p = argv;
+ while (*p) {
+ ++argc;
+ ++p;
+ }
+
+ return builtin_functions[builtin_index](argc, argv);
+}
+
+#ifdef BUILTIN_UNIT_TEST
+
+int main() {
+ const char *argv[] = { "lelp", 0 };
+
+ if (has_builtin_with_name(argv[0]))
+ return run_builtin(argv[0], argv);
+
+ return 0;
+}
+
+#endif