Skip to content

Commit 2f483e7

Browse files
committed
Reformat with default rustfmt rules (tabs -> spaces).
1 parent 8d9bee2 commit 2f483e7

File tree

12 files changed

+575
-512
lines changed

12 files changed

+575
-512
lines changed

ct-python/examples/example.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,19 @@
11
use ct_python::ct_python;
22

33
ct_python! {
4-
print("static A: i32 = 1;")
4+
print("static A: i32 = 1;")
55
}
66

77
static DIRECTIONS: [(f64, f64); 4] = ct_python! {
8-
from math import sin, cos, tau
9-
n = 4
10-
print("[")
11-
for i in range(n):
12-
print("(", cos(i / n * tau), ",", sin(i / n * tau), "),")
13-
print("]")
8+
from math import sin, cos, tau
9+
n = 4
10+
print("[")
11+
for i in range(n):
12+
print("(", cos(i / n * tau), ",", sin(i / n * tau), "),")
13+
print("]")
1414
};
1515

1616
fn main() {
17-
dbg!(&A);
18-
dbg!(&DIRECTIONS);
17+
dbg!(&A);
18+
dbg!(&DIRECTIONS);
1919
}

ct-python/src/lib.rs

Lines changed: 44 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -52,57 +52,65 @@ use shared::*;
5252
/// See [the crate's module level documentation](index.html) for examples.
5353
#[proc_macro]
5454
pub fn ct_python(input: TokenStream) -> TokenStream {
55-
ct_python_impl(input).unwrap_or_else(|e| e)
55+
ct_python_impl(input).unwrap_or_else(|e| e)
5656
}
5757

5858
fn ct_python_impl(input: TokenStream) -> Result<TokenStream, TokenStream> {
59-
let python = CString::new(python_from_macro(input.clone(), None)?).unwrap();
60-
let filename = CString::new(Span::call_site().file()).unwrap();
59+
let python = CString::new(python_from_macro(input.clone(), None)?).unwrap();
60+
let filename = CString::new(Span::call_site().file()).unwrap();
6161

62-
Python::with_gil(|py| {
63-
let code = compile_python(py, &python, &filename, input.clone())?;
64-
let output = run_and_capture(py, code).map_err(|err| python_error_to_compile_error(py, err, input))?;
65-
TokenStream::from_str(&output).map_err(|_| compile_error(None, "produced invalid Rust code"))
66-
})
62+
Python::with_gil(|py| {
63+
let code = compile_python(py, &python, &filename, input.clone())?;
64+
let output = run_and_capture(py, code)
65+
.map_err(|err| python_error_to_compile_error(py, err, input))?;
66+
TokenStream::from_str(&output)
67+
.map_err(|_| compile_error(None, "produced invalid Rust code"))
68+
})
6769
}
6870

6971
fn run_and_capture(py: Python, code: PyObject) -> PyResult<String> {
70-
#[cfg(unix)]
71-
let _ = ensure_libpython_symbols_loaded(py);
72+
#[cfg(unix)]
73+
let _ = ensure_libpython_symbols_loaded(py);
7274

73-
let globals = py.import("__main__")?.dict().copy()?;
75+
let globals = py.import("__main__")?.dict().copy()?;
7476

75-
let sys = py.import("sys")?;
76-
let stdout = py.import("io")?.getattr("StringIO")?.call0()?;
77-
let original_stdout = sys.dict().get_item("stdout")?;
78-
sys.dict().set_item("stdout", &stdout)?;
77+
let sys = py.import("sys")?;
78+
let stdout = py.import("io")?.getattr("StringIO")?.call0()?;
79+
let original_stdout = sys.dict().get_item("stdout")?;
80+
sys.dict().set_item("stdout", &stdout)?;
7981

80-
let result = unsafe {
81-
let ptr = pyo3::ffi::PyEval_EvalCode(code.as_ptr(), globals.as_ptr(), null_mut());
82-
PyObject::from_owned_ptr_or_err(py, ptr)
83-
};
82+
let result = unsafe {
83+
let ptr = pyo3::ffi::PyEval_EvalCode(code.as_ptr(), globals.as_ptr(), null_mut());
84+
PyObject::from_owned_ptr_or_err(py, ptr)
85+
};
8486

85-
sys.dict().set_item("stdout", original_stdout)?;
87+
sys.dict().set_item("stdout", original_stdout)?;
8688

87-
result?;
89+
result?;
8890

89-
stdout.call_method0("getvalue")?.extract()
91+
stdout.call_method0("getvalue")?.extract()
9092
}
9193

9294
#[cfg(unix)]
9395
fn ensure_libpython_symbols_loaded(py: Python) -> PyResult<()> {
94-
// On Unix, Rustc loads proc-macro crates with RTLD_LOCAL, which (at least
95-
// on Linux) means all their dependencies (in our case: libpython) don't
96-
// get their symbols made available globally either. This means that
97-
// loading modules (e.g. `import math`) will fail, as those modules refer
98-
// back to symbols of libpython.
99-
//
100-
// This function tries to (re)load the right version of libpython, but this
101-
// time with RTLD_GLOBAL enabled.
102-
let sysconfig = py.import("sysconfig")?;
103-
let libdir: String = sysconfig.getattr("get_config_var")?.call1(("LIBDIR",))?.extract()?;
104-
let so_name: String = sysconfig.getattr("get_config_var")?.call1(("INSTSONAME",))?.extract()?;
105-
let path = CString::new(format!("{libdir}/{so_name}")).unwrap();
106-
unsafe { libc::dlopen(path.as_ptr(), libc::RTLD_NOW | libc::RTLD_GLOBAL) };
107-
Ok(())
96+
// On Unix, Rustc loads proc-macro crates with RTLD_LOCAL, which (at least
97+
// on Linux) means all their dependencies (in our case: libpython) don't
98+
// get their symbols made available globally either. This means that
99+
// loading modules (e.g. `import math`) will fail, as those modules refer
100+
// back to symbols of libpython.
101+
//
102+
// This function tries to (re)load the right version of libpython, but this
103+
// time with RTLD_GLOBAL enabled.
104+
let sysconfig = py.import("sysconfig")?;
105+
let libdir: String = sysconfig
106+
.getattr("get_config_var")?
107+
.call1(("LIBDIR",))?
108+
.extract()?;
109+
let so_name: String = sysconfig
110+
.getattr("get_config_var")?
111+
.call1(("INSTSONAME",))?
112+
.extract()?;
113+
let path = CString::new(format!("{libdir}/{so_name}")).unwrap();
114+
unsafe { libc::dlopen(path.as_ptr(), libc::RTLD_NOW | libc::RTLD_GLOBAL) };
115+
Ok(())
108116
}

examples/context.rs

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,33 @@
11
use inline_python::{Context, python};
22

33
fn main() {
4-
python! {
5-
print("Hello")
6-
}
4+
python! {
5+
print("Hello")
6+
}
77

8-
let c = Context::new();
8+
let c = Context::new();
99

10-
c.run(python! {
11-
a = "asdf"
12-
});
10+
c.run(python! {
11+
a = "asdf"
12+
});
1313

14-
c.run(python! {
15-
print(a)
16-
});
14+
c.run(python! {
15+
print(a)
16+
});
1717

18-
let result: Context = python! {
19-
foo = 123 + 4
20-
};
18+
let result: Context = python! {
19+
foo = 123 + 4
20+
};
2121

22-
result.run(python! {
23-
foo += 10
24-
});
22+
result.run(python! {
23+
foo += 10
24+
});
2525

26-
let x: i32 = result.get("foo");
26+
let x: i32 = result.get("foo");
2727

28-
assert_eq!(x, 137);
28+
assert_eq!(x, 137);
2929

30-
python! {
31-
print('x)
32-
}
30+
python! {
31+
print('x)
32+
}
3333
}

examples/matplotlib.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
use inline_python::python;
22

33
fn main() {
4-
let data = vec![(4, 3), (2, 8), (3, 1), (4, 0)];
5-
python! {
6-
import matplotlib.pyplot as plt
7-
plt.plot('data)
8-
plt.show()
9-
}
4+
let data = vec![(4, 3), (2, 8), (3, 1), (4, 0)];
5+
python! {
6+
import matplotlib.pyplot as plt
7+
plt.plot('data)
8+
plt.show()
9+
}
1010
}

examples/rust-fn.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,17 @@ use pyo3::{prelude::*, wrap_pyfunction};
33

44
#[pyfunction]
55
fn rust_print(x: i32) {
6-
println!("rust: x = {}", x);
6+
println!("rust: x = {}", x);
77
}
88

99
fn main() {
10-
let c = Context::new();
10+
let c = Context::new();
1111

12-
c.add_wrapped(wrap_pyfunction!(rust_print));
12+
c.add_wrapped(wrap_pyfunction!(rust_print));
1313

14-
c.run(python! {
15-
x = 123
16-
print("python: x =", x)
17-
rust_print(x)
18-
});
14+
c.run(python! {
15+
x = 123
16+
print("python: x =", x)
17+
rust_print(x)
18+
});
1919
}

macros/src/lib.rs

Lines changed: 54 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@ extern crate proc_macro;
77
use proc_macro::{Delimiter, Group, Literal, Span, TokenStream, TokenTree};
88
use pyo3::{Py, Python};
99
use std::{
10-
collections::BTreeMap,
11-
ffi::{CStr, CString},
10+
collections::BTreeMap,
11+
ffi::{CStr, CString},
1212
};
1313

1414
mod shared;
@@ -17,57 +17,65 @@ use shared::*;
1717
#[doc(hidden)]
1818
#[proc_macro]
1919
pub fn python(input: TokenStream) -> TokenStream {
20-
python_impl(input).unwrap_or_else(|e| e)
20+
python_impl(input).unwrap_or_else(|e| e)
2121
}
2222

2323
#[rustfmt::skip]
2424
fn python_impl(input: TokenStream) -> Result<TokenStream, TokenStream> {
25-
let mut variables = BTreeMap::new();
26-
let python = CString::new(python_from_macro(input.clone(), Some(&mut variables))?).unwrap();
27-
let filename = CString::new(Span::call_site().file()).unwrap();
28-
let bytecode = compile_to_bytecode(&python, &filename, input)?;
29-
Ok(TokenStream::from_iter([
30-
punct(':'), punct(':'), ident("inline_python"),
31-
punct(':'), punct(':'), ident("FromInlinePython"),
32-
punct(':'), punct(':'), ident("from_python_macro"),
33-
parens([
34-
TokenTree::Literal(bytecode), punct(','),
35-
punct('|'), ident("globals"), punct('|'),
36-
braces(variables.into_iter().flat_map(|(key, value)| [
37-
punct(':'), punct(':'), ident("inline_python"),
38-
punct(':'), punct(':'), ident("pyo3"),
39-
punct(':'), punct(':'), ident("prelude"),
40-
punct(':'), punct(':'), ident("PyDictMethods"),
41-
punct(':'), punct(':'), ident("set_item"),
42-
parens([
43-
ident("globals"), punct(','),
44-
string(&key), punct(','),
45-
TokenTree::Ident(value)
46-
]),
47-
punct('.'), ident("expect"), parens([string("python")]),
48-
punct(';'),
49-
])),
50-
punct(','),
51-
punct('|'), ident("e"), punct('|'),
52-
punct(':'), punct(':'), ident("std"),
53-
punct(':'), punct(':'), ident("panic"),
54-
punct(':'), punct(':'), ident("panic_any"),
55-
parens([ident("e")]),
56-
]),
57-
]))
25+
let mut variables = BTreeMap::new();
26+
let python = CString::new(python_from_macro(input.clone(), Some(&mut variables))?).unwrap();
27+
let filename = CString::new(Span::call_site().file()).unwrap();
28+
let bytecode = compile_to_bytecode(&python, &filename, input)?;
29+
Ok(TokenStream::from_iter([
30+
punct(':'), punct(':'), ident("inline_python"),
31+
punct(':'), punct(':'), ident("FromInlinePython"),
32+
punct(':'), punct(':'), ident("from_python_macro"),
33+
parens([
34+
TokenTree::Literal(bytecode), punct(','),
35+
punct('|'), ident("globals"), punct('|'),
36+
braces(variables.into_iter().flat_map(|(key, value)| [
37+
punct(':'), punct(':'), ident("inline_python"),
38+
punct(':'), punct(':'), ident("pyo3"),
39+
punct(':'), punct(':'), ident("prelude"),
40+
punct(':'), punct(':'), ident("PyDictMethods"),
41+
punct(':'), punct(':'), ident("set_item"),
42+
parens([
43+
ident("globals"), punct(','),
44+
string(&key), punct(','),
45+
TokenTree::Ident(value)
46+
]),
47+
punct('.'), ident("expect"), parens([string("python")]),
48+
punct(';'),
49+
])),
50+
punct(','),
51+
punct('|'), ident("e"), punct('|'),
52+
punct(':'), punct(':'), ident("std"),
53+
punct(':'), punct(':'), ident("panic"),
54+
punct(':'), punct(':'), ident("panic_any"),
55+
parens([ident("e")]),
56+
]),
57+
]))
5858
}
5959

6060
fn parens(t: impl IntoIterator<Item = TokenTree>) -> TokenTree {
61-
TokenTree::Group(Group::new(Delimiter::Parenthesis, TokenStream::from_iter(t)))
61+
TokenTree::Group(Group::new(
62+
Delimiter::Parenthesis,
63+
TokenStream::from_iter(t),
64+
))
6265
}
6366

64-
fn compile_to_bytecode(python: &CStr, filename: &CStr, tokens: TokenStream) -> Result<Literal, TokenStream> {
65-
Python::with_gil(|py| {
66-
let compiled = compile_python(py, python, filename, tokens)?;
67-
let bytes = unsafe {
68-
let ptr = pyo3::ffi::PyMarshal_WriteObjectToString(compiled.as_ptr(), pyo3::marshal::VERSION);
69-
Py::from_owned_ptr(py, ptr)
70-
};
71-
Ok(Literal::byte_string(bytes.as_bytes(py)))
72-
})
67+
fn compile_to_bytecode(
68+
python: &CStr,
69+
filename: &CStr,
70+
tokens: TokenStream,
71+
) -> Result<Literal, TokenStream> {
72+
Python::with_gil(|py| {
73+
let compiled = compile_python(py, python, filename, tokens)?;
74+
let bytes = unsafe {
75+
let ptr =
76+
pyo3::ffi::PyMarshal_WriteObjectToString(compiled.as_ptr(), pyo3::marshal::VERSION);
77+
Py::from_owned_ptr(py, ptr)
78+
};
79+
Ok(Literal::byte_string(bytes.as_bytes(py)))
80+
})
7381
}

0 commit comments

Comments
 (0)