feat(ivy): detect cycles and use remote scoping of components if needed (#28169)

By its nature, Ivy alters the import graph of a TS program, adding imports
where template dependencies exist. For example, if ComponentA uses PipeB
in its template, Ivy will insert an import of PipeB into the file in which
ComponentA is declared.

Any insertion of an import into a program has the potential to introduce a
cycle into the import graph. If for some reason the file in which PipeB is
declared imports the file in which ComponentA is declared (maybe it makes
use of a service or utility function that happens to be in the same file as
ComponentA) then this could create an import cycle. This turns out to
happen quite regularly in larger Angular codebases.

TypeScript and the Ivy runtime have no issues with such cycles. However,
other tools are not so accepting. In particular the Closure Compiler is
very anti-cycle.

To mitigate this problem, it's necessary to detect when the insertion of
an import would create a cycle. ngtsc can then use a different strategy,
known as "remote scoping", instead of directly writing a reference from
one component to another. Under remote scoping, a function
'setComponentScope' is called after the declaration of the component's
module, which does not require the addition of new imports.

FW-647 #resolve

PR Close #28169
This commit is contained in:
Alex Rickabaugh
2019-01-15 12:32:10 -08:00
committed by Jason Aden
parent cac9199d7c
commit 7d954dffd0
27 changed files with 1049 additions and 23 deletions

View File

@ -0,0 +1,88 @@
package(default_visibility = ["//visibility:public"])
load("//tools:defaults.bzl", "jasmine_node_test", "ng_module", "ng_rollup_bundle", "ts_library")
load("//tools/symbol-extractor:index.bzl", "js_expected_symbol_test")
load("//tools/http-server:http_server.bzl", "http_server")
ng_module(
name = "cyclic_import",
srcs = [
"index.ts",
"trigger.ts",
],
tags = [
"ivy-only",
],
deps = [
"//packages/core",
],
)
ng_rollup_bundle(
name = "bundle",
# TODO(alexeagle): This is inconsistent.
# We try to teach users to always have their workspace at the start of a
# path, to disambiguate from other workspaces.
# Here, the rule implementation is looking in an execroot where the layout
# has an "external" directory for external dependencies.
# This should probably start with "angular/" and let the rule deal with it.
entry_point = "packages/core/test/bundling/cyclic_import/index.js",
tags = [
"ivy-only",
],
deps = [
":cyclic_import",
"//packages/core",
],
)
ts_library(
name = "test_lib",
testonly = True,
srcs = glob(["*_spec.ts"]),
tags = [
"ivy-only",
],
deps = [
"//packages:types",
"//packages/compiler",
"//packages/core/testing",
"//packages/private/testing",
],
)
jasmine_node_test(
name = "test",
data = [
":bundle",
":bundle.js",
":bundle.min.js.br",
":bundle.min_debug.js",
],
tags = [
"ivy-only",
],
deps = [":test_lib"],
)
js_expected_symbol_test(
name = "symbol_test",
src = ":bundle.min_debug.js",
golden = ":bundle.golden_symbols.json",
tags = [
"ivy-aot",
"ivy-only",
],
)
http_server(
name = "devserver",
data = [
"index.html",
":bundle.min.js",
":bundle.min_debug.js",
],
tags = [
"ivy-only",
],
)

View File

@ -0,0 +1,22 @@
# Purpose
This test exists to validate that ngtsc, when compiling an application where Ivy would otherwise
require a circular dependency, uses "remote scoping" via the `setComponentScope` function instead.
# How it works
There are two files, `index.ts` and `trigger.ts`. `index.ts` contains the NgModule and a simple
component (`<dep>`).
`trigger.ts` contains a component `TriggerComponent` that uses `<dep>` in its template. Normally,
Ivy would want `DepComponent` to be listed in `TriggerComponent`'s definition. However, this
requires adding an import from `trigger.ts` -> `index.ts`, and there's already an import from
`index.ts` to `trigger.ts` (for the NgModule).
In this case, ngtsc decides to set the directives in `TriggerComponent`'s definition via a different
mechanism: remote scoping. Alongside the NgModule (in `index.ts`) a call to `setComponentScope` is
generated which sets up `TriggerComponent`'s definition correctly, without introducing any imports.
This call is not tree-shakeable, but does not create a cycle.
The symbol test here verifies that `setComponentScope` is used, and the e2e spec verifies that the
application works correctly.

View File

@ -0,0 +1,644 @@
[
{
"name": "ACTIVE_INDEX"
},
{
"name": "ANIMATION_PROP_PREFIX"
},
{
"name": "BINDING_INDEX"
},
{
"name": "BLOOM_MASK"
},
{
"name": "CLEAN_PROMISE"
},
{
"name": "CONTAINER_INDEX"
},
{
"name": "CONTEXT"
},
{
"name": "ChangeDetectionStrategy"
},
{
"name": "DECLARATION_VIEW"
},
{
"name": "DepComponent"
},
{
"name": "EMPTY_ARRAY"
},
{
"name": "EMPTY_OBJ"
},
{
"name": "EmptyErrorImpl"
},
{
"name": "FLAGS"
},
{
"name": "FactoryPrototype"
},
{
"name": "HEADER_OFFSET"
},
{
"name": "HOST"
},
{
"name": "HOST_NODE"
},
{
"name": "INJECTOR"
},
{
"name": "INJECTOR_BLOOM_PARENT_SIZE"
},
{
"name": "LCONTAINER_LENGTH"
},
{
"name": "MONKEY_PATCH_KEY_NAME"
},
{
"name": "Module"
},
{
"name": "NATIVE"
},
{
"name": "NEXT"
},
{
"name": "NG_COMPONENT_DEF"
},
{
"name": "NG_DIRECTIVE_DEF"
},
{
"name": "NG_ELEMENT_ID"
},
{
"name": "NG_PIPE_DEF"
},
{
"name": "NG_PROJECT_AS_ATTR_NAME"
},
{
"name": "NG_TEMPLATE_SELECTOR"
},
{
"name": "NO_CHANGE"
},
{
"name": "NO_PARENT_INJECTOR"
},
{
"name": "NodeInjectorFactory"
},
{
"name": "ObjectUnsubscribedErrorImpl"
},
{
"name": "PARENT"
},
{
"name": "PARENT_INJECTOR"
},
{
"name": "QUERIES"
},
{
"name": "RENDERER"
},
{
"name": "RENDERER_FACTORY"
},
{
"name": "RendererStyleFlags3"
},
{
"name": "SANITIZER"
},
{
"name": "TAIL"
},
{
"name": "TVIEW"
},
{
"name": "TriggerComponent"
},
{
"name": "UnsubscriptionErrorImpl"
},
{
"name": "VIEWS"
},
{
"name": "ViewEncapsulation"
},
{
"name": "__self"
},
{
"name": "__values"
},
{
"name": "__window"
},
{
"name": "_currentNamespace"
},
{
"name": "_global"
},
{
"name": "_renderCompCount"
},
{
"name": "addComponentLogic"
},
{
"name": "addToViewTree"
},
{
"name": "allocStylingContext"
},
{
"name": "appendChild"
},
{
"name": "attachPatchData"
},
{
"name": "baseResolveDirective"
},
{
"name": "bloomAdd"
},
{
"name": "cacheMatchingLocalNames"
},
{
"name": "callHooks"
},
{
"name": "checkNoChangesMode"
},
{
"name": "checkView"
},
{
"name": "componentRefresh"
},
{
"name": "createDirectivesAndLocals"
},
{
"name": "createEmptyStylingContext"
},
{
"name": "createLView"
},
{
"name": "createNodeAtIndex"
},
{
"name": "createRootComponent"
},
{
"name": "createRootComponentView"
},
{
"name": "createRootContext"
},
{
"name": "createTNode"
},
{
"name": "createTView"
},
{
"name": "createTextNode"
},
{
"name": "createViewBlueprint"
},
{
"name": "decreaseElementDepthCount"
},
{
"name": "defaultScheduler"
},
{
"name": "defineComponent"
},
{
"name": "defineInjector"
},
{
"name": "defineNgModule"
},
{
"name": "diPublicInInjector"
},
{
"name": "domRendererFactory3"
},
{
"name": "element"
},
{
"name": "elementCreate"
},
{
"name": "elementEnd"
},
{
"name": "elementStart"
},
{
"name": "enterView"
},
{
"name": "executeHooks"
},
{
"name": "executeInitHooks"
},
{
"name": "executeViewQueryFn"
},
{
"name": "extractDirectiveDef"
},
{
"name": "extractPipeDef"
},
{
"name": "findAttrIndexInNode"
},
{
"name": "findDirectiveMatches"
},
{
"name": "firstTemplatePass"
},
{
"name": "generateExpandoInstructionBlock"
},
{
"name": "generateInitialInputs"
},
{
"name": "generatePropertyAliases"
},
{
"name": "getBeforeNodeForView"
},
{
"name": "getBindingsEnabled"
},
{
"name": "getCheckNoChangesMode"
},
{
"name": "getClosureSafeProperty"
},
{
"name": "getComponentDef"
},
{
"name": "getComponentViewByIndex"
},
{
"name": "getContainerRenderParent"
},
{
"name": "getDirectiveDef"
},
{
"name": "getElementDepthCount"
},
{
"name": "getFirstTemplatePass"
},
{
"name": "getHighestElementOrICUContainer"
},
{
"name": "getHostNative"
},
{
"name": "getInitialClassNameValue"
},
{
"name": "getInjectorIndex"
},
{
"name": "getIsParent"
},
{
"name": "getLContainer"
},
{
"name": "getLView"
},
{
"name": "getLViewChild"
},
{
"name": "getNativeAnchorNode"
},
{
"name": "getNativeByTNode"
},
{
"name": "getNodeInjectable"
},
{
"name": "getOrCreateNodeInjectorForNode"
},
{
"name": "getOrCreateTView"
},
{
"name": "getParentInjectorIndex"
},
{
"name": "getParentInjectorLocation"
},
{
"name": "getParentInjectorView"
},
{
"name": "getParentInjectorViewOffset"
},
{
"name": "getPipeDef"
},
{
"name": "getPreviousOrParentTNode"
},
{
"name": "getRenderFlags"
},
{
"name": "getRenderParent"
},
{
"name": "getRootContext"
},
{
"name": "getRootView"
},
{
"name": "getStylingContext"
},
{
"name": "getTNode"
},
{
"name": "hasClassInput"
},
{
"name": "hasParentInjector"
},
{
"name": "hasStyling"
},
{
"name": "hasTagAndTypeMatch"
},
{
"name": "includeViewProviders"
},
{
"name": "increaseElementDepthCount"
},
{
"name": "initNodeFlags"
},
{
"name": "initializeStaticContext"
},
{
"name": "initializeTNodeInputs"
},
{
"name": "insertBloom"
},
{
"name": "instantiateAllDirectives"
},
{
"name": "instantiateRootComponent"
},
{
"name": "invertObject"
},
{
"name": "invokeDirectivesHostBindings"
},
{
"name": "isAnimationProp"
},
{
"name": "isComponentDef"
},
{
"name": "isContentQueryHost"
},
{
"name": "isCreationMode"
},
{
"name": "isCssClassMatching"
},
{
"name": "isFactory"
},
{
"name": "isNodeMatchingSelector"
},
{
"name": "isNodeMatchingSelectorList"
},
{
"name": "isPositive"
},
{
"name": "isProceduralRenderer"
},
{
"name": "isRootView"
},
{
"name": "isStylingContext"
},
{
"name": "leaveView"
},
{
"name": "locateHostElement"
},
{
"name": "namespaceHTML"
},
{
"name": "nativeAppendChild"
},
{
"name": "nativeAppendOrInsertBefore"
},
{
"name": "nativeInsertBefore"
},
{
"name": "nativeParentNode"
},
{
"name": "nextNgElementId"
},
{
"name": "noSideEffects"
},
{
"name": "postProcessBaseDirective"
},
{
"name": "postProcessDirective"
},
{
"name": "queueComponentIndexForCheck"
},
{
"name": "readClassValueFromTNode"
},
{
"name": "readElementValue"
},
{
"name": "readPatchedData"
},
{
"name": "readPatchedLView"
},
{
"name": "refreshChildComponents"
},
{
"name": "refreshContentQueries"
},
{
"name": "refreshDescendantViews"
},
{
"name": "refreshDynamicEmbeddedViews"
},
{
"name": "registerPostOrderHooks"
},
{
"name": "registerPreOrderHooks"
},
{
"name": "renderComponent"
},
{
"name": "renderComponentOrTemplate"
},
{
"name": "renderEmbeddedTemplate"
},
{
"name": "renderInitialStylesAndClasses"
},
{
"name": "renderInitialStylingValues"
},
{
"name": "renderStringify"
},
{
"name": "resetComponentState"
},
{
"name": "resolveDirectives"
},
{
"name": "saveNameToExportMap"
},
{
"name": "saveResolvedLocalsInData"
},
{
"name": "setBindingRoot"
},
{
"name": "setClass"
},
{
"name": "setComponentScope"
},
{
"name": "setCurrentDirectiveDef"
},
{
"name": "setCurrentViewQueryIndex"
},
{
"name": "setFirstTemplatePass"
},
{
"name": "setHostBindings"
},
{
"name": "setIncludeViewProviders"
},
{
"name": "setInjectImplementation"
},
{
"name": "setInputsForProperty"
},
{
"name": "setInputsFromAttrs"
},
{
"name": "setIsParent"
},
{
"name": "setPreviousOrParentTNode"
},
{
"name": "setStyle"
},
{
"name": "setTNodeAndViewData"
},
{
"name": "setUpAttributes"
},
{
"name": "syncViewWithBlueprint"
},
{
"name": "text"
},
{
"name": "throwMultipleComponentError"
},
{
"name": "tickRootContext"
},
{
"name": "viewAttached"
}
]

View File

@ -0,0 +1,31 @@
<!doctype html>
<html>
<head>
<title>Angular Cyclic Import Example</title>
</head>
<body>
<!-- The Angular application will be bootstrapped into this element. -->
<trigger></trigger>
<!--
Script tag which bootstraps the application. Use `?debug` in URL to select
the debug version of the script.
There are two scripts sources: `bundle.min.js` and `bundle.min_debug.js` You can
switch between which bundle the browser loads to experiment with the application.
- `bundle.min.js`: Is what the site would serve to their users. It has gone
through rollup, build-optimizer, and uglify with tree shaking.
- `bundle.min_debug.js`: Is what the developer would like to see when debugging
the application. It has also done through full pipeline of rollup, build-optimizer,
and uglify, however special flags were passed to uglify to prevent inlining and
property renaming.
-->
<script>
document.write('<script src="' +
(document.location.search.endsWith('debug') ? '/bundle.min_debug.js' : '/bundle.min.js') +
'"></' + 'script>');
</script>
</body>
</html>

View File

@ -0,0 +1,26 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Component, NgModule, ɵrenderComponent as renderComponent} from '@angular/core';
import {TriggerComponent} from './trigger';
@Component({
selector: 'dep',
template: 'dep',
})
export class DepComponent {
}
@NgModule({
declarations: [DepComponent, TriggerComponent],
})
export class Module {
}
renderComponent(TriggerComponent);

View File

@ -0,0 +1,41 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import '@angular/compiler';
import {withBody} from '@angular/private/testing';
import * as fs from 'fs';
import * as path from 'path';
const UTF8 = {
encoding: 'utf-8'
};
const PACKAGE = 'angular/packages/core/test/bundling/cyclic_import';
describe('treeshaking with uglify', () => {
let content: string;
const contentPath = require.resolve(path.join(PACKAGE, 'bundle.min_debug.js'));
beforeAll(() => { content = fs.readFileSync(contentPath, UTF8); });
describe('functional test in domino', () => {
it('should render hello world when not minified', withBody('<trigger></trigger>', () => {
require(path.join(PACKAGE, 'bundle.js'));
expect(document.body.textContent).toEqual('dep');
}));
it('should render hello world when debug minified', withBody('<trigger></trigger>', () => {
require(path.join(PACKAGE, 'bundle.min_debug.js'));
expect(document.body.textContent).toEqual('dep');
}));
it('should render hello world when fully minified', withBody('<trigger></trigger>', () => {
require(path.join(PACKAGE, 'bundle.min.js'));
expect(document.body.textContent).toEqual('dep');
}));
});
});

View File

@ -0,0 +1,16 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Component} from '@angular/core';
@Component({
selector: 'trigger',
template: '<dep></dep>',
})
export class TriggerComponent {
}