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
20 changes: 17 additions & 3 deletions src/main/jjtree/net/sf/jsqlparser/parser/JSqlParserCC.jjt
Original file line number Diff line number Diff line change
Expand Up @@ -6178,28 +6178,42 @@ TOKEN_MGR_DECLS : {
* Consumes the body of a block comment after the opening delimiter has been matched,
* honouring nesting, up to and including the outermost closing delimiter. Then backs
* up 2 characters so the MULTI_LINE_COMMENT rule matches the closing delimiter and
* terminates the MORE chain.
* terminates the MORE chain. If nesting runs past the end of the input and a closing
* delimiter was seen along the way, the comment is closed at the first one instead,
* which is how dialects that do not nest block comments read it.
*/
void consumeBlockCommentBody() {
int nesting = 1;
char prev = 0;
int read = 0;
int firstCloseEnd = -1;
try {
while (nesting > 0) {
char c = input_stream.readChar();
read++;
if (prev == '/' && c == '*') {
nesting++;
prev = 0;
} else if (prev == '*' && c == '/') {
nesting--;
if (firstCloseEnd < 0) {
firstCloseEnd = read;
}
prev = 0;
} else {
prev = c;
}
}
input_stream.backup(2);
} catch (java.io.IOException e) {
// Unterminated comment: leave the stream at EOF and let the token
// manager raise the lexical error from IN_BLOCK_COMMENT.
if (firstCloseEnd < 0) {
// Nothing closed the comment at all: leave the stream at EOF and let
// the token manager raise the lexical error from IN_BLOCK_COMMENT.
return;
}
// Nesting ran off the end of the input, so the inner "/*" was comment text,
// not a delimiter: close at the first "*/" as a non-nesting dialect would.
input_stream.backup(read - firstCloseEnd + 2);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
*/
package net.sf.jsqlparser.statement.select;

import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -102,4 +103,28 @@ void testMultilineNestedComment() {
void testOracleHintPreserved() {
assertParses("SELECT /*+ FULL(t) */ * FROM t");
}

@Test
void testUnbalancedNestingClosesAtFirstDelimiter() {
// Dialects such as Snowflake do not nest, so the inner "/*" is comment text and
// the comment ends at the only closing delimiter.
assertParses("SELECT /* a /* b */ 1");
}

@Test
void testUnbalancedNestingAcrossLines() {
assertParses(
"SELECT * FROM t WHERE 1 = 1\n"
+ "/* commented out:\n"
+ " AND x = /* default 42\n"
+ " AND y = 0\n"
+ "*/\n"
+ "AND z = 2");
}

@Test
void testUnterminatedBlockCommentStillFails() {
assertThrows(JSQLParserException.class,
() -> CCJSqlParserUtil.parse("SELECT /* never closed"));
}
}
Loading