Alex Rickabaugh
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee
  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Undecorated Classes: Migration Checklist Owner: Alex R Date: 6/26/19 #### Related design docs: - [Original problem description](https://hackmd.io/Ihp4YWMoQ1e1nbSbg7HStA?view) - [Design for Ivy code changes](https://hackmd.io/wuNqEgYCQc2tZBr0dpaWHQ?view) ## Design This proposal discusses migration of inheritance patterns which are problematic in Ivy. There are two kinds of such patterns: 1. Inheritance of a constructor from a base class which is not decoratored. ```typescript export class BasePlain { constructor(private vcr: ViewContainerRef) {} } @Directive({selector: '[blah]'}) export class DerivedDir extends BasePlain {} ``` This is hereafter referred to as the "Undecorated Parent" pattern. 2. Inheritance from a decorated to an undecorated class. ```typescript @Directive({selector: '[blah]'}) export class BaseDir { ... } export class DerivedPlain extends BaseDir {} ``` This is hereafter referred to as the "Undecorated Child" pattern. Both of these cases are somewhat problematic in View Engine JIT mode if no other decorators are found on the class, as the TypeScript compiler does not emit the relevant decorator metadata. In AOT mode (for example, all of g3), the compiler handles these cases just fine. ### Why a migration? The tl;dr answer is "locality". Ivy's model is that the Angular behavior of a directive is described by its `ngDirectiveDef` (or `ngComponentDef` in the case of a component). #### Undecorated Parent For the "undecorated parent" case, when compiling a `DerivedDir` class which extends an undecorated `BasePlain` class, the compiler needs to generate a `ngDirectiveDef` for `Derived`. In particular, it needs to generate a `factory` function that creates instances of `DerivedDir`. If `DerivedDir` has a constructor, this is trivial. The `factory` function will invoke `new DerivedDir(...)` with injected constructor parameters, and the `BasePlain` superclass is irrelevant. If `DerivedDir` has no constructor, then we have a problem. The compiler has two choices: 1) Figure out the parameters to the constructor, and write a `factory` that calls `new DerivedDir(...)` and injects them. :::danger This is a locality violation - the compilation of `DerivedDir` shouldn't depend on metadata about `BasePlain`, which may come from an upstream library and may be changed in a future version of that library. ::: 2) Delegate construction of the instance to the `factory` for `BasePlain`, which has the constructor parameters. Another way of putting this is that if the constructor is inherited, the `factory` should be too. Ivy is set up to inherit this way, but this _requires that `Base` have a `factory` to begin with_. #### Undecorated Child In the undecorated child case, the problem is more subtle. Consider the `BaseDir`/`DerivedPlain` directive pair, and assume that `DerivedPlain` is ultimately used in a component `Cmp`'s template. `Cmp` will then have an `ngComponentDef`: ```typescript class Cmp { static ngComponentDef = defineComponent({ ..., directiveDefs: [DerivedPlain.ngDirectiveDef], }); } ``` Ivy records that `Cmp` makes use of `DerivedPlain` by linking its `ngDirectiveDef` in `Cmp.ngComponentDef.directiveDefs`. Since `DerivedPlain` has no `ngDirectiveDef` property (by virtue of not being decorated), that read falls through to the prototype at runtime. As a result, `BaseDir.ngDirectiveDef` is recorded in `Cmp`'s `directiveDefs`. Thus the information that `DerivedPlain` exists at all is lost to the runtime, which will instead incorrectly create instances of `BaseDir`. ### Impact We unfortunately do not have good numbers on the usage of inheritance in Angular. There are mitigating factors: 1. Externally, a lot of the problematic inheritance patterns don't work in JIT. This cuts down on the number of likely cases, as developers will not write code that doesn't work in Angular's dev mode. 2. Internally, there have been a medium number of occurrences of these issues. Internally JIT is not really used, so the mitigating effect of point #1 don't apply. Here is a TAP from a CL that adds a compiler error for undecorated directives: https://test.corp.google.com/ui#id=OCL:256186366:BASE:256186854:1562087174458:592e6647 It appears to affect a good chunk of Google3. ### Schematic Design This section focuses on the external schematic. Internally, the situation is a bit more complicated due to the division of targets. Both versions suffer from an issue of detecting when classes in dependencies are decorated. #### Detection within the compilation unit This is the most likely case externally. Within a given compilation unit (`tsconfig.json`) file, it's possible to construct a TypeScript `ts.Program` and discover any decorated classes that inherit from a base class. This chain can be walked to identify classes that either: * Are directives/components, but inherit a constructor from a class without a Directive/Component decorator (undecorated parent), or * Do not have a decorator, but inherit from a class which does (undecorated child) In the first case, the schematic can apply an `@Directive()` annotation to the parent class (without a selector). The compiler/runtime will support this (see [design doc](https://hackmd.io/wuNqEgYCQc2tZBr0dpaWHQ?view)). ```typescript @Directive() export class BasePlain { constructor(private vcr: ViewContainerRef) {} } @Directive({selector: '[blah]'}) export class DerivedDir extends BasePlain {} ``` In the second case, things are a bit trickier. The schematic will determine if metadata can be copied over. For example, in this hierarchy: ```typescript @Component({ selector: 'base-class', templateUrl: './base-class.html', }) export class Base {} export class Derived extends Base {} ``` None of the metadata for `Base` depends on imports, local variables, etc. so it can be cleanly copied to `Derived` (adjusting the paths if necessary). ```typescript @Component({ selector: 'base-class', templateUrl: './base-class.html', }) export class Base {} @Component({ selector: 'base-class', templateUrl: './base-class.html', }) export class Derived extends Base {} ``` ##### Problematic metadata Sometimes this won't be possible. Consider this base class: ```typescript import {SomeService} from './path/to/service'; export const TEMPLATE = '....'; @Component({ selector: 'base-class', providers: [SomeService], template: TEMPLATE, }) export class Base {} ``` Here, the metadata contains references to other symbols, some of which are imported and some which are exported from this file. If this metadata were copied to the `Derived` class, imports would need to be added for these symbols. Adding such imports is possible, but non-trivial due to concerns like path mapping. In rare cases like this, the schematic should add a decorator to the derived class with any metadata fields (e.g. `selector`) that can be copied, as well as comments for the fields that can't. For example: ```typescript @Component({ selector: 'base-class', // The following fields were copied from `Base`, but // imports need to be added manually. Please add any // required imports and uncomment the below lines: // // providers: [SomeService], // template: TEMPLATE, }) export class Derived {} ``` #### Inheritance hierarchies spanning dependencies In general, the question of "is this class an Angular directive/component" is hard for a schematic to answer. For classes in the compilation unit, with `.ts` source available, it's possible to detect the presence of an Angular decorator. In a `.d.ts` file, it's not so easy. To make this work, the schematic should use the View Engine compiler to load the program, allowing use of the metadata loaded from `.metadata.json` files. For case 1 (undecorated parents), if a component/directive in the compilation unit inherits a constructor from an undecorated base class, and the base class is from a library (.d.ts file), then the migration needs to add a comment to the derived class explaining that an explicit constructor needs to be declared. This case should be very rare. For case 2 (undecorated child), it should be possible to look at the metadata for the base class and make a determination about whether it can be automatically generated per above. ### ngcc These transformations will also need to be applied by the Angular compatibility compiler, `ngcc`. `ngcc`'s job will be a bit simpler than the schematic, since it: 1) knows how to generate `imports`, so it can handle cases where the schematic would have to bail out. 2) has a much easier time of detecting whether a class is a directive/component, thanks to Ivy. ### Backsliding Both of these patterns will become diagnostic errors in the Ivy compiler, ngtsc. #### G3 *Short term*: After the schematic is run internally, we can create a local mod to cause View Engine to throw an error if a directive is not properly decorated. *Long term*: In g3 we will eventually run the Ivy compiler in parallel to produce diagnostics. ### Deprecations No deprecations necessary - the old behavior is implicitly deprecated as it's not supported by Ivy. ## Checklist - [x] Design doc for migration. Should include: - [x] Why create a migration? (**Important**) - [x] Why can't we just "fix" this? - [x] How do we know it's impactful enough that we need a migration? - [x] How will the schematic work? - [x] What does this mean for libraries? - [x] What about applications using non-migrated libraries? - [x] Should this schematic be used externally or internally? In which version? - [x] Is there something that we should deprecate? In which version? - [x] How will we prevent backsliding? - [x] Any open questions? - [x] Post doc in #fw Slack channel for feedback - [x] Post doc in #tools Slack channel for feedback - [x] Confer with #devrel Slack channel for feedback - [x] Present in framework sync to answer Qs, get buy-in from team ## Approval - [x] Kara - [x] Igor - [ ] Misko ## After Approval - [x] Add to appropriate list of migrations (see [v9 list](https://docs.google.com/spreadsheets/d/1jqeXZ85N3SR5uTSndIfBuGebLgeL0zAnHH63290AKNM/edit#gid=0)) - [x] Schematic implementation - [x] Create a JIRA for schematic implementation and send to Kara - [x] Link: https://angular-team.atlassian.net/browse/FW-1421 - [ ] PR: - [ ] Internal migration in G3 - [x] Create a JIRA and send to Kara - [x] Link: https://angular-team.atlassian.net/browse/FW-1423 - [ ] [If applicable] LSC process - [x] Create a JIRA for LSC design doc and send to Kara - [x] Link: https://angular-team.atlassian.net/browse/FW-1424 - [ ] Migration guide - [x] Create a JIRA and send to Kara - [x] Link: https://angular-team.atlassian.net/browse/FW-1425 - [ ] Let docs team / Brandon know (needs docs review) - [ ] Communicate new schematic with the rest of team - [ ] Present in team meeting - [ ] Test schematic in RC period

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully