Debian Codegraph @

libgrust/libformat_parser/src/lib.rs

raw
1 //! FFI interface for `rustc_format_parser`
2
3 // what's the plan? Have a function return something that can be constructed into a vector?
4 // or an iterator?
5
6 use std::ffi::CStr;
7
8 trait IntoFFI<T> {
9 fn into_ffi(self) -> T;
10 }
11
12 impl<T> IntoFFI<*const T> for Option<T>
13 where
14 T: Sized,
15 {
16 fn into_ffi(self) -> *const T {
17 match self.as_ref() {
18 None => std::ptr::null(),
19 Some(r) => r as *const T,
20 }
21 }
22 }
23
24 // Extension trait to provide `String::leak` which did not exist in Rust 1.49
25 pub trait StringLeakExt {
26 fn leak<'a>(self) -> &'a mut str;
27 }
28
29 impl StringLeakExt for String {
30 fn leak<'a>(self) -> &'a mut str {
31 Box::leak(self.into_boxed_str())
32 }
33 }
34
35 // FIXME: Make an ffi module in a separate file
36 // FIXME: Remember to leak the boxed type somehow
37 // FIXME: How to encode the Option type? As a pointer? Option<T> -> Option<&T> -> *const T could work maybe?
38 pub mod ffi {
39 use super::IntoFFI;
40
41 // FIXME: We need to ensure we deal with memory properly - whether it's owned by the C++ side or the Rust side
42 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
43 #[repr(C)]
44 pub struct RustHamster {
45 ptr: *const u8,
46 len: usize,
47 }
48
49 impl<'a> From<&'a str> for RustHamster {
50 fn from(s: &'a str) -> RustHamster {
51 RustHamster {
52 ptr: s.as_ptr(),
53 len: s.len(),
54 }
55 }
56 }
57
58 // Note: copied from rustc_span
59 /// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
60 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
61 #[repr(C)]
62 pub struct InnerSpan {
63 pub start: usize,
64 pub end: usize,
65 }
66
67 /// The location and before/after width of a character whose width has changed from its source code
68 /// representation
69 #[derive(Copy, Clone, PartialEq, Eq)]
70 #[repr(C)]
71 pub struct InnerWidthMapping {
72 /// Index of the character in the source
73 pub position: usize,
74 /// The inner width in characters
75 pub before: usize,
76 /// The transformed width in characters
77 pub after: usize,
78 }
79
80 // TODO: Not needed for now?
81 // /// Whether the input string is a literal. If yes, it contains the inner width mappings.
82 // #[derive(Clone, PartialEq, Eq)]
83 // #[repr(C)]
84 // enum InputStringKind {
85 // NotALiteral,
86 // Literal {
87 // width_mappings: Vec<InnerWidthMapping>,
88 // },
89 // }
90
91 // TODO: Not needed for now?
92 // /// The type of format string that we are parsing.
93 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
94 #[repr(C)]
95 pub enum ParseMode {
96 /// A normal format string as per `format_args!`.
97 Format = 0,
98 /// An inline assembly template string for `asm!`.
99 InlineAsm,
100 }
101
102 /// A piece is a portion of the format string which represents the next part
103 /// to emit. These are emitted as a stream by the `Parser` class.
104 #[derive(Debug, Clone, PartialEq)]
105 #[repr(C)]
106 pub enum Piece<'a> {
107 /// A literal string which should directly be emitted
108 String(RustHamster),
109 /// This describes that formatting should process the next argument (as
110 /// specified inside) for emission.
111 // do we need a pointer here? we're doing big cloning anyway
112 NextArgument(Argument<'a>),
113 }
114
115 /// Representation of an argument specification.
116 #[derive(Copy, Clone, Debug, PartialEq)]
117 #[repr(C)]
118 pub struct Argument<'a> {
119 /// Where to find this argument
120 pub position: Position<'a>,
121 /// The span of the position indicator. Includes any whitespace in implicit
122 /// positions (`{ }`).
123 pub position_span: InnerSpan,
124 /// How to format the argument
125 pub format: FormatSpec<'a>,
126 }
127
128 /// Specification for the formatting of an argument in the format string.
129 #[derive(Copy, Clone, Debug, PartialEq)]
130 #[repr(C)]
131 pub struct FormatSpec<'a> {
132 /// Optionally specified character to fill alignment with.
133 pub fill: Option<char>,
134 /// Span of the optionally specified fill character.
135 pub fill_span: *const InnerSpan,
136 /// Optionally specified alignment.
137 pub align: Alignment,
138 /// The `+` or `-` flag.
139 pub sign: *const Sign,
140 /// The `#` flag.
141 pub alternate: bool,
142 /// The `0` flag.
143 pub zero_pad: bool,
144 /// The `x` or `X` flag. (Only for `Debug`.)
145 pub debug_hex: *const DebugHex,
146 /// The integer precision to use.
147 pub precision: Count<'a>,
148 /// The span of the precision formatting flag (for diagnostics).
149 pub precision_span: *const InnerSpan,
150 /// The string width requested for the resulting format.
151 pub width: Count<'a>,
152 /// The span of the width formatting flag (for diagnostics).
153 pub width_span: *const InnerSpan,
154 /// The descriptor string representing the name of the format desired for
155 /// this argument, this can be empty or any number of characters, although
156 /// it is required to be one word.
157 pub ty: &'a str,
158 /// The span of the descriptor string (for diagnostics).
159 pub ty_span: *const InnerSpan,
160 }
161
162 /// Enum describing where an argument for a format can be located.
163 #[derive(Copy, Clone, Debug, PartialEq)]
164 #[repr(C)]
165 pub enum Position<'a> {
166 /// The argument is implied to be located at an index
167 ArgumentImplicitlyIs(usize),
168 /// The argument is located at a specific index given in the format,
169 ArgumentIs(usize),
170 /// The argument has a name.
171 ArgumentNamed(&'a str),
172 }
173
174 /// Enum of alignments which are supported.
175 #[derive(Copy, Clone, Debug, PartialEq)]
176 #[repr(C)]
177 pub enum Alignment {
178 /// The value will be aligned to the left.
179 AlignLeft,
180 /// The value will be aligned to the right.
181 AlignRight,
182 /// The value will be aligned in the center.
183 AlignCenter,
184 /// The value will take on a default alignment.
185 AlignUnknown,
186 }
187
188 /// Enum for the sign flags.
189 #[derive(Copy, Clone, Debug, PartialEq)]
190 #[repr(C)]
191 pub enum Sign {
192 /// The `+` flag.
193 Plus,
194 /// The `-` flag.
195 Minus,
196 }
197
198 /// Enum for the debug hex flags.
199 #[derive(Copy, Clone, Debug, PartialEq)]
200 #[repr(C)]
201 pub enum DebugHex {
202 /// The `x` flag in `{:x?}`.
203 Lower,
204 /// The `X` flag in `{:X?}`.
205 Upper,
206 }
207
208 /// A count is used for the precision and width parameters of an integer, and
209 /// can reference either an argument or a literal integer.
210 #[derive(Copy, Clone, Debug, PartialEq)]
211 #[repr(C)]
212 pub enum Count<'a> {
213 /// The count is specified explicitly.
214 CountIs(usize),
215 /// The count is specified by the argument with the given name.
216 CountIsName(&'a str, InnerSpan),
217 /// The count is specified by the argument at the given index.
218 CountIsParam(usize),
219 /// The count is specified by a star (like in `{:.*}`) that refers to the argument at the given index.
220 CountIsStar(usize),
221 /// The count is implied and cannot be explicitly specified.
222 CountImplied,
223 }
224
225 impl<'a> From<generic_format_parser::Piece<'a>> for Piece<'a> {
226 fn from(old: generic_format_parser::Piece<'a>) -> Self {
227 match old {
228 generic_format_parser::Piece::String(x) => Piece::String(x.into()),
229 generic_format_parser::Piece::NextArgument(x) => {
230 // FIXME: This is problematic - if we do this, then we probably run into the issue that the Box
231 // is freed at the end of the call to collect_pieces. if we just .leak() it, then we have
232 // a memory leak... should we resend the info back to the Rust lib afterwards to free it?
233 // this is definitely the best way - store that pointer in the FFI piece and rebuild the box
234 // in a Rust destructor
235 let ptr = Box::leak(x);
236 let dst = Into::<Argument>::into(*ptr);
237
238 Piece::NextArgument(dst)
239 }
240 }
241 }
242 }
243
244 impl<'a> From<generic_format_parser::Argument<'a>> for Argument<'a> {
245 fn from(old: generic_format_parser::Argument<'a>) -> Self {
246 Argument {
247 position: old.position.into(),
248 position_span: old.position_span.into(),
249 format: old.format.into(),
250 }
251 }
252 }
253
254 impl<'a> From<generic_format_parser::Position<'a>> for Position<'a> {
255 fn from(old: generic_format_parser::Position<'a>) -> Self {
256 match old {
257 generic_format_parser::Position::ArgumentImplicitlyIs(x) => {
258 Position::ArgumentImplicitlyIs(x.into())
259 }
260 generic_format_parser::Position::ArgumentIs(x) => Position::ArgumentIs(x.into()),
261 generic_format_parser::Position::ArgumentNamed(x) => {
262 Position::ArgumentNamed(x.into())
263 }
264 }
265 }
266 }
267
268 impl From<generic_format_parser::InnerSpan> for InnerSpan {
269 fn from(old: generic_format_parser::InnerSpan) -> Self {
270 InnerSpan {
271 start: old.start,
272 end: old.end,
273 }
274 }
275 }
276
277 impl<'a> From<generic_format_parser::FormatSpec<'a>> for FormatSpec<'a> {
278 fn from(old: generic_format_parser::FormatSpec<'a>) -> Self {
279 FormatSpec {
280 fill: old.fill,
281 fill_span: old.fill_span.map(Into::into).into_ffi(),
282 align: old.align.into(),
283 sign: old.sign.map(Into::into).into_ffi(),
284 alternate: old.alternate,
285 zero_pad: old.zero_pad,
286 debug_hex: old.debug_hex.map(Into::into).into_ffi(),
287 precision: old.precision.into(),
288 precision_span: old.precision_span.map(Into::into).into_ffi(),
289 width: old.width.into(),
290 width_span: old.width_span.map(Into::into).into_ffi(),
291 ty: old.ty,
292 ty_span: old.ty_span.map(Into::into).into_ffi(),
293 }
294 }
295 }
296
297 impl From<generic_format_parser::DebugHex> for DebugHex {
298 fn from(old: generic_format_parser::DebugHex) -> Self {
299 match old {
300 generic_format_parser::DebugHex::Lower => DebugHex::Lower,
301 generic_format_parser::DebugHex::Upper => DebugHex::Upper,
302 }
303 }
304 }
305
306 impl<'a> From<generic_format_parser::Count<'a>> for Count<'a> {
307 fn from(old: generic_format_parser::Count<'a>) -> Self {
308 match old {
309 generic_format_parser::Count::CountIs(x) => Count::CountIs(x),
310 generic_format_parser::Count::CountIsName(x, y) => Count::CountIsName(x, y.into()),
311 generic_format_parser::Count::CountIsParam(x) => Count::CountIsParam(x),
312 generic_format_parser::Count::CountIsStar(x) => Count::CountIsStar(x),
313 generic_format_parser::Count::CountImplied => Count::CountImplied,
314 }
315 }
316 }
317
318 impl From<generic_format_parser::Sign> for Sign {
319 fn from(old: generic_format_parser::Sign) -> Self {
320 match old {
321 generic_format_parser::Sign::Plus => Sign::Plus,
322 generic_format_parser::Sign::Minus => Sign::Minus,
323 }
324 }
325 }
326
327 impl From<generic_format_parser::Alignment> for Alignment {
328 fn from(old: generic_format_parser::Alignment) -> Self {
329 match old {
330 generic_format_parser::Alignment::AlignLeft => Alignment::AlignLeft,
331 generic_format_parser::Alignment::AlignRight => Alignment::AlignRight,
332 generic_format_parser::Alignment::AlignCenter => Alignment::AlignCenter,
333 generic_format_parser::Alignment::AlignUnknown => Alignment::AlignUnknown,
334 }
335 }
336 }
337 }
338
339 // FIXME: Rename?
340 pub mod rust {
341 use crate::ffi::ParseMode;
342 use generic_format_parser::{Parser, Piece};
343 pub fn collect_pieces(
344 input: &str,
345 style: Option<usize>,
346 snippet: Option<String>,
347 append_newline: bool,
348 parse_mode: ParseMode,
349 ) -> Vec<Piece<'_>> {
350 let converted_parse_mode = match parse_mode {
351 ParseMode::Format => generic_format_parser::ParseMode::Format,
352 ParseMode::InlineAsm => generic_format_parser::ParseMode::InlineAsm,
353 };
354 let parser = Parser::new(input, style, snippet, append_newline, converted_parse_mode);
355 parser.into_iter().collect()
356 }
357 }
358
359 // TODO: Should we instead make an FFIVector struct?
360 #[repr(C)]
361 pub struct PieceSlice {
362 base_ptr: *mut ffi::Piece<'static /* FIXME: That's wrong */>,
363 len: usize,
364 cap: usize,
365 }
366
367 #[repr(C)]
368 // FIXME: we should probably use FFIString here
369 pub struct RustString {
370 ptr: *const u8,
371 len: usize,
372 cap: usize,
373 }
374
375 #[repr(C)]
376 pub struct FormatArgsHandle(PieceSlice, RustString);
377
378 #[no_mangle]
379 pub extern "C" fn collect_pieces(
380 input: *const libc::c_char,
381 append_newline: bool,
382 parse_mode: crate::ffi::ParseMode,
383 ) -> FormatArgsHandle {
384 // FIXME: Add comment
385 let str = unsafe { CStr::from_ptr(input) };
386 let str = str.to_str().unwrap().to_owned();
387
388 // we are never going to free this string here (we leak it later on), so we can extend its lifetime
389 // to send it across an FFI boundary.
390 // FIXME: Is that correct?
391 let s = &str;
392 let s = unsafe { std::mem::transmute::<&'_ str, &'static str>(s) };
393
394 // FIXME: No unwrap
395 let pieces: Vec<ffi::Piece<'_>> =
396 rust::collect_pieces(s, None, None, append_newline, parse_mode)
397 .into_iter()
398 .map(Into::into)
399 .collect();
400
401 let piece_slice = PieceSlice {
402 len: pieces.len(),
403 cap: pieces.capacity(),
404 base_ptr: pieces.leak().as_mut_ptr(),
405 };
406 let rust_string = RustString {
407 len: str.len(),
408 cap: str.capacity(),
409 ptr: str.leak().as_ptr(),
410 };
411
412 FormatArgsHandle(piece_slice, rust_string)
413 }
414
415 #[no_mangle]
416 pub unsafe extern "C" fn destroy_pieces(FormatArgsHandle(piece_slice, s): FormatArgsHandle) {
417 let PieceSlice { base_ptr, len, cap } = piece_slice;
418 drop(Vec::from_raw_parts(base_ptr, len, cap));
419
420 let RustString { ptr, len, cap } = s;
421 drop(String::from_raw_parts(ptr as *mut u8, len, cap));
422 }
423
424 #[no_mangle]
425 pub extern "C" fn clone_pieces(
426 FormatArgsHandle(piece_slice, s): &FormatArgsHandle,
427 ) -> FormatArgsHandle {
428 let PieceSlice { base_ptr, len, cap } = *piece_slice;
429
430 let v = unsafe { Vec::from_raw_parts(base_ptr, len, cap) };
431 let cloned_v = v.clone();
432
433 // FIXME: Add documentation
434 v.leak();
435
436 let piece_slice = PieceSlice {
437 len: cloned_v.len(),
438 cap: cloned_v.capacity(),
439 base_ptr: cloned_v.leak().as_mut_ptr(),
440 };
441
442 let RustString { ptr, len, cap } = *s;
443 let s = unsafe { String::from_raw_parts(ptr as *mut u8, len, cap) };
444 let cloned_s = s.clone();
445
446 // FIXME: Documentation
447 s.leak();
448
449 let rust_string = RustString {
450 len: cloned_s.len(),
451 cap: cloned_s.capacity(),
452 ptr: cloned_s.leak().as_ptr(),
453 };
454
455 FormatArgsHandle(piece_slice, rust_string)
456 }