Skip to content

Rework language boundary detection #502

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

Merged
merged 3 commits into from
Mar 2, 2022
Merged
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
32,079 changes: 23,893 additions & 8,186 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions packages/tailwindcss-language-service/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"semver": "7.3.2",
"sift-string": "0.0.2",
"stringify-object": "3.3.0",
"tmp-cache": "1.1.0",
"vscode-emmet-helper-bundled": "0.0.1",
"vscode-languageclient": "7.0.0",
"vscode-languageserver": "7.0.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@ export async function provideInvalidApplyCodeActions(
if (!isCssDoc(state, document)) {
let languageBoundaries = getLanguageBoundaries(state, document)
if (!languageBoundaries) return []
cssRange = languageBoundaries.css.find((range) => isWithinRange(diagnostic.range.start, range))
cssRange = languageBoundaries
.filter((b) => b.type === 'css')
.find(({ range }) => isWithinRange(diagnostic.range.start, range))?.range
if (!cssRange) return []
cssText = document.getText(cssRange)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { stringifyScreen, Screen } from './util/screens'
import isObject from './util/isObject'
import * as emmetHelper from 'vscode-emmet-helper-bundled'
import { isValidLocationForEmmetAbbreviation } from './util/isValidLocationForEmmetAbbreviation'
import { isJsContext } from './util/js'
import { isJsDoc, isJsxContext } from './util/js'
import { naturalExpand } from './util/naturalExpand'
import semver from 'semver'
import { docsUrl } from './util/docsUrl'
Expand Down Expand Up @@ -511,7 +511,7 @@ async function provideClassNameCompletions(
return provideAtApplyCompletions(state, document, position)
}

if (isHtmlContext(state, document, position) || isJsContext(state, document, position)) {
if (isHtmlContext(state, document, position) || isJsxContext(state, document, position)) {
return provideClassAttributeCompletions(state, document, position, context)
}

Expand Down Expand Up @@ -973,8 +973,8 @@ async function provideEmmetCompletions(
let settings = await state.editor.getConfiguration(document.uri)
if (settings.tailwindCSS.emmetCompletions !== true) return null

const isHtml = isHtmlContext(state, document, position)
const isJs = !isHtml && isJsContext(state, document, position)
const isHtml = !isJsDoc(state, document) && isHtmlContext(state, document, position)
const isJs = isJsDoc(state, document) || isJsxContext(state, document, position)

const syntax = isHtml ? 'html' : isJs ? 'jsx' : null

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ export function getInvalidConfigPathDiagnostics(
} else {
let boundaries = getLanguageBoundaries(state, document)
if (!boundaries) return []
ranges.push(...boundaries.css)
ranges.push(...boundaries.filter((b) => b.type === 'css').map(({ range }) => range))
}

ranges.forEach((range) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export function getInvalidScreenDiagnostics(
} else {
let boundaries = getLanguageBoundaries(state, document)
if (!boundaries) return []
ranges.push(...boundaries.css)
ranges.push(...boundaries.filter((b) => b.type === 'css').map(({ range }) => range))
}

ranges.forEach((range) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export function getInvalidTailwindDirectiveDiagnostics(
} else {
let boundaries = getLanguageBoundaries(state, document)
if (!boundaries) return []
ranges.push(...boundaries.css)
ranges.push(...boundaries.filter((b) => b.type === 'css').map(({ range }) => range))
}

let notSemicolonLanguages = ['sass', 'sugarss', 'stylus']
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export function getInvalidVariantDiagnostics(
} else {
let boundaries = getLanguageBoundaries(state, document)
if (!boundaries) return []
ranges.push(...boundaries.css)
ranges.push(...boundaries.filter((b) => b.type === 'css').map(({ range }) => range))
}

let possibleVariants = Object.keys(state.variants)
Expand Down
7 changes: 5 additions & 2 deletions packages/tailwindcss-language-service/src/util/css.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import type { TextDocument, Position } from 'vscode-languageserver'
import { isInsideTag, isVueDoc, isSvelteDoc, isHtmlDoc } from './html'
import { isVueDoc, isSvelteDoc, isHtmlDoc } from './html'
import { isJsDoc } from './js'
import { State } from './state'
import { cssLanguages } from './languages'
import { getLanguageBoundaries } from './getLanguageBoundaries'

export function isCssDoc(state: State, doc: TextDocument): boolean {
const userCssLanguages = Object.keys(state.editor.userLanguages).filter((lang) =>
Expand All @@ -23,7 +24,9 @@ export function isCssContext(state: State, doc: TextDocument, position: Position
end: position,
})

return isInsideTag(str, ['style'])
let boundaries = getLanguageBoundaries(state, doc, str)

return boundaries ? boundaries[boundaries.length - 1].type === 'css' : false
}

return false
Expand Down
18 changes: 13 additions & 5 deletions packages/tailwindcss-language-service/src/util/find.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import lineColumn from 'line-column'
import { isCssContext, isCssDoc } from './css'
import { isHtmlContext } from './html'
import { isWithinRange } from './isWithinRange'
import { isJsContext } from './js'
import { isJsxContext } from './js'
import { flatten } from './array'
import { getClassAttributeLexer, getComputedClassAttributeLexer } from './lexers'
import { getLanguageBoundaries } from './getLanguageBoundaries'
Expand Down Expand Up @@ -306,9 +306,13 @@ export async function findClassListsInDocument(

return flatten([
...(await Promise.all(
boundaries.html.map((range) => findClassListsInHtmlRange(state, doc, range))
boundaries
.filter((b) => b.type === 'html' || b.type === 'jsx')
.map(({ range }) => findClassListsInHtmlRange(state, doc, range))
)),
...boundaries.css.map((range) => findClassListsInCssRange(doc, range)),
...boundaries
.filter((b) => b.type === 'css')
.map(({ range }) => findClassListsInCssRange(doc, range)),
await findCustomClassLists(state, doc),
])
}
Expand All @@ -324,7 +328,11 @@ export function findHelperFunctionsInDocument(
let boundaries = getLanguageBoundaries(state, doc)
if (!boundaries) return []

return flatten(boundaries.css.map((range) => findHelperFunctionsInRange(doc, range)))
return flatten(
boundaries
.filter((b) => b.type === 'css')
.map(({ range }) => findHelperFunctionsInRange(doc, range))
)
}

export function findHelperFunctionsInRange(
Expand Down Expand Up @@ -385,7 +393,7 @@ export async function findClassNameAtPosition(

if (isCssContext(state, doc, position)) {
classNames = await findClassNamesInRange(state, doc, searchRange, 'css')
} else if (isHtmlContext(state, doc, position) || isJsContext(state, doc, position)) {
} else if (isHtmlContext(state, doc, position) || isJsxContext(state, doc, position)) {
classNames = await findClassNamesInRange(state, doc, searchRange, 'html')
}

Expand Down
199 changes: 137 additions & 62 deletions packages/tailwindcss-language-service/src/util/getLanguageBoundaries.ts
Original file line number Diff line number Diff line change
@@ -1,78 +1,153 @@
import type { TextDocument, Range } from 'vscode-languageserver'
import { isVueDoc, isHtmlDoc, isSvelteDoc } from './html'
import { State } from './state'
import { findAll, indexToPosition } from './find'
import { indexToPosition } from './find'
import { isJsDoc } from './js'
import moo from 'moo'
import Cache from 'tmp-cache'

export interface LanguageBoundaries {
html: Range[]
css: Range[]
export type LanguageBoundary = { type: 'html' | 'js' | 'css' | string; range: Range }

let text = { text: { match: /[^]/, lineBreaks: true } }

let states = {
main: {
cssBlockStart: { match: '<style', push: 'cssBlock' },
jsBlockStart: { match: '<script', push: 'jsBlock' },
...text,
},
cssBlock: {
styleStart: { match: '>', next: 'style' },
cssBlockEnd: { match: '/>', pop: 1 },
attrStartDouble: { match: '"', push: 'attrDouble' },
attrStartSingle: { match: "'", push: 'attrSingle' },
interp: { match: '{', push: 'interp' },
...text,
},
jsBlock: {
scriptStart: { match: '>', next: 'script' },
jsBlockEnd: { match: '/>', pop: 1 },
langAttrStartDouble: { match: 'lang="', push: 'langAttrDouble' },
langAttrStartSingle: { match: "lang='", push: 'langAttrSingle' },
attrStartDouble: { match: '"', push: 'attrDouble' },
attrStartSingle: { match: "'", push: 'attrSingle' },
interp: { match: '{', push: 'interp' },
...text,
},
interp: {
interp: { match: '{', push: 'interp' },
end: { match: '}', pop: 1 },
...text,
},
langAttrDouble: {
langAttrEnd: { match: '"', pop: 1 },
lang: { match: /[^"]+/, lineBreaks: true },
},
langAttrSingle: {
langAttrEnd: { match: "'", pop: 1 },
lang: { match: /[^']+/, lineBreaks: true },
},
attrDouble: {
attrEnd: { match: '"', pop: 1 },
...text,
},
attrSingle: {
attrEnd: { match: "'", pop: 1 },
...text,
},
style: {
cssBlockEnd: { match: '</style>', pop: 1 },
...text,
},
script: {
jsBlockEnd: { match: '</script>', pop: 1 },
...text,
},
}

export function getLanguageBoundaries(state: State, doc: TextDocument): LanguageBoundaries | null {
if (isVueDoc(doc)) {
let text = doc.getText()
let blocks = findAll(
/(?<open><(?<type>template|style|script)\b[^>]*>).*?(?<close><\/\k<type>>|$)/gis,
text
)
let htmlRanges: Range[] = []
let cssRanges: Range[] = []
for (let i = 0; i < blocks.length; i++) {
let range = {
start: indexToPosition(text, blocks[i].index + blocks[i].groups.open.length),
end: indexToPosition(
text,
blocks[i].index + blocks[i][0].length - blocks[i].groups.close.length
),
}
if (blocks[i].groups.type === 'style') {
cssRanges.push(range)
} else {
htmlRanges.push(range)
}
}
let vueStates = {
...states,
main: {
htmlBlockStart: { match: '<template', push: 'htmlBlock' },
...states.main,
},
htmlBlock: {
htmlStart: { match: '>', next: 'html' },
htmlBlockEnd: { match: '/>', pop: 1 },
attrStartDouble: { match: '"', push: 'attrDouble' },
attrStartSingle: { match: "'", push: 'attrSingle' },
interp: { match: '{', push: 'interp' },
...text,
},
html: {
htmlBlockEnd: { match: '</template>', pop: 1 },
...text,
},
}

return {
html: htmlRanges,
css: cssRanges,
}
let defaultLexer = moo.states(states)
let vueLexer = moo.states(vueStates)

let cache = new Cache<string, LanguageBoundary[] | null>({ max: 25, maxAge: 1000 })

export function getLanguageBoundaries(
state: State,
doc: TextDocument,
text: string = doc.getText()
): LanguageBoundary[] | null {
let cacheKey = `${doc.languageId}:${text}`
if (cache.has(cacheKey)) {
return cache.get(cacheKey)
}

if (isHtmlDoc(state, doc) || isJsDoc(state, doc) || isSvelteDoc(doc)) {
let text = doc.getText()
let styleBlocks = findAll(
/(?<open><style(?:\s[^>]*[^\/]>|\s*>)).*?(?<close><\/style>|$)/gis,
text
)
let htmlRanges: Range[] = []
let cssRanges: Range[] = []
let currentIndex = 0
let defaultType = isVueDoc(doc)
? 'none'
: isHtmlDoc(state, doc) || isJsDoc(state, doc) || isSvelteDoc(doc)
? 'html'
: null

for (let i = 0; i < styleBlocks.length; i++) {
htmlRanges.push({
start: indexToPosition(text, currentIndex),
end: indexToPosition(text, styleBlocks[i].index),
})
cssRanges.push({
start: indexToPosition(text, styleBlocks[i].index + styleBlocks[i].groups.open.length),
end: indexToPosition(
text,
styleBlocks[i].index + styleBlocks[i][0].length - styleBlocks[i].groups.close.length
),
})
currentIndex = styleBlocks[i].index + styleBlocks[i][0].length
}
htmlRanges.push({
start: indexToPosition(text, currentIndex),
end: indexToPosition(text, text.length),
})
if (defaultType === null) {
cache.set(cacheKey, null)
return null
}

let lexer = defaultType === 'none' ? vueLexer : defaultLexer
lexer.reset(text)

let type = defaultType
let boundaries: LanguageBoundary[] = [
{ type: defaultType, range: { start: { line: 0, character: 0 }, end: undefined } },
]
let offset = 0

return {
html: htmlRanges,
css: cssRanges,
try {
for (let token of lexer) {
if (token.type.endsWith('BlockStart')) {
let position = indexToPosition(text, offset)
if (!boundaries[boundaries.length - 1].range.end) {
boundaries[boundaries.length - 1].range.end = position
}
type = token.type.replace(/BlockStart$/, '')
boundaries.push({ type, range: { start: position, end: undefined } })
} else if (token.type.endsWith('BlockEnd')) {
let position = indexToPosition(text, offset)
boundaries[boundaries.length - 1].range.end = position
boundaries.push({ type: defaultType, range: { start: position, end: undefined } })
} else if (token.type === 'lang') {
boundaries[boundaries.length - 1].type = token.text
}
offset += token.text.length
}
} catch {
cache.set(cacheKey, null)
return null
}

if (!boundaries[boundaries.length - 1].range.end) {
boundaries[boundaries.length - 1].range.end = indexToPosition(text, offset)
}

return null
cache.set(cacheKey, boundaries)

return boundaries
}
Loading