Skip to content

refactor #246

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 1 commit into from
Jan 29, 2025
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
10 changes: 5 additions & 5 deletions scripts/update-fixtures-ast.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,11 +102,11 @@ for (const name of TARGETS) {
const servicesPath = path.join(ROOT, `${name}/services.json`)
const source = fs.readFileSync(sourcePath, "utf8")
const parserOptions = optionsPath ? require(optionsPath) : {}
const options = Object.assign(
{ filePath: sourcePath },
PARSER_OPTIONS,
parserOptions,
)
const options = {
filePath: sourcePath,
...PARSER_OPTIONS,
...parserOptions,
}
// console.log("Start:", name)
const actual = parser.parseForESLint(source, options)
const tokenRanges = getAllTokens(actual.ast).map((t) =>
Expand Down
11 changes: 6 additions & 5 deletions scripts/update-fixtures-document-fragment.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,12 @@ for (const name of TARGETS) {
path.join(ROOT, `${name}/parser-options.js`),
].find((fp) => fs.existsSync(fp))
const source = fs.readFileSync(sourcePath, "utf8")
const options = Object.assign(
{ filePath: sourcePath },
PARSER_OPTIONS,
optionsPath ? require(optionsPath) : {},
)
const options = {
filePath: sourcePath,
...PARSER_OPTIONS,
...(optionsPath ? require(optionsPath) : {}),
}

const result = parser.parseForESLint(source, options)
const actual = result.services.getDocumentFragment()

Expand Down
3 changes: 2 additions & 1 deletion src/ast/traverse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export const KEYS = Evk.unionWith({
VSlotScopeExpression: ["params"],
VStartTag: ["attributes"],
VText: [],
VGenericExpression: ["expression"],
})

/**
Expand Down Expand Up @@ -82,7 +83,7 @@ function traverse(node: Node, parent: Node | null, visitor: Visitor): void {
visitor.enterNode(node, parent)

const keys =
(visitor.visitorKeys || KEYS)[node.type] || getFallbackKeys(node)
(visitor.visitorKeys ?? KEYS)[node.type] ?? getFallbackKeys(node)
for (i = 0; i < keys.length; ++i) {
const child = (node as any)[keys[i]]

Expand Down
4 changes: 2 additions & 2 deletions src/common/ast-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,8 @@ export function isLang(
* @returns The `lang` attribute value.
*/
export function getLang(element: VElement | undefined): string | null {
const langAttr = element && element.startTag.attributes.find(isLang)
const lang = langAttr && langAttr.value && langAttr.value.value
const langAttr = element?.startTag.attributes.find(isLang)
const lang = langAttr?.value?.value
return lang || null
}
/**
Expand Down
2 changes: 1 addition & 1 deletion src/common/eslint-scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ let escopeCache: ESLintScope | null = null
* Load the newest `eslint-scope` from the loaded ESLint or dependency.
*/
export function getEslintScope(): ESLintScope {
return escopeCache || (escopeCache = getNewest())
return escopeCache ?? (escopeCache = getNewest())
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/common/espree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ let espreeCache: Espree | null = null
* Gets the espree that the given ecmaVersion can parse.
*/
export function getEspree(): Espree {
return espreeCache || (espreeCache = getNewestEspree())
return espreeCache ?? (espreeCache = getNewestEspree())
}

export function getEcmaVersionIfUseEspree(
Expand Down
4 changes: 2 additions & 2 deletions src/common/fix-locations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ export function fixLocations(
): void {
fixNodeLocations(result.ast, result.visitorKeys, locationCalculator)

for (const token of result.ast.tokens || []) {
for (const token of result.ast.tokens ?? []) {
fixLocation(token, locationCalculator)
}
for (const comment of result.ast.comments || []) {
for (const comment of result.ast.comments ?? []) {
fixLocation(comment, locationCalculator)
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/common/location-calculator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export class LocationCalculatorForHtml
super(ltOffsets)
this.gapOffsets = gapOffsets
this.ltOffsets = ltOffsets
this.baseOffset = baseOffset || 0
this.baseOffset = baseOffset ?? 0
this.baseIndexOfGap =
this.baseOffset === 0
? 0
Expand Down
2 changes: 1 addition & 1 deletion src/external/token-store/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,7 @@ export default class TokenStore {
)
.getOneToken()

if (token && token.range[0] === offset) {
if (token?.range[0] === offset) {
return token
}
return null
Expand Down
2 changes: 1 addition & 1 deletion src/html/intermediate-tokenizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ export class IntermediateTokenizer {
private processComment(token: Token): IntermediateToken | null {
this.comments.push(token)

if (this.currentToken != null && this.currentToken.type === "Text") {
if (this.currentToken?.type === "Text") {
return this.commit()
}
return null
Expand Down
7 changes: 3 additions & 4 deletions src/html/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -421,7 +421,7 @@ export class Parser {

if (name === "template") {
const xmlns = token.attributes.find((a) => a.key.name === "xmlns")
const value = xmlns && xmlns.value && xmlns.value.value
const value = xmlns?.value?.value

if (value === NS.HTML || value === NS.MathML || value === NS.SVG) {
return value
Expand Down Expand Up @@ -477,7 +477,7 @@ export class Parser {

node.key.name = adjustAttributeName(node.key.name, namespace)
const key = this.getTagName(node.key)
const value = node.value && node.value.value
const value = node.value?.value

if (key === "xmlns" && value !== namespace) {
this.reportParseError(node, "x-invalid-namespace")
Expand Down Expand Up @@ -616,8 +616,7 @@ export class Parser {
for (const attribute of element.startTag.attributes) {
if (attribute.directive) {
if (
attribute.key.argument != null &&
attribute.key.argument.type === "VExpressionContainer"
attribute.key.argument?.type === "VExpressionContainer"
) {
resolveReferences(attribute.key.argument)
}
Expand Down
3 changes: 1 addition & 2 deletions src/html/tokenizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -980,8 +980,7 @@ export class Tokenizer {
function maybeValidCustomBlock(this: Tokenizer, nextCp: number) {
return (
this.currentToken &&
this.lastTagOpenToken &&
this.lastTagOpenToken.value.startsWith(
this.lastTagOpenToken?.value.startsWith(
this.currentToken.value + String.fromCodePoint(nextCp),
)
)
Expand Down
30 changes: 14 additions & 16 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,13 @@ export function parseForESLint(
code: string,
parserOptions: any,
): AST.ESLintExtendedProgram {
const options: ParserOptions = Object.assign(
{
comment: true,
loc: true,
range: true,
tokens: true,
},
parserOptions || {},
)
const options: ParserOptions = {
comment: true,
loc: true,
range: true,
tokens: true,
...(parserOptions ?? {}),
}

let result: AST.ESLintExtendedProgram
let document: AST.VDocumentFragment | null
Expand All @@ -70,12 +68,12 @@ export function parseForESLint(
;({ result, document, locationCalculator } = parseAsSFC(code, options))
}

result.services = Object.assign(
result.services || {},
services.define(code, result.ast, document, locationCalculator, {
result.services = {
...(result.services || {}),
...services.define(code, result.ast, document, locationCalculator, {
parserOptions: options,
}),
)
}

return result
}
Expand All @@ -96,7 +94,7 @@ export { AST }
function parseAsSFC(code: string, options: ParserOptions) {
const optionsForTemplate = {
...options,
ecmaVersion: options.ecmaVersion || DEFAULT_ECMA_VERSION,
ecmaVersion: options.ecmaVersion ?? DEFAULT_ECMA_VERSION,
}
const skipParsingScript = options.parser === false
const tokenizer = new HTMLTokenizer(code, optionsForTemplate)
Expand Down Expand Up @@ -128,7 +126,7 @@ function parseAsSFC(code: string, options: ParserOptions) {
if (skipParsingScript || !scripts.length) {
result = parseScript("", {
...options,
ecmaVersion: options.ecmaVersion || DEFAULT_ECMA_VERSION,
ecmaVersion: options.ecmaVersion ?? DEFAULT_ECMA_VERSION,
parser: scriptParser,
})
} else if (
Expand Down Expand Up @@ -195,7 +193,7 @@ function parseAsSFC(code: string, options: ParserOptions) {
function parseAsScript(code: string, options: ParserOptions) {
return parseScript(code, {
...options,
ecmaVersion: options.ecmaVersion || DEFAULT_ECMA_VERSION,
ecmaVersion: options.ecmaVersion ?? DEFAULT_ECMA_VERSION,
parser: getScriptParser(options.parser, () => {
const ext = (
path.extname(options.filePath || "unknown.js").toLowerCase() ||
Expand Down
2 changes: 1 addition & 1 deletion src/parser-services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,7 @@ export function define(
)
// Register handlers into the intermediate event emitter.
for (const selector of Object.keys(
visitor || {},
visitor ?? {},
)) {
emitter.on(selector, visitor![selector])
}
Expand Down
10 changes: 5 additions & 5 deletions src/script-setup/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ export function parseScriptSetupElements(
): ESLintExtendedProgram {
const parserOptions: ParserOptions = {
...originalParserOptions,
ecmaVersion: originalParserOptions.ecmaVersion || DEFAULT_ECMA_VERSION,
ecmaVersion: originalParserOptions.ecmaVersion ?? DEFAULT_ECMA_VERSION,
}
const scriptSetupModuleCodeBlocks = getScriptSetupModuleCodeBlocks(
scriptSetupElement,
Expand Down Expand Up @@ -323,7 +323,7 @@ export function parseScriptSetupElements(
const textNode = node.children[0]
return Math.min(
start,
textNode != null && textNode.type === "VText"
textNode?.type === "VText"
? textNode.range[0]
: node.startTag.range[1],
)
Expand All @@ -344,7 +344,7 @@ export function parseScriptSetupElements(
const textNode = node.children[0]
return Math.max(
end,
textNode != null && textNode.type === "VText"
textNode?.type === "VText"
? textNode.range[1]
: (node.endTag?.range[0] ?? node.range[1]),
)
Expand Down Expand Up @@ -575,7 +575,7 @@ function getScriptSetupCodeBlocks(
(t) => t.range[0] === body.range[0],
)
const exportToken = tokens[exportTokenIndex]
if (exportToken && exportToken.value === "export") {
if (exportToken?.value === "export") {
// Consume code up to the start position of `export`.
// The code may contain legacy decorators.
append(statementCodeBlocks, usedOffset, exportToken.range[0])
Expand Down Expand Up @@ -958,7 +958,7 @@ function remapLocationAndTokens(
{ codeBlocks }: ScriptSetupModuleCodeBlocks,
locationCalculator: LocationCalculator,
) {
const tokens = result.ast.tokens || []
const tokens = result.ast.tokens ?? []

const endMap = new Map<number, number>()
const buffer: number[] = []
Expand Down
2 changes: 1 addition & 1 deletion src/script-setup/scope-analyzer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ function extractVariables(scopeManager: escopeTypes.ScopeManager) {
const moduleScope = globalScope.childScopes.find(
(scope) => scope.type === "module",
)
for (const variable of (moduleScope && moduleScope.variables) || []) {
for (const variable of moduleScope?.variables ?? []) {
scriptVariables.set(variable.name, variable)
}
return scriptVariables
Expand Down
Loading