├── .gitattributes ├── .gitignore ├── LICENSE.txt ├── NOTICE.txt ├── README.md ├── TypeScriptAST.sln ├── TypeScriptAST ├── Change │ ├── ChangeAST.cs │ ├── NodeChangeItem.cs │ └── NodeChangeType.cs ├── Parser │ ├── Core.cs │ ├── Debug.cs │ ├── Diagnostics.cs │ ├── Factory.cs │ ├── JsDocParser.cs │ ├── Parser.cs │ ├── Scanner.cs │ ├── Ts.cs │ ├── TsExtensions.cs │ └── Utilities.cs ├── Properties │ └── AssemblyInfo.cs ├── TsTypes │ ├── Enums.cs │ ├── Node.cs │ ├── NodeExtensions.cs │ ├── SyntaxKind.cs │ └── TsTypes.cs ├── TypeScriptAST.cs ├── TypeScriptAST.csproj ├── TypeScriptAST.nuspec └── packages.config └── TypeScriptAstExample ├── App.config ├── App.xaml ├── App.xaml.cs ├── MainWindow.xaml ├── MainWindow.xaml.cs ├── Properties ├── AssemblyInfo.cs ├── Resources.Designer.cs ├── Resources.resx ├── Settings.Designer.cs └── Settings.settings └── TypeScriptAstExample.csproj /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | project.fragment.lock.json 46 | artifacts/ 47 | 48 | *_i.c 49 | *_p.c 50 | *_i.h 51 | *.ilk 52 | *.meta 53 | *.obj 54 | *.pch 55 | *.pdb 56 | *.pgc 57 | *.pgd 58 | *.rsp 59 | *.sbr 60 | *.tlb 61 | *.tli 62 | *.tlh 63 | *.tmp 64 | *.tmp_proj 65 | *.log 66 | *.vspscc 67 | *.vssscc 68 | .builds 69 | *.pidb 70 | *.svclog 71 | *.scc 72 | 73 | # Chutzpah Test files 74 | _Chutzpah* 75 | 76 | # Visual C++ cache files 77 | ipch/ 78 | *.aps 79 | *.ncb 80 | *.opendb 81 | *.opensdf 82 | *.sdf 83 | *.cachefile 84 | *.VC.db 85 | *.VC.VC.opendb 86 | 87 | # Visual Studio profiler 88 | *.psess 89 | *.vsp 90 | *.vspx 91 | *.sap 92 | 93 | # TFS 2012 Local Workspace 94 | $tf/ 95 | 96 | # Guidance Automation Toolkit 97 | *.gpState 98 | 99 | # ReSharper is a .NET coding add-in 100 | _ReSharper*/ 101 | *.[Rr]e[Ss]harper 102 | *.DotSettings.user 103 | 104 | # JustCode is a .NET coding add-in 105 | .JustCode 106 | 107 | # TeamCity is a build add-in 108 | _TeamCity* 109 | 110 | # DotCover is a Code Coverage Tool 111 | *.dotCover 112 | 113 | # NCrunch 114 | _NCrunch_* 115 | .*crunch*.local.xml 116 | nCrunchTemp_* 117 | 118 | # MightyMoose 119 | *.mm.* 120 | AutoTest.Net/ 121 | 122 | # Web workbench (sass) 123 | .sass-cache/ 124 | 125 | # Installshield output folder 126 | [Ee]xpress/ 127 | 128 | # DocProject is a documentation generator add-in 129 | DocProject/buildhelp/ 130 | DocProject/Help/*.HxT 131 | DocProject/Help/*.HxC 132 | DocProject/Help/*.hhc 133 | DocProject/Help/*.hhk 134 | DocProject/Help/*.hhp 135 | DocProject/Help/Html2 136 | DocProject/Help/html 137 | 138 | # Click-Once directory 139 | publish/ 140 | 141 | # Publish Web Output 142 | *.[Pp]ublish.xml 143 | *.azurePubxml 144 | # TODO: Comment the next line if you want to checkin your web deploy settings 145 | # but database connection strings (with potential passwords) will be unencrypted 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 150 | # checkin your Azure Web App publish settings, but sensitive information contained 151 | # in these scripts will be unencrypted 152 | PublishScripts/ 153 | 154 | # NuGet Packages 155 | *.nupkg 156 | # The packages folder can be ignored because of Package Restore 157 | **/packages/* 158 | # except build/, which is used as an MSBuild target. 159 | !**/packages/build/ 160 | # Uncomment if necessary however generally it will be regenerated when needed 161 | #!**/packages/repositories.config 162 | # NuGet v3's project.json files produces more ignoreable files 163 | *.nuget.props 164 | *.nuget.targets 165 | 166 | # Microsoft Azure Build Output 167 | csx/ 168 | *.build.csdef 169 | 170 | # Microsoft Azure Emulator 171 | ecf/ 172 | rcf/ 173 | 174 | # Windows Store app package directories and files 175 | AppPackages/ 176 | BundleArtifacts/ 177 | Package.StoreAssociation.xml 178 | _pkginfo.txt 179 | 180 | # Visual Studio cache files 181 | # files ending in .cache can be ignored 182 | *.[Cc]ache 183 | # but keep track of directories ending in .cache 184 | !*.[Cc]ache/ 185 | 186 | # Others 187 | ClientBin/ 188 | ~$* 189 | *~ 190 | *.dbmdl 191 | *.dbproj.schemaview 192 | *.jfm 193 | *.pfx 194 | *.publishsettings 195 | node_modules/ 196 | orleans.codegen.cs 197 | 198 | # Since there are multiple workflows, uncomment next line to ignore bower_components 199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 200 | #bower_components/ 201 | 202 | # RIA/Silverlight projects 203 | Generated_Code/ 204 | 205 | # Backup & report files from converting an old project file 206 | # to a newer Visual Studio version. Backup files are not needed, 207 | # because we have git ;-) 208 | _UpgradeReport_Files/ 209 | Backup*/ 210 | UpgradeLog*.XML 211 | UpgradeLog*.htm 212 | 213 | # SQL Server files 214 | *.mdf 215 | *.ldf 216 | 217 | # Business Intelligence projects 218 | *.rdl.data 219 | *.bim.layout 220 | *.bim_*.settings 221 | 222 | # Microsoft Fakes 223 | FakesAssemblies/ 224 | 225 | # GhostDoc plugin setting file 226 | *.GhostDoc.xml 227 | 228 | # Node.js Tools for Visual Studio 229 | .ntvs_analysis.dat 230 | 231 | # Visual Studio 6 build log 232 | *.plg 233 | 234 | # Visual Studio 6 workspace options file 235 | *.opt 236 | 237 | # Visual Studio LightSwitch build output 238 | **/*.HTMLClient/GeneratedArtifacts 239 | **/*.DesktopClient/GeneratedArtifacts 240 | **/*.DesktopClient/ModelManifest.xml 241 | **/*.Server/GeneratedArtifacts 242 | **/*.Server/ModelManifest.xml 243 | _Pvt_Extensions 244 | 245 | # Paket dependency manager 246 | .paket/paket.exe 247 | paket-files/ 248 | 249 | # FAKE - F# Make 250 | .fake/ 251 | 252 | # JetBrains Rider 253 | .idea/ 254 | *.sln.iml 255 | 256 | # CodeRush 257 | .cr/ 258 | 259 | # Python Tools for Visual Studio (PTVS) 260 | __pycache__/ 261 | *.pyc 262 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /NOTICE.txt: -------------------------------------------------------------------------------- 1 | TypeScriptAST is based on some portions of TypeScript project hosted on https://github.com/Microsoft/TypeScript distributed with Apache 2.0 license. 2 | It does not represent a direct port of TypeScript into C#, it only uses some parts related to TypeScript parser. 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | This is old project for TypeScript, which is developing so fast. I think now is not the best option for parsing TypeScript. Now it's not easy to upgrade to the current TypeScript. For JavaScript I think it still good. 2 | It's time to rewrite TypeScriptAST. Microsoft showed us how to do it in System.Text.Json for .NET Core 3.0: 3 | "Provide high-performance JSON APIs. We needed a new set of JSON APIs that are highly tuned for performance by using Span" 4 | https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/ 5 | https://github.com/dotnet/runtime/blob/master/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.cs 6 | 7 | # TypeScriptAST 8 | 9 | .NET port of Microsoft's TypeScript parser for simple AST manipulation. 10 | 11 | It works with TypeScript, JavaScript and DefinitelyTyped(".d.ts") files and gives the same tree as typescriptServices.js. 12 | 13 | [![Join the chat at https://gitter.im/TypeScriptAST/Lobby](https://badges.gitter.im/TypeScriptAST/Lobby.svg)](https://gitter.im/TypeScriptAST/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) 14 | 15 | 16 | ## Install TypeScriptAST via NuGet 17 | 18 | If you want to include TypeScriptAST in your project, you can [install it directly from NuGet](https://www.nuget.org/packages/TypeScriptAST/) 19 | 20 | ``` 21 | PM> Install-Package TypeScriptAST 22 | ``` 23 | 24 | ## Create AST 25 | ```csharp 26 | var ast = new TypeScriptAST(File.ReadAllText(file), file); 27 | ``` 28 | ## Find Node 29 | By SyntaxKind 30 | ```csharp 31 | var functions = ast.OfKind(SyntaxKind.FunctionExpression); 32 | var vars = functions.FirstOrDefault()?.OfKind(SyntaxKind.VariableDeclaration); 33 | ``` 34 | By Node type 35 | ```csharp 36 | var functions = ast.GetDescendants().OfType(); 37 |  var vars = functions.FirstOrDefault()?.GetDescendants().OfType(); 38 | ``` 39 | ## GetText 40 | ```csharp 41 | var firstFunc = ast.OfKind(SyntaxKind.FunctionExpression).FirstOrDefault(); 42 | var text = firstFunc?.GetText(); 43 | var withComments = firstFunc?.GetTextWithComments(); 44 | ``` 45 | ## Change Node 46 | ```csharp 47 | var funcNewCode = "function() {}"; 48 | var change = new ChangeAST(); 49 | change.ChangeNode(firstFunc, funcNewCode); 50 | var newSource = change.GetChangedSource(ast.SourceStr); 51 | File.WriteAllText(file, newSource); 52 | ``` 53 | ## File modification Example 54 | 55 | This example included in TypeScriptAstExample. It finds modules in file, collects some info, adds new function to module. 56 | 57 | ```csharp 58 | using Zu.TypeScript; 59 | using Zu.TypeScript.Change; 60 | using Zu.TypeScript.TsTypes; 61 | 62 | var fileName = "parser.ts"; 63 | var source = File.ReadAllText(fileName); 64 | 65 | var ast = new TypeScriptAST(source, fileName); 66 | 67 | var change = new ChangeAST(); 68 | 69 | foreach (var module in ast.GetDescendants().OfType()) 70 | { 71 | var funcs = module.Body.Children.OfType().ToList(); 72 | var enums = module.Body.Children.OfType(); 73 | var moduleInfoFunc = $@" 74 | export function getModuleInfo() {{ 75 | return ""Module {module.IdentifierStr} contains {funcs.Count()} functions ({funcs.Count(v => v.IdentifierStr.StartsWith("parse"))} starts with parse), {enums.Count()} enums ...""; 76 | }} 77 | "; 78 | change.InsertBefore(module.Body.Children.First(), moduleInfoFunc); 79 | } 80 | var newSource = change.GetChangedSource(ast.SourceStr); 81 | 82 | File.WriteAllText("parser2.ts", newSource); 83 | 84 | ``` 85 | -------------------------------------------------------------------------------- /TypeScriptAST.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26403.3 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TypeScriptAST", "TypeScriptAST\TypeScriptAST.csproj", "{7728B98C-9E88-4E6D-8ECD-D51DED278AC2}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TypeScriptAstExample", "TypeScriptAstExample\TypeScriptAstExample.csproj", "{98383B0A-D61E-48C9-9D18-9656AC601CA5}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {7728B98C-9E88-4E6D-8ECD-D51DED278AC2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {7728B98C-9E88-4E6D-8ECD-D51DED278AC2}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {7728B98C-9E88-4E6D-8ECD-D51DED278AC2}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {7728B98C-9E88-4E6D-8ECD-D51DED278AC2}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {98383B0A-D61E-48C9-9D18-9656AC601CA5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {98383B0A-D61E-48C9-9D18-9656AC601CA5}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {98383B0A-D61E-48C9-9D18-9656AC601CA5}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {98383B0A-D61E-48C9-9D18-9656AC601CA5}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /TypeScriptAST/Change/ChangeAST.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using Zu.TypeScript.TsTypes; 6 | 7 | namespace Zu.TypeScript.Change 8 | { 9 | public class ChangeAST 10 | { 11 | private readonly ICollection _nodeChangeItems; 12 | 13 | public ChangeAST(ICollection changeItems = null) 14 | { 15 | _nodeChangeItems = changeItems ?? new List(); 16 | } 17 | 18 | public static string Change(string source, IEnumerable changeItems) 19 | { 20 | var changes = changeItems.OrderBy(v => v.Node.Pos).ThenBy(v2 => v2.ChangeType); 21 | var sb = new StringBuilder(); 22 | var pos = 0; 23 | foreach (var ch in changes) 24 | { 25 | if (ch.Node.Pos == null) throw new NullReferenceException("Node.Pos"); 26 | switch (ch.ChangeType) 27 | { 28 | case NodeChangeType.InsertBefore: 29 | if (ch.Node.Pos > pos) sb.Append(source.Substring(pos, (int) ch.Node.Pos - pos)); 30 | sb.Append(ch.NewValue); 31 | pos = (int) ch.Node.Pos; 32 | break; 33 | case NodeChangeType.Change: 34 | if (ch.Node.Pos > pos) sb.Append(source.Substring(pos, (int) ch.Node.Pos - pos)); 35 | sb.Append(ch.NewValue); 36 | if (ch.Node.End != null) pos = (int) ch.Node.End; 37 | else throw new NullReferenceException("Node.End"); 38 | break; 39 | case NodeChangeType.Delete: 40 | if (ch.Node.Pos > pos) sb.Append(source.Substring(pos, (int) ch.Node.Pos - pos)); 41 | if (ch.Node.End != null) pos = (int) ch.Node.End + 1; 42 | break; 43 | case NodeChangeType.InsertAfter: 44 | if (ch.Node.End > pos) sb.Append(source.Substring(pos, (int) ch.Node.End - pos)); 45 | sb.Append(ch.NewValue); 46 | if (ch.Node.End != null) pos = (int) ch.Node.End; 47 | break; 48 | default: 49 | throw new ArgumentOutOfRangeException(); 50 | } 51 | } 52 | if (pos < source.Length) sb.Append(source.Substring(pos)); 53 | var newSource = sb.ToString(); 54 | 55 | return newSource; 56 | } 57 | 58 | public string GetChangedSource(string baseSource) 59 | { 60 | return Change(baseSource, _nodeChangeItems); 61 | } 62 | 63 | public void ChangeNode(INode node, string newValue) 64 | { 65 | if (_nodeChangeItems.Any(v => v.Node == node && 66 | (v.ChangeType == NodeChangeType.Change || 67 | v.ChangeType == NodeChangeType.Delete))) 68 | throw new Exception("ChangeItems already have this node. Delete first"); 69 | if (_nodeChangeItems.Any(v => v.Node.Pos < node.Pos && v.Node.End > node.Pos)) 70 | throw new Exception("ChangeItems already have node that contains this node. Delete first"); 71 | 72 | if (newValue != node.GetTextWithComments()) 73 | { 74 | var nodeCh = new NodeChangeItem {ChangeType = NodeChangeType.Change, Node = node, NewValue = newValue}; 75 | _nodeChangeItems.Add(nodeCh); 76 | } 77 | else 78 | { 79 | throw new Exception("Same value"); 80 | } 81 | } 82 | 83 | public void InsertBefore(INode node, string newValue) 84 | { 85 | if (node != null) 86 | { 87 | //if (_nodeChangeItems.Any(v => v.Node.Pos < node.Pos && v.Node.End > node.Pos)) 88 | // throw new Exception("ChangeItems already have node that contains this node. Delete first"); 89 | 90 | var nodeCh = new NodeChangeItem 91 | { 92 | ChangeType = NodeChangeType.InsertBefore, 93 | Node = node, 94 | NewValue = newValue 95 | }; 96 | _nodeChangeItems.Add(nodeCh); 97 | } 98 | } 99 | 100 | public void InsertAfter(INode node, string newValue) 101 | { 102 | if (node != null) 103 | { 104 | //if (_nodeChangeItems.Any(v => v.Node.Pos < node.Pos && v.Node.End > node.Pos)) 105 | // throw new Exception("ChangeItems already have node that contains this node. Delete first"); 106 | 107 | var nodeCh = new NodeChangeItem 108 | { 109 | ChangeType = NodeChangeType.InsertAfter, 110 | Node = node, 111 | NewValue = newValue 112 | }; 113 | _nodeChangeItems.Add(nodeCh); 114 | } 115 | } 116 | 117 | public void Delete(INode node) 118 | { 119 | if (node != null) 120 | { 121 | if (_nodeChangeItems.Any(v => v.Node.Pos < node.Pos && v.Node.End > node.Pos)) 122 | throw new Exception("ChangeItems already have node that contains this node. Delete first"); 123 | 124 | var nodeCh = new NodeChangeItem {ChangeType = NodeChangeType.Delete, Node = node}; 125 | _nodeChangeItems.Add(nodeCh); 126 | } 127 | } 128 | } 129 | } -------------------------------------------------------------------------------- /TypeScriptAST/Change/NodeChangeItem.cs: -------------------------------------------------------------------------------- 1 | using Zu.TypeScript.TsTypes; 2 | 3 | namespace Zu.TypeScript.Change 4 | { 5 | public class NodeChangeItem 6 | { 7 | public NodeChangeType ChangeType { get; set; } 8 | 9 | public INode Node { get; set; } 10 | //public int Pos { get; set; } 11 | 12 | //public int End { get; set; } 13 | public string NewValue { get; set; } 14 | 15 | private string NewValueSmall => NewValue == null 16 | ? "" 17 | : NewValue.Length > 20 18 | ? NewValue.Substring(0, 18) + $"..({NewValue.Length})" 19 | : NewValue; 20 | 21 | public override string ToString() 22 | { 23 | if (ChangeType == NodeChangeType.Delete) return $"{ChangeType} {Node}."; 24 | return $"{ChangeType} {Node}. NewValue = \"{NewValueSmall}\""; 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /TypeScriptAST/Change/NodeChangeType.cs: -------------------------------------------------------------------------------- 1 | namespace Zu.TypeScript.Change 2 | { 3 | public enum NodeChangeType 4 | { 5 | InsertBefore, 6 | Change, 7 | Delete, 8 | InsertAfter 9 | } 10 | } -------------------------------------------------------------------------------- /TypeScriptAST/Parser/Core.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Text.RegularExpressions; 6 | using Zu.TypeScript.TsTypes; 7 | 8 | namespace Zu.TypeScript.TsParser 9 | { 10 | public static class Core 11 | { 12 | // from core.ts 13 | 14 | public static int BinarySearch(int[] array, int value, Func comparer = null, int? offset = null) 15 | { 16 | if (array == null || array.Length == 0) 17 | { 18 | return -1; 19 | } 20 | var low = offset ?? 0; 21 | var high = array.Length - 1; 22 | comparer = comparer ?? ((v1, v2) => (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0))); 23 | while (low <= high) 24 | { 25 | var middle = low + ((high - low) >> 1); 26 | var midValue = array[middle]; 27 | if (comparer(midValue, value) == 0) 28 | { 29 | return middle; 30 | } 31 | else 32 | if (comparer(midValue, value) > 0) 33 | { 34 | high = middle - 1; 35 | } 36 | else 37 | { 38 | low = middle + 1; 39 | } 40 | } 41 | return ~low; 42 | } 43 | public static bool PositionIsSynthesized(int pos) 44 | { 45 | // This is a fast way of testing the following conditions: 46 | // pos == null || pos == null || isNaN(pos) || pos < 0; 47 | return !(pos >= 0); 48 | } 49 | 50 | public static ScriptKind EnsureScriptKind(string fileName, ScriptKind scriptKind) 51 | { 52 | // Using scriptKind as a condition handles both: 53 | // - 'scriptKind' is unspecified and thus it is `null` 54 | // - 'scriptKind' is set and it is `Unknown` (0) 55 | // If the 'scriptKind' is 'null' or 'Unknown' then we attempt 56 | // to get the ScriptKind from the file name. If it cannot be resolved 57 | // from the file name then the default 'TS' script kind is returned. 58 | var sk = scriptKind != ScriptKind.Unknown ? scriptKind : GetScriptKindFromFileName(fileName); 59 | return sk != ScriptKind.Unknown ? sk : ScriptKind.Ts; 60 | } 61 | public static ScriptKind GetScriptKindFromFileName(string fileName) 62 | { 63 | //var ext = fileName.substr(fileName.LastIndexOf(".")); 64 | var ext = Path.GetExtension(fileName); 65 | switch (ext?.ToLower()) 66 | { 67 | case ".js": 68 | return ScriptKind.Js; 69 | case ".jsx": 70 | return ScriptKind.Jsx; 71 | case ".ts": 72 | return ScriptKind.Ts; 73 | case ".tsx": 74 | return ScriptKind.Tsx; 75 | default: 76 | return ScriptKind.Unknown; 77 | } 78 | } 79 | 80 | public static string NormalizePath(string path) 81 | { 82 | path = NormalizeSlashes(path); 83 | var rootLength = GetRootLength(path); 84 | var root = path.Substring(0, rootLength); 85 | var normalized = GetNormalizedParts(path, rootLength); 86 | if (normalized.Any()) 87 | { 88 | var joinedParts = root + string.Join(DirectorySeparator.ToString(), normalized);//.join(directorySeparator); 89 | return PathEndsWithDirectorySeparator(path) ? joinedParts + DirectorySeparator : joinedParts; 90 | } 91 | else 92 | { 93 | return root; 94 | } 95 | } 96 | public static string NormalizeSlashes(string path) 97 | { 98 | return Regex.Replace(path, "/\\/ g", "/"); 99 | //return path.replace(/\\/ g, "/"); 100 | } 101 | public static int GetRootLength(string path) 102 | { 103 | if (path.charCodeAt(0) == (int)CharacterCodes.Slash) 104 | { 105 | if (path.charCodeAt(1) != (int)CharacterCodes.Slash) 106 | { 107 | return 1; 108 | } 109 | var p1 = path.IndexOf("/", 2, StringComparison.Ordinal); 110 | if (p1 < 0) 111 | { 112 | return 2; 113 | } 114 | var p2 = path.IndexOf("/", p1 + 1, StringComparison.Ordinal); 115 | if (p2 < 0) 116 | { 117 | return p1 + 1; 118 | } 119 | return p2 + 1; 120 | } 121 | if (path.charCodeAt(1) == (int)CharacterCodes.Colon) 122 | { 123 | if (path.charCodeAt(2) == (int)CharacterCodes.Slash) 124 | { 125 | return 3; 126 | } 127 | return 2; 128 | } 129 | if (path.LastIndexOf("file:///", 0, StringComparison.Ordinal) == 0) 130 | { 131 | return "file:///".Length; 132 | } 133 | var idx = path.IndexOf("://", StringComparison.Ordinal); 134 | if (idx != -1) 135 | { 136 | return idx + "://".Length; 137 | } 138 | return 0; 139 | } 140 | public static char DirectorySeparator = '/'; 141 | public static int DirectorySeparatorCharCode = (int)CharacterCodes.Slash; 142 | public static List GetNormalizedParts(string normalizedSlashedPath, int rootLength) 143 | { 144 | var parts = normalizedSlashedPath.Substring(rootLength).Split(DirectorySeparator); 145 | List normalized = new List(); 146 | foreach (var part in parts) 147 | { 148 | if (part != ".") 149 | { 150 | if (part == ".." && normalized.Count > 0 && LastOrUndefined(normalized) != "..") 151 | { 152 | normalized.pop(); 153 | } 154 | else 155 | { 156 | // A part may be an empty string (which is 'falsy') if the path had consecutive slashes, 157 | // e.g. "path//file.ts". Drop these before re-joining the parts. 158 | if (part != null) 159 | { 160 | normalized.Add(part); 161 | } 162 | } 163 | } 164 | } 165 | return normalized; 166 | } 167 | public static T LastOrUndefined(List array) 168 | { 169 | return array != null && array.Any() 170 | ? array.Last() 171 | : default(T); 172 | } 173 | public static bool PathEndsWithDirectorySeparator(string path) 174 | { 175 | return path.charCodeAt(path.Length - 1) == DirectorySeparatorCharCode; 176 | } 177 | public static bool FileExtensionIs(string path, string extension) 178 | { 179 | return path.Length > extension.Length && EndsWith(path, extension); 180 | } 181 | public static bool EndsWith(string str, string suffix) 182 | { 183 | var expectedPos = str.Length - suffix.Length; 184 | return expectedPos >= 0 && str.IndexOf(suffix, expectedPos, StringComparison.Ordinal) == expectedPos; 185 | } 186 | public static Diagnostic CreateFileDiagnostic(SourceFile file, int start, int length, DiagnosticMessage message, params string[] arguments) 187 | { 188 | var end = start + length; 189 | Debug.Assert(start >= 0, "start must be non-negative, is " + start); 190 | Debug.Assert(length >= 0, "length must be non-negative, is " + length); 191 | if (file != null) 192 | { 193 | Debug.Assert(start <= file.Text.Length, $"start must be within the bounds of the file. { start} > { file.Text.Length}"); 194 | Debug.Assert(end <= file.Text.Length, $"end must be the bounds of the file. { end} > { file.Text.Length}"); 195 | } 196 | var text = GetLocaleSpecificMessage(message); 197 | if (arguments.Length > 0) // 4) 198 | { 199 | //text = formatStringFromArgs(text, arguments, 4); 200 | } 201 | return new Diagnostic 202 | { 203 | File = file, 204 | Start = start, 205 | Length = length, 206 | 207 | MessageText = text, 208 | Category = message?.Category ?? DiagnosticCategory.Unknown, 209 | Code = message?.Code ?? 0, 210 | }; 211 | } 212 | public static string GetLocaleSpecificMessage(DiagnosticMessage message) 213 | { 214 | return "localizedDiagnosticMessages";// && localizedDiagnosticMessages[message.key] || message.message; 215 | } 216 | 217 | } 218 | } 219 | -------------------------------------------------------------------------------- /TypeScriptAST/Parser/Debug.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Zu.TypeScript.TsParser 4 | { 5 | internal class Debug 6 | { 7 | internal static void Assert(object v, object v2 = null) 8 | { 9 | 10 | } 11 | 12 | internal static void Fail(string v = null) 13 | { 14 | throw new NotImplementedException(); 15 | } 16 | 17 | internal static bool ShouldAssert(object obj) 18 | { 19 | throw new NotImplementedException(); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /TypeScriptAST/Parser/Diagnostics.cs: -------------------------------------------------------------------------------- 1 | using Zu.TypeScript.TsTypes; 2 | 3 | namespace Zu.TypeScript.TsParser 4 | { 5 | internal class Diagnostics 6 | { 7 | public static DiagnosticMessage Merge_conflict_marker_encountered; 8 | public static DiagnosticMessage Digit_expected; 9 | public static DiagnosticMessage Unterminated_string_literal; 10 | public static DiagnosticMessage Unterminated_template_literal; 11 | public static DiagnosticMessage Unexpected_end_of_text; 12 | public static DiagnosticMessage Hexadecimal_digit_expected; 13 | public static DiagnosticMessage An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive; 14 | public static DiagnosticMessage Unterminated_Unicode_escape_sequence; 15 | public static DiagnosticMessage Asterisk_Slash_expected; 16 | public static DiagnosticMessage Binary_digit_expected; 17 | public static DiagnosticMessage Octal_digit_expected; 18 | public static DiagnosticMessage Invalid_character; 19 | public static DiagnosticMessage Unterminated_regular_expression_literal; 20 | public static DiagnosticMessage _0_expected; 21 | public static DiagnosticMessage Identifier_expected; 22 | public static DiagnosticMessage Declaration_or_statement_expected; 23 | public static DiagnosticMessage case_or_default_expected; 24 | public static DiagnosticMessage Statement_expected; 25 | public static DiagnosticMessage Property_or_signature_expected; 26 | public static DiagnosticMessage Unexpected_token_A_constructor_method_accessor_or_property_was_expected; 27 | public static DiagnosticMessage Enum_member_expected; 28 | public static DiagnosticMessage Expression_expected; 29 | public static DiagnosticMessage Variable_declaration_expected; 30 | public static DiagnosticMessage Property_destructuring_pattern_expected; 31 | public static DiagnosticMessage Array_element_destructuring_pattern_expected; 32 | public static DiagnosticMessage Argument_expression_expected; 33 | public static DiagnosticMessage Property_assignment_expected; 34 | public static DiagnosticMessage Expression_or_comma_expected; 35 | public static DiagnosticMessage Parameter_declaration_expected; 36 | public static DiagnosticMessage Type_parameter_declaration_expected; 37 | public static DiagnosticMessage Type_argument_expected; 38 | public static DiagnosticMessage Type_expected; 39 | public static DiagnosticMessage Unexpected_token_expected; 40 | 41 | public static DiagnosticMessage 42 | A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses 43 | ; 44 | 45 | public static DiagnosticMessage 46 | An_unary_expression_with_the_0_operator_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses 47 | ; 48 | 49 | public static DiagnosticMessage super_must_be_followed_by_an_argument_list_or_member_access; 50 | public static DiagnosticMessage Expected_corresponding_JSX_closing_tag_for_0; 51 | public static DiagnosticMessage JSX_expressions_must_have_one_parent_element; 52 | public static DiagnosticMessage JSX_element_0_has_no_corresponding_closing_tag; 53 | public static DiagnosticMessage Declaration_expected; 54 | public static DiagnosticMessage or_expected; 55 | public static DiagnosticMessage An_AMD_module_cannot_have_multiple_name_assignments; 56 | public static DiagnosticMessage Type_argument_list_cannot_be_empty; 57 | public static DiagnosticMessage Trailing_comma_not_allowed; 58 | public static DiagnosticMessage _0_tag_already_specified; 59 | } 60 | } -------------------------------------------------------------------------------- /TypeScriptAST/Parser/Factory.cs: -------------------------------------------------------------------------------- 1 | using Zu.TypeScript.TsTypes; 2 | 3 | namespace Zu.TypeScript.TsParser 4 | { 5 | public static class Factory 6 | { 7 | public static INode SkipPartiallyEmittedExpressions(INode node) 8 | { 9 | while (node.Kind == SyntaxKind.PartiallyEmittedExpression) 10 | node = ((PartiallyEmittedExpression) node).Expression; 11 | 12 | 13 | return node; 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /TypeScriptAST/Parser/Ts.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using Zu.TypeScript.TsTypes; 5 | 6 | namespace Zu.TypeScript.TsParser 7 | { 8 | public class Ts 9 | { 10 | public static INode VisitNode(Func cbNode, INode node) 11 | { 12 | if (node != null) 13 | return cbNode(node); 14 | return null; 15 | } 16 | 17 | 18 | public static T VisitList(Func cbNodes, INode[] nodes) 19 | { 20 | if (nodes != null) 21 | return cbNodes(nodes); 22 | return default(T); 23 | } 24 | 25 | 26 | public static INode VisitNodeArray(Func cbNodes, INode[] nodes) 27 | { 28 | if (nodes != null) 29 | return cbNodes(nodes); 30 | return null; 31 | } 32 | 33 | public static INode VisitEachNode(Func cbNode, List nodes) 34 | { 35 | if (nodes != null) 36 | foreach (var node in nodes) 37 | { 38 | var result = cbNode(node); 39 | if (result != null) 40 | return result; 41 | } 42 | return null; 43 | } 44 | 45 | 46 | public static INode ForEachChild(INode node, Func cbNode, Func cbNodeArray = null) 47 | { 48 | if (node == null) 49 | return null; 50 | Func, INode> visitNodes = (o1, o2) => 51 | { 52 | var list = o2?.Cast().ToList(); 53 | if (list != null) 54 | if (cbNodeArray == null) 55 | return VisitEachNode(cbNode, list); 56 | else 57 | return cbNodeArray(list.ToArray()); 58 | return null; 59 | }; 60 | var cbNodes = cbNodeArray; 61 | switch (node.Kind) 62 | { 63 | case SyntaxKind.QualifiedName: 64 | 65 | return VisitNode(cbNode, (node as QualifiedName)?.Left) ?? 66 | VisitNode(cbNode, (node as QualifiedName)?.Right); 67 | case SyntaxKind.TypeParameter: 68 | 69 | return VisitNode(cbNode, (node as TypeParameterDeclaration)?.Name) ?? 70 | VisitNode(cbNode, (node as TypeParameterDeclaration)?.Constraint) ?? 71 | VisitNode(cbNode, (node as TypeParameterDeclaration)?.Default) ?? 72 | VisitNode(cbNode, (node as TypeParameterDeclaration)?.Expression); 73 | case SyntaxKind.ShorthandPropertyAssignment: 74 | 75 | return visitNodes(cbNodes, node.Decorators) ?? 76 | visitNodes(cbNodes, node.Modifiers) ?? 77 | VisitNode(cbNode, (node as ShorthandPropertyAssignment)?.Name) ?? 78 | VisitNode(cbNode, (node as ShorthandPropertyAssignment)?.QuestionToken) ?? 79 | VisitNode(cbNode, (node as ShorthandPropertyAssignment)?.EqualsToken) ?? 80 | VisitNode(cbNode, (node as ShorthandPropertyAssignment)?.ObjectAssignmentInitializer); 81 | case SyntaxKind.SpreadAssignment: 82 | 83 | return VisitNode(cbNode, (node as SpreadAssignment)?.Expression); 84 | case SyntaxKind.Parameter: 85 | case SyntaxKind.PropertyDeclaration: 86 | case SyntaxKind.PropertySignature: 87 | case SyntaxKind.PropertyAssignment: 88 | case SyntaxKind.VariableDeclaration: 89 | case SyntaxKind.BindingElement: 90 | 91 | return visitNodes(cbNodes, node.Decorators) ?? 92 | visitNodes(cbNodes, node.Modifiers) ?? 93 | VisitNode(cbNode, (node as IVariableLikeDeclaration)?.PropertyName) ?? 94 | VisitNode(cbNode, (node as IVariableLikeDeclaration)?.DotDotDotToken) ?? 95 | VisitNode(cbNode, (node as IVariableLikeDeclaration)?.Name) ?? 96 | VisitNode(cbNode, (node as IVariableLikeDeclaration)?.QuestionToken) ?? 97 | VisitNode(cbNode, (node as IVariableLikeDeclaration)?.Type) ?? 98 | VisitNode(cbNode, (node as IVariableLikeDeclaration)?.Initializer); 99 | case SyntaxKind.FunctionType: 100 | case SyntaxKind.ConstructorType: 101 | case SyntaxKind.CallSignature: 102 | case SyntaxKind.ConstructSignature: 103 | case SyntaxKind.IndexSignature: 104 | 105 | return visitNodes(cbNodes, node.Decorators) ?? 106 | visitNodes(cbNodes, node.Modifiers) ?? 107 | visitNodes(cbNodes, (node as ISignatureDeclaration)?.TypeParameters) ?? 108 | visitNodes(cbNodes, (node as ISignatureDeclaration)?.Parameters) ?? 109 | VisitNode(cbNode, (node as ISignatureDeclaration)?.Type); 110 | case SyntaxKind.MethodDeclaration: 111 | case SyntaxKind.MethodSignature: 112 | case SyntaxKind.Constructor: 113 | case SyntaxKind.GetAccessor: 114 | case SyntaxKind.SetAccessor: 115 | case SyntaxKind.FunctionExpression: 116 | case SyntaxKind.FunctionDeclaration: 117 | case SyntaxKind.ArrowFunction: 118 | 119 | return visitNodes(cbNodes, node.Decorators) ?? 120 | visitNodes(cbNodes, node.Modifiers) ?? 121 | VisitNode(cbNode, (node as IFunctionLikeDeclaration)?.AsteriskToken) ?? 122 | VisitNode(cbNode, (node as IFunctionLikeDeclaration)?.Name) ?? 123 | VisitNode(cbNode, (node as IFunctionLikeDeclaration)?.QuestionToken) ?? 124 | visitNodes(cbNodes, (node as IFunctionLikeDeclaration)?.TypeParameters) ?? 125 | visitNodes(cbNodes, (node as IFunctionLikeDeclaration)?.Parameters) ?? 126 | VisitNode(cbNode, (node as IFunctionLikeDeclaration)?.Type) ?? 127 | VisitNode(cbNode, (node as ArrowFunction)?.EqualsGreaterThanToken) ?? 128 | VisitNode(cbNode, (node as IFunctionLikeDeclaration)?.Body); 129 | case SyntaxKind.TypeReference: 130 | 131 | return VisitNode(cbNode, (node as TypeReferenceNode)?.TypeName) ?? 132 | visitNodes(cbNodes, (node as TypeReferenceNode)?.TypeArguments); 133 | case SyntaxKind.TypePredicate: 134 | 135 | return VisitNode(cbNode, (node as TypePredicateNode)?.ParameterName) ?? 136 | VisitNode(cbNode, (node as TypePredicateNode)?.Type); 137 | case SyntaxKind.TypeQuery: 138 | 139 | return VisitNode(cbNode, (node as TypeQueryNode)?.ExprName); 140 | case SyntaxKind.TypeLiteral: 141 | 142 | return visitNodes(cbNodes, (node as TypeLiteralNode)?.Members); 143 | case SyntaxKind.ArrayType: 144 | 145 | return VisitNode(cbNode, (node as ArrayTypeNode)?.ElementType); 146 | case SyntaxKind.TupleType: 147 | 148 | return visitNodes(cbNodes, (node as TupleTypeNode)?.ElementTypes); 149 | case SyntaxKind.UnionType: 150 | case SyntaxKind.IntersectionType: 151 | 152 | return visitNodes(cbNodes, (node as IUnionOrIntersectionTypeNode)?.Types); 153 | case SyntaxKind.ParenthesizedType: 154 | case SyntaxKind.TypeOperator: 155 | 156 | return VisitNode(cbNode, (node as ParenthesizedTypeNode)?.Type ?? (node as TypeOperatorNode)?.Type); 157 | case SyntaxKind.IndexedAccessType: 158 | 159 | return VisitNode(cbNode, (node as IndexedAccessTypeNode)?.ObjectType) ?? 160 | VisitNode(cbNode, (node as IndexedAccessTypeNode)?.IndexType); 161 | case SyntaxKind.MappedType: 162 | 163 | return VisitNode(cbNode, (node as MappedTypeNode)?.ReadonlyToken) ?? 164 | VisitNode(cbNode, (node as MappedTypeNode)?.TypeParameter) ?? 165 | VisitNode(cbNode, (node as MappedTypeNode)?.QuestionToken) ?? 166 | VisitNode(cbNode, (node as MappedTypeNode)?.Type); 167 | case SyntaxKind.LiteralType: 168 | 169 | return VisitNode(cbNode, (node as LiteralTypeNode)?.Literal); 170 | case SyntaxKind.ObjectBindingPattern: 171 | case SyntaxKind.ArrayBindingPattern: 172 | 173 | return visitNodes(cbNodes, ((IBindingPattern) node).Elements); 174 | case SyntaxKind.ArrayLiteralExpression: 175 | 176 | return visitNodes(cbNodes, (node as ArrayLiteralExpression)?.Elements); 177 | case SyntaxKind.ObjectLiteralExpression: 178 | 179 | return visitNodes(cbNodes, (node as ObjectLiteralExpression)?.Properties); 180 | case SyntaxKind.PropertyAccessExpression: 181 | 182 | return VisitNode(cbNode, (node as PropertyAccessExpression)?.Expression) ?? 183 | VisitNode(cbNode, (node as PropertyAccessExpression)?.Name); 184 | case SyntaxKind.ElementAccessExpression: 185 | 186 | return VisitNode(cbNode, (node as ElementAccessExpression)?.Expression) ?? 187 | VisitNode(cbNode, (node as ElementAccessExpression)?.ArgumentExpression); 188 | case SyntaxKind.CallExpression: 189 | case SyntaxKind.NewExpression: 190 | 191 | return VisitNode(cbNode, (node as CallExpression)?.Expression) ?? 192 | visitNodes(cbNodes, (node as CallExpression)?.TypeArguments) ?? 193 | visitNodes(cbNodes, (node as CallExpression)?.Arguments); 194 | case SyntaxKind.TaggedTemplateExpression: 195 | 196 | return VisitNode(cbNode, (node as TaggedTemplateExpression)?.Tag) ?? 197 | VisitNode(cbNode, (node as TaggedTemplateExpression)?.Template); 198 | case SyntaxKind.TypeAssertionExpression: 199 | 200 | return VisitNode(cbNode, (node as TypeAssertion)?.Type) ?? 201 | VisitNode(cbNode, (node as TypeAssertion)?.Expression); 202 | case SyntaxKind.ParenthesizedExpression: 203 | 204 | return VisitNode(cbNode, (node as ParenthesizedExpression)?.Expression); 205 | case SyntaxKind.DeleteExpression: 206 | 207 | return VisitNode(cbNode, (node as DeleteExpression)?.Expression); 208 | case SyntaxKind.TypeOfExpression: 209 | 210 | return VisitNode(cbNode, (node as TypeOfExpression)?.Expression); 211 | case SyntaxKind.VoidExpression: 212 | 213 | return VisitNode(cbNode, (node as VoidExpression)?.Expression); 214 | case SyntaxKind.PrefixUnaryExpression: 215 | 216 | return VisitNode(cbNode, (node as PrefixUnaryExpression)?.Operand); 217 | case SyntaxKind.YieldExpression: 218 | 219 | return VisitNode(cbNode, (node as YieldExpression)?.AsteriskToken) ?? 220 | VisitNode(cbNode, (node as YieldExpression)?.Expression); 221 | case SyntaxKind.AwaitExpression: 222 | 223 | return VisitNode(cbNode, (node as AwaitExpression)?.Expression); 224 | case SyntaxKind.PostfixUnaryExpression: 225 | 226 | return VisitNode(cbNode, (node as PostfixUnaryExpression)?.Operand); 227 | case SyntaxKind.BinaryExpression: 228 | 229 | return VisitNode(cbNode, (node as BinaryExpression)?.Left) ?? 230 | VisitNode(cbNode, (node as BinaryExpression)?.OperatorToken) ?? 231 | VisitNode(cbNode, (node as BinaryExpression)?.Right); 232 | case SyntaxKind.AsExpression: 233 | 234 | return VisitNode(cbNode, (node as AsExpression)?.Expression) ?? 235 | VisitNode(cbNode, (node as AsExpression)?.Type); 236 | case SyntaxKind.NonNullExpression: 237 | 238 | return VisitNode(cbNode, (node as NonNullExpression)?.Expression); 239 | case SyntaxKind.MetaProperty: 240 | 241 | return VisitNode(cbNode, (node as MetaProperty)?.Name); 242 | case SyntaxKind.ConditionalExpression: 243 | 244 | return VisitNode(cbNode, (node as ConditionalExpression)?.Condition) ?? 245 | VisitNode(cbNode, (node as ConditionalExpression)?.QuestionToken) ?? 246 | VisitNode(cbNode, (node as ConditionalExpression)?.WhenTrue) ?? 247 | VisitNode(cbNode, (node as ConditionalExpression)?.ColonToken) ?? 248 | VisitNode(cbNode, (node as ConditionalExpression)?.WhenFalse); 249 | case SyntaxKind.SpreadElement: 250 | 251 | return VisitNode(cbNode, (node as SpreadElement)?.Expression); 252 | case SyntaxKind.Block: 253 | case SyntaxKind.ModuleBlock: 254 | 255 | return visitNodes(cbNodes, (node as Block)?.Statements); 256 | case SyntaxKind.SourceFile: 257 | 258 | return visitNodes(cbNodes, (node as SourceFile)?.Statements) ?? 259 | VisitNode(cbNode, (node as SourceFile)?.EndOfFileToken); 260 | case SyntaxKind.VariableStatement: 261 | 262 | return visitNodes(cbNodes, node.Decorators) ?? 263 | visitNodes(cbNodes, node.Modifiers) ?? 264 | VisitNode(cbNode, (node as VariableStatement)?.DeclarationList); 265 | case SyntaxKind.VariableDeclarationList: 266 | 267 | return visitNodes(cbNodes, (node as VariableDeclarationList)?.Declarations); 268 | case SyntaxKind.ExpressionStatement: 269 | 270 | return VisitNode(cbNode, (node as ExpressionStatement)?.Expression); 271 | case SyntaxKind.IfStatement: 272 | 273 | return VisitNode(cbNode, (node as IfStatement)?.Expression) ?? 274 | VisitNode(cbNode, (node as IfStatement)?.ThenStatement) ?? 275 | VisitNode(cbNode, (node as IfStatement)?.ElseStatement); 276 | case SyntaxKind.DoStatement: 277 | 278 | return VisitNode(cbNode, (node as DoStatement)?.Statement) ?? 279 | VisitNode(cbNode, (node as DoStatement)?.Expression); 280 | case SyntaxKind.WhileStatement: 281 | 282 | return VisitNode(cbNode, (node as WhileStatement)?.Expression) ?? 283 | VisitNode(cbNode, (node as WhileStatement)?.Statement); 284 | case SyntaxKind.ForStatement: 285 | 286 | return VisitNode(cbNode, (node as ForStatement)?.Initializer) ?? 287 | VisitNode(cbNode, (node as ForStatement)?.Condition) ?? 288 | VisitNode(cbNode, (node as ForStatement)?.Incrementor) ?? 289 | VisitNode(cbNode, (node as ForStatement)?.Statement); 290 | case SyntaxKind.ForInStatement: 291 | 292 | return VisitNode(cbNode, (node as ForInStatement)?.Initializer) ?? 293 | VisitNode(cbNode, (node as ForInStatement)?.Expression) ?? 294 | VisitNode(cbNode, (node as ForInStatement)?.Statement); 295 | case SyntaxKind.ForOfStatement: 296 | 297 | return VisitNode(cbNode, (node as ForOfStatement)?.AwaitModifier) ?? 298 | VisitNode(cbNode, (node as ForOfStatement)?.Initializer) ?? 299 | VisitNode(cbNode, (node as ForOfStatement)?.Expression) ?? 300 | VisitNode(cbNode, (node as ForOfStatement)?.Statement); 301 | case SyntaxKind.ContinueStatement: 302 | case SyntaxKind.BreakStatement: 303 | 304 | return VisitNode(cbNode, (node as IBreakOrContinueStatement)?.Label); 305 | case SyntaxKind.ReturnStatement: 306 | 307 | return VisitNode(cbNode, (node as ReturnStatement)?.Expression); 308 | case SyntaxKind.WithStatement: 309 | 310 | return VisitNode(cbNode, (node as WithStatement)?.Expression) ?? 311 | VisitNode(cbNode, (node as WithStatement)?.Statement); 312 | case SyntaxKind.SwitchStatement: 313 | 314 | return VisitNode(cbNode, (node as SwitchStatement)?.Expression) ?? 315 | VisitNode(cbNode, (node as SwitchStatement)?.CaseBlock); 316 | case SyntaxKind.CaseBlock: 317 | 318 | return visitNodes(cbNodes, (node as CaseBlock)?.Clauses); 319 | case SyntaxKind.CaseClause: 320 | 321 | return VisitNode(cbNode, (node as CaseClause)?.Expression) ?? 322 | visitNodes(cbNodes, (node as CaseClause)?.Statements); 323 | case SyntaxKind.DefaultClause: 324 | 325 | return visitNodes(cbNodes, (node as DefaultClause)?.Statements); 326 | case SyntaxKind.LabeledStatement: 327 | 328 | return VisitNode(cbNode, (node as LabeledStatement)?.Label) ?? 329 | VisitNode(cbNode, (node as LabeledStatement)?.Statement); 330 | case SyntaxKind.ThrowStatement: 331 | 332 | return VisitNode(cbNode, (node as ThrowStatement)?.Expression); 333 | case SyntaxKind.TryStatement: 334 | 335 | return VisitNode(cbNode, (node as TryStatement)?.TryBlock) ?? 336 | VisitNode(cbNode, (node as TryStatement)?.CatchClause) ?? 337 | VisitNode(cbNode, (node as TryStatement)?.FinallyBlock); 338 | case SyntaxKind.CatchClause: 339 | 340 | return VisitNode(cbNode, (node as CatchClause)?.VariableDeclaration) ?? 341 | VisitNode(cbNode, (node as CatchClause)?.Block); 342 | case SyntaxKind.Decorator: 343 | 344 | return VisitNode(cbNode, (node as Decorator)?.Expression); 345 | case SyntaxKind.ClassDeclaration: 346 | return visitNodes(cbNodes, node.Decorators) ?? 347 | visitNodes(cbNodes, node.Modifiers) ?? 348 | VisitNode(cbNode, (node as ClassDeclaration)?.Name) ?? 349 | visitNodes(cbNodes, (node as ClassDeclaration)?.TypeParameters) ?? 350 | visitNodes(cbNodes, (node as ClassDeclaration)?.HeritageClauses) ?? 351 | visitNodes(cbNodes, (node as ClassDeclaration)?.Members); 352 | case SyntaxKind.ClassExpression: 353 | 354 | return visitNodes(cbNodes, node.Decorators) ?? 355 | visitNodes(cbNodes, node.Modifiers) ?? 356 | VisitNode(cbNode, (node as ClassExpression)?.Name) ?? 357 | visitNodes(cbNodes, (node as ClassExpression)?.TypeParameters) ?? 358 | visitNodes(cbNodes, (node as ClassExpression)?.HeritageClauses) ?? 359 | visitNodes(cbNodes, (node as ClassExpression)?.Members); 360 | case SyntaxKind.InterfaceDeclaration: 361 | 362 | return visitNodes(cbNodes, node.Decorators) ?? 363 | visitNodes(cbNodes, node.Modifiers) ?? 364 | VisitNode(cbNode, (node as InterfaceDeclaration)?.Name) ?? 365 | visitNodes(cbNodes, (node as InterfaceDeclaration)?.TypeParameters) ?? 366 | visitNodes(cbNodes, (node as InterfaceDeclaration)?.HeritageClauses) ?? 367 | visitNodes(cbNodes, (node as InterfaceDeclaration)?.Members); 368 | case SyntaxKind.TypeAliasDeclaration: 369 | 370 | return visitNodes(cbNodes, node.Decorators) ?? 371 | visitNodes(cbNodes, node.Modifiers) ?? 372 | VisitNode(cbNode, (node as TypeAliasDeclaration)?.Name) ?? 373 | visitNodes(cbNodes, (node as TypeAliasDeclaration)?.TypeParameters) ?? 374 | VisitNode(cbNode, (node as TypeAliasDeclaration)?.Type); 375 | case SyntaxKind.EnumDeclaration: 376 | 377 | return visitNodes(cbNodes, node.Decorators) ?? 378 | visitNodes(cbNodes, node.Modifiers) ?? 379 | VisitNode(cbNode, (node as EnumDeclaration)?.Name) ?? 380 | visitNodes(cbNodes, (node as EnumDeclaration)?.Members); 381 | case SyntaxKind.EnumMember: 382 | 383 | return VisitNode(cbNode, (node as EnumMember)?.Name) ?? 384 | VisitNode(cbNode, (node as EnumMember)?.Initializer); 385 | case SyntaxKind.ModuleDeclaration: 386 | 387 | return visitNodes(cbNodes, node.Decorators) ?? 388 | visitNodes(cbNodes, node.Modifiers) ?? 389 | VisitNode(cbNode, (node as ModuleDeclaration)?.Name) ?? 390 | VisitNode(cbNode, (node as ModuleDeclaration)?.Body); 391 | case SyntaxKind.ImportEqualsDeclaration: 392 | 393 | return visitNodes(cbNodes, node.Decorators) ?? 394 | visitNodes(cbNodes, node.Modifiers) ?? 395 | VisitNode(cbNode, (node as ImportEqualsDeclaration)?.Name) ?? 396 | VisitNode(cbNode, (node as ImportEqualsDeclaration)?.ModuleReference); 397 | case SyntaxKind.ImportDeclaration: 398 | 399 | return visitNodes(cbNodes, node.Decorators) ?? 400 | visitNodes(cbNodes, node.Modifiers) ?? 401 | VisitNode(cbNode, (node as ImportDeclaration)?.ImportClause) ?? 402 | VisitNode(cbNode, (node as ImportDeclaration)?.ModuleSpecifier); 403 | case SyntaxKind.ImportClause: 404 | 405 | return VisitNode(cbNode, (node as ImportClause)?.Name) ?? 406 | VisitNode(cbNode, (node as ImportClause)?.NamedBindings); 407 | case SyntaxKind.NamespaceExportDeclaration: 408 | 409 | return VisitNode(cbNode, (node as NamespaceExportDeclaration)?.Name); 410 | case SyntaxKind.NamespaceImport: 411 | 412 | return VisitNode(cbNode, (node as NamespaceImport)?.Name); 413 | case SyntaxKind.NamedImports: 414 | case SyntaxKind.NamedExports: 415 | 416 | if (node is NamedImports) return visitNodes(cbNodes, (node as NamedImports)?.Elements); 417 | else return visitNodes(cbNodes, (node as NamedExports)?.Elements); 418 | case SyntaxKind.ExportDeclaration: 419 | 420 | return visitNodes(cbNodes, node.Decorators) ?? 421 | visitNodes(cbNodes, node.Modifiers) ?? 422 | VisitNode(cbNode, (node as ExportDeclaration)?.ExportClause) ?? 423 | VisitNode(cbNode, (node as ExportDeclaration)?.ModuleSpecifier); 424 | case SyntaxKind.ImportSpecifier: 425 | case SyntaxKind.ExportSpecifier: 426 | return VisitNode(cbNode, (node as IMportOrExportSpecifier)?.PropertyName ?? 427 | VisitNode(cbNode, (node as IMportOrExportSpecifier)?.Name)); 428 | case SyntaxKind.ExportAssignment: 429 | 430 | return visitNodes(cbNodes, node.Decorators) ?? 431 | visitNodes(cbNodes, node.Modifiers) ?? 432 | VisitNode(cbNode, (node as ExportAssignment)?.Expression); 433 | case SyntaxKind.TemplateExpression: 434 | 435 | return VisitNode(cbNode, (node as TemplateExpression)?.Head) ?? 436 | visitNodes(cbNodes, (node as TemplateExpression)?.TemplateSpans); 437 | case SyntaxKind.TemplateSpan: 438 | 439 | return VisitNode(cbNode, (node as TemplateSpan)?.Expression) ?? 440 | VisitNode(cbNode, (node as TemplateSpan)?.Literal); 441 | case SyntaxKind.ComputedPropertyName: 442 | 443 | return VisitNode(cbNode, (node as ComputedPropertyName)?.Expression); 444 | case SyntaxKind.HeritageClause: 445 | 446 | return visitNodes(cbNodes, (node as HeritageClause)?.Types); 447 | case SyntaxKind.ExpressionWithTypeArguments: 448 | 449 | return VisitNode(cbNode, (node as ExpressionWithTypeArguments)?.Expression) ?? 450 | visitNodes(cbNodes, (node as ExpressionWithTypeArguments)?.TypeArguments); 451 | case SyntaxKind.ExternalModuleReference: 452 | 453 | return VisitNode(cbNode, (node as ExternalModuleReference)?.Expression); 454 | case SyntaxKind.MissingDeclaration: 455 | 456 | return visitNodes(cbNodes, node.Decorators); 457 | case SyntaxKind.JsxElement: 458 | 459 | return VisitNode(cbNode, (node as JsxElement)?.OpeningElement) ?? 460 | visitNodes(cbNodes, (node as JsxElement)?.JsxChildren) ?? 461 | VisitNode(cbNode, (node as JsxElement)?.ClosingElement); 462 | case SyntaxKind.JsxSelfClosingElement: 463 | case SyntaxKind.JsxOpeningElement: 464 | return VisitNode(cbNode, 465 | (node as JsxSelfClosingElement)?.TagName ?? (node as JsxOpeningElement)?.TagName) ?? 466 | VisitNode(cbNode, 467 | (node as JsxSelfClosingElement)?.Attributes ?? (node as JsxOpeningElement)?.Attributes); 468 | case SyntaxKind.JsxAttributes: 469 | 470 | return visitNodes(cbNodes, (node as JsxAttributes)?.Properties); 471 | case SyntaxKind.JsxAttribute: 472 | 473 | return VisitNode(cbNode, (node as JsxAttribute)?.Name) ?? 474 | VisitNode(cbNode, (node as JsxAttribute)?.Initializer); 475 | case SyntaxKind.JsxSpreadAttribute: 476 | 477 | return VisitNode(cbNode, (node as JsxSpreadAttribute)?.Expression); 478 | case SyntaxKind.JsxExpression: 479 | 480 | return VisitNode(cbNode, (node as JsxExpression).DotDotDotToken) ?? 481 | VisitNode(cbNode, (node as JsxExpression).Expression); 482 | case SyntaxKind.JsxClosingElement: 483 | 484 | return VisitNode(cbNode, (node as JsxClosingElement)?.TagName); 485 | case SyntaxKind.JsDocTypeExpression: 486 | 487 | return VisitNode(cbNode, (node as JsDocTypeExpression)?.Type); 488 | case SyntaxKind.JsDocUnionType: 489 | 490 | return visitNodes(cbNodes, (node as JsDocUnionType)?.Types); 491 | case SyntaxKind.JsDocTupleType: 492 | 493 | return visitNodes(cbNodes, (node as JsDocTupleType)?.Types); 494 | case SyntaxKind.JsDocArrayType: 495 | 496 | return VisitNode(cbNode, (node as JsDocArrayType)?.ElementType); 497 | case SyntaxKind.JsDocNonNullableType: 498 | 499 | return VisitNode(cbNode, (node as JsDocNonNullableType)?.Type); 500 | case SyntaxKind.JsDocNullableType: 501 | 502 | return VisitNode(cbNode, (node as JsDocNullableType)?.Type); 503 | case SyntaxKind.JsDocRecordType: 504 | 505 | return VisitNode(cbNode, (node as JsDocRecordType)?.Literal); 506 | case SyntaxKind.JsDocTypeReference: 507 | 508 | return VisitNode(cbNode, (node as JsDocTypeReference)?.Name) ?? 509 | visitNodes(cbNodes, (node as JsDocTypeReference)?.TypeArguments); 510 | case SyntaxKind.JsDocOptionalType: 511 | 512 | return VisitNode(cbNode, (node as JsDocOptionalType)?.Type); 513 | case SyntaxKind.JsDocFunctionType: 514 | 515 | return visitNodes(cbNodes, (node as JsDocFunctionType)?.Parameters) ?? 516 | VisitNode(cbNode, (node as JsDocFunctionType)?.Type); 517 | case SyntaxKind.JsDocVariadicType: 518 | 519 | return VisitNode(cbNode, (node as JsDocVariadicType)?.Type); 520 | case SyntaxKind.JsDocConstructorType: 521 | 522 | return VisitNode(cbNode, (node as JsDocConstructorType)?.Type); 523 | case SyntaxKind.JsDocThisType: 524 | 525 | return VisitNode(cbNode, (node as JsDocThisType)?.Type); 526 | case SyntaxKind.JsDocRecordMember: 527 | 528 | return VisitNode(cbNode, (node as JsDocRecordMember)?.Name) ?? 529 | VisitNode(cbNode, (node as JsDocRecordMember)?.Type); 530 | case SyntaxKind.JsDocComment: 531 | 532 | return visitNodes(cbNodes, (node as JsDoc)?.Tags); 533 | case SyntaxKind.JsDocParameterTag: 534 | 535 | return VisitNode(cbNode, (node as JsDocParameterTag)?.PreParameterName) ?? 536 | VisitNode(cbNode, (node as JsDocParameterTag)?.TypeExpression) ?? 537 | VisitNode(cbNode, (node as JsDocParameterTag)?.PostParameterName); 538 | case SyntaxKind.JsDocReturnTag: 539 | 540 | return VisitNode(cbNode, (node as JsDocReturnTag)?.TypeExpression); 541 | case SyntaxKind.JsDocTypeTag: 542 | 543 | return VisitNode(cbNode, (node as JsDocTypeTag)?.TypeExpression); 544 | case SyntaxKind.JsDocAugmentsTag: 545 | 546 | return VisitNode(cbNode, (node as JsDocAugmentsTag)?.TypeExpression); 547 | case SyntaxKind.JsDocTemplateTag: 548 | 549 | return visitNodes(cbNodes, (node as JsDocTemplateTag)?.TypeParameters); 550 | case SyntaxKind.JsDocTypedefTag: 551 | 552 | return VisitNode(cbNode, (node as JsDocTypedefTag)?.TypeExpression) ?? 553 | VisitNode(cbNode, (node as JsDocTypedefTag)?.FullName) ?? 554 | VisitNode(cbNode, (node as JsDocTypedefTag)?.Name) ?? 555 | VisitNode(cbNode, (node as JsDocTypedefTag)?.JsDocTypeLiteral); 556 | case SyntaxKind.JsDocTypeLiteral: 557 | 558 | return visitNodes(cbNodes, (node as JsDocTypeLiteral)?.JsDocPropertyTags); 559 | case SyntaxKind.JsDocPropertyTag: 560 | 561 | return VisitNode(cbNode, (node as JsDocPropertyTag)?.TypeExpression) ?? 562 | VisitNode(cbNode, (node as JsDocPropertyTag)?.Name); 563 | case SyntaxKind.PartiallyEmittedExpression: 564 | 565 | return VisitNode(cbNode, (node as PartiallyEmittedExpression)?.Expression); 566 | case SyntaxKind.JsDocLiteralType: 567 | 568 | return VisitNode(cbNode, (node as JsDocLiteralType)?.Literal); 569 | } 570 | return null; 571 | } 572 | 573 | private static INode VisitNodes(Func cbNodes, List list) 574 | { 575 | throw new NotImplementedException(); 576 | } 577 | 578 | 579 | public bool IsExternalModule(SourceFile file) 580 | { 581 | return file.ExternalModuleIndicator != null; 582 | } 583 | } 584 | } -------------------------------------------------------------------------------- /TypeScriptAST/Parser/TsExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Text.RegularExpressions; 6 | 7 | namespace Zu.TypeScript.TsParser 8 | { 9 | public static class TsExtensions 10 | { 11 | public static int charCodeAt(this string str, int pos) => (int)str[pos]; 12 | //public static int length(this string str) => str.Length; 13 | public static string substring(this string str, int start, int? end = null) 14 | { 15 | return end == null ? str.Substring(start) : str.Substring(start, (int)end - start); 16 | } 17 | public static string[] exec(this Regex r, string text) => r.Match(text).Captures.Cast().ToArray(); 18 | public static bool test(this Regex r, string text) => r.IsMatch(text); 19 | public static void pop(this List list) => list.RemoveAt(0); 20 | 21 | 22 | } 23 | public static class String 24 | { 25 | internal static string fromCharCode(params int[] codes) 26 | { 27 | var sb = new StringBuilder(); 28 | foreach (var c in codes) 29 | { 30 | sb.Append((char)c); 31 | } 32 | return sb.ToString(); 33 | } 34 | public static string slice(this string str, int start, int end = int.MaxValue) 35 | { 36 | if (start < 0) 37 | start += str.Length; 38 | if (end < 0) 39 | end += str.Length; 40 | 41 | start = Math.Min(Math.Max(start, 0), str.Length); 42 | end = Math.Min(Math.Max(end, 0), str.Length); 43 | if (end <= start) 44 | return string.Empty; 45 | 46 | return str.Substring(start, end - start); 47 | } 48 | 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /TypeScriptAST/Parser/Utilities.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using Zu.TypeScript.TsTypes; 4 | using static Zu.TypeScript.TsParser.Factory; 5 | using static Zu.TypeScript.TsParser.Scanner; 6 | using static Zu.TypeScript.TsParser.Ts; 7 | 8 | namespace Zu.TypeScript.TsParser 9 | { 10 | public class Utilities 11 | { 12 | public static int GetFullWidth(INode node) 13 | { 14 | return (node.End ?? 0) - (node.Pos ?? 0); 15 | } 16 | 17 | 18 | public static INode ContainsParseError(INode node) 19 | { 20 | AggregateChildData(node); 21 | 22 | return (node.Flags & NodeFlags.ThisNodeOrAnySubNodesHasError) != 0 ? node : null; 23 | } 24 | 25 | 26 | public static void AggregateChildData(INode node) 27 | { 28 | if ((node.Flags & NodeFlags.HasAggregatedChildData) != 0) 29 | { 30 | var thisNodeOrAnySubNodesHasError = (node.Flags & NodeFlags.ThisNodeHasError) != 0 || 31 | ForEachChild(node, ContainsParseError) != null; 32 | if (thisNodeOrAnySubNodesHasError) 33 | node.Flags |= NodeFlags.ThisNodeOrAnySubNodesHasError; 34 | 35 | 36 | node.Flags |= NodeFlags.HasAggregatedChildData; 37 | } 38 | } 39 | 40 | 41 | public static bool NodeIsMissing(INode node) 42 | { 43 | if (node == null) 44 | return true; 45 | 46 | 47 | return node.Pos == node.End && node.Pos >= 0 && node.Kind != SyntaxKind.EndOfFileToken; 48 | } 49 | 50 | 51 | public static string GetTextOfNodeFromSourceText(string sourceText, INode node) 52 | { 53 | if (NodeIsMissing(node)) 54 | return ""; 55 | 56 | 57 | return sourceText.substring(SkipTriviaM(sourceText, node.Pos ?? 0), node.End); 58 | } 59 | 60 | 61 | public static string EscapeIdentifier(string identifier) 62 | { 63 | return identifier.Length >= 2 && identifier.charCodeAt(0) == (int) CharacterCodes._ && 64 | identifier.charCodeAt(1) == (int) CharacterCodes._ 65 | ? "_" + identifier 66 | : identifier; 67 | } 68 | 69 | 70 | public static List GetLeadingCommentRangesOfNodeFromText(INode node, string text) 71 | { 72 | return GetLeadingCommentRanges(text, node.Pos ?? 0); 73 | } 74 | 75 | 76 | public static List GetJsDocCommentRanges(INode node, string text) 77 | { 78 | var commentRanges = node.Kind == SyntaxKind.Parameter || 79 | node.Kind == SyntaxKind.TypeParameter || 80 | node.Kind == SyntaxKind.FunctionExpression || 81 | node.Kind == SyntaxKind.ArrowFunction 82 | ? GetTrailingCommentRanges(text, node.Pos ?? 0).Concat(GetLeadingCommentRanges(text, node.Pos ?? 0)) 83 | : GetLeadingCommentRangesOfNodeFromText(node, text); 84 | if (commentRanges == null) commentRanges = new List(); 85 | return commentRanges.Where(comment => 86 | text.charCodeAt((comment.Pos ?? 0) + 1) == (int) CharacterCodes.Asterisk && 87 | text.charCodeAt((comment.Pos ?? 0) + 2) == (int) CharacterCodes.Asterisk && 88 | text.charCodeAt((comment.Pos ?? 0) + 3) != (int) CharacterCodes.Slash) 89 | .ToList(); 90 | } 91 | 92 | 93 | public static bool IsKeyword(SyntaxKind token) 94 | { 95 | return SyntaxKind.FirstKeyword <= token && token <= SyntaxKind.LastKeyword; 96 | } 97 | 98 | 99 | public static bool IsTrivia(SyntaxKind token) 100 | { 101 | return SyntaxKind.FirstTriviaToken <= token && token <= SyntaxKind.LastTriviaToken; 102 | } 103 | 104 | 105 | public static bool IsModifierKind(SyntaxKind token) 106 | { 107 | switch (token) 108 | { 109 | case SyntaxKind.AbstractKeyword: 110 | case SyntaxKind.AsyncKeyword: 111 | case SyntaxKind.ConstKeyword: 112 | case SyntaxKind.DeclareKeyword: 113 | case SyntaxKind.DefaultKeyword: 114 | case SyntaxKind.ExportKeyword: 115 | case SyntaxKind.PublicKeyword: 116 | case SyntaxKind.PrivateKeyword: 117 | case SyntaxKind.ProtectedKeyword: 118 | case SyntaxKind.ReadonlyKeyword: 119 | case SyntaxKind.StaticKeyword: 120 | 121 | return true; 122 | } 123 | 124 | return false; 125 | } 126 | 127 | 128 | public static bool IsParameterDeclaration(IVariableLikeDeclaration node) 129 | { 130 | var root = GetRootDeclaration(node); 131 | 132 | return root.Kind == SyntaxKind.Parameter; 133 | } 134 | 135 | 136 | public static INode GetRootDeclaration(INode node) 137 | { 138 | while (node.Kind == SyntaxKind.BindingElement) 139 | node = node.Parent.Parent; 140 | 141 | return node; 142 | } 143 | 144 | 145 | public static bool HasModifiers(Node node) 146 | { 147 | return GetModifierFlags(node) != ModifierFlags.None; 148 | } 149 | 150 | 151 | public static bool HasModifier(INode node, ModifierFlags flags) 152 | { 153 | return (GetModifierFlags(node) & flags) != 0; 154 | } 155 | 156 | 157 | public static ModifierFlags GetModifierFlags(INode node) 158 | { 159 | if ((node.ModifierFlagsCache & ModifierFlags.HasComputedFlags) != 0) 160 | return node.ModifierFlagsCache & ~ModifierFlags.HasComputedFlags; 161 | var flags = ModifierFlags.None; 162 | if (node.Modifiers != null) 163 | foreach (var modifier in node.Modifiers) 164 | flags |= ModifierToFlag(modifier.Kind); 165 | if (node.Flags.HasFlag(NodeFlags.NestedNamespace) || node.Kind == SyntaxKind.Identifier && 166 | ((Identifier) node).IsInJsDocNamespace) 167 | flags |= ModifierFlags.Export; 168 | 169 | 170 | node.ModifierFlagsCache = flags | ModifierFlags.HasComputedFlags; 171 | 172 | return flags; 173 | } 174 | 175 | 176 | public static ModifierFlags ModifierToFlag(SyntaxKind token) 177 | { 178 | switch (token) 179 | { 180 | case SyntaxKind.StaticKeyword: 181 | return ModifierFlags.Static; 182 | case SyntaxKind.PublicKeyword: 183 | return ModifierFlags.Public; 184 | case SyntaxKind.ProtectedKeyword: 185 | return ModifierFlags.Protected; 186 | case SyntaxKind.PrivateKeyword: 187 | return ModifierFlags.Private; 188 | case SyntaxKind.AbstractKeyword: 189 | return ModifierFlags.Abstract; 190 | case SyntaxKind.ExportKeyword: 191 | return ModifierFlags.Export; 192 | case SyntaxKind.DeclareKeyword: 193 | return ModifierFlags.Ambient; 194 | case SyntaxKind.ConstKeyword: 195 | return ModifierFlags.Const; 196 | case SyntaxKind.DefaultKeyword: 197 | return ModifierFlags.Default; 198 | case SyntaxKind.AsyncKeyword: 199 | return ModifierFlags.Async; 200 | case SyntaxKind.ReadonlyKeyword: 201 | return ModifierFlags.Readonly; 202 | } 203 | 204 | return ModifierFlags.None; 205 | } 206 | 207 | 208 | public static bool IsLogicalOperator(SyntaxKind token) 209 | { 210 | return token == SyntaxKind.BarBarToken 211 | || token == SyntaxKind.AmpersandAmpersandToken 212 | || token == SyntaxKind.ExclamationToken; 213 | } 214 | 215 | 216 | public static bool IsAssignmentOperator(SyntaxKind token) 217 | { 218 | return token >= SyntaxKind.FirstAssignment && token <= SyntaxKind.LastAssignment; 219 | } 220 | 221 | 222 | public static bool IsLeftHandSideExpressionKind(SyntaxKind kind) 223 | { 224 | return kind == SyntaxKind.PropertyAccessExpression 225 | || kind == SyntaxKind.ElementAccessExpression 226 | || kind == SyntaxKind.NewExpression 227 | || kind == SyntaxKind.CallExpression 228 | || kind == SyntaxKind.JsxElement 229 | || kind == SyntaxKind.JsxSelfClosingElement 230 | || kind == SyntaxKind.TaggedTemplateExpression 231 | || kind == SyntaxKind.ArrayLiteralExpression 232 | || kind == SyntaxKind.ParenthesizedExpression 233 | || kind == SyntaxKind.ObjectLiteralExpression 234 | || kind == SyntaxKind.ClassExpression 235 | || kind == SyntaxKind.FunctionExpression 236 | || kind == SyntaxKind.Identifier 237 | || kind == SyntaxKind.RegularExpressionLiteral 238 | || kind == SyntaxKind.NumericLiteral 239 | || kind == SyntaxKind.StringLiteral 240 | || kind == SyntaxKind.NoSubstitutionTemplateLiteral 241 | || kind == SyntaxKind.TemplateExpression 242 | || kind == SyntaxKind.FalseKeyword 243 | || kind == SyntaxKind.NullKeyword 244 | || kind == SyntaxKind.ThisKeyword 245 | || kind == SyntaxKind.TrueKeyword 246 | || kind == SyntaxKind.SuperKeyword 247 | || kind == SyntaxKind.NonNullExpression 248 | || kind == SyntaxKind.MetaProperty; 249 | } 250 | 251 | 252 | public static bool IsLeftHandSideExpression(IExpression node) 253 | { 254 | return IsLeftHandSideExpressionKind(SkipPartiallyEmittedExpressions(node).Kind); 255 | } 256 | } 257 | } -------------------------------------------------------------------------------- /TypeScriptAST/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | [assembly: AssemblyTitle("TypeScriptAST")] 6 | [assembly: AssemblyDescription(".NET port of Microsoft's TypeScript parser for simple AST manipulation")] 7 | [assembly: AssemblyConfiguration("")] 8 | [assembly: AssemblyCompany("Oleg Zudov")] 9 | [assembly: AssemblyProduct("TypeScriptAST")] 10 | [assembly: AssemblyCopyright("Copyright © Oleg Zudov 2017")] 11 | [assembly: AssemblyTrademark("")] 12 | [assembly: AssemblyCulture("")] 13 | 14 | [assembly: ComVisible(false)] 15 | 16 | [assembly: Guid("7728b98c-9e88-4e6d-8ecd-d51ded278ac2")] 17 | 18 | [assembly: AssemblyVersion("1.0.2.0")] 19 | [assembly: AssemblyFileVersion("1.0.2.0")] 20 | -------------------------------------------------------------------------------- /TypeScriptAST/TsTypes/Enums.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Zu.TypeScript.TsTypes 4 | { 5 | [Flags] 6 | public enum NodeFlags 7 | { 8 | None = 0, 9 | Let = 1 << 0, // Variable declaration 10 | Const = 1 << 1, // Variable declaration 11 | NestedNamespace = 1 << 2, // Namespace declaration 12 | Synthesized = 1 << 3, // Node was synthesized during transformation 13 | Namespace = 1 << 4, // Namespace declaration 14 | ExportContext = 1 << 5, // Export context (initialized by binding) 15 | ContainsThis = 1 << 6, // Interface contains references to "this" 16 | HasImplicitReturn = 1 << 7, // If function implicitly returns on one of codepaths (initialized by binding) 17 | 18 | HasExplicitReturn = 19 | 1 << 8, // If function has explicit reachable return on one of codepaths (initialized by binding) 20 | GlobalAugmentation = 1 << 9, // Set if module declaration is an augmentation for the global scope 21 | HasAsyncFunctions = 1 << 10, // If the file has async functions (initialized by binding) 22 | DisallowInContext = 1 << 11, // If node was parsed in a context where 'in-expressions' are not allowed 23 | YieldContext = 1 << 12, // If node was parsed in the 'yield' context created when parsing a generator 24 | DecoratorContext = 1 << 13, // If node was parsed as part of a decorator 25 | AwaitContext = 1 << 14, // If node was parsed in the 'await' context created when parsing an async function 26 | ThisNodeHasError = 1 << 15, // If the parser encountered an error when parsing the code that created this node 27 | JavaScriptFile = 1 << 16, // If node was parsed in a JavaScript 28 | ThisNodeOrAnySubNodesHasError = 1 << 17, // If this node or any of its children had an error 29 | HasAggregatedChildData = 1 << 18, // If we've computed data from children and cached it in this node 30 | 31 | BlockScoped = Let | Const, 32 | 33 | ReachabilityCheckFlags = HasImplicitReturn | HasExplicitReturn, 34 | ReachabilityAndEmitFlags = ReachabilityCheckFlags | HasAsyncFunctions, 35 | 36 | // Parsing context flags 37 | ContextFlags = DisallowInContext | YieldContext | DecoratorContext | AwaitContext | JavaScriptFile, 38 | 39 | // Exclude these flags when parsing a Type 40 | TypeExcludesFlags = YieldContext | AwaitContext 41 | } 42 | 43 | public enum ParsingContext 44 | { 45 | SourceElements, // Elements in source file 46 | BlockStatements, // Statements in block 47 | SwitchClauses, // Clauses in switch statement 48 | SwitchClauseStatements, // Statements in switch clause 49 | TypeMembers, // Members in interface or type literal 50 | ClassMembers, // Members in class declaration 51 | EnumMembers, // Members in enum declaration 52 | HeritageClauseElement, // Elements in a heritage clause 53 | VariableDeclarations, // Variable declarations in variable statement 54 | ObjectBindingElements, // Binding elements in object binding list 55 | ArrayBindingElements, // Binding elements in array binding list 56 | ArgumentExpressions, // Expressions in argument list 57 | ObjectLiteralMembers, // Members in object literal 58 | JsxAttributes, // Attributes in jsx element 59 | JsxChildren, // Things between opening and closing JSX tags 60 | ArrayLiteralMembers, // Members in array literal 61 | Parameters, // Parameters in parameter list 62 | RestProperties, // Property names in a rest type list 63 | TypeParameters, // Type parameters in type parameter list 64 | TypeArguments, // Type arguments in type argument list 65 | TupleElementTypes, // Element types in tuple element type list 66 | HeritageClauses, // Heritage clauses for a class or interface declaration. 67 | ImportOrExportSpecifiers, // Named import clause's import specifier list 68 | JSDocFunctionParameters, 69 | JSDocTypeArguments, 70 | JSDocRecordMembers, 71 | JSDocTupleTypes, 72 | Count // Number of parsing contexts 73 | } 74 | 75 | public enum Tristate 76 | { 77 | False, 78 | True, 79 | Unknown 80 | } 81 | 82 | public enum JSDocState 83 | { 84 | BeginningOfLine, 85 | SawAsterisk, 86 | SavingComments 87 | } 88 | 89 | public enum ModifierFlags 90 | { 91 | None = 0, 92 | Export = 1 << 0, // Declarations 93 | Ambient = 1 << 1, // Declarations 94 | Public = 1 << 2, // Property/Method 95 | Private = 1 << 3, // Property/Method 96 | Protected = 1 << 4, // Property/Method 97 | Static = 1 << 5, // Property/Method 98 | Readonly = 1 << 6, // Property/Method 99 | Abstract = 1 << 7, // Class/Method/ConstructSignature 100 | Async = 1 << 8, // Property/Method/Function 101 | Default = 1 << 9, // Function/Class (export default declaration) 102 | Const = 1 << 11, // Variable declaration 103 | HasComputedFlags = 1 << 29, // Modifier flags have been computed 104 | 105 | AccessibilityModifier = Public | Private | Protected, 106 | 107 | // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. 108 | ParameterPropertyModifier = AccessibilityModifier | Readonly, 109 | NonPublicAccessibilityModifier = Private | Protected, 110 | 111 | TypeScriptModifier = Ambient | Public | Private | Protected | Readonly | Abstract | Const, 112 | ExportDefault = Export | Default 113 | } 114 | 115 | public enum JsxFlags 116 | { 117 | None = 0, 118 | 119 | /** An element from a named property of the JSX.IntrinsicElements interface */ 120 | IntrinsicNamedElement = 1 << 0, 121 | 122 | /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ 123 | IntrinsicIndexedElement = 1 << 1, 124 | 125 | IntrinsicElement = IntrinsicNamedElement | IntrinsicIndexedElement 126 | } 127 | 128 | public enum RelationComparisonResult 129 | { 130 | Succeeded = 1, // Should be truthy 131 | Failed = 2, 132 | FailedAndReported = 3 133 | } 134 | 135 | public enum GeneratedIdentifierKind 136 | { 137 | None, // Not automatically generated. 138 | Auto, // Automatically generated identifier. 139 | Loop, // Automatically generated identifier with a preference for '_i'. 140 | Unique, // Unique name based on the 'text' property. 141 | Node // Unique name based on the node in the 'original' property. 142 | } 143 | 144 | public enum FlowFlags 145 | { 146 | Unreachable = 1 << 0, // Unreachable code 147 | Start = 1 << 1, // Start of flow graph 148 | BranchLabel = 1 << 2, // Non-looping junction 149 | LoopLabel = 1 << 3, // Looping junction 150 | Assignment = 1 << 4, // Assignment 151 | TrueCondition = 1 << 5, // Condition known to be true 152 | FalseCondition = 1 << 6, // Condition known to be false 153 | SwitchClause = 1 << 7, // Switch statement clause 154 | ArrayMutation = 1 << 8, // Potential array mutation 155 | Referenced = 1 << 9, // Referenced as antecedent once 156 | Shared = 1 << 10, // Referenced as antecedent more than once 157 | PreFinally = 1 << 11, // Injected edge that links pre-finally label and pre-try flow 158 | AfterFinally = 1 << 12, // Injected edge that links post-finally flow with the rest of the graph 159 | Label = BranchLabel | LoopLabel, 160 | Condition = TrueCondition | FalseCondition 161 | } 162 | 163 | public enum ExitStatus 164 | { 165 | // Compiler ran successfully. Either this was a simple do-nothing compilation (for example, 166 | // when -version or -help was provided, or this was a normal compilation, no diagnostics 167 | // were produced, and all outputs were generated successfully. 168 | Success = 0, 169 | 170 | // Diagnostics were produced and because of them no code was generated. 171 | DiagnosticsPresentOutputsSkipped = 1, 172 | 173 | // Diagnostics were produced and outputs were generated in spite of them. 174 | DiagnosticsPresentOutputsGenerated = 2 175 | } 176 | 177 | public enum NodeBuilderFlags 178 | { 179 | None = 0, 180 | AllowThisInObjectLiteral = 1 << 0, 181 | AllowQualifedNameInPlaceOfIdentifier = 1 << 1, 182 | AllowTypeParameterInQualifiedName = 1 << 2, 183 | AllowAnonymousIdentifier = 1 << 3, 184 | AllowEmptyUnionOrIntersection = 1 << 4, 185 | AllowEmptyTuple = 1 << 5 186 | } 187 | 188 | public enum TypeFormatFlags 189 | { 190 | None = 0x00000000, 191 | WriteArrayAsGenericType = 0x00000001, // Write Array instead T[] 192 | UseTypeOfFunction = 0x00000002, // Write typeof instead of function type literal 193 | NoTruncation = 0x00000004, // Don't truncate typeToString result 194 | WriteArrowStyleSignature = 0x00000008, // Write arrow style signature 195 | 196 | WriteOwnNameForAnyLike = 197 | 0x00000010, // Write symbol's own name instead of 'any' for any like types (eg. unknown, __resolving__ etc) 198 | 199 | WriteTypeArgumentsOfSignature = 200 | 0x00000020, // Write the type arguments instead of type parameters of the signature 201 | InElementType = 0x00000040, // Writing an array or union element type 202 | 203 | UseFullyQualifiedType = 204 | 0x00000080, // Write out the fully qualified type name (eg. Module.Type, instead of Type) 205 | InFirstTypeArgument = 0x00000100, // Writing first type argument of the instantiated type 206 | InTypeAlias = 0x00000200, // Writing type in type alias declaration 207 | 208 | UseTypeAliasValue = 209 | 0x00000400, // Serialize the type instead of using type-alias. This is needed when we emit declaration file. 210 | SuppressAnyReturnType = 0x00000800, // If the return type is any-like, don't offer a return type. 211 | AddUndefined = 0x00001000 // Add undefined to types of initialized, non-optional parameters 212 | } 213 | 214 | public enum SymbolFormatFlags 215 | { 216 | None = 0x00000000, 217 | 218 | // Write symbols's type argument if it is instantiated symbol 219 | // eg. class C { p: T } <-- Show p as C.p here 220 | // var a: C; 221 | // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p 222 | WriteTypeParametersOrArguments = 0x00000001, 223 | 224 | // Use only external alias information to get the symbol name in the given context 225 | // eg. module m { export class c { } } import x = m.c; 226 | // When this flag is specified m.c will be used to refer to the class instead of alias symbol x 227 | UseOnlyExternalAliasing = 0x00000002 228 | } 229 | 230 | public enum SymbolAccessibility 231 | { 232 | Accessible, 233 | NotAccessible, 234 | CannotBeNamed 235 | } 236 | 237 | public enum SyntheticSymbolKind 238 | { 239 | UnionOrIntersection, 240 | Spread 241 | } 242 | 243 | public enum TypePredicateKind 244 | { 245 | This, 246 | Identifier 247 | } 248 | 249 | public enum TypeReferenceSerializationKind 250 | { 251 | Unknown, // The TypeReferenceNode could not be resolved. The type name 252 | 253 | // should be emitted using a safe fallback. 254 | TypeWithConstructSignatureAndValue, // The TypeReferenceNode resolves to a type with a constructor 255 | 256 | // function that can be reached at runtime (e.g. a `class` 257 | // declaration or a `var` declaration for the static side 258 | // of a type, such as the global `Promise` type in lib.d.ts). 259 | VoidNullableOrNeverType, // The TypeReferenceNode resolves to a Void-like, Nullable, or Never type. 260 | NumberLikeType, // The TypeReferenceNode resolves to a Number-like type. 261 | StringLikeType, // The TypeReferenceNode resolves to a String-like type. 262 | BooleanType, // The TypeReferenceNode resolves to a Boolean-like type. 263 | ArrayLikeType, // The TypeReferenceNode resolves to an Array-like type. 264 | EsSymbolType, // The TypeReferenceNode resolves to the ESSymbol type. 265 | Promise, // The TypeReferenceNode resolved to the global Promise constructor symbol. 266 | TypeWithCallSignature, // The TypeReferenceNode resolves to a Function type or a type 267 | 268 | // with call signatures. 269 | ObjectType // The TypeReferenceNode resolves to any other type. 270 | } 271 | 272 | public enum SymbolFlags 273 | { 274 | None = 0, 275 | FunctionScopedVariable = 1 << 0, // Variable (var) or parameter 276 | BlockScopedVariable = 1 << 1, // A block-scoped variable (let or const) 277 | Property = 1 << 2, // Property or enum member 278 | EnumMember = 1 << 3, // Enum member 279 | Function = 1 << 4, // Function 280 | Class = 1 << 5, // Class 281 | Interface = 1 << 6, // Interface 282 | ConstEnum = 1 << 7, // Const enum 283 | RegularEnum = 1 << 8, // Enum 284 | ValueModule = 1 << 9, // Instantiated module 285 | NamespaceModule = 1 << 10, // Uninstantiated module 286 | TypeLiteral = 1 << 11, // Type Literal or mapped type 287 | ObjectLiteral = 1 << 12, // Object Literal 288 | Method = 1 << 13, // Method 289 | Constructor = 1 << 14, // Constructor 290 | GetAccessor = 1 << 15, // Get accessor 291 | SetAccessor = 1 << 16, // Set accessor 292 | Signature = 1 << 17, // Call, construct, or index signature 293 | TypeParameter = 1 << 18, // Type parameter 294 | TypeAlias = 1 << 19, // Type alias 295 | ExportValue = 1 << 20, // Exported value marker (see comment in declareModuleMember in binder) 296 | ExportType = 1 << 21, // Exported type marker (see comment in declareModuleMember in binder) 297 | ExportNamespace = 1 << 22, // Exported namespace marker (see comment in declareModuleMember in binder) 298 | Alias = 1 << 23, // An alias for another symbol (see comment in isAliasSymbolDeclaration in checker) 299 | Prototype = 1 << 24, // Prototype property (no source representation) 300 | ExportStar = 1 << 25, // Export * declaration 301 | Optional = 1 << 26, // Optional property 302 | Transient = 1 << 27, // Transient symbol (created during type check) 303 | 304 | Enum = RegularEnum | ConstEnum, 305 | Variable = FunctionScopedVariable | BlockScopedVariable, 306 | 307 | Value = Variable | Property | EnumMember | Function | Class | Enum | ValueModule | Method | GetAccessor | 308 | SetAccessor, 309 | Type = Class | Interface | Enum | EnumMember | TypeLiteral | ObjectLiteral | TypeParameter | TypeAlias, 310 | Namespace = ValueModule | NamespaceModule | Enum, 311 | Module = ValueModule | NamespaceModule, 312 | Accessor = GetAccessor | SetAccessor, 313 | 314 | // Variables can be redeclared, but can not redeclare a block-scoped declaration with the 315 | // same name, or any other value that is not a variable, e.g. ValueModule or Class 316 | FunctionScopedVariableExcludes = Value & ~FunctionScopedVariable, 317 | 318 | // Block-scoped declarations are not allowed to be re-declared 319 | // they can not merge with anything in the value space 320 | BlockScopedVariableExcludes = Value, 321 | 322 | ParameterExcludes = Value, 323 | PropertyExcludes = None, 324 | EnumMemberExcludes = Value | Type, 325 | FunctionExcludes = Value & ~(Function | ValueModule), 326 | ClassExcludes = (Value | Type) & ~(ValueModule | Interface), // class-interface mergability done in checker.ts 327 | InterfaceExcludes = Type & ~(Interface | Class), 328 | 329 | RegularEnumExcludes = 330 | (Value | Type) & ~(RegularEnum | ValueModule), // regular enums merge only with regular enums and modules 331 | ConstEnumExcludes = (Value | Type) & ~ConstEnum, // const enums merge only with const enums 332 | ValueModuleExcludes = Value & ~(Function | Class | RegularEnum | ValueModule), 333 | NamespaceModuleExcludes = 0, 334 | MethodExcludes = Value & ~Method, 335 | GetAccessorExcludes = Value & ~SetAccessor, 336 | SetAccessorExcludes = Value & ~GetAccessor, 337 | TypeParameterExcludes = Type & ~TypeParameter, 338 | TypeAliasExcludes = Type, 339 | AliasExcludes = Alias, 340 | 341 | ModuleMember = Variable | Function | Class | Interface | Enum | Module | TypeAlias | Alias, 342 | 343 | ExportHasLocal = Function | Class | Enum | ValueModule, 344 | 345 | HasExports = Class | Enum | Module, 346 | HasMembers = Class | Interface | TypeLiteral | ObjectLiteral, 347 | 348 | BlockScoped = BlockScopedVariable | Class | Enum, 349 | 350 | PropertyOrAccessor = Property | Accessor, 351 | Export = ExportNamespace | ExportType | ExportValue, 352 | 353 | ClassMember = Method | Accessor | Property, 354 | 355 | /* @internal */ 356 | // The set of things we consider semantically classifiable. Used to speed up the LS during 357 | // classification. 358 | Classifiable = Class | Enum | TypeAlias | Interface | TypeParameter | Module 359 | } 360 | 361 | public enum CheckFlags 362 | { 363 | Instantiated = 1 << 0, // Instantiated symbol 364 | SyntheticProperty = 1 << 1, // Property in union or intersection type 365 | SyntheticMethod = 1 << 2, // Method in union or intersection type 366 | Readonly = 1 << 3, // Readonly transient symbol 367 | Partial = 1 << 4, // Synthetic property present in some but not all constituents 368 | HasNonUniformType = 1 << 5, // Synthetic property with non-uniform type in constituents 369 | ContainsPublic = 1 << 6, // Synthetic property with public constituent(s) 370 | ContainsProtected = 1 << 7, // Synthetic property with protected constituent(s) 371 | ContainsPrivate = 1 << 8, // Synthetic property with private constituent(s) 372 | ContainsStatic = 1 << 9, // Synthetic property with static constituent(s) 373 | Synthetic = SyntheticProperty | SyntheticMethod 374 | } 375 | 376 | public enum NodeCheckFlags 377 | { 378 | TypeChecked = 0x00000001, // Node has been type checked 379 | LexicalThis = 0x00000002, // Lexical 'this' reference 380 | CaptureThis = 0x00000004, // Lexical 'this' used in body 381 | CaptureNewTarget = 0x00000008, // Lexical 'new.target' used in body 382 | SuperInstance = 0x00000100, // Instance 'super' reference 383 | SuperStatic = 0x00000200, // Static 'super' reference 384 | ContextChecked = 0x00000400, // Contextual types have been assigned 385 | AsyncMethodWithSuper = 0x00000800, // An async method that reads a value from a member of 'super'. 386 | AsyncMethodWithSuperBinding = 0x00001000, // An async method that assigns a value to a member of 'super'. 387 | CaptureArguments = 0x00002000, // Lexical 'arguments' used in body (for async functions) 388 | 389 | EnumValuesComputed = 390 | 0x00004000, // Values for enum members have been computed, and any errors have been reported for them. 391 | 392 | LexicalModuleMergesWithClass = 393 | 0x00008000, // Instantiated lexical module declaration is merged with a previous class declaration. 394 | LoopWithCapturedBlockScopedBinding = 0x00010000, // Loop that contains block scoped variable captured in closure 395 | CapturedBlockScopedBinding = 0x00020000, // Block-scoped binding that is captured in some function 396 | 397 | BlockScopedBindingInLoop = 398 | 0x00040000, // Block-scoped binding with declaration nested inside iteration statement 399 | 400 | ClassWithBodyScopedClassBinding = 401 | 0x00080000, // Decorated class that contains a binding to itself inside of the class body. 402 | BodyScopedClassBinding = 0x00100000, // Binding to a decorated class inside of the class's body. 403 | 404 | NeedsLoopOutParameter = 405 | 0x00200000, // Block scoped binding whose value should be explicitly copied outside of the converted loop 406 | AssignmentsMarked = 0x00400000, // Parameter assignments have been marked 407 | 408 | ClassWithConstructorReference = 409 | 0x00800000, // Class that contains a binding to its constructor inside of the class body. 410 | ConstructorReferenceInClass = 0x01000000 // Binding to a class constructor inside of the class's body. 411 | } 412 | 413 | public enum TypeFlags 414 | { 415 | Any = 1 << 0, 416 | String = 1 << 1, 417 | Number = 1 << 2, 418 | Boolean = 1 << 3, 419 | Enum = 1 << 4, 420 | StringLiteral = 1 << 5, 421 | NumberLiteral = 1 << 6, 422 | BooleanLiteral = 1 << 7, 423 | EnumLiteral = 1 << 8, 424 | EsSymbol = 1 << 9, // Type of symbol primitive introduced in ES6 425 | Void = 1 << 10, 426 | Undefined = 1 << 11, 427 | Null = 1 << 12, 428 | Never = 1 << 13, // Never type 429 | TypeParameter = 1 << 14, // Type parameter 430 | Object = 1 << 15, // Object type 431 | Union = 1 << 16, // Union (T | U) 432 | Intersection = 1 << 17, // Intersection (T & U) 433 | Index = 1 << 18, // keyof T 434 | IndexedAccess = 1 << 19, // T[K] 435 | 436 | /* @internal */ 437 | FreshLiteral = 1 << 20, // Fresh literal type 438 | 439 | /* @internal */ 440 | ContainsWideningType = 1 << 21, // Type is or contains undefined or null widening type 441 | 442 | /* @internal */ 443 | ContainsObjectLiteral = 1 << 22, // Type is or contains object literal type 444 | 445 | /* @internal */ 446 | ContainsAnyFunctionType = 1 << 23, // Type is or contains object literal type 447 | NonPrimitive = 1 << 24, // intrinsic object type 448 | 449 | /* @internal */ 450 | JsxAttributes = 1 << 25, // Jsx attributes type 451 | 452 | /* @internal */ 453 | Nullable = Undefined | Null, 454 | Literal = StringLiteral | NumberLiteral | BooleanLiteral | EnumLiteral, 455 | StringOrNumberLiteral = StringLiteral | NumberLiteral, 456 | 457 | /* @internal */ 458 | DefinitelyFalsy = StringLiteral | NumberLiteral | BooleanLiteral | Void | Undefined | Null, 459 | PossiblyFalsy = DefinitelyFalsy | String | Number | Boolean, 460 | 461 | /* @internal */ 462 | Intrinsic = Any | String | Number | Boolean | BooleanLiteral | EsSymbol | Void | Undefined | Null | Never | 463 | NonPrimitive, 464 | 465 | /* @internal */ 466 | Primitive = String | Number | Boolean | Enum | EsSymbol | Void | Undefined | Null | Literal, 467 | StringLike = String | StringLiteral | Index, 468 | NumberLike = Number | NumberLiteral | Enum | EnumLiteral, 469 | BooleanLike = Boolean | BooleanLiteral, 470 | EnumLike = Enum | EnumLiteral, 471 | UnionOrIntersection = Union | Intersection, 472 | StructuredType = Object | Union | Intersection, 473 | StructuredOrTypeVariable = StructuredType | TypeParameter | Index | IndexedAccess, 474 | TypeVariable = TypeParameter | IndexedAccess, 475 | 476 | // 'Narrowable' types are types where narrowing actually narrows. 477 | // This *should* be every type other than null, undefined, void, and never 478 | Narrowable = Any | StructuredType | TypeParameter | Index | IndexedAccess | StringLike | NumberLike | 479 | BooleanLike | EsSymbol | NonPrimitive, 480 | NotUnionOrUnit = Any | EsSymbol | Object | NonPrimitive, 481 | 482 | /* @internal */ 483 | RequiresWidening = ContainsWideningType | ContainsObjectLiteral, 484 | 485 | /* @internal */ 486 | PropagatingFlags = ContainsWideningType | ContainsObjectLiteral | ContainsAnyFunctionType 487 | } 488 | 489 | public enum ObjectFlags 490 | { 491 | Class = 1 << 0, // Class 492 | Interface = 1 << 1, // Interface 493 | Reference = 1 << 2, // Generic type reference 494 | Tuple = 1 << 3, // Synthesized generic tuple type 495 | Anonymous = 1 << 4, // Anonymous 496 | Mapped = 1 << 5, // Mapped 497 | Instantiated = 1 << 6, // Instantiated anonymous or mapped type 498 | ObjectLiteral = 1 << 7, // Originates in an object literal 499 | EvolvingArray = 1 << 8, // Evolving array type 500 | ObjectLiteralPatternWithComputedProperties = 1 << 9, // Object literal pattern with computed properties 501 | ClassOrInterface = Class | Interface 502 | } 503 | 504 | public enum SignatureKind 505 | { 506 | Call, 507 | Construct 508 | } 509 | 510 | public enum IndexKind 511 | { 512 | String, 513 | Number 514 | } 515 | 516 | public enum SpecialPropertyAssignmentKind 517 | { 518 | None, 519 | 520 | /// exports.name = expr 521 | ExportsProperty, 522 | 523 | /// module.exports = expr 524 | ModuleExports, 525 | 526 | /// className.prototype.name = expr 527 | PrototypeProperty, 528 | 529 | /// this.name = expr 530 | ThisProperty, 531 | 532 | // F.name = expr 533 | Property 534 | } 535 | 536 | public enum DiagnosticCategory 537 | { 538 | Warning, 539 | Error, 540 | Message, 541 | Unknown 542 | } 543 | 544 | public enum ModuleResolutionKind 545 | { 546 | Classic = 1, 547 | NodeJs = 2 548 | } 549 | 550 | public enum ModuleKind 551 | { 552 | None = 0, 553 | CommonJs = 1, 554 | Amd = 2, 555 | Umd = 3, 556 | System = 4, 557 | Es2015 = 5 558 | } 559 | 560 | public enum JsxEmit 561 | { 562 | None = 0, 563 | Preserve = 1, 564 | React = 2, 565 | ReactNative = 3 566 | } 567 | 568 | public enum NewLineKind 569 | { 570 | CarriageReturnLineFeed = 0, 571 | LineFeed = 1 572 | } 573 | 574 | public enum ScriptKind 575 | { 576 | Unknown = 0, 577 | Js = 1, 578 | Jsx = 2, 579 | Ts = 3, 580 | Tsx = 4, 581 | External = 5 582 | } 583 | 584 | public enum ScriptTarget 585 | { 586 | Es3 = 0, 587 | Es5 = 1, 588 | Es2015 = 2, 589 | Es2016 = 3, 590 | Es2017 = 4, 591 | EsNext = 5, 592 | Latest = EsNext 593 | } 594 | 595 | public enum LanguageVariant 596 | { 597 | Standard, 598 | Jsx 599 | } 600 | 601 | public enum DiagnosticStyle 602 | { 603 | Simple, 604 | Pretty 605 | } 606 | 607 | public enum WatchDirectoryFlags 608 | { 609 | None = 0, 610 | Recursive = 1 << 0 611 | } 612 | 613 | public enum CharacterCodes 614 | { 615 | NullCharacter = 0, 616 | MaxAsciiCharacter = 0x7F, 617 | 618 | LineFeed = 0x0A, // \n 619 | CarriageReturn = 0x0D, // \r 620 | LineSeparator = 0x2028, 621 | ParagraphSeparator = 0x2029, 622 | NextLine = 0x0085, 623 | 624 | // Unicode 3.0 space characters 625 | Space = 0x0020, // " " 626 | NonBreakingSpace = 0x00A0, // 627 | EnQuad = 0x2000, 628 | EmQuad = 0x2001, 629 | EnSpace = 0x2002, 630 | EmSpace = 0x2003, 631 | ThreePerEmSpace = 0x2004, 632 | FourPerEmSpace = 0x2005, 633 | SixPerEmSpace = 0x2006, 634 | FigureSpace = 0x2007, 635 | PunctuationSpace = 0x2008, 636 | ThinSpace = 0x2009, 637 | HairSpace = 0x200A, 638 | ZeroWidthSpace = 0x200B, 639 | NarrowNoBreakSpace = 0x202F, 640 | IdeographicSpace = 0x3000, 641 | MathematicalSpace = 0x205F, 642 | Ogham = 0x1680, 643 | 644 | _ = 0x5F, 645 | Dollar = 0x24, 646 | 647 | _0 = 0x30, 648 | _1 = 0x31, 649 | _2 = 0x32, 650 | _3 = 0x33, 651 | _4 = 0x34, 652 | _5 = 0x35, 653 | _6 = 0x36, 654 | _7 = 0x37, 655 | _8 = 0x38, 656 | _9 = 0x39, 657 | 658 | a = 0x61, 659 | b = 0x62, 660 | c = 0x63, 661 | d = 0x64, 662 | e = 0x65, 663 | f = 0x66, 664 | g = 0x67, 665 | h = 0x68, 666 | i = 0x69, 667 | j = 0x6A, 668 | k = 0x6B, 669 | l = 0x6C, 670 | m = 0x6D, 671 | n = 0x6E, 672 | o = 0x6F, 673 | p = 0x70, 674 | q = 0x71, 675 | r = 0x72, 676 | s = 0x73, 677 | t = 0x74, 678 | u = 0x75, 679 | v = 0x76, 680 | w = 0x77, 681 | x = 0x78, 682 | y = 0x79, 683 | z = 0x7A, 684 | 685 | A = 0x41, 686 | B = 0x42, 687 | C = 0x43, 688 | D = 0x44, 689 | E = 0x45, 690 | F = 0x46, 691 | G = 0x47, 692 | H = 0x48, 693 | I = 0x49, 694 | J = 0x4A, 695 | K = 0x4B, 696 | L = 0x4C, 697 | M = 0x4D, 698 | N = 0x4E, 699 | O = 0x4F, 700 | P = 0x50, 701 | Q = 0x51, 702 | R = 0x52, 703 | S = 0x53, 704 | T = 0x54, 705 | U = 0x55, 706 | V = 0x56, 707 | W = 0x57, 708 | X = 0x58, 709 | Y = 0x59, 710 | Z = 0x5a, 711 | 712 | Ampersand = 0x26, // & 713 | Asterisk = 0x2A, // * 714 | At = 0x40, // @ 715 | Backslash = 0x5C, // \ 716 | Backtick = 0x60, // ` 717 | Bar = 0x7C, // | 718 | Caret = 0x5E, // ^ 719 | CloseBrace = 0x7D, // } 720 | CloseBracket = 0x5D, // ] 721 | CloseParen = 0x29, // ) 722 | Colon = 0x3A, // : 723 | Comma = 0x2C, // , 724 | Dot = 0x2E, // . 725 | DoubleQuote = 0x22, // " 726 | equals = 0x3D, // = 727 | Exclamation = 0x21, // ! 728 | GreaterThan = 0x3E, // > 729 | Hash = 0x23, // # 730 | LessThan = 0x3C, // < 731 | Minus = 0x2D, // - 732 | OpenBrace = 0x7B, // { 733 | OpenBracket = 0x5B, // [ 734 | OpenParen = 0x28, // ( 735 | Percent = 0x25, // % 736 | Plus = 0x2B, // + 737 | Question = 0x3F, // ? 738 | Semicolon = 0x3B, // ; 739 | SingleQuote = 0x27, // ' 740 | Slash = 0x2F, // / 741 | Tilde = 0x7E, // ~ 742 | 743 | Backspace = 0x08, // \b 744 | FormFeed = 0x0C, // \f 745 | ByteOrderMark = 0xFEFF, 746 | Tab = 0x09, // \t 747 | VerticalTab = 0x0B // \v 748 | } 749 | 750 | public enum Extension 751 | { 752 | Ts, 753 | Tsx, 754 | Dts, 755 | Js, 756 | Jsx, 757 | LastTypeScriptExtension = Dts 758 | } 759 | 760 | public enum TransformFlags 761 | { 762 | None = 0, 763 | 764 | // Facts 765 | // - Flags used to indicate that a node or subtree contains syntax that requires transformation. 766 | TypeScript = 1 << 0, 767 | ContainsTypeScript = 1 << 1, 768 | ContainsJsx = 1 << 2, 769 | ContainsEsNext = 1 << 3, 770 | ContainsEs2017 = 1 << 4, 771 | ContainsEs2016 = 1 << 5, 772 | Es2015 = 1 << 6, 773 | ContainsEs2015 = 1 << 7, 774 | Generator = 1 << 8, 775 | ContainsGenerator = 1 << 9, 776 | DestructuringAssignment = 1 << 10, 777 | ContainsDestructuringAssignment = 1 << 11, 778 | 779 | // Markers 780 | // - Flags used to indicate that a subtree contains a specific transformation. 781 | ContainsDecorators = 1 << 12, 782 | ContainsPropertyInitializer = 1 << 13, 783 | ContainsLexicalThis = 1 << 14, 784 | ContainsCapturedLexicalThis = 1 << 15, 785 | ContainsLexicalThisInComputedPropertyName = 1 << 16, 786 | ContainsDefaultValueAssignments = 1 << 17, 787 | ContainsParameterPropertyAssignments = 1 << 18, 788 | ContainsSpread = 1 << 19, 789 | ContainsObjectSpread = 1 << 20, 790 | ContainsRest = ContainsSpread, 791 | ContainsObjectRest = ContainsObjectSpread, 792 | ContainsComputedPropertyName = 1 << 21, 793 | ContainsBlockScopedBinding = 1 << 22, 794 | ContainsBindingPattern = 1 << 23, 795 | ContainsYield = 1 << 24, 796 | ContainsHoistedDeclarationOrCompletion = 1 << 25, 797 | 798 | HasComputedFlags = 1 << 29, // Transform flags have been computed. 799 | 800 | // Assertions 801 | // - Bitmasks that are used to assert facts about the syntax of a node and its subtree. 802 | AssertTypeScript = TypeScript | ContainsTypeScript, 803 | AssertJsx = ContainsJsx, 804 | AssertEsNext = ContainsEsNext, 805 | AssertEs2017 = ContainsEs2017, 806 | AssertEs2016 = ContainsEs2016, 807 | AssertEs2015 = Es2015 | ContainsEs2015, 808 | AssertGenerator = Generator | ContainsGenerator, 809 | AssertDestructuringAssignment = DestructuringAssignment | ContainsDestructuringAssignment, 810 | 811 | // Scope Exclusions 812 | // - Bitmasks that exclude flags from propagating out of a specific context 813 | // into the subtree flags of their container. 814 | NodeExcludes = TypeScript | Es2015 | DestructuringAssignment | Generator | HasComputedFlags, 815 | 816 | ArrowFunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | 817 | ContainsLexicalThis | ContainsParameterPropertyAssignments | 818 | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | 819 | ContainsBindingPattern | ContainsObjectRest, 820 | 821 | FunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | 822 | ContainsCapturedLexicalThis | ContainsLexicalThis | ContainsParameterPropertyAssignments | 823 | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion | 824 | ContainsBindingPattern | ContainsObjectRest, 825 | 826 | ConstructorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | 827 | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | 828 | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRest, 829 | 830 | MethodOrAccessorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | 831 | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | 832 | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRest, 833 | 834 | ClassExcludes = NodeExcludes | ContainsDecorators | ContainsPropertyInitializer | ContainsLexicalThis | 835 | ContainsCapturedLexicalThis | ContainsComputedPropertyName | 836 | ContainsParameterPropertyAssignments | ContainsLexicalThisInComputedPropertyName, 837 | 838 | ModuleExcludes = NodeExcludes | ContainsDecorators | ContainsLexicalThis | ContainsCapturedLexicalThis | 839 | ContainsBlockScopedBinding | ContainsHoistedDeclarationOrCompletion, 840 | TypeExcludes = ~ContainsTypeScript, 841 | 842 | ObjectLiteralExcludes = NodeExcludes | ContainsDecorators | ContainsComputedPropertyName | 843 | ContainsLexicalThisInComputedPropertyName | ContainsObjectSpread, 844 | ArrayLiteralOrCallOrNewExcludes = NodeExcludes | ContainsSpread, 845 | VariableDeclarationListExcludes = NodeExcludes | ContainsBindingPattern | ContainsObjectRest, 846 | ParameterExcludes = NodeExcludes, 847 | CatchClauseExcludes = NodeExcludes | ContainsObjectRest, 848 | BindingPatternExcludes = NodeExcludes | ContainsRest, 849 | 850 | // Masks 851 | // - Additional bitmasks 852 | TypeScriptClassSyntaxMask = ContainsParameterPropertyAssignments | ContainsPropertyInitializer | 853 | ContainsDecorators, 854 | Es2015FunctionSyntaxMask = ContainsCapturedLexicalThis | ContainsDefaultValueAssignments 855 | } 856 | 857 | public enum EmitFlags 858 | { 859 | SingleLine = 1 << 0, // The contents of this node should be emitted on a single line. 860 | AdviseOnEmitNode = 1 << 1, // The printer should invoke the onEmitNode callback when printing this node. 861 | NoSubstitution = 1 << 2, // Disables further substitution of an expression. 862 | CapturesThis = 1 << 3, // The function captures a lexical `this` 863 | NoLeadingSourceMap = 1 << 4, // Do not emit a leading source map location for this node. 864 | NoTrailingSourceMap = 1 << 5, // Do not emit a trailing source map location for this node. 865 | NoSourceMap = NoLeadingSourceMap | NoTrailingSourceMap, // Do not emit a source map location for this node. 866 | NoNestedSourceMaps = 1 << 6, // Do not emit source map locations for children of this node. 867 | NoTokenLeadingSourceMaps = 1 << 7, // Do not emit leading source map location for token nodes. 868 | NoTokenTrailingSourceMaps = 1 << 8, // Do not emit trailing source map location for token nodes. 869 | 870 | NoTokenSourceMaps = 871 | NoTokenLeadingSourceMaps | 872 | NoTokenTrailingSourceMaps, // Do not emit source map locations for tokens of this node. 873 | NoLeadingComments = 1 << 9, // Do not emit leading comments for this node. 874 | NoTrailingComments = 1 << 10, // Do not emit trailing comments for this node. 875 | NoComments = NoLeadingComments | NoTrailingComments, // Do not emit comments for this node. 876 | NoNestedComments = 1 << 11, 877 | HelperName = 1 << 12, 878 | 879 | ExportName = 880 | 1 << 881 | 13, // Ensure an export prefix is added for an identifier that points to an exported declaration with a local name (see SymbolFlags.ExportHasLocal). 882 | 883 | LocalName = 884 | 1 << 14, // Ensure an export prefix is not added for an identifier that points to an exported declaration. 885 | 886 | Indented = 887 | 1 << 888 | 15, // Adds an explicit extra indentation level for class and function bodies when printing (used to match old emitter). 889 | NoIndentation = 1 << 16, // Do not indent the node. 890 | AsyncFunctionBody = 1 << 17, 891 | ReuseTempVariableScope = 1 << 18, // Reuse the existing temp variable scope during emit. 892 | 893 | CustomPrologue = 894 | 1 << 895 | 19, // Treat the statement as if it were a prologue directive (NOTE: Prologue directives are *not* transformed). 896 | NoHoisting = 1 << 20, // Do not hoist this declaration in --module system 897 | 898 | HasEndOfDeclarationMarker = 899 | 1 << 21 // Declaration has an associated NotEmittedStatement to mark the end of the declaration 900 | } 901 | 902 | public enum ExternalEmitHelpers 903 | { 904 | Extends = 1 << 0, // __extends (used by the ES2015 class transformation) 905 | Assign = 1 << 1, // __assign (used by Jsx and ESNext object spread transformations) 906 | Rest = 1 << 2, // __rest (used by ESNext object rest transformation) 907 | Decorate = 1 << 3, // __decorate (used by TypeScript decorators transformation) 908 | Metadata = 1 << 4, // __metadata (used by TypeScript decorators transformation) 909 | Param = 1 << 5, // __param (used by TypeScript decorators transformation) 910 | Awaiter = 1 << 6, // __awaiter (used by ES2017 async functions transformation) 911 | Generator = 1 << 7, // __generator (used by ES2015 generator transformation) 912 | Values = 1 << 8, // __values (used by ES2015 for..of and yield* transformations) 913 | Read = 1 << 9, // __read (used by ES2015 iterator destructuring transformation) 914 | Spread = 1 << 10, // __spread (used by ES2015 array spread and argument list spread transformations) 915 | AsyncGenerator = 1 << 11, // __asyncGenerator (used by ES2017 async generator transformation) 916 | AsyncDelegator = 1 << 12, // __asyncDelegator (used by ES2017 async generator yield* transformation) 917 | AsyncValues = 1 << 13, // __asyncValues (used by ES2017 for..await..of transformation) 918 | 919 | // Helpers included by ES2015 for..of 920 | ForOfIncludes = Values, 921 | 922 | // Helpers included by ES2017 for..await..of 923 | ForAwaitOfIncludes = AsyncValues, 924 | 925 | // Helpers included by ES2015 spread 926 | SpreadIncludes = Read | Spread, 927 | 928 | FirstEmitHelper = Extends, 929 | LastEmitHelper = AsyncValues 930 | } 931 | 932 | public enum EmitHint 933 | { 934 | SourceFile, // Emitting a SourceFile 935 | Expression, // Emitting an Expression 936 | IdentifierName, // Emitting an IdentifierName 937 | Unspecified // Emitting an otherwise unspecified node 938 | } 939 | } -------------------------------------------------------------------------------- /TypeScriptAST/TsTypes/Node.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using Zu.TypeScript.TsParser; 6 | 7 | namespace Zu.TypeScript.TsTypes 8 | { 9 | public class Node : TextRange, INode 10 | { 11 | public List Children { get; set; } = new List(); 12 | public ITypeScriptAST Ast { get; set; } 13 | 14 | public string SourceStr 15 | { 16 | get => Ast.SourceStr; 17 | set => Ast.SourceStr = value; 18 | } 19 | 20 | public string IdentifierStr => Kind == SyntaxKind.Identifier 21 | ? GetText() 22 | : Children.FirstOrDefault(v => v.Kind == SyntaxKind.Identifier)?.GetText().Trim(); 23 | 24 | public int ParentId { get; set; } 25 | public int Depth { get; set; } 26 | public int NodeStart { get; set; } = -1; 27 | public SyntaxKind Kind { get; set; } 28 | public NodeFlags Flags { get; set; } 29 | public ModifierFlags ModifierFlagsCache { get; set; } 30 | public TransformFlags TransformFlags { get; set; } 31 | public NodeArray Decorators { get; set; } 32 | public /*ModifiersArray*/NodeArray Modifiers { get; set; } 33 | public int Id { get; set; } 34 | public INode Parent { get; set; } 35 | public Node Original { get; set; } 36 | public bool StartsOnNewLine { get; set; } 37 | public List JsDoc { get; set; } 38 | public List JsDocCache { get; set; } 39 | public Symbol Symbol { get; set; } 40 | public SymbolTable Locals { get; set; } 41 | public Node NextContainer { get; set; } 42 | public Symbol LocalSymbol { get; set; } 43 | public FlowNode FlowNode { get; set; } 44 | public EmitNode EmitNode { get; set; } 45 | 46 | public Type ContextualType { get; set; } 47 | public TypeMapper ContextualMapper { get; set; } 48 | 49 | public int TagInt { get; set; } 50 | 51 | public void MakeChildren(TypeScriptAST ast) 52 | { 53 | Children = new List(); 54 | Ts.ForEachChild(this, node => 55 | { 56 | if (node == null) 57 | return null; 58 | var n = (Node)node; 59 | n.Ast = ast; 60 | n.Depth = Depth + 1; 61 | n.Parent = this; 62 | if (n.Pos != null) n.NodeStart = Scanner.SkipTriviaM(SourceStr, (int)n.Pos); 63 | Children.Add(n); 64 | n.MakeChildren(ast); 65 | return null; 66 | }); 67 | } 68 | 69 | public string GetText(string source = null) 70 | { 71 | if (source == null) source = SourceStr; 72 | if (NodeStart == -1) 73 | if (Pos != null && End != null) return source.Substring((int)Pos, (int)End - (int)Pos); 74 | else return null; 75 | 76 | if (End != null) return source.Substring(NodeStart, (int)End - NodeStart); 77 | return null; 78 | } 79 | 80 | public string GetTextWithComments(string source = null) 81 | { 82 | if (source == null) source = SourceStr; 83 | if (Pos != null && End != null) 84 | return source.Substring((int)Pos, (int)End - (int)Pos); 85 | return null; 86 | } 87 | 88 | public override string ToString() 89 | { 90 | var posStr = $" [{Pos}, {End}]"; 91 | 92 | return $"{Enum.GetName(typeof(SyntaxKind), Kind)} {posStr} {IdentifierStr}"; 93 | } 94 | 95 | public string ToString(bool withPos) 96 | { 97 | if (withPos) 98 | { 99 | var posStr = $" [{Pos}, {End}]"; 100 | 101 | return $"{Enum.GetName(typeof(SyntaxKind), Kind)} {posStr} {IdentifierStr}"; 102 | } 103 | return $"{Enum.GetName(typeof(SyntaxKind), Kind)} {IdentifierStr}"; 104 | } 105 | public Node First => Children.FirstOrDefault(); 106 | public Node Last => Children.LastOrDefault(); 107 | public int Count => Children.Count; 108 | 109 | public IEnumerable OfKind(SyntaxKind kind) => GetDescendants(false).OfKind(kind); 110 | 111 | public IEnumerable GetDescendants(bool includeSelf = true) 112 | { 113 | if (includeSelf) yield return this; 114 | 115 | foreach (var descendant in Children) 116 | { 117 | foreach (var ch in descendant.GetDescendants()) 118 | yield return ch; 119 | } 120 | } 121 | public string GetTreeString(bool withPos = true) 122 | { 123 | var sb = new StringBuilder(); 124 | var descendants = GetDescendants().ToList(); 125 | foreach (var node in descendants) 126 | { 127 | //var anc = node.GetAncestors().ToList(); 128 | for (int i = 1; i < node.Depth; i++) //anc.Count() 129 | { 130 | sb.Append(" "); 131 | } 132 | sb.AppendLine(node.ToString(withPos)); 133 | } 134 | return sb.ToString(); 135 | } 136 | 137 | } 138 | 139 | public interface INode : ITextRange 140 | { 141 | SyntaxKind Kind { get; set; } 142 | NodeFlags Flags { get; set; } 143 | ModifierFlags ModifierFlagsCache { get; set; } 144 | TransformFlags TransformFlags { get; set; } 145 | 146 | NodeArray Decorators { get; set; } 147 | 148 | /*ModifiersArray*/ 149 | NodeArray Modifiers { get; set; } 150 | 151 | int Id { get; set; } 152 | INode Parent { get; set; } 153 | List Children { get; set; } 154 | int Depth { get; set; } 155 | Node Original { get; set; } 156 | bool StartsOnNewLine { get; set; } 157 | List JsDoc { get; set; } 158 | List JsDocCache { get; set; } 159 | Symbol Symbol { get; set; } 160 | SymbolTable Locals { get; set; } 161 | Node NextContainer { get; set; } 162 | Symbol LocalSymbol { get; set; } 163 | FlowNode FlowNode { get; set; } 164 | EmitNode EmitNode { get; set; } 165 | Type ContextualType { get; set; } 166 | TypeMapper ContextualMapper { get; set; } 167 | int TagInt { get; set; } 168 | 169 | string GetText(string source = null); 170 | string GetTextWithComments(string source = null); 171 | string GetTreeString(bool withPos = true); 172 | 173 | string ToString(bool withPos); 174 | Node First { get; } 175 | Node Last { get; } 176 | int Count { get; } 177 | 178 | } 179 | } -------------------------------------------------------------------------------- /TypeScriptAST/TsTypes/NodeExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Zu.TypeScript.TsTypes 4 | { 5 | public static class NodeExtensions 6 | { 7 | public static IEnumerable GetDescendants(this INode node, bool includeSelf = true) 8 | { 9 | if (includeSelf) yield return node; 10 | 11 | foreach (var descendant in node.Children) 12 | foreach (var ch in descendant.GetDescendants()) 13 | yield return ch; 14 | } 15 | 16 | public static IEnumerable GetAncestors(this INode node) 17 | { 18 | var current = node.Parent; 19 | 20 | while (current != null) 21 | { 22 | yield return current; 23 | current = current.Parent; 24 | } 25 | } 26 | public static IEnumerable OfKind(this IEnumerable nodes, SyntaxKind kind) 27 | { 28 | foreach (var node in nodes) 29 | { 30 | if (node.Kind == kind) yield return node; 31 | } 32 | } 33 | 34 | public static IEnumerable OfKind(this IEnumerable nodes, SyntaxKind kind) 35 | { 36 | foreach (var node in nodes) 37 | { 38 | if (node.Kind == kind) yield return node; 39 | } 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /TypeScriptAST/TsTypes/SyntaxKind.cs: -------------------------------------------------------------------------------- 1 | namespace Zu.TypeScript.TsTypes 2 | { 3 | public enum SyntaxKind 4 | { 5 | Unknown, 6 | EndOfFileToken, 7 | SingleLineCommentTrivia, 8 | MultiLineCommentTrivia, 9 | NewLineTrivia, 10 | WhitespaceTrivia, 11 | 12 | // We detect and preserve #! on the first line 13 | ShebangTrivia, 14 | 15 | // We detect and provide better error recovery when we encounter a git merge marker. This 16 | // allows us to edit files with git-conflict markers in them in a much more pleasant manner. 17 | ConflictMarkerTrivia, 18 | 19 | // Literals 20 | NumericLiteral, 21 | StringLiteral, 22 | JsxText, 23 | RegularExpressionLiteral, 24 | NoSubstitutionTemplateLiteral, 25 | 26 | // Pseudo-literals 27 | TemplateHead, 28 | TemplateMiddle, 29 | TemplateTail, 30 | 31 | // Punctuation 32 | OpenBraceToken, 33 | CloseBraceToken, 34 | OpenParenToken, 35 | CloseParenToken, 36 | OpenBracketToken, 37 | CloseBracketToken, 38 | DotToken, 39 | DotDotDotToken, 40 | SemicolonToken, 41 | CommaToken, 42 | LessThanToken, 43 | LessThanSlashToken, 44 | GreaterThanToken, 45 | LessThanEqualsToken, 46 | GreaterThanEqualsToken, 47 | EqualsEqualsToken, 48 | ExclamationEqualsToken, 49 | EqualsEqualsEqualsToken, 50 | ExclamationEqualsEqualsToken, 51 | EqualsGreaterThanToken, 52 | PlusToken, 53 | MinusToken, 54 | AsteriskToken, 55 | AsteriskAsteriskToken, 56 | SlashToken, 57 | PercentToken, 58 | PlusPlusToken, 59 | MinusMinusToken, 60 | LessThanLessThanToken, 61 | GreaterThanGreaterThanToken, 62 | GreaterThanGreaterThanGreaterThanToken, 63 | AmpersandToken, 64 | BarToken, 65 | CaretToken, 66 | ExclamationToken, 67 | TildeToken, 68 | AmpersandAmpersandToken, 69 | BarBarToken, 70 | QuestionToken, 71 | ColonToken, 72 | AtToken, 73 | 74 | // Assignments 75 | EqualsToken, 76 | PlusEqualsToken, 77 | MinusEqualsToken, 78 | AsteriskEqualsToken, 79 | AsteriskAsteriskEqualsToken, 80 | SlashEqualsToken, 81 | PercentEqualsToken, 82 | LessThanLessThanEqualsToken, 83 | GreaterThanGreaterThanEqualsToken, 84 | GreaterThanGreaterThanGreaterThanEqualsToken, 85 | AmpersandEqualsToken, 86 | BarEqualsToken, 87 | CaretEqualsToken, 88 | 89 | // Identifiers 90 | Identifier, 91 | 92 | // Reserved words 93 | BreakKeyword, 94 | CaseKeyword, 95 | CatchKeyword, 96 | ClassKeyword, 97 | ConstKeyword, 98 | ContinueKeyword, 99 | DebuggerKeyword, 100 | DefaultKeyword, 101 | DeleteKeyword, 102 | DoKeyword, 103 | ElseKeyword, 104 | EnumKeyword, 105 | ExportKeyword, 106 | ExtendsKeyword, 107 | FalseKeyword, 108 | FinallyKeyword, 109 | ForKeyword, 110 | FunctionKeyword, 111 | IfKeyword, 112 | ImportKeyword, 113 | InKeyword, 114 | InstanceOfKeyword, 115 | NewKeyword, 116 | NullKeyword, 117 | ReturnKeyword, 118 | SuperKeyword, 119 | SwitchKeyword, 120 | ThisKeyword, 121 | ThrowKeyword, 122 | TrueKeyword, 123 | TryKeyword, 124 | TypeOfKeyword, 125 | VarKeyword, 126 | VoidKeyword, 127 | WhileKeyword, 128 | WithKeyword, 129 | 130 | // Strict mode reserved words 131 | ImplementsKeyword, 132 | InterfaceKeyword, 133 | LetKeyword, 134 | PackageKeyword, 135 | PrivateKeyword, 136 | ProtectedKeyword, 137 | PublicKeyword, 138 | StaticKeyword, 139 | YieldKeyword, 140 | 141 | // Contextual keywords 142 | AbstractKeyword, 143 | AsKeyword, 144 | AnyKeyword, 145 | AsyncKeyword, 146 | AwaitKeyword, 147 | BooleanKeyword, 148 | ConstructorKeyword, 149 | DeclareKeyword, 150 | GetKeyword, 151 | IsKeyword, 152 | KeyOfKeyword, 153 | ModuleKeyword, 154 | NamespaceKeyword, 155 | NeverKeyword, 156 | ReadonlyKeyword, 157 | RequireKeyword, 158 | NumberKeyword, 159 | ObjectKeyword, 160 | SetKeyword, 161 | StringKeyword, 162 | SymbolKeyword, 163 | TypeKeyword, 164 | UndefinedKeyword, 165 | FromKeyword, 166 | GlobalKeyword, 167 | OfKeyword, // LastKeyword and LastToken 168 | 169 | // Parse tree nodes 170 | 171 | // Names 172 | QualifiedName, 173 | ComputedPropertyName, 174 | 175 | // Signature elements 176 | TypeParameter, 177 | Parameter, 178 | Decorator, 179 | 180 | // TypeMember 181 | PropertySignature, 182 | PropertyDeclaration, 183 | MethodSignature, 184 | MethodDeclaration, 185 | Constructor, 186 | GetAccessor, 187 | SetAccessor, 188 | CallSignature, 189 | ConstructSignature, 190 | IndexSignature, 191 | 192 | // Type 193 | TypePredicate, 194 | TypeReference, 195 | FunctionType, 196 | ConstructorType, 197 | TypeQuery, 198 | TypeLiteral, 199 | ArrayType, 200 | TupleType, 201 | UnionType, 202 | IntersectionType, 203 | ParenthesizedType, 204 | ThisType, 205 | TypeOperator, 206 | IndexedAccessType, 207 | MappedType, 208 | LiteralType, 209 | 210 | // Binding patterns 211 | ObjectBindingPattern, 212 | ArrayBindingPattern, 213 | BindingElement, 214 | 215 | // Expression 216 | ArrayLiteralExpression, 217 | ObjectLiteralExpression, 218 | PropertyAccessExpression, 219 | ElementAccessExpression, 220 | CallExpression, 221 | NewExpression, 222 | TaggedTemplateExpression, 223 | TypeAssertionExpression, 224 | ParenthesizedExpression, 225 | FunctionExpression, 226 | ArrowFunction, 227 | DeleteExpression, 228 | TypeOfExpression, 229 | VoidExpression, 230 | AwaitExpression, 231 | PrefixUnaryExpression, 232 | PostfixUnaryExpression, 233 | BinaryExpression, 234 | ConditionalExpression, 235 | TemplateExpression, 236 | YieldExpression, 237 | SpreadElement, 238 | ClassExpression, 239 | OmittedExpression, 240 | ExpressionWithTypeArguments, 241 | AsExpression, 242 | NonNullExpression, 243 | MetaProperty, 244 | 245 | // Misc 246 | TemplateSpan, 247 | SemicolonClassElement, 248 | 249 | // Element 250 | Block, 251 | VariableStatement, 252 | EmptyStatement, 253 | ExpressionStatement, 254 | IfStatement, 255 | DoStatement, 256 | WhileStatement, 257 | ForStatement, 258 | ForInStatement, 259 | ForOfStatement, 260 | ContinueStatement, 261 | BreakStatement, 262 | ReturnStatement, 263 | WithStatement, 264 | SwitchStatement, 265 | LabeledStatement, 266 | ThrowStatement, 267 | TryStatement, 268 | DebuggerStatement, 269 | VariableDeclaration, 270 | VariableDeclarationList, 271 | FunctionDeclaration, 272 | ClassDeclaration, 273 | InterfaceDeclaration, 274 | TypeAliasDeclaration, 275 | EnumDeclaration, 276 | ModuleDeclaration, 277 | ModuleBlock, 278 | CaseBlock, 279 | NamespaceExportDeclaration, 280 | ImportEqualsDeclaration, 281 | ImportDeclaration, 282 | ImportClause, 283 | NamespaceImport, 284 | NamedImports, 285 | ImportSpecifier, 286 | ExportAssignment, 287 | ExportDeclaration, 288 | NamedExports, 289 | ExportSpecifier, 290 | MissingDeclaration, 291 | 292 | // Module references 293 | ExternalModuleReference, 294 | 295 | // JSX 296 | JsxElement, 297 | JsxSelfClosingElement, 298 | JsxOpeningElement, 299 | JsxClosingElement, 300 | JsxAttribute, 301 | JsxAttributes, 302 | JsxSpreadAttribute, 303 | JsxExpression, 304 | 305 | // Clauses 306 | CaseClause, 307 | DefaultClause, 308 | HeritageClause, 309 | CatchClause, 310 | 311 | // Property assignments 312 | PropertyAssignment, 313 | ShorthandPropertyAssignment, 314 | SpreadAssignment, 315 | 316 | // Enum 317 | EnumMember, 318 | 319 | // Top-level nodes 320 | SourceFile, 321 | Bundle, 322 | 323 | // JSDoc nodes 324 | JsDocTypeExpression, 325 | 326 | // The * type 327 | JsDocAllType, 328 | 329 | // The ? type 330 | JsDocUnknownType, 331 | JsDocArrayType, 332 | JsDocUnionType, 333 | JsDocTupleType, 334 | JsDocNullableType, 335 | JsDocNonNullableType, 336 | JsDocRecordType, 337 | JsDocRecordMember, 338 | JsDocTypeReference, 339 | JsDocOptionalType, 340 | JsDocFunctionType, 341 | JsDocVariadicType, 342 | JsDocConstructorType, 343 | JsDocThisType, 344 | JsDocComment, 345 | JsDocTag, 346 | JsDocAugmentsTag, 347 | JsDocParameterTag, 348 | JsDocReturnTag, 349 | JsDocTypeTag, 350 | JsDocTemplateTag, 351 | JsDocTypedefTag, 352 | JsDocPropertyTag, 353 | JsDocTypeLiteral, 354 | JsDocLiteralType, 355 | 356 | // Synthesized list 357 | SyntaxList, 358 | 359 | // Transformation nodes 360 | NotEmittedStatement, 361 | PartiallyEmittedExpression, 362 | MergeDeclarationMarker, 363 | EndOfDeclarationMarker, 364 | 365 | // Enum value count 366 | Count, 367 | 368 | // Markers 369 | FirstAssignment = EqualsToken, 370 | LastAssignment = CaretEqualsToken, 371 | FirstCompoundAssignment = PlusEqualsToken, 372 | LastCompoundAssignment = CaretEqualsToken, 373 | FirstReservedWord = BreakKeyword, 374 | LastReservedWord = WithKeyword, 375 | FirstKeyword = BreakKeyword, 376 | LastKeyword = OfKeyword, 377 | FirstFutureReservedWord = ImplementsKeyword, 378 | LastFutureReservedWord = YieldKeyword, 379 | FirstTypeNode = TypePredicate, 380 | LastTypeNode = LiteralType, 381 | FirstPunctuation = OpenBraceToken, 382 | LastPunctuation = CaretEqualsToken, 383 | FirstToken = Unknown, 384 | LastToken = LastKeyword, 385 | FirstTriviaToken = SingleLineCommentTrivia, 386 | LastTriviaToken = ConflictMarkerTrivia, 387 | FirstLiteralToken = NumericLiteral, 388 | LastLiteralToken = NoSubstitutionTemplateLiteral, 389 | FirstTemplateToken = NoSubstitutionTemplateLiteral, 390 | LastTemplateToken = TemplateTail, 391 | FirstBinaryOperator = LessThanToken, 392 | LastBinaryOperator = CaretEqualsToken, 393 | FirstNode = QualifiedName, 394 | FirstJsDocNode = JsDocTypeExpression, 395 | LastJsDocNode = JsDocLiteralType, 396 | FirstJsDocTagNode = JsDocComment, 397 | LastJsDocTagNode = JsDocLiteralType 398 | } 399 | } -------------------------------------------------------------------------------- /TypeScriptAST/TypeScriptAST.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Text; 4 | using Zu.TypeScript.TsParser; 5 | using Zu.TypeScript.TsTypes; 6 | 7 | namespace Zu.TypeScript 8 | { 9 | public interface ITypeScriptAST 10 | { 11 | ScriptTarget ScriptTarget { get; set; } 12 | string SourceStr { get; set; } 13 | Node RootNode { get; set; } 14 | string GetTreeString(bool withPos); 15 | IEnumerable GetDescendants(); 16 | void MakeAST(string source, string fileName = "fileName.ts", bool setChildren = true); 17 | } 18 | public class TypeScriptAST: ITypeScriptAST 19 | { 20 | public ScriptTarget ScriptTarget { get; set; } = ScriptTarget.Latest; //ES6 21 | public string SourceStr { get; set; } 22 | public Node RootNode { get; set; } 23 | 24 | public TypeScriptAST(string source = null, string fileName = "fileName.ts", bool setChildren = true) 25 | { 26 | if (source != null) 27 | { 28 | MakeAST(source, fileName, setChildren); 29 | } 30 | } 31 | 32 | public void MakeAST(string source, string fileName = "fileName.ts", bool setChildren = true) 33 | { 34 | SourceStr = source; 35 | var parser = new Parser(); 36 | var sourceFile = parser.ParseSourceFile(fileName, source, ScriptTarget, null, false, ScriptKind.Ts); 37 | RootNode = sourceFile; 38 | RootNode.Ast = this; 39 | if (setChildren) 40 | { 41 | childrenMade = true; 42 | RootNode.MakeChildren(this); 43 | } 44 | //RootNode.GetDescendants().ToList().ForEach((n) => n.AST = this); 45 | } 46 | 47 | private bool childrenMade = false; 48 | public IEnumerable OfKind(SyntaxKind kind) => RootNode?.OfKind(kind); 49 | public IEnumerable GetDescendants() 50 | { 51 | if (!childrenMade && RootNode != null) 52 | { 53 | RootNode.MakeChildren(this); 54 | childrenMade = true; 55 | } 56 | return RootNode?.GetDescendants(); 57 | } 58 | 59 | public string GetTreeString(bool withPos = true) 60 | { 61 | return RootNode?.GetTreeString(withPos); 62 | } 63 | } 64 | } -------------------------------------------------------------------------------- /TypeScriptAST/TypeScriptAST.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {7728B98C-9E88-4E6D-8ECD-D51DED278AC2} 8 | Library 9 | Properties 10 | TypeScriptAST 11 | TypeScriptAST 12 | v4.5.2 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | 35 | 36 | ..\packages\System.ValueTuple.4.3.0\lib\netstandard1.0\System.ValueTuple.dll 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /TypeScriptAST/TypeScriptAST.nuspec: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $id$ 5 | $version$ 6 | $title$ 7 | $author$ 8 | $author$ 9 | https://github.com/ToCSharp/TypeScriptAST/blob/master/LICENSE.txt 10 | https://github.com/ToCSharp/TypeScriptAST 11 | false 12 | $description$ 13 | Initial release. 14 | Copyright Oleg Zudov 2017 15 | TypeScript JavaScript DefinitelyTyped AST parser 16 | 17 | -------------------------------------------------------------------------------- /TypeScriptAST/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /TypeScriptAstExample/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /TypeScriptAstExample/App.xaml: -------------------------------------------------------------------------------- 1 |  6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /TypeScriptAstExample/App.xaml.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Configuration; 4 | using System.Data; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | using System.Windows; 8 | 9 | namespace TypeScriptAstExample 10 | { 11 | public partial class App : Application 12 | { 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /TypeScriptAstExample/MainWindow.xaml: -------------------------------------------------------------------------------- 1 |  9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 |