Type operators
Table of contents
Overview
Carbon provides the following operators to transform or produce types:
constas a prefix unary operator produces aconst-qualified type.*as a postfix unary operator produces a pointer type to some other type.typeof(x)produces the static type of the expressionx.
The pointer type operator is also covered as one of the pointer operators.
Details
The semantic details of both const-qualified types and pointer types are provided as part of the values design:
The syntax of these operators tries to mimic the most common appearance of const types and pointer types in C++.
typeof
We provisionally define typeof(x) to give the static type of the expression x without any runtime evaluation of x.
typeof(x) has no runtime side effects, and produces a compile-time result. This may involve compile-time evaluation, but all runtime effects from that evaluation are discarded before code generation, as if the code is in an if (false) block. For example:
musteval fn P(T: type) -> type {
return T*;
}
fn F[template T: type](ref x: T) -> P(T) {
x += 1;
return &x;
}
fn Call() {
var y: i32 = 0;
// Involves the compile-time evaluation of `P(i32)`,
// and forming a specific instance of `F`. However,
// `F(ref y)` is not called at runtime.
StaticAssert(typeof(F(ref y)) == i32*);
Assert(y == 0);
}
Precedence
Because these are type operators, they don’t have many precedence relationship with non-type operators.
constbinds more tightly than*and can appear unparenthesized in an operand, despite being both a unary operator and having whitespace separating it.- This allows the syntax of a pointer to a
const i32to beconst i32*, which is intended to be familiar to C++ developers. - Forming a
constpointer type requires parentheses:const (i32*).
- This allows the syntax of a pointer to a
- All type operators bind more tightly than
asso they can be used in its type operand.- This also allows a desirable transitive precedence with
if:if condition then T* else U*.
- This also allows a desirable transitive precedence with
Alternatives considered
- Alternative pointer syntaxes
- Alternative syntaxes for locals
- Make
consta postfix rather than prefix operator