Skip to content

Parsing invalid input with specified base location doesn't work properly #251

@scripthunter7

Description

@scripthunter7

In some cases, I only want to parse a particular source fragment, but I need the exact position of the nodes, however the fragment is located somewhere in a larger source code. To solve this, I specify the base location in the parser settings (offset, line, column). This method gives the expected result for valid input. The following code

import * as cssTree from 'css-tree';
import { inspect } from 'util';

console.log(
    inspect(
        cssTree.toPlainObject(
            cssTree.parse(
                '.classname',
                { context: 'selector', positions: true, offset: 10, line: 10, column: 10 }
            ),
        ),
        { depth: null, colors: true },
    )
);

will gives

{
  type: 'Selector',
  loc: {
    source: '<unknown>',
    start: { offset: 10, line: 10, column: 10 },
    end: { offset: 20, line: 10, column: 20 }
  },
  children: [
    {
      type: 'ClassSelector',
      loc: {
        source: '<unknown>',
        start: { offset: 10, line: 10, column: 10 },
        end: { offset: 20, line: 10, column: 20 }
      },
      name: 'classname'
    }
  ]
}

which is a good result, and the positions are correct.

And here comes the problem: if the input is invalid (for example: #.classname), then the error generation doesn't work properly, and results the following error:

node_modules/css-tree/lib/parser/SyntaxError.js:23
    column += (TAB_REPLACEMENT.length - 1) * (lines[line - 1].substr(0, column - 1).match(/\t/g) || []).length;
                                                              ^

TypeError: Cannot read properties of undefined (reading 'substr')

since the error generation is trying to work with a line that doesn't actually exist, only a relative position has been specified.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions