Skip to content

Commit

Permalink
[BUGFIX] Fix comment parsing to support multiple comments
Browse files Browse the repository at this point in the history
Because of an eager consumption of whitespace, the rule parsing would
swallow a trailing comment, meaning the comment for the next rule would
be affected. This patch addresses this by only consuming real whitespace
without comments after a rule.

Fixes MyIntervals#173

Signed-off-by: Daniel Ziegenberg <[email protected]>
  • Loading branch information
ziegenberg committed Aug 24, 2024
1 parent 5a25712 commit dce07e5
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 7 deletions.
12 changes: 10 additions & 2 deletions src/Parsing/ParserState.php
Original file line number Diff line number Diff line change
Expand Up @@ -220,18 +220,26 @@ public function parseCharacter($bIsForIdentifier)
}

/**
* @return array<int, Comment>|void
* Consumes whitespace and comments and returns the comments.
* If $withoutComment is true, only whitespace is consumed.
*
* @param bool $withoutComment Do not consume comments, only whitespace.
*
* @return array<int, Comment>|void List of comments.
*
* @throws UnexpectedEOFException
* @throws UnexpectedTokenException
*/
public function consumeWhiteSpace(): array
public function consumeWhiteSpace(bool $withoutComment = false): array
{
$aComments = [];
do {
while (\preg_match('/\\s/isSu', $this->peek()) === 1) {
$this->consume(1);
}
if ($withoutComment) {
break;
}
if ($this->oParserSettings->bLenientParsing) {
try {
$oComment = $this->consumeComment();
Expand Down
2 changes: 1 addition & 1 deletion src/Rule/Rule.php
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ public static function parse(ParserState $oParserState): Rule
while ($oParserState->comes(';')) {
$oParserState->consume(';');
}
$oParserState->consumeWhiteSpace();
$oParserState->consumeWhiteSpace(true);

return $oRule;
}
Expand Down
11 changes: 7 additions & 4 deletions tests/ParserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1161,13 +1161,16 @@ public function commentExtracting(): void
*/
public function flatCommentExtracting(): void
{
$parser = new Parser('div {/*Find Me!*/left:10px; text-align:left;}');
$parser = new Parser('div {/*Find Me!*/left:10px; /*Find Me Too!*/text-align:left;}');
$doc = $parser->parse();
$contents = $doc->getContents();
$divRules = $contents[0]->getRules();
$comments = $divRules[0]->getComments();
self::assertCount(1, $comments);
self::assertSame('Find Me!', $comments[0]->getComment());
$rule1Comments = $divRules[0]->getComments();
$rule2Comments = $divRules[1]->getComments();
$this->assertCount(1, $rule1Comments);
$this->assertCount(1, $rule2Comments);
$this->assertEquals("Find Me!", $rule1Comments[0]->getComment());
$this->assertEquals("Find Me Too!", $rule2Comments[0]->getComment());
}

/**
Expand Down

0 comments on commit dce07e5

Please sign in to comment.