Skip to content

Commit f614f07

Browse files
authored
Don't translate default arguments as Option (#648)
Master translates `int add(int a, int b = 2) { return a + b; }` as `fn add(a: i32, b: Option<i32>) -> i32`. This breaks taking the address of functions with default arguments: `expected 'fn add(a: i32, b: i32) -> i32', found 'fn add(a: i32, b: Option<i32>) -> i32'`. Drop the Option from the function signature and evaluate the default argument before entering the function. This is closer to what C++ does.
1 parent 23debb3 commit f614f07

29 files changed

Lines changed: 770 additions & 424 deletions

‎cpp2rust/converter/converter.cpp‎

Lines changed: 31 additions & 102 deletions
Original file line numberDiff line numberDiff line change
@@ -588,22 +588,10 @@ bool Converter::ConvertVarDeclSkipInit(clang::VarDecl *decl) {
588588
StrCat(keyword::kMut);
589589
}
590590
StrCat(name, token::kColon);
591-
592-
bool is_parm_with_default_value = false;
593-
if (auto parm = clang::dyn_cast<clang::ParmVarDecl>(decl)) {
594-
is_parm_with_default_value = HasUsableDefaultArg(parm);
595-
}
596-
597-
if (is_parm_with_default_value) {
598-
StrCat("Option<");
599-
}
600591
{
601592
PushLazyType lazy(*this, IsGlobalVar(decl) && LazyStaticInit());
602593
Convert(qual_type);
603594
}
604-
if (is_parm_with_default_value) {
605-
StrCat('>');
606-
}
607595
return true;
608596
}
609597

@@ -1028,9 +1016,9 @@ void Converter::EmitConversionAttrs(clang::CXXRecordDecl *decl) {
10281016
!type->isReferenceType() ? "value"
10291017
: is_move || type.getNonReferenceType().isConstQualified() ? "ptr"
10301018
: "mut_ptr";
1031-
StrCat(std::format(
1032-
"#[{}({}, {}, {}{})]", is_move ? "cpp_from_move" : "cpp_from", source,
1033-
GetCtorName(ctor), param->hasDefaultArg() ? "some_" : "", kind));
1019+
StrCat(std::format("#[{}({}, {}, {})]",
1020+
is_move ? "cpp_from_move" : "cpp_from", source,
1021+
GetCtorName(ctor), kind));
10341022
});
10351023
std::unordered_set<std::string> into_types;
10361024
ForEachMethod(decl, [&](clang::CXXMethodDecl *method) {
@@ -1310,41 +1298,6 @@ bool Converter::VisitFieldDecl(clang::FieldDecl *decl) {
13101298
return false;
13111299
}
13121300

1313-
std::string
1314-
Converter::EmitDefaultArgStorage(const clang::ParmVarDecl *param,
1315-
const clang::MaterializeTemporaryExpr *temp) {
1316-
auto storage = std::format("__{}_default", GetNamedDeclAsString(param));
1317-
StrCat(std::format("let mut {} : Option<{}> = None", storage,
1318-
ToString(temp->getType().getUnqualifiedType())),
1319-
token::kSemiColon);
1320-
return storage;
1321-
}
1322-
1323-
void Converter::EmitFunctionPreamble(clang::FunctionDecl *decl) {
1324-
for (auto *param : DefinitionParameters(decl)) {
1325-
if (!HasUsableDefaultArg(param)) {
1326-
continue;
1327-
}
1328-
auto name = GetNamedDeclAsString(param);
1329-
auto type = ToString(param->getType());
1330-
std::string value;
1331-
if (auto *temp = GetDefaultArgTemporary(param)) {
1332-
auto storage = EmitDefaultArgStorage(param, temp);
1333-
value = std::format("{}.insert({}) as {}", storage,
1334-
ToString(temp->getSubExpr()), type);
1335-
} else if (param->getType()->isReferenceType()) {
1336-
Buffer buf(*this);
1337-
ConvertVarInit(param->getType(), param->getDefaultArg());
1338-
value = std::move(buf).str();
1339-
} else {
1340-
value = ToString(param->getDefaultArg());
1341-
}
1342-
StrCat(std::format("let mut {} : {} = {}.unwrap_or_else(|| {} {{ {} }})",
1343-
name, type, name, keyword_unsafe_, value),
1344-
token::kSemiColon);
1345-
}
1346-
}
1347-
13481301
void Converter::ConvertDeclContext(clang::DeclContext *decl) {
13491302
for (auto *child : decl->decls()) {
13501303
if (IsInMainFile(child) || !decl_ids_.contains(GetID(child))) {
@@ -2133,6 +2086,9 @@ Converter::CallInfo Converter::CollectCallInfo(clang::CallExpr *expr) {
21332086

21342087
for (unsigned i = 0; i < num_named_params && i < num_args; ++i) {
21352088
auto *arg = expr->getArg(i + arg_begin);
2089+
if (auto *default_arg = clang::dyn_cast<clang::CXXDefaultArgExpr>(arg)) {
2090+
arg = default_arg->getExpr();
2091+
}
21362092
CallArg ca{
21372093
.param_name =
21382094
function && !function->getParamDecl(i)->getName().empty()
@@ -2141,8 +2097,6 @@ Converter::CallInfo Converter::CollectCallInfo(clang::CallExpr *expr) {
21412097
.param_type = function ? function->getParamDecl(i)->getType()
21422098
: proto->getParamType(i),
21432099
.expr = arg,
2144-
.has_default =
2145-
function && HasUsableDefaultArg(function->getParamDecl(i)),
21462100
.kind = (IsLiteral(arg) || info.is_libc_passthrough) ? Kind::Inline
21472101
: Kind::Hoisted,
21482102
};
@@ -2246,33 +2200,19 @@ void Converter::EmitArgList(const CallInfo &info) {
22462200

22472201
for (unsigned i = 0; i < info.args.size(); i++) {
22482202
const auto &ca = info.args[i];
2249-
2250-
if (ca.has_default && clang::isa<clang::CXXDefaultArgExpr>(ca.expr)) {
2251-
StrCat("None", token::kComma);
2252-
continue;
2253-
}
2254-
2255-
if (ca.has_default) {
2256-
StrCat("Some");
2257-
}
2258-
2259-
{
2260-
PushParen push(*this, ca.has_default);
2261-
switch (ca.kind) {
2262-
case Kind::Hoisted:
2263-
StrCat(ca.param_name);
2264-
break;
2265-
case Kind::Materialized:
2266-
StrCat(ca.ref_temp_name);
2267-
break;
2268-
case Kind::Inline:
2269-
ConvertParamTy(ca.param_type, ca.expr);
2270-
if (info.is_libc_passthrough) {
2271-
StrCat(
2272-
std::format("as {}", Mapper::GetParamType(*this, info.expr, i)));
2273-
}
2274-
break;
2203+
switch (ca.kind) {
2204+
case Kind::Hoisted:
2205+
StrCat(ca.param_name);
2206+
break;
2207+
case Kind::Materialized:
2208+
StrCat(ca.ref_temp_name);
2209+
break;
2210+
case Kind::Inline:
2211+
ConvertParamTy(ca.param_type, ca.expr);
2212+
if (info.is_libc_passthrough) {
2213+
StrCat(std::format("as {}", Mapper::GetParamType(*this, info.expr, i)));
22752214
}
2215+
break;
22762216
}
22772217

22782218
StrCat(token::kComma);
@@ -4110,31 +4050,15 @@ void Converter::ConvertCXXConstructExprArgs(clang::CXXConstructExpr *expr) {
41104050
GetCtorName(ctor));
41114051
PushParen paren(*this);
41124052

4113-
unsigned arg_idx = 0;
4114-
for (unsigned param_idx = 0; param_idx < ctor->getNumParams(); ++param_idx) {
4115-
auto param = ctor->getParamDecl(param_idx);
4116-
auto param_type = param->getType();
4117-
bool has_default = HasUsableDefaultArg(param);
4118-
4119-
if (arg_idx < expr->getNumArgs() &&
4120-
clang::isa<clang::CXXDefaultArgExpr>(expr->getArg(arg_idx))) {
4121-
assert(has_default);
4122-
++arg_idx;
4123-
StrCat("None", token::kComma);
4124-
continue;
4053+
for (unsigned i = 0; i < ctor->getNumParams(); ++i) {
4054+
assert(i < expr->getNumArgs());
4055+
clang::Expr *arg = expr->getArg(i);
4056+
if (auto *default_arg = clang::dyn_cast<clang::CXXDefaultArgExpr>(arg)) {
4057+
arg = default_arg->getExpr();
41254058
}
4126-
4127-
if (arg_idx < expr->getNumArgs()) {
4128-
clang::Expr *arg = expr->getArg(arg_idx++);
4059+
{
41294060
PushBrace brace(*this);
4130-
if (has_default) {
4131-
StrCat("Some");
4132-
}
4133-
PushParen some(*this, has_default);
4134-
ConvertVarInit(param_type, arg);
4135-
} else {
4136-
assert(has_default);
4137-
StrCat("None");
4061+
ConvertVarInit(ctor->getParamDecl(i)->getType(), arg);
41384062
}
41394063
StrCat(token::kComma);
41404064
}
@@ -5215,8 +5139,13 @@ void Converter::AddDefaultTrait(const clang::RecordDecl *decl) {
52155139
auto *cxx = clang::dyn_cast<clang::CXXRecordDecl>(decl);
52165140
if (auto *default_ctor =
52175141
cxx ? GetUserDefinedDefaultConstructor(cxx) : nullptr) {
5142+
std::vector<clang::Expr *> args;
5143+
for (auto *param : default_ctor->parameters()) {
5144+
args.push_back(clang::CXXDefaultArgExpr::Create(
5145+
ctx_, param->getLocation(), param, nullptr, default_ctor));
5146+
}
52185147
Convert(MakeConstructExpr(ctx_, ctx_.getCanonicalTagType(decl),
5219-
default_ctor, {}));
5148+
default_ctor, args));
52205149
} else {
52215150
EmitDefaultStructLiteral(decl);
52225151
}

‎cpp2rust/converter/converter.h‎

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -136,13 +136,7 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
136136

137137
virtual bool VisitFunctionDecl(clang::FunctionDecl *decl);
138138

139-
virtual void EmitFunctionPreamble(clang::FunctionDecl *decl);
140-
141-
// Declares the storage of the temporary temp that the default argument of
142-
// param is bound to, and returns its name.
143-
std::string
144-
EmitDefaultArgStorage(const clang::ParmVarDecl *param,
145-
const clang::MaterializeTemporaryExpr *temp);
139+
virtual void EmitFunctionPreamble(clang::FunctionDecl *) {}
146140

147141
virtual void ConvertFunctionBody(clang::FunctionDecl *decl);
148142

@@ -404,7 +398,6 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
404398
std::string ref_temp_name;
405399
clang::QualType param_type;
406400
clang::Expr *expr;
407-
bool has_default;
408401
Kind kind;
409402
};
410403

‎cpp2rust/converter/converter_lib.cpp‎

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1001,15 +1001,6 @@ bool HasUsableDefaultArg(const clang::ParmVarDecl *param) {
10011001
return param->hasDefaultArg() && !param->hasUninstantiatedDefaultArg();
10021002
}
10031003

1004-
const clang::MaterializeTemporaryExpr *
1005-
GetDefaultArgTemporary(const clang::ParmVarDecl *param) {
1006-
if (!param->getType()->isReferenceType()) {
1007-
return nullptr;
1008-
}
1009-
return clang::dyn_cast<clang::MaterializeTemporaryExpr>(
1010-
param->getDefaultArg()->IgnoreParens());
1011-
}
1012-
10131004
std::string GetFileName(const clang::Decl *decl) {
10141005
const auto &ctx = decl->getASTContext();
10151006
const auto full_location = ctx.getFullLoc(decl->getBeginLoc());

‎cpp2rust/converter/converter_lib.h‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -200,9 +200,6 @@ GetUserDefinedDefaultConstructor(const clang::CXXRecordDecl *decl);
200200

201201
bool HasUsableDefaultArg(const clang::ParmVarDecl *param);
202202

203-
const clang::MaterializeTemporaryExpr *
204-
GetDefaultArgTemporary(const clang::ParmVarDecl *param);
205-
206203
std::string GetFileName(const clang::Decl *decl);
207204

208205
unsigned GetLineNumber(const clang::Decl *decl);

‎cpp2rust/converter/models/converter_refcount.cpp‎

Lines changed: 6 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -154,12 +154,11 @@ bool ConverterRefCount::NeedsMut(const clang::VarDecl *decl,
154154
if (!in_function_formals_) {
155155
return true;
156156
}
157-
// Parameters are modified in place, except for those with a default value,
158-
// which are unwrapped into a variable, and those of a function declared
157+
// Parameters are modified in place, except for those of a function declared
159158
// without a body, which can't be mutable.
160159
auto *param = clang::cast<clang::ParmVarDecl>(decl);
161160
auto *function = clang::cast<clang::FunctionDecl>(param->getDeclContext());
162-
return !HasUsableDefaultArg(param) && !function->isPureVirtual() &&
161+
return !function->isPureVirtual() &&
163162
method_target_ != MethodTarget::TraitDecl;
164163
}
165164

@@ -834,40 +833,13 @@ void ConverterRefCount::EmitFunctionPreamble(clang::FunctionDecl *decl) {
834833
"Rc::new(RefCell::new(__args.into()));");
835834
}
836835
for (auto *param : DefinitionParameters(decl)) {
837-
auto name = GetNamedDeclAsString(param);
838-
if (param->getType()->isReferenceType()) {
839-
if (!HasUsableDefaultArg(param)) {
840-
continue;
841-
}
842-
auto type = ToString(param->getType());
843-
std::string value;
844-
if (auto *temp = GetDefaultArgTemporary(param)) {
845-
auto storage = EmitDefaultArgStorage(param, temp);
846-
value = std::format("{}.insert(Rc::new(RefCell::new({}))).as_pointer()",
847-
storage, ToString(temp->getSubExpr()));
848-
} else {
849-
Buffer buf(*this);
850-
ConvertVarInit(param->getType(), param->getDefaultArg());
851-
value = std::move(buf).str();
852-
}
853-
StrCat(std::format("let {} : {} = {}.unwrap_or_else(|| {})", name, type,
854-
name, value),
855-
token::kSemiColon);
856-
continue;
857-
}
858-
859836
// Unboxed parameters are used in place.
860-
bool unboxed = IsUnboxedVar(param);
861-
if (unboxed && !HasUsableDefaultArg(param)) {
837+
if (param->getType()->isReferenceType() || IsUnboxedVar(param)) {
862838
continue;
863839
}
864-
auto init = HasUsableDefaultArg(param)
865-
? std::format("{}.unwrap_or_else(|| {})", name,
866-
ToString(param->getDefaultArg()))
867-
: name;
868-
PushConversionKind push(*this, ConversionKind::Unboxed, unboxed);
869-
StrCat(std::format("let {}{} : {} = {}", unboxed ? "mut " : "", name,
870-
ToString(param->getType()), BoxValue(std::move(init))),
840+
auto name = GetNamedDeclAsString(param);
841+
StrCat(std::format("let {} : {} = {}", name, ToString(param->getType()),
842+
BoxValue(std::string(name))),
871843
token::kSemiColon);
872844
}
873845
}

‎libcc2rs-macros/src/cpp_from.rs‎

Lines changed: 5 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ use syn::{DeriveInput, Ident, Token, Type, parse_macro_input};
99

1010
// #[derive(CppFrom)]
1111
// #[cpp_from(i32, new, value)] // S(int)
12-
// #[cpp_from(i32, new_1, some_value)] // S(int = 0)
1312
// #[cpp_from(T, new_2, ptr)] // S(const T &)
1413
// #[cpp_from(T, new_3, mut_ptr)] // S(T &)
1514
// #[cpp_from_move(T, new_4, ptr)] // S(T &&)
@@ -21,9 +20,8 @@ use syn::{DeriveInput, Ident, Token, Type, parse_macro_input};
2120
// of S, and libcc2rs::CppFrom<S> for each type S converts to with a
2221
// conversion operator, such that the rules convert values as C++ does
2322
// implicitly. `value` passes the pointee to the constructor, `ptr` the
24-
// pointer, `mut_ptr` a mutable pointer, and `some_` wraps the argument in
25-
// Some for a defaulted parameter. CppFromUnsafe is the same for the unsafe
26-
// model.
23+
// pointer and `mut_ptr` a mutable pointer. CppFromUnsafe is the same for the
24+
// unsafe model.
2725

2826
#[derive(Clone, Copy)]
2927
enum Kind {
@@ -36,7 +34,6 @@ struct Conversion {
3634
ty: Type,
3735
method: Ident,
3836
kind: Kind,
39-
some: bool,
4037
}
4138

4239
impl Parse for Conversion {
@@ -45,36 +42,22 @@ impl Parse for Conversion {
4542
input.parse::<Token![,]>()?;
4643
let method = input.parse()?;
4744
let mut kind = Kind::Ptr;
48-
let mut some = false;
4945
if input.peek(Token![,]) {
5046
input.parse::<Token![,]>()?;
5147
let spelled: Ident = input.parse()?;
52-
let name = spelled.to_string();
53-
let name = match name.strip_prefix("some_") {
54-
Some(rest) => {
55-
some = true;
56-
rest
57-
}
58-
None => name.as_str(),
59-
};
60-
kind = match name {
48+
kind = match spelled.to_string().as_str() {
6149
"value" => Kind::Value,
6250
"ptr" => Kind::Ptr,
6351
"mut_ptr" => Kind::MutPtr,
6452
_ => {
6553
return Err(syn::Error::new(
6654
spelled.span(),
67-
"expected `value`, `ptr` or `mut_ptr`, optionally prefixed by `some_`",
55+
"expected `value`, `ptr` or `mut_ptr`",
6856
));
6957
}
7058
};
7159
}
72-
Ok(Conversion {
73-
ty,
74-
method,
75-
kind,
76-
some,
77-
})
60+
Ok(Conversion { ty, method, kind })
7861
}
7962
}
8063

@@ -97,11 +80,6 @@ fn ctor_call(
9780
(Kind::MutPtr, true) if !is_move => quote!(src.cast_mut()),
9881
(Kind::Ptr | Kind::MutPtr, _) => quote!(src),
9982
};
100-
let arg = if conversion.some {
101-
quote!(Some(#arg))
102-
} else {
103-
arg
104-
};
10583
quote!(#name::#method(#arg))
10684
}
10785

0 commit comments

Comments
 (0)