rune/modules/io.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
//! I/O functions.
#[cfg(feature = "std")]
use std::io::{self, Write as _};
use crate as rune;
#[cfg(feature = "std")]
use crate::alloc::fmt::TryWrite;
use crate::compile;
use crate::macros::{quote, FormatArgs, MacroContext, TokenStream};
use crate::parse::Parser;
#[cfg(feature = "std")]
use crate::runtime::{Formatter, InstAddress, Memory, Output, Panic, VmResult};
use crate::{ContextError, Module};
/// I/O functions.
#[rune::module(::std::io)]
pub fn module(
#[cfg_attr(not(feature = "std"), allow(unused))] stdio: bool,
) -> Result<Module, ContextError> {
let mut module = Module::from_meta(self::module_meta)?.with_unique("std::io");
module.item_mut().docs(docstring! {
/// The std::io module contains a number of common things
/// you’ll need when doing input and output.
/// The most core parts of this module are the [print()], [println()],
/// and [dbg()] functions which are used to hook up printing for a Rune project.
///
/// With complete names:
/// * `::std::io::print`
/// * `::std::io::println`
/// * `::std::io::dbg`
///
/// Their definitions can be omitted from the built-in standard library, and
/// can then easily be defined by third party modules allowing for printing
/// to be hooked up to whatever system you want.
})?;
#[cfg(feature = "std")]
module.ty::<io::Error>()?;
#[cfg(feature = "std")]
module.function_meta(io_error_display_fmt)?;
#[cfg(feature = "std")]
module.function_meta(io_error_debug_fmt)?;
#[cfg(feature = "std")]
if stdio {
module.function_meta(print_impl)?;
module.function_meta(println_impl)?;
module
.raw_function("dbg", dbg_impl)
.build()?
.docs(docstring! {
/// Debug to output.
///
/// This is the actual output hook, and if you install rune modules without
/// `I/O` enabled this will not be defined. It is then up to someone else to
/// provide an implementation.
///
/// # Examples
///
/// ```rune
/// let number = 10;
/// let number = number * 4;
///
/// let who = "World";
/// let string = format!("Hello {who}");
///
/// dbg(number, string);
/// ```
})?;
}
// These are unconditionally included, but using them might cause a
// compilation error unless `::std::io::*` functions are provided somehow.
module.macro_meta(dbg_macro)?;
module.macro_meta(print_macro)?;
module.macro_meta(println_macro)?;
Ok(module)
}
#[rune::function(instance, protocol = DISPLAY_FMT)]
#[cfg(feature = "std")]
fn io_error_display_fmt(error: &io::Error, f: &mut Formatter) -> VmResult<()> {
vm_write!(f, "{error}")
}
#[rune::function(instance, protocol = DEBUG_FMT)]
#[cfg(feature = "std")]
fn io_error_debug_fmt(error: &io::Error, f: &mut Formatter) -> VmResult<()> {
vm_write!(f, "{error:?}")
}
#[cfg(feature = "std")]
fn dbg_impl(stack: &mut dyn Memory, addr: InstAddress, args: usize, out: Output) -> VmResult<()> {
let stdout = io::stdout();
let mut stdout = stdout.lock();
for value in vm_try!(stack.slice_at(addr, args)) {
vm_try!(writeln!(stdout, "{:?}", value).map_err(Panic::custom));
}
vm_try!(out.store(stack, ()));
VmResult::Ok(())
}
/// Debug print the given argument.
///
/// Everything in rune can be "debug printed" in one way or another. This is
/// provided as a cheap an dirty way to introspect values.
///
/// See also the [`dbg!`] macro.
///
/// # Examples
///
/// ```rune
/// let number = 10;
/// let number = number * 4;
///
/// let who = "World";
/// let string = format!("Hello {}", who);
///
/// dbg!(number, string);
/// ```
#[rune::macro_(path = dbg)]
pub(crate) fn dbg_macro(
cx: &mut MacroContext<'_, '_, '_>,
stream: &TokenStream,
) -> compile::Result<TokenStream> {
Ok(quote!(::std::io::dbg(#stream)).into_token_stream(cx)?)
}
/// Prints to output.
///
/// Output printing is performed by calling the [`print()`] function, this is
/// just a convenience wrapper around it which allows for formatting.
///
/// # Examples
///
/// ```rune
/// let who = "World";
/// print!("Hello {}!", who);
/// ```
#[rune::macro_(path = print)]
pub(crate) fn print_macro(
cx: &mut MacroContext<'_, '_, '_>,
stream: &TokenStream,
) -> compile::Result<TokenStream> {
let mut p = Parser::from_token_stream(stream, cx.input_span());
let args = p.parse_all::<FormatArgs>()?;
let expanded = args.expand(cx)?;
Ok(quote!(::std::io::print(#expanded)).into_token_stream(cx)?)
}
/// Prints to output.
///
/// This is the actual output hook, and if you install rune modules without
/// `I/O` enabled this will not be defined. It is then up to someone else to
/// provide an implementation.
///
/// See also the [`print!`] macro.
///
/// # Examples
///
/// ```rune
/// print("Hi!");
/// ```
#[rune::function(path = print)]
#[cfg(feature = "std")]
fn print_impl(m: &str) -> VmResult<()> {
let stdout = io::stdout();
let mut stdout = stdout.lock();
if let Err(error) = write!(stdout, "{}", m) {
return VmResult::err(Panic::custom(error));
}
VmResult::Ok(())
}
/// Prints to output, with a newline.
///
/// Output printing is performed by calling the [`println()`] function, this is
/// just a convenience wrapper around it which allows for formatting.
///
/// # Examples
///
/// ```rune
/// let who = "World";
/// println!("Hello {}!", who);
/// ```
#[rune::macro_(path = println)]
pub(crate) fn println_macro(
cx: &mut MacroContext<'_, '_, '_>,
stream: &TokenStream,
) -> compile::Result<TokenStream> {
let mut p = Parser::from_token_stream(stream, cx.input_span());
let args = p.parse_all::<FormatArgs>()?;
let expanded = args.expand(cx)?;
Ok(quote!(::std::io::println(#expanded)).into_token_stream(cx)?)
}
/// Prints to output, with a newline.
///
/// This is the actual output hook, and if you install rune modules without
/// `I/O` enabled this will not be defined. It is then up to someone else to
/// provide an implementation.
///
/// # Examples
///
/// ```rune
/// println("Hi!");
/// ```
#[rune::function(path = println)]
#[cfg(feature = "std")]
fn println_impl(message: &str) -> VmResult<()> {
let stdout = io::stdout();
let mut stdout = stdout.lock();
if let Err(error) = writeln!(stdout, "{}", message) {
return VmResult::err(Panic::custom(error));
}
VmResult::Ok(())
}