Skip to content

Commit

Permalink
fix formatting of block quotes with **/ closing characters
Browse files Browse the repository at this point in the history
  • Loading branch information
wylieconlon committed Jun 14, 2024
1 parent 7aee250 commit 5c37ecf
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 14 deletions.
34 changes: 20 additions & 14 deletions src/lexer/NestedComment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
import { RegExpLike } from './TokenizerEngine.js';

const START = /\/\*/uy; // matches: /*
const MIDDLE = /([^/*]|\*[^/]|\/[^*])+/uy; // matches text NOT containing /* or */
const END = /\*\//uy; // matches: */

/**
* An object mimicking a regular expression,
Expand All @@ -15,29 +13,37 @@ export class NestedComment implements RegExpLike {
public exec(input: string): string[] | null {
let result = '';
let match: string | null;
let nestLevel = 0;

if ((match = this.matchSection(START, input))) {
result += match;
nestLevel++;
} else {
return null;
}

while (nestLevel > 0) {
if ((match = this.matchSection(START, input))) {
result += match;
nestLevel++;
} else if ((match = this.matchSection(END, input))) {
result += match;
let nestLevel = 1;
// start at the last index, break if we find a closing */ that matches
for (let i = this.lastIndex; i < input.length; i++) {
if (input[i] === '*' && input[i + 1] === '/') {
nestLevel--;
} else if ((match = this.matchSection(MIDDLE, input))) {
result += match;
result += '*/';
i++;
if (nestLevel === 0) {
this.lastIndex = i;
return [result];
} else if (nestLevel < 0) {
return null;
}
} else if (input[i] === '/' && input[i + 1] === '*') {
nestLevel++;
result += '/*';
i++;
} else {
return null;
result += input[i];
}
}

if (nestLevel > 0) {
return null;
}
return [result];
}

Expand Down
6 changes: 6 additions & 0 deletions test/features/comments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,12 @@ export default function supportsComments(format: FormatFn, opts: CommentsConfig
`);
});

// Regression test for https://github.com/sql-formatter-org/sql-formatter/issues/747
it('handles block comments with /** and **/ patterns', () => {
const sql = `/** This is a block comment **/`;
expect(format(sql)).toBe(sql);
});

if (opts.hashComments) {
it('supports # line comment', () => {
const result = format('SELECT alpha # commment\nFROM beta');
Expand Down

0 comments on commit 5c37ecf

Please sign in to comment.