Skip to content

Commit

Permalink
refactor: use @babel/parser
Browse files Browse the repository at this point in the history
  • Loading branch information
geekdada committed Jun 17, 2023
1 parent b174e14 commit 0a13a1c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
12 changes: 10 additions & 2 deletions src/utils/__tests__/remote-snippet.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,8 @@ test('parseMacro', (t) => {
t.throws(
() => {
utils.parseMacro(`
{% macro wrong(rule1, rule2) %}{% endmacro %}
{% macro wrong_function_name(rule1, rule2) %}
{% endmacro %}
`)
},
undefined,
Expand All @@ -176,7 +177,8 @@ test('parseMacro', (t) => {
t.throws(
() => {
utils.parseMacro(`
{% macro main %}{% endmacro %}
{% macro main %}
{% endmacro %}
`)
},
undefined,
Expand All @@ -190,4 +192,10 @@ test('parseMacro', (t) => {
undefined,
'该片段不包含可用的宏',
)
t.notThrows(() => {
utils.parseMacro(`
{% macro main(rule1, rule2) %}
{% endmacro %}
`)
})
})
18 changes: 14 additions & 4 deletions src/utils/remote-snippet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import Bluebird from 'bluebird'
import { logger } from '@surgio/logger'
import detectNewline from 'detect-newline'
import nunjucks from 'nunjucks'
import * as parser from '@typescript-eslint/parser'
import * as babelParser from '@babel/parser'

import { CACHE_KEYS } from '../constant'
import { RemoteSnippet, RemoteSnippetConfig } from '../types'
Expand All @@ -26,10 +26,14 @@ export const parseMacro = (
throw new Error('该片段不包含可用的宏')
}

const ast = parser.parse(match[1], { ecmaVersion: 6 })
const ast = babelParser.parse(match[1], {})
let statement

for (const node of ast.body) {
if (ast.errors.length) {
throw new Error('该片段不包含可用的宏')
}

for (const node of ast.program.body) {
if (node.type === 'ExpressionStatement') {
statement = node
break
Expand All @@ -44,7 +48,13 @@ export const parseMacro = (
) {
return {
functionName: statement.expression.callee.name,
arguments: statement.expression.arguments.map((item: any) => item.name),
arguments: statement.expression.arguments.map((item) => {
if (item.type === 'Identifier') {
return item.name
} else {
throw new Error('该片段不包含可用的宏')
}
}),
}
}

Expand Down

0 comments on commit 0a13a1c

Please sign in to comment.