From c5891eb4626d006907618b2604b2b5baa670d4ce Mon Sep 17 00:00:00 2001 From: Jeremy HERGAULT Date: Fri, 27 Nov 2026 16:29:32 +0100 Subject: [PATCH] fix: take into account constructor initializer Signed-off-by: Jeremy HERGAULT --- Cargo.toml | 2 +- src/ast/parse.rs | 148 +++++++++++++++++++++++++++++++++++++++++++- src/transpile/ty.rs | 96 ++++++++++++++++++++++++++-- 3 files changed, 239 insertions(+), 7 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 138ca04..db0a77c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" diff --git a/src/ast/parse.rs b/src/ast/parse.rs index 7b0369d..432dacd 100644 --- a/src/ast/parse.rs +++ b/src/ast/parse.rs @@ -1499,8 +1499,8 @@ fn parse_item_fn_or_var<'de>(p: &mut Parser<'de>) -> Result, 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 @@ -1695,6 +1695,10 @@ fn parse_item_fn_or_var<'de>(p: &mut Parser<'de>) -> Result, 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 }; @@ -1713,6 +1717,8 @@ fn parse_item_fn_or_var<'de>(p: &mut Parser<'de>) -> Result, 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)?; @@ -1748,6 +1754,71 @@ fn parse_item_fn_or_var<'de>(p: &mut Parser<'de>) -> Result, 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, 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> { + 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, @@ -3576,6 +3647,22 @@ fn parse_braced_args<'de>(p: &mut Parser<'de>) -> Result(p: &mut Parser<'de>) -> Result>, 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, AstError> { match p.peek_kind() { Some(TokenKind::Minus) => { @@ -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;"); diff --git a/src/transpile/ty.rs b/src/transpile/ty.rs index fdbd0aa..d2fc914 100644 --- a/src/transpile/ty.rs +++ b/src/transpile/ty.rs @@ -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 `::new(0, 0)`. +fn transpile_initializer<'de>( + ty: &Type<'de>, + expr: &Expr<'de>, + transpiler: &Transpiler, + ctx: &mut TranspileContext, +) -> Result { + 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::, _>>()?; + return Ok(quote::quote!(<#rust_ty>::new(#(#args),*))); + } + expr.transpile_token_stream(transpiler, ctx) +} + impl<'de> Transpile for ItemConst<'de> { fn transpile( &self, @@ -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` @@ -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` @@ -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();