Skip to content

Add diagnostics for returning a temporary, closes #381 #384

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conversation

filipsajdak
Copy link
Contributor

The current implementation of cppfront (65fcd0f) does not provide diagnostics for forward return temporary variables, e.g.:

forward_return_literal: () -> forward _ = {
    return 1;
}

forward_return_rvalue: () -> forward _ = {
    return global + 1;
}

Generates:

cpp2::i32 global {42}; 

[[nodiscard]] auto forward_return_literal() -> auto&&{
    return 1; // return reference to literal
}

[[nodiscard]] auto forward_return_rvalue() -> auto&&{
    return global + 1; // return reference to temporary variable
}

This change provides better diagnostics and handles most operators that might create a temporary variable:

  • binary expression: /, <<, <=>, <, <=, >>, >=, >, +, -, ||, |, &&, *, %, &, ^, ==, !=,
  • prefix expression: !,
  • postfix expression: &, ~

All other operators that return references are accepted.

All regression tests pass. Closes #381

Need to be checked

The below cases still might not be supported:

  • using operators that return a reference on local variables,
  • calling function that returns a non-reference,

@JohelEGP
Copy link
Contributor

I think https://en.cppreference.com/w/cpp/types/reference_converts_from_temporary could be used for the general case. See https://compiler-explorer.com/z/87b6aEEc8. But that's C++23 and incompletely supported:
1681856957
1681856975

@filipsajdak filipsajdak force-pushed the fsajdak-diagnostics-for-forwarding-temporary-variable branch from b3b196b to 4fda4ff Compare April 19, 2023 16:38
@hsutter
Copy link
Owner

hsutter commented Apr 20, 2023

Thanks!

@hsutter hsutter merged commit 81e08cf into hsutter:main Apr 20, 2023
@filipsajdak filipsajdak deleted the fsajdak-diagnostics-for-forwarding-temporary-variable branch April 20, 2023 00:42
zaucy pushed a commit to zaucy/cppfront that referenced this pull request Dec 5, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[BUG] Forward returning literals and rvalues not rejected.
3 participants