On Mon, Sep 20, 2010 at 1:25 PM, Patrick Walton <[email protected]> wrote: > On 9/20/10 11:09 AM, Graydon Hoare wrote: >>> >>> Is it possible to infer the type from the expression, e.g. in 2 + x >>> the 2 matches the declared type of x? >> >> Plausible. Go takes a similar angle on this; their numeric literals are >> "untyped" and acquire a type via inference from the context. I'm not >> sure I'm really keen on that -- every additional complication to >> inference is a bit of a penalty to implementers, tools and future >> readers -- but it could work. >> >> Any feelings from others? Particularly .. those who have worked on the >> type inference module :) > > I'm also somewhat opposed to the proposal. To me, the strict typing of > numeric literals is a great feature of Rust: it lets the programmer look at > the code and immediately tell what's going to happen in the generated > instructions and memory layout. C's integer promotion rules are confusing; > by looking at C code I can never really tell precisely which instruction is > going to be emitted.
C's promotion rules are confusing at least partly because they apply to variables, not just literals. If they only applied to literals, you could find the type just as easily as you find a variable's type, just by looking at the variables the literal is used with. > Adding Go-style untyped numeric literals would also be difficult to > reconcile with our type inference and polymorphic binary operators: what's > the type of x in "auto x = 2 + 3;"? IIRC, Fortress gives each integral literal the type IntLiteral, which captures the exact sequence of digits and has implicit conversions to each particular integral type. Haskell does something similar by making literals a shorthand for "fromInteger (something::Integer)", and fromInteger is overloaded for each integral type. In both languages, the compiler's welcome to inline and pre-evaluate the overloaded conversion. In Fortress, IntLiteral can leak into type-parametrized functions or even data structures and so survive to runtime, while in Haskell, the type of "fromInteger x", "Num a=>a" has to be lowered to a concrete type before runtime (although it defaults to Integer if there's no other constraint). For Rust, if you go with magic literals, I see two places you can block them from leaking to runtime: either forbid functions from taking the literal type as a type parameter, or also forbid "auto" from being used with a literal type. If you allow "auto" to be used with the literal type, it requires more work on the compiler's part to always lower literals to their final type before emitting code, but I believe the compiler can always do it. On the other hand, if you were to allow the literal type as a type parameter, I think rust's lack of specialized functions would force it to be propagated to runtime. Jeffrey _______________________________________________ Rust-dev mailing list [email protected] https://mail.mozilla.org/listinfo/rust-dev
