From d415b4d98a0ac7d5177e3b5844477e8460bfa862 Mon Sep 17 00:00:00 2001
From: Jannis Harder <me@jix.one>
Date: Mon, 6 Nov 2023 16:40:13 +0100
Subject: [PATCH] cli: Cleanups for tcl argument handling

* Keep the previous behavior when no tcl script is used
* Do not treat "-" as a flag but as a positional argument
* Keep including <unistd.h> as it's also used for other functions (at
  least for the emscripten build)
* Move the custom getopt implementation into the Yosys namespace to
  avoid potential collisions
---
 kernel/driver.cc | 17 +++++++++++++----
 1 file changed, 13 insertions(+), 4 deletions(-)

diff --git a/kernel/driver.cc b/kernel/driver.cc
index 661400e7a..c779611e0 100644
--- a/kernel/driver.cc
+++ b/kernel/driver.cc
@@ -49,6 +49,12 @@
 #  include <sys/user.h>
 #endif
 
+#if !defined(_WIN32) || defined(__MINGW32__)
+#  include <unistd.h>
+#endif
+
+USING_YOSYS_NAMESPACE
+
 char *optarg;
 int optind = 1, optcur = 1, optopt = 0;
 int getopt(int argc, char **argv, const char *optstring)
@@ -56,7 +62,7 @@ int getopt(int argc, char **argv, const char *optstring)
 	if (optind >= argc)
 		return -1;
 
-	if (argv[optind][0] != '-') {
+	if (argv[optind][0] != '-' || argv[optind][1] == 0) {
 		optopt = 1;
 		optarg = argv[optind++];
 		return optopt;
@@ -91,9 +97,6 @@ int getopt(int argc, char **argv, const char *optstring)
 	return optopt;
 }
 
-
-USING_YOSYS_NAMESPACE
-
 #ifdef EMSCRIPTEN
 #  include <sys/stat.h>
 #  include <sys/types.h>
@@ -573,6 +576,12 @@ int main(int argc, char **argv)
 		run_pass(vdef_cmd);
 	}
 
+	if (scriptfile.empty() || !scriptfile_tcl) {
+		// Without a TCL script, arguments following '--' are also treated as frontend files
+		for (int i = optind; i < argc; ++i)
+			frontend_files.push_back(argv[i]);
+	}
+
 	for (auto it = frontend_files.begin(); it != frontend_files.end(); ++it) {
 		if (run_frontend((*it).c_str(), frontend_command))
 			run_shell = false;