Files
carbon-lang/toolchain/check/literal.cpp
T
Jon Ross-Perkins 4923445e3a Drop Singleton from ErrorInst::SingletonInstId and similar (#5304)
We frequently want to operate on singletons. Per discussion, drop
`Singleton` to make the code shorter.

This started off as wanting to write `inst_id.is_error()`, but the
dependency relationship between ids.h and singleton_insts.h would
require some kind of delayed evaluation to allow the implementation to
remain in headers (which I suspect is helpful to have for inlining). I
could have added something like `IsErrorInst`, forward declared in ids.h
and defined in singleton_insts.h (which would always be included by
typed_insts.h), but the template approach felt like a decent balance
between (a) removing the boilerplate `::SingletonInstId`, (b)
understandability, (c) still visually mirroring if we immediately return
a singleton, and (d) flexibility for more than just `ErrorInst`. But TBH
I'd probably still have written `is_error()` if it didn't require
addressing the cross-header cycle.

Then I tried `SemIR::InstId::Is<SemIR::ErrorInst>`, which generally
worked with types but generated the complaint that it didn't shorten
*all* singleton uses. So pulling back on `::Is`, and instead just
dropping `Singleton`.
2025-04-15 22:40:29 +00:00

39 lines
1.4 KiB
C++

// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "toolchain/check/literal.h"
#include "toolchain/check/call.h"
#include "toolchain/check/context.h"
#include "toolchain/check/convert.h"
#include "toolchain/check/name_lookup.h"
#include "toolchain/check/type.h"
namespace Carbon::Check {
auto MakeIntLiteral(Context& context, Parse::NodeId node_id, IntId int_id)
-> SemIR::InstId {
return AddInst<SemIR::IntValue>(
context, node_id,
{.type_id = GetSingletonType(context, SemIR::IntLiteralType::InstId),
.int_id = int_id});
}
auto MakeIntTypeLiteral(Context& context, Parse::NodeId node_id,
SemIR::IntKind int_kind, IntId size_id)
-> SemIR::InstId {
auto width_id = MakeIntLiteral(context, node_id, size_id);
auto fn_inst_id = LookupNameInCore(
context, node_id, int_kind == SemIR::IntKind::Signed ? "Int" : "UInt");
return PerformCall(context, node_id, fn_inst_id, {width_id});
}
auto MakeIntType(Context& context, Parse::NodeId node_id,
SemIR::IntKind int_kind, IntId size_id) -> SemIR::TypeId {
auto type_inst_id = MakeIntTypeLiteral(context, node_id, int_kind, size_id);
return ExprAsType(context, node_id, type_inst_id).type_id;
}
} // namespace Carbon::Check