Improved readline tab completion
[yosys.git] / kernel / driver.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
5 *
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.
9 *
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.
17 *
18 */
19
20 #include <stdio.h>
21 #include <readline/readline.h>
22 #include <readline/history.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include <libgen.h>
26 #include <dlfcn.h>
27
28 #include <algorithm>
29
30 #include "kernel/rtlil.h"
31 #include "kernel/register.h"
32 #include "kernel/log.h"
33
34 bool fgetline(FILE *f, std::string &buffer)
35 {
36 buffer = "";
37 char block[4096];
38 while (1) {
39 if (fgets(block, 4096, f) == NULL)
40 return false;
41 buffer += block;
42 if (buffer.size() > 0 && (buffer[buffer.size()-1] == '\n' || buffer[buffer.size()-1] == '\r'))
43 return true;
44 }
45 }
46
47 static void run_frontend(std::string filename, std::string command, RTLIL::Design *design, std::string *backend_command)
48 {
49 if (command == "auto") {
50 if (filename.size() > 2 && filename.substr(filename.size()-2) == ".v")
51 command = "verilog";
52 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".il")
53 command = "ilang";
54 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".ys")
55 command = "script";
56 else if (filename == "-")
57 command = "script";
58 else
59 log_error("Can't guess frontend for input file `%s' (missing -f option)!\n", filename.c_str());
60 }
61
62 if (command == "script") {
63 log("\n-- Executing script file `%s' --\n", filename.c_str());
64 FILE *f = stdin;
65 if (filename != "-")
66 f = fopen(filename.c_str(), "r");
67 if (f == NULL)
68 log_error("Can't open script file `%s' for reading: %s\n", filename.c_str(), strerror(errno));
69 std::string command;
70 while (fgetline(f, command)) {
71 Pass::call(design, command);
72 design->check();
73 }
74 if (!command.empty()) {
75 Pass::call(design, command);
76 design->check();
77 }
78 if (filename != "-")
79 fclose(f);
80 if (backend_command != NULL && *backend_command == "auto")
81 *backend_command = "";
82 return;
83 }
84
85 if (filename == "-") {
86 log("\n-- Parsing stdin using frontend `%s' --\n", command.c_str());
87 } else {
88 log("\n-- Parsing `%s' using frontend `%s' --\n", filename.c_str(), command.c_str());
89 }
90
91 Frontend::frontend_call(design, NULL, filename, command);
92 design->check();
93 }
94
95 static void run_pass(std::string command, RTLIL::Design *design)
96 {
97 log("\n-- Running pass `%s' --\n", command.c_str());
98
99 Pass::call(design, command);
100 design->check();
101 }
102
103 static void run_backend(std::string filename, std::string command, RTLIL::Design *design)
104 {
105 if (command == "auto") {
106 if (filename.size() > 2 && filename.substr(filename.size()-2) == ".v")
107 command = "verilog";
108 else if (filename.size() > 3 && filename.substr(filename.size()-3) == ".il")
109 command = "ilang";
110 else if (filename == "-")
111 command = "ilang";
112 else if (filename.empty())
113 return;
114 else
115 log_error("Can't guess frontend for input file `%s' (missing -f option)!\n", filename.c_str());
116 }
117
118 if (filename.empty())
119 filename = "-";
120
121 if (filename == "-") {
122 log("\n-- Writing to stdout using backend `%s' --\n", command.c_str());
123 } else {
124 log("\n-- Writing to `%s' using backend `%s' --\n", filename.c_str(), command.c_str());
125 }
126
127 Backend::backend_call(design, NULL, filename, command);
128 design->check();
129 }
130
131 static char *readline_cmd_generator(const char *text, int state)
132 {
133 static std::map<std::string, Pass*>::iterator it;
134 static int len;
135
136 if (!state) {
137 it = REGISTER_INTERN::pass_register.begin();
138 len = strlen(text);
139 }
140
141 for (; it != REGISTER_INTERN::pass_register.end(); it++) {
142 if (it->first.substr(0, len) == text)
143 return strdup((it++)->first.c_str());
144 }
145 return NULL;
146 }
147
148 static char *readline_obj_generator(const char *text, int state)
149 {
150 static std::vector<char*> obj_names;
151 static size_t idx;
152
153 if (!state)
154 {
155 idx = 0;
156 obj_names.clear();
157
158 RTLIL::Design *design = yosys_get_design();
159 int len = strlen(text);
160
161 if (design->selected_active_module.empty())
162 {
163 for (auto &it : design->modules)
164 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
165 obj_names.push_back(strdup(RTLIL::id2cstr(it.first.c_str())));
166 }
167 else
168 if (design->modules.count(design->selected_active_module) > 0)
169 {
170 RTLIL::Module *module = design->modules.at(design->selected_active_module);
171
172 for (auto &it : module->wires)
173 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
174 obj_names.push_back(strdup(RTLIL::id2cstr(it.first.c_str())));
175
176 for (auto &it : module->memories)
177 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
178 obj_names.push_back(strdup(RTLIL::id2cstr(it.first.c_str())));
179
180 for (auto &it : module->cells)
181 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
182 obj_names.push_back(strdup(RTLIL::id2cstr(it.first.c_str())));
183
184 for (auto &it : module->processes)
185 if (RTLIL::unescape_id(it.first).substr(0, len) == text)
186 obj_names.push_back(strdup(RTLIL::id2cstr(it.first.c_str())));
187 }
188
189 std::sort(obj_names.begin(), obj_names.end());
190 }
191
192 if (idx < obj_names.size())
193 return strdup(obj_names[idx++]);
194
195 idx = 0;
196 obj_names.clear();
197 return NULL;
198 }
199
200 static char **readline_completion(const char *text, int start, int)
201 {
202 if (start == 0)
203 return rl_completion_matches(text, readline_cmd_generator);
204 if (strncmp(rl_line_buffer, "read_", 5) && strncmp(rl_line_buffer, "write_", 6))
205 return rl_completion_matches(text, readline_obj_generator);
206 return NULL;
207 }
208
209 static const char *create_prompt(RTLIL::Design *design, int recursion_counter)
210 {
211 static char buffer[100];
212 std::string str = "\n";
213 if (recursion_counter > 1)
214 str += stringf("(%d) ", recursion_counter);
215 str += "yosys";
216 if (!design->selected_active_module.empty())
217 str += stringf(" [%s]", design->selected_active_module.c_str());
218 if (!design->selection_stack.back().full_selection) {
219 if (design->selected_active_module.empty())
220 str += "*";
221 else if (design->selection_stack.back().selected_modules.size() != 1 || design->selection_stack.back().selected_members.size() != 0 ||
222 design->selection_stack.back().selected_modules.count(design->selected_active_module) == 0)
223 str += "*";
224 }
225 snprintf(buffer, 100, "%s> ", str.c_str());
226 return buffer;
227 }
228
229 static void shell(RTLIL::Design *design)
230 {
231 static int recursion_counter = 0;
232
233 recursion_counter++;
234 log_cmd_error_throw = true;
235
236 rl_readline_name = "yosys";
237 rl_attempted_completion_function = readline_completion;
238
239 char *command = NULL;
240 while ((command = readline(create_prompt(design, recursion_counter))) != NULL)
241 {
242 if (command[strspn(command, " \t\r\n")] == 0)
243 continue;
244 add_history(command);
245
246 char *p = command + strspn(command, " \t\r\n");
247 if (!strncmp(p, "exit", 4)) {
248 p += 4;
249 p += strspn(p, " \t\r\n");
250 if (*p == 0)
251 break;
252 }
253
254 try {
255 assert(design->selection_stack.size() == 1);
256 Pass::call(design, command);
257 } catch (int) {
258 while (design->selection_stack.size() > 1)
259 design->selection_stack.pop_back();
260 log_reset_stack();
261 }
262 }
263 if (command == NULL)
264 printf("exit\n");
265
266 recursion_counter--;
267 log_cmd_error_throw = false;
268 }
269
270 struct ShellPass : public Pass {
271 ShellPass() : Pass("shell", "enter interactive command mode") { }
272 virtual void help() {
273 log("\n");
274 log(" shell\n");
275 log("\n");
276 log("This command enters the interactive command mode. This can be useful\n");
277 log("in a script to interrupt the script at a certain point and allow for\n");
278 log("interactive inspection or manual synthesis of the design at this point.\n");
279 log("\n");
280 log("The command prompt of the interactive shell indicates the current\n");
281 log("selection (see 'help select'):\n");
282 log("\n");
283 log(" yosys>\n");
284 log(" the entire design is selected\n");
285 log("\n");
286 log(" yosys*>\n");
287 log(" only part of the design is selected\n");
288 log("\n");
289 log(" yosys [modname]>\n");
290 log(" the entire module 'modname' is selected using 'select -module modname'\n");
291 log("\n");
292 log(" yosys [modname]*>\n");
293 log(" only part of current module 'modname' is selected\n");
294 log("\n");
295 log("When in interactive shell, some errors (e.g. invalid command arguments)\n");
296 log("do not terminate yosys but return to the command prompt.\n");
297 log("\n");
298 log("This command is the default action if nothing else has been specified\n");
299 log("on the command line.\n");
300 log("\n");
301 log("Press Ctrl-D or type 'exit' to leave the interactive shell.\n");
302 log("\n");
303 }
304 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
305 extra_args(args, 1, design, false);
306 shell(design);
307 }
308 } ShellPass;
309
310 struct ScriptPass : public Pass {
311 ScriptPass() : Pass("script", "execute commands from script file") { }
312 virtual void help() {
313 log("\n");
314 log(" script <filename>\n");
315 log("\n");
316 log("This command executes the yosys commands in the specified file.\n");
317 log("\n");
318 }
319 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
320 if (args.size() < 2)
321 log_cmd_error("Missing script file.\n");
322 if (args.size() > 2)
323 extra_args(args, 1, design, false);
324 run_frontend(args[1], "script", design, NULL);
325 }
326 } ScriptPass;
327
328 #ifdef YOSYS_ENABLE_TCL
329 static Tcl_Interp *yosys_tcl_interp = NULL;
330
331 static int tcl_yosys_cmd(ClientData, Tcl_Interp *interp, int argc, const char *argv[])
332 {
333 std::vector<std::string> args;
334 for (int i = 1; i < argc; i++)
335 args.push_back(argv[i]);
336
337 if (args.size() >= 1 && args[0] == "-import") {
338 for (auto &it : REGISTER_INTERN::pass_register) {
339 std::string tcl_command_name = it.first;
340 if (tcl_command_name == "proc")
341 tcl_command_name = "procs";
342 Tcl_CmdInfo info;
343 if (Tcl_GetCommandInfo(interp, tcl_command_name.c_str(), &info) != 0) {
344 log("[TCL: yosys -import] Command name collision: found pre-existing command `%s' -> skip.\n", it.first.c_str());
345 } else {
346 std::string tcl_script = stringf("proc %s args { yosys %s {*}$args }", tcl_command_name.c_str(), it.first.c_str());
347 Tcl_Eval(interp, tcl_script.c_str());
348 }
349 }
350 return TCL_OK;
351 }
352
353 if (args.size() == 1) {
354 Pass::call(yosys_get_design(), args[0]);
355 return TCL_OK;
356 }
357
358 Pass::call(yosys_get_design(), args);
359 return TCL_OK;
360 }
361
362 extern Tcl_Interp *yosys_get_tcl_interp()
363 {
364 if (yosys_tcl_interp == NULL) {
365 yosys_tcl_interp = Tcl_CreateInterp();
366 Tcl_CreateCommand(yosys_tcl_interp, "yosys", tcl_yosys_cmd, NULL, NULL);
367 }
368 return yosys_tcl_interp;
369 }
370
371 struct TclPass : public Pass {
372 TclPass() : Pass("tcl", "execute a TCL script file") { }
373 virtual void help() {
374 log("\n");
375 log(" tcl <filename>\n");
376 log("\n");
377 log("This command executes the tcl commands in the specified file.\n");
378 log("Use 'yosys cmd' to run the yosys command 'cmd' from tcl.\n");
379 log("\n");
380 log("The tcl command 'yosys -import' can be used to import all yosys\n");
381 log("commands directly as tcl commands to the tcl shell. The yosys\n");
382 log("command 'proc' is wrapped using the tcl command 'procs' in order\n");
383 log("to avoid a name collision with the tcl builting command 'proc'.\n");
384 log("\n");
385 }
386 virtual void execute(std::vector<std::string> args, RTLIL::Design *design) {
387 if (args.size() < 2)
388 log_cmd_error("Missing script file.\n");
389 if (args.size() > 2)
390 extra_args(args, 1, design, false);
391 if (Tcl_EvalFile(yosys_get_tcl_interp(), args[1].c_str()) != TCL_OK)
392 log_cmd_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(yosys_get_tcl_interp()));
393 }
394 } TclPass;
395 #endif
396
397 static RTLIL::Design *yosys_design = NULL;
398
399 extern RTLIL::Design *yosys_get_design()
400 {
401 return yosys_design;
402 }
403
404 std::string rewrite_yosys_exe(std::string exe)
405 {
406 char buffer[1024];
407 ssize_t buflen = readlink("/proc/self/exe", buffer, sizeof(buffer)-1);
408
409 if (buflen < 0)
410 return exe;
411
412 buffer[buflen] = 0;
413 std::string newexe = stringf("%s/%s", dirname(buffer), exe.c_str());
414 if (access(newexe.c_str(), X_OK) == 0)
415 return newexe;
416
417 return exe;
418 }
419
420 int main(int argc, char **argv)
421 {
422 std::string frontend_command = "auto";
423 std::string backend_command = "auto";
424 std::vector<std::string> passes_commands;
425 std::vector<void*> loaded_modules;
426 std::string output_filename = "";
427 std::string scriptfile = "";
428 bool scriptfile_tcl = false;
429 bool got_output_filename = false;
430
431 int opt;
432 while ((opt = getopt(argc, argv, "Sm:f:b:o:p:l:qts:c:")) != -1)
433 {
434 switch (opt)
435 {
436 case 'S':
437 backend_command = "verilog -noattr";
438 passes_commands.push_back("hierarchy");
439 passes_commands.push_back("proc");
440 passes_commands.push_back("opt");
441 passes_commands.push_back("memory");
442 passes_commands.push_back("techmap");
443 passes_commands.push_back("opt");
444 break;
445 case 'm':
446 loaded_modules.push_back(dlopen(optarg, RTLD_LAZY|RTLD_GLOBAL));
447 if (loaded_modules.back() == NULL) {
448 fprintf(stderr, "Can't load module `%s': %s\n", optarg, dlerror());
449 exit(1);
450 }
451 break;
452 case 'f':
453 frontend_command = optarg;
454 break;
455 case 'b':
456 backend_command = optarg;
457 break;
458 case 'p':
459 passes_commands.push_back(optarg);
460 break;
461 case 'o':
462 output_filename = optarg;
463 got_output_filename = true;
464 break;
465 case 'l':
466 log_files.push_back(fopen(optarg, "wt"));
467 if (log_files.back() == NULL) {
468 fprintf(stderr, "Can't open log file `%s' for writing!\n", optarg);
469 exit(1);
470 }
471 break;
472 case 'q':
473 log_errfile = stderr;
474 break;
475 case 't':
476 log_time = true;
477 break;
478 case 's':
479 scriptfile = optarg;
480 scriptfile_tcl = false;
481 break;
482 case 'c':
483 scriptfile = optarg;
484 scriptfile_tcl = true;
485 break;
486 default:
487 fprintf(stderr, "\n");
488 fprintf(stderr, "Usage: %s [-S] [-q] [-t] [-l logfile] [-o <outfile>] [-f <frontend>] [{-s|-c} <scriptfile>]\n", argv[0]);
489 fprintf(stderr, " %*s[-p <pass> [-p ..]] [-b <backend>] [-m <module_file>] [<infile> [..]]\n", int(strlen(argv[0])+1), "");
490 fprintf(stderr, "\n");
491 fprintf(stderr, " -q\n");
492 fprintf(stderr, " quiet operation. only write error messages to console\n");
493 fprintf(stderr, "\n");
494 fprintf(stderr, " -t\n");
495 fprintf(stderr, " annotate all log messages with a time stamp\n");
496 fprintf(stderr, "\n");
497 fprintf(stderr, " -l logfile\n");
498 fprintf(stderr, " write log messages to the specified file\n");
499 fprintf(stderr, "\n");
500 fprintf(stderr, " -o outfile\n");
501 fprintf(stderr, " write the design to the specified file on exit\n");
502 fprintf(stderr, "\n");
503 fprintf(stderr, " -b backend\n");
504 fprintf(stderr, " use this backend for the output file specified on the command line\n");
505 fprintf(stderr, "\n");
506 fprintf(stderr, " -f backend\n");
507 fprintf(stderr, " use the specified front for the input files on the command line\n");
508 fprintf(stderr, "\n");
509 fprintf(stderr, " -s scriptfile\n");
510 fprintf(stderr, " execute the commands in the script file\n");
511 fprintf(stderr, "\n");
512 fprintf(stderr, " -c tcl_scriptfile\n");
513 fprintf(stderr, " execute the commands in the tcl script file (see 'help tcl' for details)\n");
514 fprintf(stderr, "\n");
515 fprintf(stderr, " -p command\n");
516 fprintf(stderr, " execute the commands\n");
517 fprintf(stderr, "\n");
518 fprintf(stderr, " -m module_file\n");
519 fprintf(stderr, " load the specified module (aka plugin)\n");
520 fprintf(stderr, "\n");
521 fprintf(stderr, "The option -S is an alias for the following options that perform a simple\n");
522 fprintf(stderr, "transformation of the input to a gate-level netlist. This can be helpful when\n");
523 fprintf(stderr, "e.g. using yosys as a pre-processor for a tool that can't understand full verilog.\n");
524 fprintf(stderr, "\n");
525 fprintf(stderr, " -b 'verilog -noattr' -p hierarchy -p proc -p opt -p memory -p techmap -p opt\n");
526 fprintf(stderr, "\n");
527 fprintf(stderr, "For more complex synthesis jobs it is recommended to use the read_* and write_*\n");
528 fprintf(stderr, "commands in a script file instead of specifying input and output files on the\n");
529 fprintf(stderr, "command line.\n");
530 fprintf(stderr, "\n");
531 fprintf(stderr, "When no commands, script files and input files are specified on the command\n");
532 fprintf(stderr, "line, yosys automatically enters the interactive command mode. Use the 'help'\n");
533 fprintf(stderr, "command to get information on the individual commands.\n");
534 fprintf(stderr, "\n");
535 exit(1);
536 }
537 }
538
539 if (log_errfile == NULL)
540 log_files.push_back(stderr);
541
542 log("\n");
543 log(" /-----------------------------------------------------------------------------\\\n");
544 log(" | |\n");
545 log(" | yosys -- Yosys Open SYnthesis Suite |\n");
546 log(" | |\n");
547 log(" | Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> |\n");
548 log(" | |\n");
549 log(" | Permission to use, copy, modify, and/or distribute this software for any |\n");
550 log(" | purpose with or without fee is hereby granted, provided that the above |\n");
551 log(" | copyright notice and this permission notice appear in all copies. |\n");
552 log(" | |\n");
553 log(" | THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES |\n");
554 log(" | WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF |\n");
555 log(" | MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR |\n");
556 log(" | ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |\n");
557 log(" | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN |\n");
558 log(" | ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF |\n");
559 log(" | OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |\n");
560 log(" | |\n");
561 log(" \\-----------------------------------------------------------------------------/\n");
562 log("\n");
563
564 Pass::init_register();
565
566 yosys_design = new RTLIL::Design;
567 yosys_design->selection_stack.push_back(RTLIL::Selection());
568 log_push();
569
570 if (optind == argc && passes_commands.size() == 0 && scriptfile.empty()) {
571 if (!got_output_filename)
572 backend_command = "";
573 shell(yosys_design);
574 }
575
576 while (optind < argc)
577 run_frontend(argv[optind++], frontend_command, yosys_design, output_filename == "-" ? &backend_command : NULL);
578
579 if (!scriptfile.empty()) {
580 if (scriptfile_tcl) {
581 #ifdef YOSYS_ENABLE_TCL
582 if (Tcl_EvalFile(yosys_get_tcl_interp(), scriptfile.c_str()) != TCL_OK)
583 log_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(yosys_get_tcl_interp()));
584 #else
585 log_error("Can't exectue TCL script: this version of yosys is not built with TCL support enabled.\n");
586 #endif
587 } else
588 run_frontend(scriptfile, "script", yosys_design, output_filename == "-" ? &backend_command : NULL);
589 }
590
591 for (auto it = passes_commands.begin(); it != passes_commands.end(); it++)
592 run_pass(*it, yosys_design);
593
594 if (!backend_command.empty())
595 run_backend(output_filename, backend_command, yosys_design);
596
597 delete yosys_design;
598 yosys_design = NULL;
599
600 log("\nREADY.\n");
601 log_pop();
602
603 for (auto f : log_files)
604 if (f != stderr)
605 fclose(f);
606 log_errfile = NULL;
607 log_files.clear();
608
609 Pass::done_register();
610
611 for (auto mod : loaded_modules)
612 dlclose(mod);
613
614 #ifdef YOSYS_ENABLE_TCL
615 if (yosys_tcl_interp != NULL) {
616 Tcl_DeleteInterp(yosys_tcl_interp);
617 Tcl_Finalize();
618 yosys_tcl_interp = NULL;
619 }
620 #endif
621
622 return 0;
623 }
624