-
-
Notifications
You must be signed in to change notification settings - Fork 103
Closed
Description
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.