Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 51 additions & 9 deletions grammar.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ const BUILTIN_TYPE_KEYWORDS = [
'void',
];

const preprocIf = C.preprocIf;
const preprocIf = cppPreprocIf;
const preprocessor = C.preprocessor;

// oxlint-disable-next-line unicorn/prefer-module -- This package is CommonJS, so tree-sitter loads grammar.js as CommonJS.
Expand Down Expand Up @@ -529,10 +529,25 @@ module.exports = C.assertMacroCaseIdentifierSpellsNoKeyword(
reserved: { global: () => [], marker: ($) => [$._typedef_primitive_type, $._non_pack_builtin_type] },

rules: {
...inheritedPreprocIfdefRules(),

// C++ ([lex.name]) admits only XID characters, while the C grammar also admits C17 Annex D ranges such as U+200B.
identifier: () =>
/(\p{XID_Start}|\$|_|\\u[0-9A-Fa-f]{4}|\\U[0-9A-Fa-f]{8})(\p{XID_Continue}|\$|\\u[0-9A-Fa-f]{4}|\\U[0-9A-Fa-f]{8})*/u,

_preproc_ifdef_name: ($) => choice($.identifier, alias($._spliced_preproc_identifier, $.identifier)),

_spliced_preproc_identifier: () =>
token(
seq(
/\p{XID_Start}|\$|_|\\u[0-9A-Fa-f]{4}|\\U[0-9A-Fa-f]{8}/u,
repeat(/\p{XID_Continue}|\$|\\u[0-9A-Fa-f]{4}|\\U[0-9A-Fa-f]{8}/u),
repeat1(
seq(repeat1(/\\(\r\n?|\n\r?)/), repeat1(/\p{XID_Continue}|\$|\\u[0-9A-Fa-f]{4}|\\U[0-9A-Fa-f]{8}/u))
)
)
),

_top_level_expression_statement: ($, original = missingOriginalRule()) =>
choice(
original,
Expand Down Expand Up @@ -681,8 +696,6 @@ module.exports = C.assertMacroCaseIdentifierSpellsNoKeyword(
)
),

// Unlike the inherited conditionals, each directive line must end before the branch, so that a seam written on the
// directive line stays an error.
preproc_if_in_if_block: () =>
prec(
1,
Expand Down Expand Up @@ -734,15 +747,15 @@ module.exports = C.assertMacroCaseIdentifierSpellsNoKeyword(
// `else_continuation`: one of an enclosing `if` whose block the `try` starts, or one in a disabled branch.
_split_try_statement: () => splitTryStatement('_try_opening_ifdef'),

// In the block of an `if` statement the `#ifdef` line of the opening ends as that of `preproc_ifdef_in_if_block`
// does, which reads the same directive. Outranks `_split_try_statement` as `_if_block_item` does `_block_item`.
// In the block of an `if` statement the opening reads `_preproc_newline` as `preproc_ifdef_in_if_block` does,
// which shares its `#ifdef` states. Outranks `_split_try_statement` as `_if_block_item` does `_block_item`.
_split_try_statement_in_if_block: () => prec(1, splitTryStatement('_try_opening_ifdef_in_if_block')),

_try_opening_if: () => seamIf(tryOpening()),
_try_opening_ifdef: () =>
_try_opening_ifdef: ($) =>
seq(
choice(preprocessor('ifdef'), preprocessor('ifndef')),
field('name', sym('identifier')),
field('name', $._preproc_ifdef_name),
tryOpening(),
preprocessor('endif')
),
Expand Down Expand Up @@ -3727,7 +3740,7 @@ function initializerIf(body) {
function initializerIfdef(body) {
return seq(
choice(preprocessor('ifdef'), preprocessor('ifndef')),
field('name', sym('identifier')),
field('name', sym('_preproc_ifdef_name')),
initializerDirectiveNewline(),
body,
preprocessor('endif'),
Expand All @@ -3749,7 +3762,7 @@ function initializerElif(body) {
function initializerElifdef(body) {
return seq(
choice(preprocessor('elifdef'), preprocessor('elifndef')),
field('name', sym('identifier')),
field('name', sym('_preproc_ifdef_name')),
initializerDirectiveNewline(),
body
);
Expand Down Expand Up @@ -4061,3 +4074,32 @@ function commaSep(rule) {
function commaSep1(rule) {
return seq(rule, repeat(seq(',', rule)));
}

/**
* @param {string} suffix
* @param {Parameters<typeof C.preprocIf>[1]} content
* @param {number} [precedence]
* @param {boolean} [repeatContent]
* @returns {Record<string, ($: GrammarSymbols<string>) => Rule>}
*/
function cppPreprocIf(suffix, content, precedence = 0, repeatContent = true) {
const generated = /** @type {Record<string, ($: GrammarSymbols<string>) => Rule>} */ (
C.preprocIf(suffix, content, precedence, repeatContent)
);
for (const prefix of ['preproc_ifdef', 'preproc_elifdef']) {
const original = generated[prefix + suffix];
if (original) generated[prefix + suffix] = ($) => replaceRuleField(original($), 'name', sym('_preproc_ifdef_name'));
}
return generated;
}

function inheritedPreprocIfdefRules() {
return Object.fromEntries(
Object.entries(C.grammar.rules)
.filter(([name]) => /^(?:_(?:leading_)?marker_)?preproc_(?:ifdef|elifdef)/.test(name))
.map(([name, rule]) => [
name,
() => replaceRuleField(/** @type {Rule} */ (rule), 'name', sym('_preproc_ifdef_name')),
])
);
}
217 changes: 191 additions & 26 deletions src/cppTrivia.h
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#ifndef TREE_SITTER_CPP_TRIVIA_H_
#define TREE_SITTER_CPP_TRIVIA_H_

#include "conditionalMacro.h"
#include "emptyDirectives.h"
#include "pragma.h"

Expand Down Expand Up @@ -28,10 +29,21 @@ static inline bool at_eof(const TSLexer *lexer);
static bool has_plain_ascii_directive_word(const TSLexer *lexer);
static bool scan_cpp_extended_directive_word(TSLexer *lexer, CppDirectiveWord *out);
static bool skip_cpp_directive_prefix(TSLexer *lexer, bool *starts_with_ucn);
static bool skip_cpp_directive_comment(TSLexer *lexer);
static void scan_cpp_directive_tail(TSLexer *lexer, CppDirectiveWord *out, CppDirectiveScanState *scan, TSLexerPosition *prefix_end);
static bool scan_cpp_directive_backslash(TSLexer *lexer, bool continuation, bool *spliced);
static void accept_cpp_directive_character(TSLexer *lexer, CppDirectiveWord *out, CppDirectiveScanState *scan, int32_t c, bool first, TSLexerPosition *prefix_end);
static inline bool ascii_identifier_unit(uint32_t c, bool continuation);
static int peek_cpp_units_line_end(const char *units, uint32_t size, uint32_t i, uint32_t count);
static int peek_cpp_units_line_comment(const char *units, uint32_t size, uint32_t i, uint32_t count);
static bool scan_cpp_ifdef_word(TSLexer *lexer, char *word, unsigned capacity, bool *ascii, bool escaped);
static bool scan_cpp_ifdef_word_tail(TSLexer *lexer, char *word, unsigned capacity, unsigned *length, bool *ascii);
static void append_cpp_ifdef_character(TSLexer *lexer, char *word, unsigned capacity, unsigned *length, bool *ascii, bool spliced);
static bool scan_cpp_directive_line_end(EmptyDirectives *state, TSLexer *lexer, bool *had_pragma);
static bool scan_cpp_directive_pragma_args(TSLexer *lexer);
static bool skip_cpp_ifdef_trivia(TSLexer *lexer, bool allow_line_comment, bool *escaped);
static bool skip_cpp_inline_spacing(TSLexer *lexer, bool spaced_splices, bool allow_line_comment);
static bool skip_cpp_inline_comment(TSLexer *lexer, bool spaced_splices, bool allow_line_comment);
static bool skip_cpp_block_comment_body(TSLexer *lexer, bool spaced_splices);

/// Skips the trivia a lookahead crosses, null directives included, which end a line like the newline they contain.
/// Returns false at a `\\` or `/` that starts no trivia, setting `*failure` (when given) to its byte.
Expand Down Expand Up @@ -150,16 +162,8 @@ static bool scan_cpp_extended_directive_word(TSLexer *lexer, CppDirectiveWord *o
static bool skip_cpp_directive_prefix(TSLexer *lexer, bool *starts_with_ucn) {
*starts_with_ucn = false;
for (;;) {
int32_t c = lexer->lookahead;
if (directive_horizontal(c)) {
lexer->advance(lexer, false);
continue;
}
if (c == '/') {
if (!skip_cpp_directive_comment(lexer)) return false;
continue;
}
if (c != '\\') return true;
if (!skip_cpp_inline_spacing(lexer, true, false)) return false;
if (lexer->lookahead != '\\') return true;
bool spliced = false;
if (!scan_cpp_directive_backslash(lexer, false, &spliced)) return false;
if (!spliced) {
Expand All @@ -169,21 +173,6 @@ static bool skip_cpp_directive_prefix(TSLexer *lexer, bool *starts_with_ucn) {
}
}

static bool skip_cpp_directive_comment(TSLexer *lexer) {
lexer->advance(lexer, false);
if (!empty_directives_skip_splices(lexer, true) || lexer->lookahead != '*') return false;
lexer->advance(lexer, false);
bool star = false;
while (!pragma_eof(lexer)) {
int32_t c = lexer->lookahead;
lexer->advance(lexer, false);
if (c == '\\' && empty_directives_skip_line_splice(lexer, true)) continue;
if (star && c == '/') return true;
star = c == '*';
}
return false;
}

static void scan_cpp_directive_tail(TSLexer *lexer, CppDirectiveWord *out, CppDirectiveScanState *scan, TSLexerPosition *prefix_end) {
for (;;) {
int32_t c = lexer->lookahead;
Expand Down Expand Up @@ -225,4 +214,180 @@ static void accept_cpp_directive_character(TSLexer *lexer, CppDirectiveWord *out
if (scan->keyword_prefix) scan->trailing_splice = false;
}

static int peek_cpp_directive_line_end(const TSLexer *lexer) {
uint32_t count = 0, size = 0;
const char *units = lexer->peek_units(lexer, &count, &size);
return peek_cpp_units_line_end(units, size, 0, count);
}

static int peek_cpp_ifdef_header(const TSLexer *lexer) {
uint32_t count = 0, size = 0;
const char *units = lexer->peek_units(lexer, &count, &size);
uint32_t i = 0;
while (i < count && (directive_unit(units, size, i) == ' ' || directive_unit(units, size, i) == '\t')) i++;
if (!i || i >= count) return 0;
uint32_t first = directive_unit(units, size, i);
if (first == '\n' || first == '\r') return -1;
if (!ascii_identifier_unit(first, false)) return 0;
uint32_t start = i++;
while (i < count && ascii_identifier_unit(directive_unit(units, size, i), true)) i++;
if (i >= count) return 0;
uint32_t stop = directive_unit(units, size, i);
if (stop >= 0x80 || stop == '\\' || (i - start == 7 && directive_unit(units, size, start) == '_')) return 0;
return peek_cpp_units_line_end(units, size, i, count);
}

static inline bool ascii_identifier_unit(uint32_t c, bool continuation) {
if (c >= 0x80 || c == '\\') return false;
const uint64_t *table = continuation ? preproc_identifier_continue_ascii : preproc_identifier_start_ascii;
return ((table[c / 64] >> (c % 64)) & 1) != 0;
}

static int peek_cpp_units_line_end(const char *units, uint32_t size, uint32_t i, uint32_t count) {
while (i < count && (directive_unit(units, size, i) == ' ' || directive_unit(units, size, i) == '\t')) i++;
if (i >= count) return 0;
uint32_t c = directive_unit(units, size, i);
if (c == '\n' || c == '\r') return 1;
if (c == '/') return peek_cpp_units_line_comment(units, size, i, count);
if (c >= 0x80 || c == '\v' || c == '\f' || c == '\\' || c == '_') return 0;
return -1;
}

static int peek_cpp_units_line_comment(const char *units, uint32_t size, uint32_t i, uint32_t count) {
if (i + 1 >= count || directive_unit(units, size, i + 1) != '/') return 0;
for (i += 2; i < count; i++) {
uint32_t c = directive_unit(units, size, i);
if (c == '\n') return 1;
if (c >= 0x80 || c == '\r' || c == '\\') return 0;
}
return 0;
}

static bool scan_cpp_ifdef_header(EmptyDirectives *state, TSLexer *lexer, bool *had_pragma) {
*had_pragma = false;
for (;;) {
bool escaped = false;
if (!skip_cpp_ifdef_trivia(lexer, false, &escaped)) return false;
char word[sizeof(pragma_word)] = {0};
bool ascii = false;
if (!scan_cpp_ifdef_word(lexer, word, sizeof(word) - 1, &ascii, escaped)) return false;
if (!ascii || strcmp(word, pragma_word) != 0 || !empty_directives_pragma_possible(state)) {
return scan_cpp_directive_line_end(state, lexer, had_pragma);
}
bool after_escaped = false;
if (!skip_cpp_ifdef_trivia(lexer, true, &after_escaped) || after_escaped) return false;
if (lexer->lookahead != '(') return scan_cpp_directive_line_end(state, lexer, had_pragma);
if (!scan_cpp_directive_pragma_args(lexer)) return false;
*had_pragma = true;
}
}

static bool scan_cpp_ifdef_word(TSLexer *lexer, char *word, unsigned capacity, bool *ascii, bool escaped) {
unsigned length = 0;
*ascii = !escaped;
if (escaped) {
if (!scan_macro_name_ucn(lexer)) return false;
} else if (lexer->lookahead == '\\' || !preproc_identifier_character(lexer->lookahead, false)) {
return false;
} else {
append_cpp_ifdef_character(lexer, word, capacity, &length, ascii, false);
}
if (!scan_cpp_ifdef_word_tail(lexer, word, capacity, &length, ascii)) return false;
word[*ascii ? length : 0] = '\0';
return true;
}

static bool scan_cpp_ifdef_word_tail(TSLexer *lexer, char *word, unsigned capacity, unsigned *length, bool *ascii) {
bool spliced = false;
for (;;) {
int32_t c = lexer->lookahead;
if (c != '\\') {
if (!preproc_identifier_character(c, true)) return true;
append_cpp_ifdef_character(lexer, word, capacity, length, ascii, spliced);
continue;
}
lexer->advance(lexer, false);
if (scan_preproc_newline(lexer, false)) {
spliced = true;
continue;
}
*ascii = false;
if (!scan_macro_name_ucn(lexer)) return false;
}
}

static void append_cpp_ifdef_character(TSLexer *lexer, char *word, unsigned capacity, unsigned *length, bool *ascii, bool spliced) {
int32_t c = lexer->lookahead;
if (!spliced && *ascii && c < 0x80 && *length < capacity) word[(*length)++] = (char)c;
else *ascii = false;
lexer->advance(lexer, false);
}

static bool scan_cpp_directive_line_end(EmptyDirectives *state, TSLexer *lexer, bool *had_pragma) {
for (;;) {
bool escaped = false;
if (!skip_cpp_ifdef_trivia(lexer, true, &escaped) || escaped) return false;
int32_t c = lexer->lookahead;
if (c == '\n' || c == '\r' || at_eof(lexer)) return true;
if (c != '_' || !empty_directives_pragma_possible(state) || !scan_pragma_word(lexer)) return false;
if (!skip_cpp_ifdef_trivia(lexer, false, &escaped) || escaped || lexer->lookahead != '(') return false;
if (!scan_cpp_directive_pragma_args(lexer)) return false;
*had_pragma = true;
}
}

static bool scan_cpp_directive_pragma_args(TSLexer *lexer) {
lexer->advance(lexer, false);
bool escaped = false;
if (!skip_cpp_ifdef_trivia(lexer, false, &escaped) || escaped || !scan_pragma_argument(lexer)) return false;
if (!skip_cpp_ifdef_trivia(lexer, false, &escaped) || escaped || lexer->lookahead != ')') return false;
lexer->advance(lexer, false);
return true;
}

static bool skip_cpp_ifdef_trivia(TSLexer *lexer, bool allow_line_comment, bool *escaped) {
*escaped = false;
for (;;) {
if (!skip_cpp_inline_spacing(lexer, false, allow_line_comment)) return false;
if (lexer->lookahead != '\\') return true;
lexer->advance(lexer, false);
if (!scan_preproc_newline(lexer, false)) {
*escaped = true;
return true;
}
}
}

static bool skip_cpp_inline_spacing(TSLexer *lexer, bool spaced_splices, bool allow_line_comment) {
for (;;) {
if (directive_horizontal(lexer->lookahead)) {
lexer->advance(lexer, false);
} else if (lexer->lookahead == '/') {
if (!skip_cpp_inline_comment(lexer, spaced_splices, allow_line_comment)) return false;
} else {
return true;
}
}
}

static bool skip_cpp_inline_comment(TSLexer *lexer, bool spaced_splices, bool allow_line_comment) {
lexer->advance(lexer, false);
if (!empty_directives_skip_splices(lexer, spaced_splices)) return false;
if (lexer->lookahead == '*') return skip_cpp_block_comment_body(lexer, spaced_splices);
return allow_line_comment && lexer->lookahead == '/' && scan_preproc_line_comment(lexer);
}

static bool skip_cpp_block_comment_body(TSLexer *lexer, bool spaced_splices) {
lexer->advance(lexer, false);
bool star = false;
while (!pragma_eof(lexer)) {
int32_t c = lexer->lookahead;
lexer->advance(lexer, false);
if (c == '\\' && empty_directives_skip_line_splice(lexer, spaced_splices)) continue;
if (star && c == '/') return true;
star = c == '*';
}
return false;
}

#endif
Loading
Loading