Skip to content

Commit

Permalink
fixed bugs related to AST parsing for for-loop index key usage detection
Browse files Browse the repository at this point in the history
  • Loading branch information
uguraslan committed Nov 18, 2024
1 parent d4513ce commit 8216bfb
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 51 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ out
backup
*.vsix
*.zip
test/
18 changes: 4 additions & 14 deletions src/completionItems/componentProps.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,8 @@ const createCompletionItems = (props, attributes) => {
if (attributes.includes(prop.key)) return []

const createItem = (prefix = '') => {
const item = new vscode.CompletionItem(
`${prefix}${prop.key}`,
vscode.CompletionItemKind.Property
)
item.insertText = new vscode.SnippetString(
`${prop.key}="${prop.default || ''}$0"`
)
const item = new vscode.CompletionItem(`${prefix}${prop.key}`, vscode.CompletionItemKind.Property)
item.insertText = new vscode.SnippetString(`${prop.key}="${prop.default || ''}$0"`)
item.sortText = `0${prefix}${prop.key}`
return item
}
Expand All @@ -46,8 +41,7 @@ const parseComponent = (attributes, componentFileContent, fileExtension) => {
let ast, props

if (fileExtension === 'blits') {
const { content, language } =
templateHelper.getScriptContentForBlits(componentFileContent)
const { content, language } = templateHelper.getScriptContentForBlits(componentFileContent)
ast = parse.AST(content, language)
} else {
ast = parse.AST(componentFileContent)
Expand All @@ -74,11 +68,7 @@ const suggest = async (tag, attributes, doc, docAst) => {
const componentFileContent = await fs.readFile(componentFilePath, 'utf-8')

if (componentFileContent) {
completionItems = parseComponent(
attributes,
componentFileContent,
fileExtension
)
completionItems = parseComponent(attributes, componentFileContent, fileExtension)
}
} catch (err) {
console.error('Error parsing component:', err)
Expand Down
74 changes: 37 additions & 37 deletions src/errorChecking/forLoopIndexAsKey.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,27 +18,41 @@
const vscode = require('vscode')
const templateHelper = require('../helpers/template')
const parse = require('../parsers')
const path = require('path')

// Allowed file extensions
const ALLOWED_EXTENSIONS = ['.js', '.ts', '.blits']

function shouldProcessFile(document) {
let fileName = document.fileName
if (fileName.endsWith('.git')) {
fileName = fileName.slice(0, -4)
}

const extension = path.extname(fileName)
const isAllowedExtension = ALLOWED_EXTENSIONS.includes(extension)
const isValidScheme = document.uri.scheme === 'file' || (document.uri.scheme === 'git' && extension === '.blits')
const isInWorkspace =
!fileName.includes('node_modules') && vscode.workspace.getWorkspaceFolder(document.uri) !== undefined
return isAllowedExtension && isValidScheme && isInWorkspace
}

module.exports = (context, diagnosticsCollection) => {
const checkForLoopIndexAsKey = (document) => {
// Clear previous diagnostics for this document
diagnosticsCollection.clear()

const currentDoc = document.getText()
const isBlits = document.languageId === 'blits'

const diagnostics = analyzeForLoopKeyAttribute(
document,
currentDoc,
isBlits
)
diagnosticsCollection.set(document.uri, diagnostics)
context.subscriptions.push(diagnosticsCollection)
if (shouldProcessFile(document)) {
// Clear previous diagnostics for this document
diagnosticsCollection.clear()

const currentDoc = document.getText()
const isBlits = document.languageId === 'blits'

const diagnostics = analyzeForLoopKeyAttribute(document, currentDoc, isBlits)
diagnosticsCollection.set(document.uri, diagnostics)
context.subscriptions.push(diagnosticsCollection)
}
}

vscode.workspace.onDidChangeTextDocument((event) =>
checkForLoopIndexAsKey(event.document)
)
vscode.workspace.onDidChangeTextDocument((event) => checkForLoopIndexAsKey(event.document))
vscode.workspace.onDidOpenTextDocument(checkForLoopIndexAsKey)
}

Expand All @@ -47,14 +61,12 @@ function analyzeForLoopKeyAttribute(document, currentDoc, isBlits) {

let templateSections = []
if (isBlits) {
const template = templateHelper.getTemplateTextForBlits(
document,
currentDoc
)
const template = templateHelper.getTemplateTextForBlits(document, currentDoc)
if (template) {
templateSections.push(template)
}
} else {
console.log(`for loop: parsing AST : ${document.uri.fsPath}`)
const ast = parse.AST(currentDoc, document.uri.fsPath.split('.').pop())
templateSections = templateHelper.getTemplateText(ast, currentDoc) || []
}
Expand All @@ -72,9 +84,7 @@ function analyzeForLoopKeyAttribute(document, currentDoc, isBlits) {
// vscode.DiagnosticSeverity.Information
// )
// )
} else if (
keyUsesIndex(forLoop.keyAttribute, forLoop.forExpression.indexVariable)
) {
} else if (keyUsesIndex(forLoop.keyAttribute, forLoop.forExpression.indexVariable)) {
diagnostics.push(
createDiagnostic(
forLoop.keyAttributeRange || forLoop.range, // Use keyAttributeRange if available
Expand All @@ -91,10 +101,7 @@ function analyzeForLoopKeyAttribute(document, currentDoc, isBlits) {

function keyUsesIndex(keyAttribute, indexVariable) {
if (!indexVariable) return false
const indexRegex = new RegExp(
'\\$' + indexVariable + '(?:\\b|\\s*[+\\-*/])',
'g'
)
const indexRegex = new RegExp('\\$' + indexVariable + '(?:\\b|\\s*[+\\-*/])', 'g')

return indexRegex.test(keyAttribute)
}
Expand Down Expand Up @@ -122,9 +129,7 @@ function findForLoops(templateInfo, document) {
// Handle multi-line tags
let fullTag = fullMatch
if (!fullTag.includes('>')) {
const remainingTemplate = templateText.slice(
match.index + fullMatch.length
)
const remainingTemplate = templateText.slice(match.index + fullMatch.length)
const closingTagIndex = remainingTemplate.indexOf('>')
if (closingTagIndex !== -1) {
fullTag += remainingTemplate.slice(0, closingTagIndex + 1)
Expand Down Expand Up @@ -166,17 +171,12 @@ function findForLoops(templateInfo, document) {

const forParts = forExpression.split(/\s+in\s+/)
const itemVariable = forParts[0].replace(/[()]/g, '').split(',')[0].trim()
const indexVariable = forParts[0].includes(',')
? forParts[0].replace(/[()]/g, '').split(',')[1].trim()
: null
const indexVariable = forParts[0].includes(',') ? forParts[0].replace(/[()]/g, '').split(',')[1].trim() : null
const iterableExpression = forParts[1]

forLoops.push({
tagName,
range: new vscode.Range(
document.positionAt(startIndex),
document.positionAt(endIndex)
),
range: new vscode.Range(document.positionAt(startIndex), document.positionAt(endIndex)),
attributes,
forExpression: {
itemVariable,
Expand Down

0 comments on commit 8216bfb

Please sign in to comment.