Skip to content

Commit

Permalink
fix: change parse function interface
Browse files Browse the repository at this point in the history
  • Loading branch information
kazupon committed Dec 11, 2024
1 parent 0e6affd commit 4825e6e
Show file tree
Hide file tree
Showing 6 changed files with 52 additions and 29 deletions.
2 changes: 1 addition & 1 deletion packages/svelte-sfc-compiler/src/compileTemplate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ function doCompileTemplate({
scopeId: scoped ? longId : undefined,
slotted,
sourceMap: true,
parser: (source: string) => templateCompiler.parse(source).html,
parser: (source: string) => templateCompiler.parse(source),
...compilerOptions,
hmr: !isProd,
// eslint-disable-next-line unicorn/prefer-spread -- FIXME: spread operator
Expand Down
6 changes: 4 additions & 2 deletions packages/svelte-template-compiler/src/compile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { parse } from 'svelte/compiler'
import { describe, expect, test, vi } from 'vitest'
import { compile } from './compile.ts'

import type { SvelteCompilerResult } from './compile.ts'

const svelteCode = `
<script>
let count = 0
Expand All @@ -19,7 +21,7 @@ describe('compile', () => {
test('source code', () => {
const { code } = compile(svelteCode, {
sourceMap: true,
parser: (source: string) => parse(source).html
parser: (source: string) => parse(source) as SvelteCompilerResult
})
expect(code).toMatchSnapshot('code')
expect(code).contains(`_renderEffect(() => _setText(n1, "\\n count is ", count, "\\n"))`)
Expand All @@ -37,7 +39,7 @@ describe('compile', () => {
test('error', () => {
const onError = vi.fn()
const { code: _ } = compile('<p>{@html}</p>', {
parser: (source: string) => parse(source).html,
parser: (source: string) => parse(source) as SvelteCompilerResult,
onError
})
expect(onError).toHaveBeenCalled()
Expand Down
57 changes: 38 additions & 19 deletions packages/svelte-template-compiler/src/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ import type {
VaporCodegenResult,
RootIRNode as VaporRootIRNode
} from '@vue-vapor/compiler-vapor'
import type { RootNode, SvelteCompileError, SvelteTemplateNode } from './ir/index.ts'
import type { RootNode, SvelteCompileError, SvelteStyle, SvelteTemplateNode } from './ir/index.ts'
import type { DirectiveTransform, HackOptions, NodeTransform } from './transforms/index.ts'

// Svelte Template Code / Svelte Template AST -> IR (transform) -> JS (generate)
Expand Down Expand Up @@ -61,9 +61,12 @@ export function compile(
prefixIdentifiers
})

let svelteAst = {} as SvelteTemplateNode
let svelteTemplateAst = {} as SvelteTemplateNode
let svelteStyleAst: SvelteStyle | undefined
try {
svelteAst = parse(source, resolvedOptions)
const ret = parse(source, resolvedOptions)
svelteTemplateAst = ret.html
svelteStyleAst = ret.css
} catch (error: unknown) {
if (isSvelteParseError(error) && isString(source)) {
const vaporError = error as unknown as CompilerError
Expand All @@ -76,7 +79,7 @@ export function compile(

const ast: RootNode = {
type: IRNodeTypes.ROOT,
children: svelteAst.children || [],
children: svelteTemplateAst.children || [],
source: isString(source) ? source : '', // TODO:
components: [],
directives: [],
Expand All @@ -97,15 +100,31 @@ export function compile(
{},
directiveTransforms,
options.directiveTransforms || {} // user transforms
)
),
css: svelteStyleAst
})
)

return generate(ir as unknown as VaporRootIRNode, resolvedOptions)
}

function parse(source: string | SvelteTemplateNode, options: CompilerOptions): SvelteTemplateNode {
return isString(source) ? getSvelteTemplateNode(source, options) : source
function parse(
source: string | SvelteTemplateNode,
{ parser, css }: SvelteCompilerOptions
): SvelteCompilerResult {
if (isString(source)) {
if (!parser) {
throw new Error('"parser" option is not given.')
}
const ret = parser(source)
ret.css ||= css
return ret
} else {
return {
html: source,
css
}
}
}

function convertToVaporCompileErrorSourceLocation(
Expand All @@ -127,23 +146,23 @@ function convertToVaporCompileErrorSourceLocation(
}
}

function getSvelteTemplateNode(
source: string,
{ parser }: SvelteCompilerOptions
): SvelteTemplateNode {
if (!parser) {
throw new Error('svelte code parsing function option is not given.')
}
return parser(source)
}

interface SvelteCompilerOptions {
/**
* Svelte parser
* @param source - Svelte code
* @returns Svelte template AST
* @returns Svelte AST, which has svelte template ast and svelte style ast optionally
*/
parser?: (source: string) => SvelteCompilerResult
/**
* Svelte AST style
* @description if your parser does not return svelte style ast, this option will be used as svelte style ast
*/
parser?: (source: string) => SvelteTemplateNode
css?: SvelteStyle
}

export type SvelteCompilerResult = {
html: SvelteTemplateNode
css?: SvelteStyle
}

export type CompilerOptions = HackOptions<BaseCompilerOptions> & SvelteCompilerOptions
Expand Down
6 changes: 4 additions & 2 deletions packages/svelte-template-compiler/src/transforms/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import type {
RootIRNode,
RootNode,
SvelteComment,
SvelteStyle,
SvelteTemplateNode
} from '../ir'
import type { HackOptions } from './types'
Expand All @@ -46,10 +47,11 @@ const defaultOptions = {
inline: false,
isTS: false,
onError: defaultOnError,
onWarn: defaultOnWarn
onWarn: defaultOnWarn,
css: null // eslint-disable-line unicorn/no-null
}

export type TransformOptions = HackOptions<BaseTransformOptions>
export type TransformOptions = HackOptions<BaseTransformOptions> & { css?: SvelteStyle }

export class TransformContext<T extends BlockIRNode['node'] = BlockIRNode['node']> {
ir: RootIRNode
Expand Down
8 changes: 4 additions & 4 deletions packages/svelte-template-compiler/src/transforms/element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ import type { NodeTransform } from './types.ts'

export const transformElement: NodeTransform = (_node, context) => {
if (__DEV__) {
console.log('transformElement', context.node.type)
// console.log('transformElement', context.node.type, context.node?.name)
// console.log('transformElement', context.node.type)
console.log('transformElement', context.node.type, context.node?.name)

Check failure on line 46 in packages/svelte-template-compiler/src/transforms/element.ts

View workflow job for this annotation

GitHub Actions / Type checking (ubuntu-latest, 18)

Property 'name' does not exist on type 'RootNode | TemplateNode'.
}

return function postTransformElement() {
Expand Down Expand Up @@ -192,7 +192,7 @@ function transformNativeElement(
template += ` ${scopeId}`
}

// console.log('transformElement building template ...', tag, JSON.stringify(propsResult))
console.log('transformElement building template ...', tag, JSON.stringify(propsResult))

let staticProps = false
const dynamicProps: string[] = []
Expand Down Expand Up @@ -239,7 +239,7 @@ function transformNativeElement(
template += `</${tag}>`
}

// console.log('transformElement exit', tag, template, context.childrenTemplate)
console.log('transformElement exit', tag, template, context.childrenTemplate)

if (
context.parent &&
Expand Down
2 changes: 1 addition & 1 deletion packages/svelte-template-explorer/src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export const defaultOptions: CompilerOptions = {
ssrCssVars: `{ color }`,
whitespace: 'condense',
parser(source) {
return parse(source).html
return parse(source)
}
}

Expand Down

0 comments on commit 4825e6e

Please sign in to comment.