Skip to content

Add parserOptions.vueFeatures.interpolationAsNonHTML option #88

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 2 commits into from
Dec 3, 2020
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
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,33 @@ For example:
If the `parserOptions.parser` is `false`, the `vue-eslint-parser` skips parsing `<script>` tags completely.
This is useful for people who use the language ESLint community doesn't provide custom parser implementation.

### parserOptions.vueFeatures.interpolationAsNonHTML

You can use `parserOptions.vueFeatures.interpolationAsNonHTML` property to specify whether to parse the interpolation as HTML. If you specify `true`, the parser handles the interpolation as non-HTML (However, you can use HTML escaping in the interpolation).
For example:

```json
{
"parser": "vue-eslint-parser",
"parserOptions": {
"vueFeatures": {
"interpolationAsNonHTML": true
}
}
}
```

If you specify `true`, it can be parsed in the same way as Vue 3.
The following template can be parsed well.

```vue
<template>
<div>{{a<b}}</div>
</template>
```

But, it cannot be parsed with Vue 2.

## 🎇 Usage for custom rules / plugins

- This parser provides `parserServices` to traverse `<template>`.
Expand Down
9 changes: 8 additions & 1 deletion scripts/update-fixtures-ast.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,13 +101,20 @@ function getTree(source, ast) {

for (const name of TARGETS) {
const sourcePath = path.join(ROOT, `${name}/source.vue`)
const optionsPath = path.join(ROOT, `${name}/parser-options.json`)
const astPath = path.join(ROOT, `${name}/ast.json`)
const tokenRangesPath = path.join(ROOT, `${name}/token-ranges.json`)
const treePath = path.join(ROOT, `${name}/tree.json`)
const source = fs.readFileSync(sourcePath, "utf8")
const actual = parser.parse(
source,
Object.assign({ filePath: sourcePath }, PARSER_OPTIONS)
Object.assign(
{ filePath: sourcePath },
PARSER_OPTIONS,
fs.existsSync(optionsPath)
? JSON.parse(fs.readFileSync(optionsPath, "utf8"))
: {}
)
)
const tokenRanges = getAllTokens(actual).map(t =>
source.slice(t.range[0], t.range[1])
Expand Down
1 change: 1 addition & 0 deletions src/ast/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ export type ErrorCode =
| "non-void-html-element-start-tag-with-trailing-solidus"
| "x-invalid-end-tag"
| "x-invalid-namespace"
| "x-missing-interpolation-end"
// ---- Use RAWTEXT state for <script> elements instead ----
// "eof-in-script-html-comment-like-text" |
// ---- Use BOGUS_COMMENT state for DOCTYPEs instead ----
Expand Down
34 changes: 34 additions & 0 deletions src/common/parser-options.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
export interface ParserOptions {
// vue-eslint-parser options
parser?: boolean | string
vueFeatures?: {
interpolationAsNonHTML?: boolean // default false
}

// espree options
ecmaVersion?: number
sourceType?: "script" | "module"
ecmaFeatures?: { [key: string]: any }

// @typescript-eslint/parser options
jsxPragma?: string
jsxFragmentName?: string | null
lib?: string[]

project?: string | string[]
projectFolderIgnoreList?: string[]
tsconfigRootDir?: string
extraFileExtensions?: string[]
warnOnUnsupportedTypeScriptVersion?: boolean

// set by eslint
filePath?: string
// enables by eslint
comment?: boolean
loc?: boolean
range?: boolean
tokens?: boolean

// others
// [key: string]: any
}
5 changes: 3 additions & 2 deletions src/html/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import {
Text,
} from "./intermediate-tokenizer"
import { Tokenizer } from "./tokenizer"
import { ParserOptions } from "../common/parser-options"

const DIRECTIVE_NAME = /^(?:v-|[.:@#]).*[^.:@#]$/u
const DT_DD = /^d[dt]$/u
Expand Down Expand Up @@ -148,7 +149,7 @@ function propagateEndLocation(node: VDocumentFragment | VElement): void {
export class Parser {
private tokenizer: IntermediateTokenizer
private locationCalculator: LocationCalculator
private parserOptions: any
private parserOptions: ParserOptions
private document: VDocumentFragment
private elementStack: VElement[]
private vPreElement: VElement | null
Expand Down Expand Up @@ -222,7 +223,7 @@ export class Parser {
* @param tokenizer The tokenizer to parse.
* @param parserOptions The parser options to parse inline expressions.
*/
public constructor(tokenizer: Tokenizer, parserOptions: any) {
public constructor(tokenizer: Tokenizer, parserOptions: ParserOptions) {
this.tokenizer = new IntermediateTokenizer(tokenizer)
this.locationCalculator = new LocationCalculator(
tokenizer.gaps,
Expand Down
82 changes: 79 additions & 3 deletions src/html/tokenizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import {
SOLIDUS,
toLowerCodePoint,
} from "./util/unicode"
import { ParserOptions } from "../common/parser-options"

/**
* Enumeration of token types.
Expand Down Expand Up @@ -123,6 +124,7 @@ export type TokenizerState =
| "NUMERIC_CHARACTER_REFERENCE_END"
| "CHARACTER_REFERENCE_END"
| "V_EXPRESSION_START"
| "V_EXPRESSION_DATA"
| "V_EXPRESSION_END"
// ---- Use RAWTEXT state for <script> elements instead ----
// "SCRIPT_DATA" |
Expand Down Expand Up @@ -165,13 +167,15 @@ export class Tokenizer {
public readonly text: string
public readonly gaps: number[]
public readonly lineTerminators: number[]
private readonly parserOptions: ParserOptions
private lastCodePoint: number
private offset: number
private column: number
private line: number

// Tokenizing
private returnState: TokenizerState
private vExpressionScriptState: { state: TokenizerState } | null = null
private reconsuming: boolean
private buffer: number[]
private crStartOffset: number
Expand Down Expand Up @@ -208,12 +212,14 @@ export class Tokenizer {
/**
* Initialize this tokenizer.
* @param text The source code to tokenize.
* @param parserOptions The parser options.
*/
public constructor(text: string) {
public constructor(text: string, parserOptions?: ParserOptions) {
debug("[html] the source code length: %d", text.length)
this.text = text
this.gaps = []
this.lineTerminators = []
this.parserOptions = parserOptions || {}
this.lastCodePoint = NULL
this.offset = -1
this.column = -1
Expand Down Expand Up @@ -1834,13 +1840,81 @@ export class Tokenizer {
this.startToken("VExpressionStart")
this.appendTokenValue(LEFT_CURLY_BRACKET, null)
this.appendTokenValue(LEFT_CURLY_BRACKET, null)
return this.returnState

if (!this.parserOptions.vueFeatures?.interpolationAsNonHTML) {
return this.returnState
}

const closeIndex = this.text.indexOf("}}", this.offset + 1)
if (closeIndex === -1) {
this.reportParseError("x-missing-interpolation-end")
return this.returnState
}
this.vExpressionScriptState = {
state: this.returnState,
}
return "V_EXPRESSION_DATA"
}

this.appendTokenValue(LEFT_CURLY_BRACKET, null)
return this.reconsumeAs(this.returnState)
}

/**
* Original state.
* Parse in interpolation.
* @see https://github.com/vuejs/vue-next/blob/3a6b1207fa39cb35eed5bae0b5fdcdb465926bca/packages/compiler-core/src/parse.ts#L752
* @param cp The current code point.
* @returns The next state.
*/
protected V_EXPRESSION_DATA(cp: number): TokenizerState {
this.clearStartTokenMark()
const state = this.vExpressionScriptState!.state

while (true) {
const type = isWhitespace(cp)
? "HTMLWhitespace"
: state === "RCDATA"
? "HTMLRawText"
: state === "RAWTEXT"
? "HTMLRCDataText"
: "HTMLText"
if (this.currentToken != null && this.currentToken.type !== type) {
this.endToken()
return this.reconsumeAs(this.state)
}
if (this.currentToken == null) {
this.startToken(type)
}

if (cp === AMPERSAND && state !== "RAWTEXT") {
this.returnState = "V_EXPRESSION_DATA"
return "CHARACTER_REFERENCE"
}
// if (cp === LESS_THAN_SIGN) {
// this.setStartTokenMark()
// return "TAG_OPEN"
// }
if (cp === RIGHT_CURLY_BRACKET) {
this.setStartTokenMark()
this.returnState = "V_EXPRESSION_DATA"
return "V_EXPRESSION_END"
}
// Already checked
/* istanbul ignore next */
if (cp === EOF) {
this.reportParseError("x-missing-interpolation-end")
return "DATA"
}

if (cp === NULL) {
this.reportParseError("unexpected-null-character")
}
this.appendTokenValue(cp, type)

cp = this.consumeNextCodePoint()
}
}
/**
* Create `}} `token.
* @param cp The current code point.
Expand All @@ -1851,7 +1925,9 @@ export class Tokenizer {
this.startToken("VExpressionEnd")
this.appendTokenValue(RIGHT_CURLY_BRACKET, null)
this.appendTokenValue(RIGHT_CURLY_BRACKET, null)
return this.returnState
return this.vExpressionScriptState
? this.vExpressionScriptState.state
: this.returnState
}

this.appendTokenValue(RIGHT_CURLY_BRACKET, null)
Expand Down
7 changes: 4 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { LocationCalculator } from "./common/location-calculator"
import { HTMLParser, HTMLTokenizer } from "./html"
import { parseScript, parseScriptElement } from "./script"
import * as services from "./parser-services"
import { ParserOptions } from "./common/parser-options"

const STARTS_WITH_LT = /^\s*</u

Expand All @@ -18,8 +19,8 @@ const STARTS_WITH_LT = /^\s*</u
* @param options The parser options.
* @returns `true` if the source code is a Vue.js component.
*/
function isVueFile(code: string, options: any): boolean {
const filePath = (options.filePath as string | undefined) || "unknown.js"
function isVueFile(code: string, options: ParserOptions): boolean {
const filePath = options.filePath || "unknown.js"
return path.extname(filePath) === ".vue" || STARTS_WITH_LT.test(code)
}

Expand Down Expand Up @@ -96,7 +97,7 @@ export function parseForESLint(
document = null
} else {
const skipParsingScript = options.parser === false
const tokenizer = new HTMLTokenizer(code)
const tokenizer = new HTMLTokenizer(code, options)
const rootAST = new HTMLParser(tokenizer, options).parse()
const locationCalcurator = new LocationCalculator(
tokenizer.gaps,
Expand Down
21 changes: 11 additions & 10 deletions src/script/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import {
analyzeVariablesAndExternalReferences,
} from "./scope-analyzer"
import { ESLintCustomParser, getEspree } from "./espree"
import { ParserOptions } from "../common/parser-options"

// [1] = spacing before the aliases.
// [2] = aliases.
Expand Down Expand Up @@ -239,7 +240,7 @@ function throwErrorAsAdjustingOutsideOfCode(
function parseScriptFragment(
code: string,
locationCalculator: LocationCalculator,
parserOptions: any,
parserOptions: ParserOptions,
): ESLintExtendedProgram {
try {
const result = parseScript(code, parserOptions)
Expand Down Expand Up @@ -368,7 +369,7 @@ function splitFilters(exp: string): string[] {
function parseExpressionBody(
code: string,
locationCalculator: LocationCalculator,
parserOptions: any,
parserOptions: ParserOptions,
allowEmpty = false,
): ExpressionParseResult<ESLintExpression> {
debug('[script] parse expression: "0(%s)"', code)
Expand Down Expand Up @@ -421,7 +422,7 @@ function parseExpressionBody(
function parseFilter(
code: string,
locationCalculator: LocationCalculator,
parserOptions: any,
parserOptions: ParserOptions,
): ExpressionParseResult<VFilter> | null {
debug('[script] parse filter: "%s"', code)

Expand Down Expand Up @@ -570,7 +571,7 @@ export interface ExpressionParseResult<T extends Node> {
*/
export function parseScript(
code: string,
parserOptions: any,
parserOptions: ParserOptions,
): ESLintExtendedProgram {
const parser: ESLintCustomParser =
typeof parserOptions.parser === "string"
Expand Down Expand Up @@ -598,7 +599,7 @@ export function parseScript(
export function parseScriptElement(
node: VElement,
globalLocationCalculator: LocationCalculator,
parserOptions: any,
parserOptions: ParserOptions,
): ESLintExtendedProgram {
const text = node.children[0]
const offset =
Expand Down Expand Up @@ -648,7 +649,7 @@ export function parseScriptElement(
export function parseExpression(
code: string,
locationCalculator: LocationCalculator,
parserOptions: any,
parserOptions: ParserOptions,
{ allowEmpty = false, allowFilters = false } = {},
): ExpressionParseResult<ESLintExpression | VFilterSequenceExpression> {
debug('[script] parse expression: "%s"', code)
Expand Down Expand Up @@ -738,7 +739,7 @@ export function parseExpression(
export function parseVForExpression(
code: string,
locationCalculator: LocationCalculator,
parserOptions: any,
parserOptions: ParserOptions,
): ExpressionParseResult<VForExpression> {
const processedCode = replaceAliasParens(code)
debug('[script] parse v-for expression: "for(%s);"', processedCode)
Expand Down Expand Up @@ -820,7 +821,7 @@ export function parseVForExpression(
export function parseVOnExpression(
code: string,
locationCalculator: LocationCalculator,
parserOptions: any,
parserOptions: ParserOptions,
): ExpressionParseResult<ESLintExpression | VOnExpression> {
if (IS_FUNCTION_EXPRESSION.test(code) || IS_SIMPLE_PATH.test(code)) {
return parseExpressionBody(code, locationCalculator, parserOptions)
Expand All @@ -838,7 +839,7 @@ export function parseVOnExpression(
function parseVOnExpressionBody(
code: string,
locationCalculator: LocationCalculator,
parserOptions: any,
parserOptions: ParserOptions,
): ExpressionParseResult<VOnExpression> {
debug('[script] parse v-on expression: "void function($event){%s}"', code)

Expand Down Expand Up @@ -911,7 +912,7 @@ function parseVOnExpressionBody(
export function parseSlotScopeExpression(
code: string,
locationCalculator: LocationCalculator,
parserOptions: any,
parserOptions: ParserOptions,
): ExpressionParseResult<VSlotScopeExpression> {
debug('[script] parse slot-scope expression: "void function(%s) {}"', code)

Expand Down
Loading