use crate::config::Style;
use crate::options::StyleOption;
use crate::roles::Roles;
use crate::tokens::Stream;
use cpp_parser::CppTokenKind;
pub fn between(stream: &Stream<'_>, index: usize, roles: &Roles, style: &Style) -> usize {
use CppTokenKind::*;
if index == 0 {
return 0;
}
let current = stream.tokens[index];
let previous = stream.tokens[index - 1];
let offset = current.start;
let declarator_after_a_template =
previous.kind == Greater && roles.is_template_angle(previous.start);
if stream.gaps[index].is_empty()
&& !declarator_after_a_template
&& is_operator_punctuation(previous.kind)
&& is_operator_punctuation(current.kind)
{
return 0;
}
if current.kind == Arrow || previous.kind == Arrow {
let before_arrow = if current.kind == Arrow {
index - 1
} else {
index - 2
};
if before_arrow < stream.tokens.len()
&& stream.tokens[before_arrow].kind == RightBrace
&& closes_a_requirement_block(stream, before_arrow)
{
return 1;
}
if matches!(
stream.tokens[before_arrow].text,
"noexcept" | "const" | "mutable" | "override" | "final" | "constexpr"
) {
return 1;
}
if before_arrow < stream.tokens.len() && stream.tokens[before_arrow].kind == RightParen {
let mut depth = 0isize;
let mut opener: Option<usize> = Option::None;
for cursor in (0..before_arrow).rev() {
match stream.tokens[cursor].kind {
RightParen => depth += 1,
LeftParen => {
if depth == 0 {
opener = Some(cursor);
break;
}
depth -= 1;
}
_ => {}
}
}
let after_a_lambda =
opener.is_some_and(|at| at > 0 && stream.tokens[at - 1].kind == RightBracket);
let after_a_declarator = opener.is_some_and(|at| {
at >= 2
&& stream.tokens[at - 1].kind == Identifier
&& matches!(
stream.tokens[at - 2].kind,
AutoKeyword
| VoidKeyword
| IntKeyword
| CharKeyword
| DoubleKeyword
| FloatKeyword
)
});
if after_a_lambda || after_a_declarator {
return 1;
}
}
}
if previous.kind == RightParen
&& !crate::layout::is_a_binary_operator(current.kind)
&& is_a_cast_expression(stream, index - 1)
{
return 0;
}
match current.kind {
Comma | Semicolon | RightParen | RightBracket | Dot | Arrow | DotStar | ArrowStar => {
return 0;
}
Scope => return 0,
_ => {}
}
match previous.kind {
LeftParen => {
return if style.text(StyleOption::SpacesInParens) == "Never" {
0
} else {
1
};
}
LeftBracket => {
return if style.flag(StyleOption::SpacesInSquareBrackets) {
1
} else {
0
};
}
Scope | Dot | Arrow | DotStar | ArrowStar => return 0,
Comma | Semicolon => return 1,
LogicalNot | Tilde => return 0,
_ => {}
}
if current.kind == Ellipsis {
return match previous.kind {
Comma | LeftParen => 1,
_ => 0,
};
}
if previous.kind == Ellipsis {
let after_a_pack_declaration = index >= 2
&& matches!(
stream.tokens[index - 2].kind,
CppTokenKind::TypenameKeyword | CppTokenKind::ClassKeyword
);
return usize::from(after_a_pack_declaration);
}
if roles.is_template_angle(offset) {
if previous.kind == TemplateKeyword {
return if style.flag(StyleOption::SpaceAfterTemplateKeyword) {
1
} else {
0
};
}
return 0;
}
if roles.is_template_angle(previous.start) && previous.kind == Less {
return 0;
}
if current.kind == Less && is_a_cast_keyword(previous.kind) {
return 0;
}
if previous.kind == Less && index >= 2 && is_a_cast_keyword(stream.tokens[index - 2].kind) {
return 0;
}
if current.kind == Greater && angle_follows_a_cast(stream, index) {
return 0;
}
if matches!(previous.kind, CppTokenKind::OperatorKeyword) {
return 0;
}
if current.kind == CppTokenKind::LeftParen
&& index >= 2
&& stream.tokens[index - 2].kind == CppTokenKind::OperatorKeyword
{
return 0;
}
if current.kind == LeftParen {
return if a_space_before_a_paren(previous.kind, previous.text, style) {
1
} else {
0
};
}
if current.kind == LeftBracket {
if matches!(
previous.kind,
StructKeyword | ClassKeyword | UnionKeyword | EnumKeyword | AutoKeyword
) {
return 1;
}
if previous.kind == Identifier
&& matches!(
previous.text,
"auto" | "struct" | "class" | "union" | "enum"
)
{
return 1;
}
return match previous.kind {
Assign | Equal | ReturnKeyword | Comma | LeftParen | LeftBrace => 1,
_ => 0,
};
}
if current.kind == LeftBrace {
if roles.block_brace.contains(&offset) || previous.kind == RightParen {
return 1;
}
return match previous.kind {
Assign | Comma | LeftParen | LeftBracket | ReturnKeyword | Equal | Colon => 1,
_ => {
if style.flag(StyleOption::SpaceBeforeCpp11BracedList) {
1
} else {
0
}
}
};
}
fn closes_a_declaration_body(stream: &crate::tokens::Stream<'_>, index: usize) -> bool {
let mut depth = 0isize;
let mut opener: Option<usize> = Option::None;
for cursor in (0..index).rev() {
match stream.tokens[cursor].kind {
CppTokenKind::RightBrace => depth += 1,
CppTokenKind::LeftBrace => {
if depth == 0 {
opener = Some(cursor);
break;
}
depth -= 1;
}
_ => {}
}
}
let Some(opener) = opener else {
return false;
};
let mut cursor = opener;
while cursor > 0 {
cursor -= 1;
match stream.tokens[cursor].kind {
CppTokenKind::ClassKeyword
| CppTokenKind::StructKeyword
| CppTokenKind::EnumKeyword
| CppTokenKind::UnionKeyword => return true,
CppTokenKind::Semicolon | CppTokenKind::LeftBrace | CppTokenKind::RightBrace => {
return false;
}
_ => {}
}
}
false
}
if current.kind == RightBrace {
let requirement_close = closes_a_requirement_block(stream, index);
if previous.kind != LeftBrace
&& (roles.block_brace.contains(&offset)
|| closes_a_declaration_body(stream, index)
|| requirement_close)
{
return 1;
}
return 0;
}
if previous.kind == LeftBrace {
let body = index >= 2 && stream.tokens[index - 2].kind == CppTokenKind::RightParen;
let requirement = is_a_requirement_block(stream, index - 1);
if (roles.block_brace.contains(&previous.start) || body || requirement)
&& current.kind != RightBrace
{
return 1;
}
return 0;
}
if matches!(
current.kind,
CppTokenKind::PlusPlus | CppTokenKind::MinusMinus
) && is_a_value(previous.kind)
{
return 0;
}
if matches!(
previous.kind,
CppTokenKind::PlusPlus | CppTokenKind::MinusMinus
) && !is_a_value(previous_before_previous(stream, index))
{
return 0;
}
if current.kind == CppTokenKind::Ellipsis && is_a_value(previous.kind) {
return 0;
}
if previous.kind == CppTokenKind::LogicalAnd && current.text == "requires" {
return 1;
}
let after_a_template = previous.kind == Greater && roles.is_template_angle(previous.start);
let mark_after_a_template = index >= 2
&& stream.tokens[index - 2].kind == Greater
&& roles.is_template_angle(stream.tokens[index - 2].start);
if is_a_mark(current.kind) && (roles.is_declarator(offset) || after_a_template) {
return match style.text(StyleOption::PointerAlignment) {
"Left" => 0,
"Middle" => 1,
_ => 1,
};
}
if is_a_mark(previous.kind) && (roles.is_declarator(previous.start) || mark_after_a_template) {
return match style.text(StyleOption::PointerAlignment) {
"Left" => 1,
"Middle" => 1,
_ => 0,
};
}
if is_a_binary_operator(current.kind) {
if is_prefix_operator(stream, index, roles) {
return 1;
}
return 1;
}
if is_a_binary_operator(previous.kind) {
if is_prefix_operator(stream, index - 1, roles) {
return 0;
}
return 1;
}
if current.kind == Question || previous.kind == Question {
return 1;
}
if current.kind == Colon {
if is_a_label_colon(stream, index) {
return 0;
}
if in_a_for_head(stream, index) {
return if style.flag(StyleOption::SpaceBeforeRangeBasedForLoopColon) {
1
} else {
0
};
}
return 1;
}
if previous.kind == Colon {
return 1;
}
1
}
fn is_a_value(kind: CppTokenKind) -> bool {
use CppTokenKind::*;
matches!(
kind,
Identifier
| IntegerLiteral
| FloatingLiteral
| CharLiteral
| StringLiteral
| NullptrLiteral
| ThisKeyword
| RightParen
| RightBracket
)
}
fn is_operator_punctuation(kind: CppTokenKind) -> bool {
use CppTokenKind::*;
matches!(
kind,
Assign
| Equal
| NotEqual
| Less
| Greater
| LessEqual
| GreaterEqual
| Plus
| Minus
| Star
| Slash
| Percent
| Ampersand
| Pipe
| Caret
| Tilde
| LogicalAnd
| LogicalOr
| LogicalNot
| Question
| Colon
| LeftShift
| RightShift
| Spaceship
| PlusAssign
| MinusAssign
| StarAssign
| SlashAssign
| PercentAssign
| AmpersandAssign
| PipeAssign
| CaretAssign
| LeftShiftAssign
| RightShiftAssign
)
}
fn is_a_mark(kind: CppTokenKind) -> bool {
matches!(
kind,
CppTokenKind::Star | CppTokenKind::Ampersand | CppTokenKind::LogicalAnd
)
}
fn is_a_requirement_block(stream: &Stream<'_>, open: usize) -> bool {
if stream
.tokens
.get(open)
.is_none_or(|token| token.kind != CppTokenKind::LeftBrace)
{
return false;
}
let mut depth = 0isize;
for cursor in open..stream.tokens.len() {
match stream.tokens[cursor].kind {
CppTokenKind::LeftBrace => depth += 1,
CppTokenKind::RightBrace => {
depth -= 1;
if depth == 0 {
return stream
.tokens
.get(cursor + 1)
.is_some_and(|token| token.kind == CppTokenKind::Arrow);
}
}
_ => {}
}
}
false
}
fn closes_a_requirement_block(stream: &Stream<'_>, close: usize) -> bool {
let mut depth = 0isize;
let mut opener: Option<usize> = Option::None;
for cursor in (0..close).rev() {
match stream.tokens[cursor].kind {
CppTokenKind::RightBrace => depth += 1,
CppTokenKind::LeftBrace => {
if depth == 0 {
opener = Some(cursor);
break;
}
depth -= 1;
}
_ => {}
}
}
opener.is_some_and(|open| is_a_requirement_block(stream, open))
}
fn is_a_cast_expression(stream: &Stream<'_>, close: usize) -> bool {
let mut depth = 0isize;
let mut opener: Option<usize> = Option::None;
for cursor in (0..close).rev() {
match stream.tokens[cursor].kind {
CppTokenKind::RightParen => depth += 1,
CppTokenKind::LeftParen => {
if depth == 0 {
opener = Some(cursor);
break;
}
depth -= 1;
}
_ => {}
}
}
let Some(opener) = opener else {
return false;
};
let inside = &stream.tokens[opener + 1..close];
!inside.is_empty()
&& inside.iter().all(|token| {
matches!(
token.kind,
CppTokenKind::VoidKeyword
| CppTokenKind::IntKeyword
| CppTokenKind::CharKeyword
| CppTokenKind::FloatKeyword
| CppTokenKind::DoubleKeyword
| CppTokenKind::BoolLiteral
| CppTokenKind::LongKeyword
| CppTokenKind::ShortKeyword
| CppTokenKind::UnsignedKeyword
| CppTokenKind::SignedKeyword
| CppTokenKind::Star
| CppTokenKind::Ampersand
| CppTokenKind::ConstKeyword
)
})
}
fn a_space_before_a_paren(previous: CppTokenKind, previous_text: &str, style: &Style) -> bool {
use CppTokenKind::*;
if matches!(
previous_text,
"static_assert"
| "_Static_assert"
| "alignas"
| "alignof"
| "decltype"
| "sizeof"
| "noexcept"
| "typeid"
| "requires"
) {
return false;
}
match style.text(StyleOption::SpaceBeforeParens) {
"Always" => true,
"Never" => false,
_ => {
if matches!(
previous,
IfKeyword
| ForKeyword
| WhileKeyword
| SwitchKeyword
| CatchKeyword
| DoKeyword
| ReturnKeyword
) {
true
} else {
let a_call = matches!(
previous,
Identifier
| RightParen
| RightBracket
| Greater
| Scope
| ThisKeyword
| OperatorKeyword
);
let a_type = matches!(
previous,
BoolLiteral
| IntKeyword
| CharKeyword
| LongKeyword
| ShortKeyword
| DoubleKeyword
| FloatKeyword
| VoidKeyword
| UnsignedKeyword
| SignedKeyword
| AutoKeyword
| SizeofKeyword
| AlignofKeyword
| DecltypeKeyword
| TypeidKeyword
| NoexceptKeyword
);
!(a_call || a_type)
}
}
}
}
fn previous_before_previous(stream: &Stream<'_>, index: usize) -> CppTokenKind {
if index >= 2 {
stream.tokens[index - 2].kind
} else {
CppTokenKind::None
}
}
fn is_a_binary_operator(kind: CppTokenKind) -> bool {
use CppTokenKind::*;
matches!(
kind,
Assign
| PlusAssign
| MinusAssign
| StarAssign
| SlashAssign
| PercentAssign
| AmpersandAssign
| PipeAssign
| CaretAssign
| LeftShiftAssign
| RightShiftAssign
| Equal
| NotEqual
| Less
| LessEqual
| Greater
| GreaterEqual
| Spaceship
| LogicalAnd
| LogicalOr
| Ampersand
| Pipe
| Caret
| LeftShift
| RightShift
| Plus
| Minus
| Star
| Slash
| Percent
)
}
fn is_prefix_operator(stream: &Stream<'_>, index: usize, roles: &Roles) -> bool {
use CppTokenKind::*;
let token = stream.tokens[index];
if !matches!(
token.kind,
Plus | Minus | Star | Ampersand | LogicalNot | Tilde
) {
return false;
}
if roles.is_declarator(token.start) {
return false;
}
let Some(previous) = stream.tokens.get(index.wrapping_sub(1)) else {
return true;
};
matches!(
previous.kind,
LeftParen
| LeftBracket
| LeftBrace
| Comma
| Semicolon
| Assign
| Colon
| Question
| LogicalAnd
| LogicalOr
| LogicalNot
| ReturnKeyword
| CaseKeyword
| Equal
| NotEqual
| Less
| Greater
| LessEqual
| GreaterEqual
| Plus
| Minus
| Star
| Slash
| Percent
| Pipe
| Caret
| Tilde
| PlusAssign | MinusAssign | StarAssign | SlashAssign | PercentAssign
)
}
fn is_a_label_colon(stream: &Stream<'_>, index: usize) -> bool {
use CppTokenKind::*;
let Some(previous) = stream.tokens.get(index.wrapping_sub(1)) else {
return false;
};
if matches!(
previous.kind,
PublicKeyword | PrivateKeyword | ProtectedKeyword | DefaultKeyword
) {
return true;
}
if previous.kind == Identifier
&& stream
.gaps
.get(index - 1)
.is_some_and(|gap| gap.newlines > 0)
{
return true;
}
let mut cursor = index;
while cursor > 0 {
cursor -= 1;
match stream.tokens[cursor].kind {
CaseKeyword => return true,
Semicolon | LeftBrace | RightBrace | LeftParen | RightParen => return false,
_ => {}
}
}
false
}
fn in_a_for_head(stream: &Stream<'_>, index: usize) -> bool {
let mut cursor = index;
let mut depth = 0usize;
while cursor > 0 {
cursor -= 1;
match stream.tokens[cursor].kind {
CppTokenKind::RightParen => depth += 1,
CppTokenKind::LeftParen => {
if depth == 0 {
return cursor > 0
&& stream.tokens[cursor - 1].kind == CppTokenKind::ForKeyword;
}
depth -= 1;
}
CppTokenKind::Semicolon | CppTokenKind::LeftBrace | CppTokenKind::RightBrace => {
return false;
}
_ => {}
}
}
false
}
fn is_a_cast_keyword(kind: CppTokenKind) -> bool {
use CppTokenKind::*;
matches!(
kind,
StaticCastKeyword | DynamicCastKeyword | ConstCastKeyword | ReinterpretCastKeyword
)
}
fn angle_follows_a_cast(stream: &Stream<'_>, index: usize) -> bool {
let mut depth = 0usize;
let mut cursor = index;
while cursor > 0 {
cursor -= 1;
match stream.tokens[cursor].kind {
CppTokenKind::Greater => depth += 1,
CppTokenKind::Less => {
if depth == 0 {
return cursor > 0 && is_a_cast_keyword(stream.tokens[cursor - 1].kind);
}
depth -= 1;
}
CppTokenKind::Semicolon | CppTokenKind::LeftBrace => return false,
_ => {}
}
}
false
}
pub fn text(stream: &Stream<'_>, index: usize, roles: &Roles, style: &Style) -> String {
" ".repeat(between(stream, index, roles, style))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::Style;
use crate::roles;
use crate::tokens;
fn spaces(source: &str, index: usize) -> usize {
let stream = tokens::stream(source);
let roles = roles::of(source);
between(&stream, index, &roles, &Style::default_style())
}
#[test]
fn a_comma_has_nothing_before_it_and_one_space_after() {
assert_eq!(spaces("f(a,b);", 3), 0, "before the comma");
assert_eq!(spaces("f(a,b);", 4), 1, "after the comma");
}
#[test]
fn a_call_is_glued_to_its_parenthesis_and_a_condition_is_not() {
assert_eq!(spaces("f (a);", 1), 0);
assert_eq!(spaces("if (a) {}", 1), 1);
}
#[test]
fn a_template_argument_list_has_no_spaces_inside_it() {
assert_eq!(spaces("std::vector < int > v;", 3), 0);
assert_eq!(spaces("std::vector < int > v;", 4), 0);
}
#[test]
fn a_declarator_star_follows_pointer_alignment() {
assert_eq!(spaces("int * p;", 1), 1, "before the star");
assert_eq!(spaces("int * p;", 2), 0, "after the star");
}
#[test]
fn a_product_keeps_its_spaces() {
assert_eq!(spaces("int x = a * b;", 4), 1, "before the star");
assert_eq!(spaces("int x = a * b;", 5), 1, "after the star");
}
}