Skip to content

Commit

Permalink
fix: c/c++ directive and preprocessor tokenize (#26)
Browse files Browse the repository at this point in the history
  • Loading branch information
blurfx authored Nov 25, 2023
1 parent 5f3772b commit 65b99bf
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
6 changes: 6 additions & 0 deletions .changeset/rare-bees-talk.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@calor/core': patch
'@calor/highlighter': patch
---

Fix C/C++ directive and preprocessor tokenize rule"
9 changes: 9 additions & 0 deletions packages/core/src/rules/cpp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@ const cppRules: ParseRule[] = [
kind: 'comment',
pattern: /(\/\/.*\n?)|\/\*[^]*?\*\//g,
},
{
kind: 'keyword',
pattern: /(#\s*include|ifdef|ifndef|elidef|elifndef)(\s*)(<.*>|".*")/g,
matchHints: ['keyword', 'plain', 'string'],
},
{
kind: 'keyword',
pattern: /(#\s*(?:define|if|elif|else|endif|import|error|line))\b/g,
},
{
kind: 'keyword',
pattern:
Expand Down
9 changes: 7 additions & 2 deletions packages/core/tests/tokenizer/c-cpp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,8 @@ describe('c/cpp tokenizer', () => {
it('can tokenize string', () => {
const tokens = tokenize(
`
#include <iostream>
int main() {
std::cout << "Hello, World!";
return 0;
}
`,
cppRules,
Expand All @@ -124,4 +122,11 @@ describe('c/cpp tokenizer', () => {
expect(stringTokens.length).toBe(1);
expect(stringTokens[0].value).toBe('"Hello, World!"');
});

it('include directive', () => {
const tokens = tokenize('#include <iostream>', cppRules);
const includeTokens = tokens.filter((token) => token.kind === 'keyword');
expect(includeTokens.length).toBe(1);
expect(includeTokens[0].value).toBe('#include');
});
});

0 comments on commit 65b99bf

Please sign in to comment.