Repository navigation
Move function-local records in global scope - #375
Merged
Merged
Conversation
joaotgouveia
pushed a commit
to joaotgouveia/cpp2rust
that referenced
this pull request
Oct 27, 2026
```cpp
template <typename T> int get(T t) { return t.x; }
int main() {
struct Local {
int x;
};
Local l{7};
assert(get(l) == 7);
return 0;
}
```
The `get` function template lives in the global scope while `Local`
(used to instantiate `get`) lives at function scope. In the AST
instantiations live in the global scope as well, so it gets translated
as:
```rs
// Wrong: the global scope has no Local_1. It only exists inside main
pub unsafe fn get_0(mut t: Local_1) -> i32 {
return (t.x as i32);
}
unsafe fn main_0() -> i32 {
pub struct Local_1 {
pub x: i32,
};
let mut l: Local_1 = Local_1 { x: 7 };
assert!(((unsafe { get_0(l,) }) == (7)));
return 0;
}
```
This PR fixes this by moving the definition of `Local_1` at a global
scope:
```rs
// Correct: now Local_1 is visible for the instantiation
pub unsafe fn get_0(mut t: Local_1) -> i32 {
return (t.x as i32);
}
unsafe fn main_0() -> i32 {
let mut l: Local_1 = Local_1 { x: 7 };
assert!(((unsafe { get_0(l,) }) == (7)));
return 0;
}
pub struct Local_1 {
pub x: i32,
};
```
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The
getfunction template lives in the global scope whileLocal(used to instantiateget) lives at function scope. In the AST instantiations live in the global scope as well, so it gets translated as:This PR fixes this by moving the definition of
Local_1at a global scope: