Prism: Greedy matching bug

Created on 21 Jul 2018  路  1Comment  路  Source: PrismJS/prism

Consider the following code:

{
    'template-string-pattern': /`(?:\\[\s\S]|\${[^}]+}|[^\\`])*`/,
    'a': 0,
    'b': 1
};
{
    'string' : /(`|')(?:\\.|(?!\1)[^\\\r\n])*\1/m,
    'c': 0
};

Highlighted using Test Drive:

image

What's happening is quite simple:

  1. template-string matches (?:\\[\s\S]|\${[^}]+}|[^\\ and /, 'a': 0 ....... 'string': /( (plus the grave accents).
  2. string matches 'template-string-pattern' and 'c'. The rest is blocked by template-string.
  3. regex breaks the matches of template-string and highlights the regexes.
  4. string gets a chance from regex to match and does so matching 'a'. But that's it, because oneshot=true.

Btw: You can see this bug all over the place when you look at the Prism code with lots of language definitions.

bug core

Most helpful comment

Here is a minimal example showing the bug in action:


Language definition

I used aliases for styling.

Prism.languages['greedy-test'] = {
    'a': {
        pattern: /'[^'\r\n]*'/,
        alias: 'comment'
    },
    'b': {
        pattern: /"[^"\r\n]*"/,
        greedy: true,
        alias: 'string'
    },
    'c': {
        pattern: /<[^>\r\n]*>/,
        greedy: true,
        alias: 'keyword'
    }
}

Code:

<'> '' ''
<"> "" ""

(Each line is one example.)

Result:
image

Notes:

  1. The order of a and b is not significant. They just have to be before c.
  2. Both example lines of code are independent of each other.

>All comments

Here is a minimal example showing the bug in action:


Language definition

I used aliases for styling.

Prism.languages['greedy-test'] = {
    'a': {
        pattern: /'[^'\r\n]*'/,
        alias: 'comment'
    },
    'b': {
        pattern: /"[^"\r\n]*"/,
        greedy: true,
        alias: 'string'
    },
    'c': {
        pattern: /<[^>\r\n]*>/,
        greedy: true,
        alias: 'keyword'
    }
}

Code:

<'> '' ''
<"> "" ""

(Each line is one example.)

Result:
image

Notes:

  1. The order of a and b is not significant. They just have to be before c.
  2. Both example lines of code are independent of each other.
Was this page helpful?
0 / 5 - 0 ratings

Related issues

timgoeller picture timgoeller  路  4Comments

RunDevelopment picture RunDevelopment  路  5Comments

TheZoker picture TheZoker  路  9Comments

kizu picture kizu  路  7Comments

neginbasiri picture neginbasiri  路  8Comments