def __init__(self): # XXX use 0 and 1 instead of sys.stdin.fileno() and sys.stdout.fileno() # because otherwise problems at testing occur self.current_instream = PrologInputStream(fdopen_as_stream(0, "r", False)) self.current_outstream = PrologOutputStream(fdopen_as_stream(1, "w", False)) self.streams = {self.current_instream.fd(): self.current_instream, self.current_outstream.fd(): self.current_outstream} self.aliases = {self.current_instream.alias: self.current_instream, self.current_outstream.alias: self.current_outstream}
def __init__(self): # XXX use 0 and 1 instead of sys.stdin.fileno() and sys.stdout.fileno() # because otherwise problems at testing occur self.current_instream = PrologInputStream( fdopen_as_stream(0, "r", False)) self.current_outstream = PrologOutputStream( fdopen_as_stream(1, "w", False)) self.streams = { self.current_instream.fd(): self.current_instream, self.current_outstream.fd(): self.current_outstream } self.aliases = { self.current_instream.alias: self.current_instream, self.current_outstream.alias: self.current_outstream }
def entry_point(argv): # Pycket's params jit.set_param(None, 'trace_limit', 1000000) jit.set_param(None, 'threshold', 131) jit.set_param(None, 'trace_eagerness', 50) jit.set_param(None, 'max_unroll_loops', 15) # HT pyrolog for i in range(len(argv)): if argv[i] == '--jit': if len(argv) == i + 1: print 'missing argument after --jit' return 2 jitarg = argv[i + 1] del argv[i:i + 2] jit.set_user_param(None, jitarg) break if len(argv) > 1: print 'too many arguments' if we_are_translated(): from rpython.rlib import streamio from pycket import pycket_json stdin = streamio.fdopen_as_stream(0, "r") json = pycket_json.loads(stdin.readall()) return main(core.json_to_term(json)) else: import sys, json import pycket_json_adapter as pja adapted = pja.adapt(json.load(sys.stdin)) sys.exit(main(core.json_to_term(adapted)))
def method_initialize(self, space, filename, w_mode=None, w_perm_or_opt=None, w_opt=None): if w_mode is None: w_mode = space.w_nil if w_perm_or_opt is None: w_perm_or_opt = space.w_nil if w_opt is None: w_opt = space.w_nil if isinstance(w_perm_or_opt, W_HashObject): assert w_opt is space.w_nil perm = 0665 w_opt = w_perm_or_opt elif w_opt is not space.w_nil: perm = space.int_w(w_perm_or_opt) else: perm = 0665 mode, mode_str, encoding = map_filemode(space, w_mode) if w_perm_or_opt is not space.w_nil or w_opt is not space.w_nil: raise space.error(space.w_NotImplementedError, "options hash or permissions for File.new") try: self.fd = os.open(filename, mode, perm) except OSError as e: raise error_for_oserror(space, e) # Optimization for ReadOnly files, using stream reading # this speedup common file read by 4 times # TODO: rewrite to something better if mode_str == "r" or mode_str == "rb": try: self.stream = streamio.fdopen_as_stream(self.fd, mode_str) except OSError as e: raise error_for_oserror(space, e) self.filename = filename return self
def direct_fdopen(self, fd, mode="r", buffering=-1): self.direct_close() self.w_name = self.space.wrap("<fdopen>") self.check_mode_ok(mode) stream = streamio.fdopen_as_stream(fd, mode, buffering, signal_checker(self.space)) self.check_not_dir(fd) self.fdopenstream(stream, fd, mode)
def _main(argv): """Program entry point. :param argv: command-line arguments :type argv: :class:`list` :return: exit code :rtype: :class:`int` """ author_strings = [] for i in xrange(len(metadata.authors)): author_strings.append( 'Author: %s <%s>' % (metadata.authors[i], metadata.emails[i])) # We can't use argparse, so we do some old-school argument parsing. if '-h' in argv or '--help' in argv: print usage(argv) # RPython doesn't support named specifiers. print ''' %s %s %s URL: <%s> ''' % (metadata.project, metadata.version, '\n'.join(author_strings), metadata.url) return 0 if '-V' in argv or '--version' in argv: print '%s %s' % (metadata.project, metadata.version) return 0 num_argv = len(argv) if num_argv > 2: print usage(argv) return 1 if num_argv == 1 or (num_argv == 2 and argv[1] == '-'): input_stream = fdopen_as_stream(0, 'r') else: input_stream = open_file_as_stream(argv[1]) try: source_code = input_stream.readall() finally: input_stream.close() try: run(source_code) except StencilLanguageError as error: # The purpose of this except block is two-fold: # # * Don't print tracebacks for interpreter errors. Tracebacks shouldn't # be shown to the user. # * RPython doesn't honor most magic methods including __str__ and # __repr__, so error messages aren't shown to the user when using the # translated executable. Only the exception name is shown. # TODO: This should print to stderr. print '%s: %s' % (error.name, error.__str__()) return 0
def direct_fdopen(self, fd, mode='r', buffering=-1): self.direct_close() self.w_name = self.space.newtext('<fdopen>') self.check_mode_ok(mode) stream = streamio.fdopen_as_stream(fd, mode, buffering, signal_checker(self.space)) self.check_not_dir(fd) self.fdopenstream(stream, fd, mode)
def open_exclusive(space, cpathname, mode): try: os.unlink(cpathname) except OSError: pass flags = (os.O_EXCL|os.O_CREAT|os.O_WRONLY|os.O_TRUNC| streamio.O_BINARY) fd = os.open(cpathname, flags, mode) return streamio.fdopen_as_stream(fd, "wb")
def open_exclusive(space, cpathname, mode): try: os.unlink(cpathname) except OSError: pass flags = (os.O_EXCL | os.O_CREAT | os.O_WRONLY | os.O_TRUNC | streamio.O_BINARY) fd = os.open(cpathname, flags, mode) return streamio.fdopen_as_stream(fd, "wb")
def get_file(space, w_file, filename, filemode): if space.is_none(w_file): try: return streamio.open_file_as_stream(filename, filemode) except streamio.StreamErrors as e: # XXX this is not quite the correct place, but it will do for now. # XXX see the issue which I'm sure exists already but whose number # XXX I cannot find any more... raise wrap_streamerror(space, e) else: w_iobase = space.interp_w(W_IOBase, w_file) # XXX: not all W_IOBase have a fileno method: in that case, we should # probably raise a TypeError? fd = space.int_w(space.call_method(w_iobase, 'fileno')) return streamio.fdopen_as_stream(fd, filemode)
def method_initialize(self, space, w_fd_or_io, w_mode_str_or_int=None, w_opts=None): if isinstance(w_fd_or_io, W_IOObject): fd = w_fd_or_io.fd else: fd = Coerce.int(space, w_fd_or_io) if w_opts is not None: raise space.error(space.w_NotImplementedError, "options hash for IO.new") mode, mode_str, encoding = map_filemode(space, w_mode_str_or_int) self.fd = fd # Optimization for ReadOnly files, using stream reading # this speedup common file read by 4 times # TODO: rewrite to something better if mode_str == "r" or mode_str == "rb": try: self.stream = streamio.fdopen_as_stream(fd, mode_str) except OSError as e: raise error_for_oserror(space, e) return self
def lprintf(fmt, args): from pycket.prims.logging import w_main_logger sio.fdopen_as_stream(2, "w", buffering=1).write(fmt % args) return
def _entry_point(space, argv): try: ( flag_globals_w, do_loop, path, search_path, globalized_switches, exprs, reqs, load_path_entries, jit_params, syntax_check, argv_w ) = _parse_argv(space, argv) except ShortCircuitError as e: os.write(1, e.message) return 0 except CommandLineError as e: os.write(2, e.message) return 1 for path_entry in load_path_entries: space.send( space.w_load_path, "<<", [space.newstr_fromstr(path_entry)] ) for required_lib in reqs: space.send( space.w_kernel, "require", [space.newstr_fromstr(required_lib)] ) space.set_const(space.w_object, "ARGV", space.newarray(argv_w)) explicitly_verbose = space.is_true(flag_globals_w["$-v"]) if explicitly_verbose: os.write(1, "%s\n" % RUBY_DESCRIPTION) for varname, w_value in flag_globals_w.iteritems(): space.globals.set(space, varname, w_value) if exprs: source = "\n".join(exprs) path = "-e" elif path is not None: if search_path: for dirname in os.environ["PATH"].split(os.pathsep): candidate_path = os.sep.join([dirname, path]) if os.access(candidate_path, os.R_OK): path = candidate_path break try: f = open_file_as_stream(path, buffering=0) except OSError as e: os.write(2, "%s -- %s (LoadError)\n" % (os.strerror(e.errno), path)) return 1 try: source = f.readall() finally: f.close() elif explicitly_verbose: return 0 else: if IS_WINDOWS: source = WinStdinStream().readall() else: source = fdopen_as_stream(0, "r").readall() path = "-" for globalized_switch in globalized_switches: value = None if "=" in globalized_switch: globalized_switch, value = globalized_switch.split("=", 1) switch_global_var = "$%s" % globalized_switch[1:].replace("-", "_") if value is None: space.globals.set(space, switch_global_var, space.w_true) else: space.globals.set(space, switch_global_var, space.newstr_fromstr(value)) w_program_name = space.newstr_fromstr(path) space.globals.set(space, "$0", w_program_name) space.globals.set(space, "$PROGRAM_NAME", w_program_name) status = 0 w_exit_error = None explicit_status = False jit.set_param(None, "trace_limit", 16000) if jit_params: # Work around TraceLimitTooHigh by setting any trace_limit explicitly parts = jit_params.split(",") limitidx = -1 for i, s in enumerate(parts): if "trace_limit" in s: limitidx = i break if limitidx >= 0: limit = parts.pop(limitidx) jit.set_param(None, "trace_limit", int(limit.split("=")[1])) if len(parts) > 0: jit.set_user_param(None, ",".join(parts)) try: if do_loop: print_after = space.is_true(flag_globals_w["$-p"]) bc = space.compile(source, path) frame = space.create_frame(bc) while True: w_line = space.send(space.w_kernel, "gets") if w_line is space.w_nil: break with space.getexecutioncontext().visit_frame(frame): w_res = space.execute_frame(frame, bc) if print_after: space.send(space.w_kernel, "print", [w_res]) elif syntax_check: space.compile(source, path) else: space.execute(source, filepath=path) except RubyError as e: explicit_status = True w_exc = e.w_value if isinstance(w_exc, W_SystemExit): status = w_exc.status else: w_exit_error = w_exc status = 1 exit_handler_status = space.run_exit_handlers() if not explicit_status and exit_handler_status != -1: status = exit_handler_status if w_exit_error is not None: print_traceback(space, w_exit_error, path) return status
def read(self, n): if self.fd() == 0: s = fdopen_as_stream(1, "w", False) s.write("|: ") return self.stream.read(n)
def get_file(space, w_file, filename, filemode): if space.is_none(w_file): try: return streamio.open_file_as_stream(filename, filemode) except streamio.StreamErrors, e: # XXX this is not quite the correct place, but it will do for now. # XXX see the issue which I'm sure exists already but whose number # XXX I cannot find any more... raise wrap_streamerror(space, e) else: w_iobase = space.interp_w(W_IOBase, w_file) # XXX: not all W_IOBase have a fileno method: in that case, we should # probably raise a TypeError? fd = space.int_w(space.call_method(w_iobase, 'fileno')) return streamio.fdopen_as_stream(fd, filemode) def find_module(space, w_name, w_path=None): name = space.fsencode_w(w_name) if space.is_none(w_path): w_path = None find_info = importing.find_module( space, name, w_name, name, w_path, use_loader=False) if not find_info: raise oefmt(space.w_ImportError, "No module named %s", name) w_filename = space.fsdecode(space.wrapbytes(find_info.filename)) stream = find_info.stream if stream is not None:
def _entry_point(space, argv): if IS_WINDOWS: system = "Windows" cpu = "x86_64" if IS_64BIT else "i686" else: system, _, _, _, cpu = os.uname() platform = "%s-%s" % (cpu, system.lower()) engine = "topaz" version = "1.9.3" patchlevel = 125 description = "%s (ruby-%sp%d) (git rev %s) [%s]" % ( engine, version, patchlevel, RUBY_REVISION, platform) space.set_const(space.w_object, "RUBY_ENGINE", space.newstr_fromstr(engine)) space.set_const(space.w_object, "RUBY_VERSION", space.newstr_fromstr(version)) space.set_const(space.w_object, "RUBY_PATCHLEVEL", space.newint(patchlevel)) space.set_const(space.w_object, "RUBY_PLATFORM", space.newstr_fromstr(platform)) space.set_const(space.w_object, "RUBY_DESCRIPTION", space.newstr_fromstr(description)) space.set_const(space.w_object, "RUBY_REVISION", space.newstr_fromstr(RUBY_REVISION)) try: (flag_globals_w, do_loop, path, search_path, globalized_switches, exprs, reqs, load_path_entries, argv_w) = _parse_argv(space, argv) except ShortCircuitError as e: os.write(1, e.message) return 0 except CommandLineError as e: os.write(2, e.message) return 1 for path_entry in load_path_entries: space.send(space.w_load_path, "<<", [space.newstr_fromstr(path_entry)]) for required_lib in reqs: space.send(space.w_kernel, "require", [space.newstr_fromstr(required_lib)]) space.set_const(space.w_object, "ARGV", space.newarray(argv_w)) explicitly_verbose = space.is_true(flag_globals_w["$-v"]) if explicitly_verbose: os.write(1, "%s\n" % description) for varname, w_value in flag_globals_w.iteritems(): space.globals.set(space, varname, w_value) if exprs: source = "\n".join(exprs) path = "-e" elif path is not None: if search_path: for dirname in os.environ["PATH"].split(os.pathsep): candidate_path = os.sep.join([dirname, path]) if os.access(candidate_path, os.R_OK): path = candidate_path break try: f = open_file_as_stream(path, buffering=0) except OSError as e: os.write(2, "%s -- %s (LoadError)\n" % (os.strerror(e.errno), path)) return 1 try: source = f.readall() finally: f.close() elif explicitly_verbose: return 0 else: if IS_WINDOWS: raise NotImplementedError("executing from stdin on Windows") else: source = fdopen_as_stream(0, "r").readall() path = "-" for globalized_switch in globalized_switches: value = None if "=" in globalized_switch: globalized_switch, value = globalized_switch.split("=", 1) switch_global_var = "$%s" % globalized_switch[1:].replace("-", "_") if value is None: space.globals.set(space, switch_global_var, space.w_true) else: space.globals.set(space, switch_global_var, space.newstr_fromstr(value)) w_program_name = space.newstr_fromstr(path) space.globals.set(space, "$0", w_program_name) space.globals.set(space, "$PROGRAM_NAME", w_program_name) status = 0 w_exit_error = None explicit_status = False jit.set_param(None, "trace_limit", 10000) try: if do_loop: print_after = space.is_true(flag_globals_w["$-p"]) bc = space.compile(source, path) frame = space.create_frame(bc) while True: w_line = space.send(space.w_kernel, "gets") if w_line is space.w_nil: break with space.getexecutioncontext().visit_frame(frame): w_res = space.execute_frame(frame, bc) if print_after: space.send(space.w_kernel, "print", [w_res]) else: space.execute(source, filepath=path) except RubyError as e: explicit_status = True w_exc = e.w_value if isinstance(w_exc, W_SystemExit): status = w_exc.status else: w_exit_error = w_exc status = 1 exit_handler_status = space.run_exit_handlers() if not explicit_status and exit_handler_status != -1: status = exit_handler_status if w_exit_error is not None: print_traceback(space, w_exit_error, path) return status
# import sys from rpython.rlib.parsing.parsing import ParseError from rpython.rlib.parsing.deterministic import LexerError from rpython.rlib.streamio import open_file_as_stream, fdopen_as_stream from asteval import Eval from fundyparse import parse from version import version_numbers # Use __stdin__ etc rather than stdin so it works in IDLE too, although you # have to interact with Fundy through the terminal that started IDLE, rather # than IDLE's gui window. stdin_stream = fdopen_as_stream(sys.__stdin__.fileno(), "rU", buffering=1) stdout_stream = fdopen_as_stream(sys.__stdout__.fileno(), "wU", buffering=1) stderr_stream = fdopen_as_stream(sys.__stderr__.fileno(), "wU", buffering=0) class FundyConsole(object): def __init__(self, filename="<console>"): self.filename = filename self.asteval = Eval() self.stdin = stdin_stream self.stdout = stdout_stream self.stderr = stderr_stream self.resetbuffer() def resetbuffer(self): self.buffer= []
def _entry_point(space, argv): system, _, _, _, cpu = os.uname() platform = "%s-%s" % (cpu, system.lower()) engine = "topaz" version = "1.9.3" patchlevel = 125 description = "%s (ruby-%sp%d) [%s]" % (engine, version, patchlevel, platform) space.set_const(space.w_object, "RUBY_ENGINE", space.newstr_fromstr(engine)) space.set_const(space.w_object, "RUBY_VERSION", space.newstr_fromstr(version)) space.set_const(space.w_object, "RUBY_PATCHLEVEL", space.newint(patchlevel)) space.set_const(space.w_object, "RUBY_PLATFORM", space.newstr_fromstr(platform)) space.set_const(space.w_object, "RUBY_DESCRIPTION", space.newstr_fromstr(description)) try: verbose, path, search_path, exprs, reqs, load_path_entries, argv_w = _parse_argv(space, argv) except ShortCircuitError as e: os.write(1, e.message) return 0 except CommandLineError as e: os.write(2, e.message) return 1 for path_entry in load_path_entries: space.send( space.w_load_path, space.newsymbol("<<"), [space.newstr_fromstr(path_entry)] ) for required_lib in reqs: space.send( space.w_kernel, space.newsymbol("require"), [space.newstr_fromstr(required_lib)] ) space.set_const(space.w_object, "ARGV", space.newarray(argv_w)) if verbose: os.write(1, "%s\n" % description) if exprs: source = "\n".join(exprs) path = "-e" elif path is not None: if search_path: for dirname in os.environ["PATH"].split(os.pathsep): candidate_path = os.sep.join([dirname, path]) if os.access(candidate_path, os.R_OK): path = candidate_path break try: f = open_file_as_stream(path) except OSError as e: os.write(2, "%s -- %s (LoadError)\n" % (os.strerror(e.errno), path)) return 1 try: source = f.readall() finally: f.close() elif verbose: return 0 else: source = fdopen_as_stream(0, "r").readall() path = "-" space.globals.set(space, "$0", space.newstr_fromstr(path)) status = 0 w_exit_error = None try: space.execute(source, filepath=path) except RubyError as e: w_exc = e.w_value if isinstance(w_exc, W_SystemExit): status = w_exc.status else: w_exit_error = w_exc status = 1 space.run_exit_handlers() if w_exit_error is not None: print_traceback(space, w_exit_error, path) return status
def _entry_point(space, argv): system, _, _, _, cpu = os.uname() platform = "%s-%s" % (cpu, system.lower()) engine = "topaz" version = "1.9.3" patchlevel = 125 description = "%s (ruby-%sp%d) [%s]" % (engine, version, patchlevel, platform) space.set_const(space.w_object, "RUBY_ENGINE", space.newstr_fromstr(engine)) space.set_const(space.w_object, "RUBY_VERSION", space.newstr_fromstr(version)) space.set_const(space.w_object, "RUBY_PATCHLEVEL", space.newint(patchlevel)) space.set_const(space.w_object, "RUBY_PLATFORM", space.newstr_fromstr(platform)) space.set_const(space.w_object, "RUBY_DESCRIPTION", space.newstr_fromstr(description)) try: ( flag_globals_w, do_loop, path, search_path, globalized_switches, exprs, reqs, load_path_entries, argv_w ) = _parse_argv(space, argv) except ShortCircuitError as e: os.write(1, e.message) return 0 except CommandLineError as e: os.write(2, e.message) return 1 for path_entry in load_path_entries: space.send( space.w_load_path, space.newsymbol("<<"), [space.newstr_fromstr(path_entry)] ) for required_lib in reqs: space.send( space.w_kernel, space.newsymbol("require"), [space.newstr_fromstr(required_lib)] ) space.set_const(space.w_object, "ARGV", space.newarray(argv_w)) explicitly_verbose = space.is_true(flag_globals_w["$-v"]) if explicitly_verbose: os.write(1, "%s\n" % description) for varname, w_value in flag_globals_w.iteritems(): space.globals.set(space, varname, w_value) if exprs: source = "\n".join(exprs) path = "-e" elif path is not None: if search_path: for dirname in os.environ["PATH"].split(os.pathsep): candidate_path = os.sep.join([dirname, path]) if os.access(candidate_path, os.R_OK): path = candidate_path break try: f = open_file_as_stream(path) except OSError as e: os.write(2, "%s -- %s (LoadError)\n" % (os.strerror(e.errno), path)) return 1 try: source = f.readall() finally: f.close() elif explicitly_verbose: return 0 else: source = fdopen_as_stream(0, "r").readall() path = "-" for globalized_switch in globalized_switches: value = None if "=" in globalized_switch: globalized_switch, value = globalized_switch.split("=", 1) switch_global_var = "$%s" % globalized_switch[1:].replace("-", "_") if value is None: space.globals.set(space, switch_global_var, space.w_true) else: space.globals.set(space, switch_global_var, space.newstr_fromstr(value)) w_program_name = space.newstr_fromstr(path) space.globals.set(space, "$0", w_program_name) space.globals.set(space, "$PROGRAM_NAME", w_program_name) status = 0 w_exit_error = None explicit_status = False try: if do_loop: bc = space.compile(source, path) frame = space.create_frame(bc) while True: w_line = space.send(space.w_kernel, space.newsymbol("gets")) if w_line is space.w_nil: break with space.getexecutioncontext().visit_frame(frame): space.execute_frame(frame, bc) else: space.execute(source, filepath=path) except RubyError as e: explicit_status = True w_exc = e.w_value if isinstance(w_exc, W_SystemExit): status = w_exc.status else: w_exit_error = w_exc status = 1 exit_handler_status = space.run_exit_handlers() if not explicit_status and exit_handler_status != -1: status = exit_handler_status if w_exit_error is not None: print_traceback(space, w_exit_error, path) return status
def direct_fdopen(self, fd, mode='r', buffering=-1): self.direct_close() self.w_name = self.space.wrap('<fdopen>') self.check_mode_ok(mode) stream = streamio.fdopen_as_stream(fd, mode, buffering) self.fdopenstream(stream, fd, mode)
def get_stderr(): from rpython.rlib import streamio as sio return sio.fdopen_as_stream(2, "w", buffering = 1)
def lprintf(fmt, args): from pycket.prims.logging import w_main_logger sio.fdopen_as_stream(2, "w", buffering=1).write(fmt%args) return
def do_has_custom_write(v): return values.w_false def shutdown(env): # called before the interpreter exits stdout_port.flush() ############################ Values and Parameters expose_val("eof", values.eof_object) current_print_param = values_parameter.W_Parameter(standard_printer) expose_val("current-print", current_print_param) # line buffer stdout stdout_port = values.W_FileOutputPort(sio.fdopen_as_stream(1, "w", buffering=1)) stderr_port = values.W_FileOutputPort(sio.fdopen_as_stream(2, "w", buffering=1)) stdin_port = values.W_FileInputPort(sio.fdopen_as_stream(0, "r")) current_out_param = values_parameter.W_Parameter(stdout_port) current_error_param = values_parameter.W_Parameter(stderr_port) current_in_param = values_parameter.W_Parameter(stdin_port) expose_val("current-output-port", current_out_param) expose_val("current-error-port", current_error_param) expose_val("current-input-port", current_in_param) print_graph_param = values_parameter.W_Parameter(values.w_false) print_struct_param = values_parameter.W_Parameter(values.w_false) print_box_param = values_parameter.W_Parameter(values.w_false) print_vector_length_param = values_parameter.W_Parameter(values.w_false) print_hash_table_param = values_parameter.W_Parameter(values.w_false)
def get_file(space, w_file, filename, filemode): if space.is_none(w_file): try: return streamio.open_file_as_stream(filename, filemode) except streamio.StreamErrors, e: # XXX this is not quite the correct place, but it will do for now. # XXX see the issue which I'm sure exists already but whose number # XXX I cannot find any more... raise wrap_streamerror(space, e) else: w_iobase = space.interp_w(W_IOBase, w_file) # XXX: not all W_IOBase have a fileno method: in that case, we should # probably raise a TypeError? fd = space.int_w(space.call_method(w_iobase, 'fileno')) return streamio.fdopen_as_stream(fd, filemode) def find_module(space, w_name, w_path=None): name = space.fsencode_w(w_name) if space.is_none(w_path): w_path = None find_info = importing.find_module(space, name, w_name, name, w_path, use_loader=False) if not find_info: raise oefmt(space.w_ImportError, "No module named %s", name)
def _entry_point(space, argv): verbose = False path = None exprs = [] idx = 1 while idx < len(argv): arg = argv[idx] if arg == "-v": verbose = True elif arg == "-e": idx += 1 if idx == len(argv): os.write(2, "no code specified for -e (RuntimeError)\n") return 1 exprs.append(argv[idx]) elif arg.startswith("-e"): exprs.append(arg[2:]) else: break idx += 1 if idx < len(argv) and not exprs: path = argv[idx] idx += 1 argv_w = [] while idx < len(argv): argv_w.append(space.newstr_fromstr(argv[idx])) idx += 1 space.set_const(space.w_object, "ARGV", space.newarray(argv_w)) system, _, _, _, cpu = os.uname() platform = "%s-%s" % (cpu, system.lower()) engine = "topaz" version = "1.9.3" patchlevel = 125 description = "%s (ruby-%sp%d) [%s]" % (engine, version, patchlevel, platform) space.set_const(space.w_object, "RUBY_ENGINE", space.newstr_fromstr(engine)) space.set_const(space.w_object, "RUBY_VERSION", space.newstr_fromstr(version)) space.set_const(space.w_object, "RUBY_PATCHLEVEL", space.newint(patchlevel)) space.set_const(space.w_object, "RUBY_PLATFORM", space.newstr_fromstr(platform)) space.set_const(space.w_object, "RUBY_DESCRIPTION", space.newstr_fromstr(description)) if verbose: os.write(1, "%s\n" % description) if exprs: source = "\n".join(exprs) path = "-e" elif path is not None: try: f = open_file_as_stream(path) except OSError as e: os.write(2, "%s -- %s (LoadError)\n" % (os.strerror(e.errno), path)) return 1 try: source = f.readall() finally: f.close() elif verbose: return 0 else: source = fdopen_as_stream(0, "r").readall() path = "-" space.globals.set(space, "$0", space.newstr_fromstr(path)) status = 0 w_exit_error = None try: space.execute(source, filepath=path) except RubyError as e: w_exc = e.w_value if isinstance(w_exc, W_SystemExit): status = w_exc.status else: w_exit_error = w_exc status = 1 space.run_exit_handlers() if w_exit_error is not None: print_traceback(space, w_exit_error, path) return status
# FIXME: @expose("custom-write?", [values.W_Object]) def do_has_custom_write(v): return values.w_false ############################ Values and Parameters expose_val("eof", values.eof_object) current_print_param = values.W_Parameter(standard_printer) expose_val("current-print", current_print_param) stdout_port = values.W_FileOutputPort(sio.fdopen_as_stream(1, "wb")) stdin_port = values.W_FileInputPort(sio.fdopen_as_stream(0, "rb")) current_out_param = values.W_Parameter(stdout_port) current_error_param = values.W_Parameter(stdout_port) current_in_param = values.W_Parameter(stdin_port) expose_val("current-output-port", current_out_param) expose_val("current-error-port", current_error_param) expose_val("current-input-port", current_in_param) print_graph_param = values.W_Parameter(values.w_false) print_struct_param = values.W_Parameter(values.w_false) print_box_param = values.W_Parameter(values.w_false) print_vector_length_param = values.W_Parameter(values.w_false) print_hash_table_param = values.W_Parameter(values.w_false) print_boolean_long_form_param = values.W_Parameter(values.w_false)