Skip to content

Commit 67cfbc5

Browse files
authored
cleanup AST builder functionality (#1350)
- remove unused function & impl - `impl<'a> Make<Unsafety> for &'a str` - `impl<'a> Make<Constness> for &'a str` - `impl Make<TokenStream> for Vec<String>` - `impl Make<PathArguments> for ParenthesizedGenericArguments` - `fn parenthesized_args` - refactor `mk().vis()` usage so we can remove `impl<'a> Make<Visibility> for &'a str` - refactor `mk().set_mutbl()` usage so we can remove `impl<'a> Make<Mutability> for &'a str` - refactor `mk().unary_expr()` usage so we can remove `impl<'a> Make<UnOp> for &'a str` - unify `impl Make<TokenStream> for Vec<&str>`, `impl Make<TokenStream> for Vec<u64>`, and `impl Make<TokenStream> for Vec<Meta>` functionality to use `fn comma_separated`
2 parents e830065 + 7a093a4 commit 67cfbc5

File tree

6 files changed

+34
-162
lines changed

6 files changed

+34
-162
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

c2rust-ast-builder/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,5 +12,6 @@ keywords.workspace = true
1212
categories.workspace = true
1313

1414
[dependencies]
15+
itertools = "0.10.0"
1516
proc-macro2 = { version = "1.0", features = ["span-locations"]}
1617
syn = { version = "2.0", features = ["full", "extra-traits", "printing", "clone-impls"]}

c2rust-ast-builder/src/builder.rs

Lines changed: 14 additions & 141 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
33
use std::str;
44

5+
use itertools::intersperse;
56
use proc_macro2::{Literal, Punct, Spacing, Span, TokenStream, TokenTree};
67
use std::default::Default;
78
use std::iter::FromIterator;
@@ -161,6 +162,16 @@ fn punct_box<T, P: Default>(x: Vec<Box<T>>) -> Punctuated<T, P> {
161162
Punctuated::from_iter(x.into_iter().map(|x| *x))
162163
}
163164

165+
fn comma_separated<I, T>(items: I) -> TokenStream
166+
where
167+
I: Iterator<Item = T>,
168+
T: ToTokens + Clone,
169+
{
170+
let items = items.map(|items| items.to_token_stream());
171+
let comma = TokenTree::Punct(Punct::new(',', Spacing::Alone)).into_token_stream();
172+
intersperse(items, comma).collect()
173+
}
174+
164175
pub trait Make<T> {
165176
fn make(self, mk: &Builder) -> T;
166177
}
@@ -208,28 +219,6 @@ impl<'a> Make<Path> for &'a str {
208219
}
209220
}
210221

211-
impl<'a> Make<Visibility> for &'a str {
212-
fn make(self, mk_: &Builder) -> Visibility {
213-
match self {
214-
"pub" => Visibility::Public(Token![pub](mk_.span)),
215-
"priv" | "" | "inherit" => Visibility::Inherited,
216-
"pub(crate)" => Visibility::Restricted(VisRestricted {
217-
pub_token: Token![pub](mk_.span),
218-
paren_token: token::Paren(mk_.span),
219-
in_token: None,
220-
path: Box::new(mk().path("crate")),
221-
}),
222-
"pub(super)" => Visibility::Restricted(VisRestricted {
223-
pub_token: Token![pub](mk_.span),
224-
paren_token: token::Paren(mk_.span),
225-
in_token: None,
226-
path: Box::new(mk().path("super")),
227-
}),
228-
_ => panic!("unrecognized string for Visibility: {:?}", self),
229-
}
230-
}
231-
}
232-
233222
impl<'a> Make<Abi> for &'a str {
234223
fn make(self, mk: &Builder) -> Abi {
235224
Abi {
@@ -252,47 +241,6 @@ impl Make<Extern> for Abi {
252241
}
253242
}
254243

255-
impl<'a> Make<Mutability> for &'a str {
256-
fn make(self, _mk: &Builder) -> Mutability {
257-
match self {
258-
"" | "imm" | "immut" | "immutable" => Mutability::Immutable,
259-
"mut" | "mutable" => Mutability::Mutable,
260-
_ => panic!("unrecognized string for Mutability: {:?}", self),
261-
}
262-
}
263-
}
264-
265-
impl<'a> Make<Unsafety> for &'a str {
266-
fn make(self, _mk: &Builder) -> Unsafety {
267-
match self {
268-
"" | "safe" | "normal" => Unsafety::Normal,
269-
"unsafe" => Unsafety::Unsafe,
270-
_ => panic!("unrecognized string for Unsafety: {:?}", self),
271-
}
272-
}
273-
}
274-
275-
impl<'a> Make<Constness> for &'a str {
276-
fn make(self, _mk: &Builder) -> Constness {
277-
match self {
278-
"" | "normal" | "not-const" => Constness::NotConst,
279-
"const" => Constness::Const,
280-
_ => panic!("unrecognized string for Constness: {:?}", self),
281-
}
282-
}
283-
}
284-
285-
impl<'a> Make<UnOp> for &'a str {
286-
fn make(self, _mk: &Builder) -> UnOp {
287-
match self {
288-
"deref" | "*" => UnOp::Deref(Default::default()),
289-
"not" | "!" => UnOp::Not(Default::default()),
290-
"neg" | "-" => UnOp::Neg(Default::default()),
291-
_ => panic!("unrecognized string for UnOp: {:?}", self),
292-
}
293-
}
294-
}
295-
296244
impl<I: Make<Ident>> Make<Lifetime> for I {
297245
fn make(self, mk: &Builder) -> Lifetime {
298246
Lifetime {
@@ -330,82 +278,21 @@ impl Make<TokenStream> for Vec<TokenTree> {
330278
}
331279
}
332280

333-
impl Make<TokenStream> for Vec<String> {
334-
fn make(self, _mk: &Builder) -> TokenStream {
335-
let mut tokens = vec![];
336-
let mut first = true;
337-
338-
for s in self {
339-
if !first {
340-
tokens.push(TokenTree::Punct(Punct::new(',', Spacing::Alone)));
341-
} else {
342-
first = false;
343-
}
344-
345-
tokens.push(TokenTree::Ident(Ident::new(&s, Span::call_site())));
346-
}
347-
348-
tokens.into_iter().collect::<TokenStream>()
349-
}
350-
}
351-
352281
impl Make<TokenStream> for Vec<&str> {
353282
fn make(self, _mk: &Builder) -> TokenStream {
354-
let mut tokens = vec![];
355-
let mut first = true;
356-
357-
for s in self {
358-
if !first {
359-
tokens.push(TokenTree::Punct(Punct::new(',', Spacing::Alone)));
360-
} else {
361-
first = false;
362-
}
363-
364-
tokens.push(TokenTree::Ident(Ident::new(s, Span::call_site())));
365-
}
366-
367-
tokens.into_iter().collect::<TokenStream>()
283+
comma_separated(self.iter().map(|&s| Ident::new(s, Span::call_site())))
368284
}
369285
}
370286

371287
impl Make<TokenStream> for Vec<u64> {
372288
fn make(self, _mk: &Builder) -> TokenStream {
373-
let mut tokens = vec![];
374-
let mut first = true;
375-
376-
for s in self {
377-
if !first {
378-
tokens.push(TokenTree::Punct(Punct::new(',', Spacing::Alone)));
379-
} else {
380-
first = false;
381-
}
382-
383-
tokens.push(TokenTree::Literal(Literal::u64_unsuffixed(s)));
384-
}
385-
386-
tokens.into_iter().collect::<TokenStream>()
289+
comma_separated(self.iter().map(|&s| Literal::u64_unsuffixed(s)))
387290
}
388291
}
389292

390293
impl Make<TokenStream> for Vec<Meta> {
391294
fn make(self, _mk: &Builder) -> TokenStream {
392-
let mut tokens = TokenStream::new();
393-
394-
let mut first = true;
395-
396-
for meta in self {
397-
if !first {
398-
let tt = TokenTree::Punct(Punct::new(',', Spacing::Alone));
399-
400-
tokens.extend(vec![tt]);
401-
} else {
402-
first = false;
403-
}
404-
405-
meta.to_tokens(&mut tokens);
406-
}
407-
408-
tokens
295+
comma_separated(self.iter())
409296
}
410297
}
411298

@@ -415,12 +302,6 @@ impl Make<PathArguments> for AngleBracketedGenericArguments {
415302
}
416303
}
417304

418-
impl Make<PathArguments> for ParenthesizedGenericArguments {
419-
fn make(self, _mk: &Builder) -> PathArguments {
420-
PathArguments::Parenthesized(self)
421-
}
422-
}
423-
424305
impl Make<GenericArgument> for Box<Type> {
425306
fn make(self, _mk: &Builder) -> GenericArgument {
426307
GenericArgument::Type(*self)
@@ -661,14 +542,6 @@ impl Builder {
661542
}
662543
}
663544

664-
pub fn parenthesized_args(self, tys: Vec<Box<Type>>) -> ParenthesizedGenericArguments {
665-
ParenthesizedGenericArguments {
666-
paren_token: token::Paren(self.span),
667-
inputs: punct_box(tys),
668-
output: ReturnType::Default,
669-
}
670-
}
671-
672545
pub fn angle_bracketed_args<A>(self, args: Vec<A>) -> AngleBracketedGenericArguments
673546
where
674547
A: Make<GenericArgument>,

c2rust-transpile/src/cfg/structures.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -667,12 +667,13 @@ impl StructureState {
667667
/// * Negating something of the form `!<expr>` produces `<expr>`
668668
///
669669
fn not(bool_expr: &Expr) -> Box<Expr> {
670+
use syn::UnOp;
670671
match *bool_expr {
671672
Expr::Unary(ExprUnary {
672-
op: syn::UnOp::Not(_),
673+
op: UnOp::Not(_),
673674
ref expr,
674675
..
675676
}) => Box::new(unparen(expr).clone()),
676-
_ => mk().unary_expr("!", Box::new(bool_expr.clone())),
677+
_ => mk().unary_expr(UnOp::Not(Default::default()), Box::new(bool_expr.clone())),
677678
}
678679
}

c2rust-transpile/src/translator/literals.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ impl<'c> Translation<'c> {
108108
// Fallback for characters outside of the valid Unicode range
109109
if (val as i32) < 0 {
110110
mk().unary_expr(
111-
"-",
111+
UnOp::Neg(Default::default()),
112112
mk().lit_expr(
113113
mk().int_lit((val as i32).unsigned_abs() as u128, "i32"),
114114
),
@@ -170,7 +170,7 @@ impl<'c> Translation<'c> {
170170
Ok(WithStmts::new_unsafe_val(transmute_expr(
171171
mk().array_ty(u8_ty, width_lit),
172172
self.convert_type(ty.ctype)?,
173-
mk().unary_expr("*", mk().lit_expr(val)),
173+
mk().unary_expr(UnOp::Deref(Default::default()), mk().lit_expr(val)),
174174
)))
175175
}
176176
}

c2rust-transpile/src/translator/mod.rs

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1008,7 +1008,7 @@ fn make_submodule(
10081008
items.push(mk().extern_("C").foreign_items(foreign_items));
10091009
}
10101010

1011-
let module_builder = mk().vis("pub");
1011+
let module_builder = mk().pub_();
10121012
let module_builder = if reorganize_definitions {
10131013
let file_path_str = file_path.map_or(mod_name.as_str(), |path| {
10141014
path.to_str().expect("Found invalid unicode")
@@ -1929,16 +1929,15 @@ impl<'c> Translation<'c> {
19291929
.expect("Variables should already be renamed");
19301930
let ConvertedVariable { ty, mutbl, init: _ } =
19311931
self.convert_variable(ctx.static_(), None, typ)?;
1932-
// When putting extern statics into submodules, they need to be public to be accessible
1933-
let visibility = if self.tcfg.reorganize_definitions {
1934-
"pub"
1935-
} else {
1936-
""
1937-
};
19381932
let mut extern_item = mk_linkage(true, &new_name, ident)
19391933
.span(span)
1940-
.set_mutbl(mutbl)
1941-
.vis(visibility);
1934+
.set_mutbl(mutbl);
1935+
1936+
// When putting extern statics into submodules, they need to be public to be accessible
1937+
if self.tcfg.reorganize_definitions {
1938+
extern_item = extern_item.pub_();
1939+
};
1940+
19421941
if has_thread_duration {
19431942
extern_item = extern_item.single_attr("thread_local");
19441943
}
@@ -2407,16 +2406,13 @@ impl<'c> Translation<'c> {
24072406
))
24082407
} else {
24092408
// Translating an extern function declaration
2409+
let mut mk_ = mk_linkage(true, new_name, name).span(span);
24102410

24112411
// When putting extern fns into submodules, they need to be public to be accessible
2412-
let visibility = if self.tcfg.reorganize_definitions {
2413-
"pub"
2414-
} else {
2415-
""
2412+
if self.tcfg.reorganize_definitions {
2413+
mk_ = mk_.pub_();
24162414
};
24172415

2418-
let mut mk_ = mk_linkage(true, new_name, name).span(span).vis(visibility);
2419-
24202416
for attr in attrs {
24212417
mk_ = match attr {
24222418
c_ast::Attribute::Alias(aliasee) => mk_.str_attr("link_name", aliasee),
@@ -2703,7 +2699,7 @@ impl<'c> Translation<'c> {
27032699

27042700
if self.ast_context.is_va_list(typ.ctype) {
27052701
// translate `va_list` variables to `VaListImpl`s and omit the initializer.
2706-
let pat_mut = mk().set_mutbl("mut").ident_pat(rust_name);
2702+
let pat_mut = mk().mutbl().ident_pat(rust_name);
27072703
let ty = {
27082704
let path = vec!["core", "ffi", "VaListImpl"];
27092705
mk().path_ty(mk().abs_path(path))
@@ -2747,7 +2743,7 @@ impl<'c> Translation<'c> {
27472743
zeroed.to_pure_expr()
27482744
}
27492745
.expect("Expected decl initializer to not have any statements");
2750-
let pat_mut = mk().set_mutbl("mut").ident_pat(rust_name.clone());
2746+
let pat_mut = mk().mutbl().ident_pat(rust_name.clone());
27512747
let local_mut = mk().local(pat_mut, Some(ty.clone()), Some(zeroed));
27522748
if has_self_reference {
27532749
let assign = mk().assign_expr(mk().ident_expr(rust_name), init);

0 commit comments

Comments
 (0)