2 * yosys -- Yosys Open SYnthesis Suite
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20 #include "kernel/yosys.h"
22 #ifdef YOSYS_ENABLE_READLINE
23 # include <readline/readline.h>
24 # include <readline/history.h>
35 RTLIL::Design
*yosys_design
= NULL
;
37 #ifdef YOSYS_ENABLE_TCL
38 Tcl_Interp
*yosys_tcl_interp
= NULL
;
41 std::string
stringf(const char *fmt
, ...)
47 string
= vstringf(fmt
, ap
);
53 std::string
vstringf(const char *fmt
, va_list ap
)
58 if (vasprintf(&str
, fmt
, ap
) < 0)
69 // this is very similar to fnmatch(). the exact rules used by this
72 // ? matches any character except
73 // * matches any sequence of characters
74 // [...] matches any of the characters in the list
75 // [!..] matches any of the characters not in the list
77 // a backslash may be used to escape the next characters in the
78 // pattern. each special character can also simply match itself.
80 static bool patmatch(const char *pattern
, const char *string
)
85 if (*pattern
== '\\') {
86 if (pattern
[1] == string
[0] && patmatch(pattern
+2, string
+1))
90 if (*pattern
== '?') {
93 return patmatch(pattern
+1, string
+1);
96 if (*pattern
== '*') {
98 if (patmatch(pattern
+1, string
++))
101 return pattern
[1] == 0;
104 if (*pattern
== '[') {
105 bool found_match
= false;
106 bool inverted_list
= pattern
[1] == '!';
107 const char *p
= pattern
+ (inverted_list
? 1 : 0);
111 if (found_match
!= inverted_list
&& patmatch(p
+1, string
+1))
125 if (*pattern
== *string
)
126 return patmatch(pattern
+1, string
+1);
131 int GetSize(RTLIL::Wire
*wire
)
138 Pass::init_register();
139 yosys_design
= new RTLIL::Design
;
143 void yosys_shutdown()
150 for (auto f
: log_files
)
156 Pass::done_register();
158 #ifdef YOSYS_ENABLE_TCL
159 if (yosys_tcl_interp
!= NULL
) {
160 Tcl_DeleteInterp(yosys_tcl_interp
);
162 yosys_tcl_interp
= NULL
;
166 for (auto &it
: loaded_plugins
)
169 loaded_plugins
.clear();
170 loaded_plugin_aliases
.clear();
173 RTLIL::IdString
new_id(std::string file
, int line
, std::string func
)
175 std::string str
= "$auto$";
176 size_t pos
= file
.find_last_of('/');
177 str
+= pos
!= std::string::npos
? file
.substr(pos
+1) : file
;
178 str
+= stringf(":%d:%s$%d", line
, func
.c_str(), autoidx
++);
182 RTLIL::Design
*yosys_get_design()
187 const char *create_prompt(RTLIL::Design
*design
, int recursion_counter
)
189 static char buffer
[100];
190 std::string str
= "\n";
191 if (recursion_counter
> 1)
192 str
+= stringf("(%d) ", recursion_counter
);
194 if (!design
->selected_active_module
.empty())
195 str
+= stringf(" [%s]", RTLIL::unescape_id(design
->selected_active_module
).c_str());
196 if (!design
->selection_stack
.empty() && !design
->selection_stack
.back().full_selection
) {
197 if (design
->selected_active_module
.empty())
199 else if (design
->selection_stack
.back().selected_modules
.size() != 1 || design
->selection_stack
.back().selected_members
.size() != 0 ||
200 design
->selection_stack
.back().selected_modules
.count(design
->selected_active_module
) == 0)
203 snprintf(buffer
, 100, "%s> ", str
.c_str());
207 #ifdef YOSYS_ENABLE_TCL
208 static int tcl_yosys_cmd(ClientData
, Tcl_Interp
*interp
, int argc
, const char *argv
[])
210 std::vector
<std::string
> args
;
211 for (int i
= 1; i
< argc
; i
++)
212 args
.push_back(argv
[i
]);
214 if (args
.size() >= 1 && args
[0] == "-import") {
215 for (auto &it
: pass_register
) {
216 std::string tcl_command_name
= it
.first
;
217 if (tcl_command_name
== "proc")
218 tcl_command_name
= "procs";
220 if (Tcl_GetCommandInfo(interp
, tcl_command_name
.c_str(), &info
) != 0) {
221 log("[TCL: yosys -import] Command name collision: found pre-existing command `%s' -> skip.\n", it
.first
.c_str());
223 std::string tcl_script
= stringf("proc %s args { yosys %s {*}$args }", tcl_command_name
.c_str(), it
.first
.c_str());
224 Tcl_Eval(interp
, tcl_script
.c_str());
230 if (args
.size() == 1) {
231 Pass::call(yosys_get_design(), args
[0]);
235 Pass::call(yosys_get_design(), args
);
239 extern Tcl_Interp
*yosys_get_tcl_interp()
241 if (yosys_tcl_interp
== NULL
) {
242 yosys_tcl_interp
= Tcl_CreateInterp();
243 Tcl_CreateCommand(yosys_tcl_interp
, "yosys", tcl_yosys_cmd
, NULL
, NULL
);
245 return yosys_tcl_interp
;
248 struct TclPass
: public Pass
{
249 TclPass() : Pass("tcl", "execute a TCL script file") { }
250 virtual void help() {
252 log(" tcl <filename>\n");
254 log("This command executes the tcl commands in the specified file.\n");
255 log("Use 'yosys cmd' to run the yosys command 'cmd' from tcl.\n");
257 log("The tcl command 'yosys -import' can be used to import all yosys\n");
258 log("commands directly as tcl commands to the tcl shell. The yosys\n");
259 log("command 'proc' is wrapped using the tcl command 'procs' in order\n");
260 log("to avoid a name collision with the tcl builting command 'proc'.\n");
263 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
265 log_cmd_error("Missing script file.\n");
267 extra_args(args
, 1, design
, false);
268 if (Tcl_EvalFile(yosys_get_tcl_interp(), args
[1].c_str()) != TCL_OK
)
269 log_cmd_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(yosys_get_tcl_interp()));
274 #if defined(__linux__)
275 std::string
proc_self_dirname ()
277 char path
[PATH_MAX
];
278 ssize_t buflen
= readlink("/proc/self/exe", path
, sizeof(path
));
280 log_error("readlink(\"/proc/self/exe\") failed: %s\n", strerror(errno
));
282 while (buflen
> 0 && path
[buflen
-1] != '/')
284 return std::string(path
, buflen
);
286 #elif defined(__APPLE__)
287 #include <mach-o/dyld.h>
288 std::string
proc_self_dirname ()
292 while (_NSGetExecutablePath(path
, &buflen
) != 0)
293 path
= (char *) realloc((void *) path
, buflen
);
294 while (buflen
> 0 && path
[buflen
-1] != '/')
296 return std::string(path
, buflen
);
298 #elif defined(EMSCRIPTEN)
299 std::string
proc_self_dirname ()
304 #error Dont know how to determine process executable base path!
307 std::string
proc_share_dirname ()
309 std::string proc_self_path
= proc_self_dirname();
310 std::string proc_share_path
= proc_self_path
+ "share/";
311 if (access(proc_share_path
.c_str(), X_OK
) == 0)
312 return proc_share_path
;
313 proc_share_path
= proc_self_path
+ "../share/yosys/";
314 if (access(proc_share_path
.c_str(), X_OK
) == 0)
315 return proc_share_path
;
316 log_error("proc_share_dirname: unable to determine share/ directory!\n");
319 bool fgetline(FILE *f
, std::string
&buffer
)
324 if (fgets(block
, 4096, f
) == NULL
)
327 if (buffer
.size() > 0 && (buffer
[buffer
.size()-1] == '\n' || buffer
[buffer
.size()-1] == '\r')) {
328 while (buffer
.size() > 0 && (buffer
[buffer
.size()-1] == '\n' || buffer
[buffer
.size()-1] == '\r'))
329 buffer
.resize(buffer
.size()-1);
335 static void handle_label(std::string
&command
, bool &from_to_active
, const std::string
&run_from
, const std::string
&run_to
)
340 while (pos
< GetSize(command
) && (command
[pos
] == ' ' || command
[pos
] == '\t'))
343 while (pos
< GetSize(command
) && command
[pos
] != ' ' && command
[pos
] != '\t' && command
[pos
] != '\r' && command
[pos
] != '\n')
344 label
+= command
[pos
++];
346 if (label
.back() == ':' && GetSize(label
) > 1)
348 label
= label
.substr(0, GetSize(label
)-1);
349 command
= command
.substr(pos
);
351 if (label
== run_from
)
352 from_to_active
= true;
353 else if (label
== run_to
|| (run_from
== run_to
&& !run_from
.empty()))
354 from_to_active
= false;
358 void run_frontend(std::string filename
, std::string command
, RTLIL::Design
*design
, std::string
*backend_command
, std::string
*from_to_label
)
360 if (command
== "auto") {
361 if (filename
.size() > 2 && filename
.substr(filename
.size()-2) == ".v")
363 else if (filename
.size() > 2 && filename
.substr(filename
.size()-3) == ".sv")
364 command
= "verilog -sv";
365 else if (filename
.size() > 3 && filename
.substr(filename
.size()-3) == ".il")
367 else if (filename
.size() > 3 && filename
.substr(filename
.size()-3) == ".ys")
369 else if (filename
== "-")
372 log_error("Can't guess frontend for input file `%s' (missing -f option)!\n", filename
.c_str());
375 if (command
== "script")
377 std::string run_from
, run_to
;
378 bool from_to_active
= true;
380 if (from_to_label
!= NULL
) {
381 size_t pos
= from_to_label
->find(':');
382 if (pos
== std::string::npos
) {
383 run_from
= *from_to_label
;
384 run_to
= *from_to_label
;
386 run_from
= from_to_label
->substr(0, pos
);
387 run_to
= from_to_label
->substr(pos
+1);
389 from_to_active
= run_from
.empty();
392 log("\n-- Executing script file `%s' --\n", filename
.c_str());
397 f
= fopen(filename
.c_str(), "r");
400 log_error("Can't open script file `%s' for reading: %s\n", filename
.c_str(), strerror(errno
));
402 FILE *backup_script_file
= Frontend::current_script_file
;
403 Frontend::current_script_file
= f
;
407 while (fgetline(f
, command
)) {
408 while (!command
.empty() && command
[command
.size()-1] == '\\') {
409 std::string next_line
;
410 if (!fgetline(f
, next_line
))
412 command
.resize(command
.size()-1);
413 command
+= next_line
;
415 handle_label(command
, from_to_active
, run_from
, run_to
);
417 Pass::call(design
, command
);
420 if (!command
.empty()) {
421 handle_label(command
, from_to_active
, run_from
, run_to
);
423 Pass::call(design
, command
);
426 catch (log_cmd_error_expection
) {
427 Frontend::current_script_file
= backup_script_file
;
428 throw log_cmd_error_expection();
431 Frontend::current_script_file
= backup_script_file
;
436 if (backend_command
!= NULL
&& *backend_command
== "auto")
437 *backend_command
= "";
442 if (filename
== "-") {
443 log("\n-- Parsing stdin using frontend `%s' --\n", command
.c_str());
445 log("\n-- Parsing `%s' using frontend `%s' --\n", filename
.c_str(), command
.c_str());
448 Frontend::frontend_call(design
, NULL
, filename
, command
);
451 void run_pass(std::string command
, RTLIL::Design
*design
)
453 log("\n-- Running pass `%s' --\n", command
.c_str());
455 Pass::call(design
, command
);
458 void run_backend(std::string filename
, std::string command
, RTLIL::Design
*design
)
460 if (command
== "auto") {
461 if (filename
.size() > 2 && filename
.substr(filename
.size()-2) == ".v")
463 else if (filename
.size() > 3 && filename
.substr(filename
.size()-3) == ".il")
465 else if (filename
.size() > 5 && filename
.substr(filename
.size()-5) == ".blif")
467 else if (filename
== "-")
469 else if (filename
.empty())
472 log_error("Can't guess backend for output file `%s' (missing -b option)!\n", filename
.c_str());
475 if (filename
.empty())
478 if (filename
== "-") {
479 log("\n-- Writing to stdout using backend `%s' --\n", command
.c_str());
481 log("\n-- Writing to `%s' using backend `%s' --\n", filename
.c_str(), command
.c_str());
484 Backend::backend_call(design
, NULL
, filename
, command
);
487 #ifdef YOSYS_ENABLE_READLINE
488 static char *readline_cmd_generator(const char *text
, int state
)
490 static std::map
<std::string
, Pass
*>::iterator it
;
494 it
= pass_register
.begin();
498 for (; it
!= pass_register
.end(); it
++) {
499 if (it
->first
.substr(0, len
) == text
)
500 return strdup((it
++)->first
.c_str());
505 static char *readline_obj_generator(const char *text
, int state
)
507 static std::vector
<char*> obj_names
;
515 RTLIL::Design
*design
= yosys_get_design();
516 int len
= strlen(text
);
518 if (design
->selected_active_module
.empty())
520 for (auto &it
: design
->modules_
)
521 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
522 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
525 if (design
->modules_
.count(design
->selected_active_module
) > 0)
527 RTLIL::Module
*module
= design
->modules_
.at(design
->selected_active_module
);
529 for (auto &it
: module
->wires_
)
530 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
531 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
533 for (auto &it
: module
->memories
)
534 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
535 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
537 for (auto &it
: module
->cells_
)
538 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
539 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
541 for (auto &it
: module
->processes
)
542 if (RTLIL::unescape_id(it
.first
).substr(0, len
) == text
)
543 obj_names
.push_back(strdup(RTLIL::id2cstr(it
.first
)));
546 std::sort(obj_names
.begin(), obj_names
.end());
549 if (idx
< obj_names
.size())
550 return strdup(obj_names
[idx
++]);
557 static char **readline_completion(const char *text
, int start
, int)
560 return rl_completion_matches(text
, readline_cmd_generator
);
561 if (strncmp(rl_line_buffer
, "read_", 5) && strncmp(rl_line_buffer
, "write_", 6))
562 return rl_completion_matches(text
, readline_obj_generator
);
567 void shell(RTLIL::Design
*design
)
569 static int recursion_counter
= 0;
572 log_cmd_error_throw
= true;
574 #ifdef YOSYS_ENABLE_READLINE
575 rl_readline_name
= "yosys";
576 rl_attempted_completion_function
= readline_completion
;
577 rl_basic_word_break_characters
= " \t\n";
580 char *command
= NULL
;
581 #ifdef YOSYS_ENABLE_READLINE
582 while ((command
= readline(create_prompt(design
, recursion_counter
))) != NULL
)
584 char command_buffer
[4096];
585 while ((command
= fgets(command_buffer
, 4096, stdin
)) != NULL
)
588 if (command
[strspn(command
, " \t\r\n")] == 0)
590 #ifdef YOSYS_ENABLE_READLINE
591 add_history(command
);
594 char *p
= command
+ strspn(command
, " \t\r\n");
595 if (!strncmp(p
, "exit", 4)) {
597 p
+= strspn(p
, " \t\r\n");
603 log_assert(design
->selection_stack
.size() == 1);
604 Pass::call(design
, command
);
605 } catch (log_cmd_error_expection
) {
606 while (design
->selection_stack
.size() > 1)
607 design
->selection_stack
.pop_back();
615 log_cmd_error_throw
= false;
618 struct ShellPass
: public Pass
{
619 ShellPass() : Pass("shell", "enter interactive command mode") { }
620 virtual void help() {
624 log("This command enters the interactive command mode. This can be useful\n");
625 log("in a script to interrupt the script at a certain point and allow for\n");
626 log("interactive inspection or manual synthesis of the design at this point.\n");
628 log("The command prompt of the interactive shell indicates the current\n");
629 log("selection (see 'help select'):\n");
632 log(" the entire design is selected\n");
635 log(" only part of the design is selected\n");
637 log(" yosys [modname]>\n");
638 log(" the entire module 'modname' is selected using 'select -module modname'\n");
640 log(" yosys [modname]*>\n");
641 log(" only part of current module 'modname' is selected\n");
643 log("When in interactive shell, some errors (e.g. invalid command arguments)\n");
644 log("do not terminate yosys but return to the command prompt.\n");
646 log("This command is the default action if nothing else has been specified\n");
647 log("on the command line.\n");
649 log("Press Ctrl-D or type 'exit' to leave the interactive shell.\n");
652 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
653 extra_args(args
, 1, design
, false);
658 #ifdef YOSYS_ENABLE_READLINE
659 struct HistoryPass
: public Pass
{
660 HistoryPass() : Pass("history", "show last interactive commands") { }
661 virtual void help() {
665 log("This command prints all commands in the shell history buffer. This are\n");
666 log("all commands executed in an interactive session, but not the commands\n");
667 log("from executed scripts.\n");
670 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
671 extra_args(args
, 1, design
, false);
672 for(HIST_ENTRY
**list
= history_list(); *list
!= NULL
; list
++)
673 log("%s\n", (*list
)->line
);
678 struct ScriptPass
: public Pass
{
679 ScriptPass() : Pass("script", "execute commands from script file") { }
680 virtual void help() {
682 log(" script <filename> [<from_label>:<to_label>]\n");
684 log("This command executes the yosys commands in the specified file.\n");
686 log("The 2nd argument can be used to only execute the section of the\n");
687 log("file between the specified labels. An empty from label is synonymous\n");
688 log("for the beginning of the file and an empty to label is synonymous\n");
689 log("for the end of the file.\n");
691 log("If only one label is specified (without ':') then only the block\n");
692 log("marked with that label (until the next label) is executed.\n");
695 virtual void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) {
697 log_cmd_error("Missing script file.\n");
698 else if (args
.size() == 2)
699 run_frontend(args
[1], "script", design
, NULL
, NULL
);
700 else if (args
.size() == 3)
701 run_frontend(args
[1], "script", design
, NULL
, &args
[2]);
703 extra_args(args
, 2, design
, false);