use std::fmt;
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum Family {
C,
Cpp,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
pub enum Standard {
C89,
C99,
C11,
C17,
C23,
Cpp11,
Cpp14,
Cpp17,
Cpp20,
Cpp23,
}
pub const STANDARDS: [Standard; 10] = [
Standard::C89,
Standard::C99,
Standard::C11,
Standard::C17,
Standard::C23,
Standard::Cpp11,
Standard::Cpp14,
Standard::Cpp17,
Standard::Cpp20,
Standard::Cpp23,
];
impl Standard {
pub fn family(self) -> Family {
match self {
Standard::C89 | Standard::C99 | Standard::C11 | Standard::C17 | Standard::C23 => {
Family::C
}
Standard::Cpp11
| Standard::Cpp14
| Standard::Cpp17
| Standard::Cpp20
| Standard::Cpp23 => Family::Cpp,
}
}
pub fn rank(self) -> u8 {
match self {
Standard::C89 | Standard::Cpp11 => 0,
Standard::C99 | Standard::Cpp14 => 1,
Standard::C11 | Standard::Cpp17 => 2,
Standard::C17 | Standard::Cpp20 => 3,
Standard::C23 | Standard::Cpp23 => 4,
}
}
pub const fn bit(self) -> u64 {
1 << (self as u32)
}
pub const fn covered_by_mask(self) -> u64 {
let (base, rank) = match self {
Standard::C89 => (0u32, 0u32),
Standard::C99 => (0, 1),
Standard::C11 => (0, 2),
Standard::C17 => (0, 3),
Standard::C23 => (0, 4),
Standard::Cpp11 => (5, 0),
Standard::Cpp14 => (5, 1),
Standard::Cpp17 => (5, 2),
Standard::Cpp20 => (5, 3),
Standard::Cpp23 => (5, 4),
};
(((1u64 << (5 - rank)) - 1) << (base + rank)) & 0b11111_11111
}
pub const fn covers_mask(self) -> u64 {
let (base, rank) = match self {
Standard::C89 => (0u32, 0u32),
Standard::C99 => (0, 1),
Standard::C11 => (0, 2),
Standard::C17 => (0, 3),
Standard::C23 => (0, 4),
Standard::Cpp11 => (5, 0),
Standard::Cpp14 => (5, 1),
Standard::Cpp17 => (5, 2),
Standard::Cpp20 => (5, 3),
Standard::Cpp23 => (5, 4),
};
((1u64 << (rank + 1)) - 1) << base
}
pub fn covers(self, needed: Standard) -> bool {
self.family() == needed.family() && self.rank() >= needed.rank()
}
}
impl fmt::Display for Standard {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Standard::C89 => "c89",
Standard::C99 => "c99",
Standard::C11 => "c11",
Standard::C17 => "c17",
Standard::C23 => "c23",
Standard::Cpp11 => "c++11",
Standard::Cpp14 => "c++14",
Standard::Cpp17 => "c++17",
Standard::Cpp20 => "c++20",
Standard::Cpp23 => "c++23",
})
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum Vendor {
Gnu,
Msvc,
Clang,
}
impl Vendor {
pub const fn bit(self) -> u64 {
1 << (10 + self as u32)
}
}
impl fmt::Display for Vendor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Vendor::Gnu => "gnu",
Vendor::Msvc => "msvc",
Vendor::Clang => "clang",
})
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Requirement {
Standard(Standard),
Vendor(Vendor),
AnyOf(&'static [Requirement]),
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum Feature {
RawStrings,
Auto,
Lambda,
RvalueReferences,
VariadicTemplates,
AliasTemplates,
Attributes,
StaticAssert,
AlignasCpp,
ThreadLocal,
GenericLambda,
VariableTemplates,
BinaryLiterals,
DigitSeparators,
StructuredBindings,
IfConstexpr,
FoldExpressions,
InlineVariables,
ClassTemplateArgumentDeduction,
Concepts,
Modules,
Coroutines,
DesignatedInitializers,
ThreeWayComparison,
UsingEnum,
Char8T,
Consteval,
Constinit,
DeducingThis,
IfConsteval,
MultidimensionalSubscript,
StaticOperator,
C89Declarations,
VariableLengthArrays,
LineComments,
LongLong,
Restrict,
InlineC,
BoolC,
FlexibleArrayMembers,
VariadicMacros,
CompoundLiterals,
GenericSelection,
Atomic,
StaticAssertC,
Alignas,
Noreturn,
AnonymousStructs,
ThreadLocalC,
C17NoNewSyntax,
AttributesC,
Nullptr,
Constexpr,
BitInt,
AutoC,
EnumeratorsWithAFixedType,
EmptyInitializer,
Elifdef,
StatementExpression,
LabelsAsValues,
ElvisOperator,
AsmBlock,
NestedFunction,
Typeof,
StructuredExceptionHandling,
Interface,
BlockLiteral,
RestrictGnu,
Int128,
}
impl Feature {
pub fn requirement(self) -> Requirement {
use Feature::*;
use Requirement::{AnyOf, Standard as S, Vendor as V};
match self {
Auto | Lambda | RvalueReferences | VariadicTemplates | AliasTemplates | Attributes
| StaticAssert | RawStrings | AlignasCpp | ThreadLocal => S(Standard::Cpp11),
GenericLambda | VariableTemplates => S(Standard::Cpp14),
BinaryLiterals | DigitSeparators => AnyOf(&[S(Standard::Cpp14), S(Standard::C23)]),
StructuredBindings
| IfConstexpr
| FoldExpressions
| InlineVariables
| ClassTemplateArgumentDeduction => S(Standard::Cpp17),
Concepts | Modules | Coroutines | ThreeWayComparison | UsingEnum | Char8T
| Consteval | Constinit => S(Standard::Cpp20),
DesignatedInitializers => AnyOf(&[S(Standard::C99), S(Standard::Cpp20)]),
DeducingThis | IfConsteval | MultidimensionalSubscript | StaticOperator => {
S(Standard::Cpp23)
}
C89Declarations => S(Standard::C89),
VariableLengthArrays => AnyOf(&[S(Standard::C99), V(Vendor::Gnu)]),
LineComments => AnyOf(&[S(Standard::C99), S(Standard::Cpp11)]),
LongLong | InlineC | BoolC | FlexibleArrayMembers | VariadicMacros
| CompoundLiterals => S(Standard::C99),
Restrict => AnyOf(&[S(Standard::C99), V(Vendor::Gnu)]),
GenericSelection | Atomic | StaticAssertC | Alignas | Noreturn | AnonymousStructs
| ThreadLocalC => S(Standard::C11),
C17NoNewSyntax => S(Standard::C17),
AttributesC | Nullptr | Constexpr => AnyOf(&[S(Standard::Cpp11), S(Standard::C23)]),
BitInt | AutoC | EnumeratorsWithAFixedType | EmptyInitializer | Elifdef => {
S(Standard::C23)
}
StatementExpression | ElvisOperator | AsmBlock | NestedFunction | LabelsAsValues => {
V(Vendor::Gnu)
}
RestrictGnu | Int128 => V(Vendor::Gnu),
Typeof => AnyOf(&[S(Standard::C23), V(Vendor::Gnu)]),
StructuredExceptionHandling | Interface => V(Vendor::Msvc),
BlockLiteral => V(Vendor::Clang),
}
}
pub fn name(self) -> &'static str {
use Feature::*;
match self {
Auto => "auto",
Lambda => "lambda",
RvalueReferences => "rvalue references",
VariadicTemplates => "variadic templates",
AliasTemplates => "alias templates",
Attributes => "[[attribute]]",
StaticAssert => "static_assert",
AlignasCpp => "alignas",
ThreadLocal => "thread_local",
GenericLambda => "generic lambda",
VariableTemplates => "variable templates",
BinaryLiterals => "binary literals",
DigitSeparators => "digit separators",
StructuredBindings => "structured bindings",
IfConstexpr => "if constexpr",
FoldExpressions => "fold expressions",
InlineVariables => "inline variables",
ClassTemplateArgumentDeduction => "class template argument deduction",
Concepts => "concepts",
Modules => "modules",
Coroutines => "coroutines",
DesignatedInitializers => "designated initializers",
ThreeWayComparison => "three-way comparison",
UsingEnum => "using enum",
Char8T => "char8_t",
Consteval => "consteval",
Constinit => "constinit",
DeducingThis => "deducing this",
IfConsteval => "if consteval",
MultidimensionalSubscript => "multidimensional subscript",
StaticOperator => "static operator",
C89Declarations => "C89 declarations",
VariableLengthArrays => "variable-length arrays",
LineComments => "// comments",
LongLong => "long long",
Restrict => "restrict",
InlineC => "inline",
BoolC => "_Bool",
FlexibleArrayMembers => "flexible array members",
VariadicMacros => "variadic macros",
CompoundLiterals => "compound literals",
GenericSelection => "_Generic",
Atomic => "_Atomic",
StaticAssertC => "_Static_assert",
Alignas => "_Alignas",
Noreturn => "_Noreturn",
AnonymousStructs => "anonymous structs",
ThreadLocalC => "_Thread_local",
C17NoNewSyntax => "C17's syntax",
AttributesC => "[[attribute]] in C",
Nullptr => "nullptr",
Constexpr => "constexpr",
BitInt => "_BitInt",
AutoC => "auto in C",
EnumeratorsWithAFixedType => "enum with a fixed underlying type",
EmptyInitializer => "empty initializer",
Elifdef => "#elifdef",
StatementExpression => "statement expression",
LabelsAsValues => "the address of a label",
ElvisOperator => "elvis operator",
AsmBlock => "asm block",
NestedFunction => "nested function",
Typeof => "typeof",
StructuredExceptionHandling => "__try/__except",
Interface => "__interface",
BlockLiteral => "block literal",
RestrictGnu => "__restrict",
RawStrings => "raw string literal",
Int128 => "__int128",
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
#[repr(transparent)]
pub struct LanguageConfig {
bits: u64,
}
impl LanguageConfig {
pub const fn new() -> Self {
Self { bits: 0 }
}
pub const fn cpp17() -> Self {
Self::new().with_standard(Standard::Cpp17)
}
pub const fn gnu_cpp17() -> Self {
Self::new()
.with_standard(Standard::Cpp17)
.with_vendor(Vendor::Gnu)
}
pub const fn c11() -> Self {
Self::new().with_standard(Standard::C11)
}
pub const fn c() -> Self {
Self::new()
.with_standard(Standard::C89)
.with_standard(Standard::C99)
.with_standard(Standard::C11)
.with_standard(Standard::C17)
.with_standard(Standard::C23)
.with_vendor(Vendor::Gnu)
}
pub const fn gnu_c89() -> Self {
Self::new()
.with_standard(Standard::C89)
.with_vendor(Vendor::Gnu)
}
pub const fn with_standard(self, standard: Standard) -> Self {
Self {
bits: self.bits | standard.bit(),
}
}
pub const fn with_all_vendors(self) -> Self {
Self {
bits: self.bits | Vendor::Gnu.bit() | Vendor::Msvc.bit() | Vendor::Clang.bit(),
}
}
pub const fn with_vendor(self, vendor: Vendor) -> Self {
Self {
bits: self.bits | vendor.bit(),
}
}
pub const fn bits(self) -> u64 {
self.bits
}
pub const fn from_bits(bits: u64) -> Self {
Self { bits }
}
pub fn family(self) -> Option<Family> {
let c = self
.standards()
.any(|standard| standard.family() == Family::C);
let cpp = self
.standards()
.any(|standard| standard.family() == Family::Cpp);
match (c, cpp) {
(true, false) => Some(Family::C),
(false, true) => Some(Family::Cpp),
_ => None,
}
}
pub fn standards(self) -> impl Iterator<Item = Standard> {
STANDARDS
.into_iter()
.filter(move |standard| self.bits & standard.bit() != 0)
}
pub fn vendors(self) -> impl Iterator<Item = Vendor> {
[Vendor::Gnu, Vendor::Msvc, Vendor::Clang]
.into_iter()
.filter(move |vendor| self.bits & vendor.bit() != 0)
}
pub fn support(self, feature: Feature) -> bool {
self.supports(feature.requirement())
}
pub fn support_all(self, features: &[Feature]) -> bool {
features.iter().all(|feature| self.support(*feature))
}
pub fn support_any(self, features: &[Feature]) -> bool {
features.iter().any(|feature| self.support(*feature))
}
fn supports(self, requirement: Requirement) -> bool {
match requirement {
Requirement::Standard(needed) => self.bits & needed.covered_by_mask() != 0,
Requirement::Vendor(vendor) => self.bits & vendor.bit() != 0,
Requirement::AnyOf(alternatives) => alternatives
.iter()
.any(|alternative| self.supports(*alternative)),
}
}
pub fn describe(self) -> String {
let suffix = match self.standards().max_by_key(|standard| standard.rank()) {
Some(Standard::C89) => "89",
Some(Standard::C99) => "99",
Some(Standard::C11) => "11",
Some(Standard::C17) => "17",
Some(Standard::C23) => "23",
Some(Standard::Cpp11) => "++11",
Some(Standard::Cpp14) => "++14",
Some(Standard::Cpp17) => "++17",
Some(Standard::Cpp20) => "++20",
Some(Standard::Cpp23) => "++23",
None => return "no-standard".to_string(),
};
let mut described = if self.bits & Vendor::Gnu.bit() != 0 {
format!("gnu{suffix}")
} else {
format!("c{suffix}")
};
for vendor in [Vendor::Msvc, Vendor::Clang] {
if self.bits & vendor.bit() != 0 {
described.push('+');
described.push_str(&vendor.to_string());
}
}
described
}
}
impl fmt::Debug for LanguageConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"LanguageConfig({}, {:#014b})",
self.describe(),
self.bits
)
}
}
impl fmt::Display for LanguageConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.describe())
}
}
impl LanguageConfig {
pub fn from_flag(flag: &str) -> Option<Self> {
let spelling = flag
.trim()
.strip_prefix("--std=")
.or_else(|| flag.trim().strip_prefix("-std="))
.unwrap_or_else(|| flag.trim());
Self::from_standard_spelling(spelling)
}
pub fn from_standard_spelling(spelling: &str) -> Option<Self> {
let spelling = spelling.trim().to_ascii_lowercase();
let (vendor, rest) = match spelling.strip_prefix("gnu") {
Some(rest) => (Some(Vendor::Gnu), rest),
None => match spelling.strip_prefix("clang") {
Some(rest) => (Some(Vendor::Clang), rest),
None => (None, spelling.as_str()),
},
};
let rest = match rest.strip_prefix("++") {
Some(version) => format!("c++{version}"),
None if vendor.is_some() => format!("c{rest}"),
None => rest.to_string(),
};
let standard = match rest.as_str() {
"c++11" | "c++0x" => Standard::Cpp11,
"c++14" | "c++1y" => Standard::Cpp14,
"c++17" | "c++1z" => Standard::Cpp17,
"c++20" | "c++2a" => Standard::Cpp20,
"c++23" | "c++2b" | "c++latest" => Standard::Cpp23,
"c89" | "c90" | "iso9899:1990" => Standard::C89,
"c99" | "c9x" | "iso9899:1999" => Standard::C99,
"c11" | "c1x" | "iso9899:2011" => Standard::C11,
"c17" | "c18" | "iso9899:2017" => Standard::C17,
"c23" | "c2x" | "iso9899:2024" => Standard::C23,
_ => return None,
};
let mut config = Self::new().with_standard(standard);
if let Some(vendor) = vendor {
config = config.with_vendor(vendor);
}
Some(config)
}
pub fn from_command_line<S: AsRef<str>>(
arguments: impl IntoIterator<Item = S>,
) -> Option<Self> {
let mut found: Option<Self> = None;
let mut iterator = arguments.into_iter();
while let Some(argument) = iterator.next() {
let argument = argument.as_ref();
if let Some(config) = Self::from_flag(argument) {
found = Some(config);
} else if argument == "-std" || argument == "--std" {
if let Some(config) = iterator
.next()
.and_then(|next| Self::from_flag(next.as_ref()))
{
found = Some(config);
}
}
}
found
}
pub fn from_language_level(level: crate::kind::CppLanguageLevel) -> Self {
use crate::kind::CppLanguageLevel;
let standard = match level {
CppLanguageLevel::Cpp11 => Standard::Cpp11,
CppLanguageLevel::Cpp14 => Standard::Cpp14,
CppLanguageLevel::Cpp17 | CppLanguageLevel::GnuCpp | CppLanguageLevel::MsvcCpp => {
Standard::Cpp17
}
CppLanguageLevel::Cpp20 => Standard::Cpp20,
CppLanguageLevel::Cpp23 => Standard::Cpp23,
};
let vendor = match level {
CppLanguageLevel::GnuCpp => Some(Vendor::Gnu),
CppLanguageLevel::MsvcCpp => Some(Vendor::Msvc),
_ => None,
};
let config = Self::new().with_standard(standard);
match vendor {
Some(vendor) => config.with_vendor(vendor),
None => config,
}
}
pub fn to_language_level(self) -> crate::kind::CppLanguageLevel {
use crate::kind::CppLanguageLevel;
match self.standards().max_by_key(|standard| standard.rank()) {
Some(Standard::Cpp11) => CppLanguageLevel::Cpp11,
Some(Standard::Cpp14) => CppLanguageLevel::Cpp14,
Some(Standard::Cpp20) => CppLanguageLevel::Cpp20,
Some(Standard::Cpp23) => CppLanguageLevel::Cpp23,
Some(Standard::Cpp17) | None => CppLanguageLevel::Cpp17,
Some(_) => CppLanguageLevel::Cpp17,
}
}
pub const fn permissive() -> Self {
Self {
bits: (1u64 << 13) - 1,
}
}
}