ziglang / zig

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
https://ziglang.org
MIT License
35.2k stars 2.56k forks source link

Errors printing float #669

Closed ofelas closed 6 years ago

ofelas commented 6 years ago

Demonstrated with the following snippet. Tested with version 0.1.1.4e3d7fc.

const warn = @import("std").debug.warn;

// bin/zig version: 0.1.1.4e3d7fc
// build-exe: a float 3.14
// with --release-safe: a float index out of bounds
//                      Aborted
// with --release-fast: a float Segmentation fault

pub fn main() -> %void {
    var f: f64 = 3.14;
    // the following needs f64() or else error: parameter of type '(float literal)' requires comptime
    // warn("float {}\n", f64(3.14)); // <- uncomment this line and both always work!?!
    warn("a float {.3}\n", f); // same behaviour with and without .3
}
zesterer commented 6 years ago

This problem exists for integer literals as well:

printf("{}", 5);

yields

error: parameter of type '(integer literal)' requires comptime

tiehuis commented 6 years ago

@zesterer

That isn't the issue presented here. Comptime literals are stored as arbitrary-precision values in the compiler (floats are stored as 128-bit right now). In order to print these, we would have to either bundle compile-time integer support into a runtime or serialize to a string at compile-time which are both fairly untenable as they require a lot of extra machinery/memory that is rather implicit. For this reason we just emit an error (which is a little unhelpful).

I've made a proposal to discuss 'solving' this here: #747.