Thanks to visit codestin.com
Credit goes to github.com

Skip to content
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
2 changes: 2 additions & 0 deletions .changeset/shy-impalas-shake.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
---
50 changes: 26 additions & 24 deletions packages/labs/compiler/src/lib/template-transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
TemplatePart,
} from './ast-fragments.js';
import {isCommentNode, isTextNode, traverse} from '@parse5/tools';
import {getTypeChecker} from './type-checker.js';
const {getTemplateHtml, markerMatch, marker} = litHtmlPrivate;

interface TemplateInfo {
Expand Down Expand Up @@ -65,7 +66,7 @@ class CompiledTemplatePass {
context: ts.TransformationContext
): ts.Transformer<ts.SourceFile> => {
return (sourceFile: ts.SourceFile): ts.SourceFile => {
const pass = new CompiledTemplatePass(context);
const pass = new CompiledTemplatePass(context, sourceFile);
pass.findTemplates(sourceFile);
const transformedSourceFile = pass.rewriteTemplates(sourceFile);
if (!ts.isSourceFile(transformedSourceFile)) {
Expand All @@ -81,11 +82,15 @@ class CompiledTemplatePass {
/**
* Map top level statements to templates marked for compilation.
*/
private topLevelStatementToTemplate = new Map<ts.Statement, TemplateInfo[]>();
private readonly topLevelStatementToTemplate = new Map<
ts.Statement,
TemplateInfo[]
>();
/**
* Map an `html` tagged template expression to the template info.
* Map an `html` tagged template expression to the template info for each
* template to compile.
*/
private expressionToTemplate = new Map<
private readonly expressionToTemplate = new Map<
ts.TaggedTemplateExpression,
TemplateInfo
>();
Expand All @@ -97,9 +102,18 @@ class CompiledTemplatePass {
* Unique security brand identifier. Used as the tag function for the prepared
* HTML.
*/
private securityBrandIdent: ts.Identifier;
private constructor(private readonly context: ts.TransformationContext) {
private readonly securityBrandIdent: ts.Identifier;
/**
* Type checker which can be used to query if a tagged template expression is
* a lit template.
*/
private readonly checker: ReturnType<typeof getTypeChecker>;
private constructor(
private readonly context: ts.TransformationContext,
sourceFile: ts.SourceFile
) {
this.securityBrandIdent = context.factory.createUniqueName('b');
this.checker = getTypeChecker(sourceFile.fileName, sourceFile.text);
}

/**
Expand All @@ -117,7 +131,10 @@ class CompiledTemplatePass {
const findTemplates = <T extends ts.Node>(node: T) => {
return ts.visitNode(node, (node: ts.Node): ts.Node => {
nodeStack.push(node);
if (isLitTemplate(node)) {
if (
ts.isTaggedTemplateExpression(node) &&
this.checker.isLitTaggedTemplateExpression(node)
) {
const topStatement = nodeStack[1] as ts.Statement;
const templateInfo = {
topStatement,
Expand Down Expand Up @@ -328,15 +345,12 @@ class CompiledTemplatePass {
node: ts.Node
): ts.Node {
const f = this.context.factory;
if (!isLitTemplate(node)) {
if (!ts.isTaggedTemplateExpression(node)) {
return node;
}

const templateInfo = this.expressionToTemplate.get(node);
if (templateInfo === undefined) {
throw new Error(
`Internal Error: template info not found for ${node.getText()}`
);
return node;
}
return createCompiledTemplateResult({
f,
Expand All @@ -348,15 +362,3 @@ class CompiledTemplatePass {

export const compileLitTemplates = (): ts.TransformerFactory<ts.SourceFile> =>
CompiledTemplatePass.getTransformer();

/**
* E.g. html`foo` or html`foo${bar}`
*
* TODO(ajakubowicz): Figure out how to handle detecting templates to compile
* correctly and robustly. We want to avoid situations where `html` imported
* from 'lit/static.js' is compiled.
*/
const isLitTemplate = (node: ts.Node): node is ts.TaggedTemplateExpression =>
ts.isTaggedTemplateExpression(node) &&
ts.isIdentifier(node.tag) &&
node.tag.escapedText === 'html';
217 changes: 217 additions & 0 deletions packages/labs/compiler/src/lib/type-checker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,217 @@
/**
* @license
* Copyright 2023 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/

import ts from 'typescript';

const compilerOptions = {
target: ts.ScriptTarget.ESNext,
module: ts.ModuleKind.ESNext,
skipDefaultLibCheck: true,
skipLibCheck: true,
moduleResolution: ts.ModuleResolutionKind.NodeNext,
};

export const getTypeChecker = (filename: string, source: string) => {
const languageServiceHost = new SingleFileLanguageServiceHost(
filename,
source
);
const languageService = ts.createLanguageService(
languageServiceHost,
ts.createDocumentRegistry()
);

const program = languageService.getProgram();
if (!program) {
throw new Error(`Internal Error: Could not start TypeScript program`);
}
return new TypeChecker(program.getTypeChecker());
};

/**
* Wrap ts.TypeChecker so we can provide a consistent and scoped API for the
* compiler.
*/
class TypeChecker {
private checker: ts.TypeChecker;
constructor(typeChecker: ts.TypeChecker) {
this.checker = typeChecker;
}

/**
* Use this method to find out if the passed in tagged template expression a
* compilable `lit` html template.
*
* The logic is strict, only marking a template compilable if it is
*
* @param node tagged template expression
* @returns if the tagged template expression is a lit template that can be
* compiled.
*/
isLitTaggedTemplateExpression(node: ts.TaggedTemplateExpression): boolean {
if (ts.isIdentifier(node.tag)) {
return this.isResolvedIdentifierLitHtmlTemplate(node.tag);
}
if (ts.isPropertyAccessExpression(node.tag)) {
return this.isResolvedPropertyAccessExpressionLitHtmlNamespace(node.tag);
}
return false;
}

/**
* Resolve the tag function identifier back to an import, returning true if
* the original reference was the `html` export from `lit` or `lit-html`.
*
* This check handles: aliasing and reassigning the import.
*
* ```ts
* import {html as h} from 'lit';
* h``;
* // isResolvedIdentifierLitHtmlTemplate(<h ast node>) returns true
* ```
*
* ```ts
* import {html} from 'lit-html/static.js';
* html`false`;
* // isResolvedIdentifierLitHtmlTemplate(<html ast node>) returns false
* ```
*
* @param node a TaggedTemplateExpression tag
*/
private isResolvedIdentifierLitHtmlTemplate(node: ts.Identifier): boolean {
const checker = this.checker;

const symbol = checker.getSymbolAtLocation(node);
if (!symbol) {
return false;
}
const templateImport = symbol.declarations?.[0];
if (!templateImport || !ts.isImportSpecifier(templateImport)) {
return false;
}

if (
templateImport.propertyName &&
templateImport.propertyName.text !== 'html'
) {
return false;
}
const namedImport = templateImport.parent;
if (!ts.isNamedImports(namedImport)) {
return false;
}
const importClause = namedImport.parent;
if (!ts.isImportClause(importClause)) {
return false;
}
const importDeclaration = importClause.parent;
if (!ts.isImportDeclaration(importDeclaration)) {
return false;
}
const specifier = importDeclaration.moduleSpecifier;
if (!ts.isStringLiteral(specifier)) {
return false;
}
return this.isLitTemplateModuleSpecifier(specifier.text);
}

/**
* Resolve a common pattern of using the `html` identifier of a lit namespace
* import.
*
* E.g.:
*
* ```ts
* import * as identifier from 'lit';
* identifier.html`<p>I am compiled!</p>`;
* ```
*/
private isResolvedPropertyAccessExpressionLitHtmlNamespace(
node: ts.PropertyAccessExpression
): boolean {
// Ensure propertyAccessExpression ends with `.html`.
if (ts.isIdentifier(node.name) && node.name.text !== 'html') {
return false;
}
// Expect a namespace preceding `html`, `<namespace>.html`.
if (!ts.isIdentifier(node.expression)) {
return false;
}

// Resolve the namespace if it has been aliased.
const checker = this.checker;
const symbol = checker.getSymbolAtLocation(node.expression);
if (!symbol) {
return false;
}
const namespaceImport = symbol.declarations?.[0];
if (!namespaceImport || !ts.isNamespaceImport(namespaceImport)) {
return false;
}
const importDeclaration = namespaceImport.parent.parent;
const specifier = importDeclaration.moduleSpecifier;
if (!ts.isStringLiteral(specifier)) {
return false;
}
return this.isLitTemplateModuleSpecifier(specifier.text);
}

private isLitTemplateModuleSpecifier(specifier: string): boolean {
return (
specifier === 'lit' ||
specifier === 'lit-html' ||
specifier === 'lit-element'
);
}
}

/**
* A simple LanguageServiceHost used for simple, single file, one-time
* transforms.
*/
class SingleFileLanguageServiceHost implements ts.LanguageServiceHost {
private compilerOptions: ts.CompilerOptions = compilerOptions;

private filename: string;
private source: string;

constructor(filename: string, source: string) {
this.filename = filename;
this.source = source;
}

getCompilationSettings(): ts.CompilerOptions {
return this.compilerOptions;
}
getScriptFileNames(): string[] {
return [this.filename];
}
getScriptVersion(_: string): string {
return '-1';
}
getScriptSnapshot(filename: string): ts.IScriptSnapshot | undefined {
const contents = this.readFile(filename);
if (contents === undefined) {
return undefined;
}
return ts.ScriptSnapshot.fromString(contents);
}
getCurrentDirectory(): string {
return '.';
}
getDefaultLibFileName(options: ts.CompilerOptions): string {
return ts.getDefaultLibFilePath(options);
}
readFile(filename: string): string | undefined {
if (!this.fileExists(filename)) {
return undefined;
}
return this.source;
}
fileExists(filename: string): boolean {
return this.filename === filename;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { html } from 'lit-element';
const b_1 = i => i;
const lit_template_1 = { h: b_1 `I compile`, parts: [] };
({ ["_$litType$"]: lit_template_1, values: [] });
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import {html} from 'lit-element';
html`I compile`;
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { html } from 'lit';
import * as litStatic from 'lit-html/static.js';
function trickyTemplate() {
const html = litStatic.html;
return html `Do not compile me, I am static!`;
}
const b_1 = i => i;
const lit_template_1 = { h: b_1 `Compile me!`, parts: [] };
({ ["_$litType$"]: lit_template_1, values: [] });
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { html } from 'lit';
import * as litStatic from 'lit-html/static.js';

function trickyTemplate() {
const html = litStatic.html;
return html`Do not compile me, I am static!`;
}

html`Compile me!`;
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { svg as html, html as svg } from 'lit';
html `<text>Do not compile me, I am an svg</text>`;
const b_1 = i => i;
const lit_template_1 = { h: b_1 `<p>Compiled me, I am an html template</p>`, parts: [] };
({ ["_$litType$"]: lit_template_1, values: [] });
4 changes: 4 additions & 0 deletions packages/labs/compiler/test_files/handle_aliased_imports.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import {svg as html, html as svg} from 'lit';

html`<text>Do not compile me, I am an svg</text>`;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ha ha, great test!

svg`<p>Compiled me, I am an html template</p>`;
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { html as a } from 'lit';
// TODO: Renaming import outside the import declaration is not supported.
// These templates will not be optimized.
const b = a;
const c = b;
let g = 1, d = c, f = 1;
d `Compile me!`;
d = (i) => i;
d `Do not compile me!`;
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import {html as a} from 'lit';
// TODO: Renaming import outside the import declaration is not supported.
// These templates will not be optimized.

const b = a;
const c = b;
let g = 1,
d = c,
f = 1;

d`Compile me!`;


d = (i) => i;
d`Do not compile me!`;

Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import * as lit from 'lit';
const b_1 = i => i;
const lit_template_1 = { h: b_1 `<p>Compile me!</p>`, parts: [] };
({ ["_$litType$"]: lit_template_1, values: [] });
let renamed = lit;
// TODO: Renaming namespaces not currently handled.
renamed.html `Compile me!`;
renamed = { html: (i) => i };
renamed.html `Do not compile me!`;
Loading