Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "cppshift"
version = "0.1.4"
version = "0.1.5"
authors = ["Jérémy HERGAULT", "Enzo PASQUALINI"]
description = "CPP parser and transpiler"
repository = "https://github.com/worldline/cppshift"
Expand Down
148 changes: 146 additions & 2 deletions src/ast/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1499,8 +1499,8 @@ fn parse_item_fn_or_var<'de>(p: &mut Parser<'de>) -> Result<Item<'de>, AstError>
}
};

// Function: ident followed by (
if p.peek_kind() == Some(TokenKind::LeftParenthese) {
// Function: ident followed by ( — unless it is a direct-initializer `T x(0, 0);`
if p.peek_kind() == Some(TokenKind::LeftParenthese) && !is_paren_initializer(p) {
let inputs = parse_fn_params(p)?;

// Trailing qualifiers
Expand Down Expand Up @@ -1695,6 +1695,10 @@ fn parse_item_fn_or_var<'de>(p: &mut Parser<'de>) -> Result<Item<'de>, AstError>
};
p.expect(TokenKind::RightBrace)?;
init
} else if p.peek_kind() == Some(TokenKind::LeftParenthese) {
// Direct initialization: type ident(args);
let args = parse_paren_args(p)?;
Some(paren_init_expr(p, &return_type, args)?)
} else {
None
};
Expand All @@ -1713,6 +1717,8 @@ fn parse_item_fn_or_var<'de>(p: &mut Parser<'de>) -> Result<Item<'de>, AstError>
}
if p.eat(TokenKind::Equal).is_some() {
let _init = parse_expr_no_comma(p)?;
} else if p.peek_kind() == Some(TokenKind::LeftParenthese) {
let _init = parse_paren_args(p)?;
}
}
p.expect(TokenKind::Semicolon)?;
Expand Down Expand Up @@ -1748,6 +1754,71 @@ fn parse_item_fn_or_var<'de>(p: &mut Parser<'de>) -> Result<Item<'de>, AstError>
}
}

/// At `(` after a declarator name: `true` when the list starts with a token that
/// cannot begin a parameter declaration (a literal or a signed number), so
/// `T x(0, 0);` is a variable while `T f();` / `T f(U);` stay functions.
fn is_paren_initializer(p: &Parser<'_>) -> bool {
match p.peek_nth_kind(1) {
Some(
TokenKind::Number
| TokenKind::String
| TokenKind::Char
| TokenKind::KeywordTrue
| TokenKind::KeywordFalse
| TokenKind::KeywordNullptr,
) => true,
Some(TokenKind::Minus | TokenKind::Plus) => p.peek_nth_kind(2) == Some(TokenKind::Number),
_ => false,
}
}

/// Initializer of `ty ident(args);`. A single argument is the initializer itself,
/// as in `ty ident = arg;`. Several arguments become a constructor call of `ty`:
/// `T x(0, 0)` → `Expr::Call { func: T, args: (0, 0) }`.
fn paren_init_expr<'de>(
p: &Parser<'de>,
ty: &Type<'de>,
args: Punctuated<'de, Expr<'de>>,
) -> Result<Expr<'de>, AstError> {
if args.len() == 1 {
return Ok(args.into_values().remove(0));
}
let func = match ty_constructor_expr(ty) {
Some(func) => func,
None => {
return Err(p.error_at_current(
"parenthesized initializer with several arguments requires a class type",
));
}
};
Ok(Expr::Call(ExprCall {
func: Box::new(func),
args,
}))
}

/// Expression naming the class type `ty` (CV-qualifiers stripped), shaped as the
/// expression parser builds the callee of `T(args)`.
fn ty_constructor_expr<'de>(ty: &Type<'de>) -> Option<Expr<'de>> {
match ty {
Type::Qualified(q) => ty_constructor_expr(&q.ty),
Type::Path(tp) if tp.path.segments.len() == 1 && !tp.path.leading_colon => {
Some(Expr::Ident(ExprIdent {
ident: tp.path.segments[0].ident,
}))
}
Type::Path(tp) => Some(Expr::Path(ExprPath {
path: tp.path.clone(),
args: None,
})),
Type::TemplateInst(t) => Some(Expr::Path(ExprPath {
path: t.path.clone(),
args: Some(t.args.clone()),
})),
_ => None,
}
}

fn is_const_type(ty: &Type) -> bool {
match ty {
Type::Qualified(q) => q.cv.const_token,
Expand Down Expand Up @@ -3576,6 +3647,22 @@ fn parse_braced_args<'de>(p: &mut Parser<'de>) -> Result<Punctuated<'de, Expr<'d
Ok(args)
}

fn parse_paren_args<'de>(p: &mut Parser<'de>) -> Result<Punctuated<'de, Expr<'de>>, AstError> {
p.expect(TokenKind::LeftParenthese)?;
let mut args = Punctuated::new();
while p.peek_kind() != Some(TokenKind::RightParenthese) && !p.is_empty() {
let arg = parse_expr_no_comma(p)?;
if let Some(comma) = p.eat(TokenKind::Comma) {
args.push_pair(arg, comma);
} else {
args.push_value(arg);
break;
}
}
p.expect(TokenKind::RightParenthese)?;
Ok(args)
}

fn parse_expr_prefix<'de>(p: &mut Parser<'de>) -> Result<Expr<'de>, AstError> {
match p.peek_kind() {
Some(TokenKind::Minus) => {
Expand Down Expand Up @@ -4606,6 +4693,63 @@ mod tests {
}
}

#[test]
fn parse_const_paren_initializer() {
let file = parse(
"const tCardDate gcInvalidCardDate(0, -1);\n\
const string isoMTIdx(\"MTYP\");\n\
static ns::Point origin(0, 0);\n\
const cTime getInvalidTime();\n\
const cDate toDate(cTime);",
);
match &file.items[0] {
Item::Const(c) => {
assert_eq!(c.ident.sym, "gcInvalidCardDate");
let Expr::Call(call) = &c.expr else {
panic!("expected Call, got {:?}", c.expr);
};
assert!(matches!(&*call.func, Expr::Ident(i) if i.ident.sym == "tCardDate"));
assert_eq!(call.args.len(), 2);
assert!(matches!(
call.args.iter().nth(1),
Some(Expr::Unary(ExprUnary {
op: UnaryOp::Negate,
..
}))
));
}
other => panic!("expected Const, got {other:?}"),
}
match &file.items[1] {
Item::Const(c) => {
assert_eq!(c.ident.sym, "isoMTIdx");
assert!(matches!(
c.expr,
Expr::Lit(ExprLit {
kind: LitKind::String,
..
})
));
}
other => panic!("expected Const, got {other:?}"),
}
match &file.items[2] {
Item::Static(s) => {
let Some(Expr::Call(call)) = &s.expr else {
panic!("expected Call, got {:?}", s.expr);
};
assert!(matches!(&*call.func, Expr::Path(p) if p.path.segments.len() == 2));
}
other => panic!("expected Static, got {other:?}"),
}
for item in &file.items[3..] {
match item {
Item::Fn(f) => assert!(f.block.is_none()),
other => panic!("expected Fn, got {other:?}"),
}
}
}

#[test]
fn parse_constexpr_variable() {
let file = parse("constexpr int SIZE = 42;");
Expand Down
96 changes: 92 additions & 4 deletions src/transpile/ty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,57 @@ fn try_transpile_char_array_from_str_lit<'de>(
Some(Ok(()))
}

/// Returns `true` if `func` names the class type `ty` (CV-qualifiers and template
/// arguments ignored), i.e. `func(args)` is a constructor call of `ty`.
fn expr_names_type(func: &Expr<'_>, ty: &Type<'_>) -> bool {
let ty_path = match ty {
Type::Qualified(q) => return expr_names_type(func, &q.ty),
Type::Path(tp) => &tp.path,
Type::TemplateInst(t) => &t.path,
_ => return false,
};
match func {
Expr::Ident(i) => {
!ty_path.leading_colon
&& ty_path.segments.len() == 1
&& ty_path.segments[0].ident.sym == i.ident.sym
}
Expr::Path(p) => {
p.path.leading_colon == ty_path.leading_colon
&& p.path.segments.len() == ty_path.segments.len()
&& p.path
.segments
.iter()
.zip(&ty_path.segments)
.all(|(a, b)| a.ident.sym == b.ident.sym)
}
_ => false,
}
}

/// Transpile the initializer of a const/static of type `ty`.
///
/// A constructor call of `ty` (`T x(0, 0);`, `T x = T(0, 0);`) becomes `<T>::new(0, 0)`.
fn transpile_initializer<'de>(
ty: &Type<'de>,
expr: &Expr<'de>,
transpiler: &Transpiler,
ctx: &mut TranspileContext,
) -> Result<TokenStream, TranspileError> {
if let Expr::Call(call) = expr
&& expr_names_type(&call.func, ty)
{
let rust_ty = transpiler.ty_mapper.map_type(ty)?;
let args = call
.args
.iter()
.map(|arg| arg.transpile_token_stream(transpiler, ctx))
.collect::<Result<Vec<_>, _>>()?;
return Ok(quote::quote!(<#rust_ty>::new(#(#args),*)));
}
expr.transpile_token_stream(transpiler, ctx)
}

impl<'de> Transpile for ItemConst<'de> {
fn transpile(
&self,
Expand All @@ -401,8 +452,7 @@ impl<'de> Transpile for ItemConst<'de> {
return result;
}

let mut expr_tokens = TokenStream::new();
self.expr.transpile(transpiler, ctx, &mut expr_tokens)?;
let expr_tokens = transpile_initializer(&self.ty, &self.expr, transpiler, ctx)?;

match &self.expr {
// C++ string constants with string literal init → `&str`
Expand Down Expand Up @@ -475,8 +525,7 @@ impl<'de> Transpile for ItemStatic<'de> {
return result;
}

let mut expr_tokens = TokenStream::new();
expr.transpile(transpiler, ctx, &mut expr_tokens)?;
let expr_tokens = transpile_initializer(&self.ty, expr, transpiler, ctx)?;

match expr {
// C++ string statics with string literal init → `&str`
Expand Down Expand Up @@ -987,6 +1036,45 @@ mod tests {
Ok(())
}

#[test]
fn const_paren_initializer_transpiles() -> Result<(), TranspileError> {
let transpiler = Transpiler {
ty_mapper: TypeMapper::builder()
.map_path("cShortDate", "ShortDate")?
.build(),
..Default::default()
};
let src = "const tCardDate gcInvalidCardDate(0, 0);\n\
const cShortDate gcDate(1, -2);\n\
const string isoMTIdx(\"MTYP\");\n\
static tCardDate gsDate(0, 0);\n\
const cTime getInvalidTime();";
let file = parse_file(src).unwrap();
let expected = [
"# [doc = concat ! (\" Auto-transpiled const \" , stringify ! (tCardDate))] pub const gcInvalidCardDate : tCardDate = < tCardDate > :: new (0 , 0) ;",
"# [doc = concat ! (\" Auto-transpiled const \" , stringify ! (ShortDate))] pub const gcDate : ShortDate = < ShortDate > :: new (1 , - 2) ;",
"# [doc = \" Auto-transpiled &str const\"] pub const isoMTIdx : & str = \"MTYP\" ;",
"# [doc = concat ! (\" Auto-transpiled static \" , stringify ! (tCardDate))] pub static gsDate : tCardDate = < tCardDate > :: new (0 , 0) ;",
];
for (item, expected) in file.items.iter().zip(expected) {
let tokens = match item {
crate::ast::Item::Const(c) => {
c.transpile_token_stream(&transpiler, &mut TranspileContext::default())?
}
crate::ast::Item::Static(s) => {
s.transpile_token_stream(&transpiler, &mut TranspileContext::default())?
}
item => panic!("expected ItemConst or ItemStatic, got {item:?}"),
};
assert_eq!(tokens.to_string(), expected);
}
assert!(matches!(
&file.items[4],
crate::ast::Item::Fn(f) if f.block.is_none()
));
Ok(())
}

#[test]
fn constexpr_transpiles() -> Result<(), TranspileError> {
let transpiler = Transpiler::default();
Expand Down
Loading