Skip to content

[BUG] int variable casted with as to size_t does not fail on compile time #1257

Closed
@filipsajdak

Description

@filipsajdak

In the current implementation of cppfront (065a993), the following code compiles and runs:

i : int = 123;
std::cout << (i as size_t) << std::endl;

produces

123

and should fail to compile with the following error:

cppfront/include/cpp2util.h:3382:9: error: static assertion failed due to requirement 'program_violates_type_safety_guarantee<unsigned long, int>': 'as' does not allow unsafe possibly-lossy narrowing conversions - if you're sure you want this, use 'unsafe_narrow<T>' to explicitly force the conversion and possibly lose information
        static_assert(
        ^
narrowing.cpp2:10:31: note: in instantiation of function template specialization 'cpp2::impl::as_<unsigned long, int>' requested here
    std::cout << (cpp2::impl::as_<size_t>(cpp2::move(i))) << std::endl;
                              ^
1 error generated.

A potential error will be caught in runtime, e.g., when the i is negative, the following error will be produced:

cppfront/include/cpp2util.h(2486) decltype(auto) cpp2::impl::as(auto &&, std::source_location) [C = unsigned long, x:auto = int]: Type safety violation: dynamic lossy narrowing conversion attempt detected
libc++abi: terminating

It will save us from the trouble... but a user should be informed to use cpp2::unsafe_narrow<size_t>(i) instead.

The bug is related to the badly defined is_narrowing_v - I have the patch already and will deliver it in next PR.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions