Skip to content

Fix source indices for Sass interpolated selectors #244

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
63 changes: 57 additions & 6 deletions src/__tests__/nonstandard.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,32 @@ test('non-standard selector', '.icon.is-$(network)', (t, tree) => {
let class1 = tree.nodes[0].nodes[0];
t.deepEqual(class1.value, 'icon');
t.deepEqual(class1.type, 'class');
t.deepEqual(class1.source.start.column, 1);
t.deepEqual(class1.source.end.column, 5);
t.deepEqual(class1.sourceIndex, 0);

let class2 = tree.nodes[0].nodes[1];
t.deepEqual(class2.value, 'is-$(network)');
t.deepEqual(class2.type, 'class');
t.deepEqual(class2.source.start.column, 6);
// t.deepEqual(class2.source.end.column, 19); // Fail - 10
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This still fails because the splitWords method processes this selector as [".icon", ".is-$"] and there is another place in the code that adds the rest of the selector in (I believe it's the pseudoselector code). I'm not sure how to fix this.

t.deepEqual(class2.sourceIndex, 5);
});

test('at word in selector', 'em@il.com', (t, tree) => {
t.deepEqual(tree.nodes[0].nodes[0].value, 'em@il');
t.deepEqual(tree.nodes[0].nodes[1].value, 'com');
const node1 = tree.nodes[0].nodes[0];
t.deepEqual(node1.value, 'em@il');
t.deepEqual(node1.type, 'tag');
t.deepEqual(node1.source.start.column, 1);
t.deepEqual(node1.source.end.column, 5);
t.deepEqual(node1.sourceIndex, 0);

const node2 = tree.nodes[0].nodes[1];
t.deepEqual(node2.value, 'com');
t.deepEqual(node2.type, 'class');
t.deepEqual(node2.source.start.column, 6);
t.deepEqual(node2.source.end.column, 9);
t.deepEqual(node2.sourceIndex, 5);
});

test('leading combinator', '> *', (t, tree) => {
Expand All @@ -20,8 +38,12 @@ test('leading combinator', '> *', (t, tree) => {
});

test('sass escapes', '.#{$classname}', (t, tree) => {
t.deepEqual(tree.nodes[0].nodes[0].type, "class");
t.deepEqual(tree.nodes[0].nodes[0].value, "#{$classname}");
const node = tree.nodes[0].nodes[0];
t.deepEqual(node.type, "class");
t.deepEqual(node.value, "#{$classname}");
t.deepEqual(node.source.start.column, 1);
t.deepEqual(node.source.end.column, 14);
t.deepEqual(node.sourceIndex, 0);
});

test('sass escapes (2)', '[lang=#{$locale}]', (t, tree) => {
Expand All @@ -31,14 +53,43 @@ test('sass escapes (2)', '[lang=#{$locale}]', (t, tree) => {
t.deepEqual(tree.nodes[0].nodes[0].value, "#{$locale}");
});

test('sass escapes (3)', '.classname1.#{$classname2}', (t, tree) => {
const node1 = tree.nodes[0].nodes[0];
t.deepEqual(node1.type, "class");
t.deepEqual(node1.value, "classname1");
t.deepEqual(node1.source.start.column, 1);
t.deepEqual(node1.source.end.column, 11);
t.deepEqual(node1.sourceIndex, 0);

const node2 = tree.nodes[0].nodes[1];
t.deepEqual(node2.type, "class");
t.deepEqual(node2.value, "#{$classname2}");
t.deepEqual(node2.source.start.column, 12);
t.deepEqual(node2.source.end.column, 26);
t.deepEqual(node2.sourceIndex, 11);
});

test('Sass escapes (4)', `.#{$classname1}\\$classname2`, (t, tree) => {
const node = tree.nodes[0].nodes[0];
t.deepEqual(node.type, "class");
t.deepEqual(node.value, "#{$classname1}$classname2");
t.deepEqual(node.source.start.column, 1);
t.deepEqual(node.source.end.column, 27);
t.deepEqual(node.sourceIndex, 0);
});

test('placeholder', '%foo', (t, tree) => {
t.deepEqual(tree.nodes[0].nodes[0].type, "tag");
t.deepEqual(tree.nodes[0].nodes[0].value, "%foo");
});

test('styled selector', '${Step}', (t, tree) => {
t.deepEqual(tree.nodes[0].nodes[0].type, "tag");
t.deepEqual(tree.nodes[0].nodes[0].value, "${Step}");
const node = tree.nodes[0].nodes[0];
t.deepEqual(node.type, "tag");
t.deepEqual(node.value, "${Step}");
t.deepEqual(node.source.start.column, 1);
t.deepEqual(node.source.end.column, 7);
t.deepEqual(node.sourceIndex, 0);
});

test('styled selector (2)', '${Step}:nth-child(odd)', (t, tree) => {
Expand Down
132 changes: 67 additions & 65 deletions src/parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import Universal from './selectors/universal';
import Combinator from './selectors/combinator';
import Nesting from './selectors/nesting';

import sortAsc from './sortAscending';
import tokenize, {FIELDS as TOKEN} from './tokenize';

import * as tokens from './tokenTypes';
Expand Down Expand Up @@ -95,23 +94,6 @@ function unescapeProp (node, prop) {
return node;
}

function indexesOf (array, item) {
let i = -1;
const indexes = [];

while ((i = array.indexOf(item, i + 1)) !== -1) {
indexes.push(i);
}

return indexes;
}

function uniqs () {
const list = Array.prototype.concat.apply([], arguments);

return list.filter((item, i) => i === list.indexOf(item));
}

export default class Parser {
constructor (rule, options = {}) {
this.rule = rule;
Expand Down Expand Up @@ -818,74 +800,94 @@ export default class Parser {
}

splitWord (namespace, firstCallback) {
// Collect all the relevant tokens together
const tokensList = [this.currToken];
let nextToken = this.nextToken;
let word = this.content();
while (
nextToken &&
~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[TOKEN.TYPE])
) {
this.position ++;
let current = this.content();
word += current;
if (current.lastIndexOf('\\') === current.length - 1) {
const token = this.currToken;
tokensList.push(token);
if (this.content(token).endsWith('\\')) {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be equivalent to current.lastIndexOf('\\') === current.length - 1, apart from the case when current is equal to "". I think we never get empty strings here though, but let me know if I'm wrong.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But also I'm not sure if this condition is ever true. The coverage report says that this if statement never evaluates to true during tests (both in this PR and also on base), and I haven't been able to write a test that hits this.

I tried parsing .#{$classname1}\\$classname2, but it gets tokenized as ["/#{", "$", "classname1}\\$classname2"] and not as ["/#{", "$", "classname1}\\", "$", "classname2"], so maybe the tokenizer handles this already?

let next = this.nextToken;
if (next && next[TOKEN.TYPE] === tokens.space) {
word += this.requiredSpace(this.content(next));
tokensList.push(next);
this.position ++;
}
}
nextToken = this.nextToken;
}
const hasClass = indexesOf(word, '.').filter(i => word[i - 1] !== '\\');
let hasId = indexesOf(word, '#').filter(i => word[i - 1] !== '\\');
// Eliminate Sass interpolations from the list of id indexes
const interpolations = indexesOf(word, '#{');
if (interpolations.length) {
hasId = hasId.filter(hashIndex => !~interpolations.indexOf(hashIndex));

// Get the content of each token
const tokensContent = tokensList.map(token => {
if (token[TOKEN.TYPE] === tokens.space) {
return this.requiredSpace(token);
}
return this.content(token);
});

// Parse the list of tokens and create a list of new nodes
const nodesToCreate = [];
let inProgressNode;
tokensList.forEach((token, tokenIndex) => {
const content = tokensContent[tokenIndex];
for (let i = 0; i < content.length; i++) {
const char = content[i];
const prevChar = content[i - 1] || (tokenIndex !== 0 ? tokensContent[tokenIndex - 1].slice(-1) : undefined);
const nextChar = content[i + 1] || (tokenIndex !== tokensContent.length - 1 ? tokensContent[tokenIndex + 1][0] : undefined);

if (char === "." && prevChar !== "\\") {
initNode(ClassName);
} else if (char === "#" && prevChar !== "\\" && nextChar !== "{") {
initNode(ID);
} else if (!inProgressNode) {
initNode(Tag, char);
} else {
inProgressNode.value += char;
inProgressNode.endToken = token;
inProgressNode.endIndex = i;
}

function initNode (NodeConstructor, value = "") {
if (inProgressNode) {
nodesToCreate.push(inProgressNode);
}
inProgressNode = {
NodeConstructor,
value,
startToken: token,
endToken: token,
startIndex: i,
endIndex: i,
};
}
}
});
if (inProgressNode) {
nodesToCreate.push(inProgressNode);
}
let indices = sortAsc(uniqs([0, ...hasClass, ...hasId]));
indices.forEach((ind, i) => {
const index = indices[i + 1] || word.length;
const value = word.slice(ind, index);

nodesToCreate.forEach((node, i) => {
if (i === 0 && firstCallback) {
return firstCallback.call(this, value, indices.length);
firstCallback.call(this, node.value, nodesToCreate.length);
return;
}
let node;
const current = this.currToken;
const sourceIndex = current[TOKEN.START_POS] + indices[i];
const {NodeConstructor, value, startToken, endToken, startIndex, endIndex} = node;
const sourceIndex = startToken[TOKEN.START_POS] + startIndex;
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was basically the fix - we're now using startToken and endToken which are correctly computed for each class/id/tag, instead of always using this.currToken

const source = getSource(
current[1],
current[2] + ind,
current[3],
current[2] + (index - 1)
startToken[TOKEN.START_LINE],
startToken[TOKEN.START_COL] + startIndex,
endToken[TOKEN.END_LINE],
endToken[TOKEN.START_COL] + endIndex
);
if (~hasClass.indexOf(ind)) {
let classNameOpts = {
value: value.slice(1),
source,
sourceIndex,
};
node = new ClassName(unescapeProp(classNameOpts, "value"));
} else if (~hasId.indexOf(ind)) {
let idOpts = {
value: value.slice(1),
source,
sourceIndex,
};
node = new ID(unescapeProp(idOpts, "value"));
} else {
let tagOpts = {
value,
source,
sourceIndex,
};
unescapeProp(tagOpts, "value");
node = new Tag(tagOpts);
}
this.newNode(node, namespace);
const opts = unescapeProp({value, source, sourceIndex}, "value");
this.newNode(new NodeConstructor(opts), namespace);
// Ensure that the namespace is used only once
namespace = null;
});

this.position ++;
}

Expand Down
3 changes: 0 additions & 3 deletions src/sortAscending.js

This file was deleted.