├── .editorconfig ├── .gitignore ├── .nuke ├── build.schema.json └── parameters.json ├── LICENSE ├── README.md ├── appveyor.yml ├── build.cmd ├── build.ps1 ├── build.sh ├── build ├── .editorconfig ├── Build.cs ├── Properties │ └── launchSettings.json ├── _build.csproj ├── _build.csproj.DotSettings └── appveyor.yml ├── img ├── settings-page.png ├── usage-csc-gen.gif ├── usage-opt.gif └── usage.gif ├── microscope.sln ├── publish-manifest.json ├── research ├── references-code-lens-call-graph.drawio └── references-code-lens-call-graph.png ├── src ├── CodeAnalysis │ ├── AllParametersMatchExt.cs │ ├── CodeAnalysis.csproj │ ├── CollectGeneratedCodeExt.cs │ ├── CompileExt.cs │ ├── GetCodeLensDataForExt.cs │ ├── GetDocumentExt.cs │ ├── GetDocumentationExt.cs │ ├── GetMethodDefinitionExt.cs │ ├── GetSymbolAtExt.cs │ ├── Model │ │ ├── DetailsData.cs │ │ ├── GeneratedMethod.cs │ │ ├── GeneratedType.cs │ │ └── InstructionData.cs │ ├── PrintInstructionExt.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── SymbolNameExt.cs │ ├── ToCodeLensDataExt.cs │ └── gen-opcode-doc-switch-cases.linq ├── CodeLensProvider │ ├── CodeLensDataPoint.cs │ ├── CodeLensProvider.cs │ ├── CodeLensProvider.csproj │ ├── GetExt.cs │ ├── LabeledExt.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── Resources.Designer.cs │ ├── Resources.resx │ └── VisualStudioConnectionHandler.cs ├── Shared │ ├── CodeLensData.cs │ ├── CodeLensDetails.cs │ ├── ConfigureAwaitAlias.cs │ ├── IInstructionsProvider.cs │ ├── Logging.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── RemoteConnection.cs │ └── Shared.csproj └── VSExtension │ ├── CodeLensConnectionHandler.cs │ ├── InstructionsProvider.cs │ ├── MicroscopeCommands.cs │ ├── MicroscopeCommands.vsct │ ├── MicroscopePackage.cs │ ├── Options │ ├── BaseOptionModel.cs │ ├── BaseOptionPage.cs │ ├── DialogPageProvider.cs │ └── GeneralOptions.cs │ ├── Properties │ └── AssemblyInfo.cs │ ├── RefreshCommand.cs │ ├── Resources │ └── icon.png │ ├── SaveCommandHandler.cs │ ├── UI │ ├── CodeLensDetailsControl.xaml │ ├── CodeLensDetailsControl.xaml.cs │ └── ViewElementFactory.cs │ ├── VS2019 │ └── Microsoft.VisualStudio.CodeSense.Common.dll │ ├── VSExtension.csproj │ ├── source.extension.cs │ └── source.extension.vsixmanifest └── tests ├── CollectGeneratedCodeExtTestData.cs ├── CollectGeneratedCodeExtTests.cs ├── DocumentationTests.cs ├── GetDocumentExtTests.cs ├── GetMethodDefinitionExtTestData.cs ├── GetMethodDefinitionExtTests.cs ├── Properties └── AssemblyInfo.cs ├── Tests.csproj ├── Util ├── DebugExt.cs ├── FluentAssertionsExt.cs └── SymbolResolver.cs └── app.config /.editorconfig: -------------------------------------------------------------------------------- 1 | # Remove the line below if you want to inherit .editorconfig settings from higher directories 2 | root = true 3 | 4 | # C# files 5 | [*.cs] 6 | 7 | # VSTHRD200: Use "Async" suffix for async methods 8 | dotnet_diagnostic.VSTHRD200.severity = none 9 | 10 | #### Core EditorConfig Options #### 11 | 12 | # Indentation and spacing 13 | indent_size = 4 14 | indent_style = space 15 | tab_width = 4 16 | 17 | # New line preferences 18 | end_of_line = crlf 19 | insert_final_newline = false 20 | 21 | #### .NET Coding Conventions #### 22 | 23 | # Organize usings 24 | dotnet_separate_import_directive_groups = true 25 | dotnet_sort_system_directives_first = false 26 | file_header_template = unset 27 | 28 | # this. and Me. preferences 29 | dotnet_style_qualification_for_event = false:warning 30 | dotnet_style_qualification_for_field = false:warning 31 | dotnet_style_qualification_for_method = false:warning 32 | dotnet_style_qualification_for_property = false:warning 33 | 34 | # Language keywords vs BCL types preferences 35 | dotnet_style_predefined_type_for_locals_parameters_members = true:warning 36 | dotnet_style_predefined_type_for_member_access = true:warning 37 | 38 | # Parentheses preferences 39 | dotnet_style_parentheses_in_arithmetic_binary_operators = never_if_unnecessary:suggestion 40 | dotnet_style_parentheses_in_other_binary_operators = never_if_unnecessary 41 | dotnet_style_parentheses_in_other_operators = never_if_unnecessary:suggestion 42 | dotnet_style_parentheses_in_relational_binary_operators = never_if_unnecessary:suggestion 43 | 44 | # Modifier preferences 45 | dotnet_style_require_accessibility_modifiers = for_non_interface_members 46 | 47 | # Expression-level preferences 48 | dotnet_style_coalesce_expression = true:warning 49 | dotnet_style_collection_initializer = true:warning 50 | dotnet_style_explicit_tuple_names = true:warning 51 | dotnet_style_namespace_match_folder = true 52 | dotnet_style_null_propagation = true:warning 53 | dotnet_style_object_initializer = true:warning 54 | dotnet_style_operator_placement_when_wrapping = beginning_of_line 55 | dotnet_style_prefer_auto_properties = true:warning 56 | dotnet_style_prefer_compound_assignment = true:warning 57 | dotnet_style_prefer_conditional_expression_over_assignment = true:warning 58 | dotnet_style_prefer_conditional_expression_over_return = true:warning 59 | dotnet_style_prefer_inferred_anonymous_type_member_names = true:warning 60 | dotnet_style_prefer_inferred_tuple_names = true:warning 61 | dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning 62 | dotnet_style_prefer_simplified_boolean_expressions = true:warning 63 | dotnet_style_prefer_simplified_interpolation = true 64 | 65 | # Field preferences 66 | dotnet_style_readonly_field = true:warning 67 | 68 | # Parameter preferences 69 | dotnet_code_quality_unused_parameters = all:warning 70 | 71 | # Suppression preferences 72 | dotnet_remove_unnecessary_suppression_exclusions = none 73 | 74 | # New line preferences 75 | dotnet_style_allow_multiple_blank_lines_experimental = true:warning 76 | dotnet_style_allow_statement_immediately_after_block_experimental = false:warning 77 | 78 | #### C# Coding Conventions #### 79 | 80 | # var preferences 81 | csharp_style_var_elsewhere = true:warning 82 | csharp_style_var_for_built_in_types = true:warning 83 | csharp_style_var_when_type_is_apparent = true:warning 84 | 85 | # Expression-bodied members 86 | csharp_style_expression_bodied_accessors = true:warning 87 | csharp_style_expression_bodied_constructors = true:warning 88 | csharp_style_expression_bodied_indexers = true:warning 89 | csharp_style_expression_bodied_lambdas = true:warning 90 | csharp_style_expression_bodied_local_functions = true:warning 91 | csharp_style_expression_bodied_methods = true:warning 92 | csharp_style_expression_bodied_operators = true:warning 93 | csharp_style_expression_bodied_properties = true:warning 94 | 95 | # Pattern matching preferences 96 | csharp_style_pattern_matching_over_as_with_null_check = true:warning 97 | csharp_style_pattern_matching_over_is_with_cast_check = true:warning 98 | csharp_style_prefer_not_pattern = true:warning 99 | csharp_style_prefer_pattern_matching = true:warning 100 | csharp_style_prefer_switch_expression = true:warning 101 | 102 | # Null-checking preferences 103 | csharp_style_conditional_delegate_call = true:warning 104 | 105 | # Modifier preferences 106 | csharp_prefer_static_local_function = true:warning 107 | csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async 108 | 109 | # Code-block preferences 110 | csharp_prefer_braces = false 111 | csharp_prefer_simple_using_statement = true:warning 112 | csharp_style_namespace_declarations = file_scoped:warning 113 | 114 | # Expression-level preferences 115 | csharp_prefer_simple_default_expression = true:warning 116 | csharp_style_deconstructed_variable_declaration = true:warning 117 | csharp_style_implicit_object_creation_when_type_is_apparent = true:warning 118 | csharp_style_inlined_variable_declaration = true:warning 119 | csharp_style_pattern_local_over_anonymous_function = true:warning 120 | csharp_style_prefer_index_operator = true:warning 121 | csharp_style_prefer_null_check_over_type_check = true:warning 122 | csharp_style_prefer_range_operator = true:warning 123 | csharp_style_throw_expression = true:warning 124 | csharp_style_unused_value_assignment_preference = discard_variable:warning 125 | csharp_style_unused_value_expression_statement_preference = discard_variable:warning 126 | 127 | # 'using' directive preferences 128 | csharp_using_directive_placement = inside_namespace:warning 129 | 130 | # New line preferences 131 | csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = false:warning 132 | csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false:warning 133 | csharp_style_allow_embedded_statements_on_same_line_experimental = true 134 | 135 | #### C# Formatting Rules #### 136 | 137 | # New line preferences 138 | csharp_new_line_before_catch = false 139 | csharp_new_line_before_else = false 140 | csharp_new_line_before_finally = false 141 | csharp_new_line_before_members_in_anonymous_types = false 142 | csharp_new_line_before_members_in_object_initializers = false 143 | csharp_new_line_before_open_brace = none 144 | csharp_new_line_between_query_expression_clauses = true 145 | 146 | # Indentation preferences 147 | csharp_indent_block_contents = true 148 | csharp_indent_braces = false 149 | csharp_indent_case_contents = true 150 | csharp_indent_case_contents_when_block = false 151 | csharp_indent_labels = one_less_than_current 152 | csharp_indent_switch_labels = true 153 | 154 | # Space preferences 155 | csharp_space_after_cast = false 156 | csharp_space_after_colon_in_inheritance_clause = true 157 | csharp_space_after_comma = true 158 | csharp_space_after_dot = false 159 | csharp_space_after_keywords_in_control_flow_statements = true 160 | csharp_space_after_semicolon_in_for_statement = true 161 | csharp_space_around_binary_operators = before_and_after 162 | csharp_space_around_declaration_statements = false 163 | csharp_space_before_colon_in_inheritance_clause = true 164 | csharp_space_before_comma = false 165 | csharp_space_before_dot = false 166 | csharp_space_before_open_square_brackets = false 167 | csharp_space_before_semicolon_in_for_statement = false 168 | csharp_space_between_empty_square_brackets = false 169 | csharp_space_between_method_call_empty_parameter_list_parentheses = false 170 | csharp_space_between_method_call_name_and_opening_parenthesis = false 171 | csharp_space_between_method_call_parameter_list_parentheses = false 172 | csharp_space_between_method_declaration_empty_parameter_list_parentheses = false 173 | csharp_space_between_method_declaration_name_and_open_parenthesis = false 174 | csharp_space_between_method_declaration_parameter_list_parentheses = false 175 | csharp_space_between_parentheses = false 176 | csharp_space_between_square_brackets = false 177 | 178 | # Wrapping preferences 179 | csharp_preserve_single_line_blocks = true 180 | csharp_preserve_single_line_statements = true 181 | 182 | #### Naming styles #### 183 | 184 | # Naming rules 185 | 186 | dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion 187 | dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface 188 | dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i 189 | 190 | dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion 191 | dotnet_naming_rule.types_should_be_pascal_case.symbols = types 192 | dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case 193 | 194 | dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion 195 | dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members 196 | dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case 197 | 198 | # Symbol specifications 199 | 200 | dotnet_naming_symbols.interface.applicable_kinds = interface 201 | dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected 202 | dotnet_naming_symbols.interface.required_modifiers = 203 | 204 | dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum 205 | dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected 206 | dotnet_naming_symbols.types.required_modifiers = 207 | 208 | dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method 209 | dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected 210 | dotnet_naming_symbols.non_field_members.required_modifiers = 211 | 212 | # Naming styles 213 | 214 | dotnet_naming_style.pascal_case.required_prefix = 215 | dotnet_naming_style.pascal_case.required_suffix = 216 | dotnet_naming_style.pascal_case.word_separator = 217 | dotnet_naming_style.pascal_case.capitalization = pascal_case 218 | 219 | dotnet_naming_style.begins_with_i.required_prefix = I 220 | dotnet_naming_style.begins_with_i.required_suffix = 221 | dotnet_naming_style.begins_with_i.word_separator = 222 | dotnet_naming_style.begins_with_i.capitalization = pascal_case 223 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | 352 | # Custom 353 | .vscode/ 354 | build/tools/ 355 | -------------------------------------------------------------------------------- /.nuke/build.schema.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json-schema.org/draft-04/schema#", 3 | "title": "Build Schema", 4 | "$ref": "#/definitions/build", 5 | "definitions": { 6 | "build": { 7 | "type": "object", 8 | "properties": { 9 | "BuildNumber": { 10 | "type": "integer", 11 | "description": "Number identifying the build - Optional, set by the CI (default: 0)" 12 | }, 13 | "Configuration": { 14 | "type": "string", 15 | "description": "Configuration to build - Optional (default: 'Release')" 16 | }, 17 | "Continue": { 18 | "type": "boolean", 19 | "description": "Indicates to continue a previously failed build attempt" 20 | }, 21 | "Help": { 22 | "type": "boolean", 23 | "description": "Shows the help text for this build assembly" 24 | }, 25 | "Host": { 26 | "type": "string", 27 | "description": "Host for execution. Default is 'automatic'", 28 | "enum": [ 29 | "AppVeyor", 30 | "AzurePipelines", 31 | "Bamboo", 32 | "Bitrise", 33 | "GitHubActions", 34 | "GitLab", 35 | "Jenkins", 36 | "Rider", 37 | "SpaceAutomation", 38 | "TeamCity", 39 | "Terminal", 40 | "TravisCI", 41 | "VisualStudio", 42 | "VSCode" 43 | ] 44 | }, 45 | "MarketplaceKey": { 46 | "type": "string", 47 | "description": "Personal access token for the VS Marketplace - Required for target `Publish` (default: null)" 48 | }, 49 | "NoLogo": { 50 | "type": "boolean", 51 | "description": "Disables displaying the NUKE logo" 52 | }, 53 | "Partition": { 54 | "type": "string", 55 | "description": "Partition to use on CI" 56 | }, 57 | "Plan": { 58 | "type": "boolean", 59 | "description": "Shows the execution plan (HTML)" 60 | }, 61 | "Profile": { 62 | "type": "array", 63 | "description": "Defines the profiles to load", 64 | "items": { 65 | "type": "string" 66 | } 67 | }, 68 | "Root": { 69 | "type": "string", 70 | "description": "Root directory during build execution" 71 | }, 72 | "SemVer": { 73 | "type": "string", 74 | "description": "Version - Optional, set to latest tag if omitted (default: null)" 75 | }, 76 | "Skip": { 77 | "type": "array", 78 | "description": "List of targets to be skipped. Empty list skips all dependencies", 79 | "items": { 80 | "type": "string", 81 | "enum": [ 82 | "Clean", 83 | "Compile", 84 | "Publish", 85 | "Restore", 86 | "SetVersion", 87 | "Test" 88 | ] 89 | } 90 | }, 91 | "Solution": { 92 | "type": "string", 93 | "description": "Path to a solution file that is automatically loaded" 94 | }, 95 | "Target": { 96 | "type": "array", 97 | "description": "List of targets to be invoked. Default is '{default_target}'", 98 | "items": { 99 | "type": "string", 100 | "enum": [ 101 | "Clean", 102 | "Compile", 103 | "Publish", 104 | "Restore", 105 | "SetVersion", 106 | "Test" 107 | ] 108 | } 109 | }, 110 | "UpdateVersion": { 111 | "type": "boolean", 112 | "description": "Update assembly properties and VSIX manifest with current version during build - Optional (default: false)" 113 | }, 114 | "Verbosity": { 115 | "type": "string", 116 | "description": "Logging verbosity during build execution. Default is 'Normal'", 117 | "enum": [ 118 | "Minimal", 119 | "Normal", 120 | "Quiet", 121 | "Verbose" 122 | ] 123 | } 124 | } 125 | } 126 | } 127 | } -------------------------------------------------------------------------------- /.nuke/parameters.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./build.schema.json", 3 | "Solution": "microscope.sln" 4 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Robert Hofmann 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # microscope 2 | 3 | [![build](https://img.shields.io/appveyor/build/bert2/microscope/main?logo=appveyor)](https://ci.appveyor.com/project/bert2/microscope/branch/main) [![CodeFactor](https://www.codefactor.io/repository/github/bert2/microscope/badge)](https://www.codefactor.io/repository/github/bert2/microscope) ![last commit](https://img.shields.io/github/last-commit/bert2/microscope/main?logo=github) [![Visual Studio Marketplace Version](https://img.shields.io/visual-studio-marketplace/v/bert.microscope?label=marketplace&logo=visual-studio&logoColor=%23bb88f3)](https://marketplace.visualstudio.com/items?itemName=bert.microscope) [![Visual Studio Marketplace Installs](https://img.shields.io/visual-studio-marketplace/i/bert.microscope?label=installs&logo=visual-studio&logoColor=%23bb88f3)](https://marketplace.visualstudio.com/items?itemName=bert.microscope) 4 | 5 | A CodeLens extension for Visual Studio that lets you inspect the intermediate language instructions of methods and properties. 6 | 7 | ![Usage example](img/usage.gif "Usage example") 8 | 9 | It also shows the compiler-generated code for lambdas/closures, local functions, `async` methods, and iterators: 10 | 11 | ![Usage example: compiler-generated code](img/usage-csc-gen.gif "Usage example: compiler-generated code") 12 | 13 | It's mostly useful for learning and getting a better understanding of how C# works internally, but it's a must-have if you enjoy procrastinating work with futile micro-optimizations: 14 | 15 | ![Usage example: micro-optimization](img/usage-opt.gif "Usage example: micro-optimization") 16 | 17 | ## Installation 18 | 19 | ### Visual Studio 2022 20 | 21 | - Install latest stable release from the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=bert.microscope). 22 | - Alternatively you can grab the [VSIX package](https://ci.appveyor.com/project/bert2/microscope/branch/main/artifacts) of the latest build from AppVeyor. 23 | 24 | ### Visual Studio 2019 25 | 26 | - Installation via Extension Marketplace is not possible. Download the VSIX package of the [v1.1.0 release](https://github.com/bert2/microscope/releases/tag/1.1.0) and install microscope manually. 27 | 28 | ## Usage 29 | 30 | - The CodeLens appears on C#/VB methods/properties and displays the number of instructions that will be generated for the method. 31 | - Click the CodeLens to get a detailed list of all instructions including their offsets and operands. 32 | - Hover over an instruction in the list to see its documentation summary in a tooltip. 33 | - Double-click an instruction in the list to navigate to its documentation on [docs.microsoft.com](https://docs.microsoft.com/dotnet/api/system.reflection.emit.opcodes). 34 | - Hover over the CodeLens to see individual counts for the number of `box` and unconstrained `callvirt` instructions in the method as well the method's/property's byte size. 35 | - The CodeLens will automatically update everytime you save the current document. You can also click the "Refresh" button in the bottom left of the details view. 36 | - Any types that the compiler generated for the method/property (e.g. for lambdas) will be shown below the list of instructions together with their methods and instructions. 37 | - In case the retrieval of instructions fails the CodeLens will display `-` instead of a count. Hover over the CodeLens to see the exception that caused the failure. 38 | - Configuration options are available in the Visual Studio settings ("Tools" > "Options..." > "microscope"). 39 | 40 | ![Settings page](img/settings-page.png "Settings page") 41 | 42 | ## Known issues 43 | 44 | - Visual Studio might freeze for a couple of seconds when you open the details view for a method with a huge amount of instructions (i.e. multiple thousands). This might be fixed in a future release. 45 | 46 | ## Contributing 47 | 48 | Bug reports and pull requests are always welcome! 49 | 50 | ### Issue tracker 51 | 52 | Feel free to [create an issue on GitHub](https://github.com/bert2/microscope/issues/new) if you found a bug, have a question or got an idea how to improve microscope. 53 | 54 | ### Cloning the source 55 | 56 | ```powershell 57 | PS> git clone https://github.com/bert2/microscope.git 58 | PS> cd microscope 59 | ``` 60 | 61 | ### Building 62 | 63 | Building microscope from source requires Visual Studio 2019 and the [Visual Studio SDK](https://docs.microsoft.com/en-us/visualstudio/extensibility/installing-the-visual-studio-sdk?view=vs-2019). 64 | 65 | You can build using either Visual Studio or the build script located in microscope's root directory: 66 | 67 | ```powershell 68 | PS> ./build.ps1 compile 69 | ``` 70 | 71 | ### Running the tests 72 | 73 | The tests are implemented using MSTest. You can execute them via Visual Studio or from microscope's root directory: 74 | 75 | ```powershell 76 | PS> ./build.ps1 test # will also build 77 | ``` 78 | 79 | ### `nuke` global tool 80 | 81 | Microscope uses [nuke](https://github.com/nuke-build/nuke) as its build tool. You can install nuke's global tool via `dotnet`: 82 | 83 | ```powershell 84 | PS> dotnet tool install Nuke.GlobalTool --global 85 | ``` 86 | 87 | Don't forget to setup its [auto-completion](https://www.nuke.build/docs/running-builds/global-tool.html#shell-snippets) too. 88 | 89 | Even though the global tool is not required, it makes life a little bit easier: 90 | 91 | ```powershell 92 | PS> nuke test # build and run tests 93 | ``` 94 | 95 | ## Possible features for future releases 96 | 97 | - show C# code in details view 98 | - lazy load when method has too many instructions to prevent temporarily freezing VS 99 | - don't show CodeLens on interface/abstract methods 100 | - reduce namespace noise in operands column of details view 101 | - setting for that 102 | - checkbox in details view for the setting as well 103 | - is it possible to move in-memory compiling and IL retrieval out of the VS process? 104 | - can we even access the `Compilation` out-of-proc? 105 | 106 | ## Changelog 107 | 108 | ### 2.4.0 109 | 110 | - Support inspecting the instructions of properties. 111 | 112 | ### 2.3.0 113 | 114 | - Support Visual Basic projects. 115 | 116 | ### 2.2.0 117 | 118 | - The code lense tooltip now also shows the method's byte size. 119 | 120 | ### 2.1.0 121 | 122 | - Adds new setting to the options page controling whether optimized (release) or unoptimized (debug) instructions are shown. 123 | 124 | ### 2.0.0 125 | 126 | - Support Visual Studio 2022. Visual Studio 2019 is no longer supported. 127 | 128 | ### 1.1.0 129 | 130 | - Adds support for local functions. 131 | 132 | ### 1.0.3 133 | 134 | - Fixes `Mono.Cecil.AssemblyResolutionException`s during retrieval of compiler-generated code. 135 | 136 | ### 1.0.2 137 | 138 | - Fixes `NullReferenceException`s during retrieval of compiler-generated code. 139 | 140 | ### 1.0.1 141 | 142 | - Fixes a bug where the compiler-generated code for nested lambdas would not be shown. 143 | - Fixes a bug where compiler-generated code for unrelated lambdas would be shown. 144 | - Fixes a bug where the compiler-generated class for anonymous types would not be shown. 145 | 146 | ### 1.0.0 147 | 148 | - Instructions of compiler-generated types/methods are now also shown below the instructions of the code-lensed method. 149 | 150 | ### 0.5.3 151 | 152 | - Refactoring to greatly reduce the amount of data exchanged between the out-of-process CodeLens engine and Visual Studio. 153 | 154 | ### 0.5.2 155 | 156 | - Fixes a bug where clicking on an instruction's opcode that has a trailing dot in its name would not open the correct documentation page. 157 | 158 | ### 0.5.1 159 | 160 | - Fixes a bug where the documentation of instructions with opcodes that have a trailing dot in their name could not be retrieved. 161 | - Adds a new custom UI for the details view, replacing the default grid UI. This is only a minor visual change, but enables future features like including instructions from compiler-generated classes or showing the CodeLens on classes. 162 | 163 | ### 0.5.0 164 | 165 | - Add settings page to de/activate auto-refresh on save. 166 | 167 | ### 0.4.0 168 | 169 | - Instructions are now refreshed automatically when saving a file. 170 | - Don't duplicate compiler errors in the tooltip for failed CodeLenses. 171 | 172 | ### 0.3.0 173 | 174 | - Show XML documentation of OpCode as tooltip when hovering an instruction. 175 | 176 | ### 0.2.0 177 | 178 | - Double-clicking an instruction in the details view now opens its documentation in the browser. 179 | 180 | ### 0.1.3 181 | 182 | - Fixes an issue where the "Refresh" button might not work when multiple instances of VS where open. 183 | 184 | ### 0.1.2 185 | 186 | - Only fixes development problems with the pipe connections between VS and the CodeLenses by using a different pipe for the VS experimental instance. 187 | 188 | ### 0.1.1 189 | 190 | - Fixes a bug where the "Refresh" button was not working properly when too many CodeLenses where loaded at once. 191 | - Fixes a regression bug where instruction retrieval failures would not be shown in the CodeLens tooltip. 192 | 193 | ### 0.1.0 194 | 195 | - Adds a "Refresh" button to the details view which retrieves the instructions of the method again. 196 | 197 | ### 0.0.5 198 | 199 | - Fixes an issue where IL retrieval failed for projects with multiple target frameworks. 200 | 201 | ### 0.0.4 202 | 203 | - Overload resolution has been extended to handle `dynamic` parameters as well. There no longer should be any issues saying that a method couldn't be found or that a method couldn't be uniquely identified. 204 | 205 | ### 0.0.3 206 | 207 | - Overload resolution has been extended to handle more types: arrays, pointers, and `ref`s. 208 | 209 | ### 0.0.2 210 | 211 | - Overload resolution has been reworked completely and now works better with generic and/or nested types. Some issues might still remain and will be addressed in the next release. 212 | 213 | ### 0.0.1 214 | 215 | Intitial preview release. 216 | 217 | - Enables CodeLens on C# methods showing the number of IL instructions. 218 | - Clicking the CodeLens opens a details view listing all IL instructions of the method. 219 | - Refreshing the CodeLens after code changes currently requires closing and re-opening the C# source file. 220 | 221 | ## Versioning scheme 222 | 223 | Microscope's versioning scheme uses a manually maintained [semantic version](https://semver.org/) with an appended build number. A semver bump is triggered by creating a Git tag. The build version is auto-incremented by [AppVeyor](https://ci.appveyor.com/project/bert2/microscope/branch/main). 224 | 225 | ## Credits 226 | 227 | ### Similar tools 228 | 229 | - [VSCodeILViewer](https://github.com/JosephWoodward/VSCodeILViewer) by Joseph Woodward only works with VSCode and isn't updated anymore. Joseph wrote a nice [article](https://josephwoodward.co.uk/2017/01/c-sharp-il-viewer-vs-code-using-roslyn) on its implementation which helped me getting started. 230 | - [Msiler](https://marketplace.visualstudio.com/items?itemName=segrived.msiler2017) by Evgeniy Babaev looks like an excellent tool, but unfortunately it's not available for Visual Studio 2019. I discovered it when I was way into the development of microscope and if I had found it earlier, I might have tried patching Msiler first. 231 | 232 | ### Dependencies 233 | 234 | - [Roslyn](https://github.com/dotnet/roslyn) compiles the current project in memory. 235 | - [Mono.Cecil](https://github.com/jbevain/cecil) retrieves the IL instructions from the compiled project. 236 | - [nuke](https://github.com/nuke-build/nuke) orchestrates the builds for microscope. 237 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | # We have to use `cmd` instead of `ps` so unicode is rendered correctly. 2 | version: '{build}' 3 | image: Visual Studio 2019 4 | environment: 5 | marketplaceKey: 6 | secure: /V44/pvMDD3CZ/FJKsgY6FC+xR4Sa6jwsLEAtzYmfwA8v8Qvt4vhrPf2jYWI+4DAW3lL9eCTUxnUIsgkRzZwgw== 7 | NUKE_TELEMETRY_OPTOUT: true 8 | build_script: 9 | - cmd: .\build.cmd --update-version --build-number %APPVEYOR_BUILD_NUMBER% 10 | test_script: 11 | - cmd: .\build.cmd test --skip --no-logo 12 | artifacts: 13 | - path: ./src/VSExtension/bin/Release/Microscope.VSExtension.vsix 14 | name: Latest build 15 | deploy_script: 16 | - cmd: if "%APPVEYOR_REPO_TAG%"=="true" .\build.cmd publish --build-number %APPVEYOR_BUILD_NUMBER% --no-logo 17 | -------------------------------------------------------------------------------- /build.cmd: -------------------------------------------------------------------------------- 1 | :; set -eo pipefail 2 | :; SCRIPT_DIR=$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd) 3 | :; ${SCRIPT_DIR}/build.sh "$@" 4 | :; exit $? 5 | 6 | @ECHO OFF 7 | powershell -ExecutionPolicy ByPass -NoProfile -File "%~dp0build.ps1" %* 8 | -------------------------------------------------------------------------------- /build.ps1: -------------------------------------------------------------------------------- 1 | [CmdletBinding()] 2 | Param( 3 | [Parameter(Position=0,Mandatory=$false,ValueFromRemainingArguments=$true)] 4 | [string[]]$BuildArguments 5 | ) 6 | 7 | Write-Output "PowerShell $($PSVersionTable.PSEdition) version $($PSVersionTable.PSVersion)" 8 | 9 | Set-StrictMode -Version 2.0; $ErrorActionPreference = "Stop"; $ConfirmPreference = "None"; trap { Write-Error $_ -ErrorAction Continue; exit 1 } 10 | $PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent 11 | 12 | ########################################################################### 13 | # CONFIGURATION 14 | ########################################################################### 15 | 16 | $BuildProjectFile = "$PSScriptRoot\build\_build.csproj" 17 | $TempDirectory = "$PSScriptRoot\\.nuke\temp" 18 | 19 | $DotNetGlobalFile = "$PSScriptRoot\\global.json" 20 | $DotNetInstallUrl = "https://dot.net/v1/dotnet-install.ps1" 21 | $DotNetChannel = "Current" 22 | 23 | $env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE = 1 24 | $env:DOTNET_CLI_TELEMETRY_OPTOUT = 1 25 | $env:DOTNET_MULTILEVEL_LOOKUP = 0 26 | 27 | ########################################################################### 28 | # EXECUTION 29 | ########################################################################### 30 | 31 | function ExecSafe([scriptblock] $cmd) { 32 | & $cmd 33 | if ($LASTEXITCODE) { exit $LASTEXITCODE } 34 | } 35 | 36 | # If dotnet CLI is installed globally and it matches requested version, use for execution 37 | if ($null -ne (Get-Command "dotnet" -ErrorAction SilentlyContinue) -and ` 38 | $(dotnet --version) -and $LASTEXITCODE -eq 0) { 39 | $env:DOTNET_EXE = (Get-Command "dotnet").Path 40 | } 41 | else { 42 | # Download install script 43 | $DotNetInstallFile = "$TempDirectory\dotnet-install.ps1" 44 | New-Item -ItemType Directory -Path $TempDirectory -Force | Out-Null 45 | [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 46 | (New-Object System.Net.WebClient).DownloadFile($DotNetInstallUrl, $DotNetInstallFile) 47 | 48 | # If global.json exists, load expected version 49 | if (Test-Path $DotNetGlobalFile) { 50 | $DotNetGlobal = $(Get-Content $DotNetGlobalFile | Out-String | ConvertFrom-Json) 51 | if ($DotNetGlobal.PSObject.Properties["sdk"] -and $DotNetGlobal.sdk.PSObject.Properties["version"]) { 52 | $DotNetVersion = $DotNetGlobal.sdk.version 53 | } 54 | } 55 | 56 | # Install by channel or version 57 | $DotNetDirectory = "$TempDirectory\dotnet-win" 58 | if (!(Test-Path variable:DotNetVersion)) { 59 | ExecSafe { & powershell $DotNetInstallFile -InstallDir $DotNetDirectory -Channel $DotNetChannel -NoPath } 60 | } else { 61 | ExecSafe { & powershell $DotNetInstallFile -InstallDir $DotNetDirectory -Version $DotNetVersion -NoPath } 62 | } 63 | $env:DOTNET_EXE = "$DotNetDirectory\dotnet.exe" 64 | } 65 | 66 | Write-Output "Microsoft (R) .NET Core SDK version $(& $env:DOTNET_EXE --version)" 67 | 68 | ExecSafe { & $env:DOTNET_EXE build $BuildProjectFile /nodeReuse:false /p:UseSharedCompilation=false -nologo -clp:NoSummary --verbosity quiet } 69 | ExecSafe { & $env:DOTNET_EXE run --project $BuildProjectFile --no-build -- $BuildArguments } 70 | -------------------------------------------------------------------------------- /build.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | bash --version 2>&1 | head -n 1 4 | 5 | set -eo pipefail 6 | SCRIPT_DIR=$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd) 7 | 8 | ########################################################################### 9 | # CONFIGURATION 10 | ########################################################################### 11 | 12 | BUILD_PROJECT_FILE="$SCRIPT_DIR/build/_build.csproj" 13 | TEMP_DIRECTORY="$SCRIPT_DIR//.nuke/temp" 14 | 15 | DOTNET_GLOBAL_FILE="$SCRIPT_DIR//global.json" 16 | DOTNET_INSTALL_URL="https://dot.net/v1/dotnet-install.sh" 17 | DOTNET_CHANNEL="Current" 18 | 19 | export DOTNET_CLI_TELEMETRY_OPTOUT=1 20 | export DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1 21 | export DOTNET_MULTILEVEL_LOOKUP=0 22 | 23 | ########################################################################### 24 | # EXECUTION 25 | ########################################################################### 26 | 27 | function FirstJsonValue { 28 | perl -nle 'print $1 if m{"'"$1"'": "([^"]+)",?}' <<< "${@:2}" 29 | } 30 | 31 | # If dotnet CLI is installed globally and it matches requested version, use for execution 32 | if [ -x "$(command -v dotnet)" ] && dotnet --version &>/dev/null; then 33 | export DOTNET_EXE="$(command -v dotnet)" 34 | else 35 | # Download install script 36 | DOTNET_INSTALL_FILE="$TEMP_DIRECTORY/dotnet-install.sh" 37 | mkdir -p "$TEMP_DIRECTORY" 38 | curl -Lsfo "$DOTNET_INSTALL_FILE" "$DOTNET_INSTALL_URL" 39 | chmod +x "$DOTNET_INSTALL_FILE" 40 | 41 | # If global.json exists, load expected version 42 | if [[ -f "$DOTNET_GLOBAL_FILE" ]]; then 43 | DOTNET_VERSION=$(FirstJsonValue "version" "$(cat "$DOTNET_GLOBAL_FILE")") 44 | if [[ "$DOTNET_VERSION" == "" ]]; then 45 | unset DOTNET_VERSION 46 | fi 47 | fi 48 | 49 | # Install by channel or version 50 | DOTNET_DIRECTORY="$TEMP_DIRECTORY/dotnet-unix" 51 | if [[ -z ${DOTNET_VERSION+x} ]]; then 52 | "$DOTNET_INSTALL_FILE" --install-dir "$DOTNET_DIRECTORY" --channel "$DOTNET_CHANNEL" --no-path 53 | else 54 | "$DOTNET_INSTALL_FILE" --install-dir "$DOTNET_DIRECTORY" --version "$DOTNET_VERSION" --no-path 55 | fi 56 | export DOTNET_EXE="$DOTNET_DIRECTORY/dotnet" 57 | fi 58 | 59 | echo "Microsoft (R) .NET Core SDK version $("$DOTNET_EXE" --version)" 60 | 61 | "$DOTNET_EXE" build "$BUILD_PROJECT_FILE" /nodeReuse:false /p:UseSharedCompilation=false -nologo -clp:NoSummary --verbosity quiet 62 | "$DOTNET_EXE" run --project "$BUILD_PROJECT_FILE" --no-build -- "$@" 63 | -------------------------------------------------------------------------------- /build/.editorconfig: -------------------------------------------------------------------------------- 1 | [*.cs] 2 | dotnet_style_qualification_for_field = false:warning 3 | dotnet_style_qualification_for_property = false:warning 4 | dotnet_style_qualification_for_method = false:warning 5 | dotnet_style_qualification_for_event = false:warning 6 | dotnet_style_require_accessibility_modifiers = never:warning 7 | 8 | csharp_style_expression_bodied_methods = true:silent 9 | csharp_style_expression_bodied_properties = true:warning 10 | csharp_style_expression_bodied_indexers = true:warning 11 | csharp_style_expression_bodied_accessors = true:warning 12 | 13 | # IDE0058: Expression value is never used 14 | csharp_style_unused_value_expression_statement_preference = discard_variable:silent 15 | 16 | # RCS1018: Add accessibility modifiers. 17 | dotnet_diagnostic.RCS1018.severity = silent 18 | 19 | # IDE0051: Remove unused private members 20 | dotnet_diagnostic.IDE0051.severity = silent 21 | 22 | # RCS1213: Remove unused member declaration. 23 | dotnet_diagnostic.RCS1213.severity = silent 24 | 25 | # RCS1110: Declare type inside namespace. 26 | dotnet_diagnostic.RCS1110.severity = silent 27 | -------------------------------------------------------------------------------- /build/Build.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Nuke.Common; 3 | using Nuke.Common.Execution; 4 | using Nuke.Common.Git; 5 | using Nuke.Common.IO; 6 | using Nuke.Common.ProjectModel; 7 | using Nuke.Common.Tooling; 8 | using Nuke.Common.Tools.MSBuild; 9 | using Nuke.Common.Utilities.Collections; 10 | using static Nuke.Common.Logger; 11 | using static Nuke.Common.IO.FileSystemTasks; 12 | using static Nuke.Common.IO.PathConstruction; 13 | using static Nuke.Common.IO.TextTasks; 14 | using static Nuke.Common.IO.XmlTasks; 15 | using static Nuke.Common.Tools.MSBuild.MSBuildTasks; 16 | using static Nuke.Common.Tools.VSTest.VSTestTasks; 17 | using System.Linq; 18 | using Nuke.Common.Utilities; 19 | using System.Text; 20 | 21 | [CheckBuildProjectConfigurations] 22 | [UnsetVisualStudioEnvironmentVariables] 23 | class Build : NukeBuild { 24 | public static int Main() => Execute(x => x.Compile); 25 | 26 | [Parameter("Configuration to build - Optional (default: 'Release')")] 27 | readonly string Configuration = "Release"; 28 | 29 | [Parameter("Version - Optional, set to latest tag if omitted (default: null)")] 30 | readonly string SemVer; 31 | 32 | [Parameter("Number identifying the build - Optional, set by the CI (default: 0)")] 33 | readonly int BuildNumber; 34 | 35 | [Parameter("Update assembly properties and VSIX manifest with current version during build - Optional (default: false)")] 36 | readonly bool UpdateVersion; 37 | 38 | [Parameter("Personal access token for the VS Marketplace - Required for target `Publish` (default: null)")] 39 | readonly string MarketplaceKey; 40 | 41 | [Solution] readonly Solution Solution; 42 | 43 | [GitRepository] readonly GitRepository GitRepository; 44 | 45 | [PathExecutable] readonly Tool Git; 46 | 47 | [PackageExecutable("Microsoft.VSSDK.BuildTools", "VsixPublisher.exe")] 48 | readonly Tool VsixPublisher; 49 | 50 | private string version; 51 | string Version { 52 | get { 53 | version ??= $"{SemVer ?? LastGitTag()}.{BuildNumber}"; 54 | return version; 55 | } 56 | } 57 | 58 | AbsolutePath SrcDir => RootDirectory / "src"; 59 | 60 | AbsolutePath VsixProjDir => SrcDir / "VSExtension"; 61 | 62 | AbsolutePath VsixOutDir => VsixProjDir / "bin" / Configuration; 63 | 64 | Target Clean => _ => _ 65 | .Before(Restore) 66 | .Executes(() => { 67 | SrcDir.GlobDirectories("**/bin", "**/obj").ForEach(DeleteDirectory); 68 | }); 69 | 70 | Target Restore => _ => _ 71 | .Executes(() => { 72 | MSBuild(s => s 73 | .SetMSBuildPlatform(MSBuildPlatform.x86) 74 | .SetTargetPath(Solution) 75 | .SetTargets("Restore") 76 | .SetVerbosity(MSBuildVerbosity.Minimal)); 77 | }); 78 | 79 | Target SetVersion => _ => _ 80 | .OnlyWhenStatic(() => UpdateVersion) 81 | .Executes(() => { 82 | Info($"Current version is {Version}."); 83 | 84 | Info("Updating assembly properties..."); 85 | 86 | SrcDir.GlobFiles("**/AssemblyInfo.cs").ForEach(file => 87 | ReplaceText( 88 | file, 89 | @"Version\(""\d+\.\d+\.\d+\.\d+""\)", 90 | $@"Version(""{Version}"")")); 91 | 92 | Info("Updating VSIX manifest..."); 93 | 94 | ReplaceText( 95 | VsixProjDir / "source.extension.cs", 96 | @"Version = ""\d+\.\d+\.\d+\.\d+""", 97 | $@"Version = ""{Version}""", 98 | bom: false); 99 | 100 | XmlPoke( 101 | VsixProjDir / "source.extension.vsixmanifest", 102 | "/ns:PackageManifest/ns:Metadata/ns:Identity/@Version", 103 | Version, 104 | ("ns", "http://schemas.microsoft.com/developer/vsx-schema/2011")); 105 | }); 106 | 107 | Target Compile => _ => _ 108 | .DependsOn(Restore) 109 | .DependsOn(SetVersion) 110 | .Executes(() => { 111 | MSBuild(s => s 112 | .SetMSBuildPlatform(MSBuildPlatform.x86) 113 | .SetTargetPath(Solution) 114 | .SetTargets("Rebuild") 115 | .SetVerbosity(MSBuildVerbosity.Minimal) 116 | .SetConfiguration(Configuration) 117 | .SetMaxCpuCount(Environment.ProcessorCount) 118 | .SetNodeReuse(IsLocalBuild) 119 | .SetProperty("DeployExtension", false) 120 | .SetProperty("ZipPackageCompressionLevel", "normal")); 121 | }); 122 | 123 | Target Test => _ => _ 124 | .DependsOn(Compile) 125 | .Executes(() => { 126 | var p = Solution.GetProject("Tests"); 127 | var outDir = p.GetMSBuildProject(Configuration).GetPropertyValue("OutputPath"); 128 | VSTest(p.Directory / outDir / "Microscope.Tests.dll"); 129 | }); 130 | 131 | Target Publish => _ => _ 132 | .Requires( 133 | () => MarketplaceKey != null, 134 | () => GitRepository.Branch == "main") 135 | .Executes(() => { 136 | Info($"Publishing {Version} to Visual Studio Marketplace..."); 137 | var manifest = RootDirectory / "publish-manifest.json"; 138 | var vsixPkg = VsixOutDir / "Microscope.VSExtension.vsix"; 139 | VsixPublisher($"publish -publishManifest {manifest} -payload {vsixPkg} -personalAccessToken {MarketplaceKey}"); 140 | }); 141 | 142 | private string LastGitTag() => Git("describe --tags --abbrev=0", logOutput: false).Single().Text; 143 | 144 | private static void ReplaceText(AbsolutePath file, string pattern, string replacement, bool bom = true) { 145 | var text = ReadAllText(file).ReplaceRegex(pattern, _ => replacement); 146 | WriteAllText(file, text, bom ? Encoding.UTF8 : null); 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /build/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "_build": { 4 | "commandName": "Project", 5 | "commandLineArgs": "--target setversion" 6 | } 7 | } 8 | } -------------------------------------------------------------------------------- /build/_build.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | CS0649;CS0169 8 | .. 9 | .. 10 | 11 | 12 | 13 | 14 | 15 | all 16 | runtime; build; native; contentfiles; analyzers; buildtransitive 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /build/_build.csproj.DotSettings: -------------------------------------------------------------------------------- 1 | 2 | DO_NOT_SHOW 3 | DO_NOT_SHOW 4 | DO_NOT_SHOW 5 | DO_NOT_SHOW 6 | Implicit 7 | Implicit 8 | ExpressionBody 9 | 0 10 | NEXT_LINE 11 | True 12 | False 13 | 120 14 | IF_OWNER_IS_SINGLE_LINE 15 | WRAP_IF_LONG 16 | False 17 | <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> 18 | <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> 19 | True 20 | True 21 | True 22 | True 23 | True 24 | True 25 | True 26 | True 27 | -------------------------------------------------------------------------------- /build/appveyor.yml: -------------------------------------------------------------------------------- 1 | # We have to use `cmd` instead of `ps` so unicode is rendered correctly. 2 | version: '{build}' 3 | image: Visual Studio 2019 4 | environment: 5 | marketplaceKey: 6 | secure: BZmbULp1SVBph/vcYiTXJnaxphIu8TTV1v0VZShOjVOc4RZvkhLaJyeb0QGvtg143vQOrza/9I+wyz6nMG1SbQ== 7 | NUKE_TELEMETRY_OPTOUT: true 8 | build_script: 9 | - cmd: .\build.cmd --update-version --build-number %APPVEYOR_BUILD_NUMBER% 10 | test_script: 11 | - cmd: .\build.cmd test --skip --no-logo 12 | artifacts: 13 | - path: ./src/VSExtension/bin/Release/Microscope.VSExtension.vsix 14 | name: Latest build 15 | deploy_script: 16 | - cmd: if "%APPVEYOR_REPO_TAG%"=="true" .\build.cmd publish --build-number %APPVEYOR_BUILD_NUMBER% --no-logo 17 | -------------------------------------------------------------------------------- /img/settings-page.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bert2/microscope/43743af1adadf9bfc2111fb85d58dd68dd84b3e5/img/settings-page.png -------------------------------------------------------------------------------- /img/usage-csc-gen.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bert2/microscope/43743af1adadf9bfc2111fb85d58dd68dd84b3e5/img/usage-csc-gen.gif -------------------------------------------------------------------------------- /img/usage-opt.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bert2/microscope/43743af1adadf9bfc2111fb85d58dd68dd84b3e5/img/usage-opt.gif -------------------------------------------------------------------------------- /img/usage.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bert2/microscope/43743af1adadf9bfc2111fb85d58dd68dd84b3e5/img/usage.gif -------------------------------------------------------------------------------- /microscope.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30330.147 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Shared", "src\Shared\Shared.csproj", "{D6F37EEC-CBA3-4DB2-B44C-5F036C6FAA9F}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeLensProvider", "src\CodeLensProvider\CodeLensProvider.csproj", "{FA8F7552-7E27-425B-9B81-09E0789179A3}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VSExtension", "src\VSExtension\VSExtension.csproj", "{A0920311-8835-4915-9E9B-384F5D8F1113}" 11 | EndProject 12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{1BB4977B-68F4-4F4B-AE01-0E477A454E9A}" 13 | ProjectSection(SolutionItems) = preProject 14 | .editorconfig = .editorconfig 15 | .gitignore = .gitignore 16 | LICENSE = LICENSE 17 | publish-manifest.json = publish-manifest.json 18 | README.md = README.md 19 | EndProjectSection 20 | EndProject 21 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "_build", "build\_build.csproj", "{A8374006-F0B8-4AF1-9DCA-A0B7ED193DC5}" 22 | EndProject 23 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "img", "img", "{C2F6B56F-9586-421D-861C-92AF566D4F29}" 24 | ProjectSection(SolutionItems) = preProject 25 | img\usage.gif = img\usage.gif 26 | EndProjectSection 27 | EndProject 28 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tests", "tests\Tests.csproj", "{EE04FE33-9AE6-42C1-A7B9-794196D52A4F}" 29 | EndProject 30 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeAnalysis", "src\CodeAnalysis\CodeAnalysis.csproj", "{F98BB94E-CF38-466B-ADFD-9BB26D8493B7}" 31 | EndProject 32 | Global 33 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 34 | Debug|Any CPU = Debug|Any CPU 35 | Release|Any CPU = Release|Any CPU 36 | EndGlobalSection 37 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 38 | {D6F37EEC-CBA3-4DB2-B44C-5F036C6FAA9F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 39 | {D6F37EEC-CBA3-4DB2-B44C-5F036C6FAA9F}.Debug|Any CPU.Build.0 = Debug|Any CPU 40 | {D6F37EEC-CBA3-4DB2-B44C-5F036C6FAA9F}.Release|Any CPU.ActiveCfg = Release|Any CPU 41 | {D6F37EEC-CBA3-4DB2-B44C-5F036C6FAA9F}.Release|Any CPU.Build.0 = Release|Any CPU 42 | {FA8F7552-7E27-425B-9B81-09E0789179A3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 43 | {FA8F7552-7E27-425B-9B81-09E0789179A3}.Debug|Any CPU.Build.0 = Debug|Any CPU 44 | {FA8F7552-7E27-425B-9B81-09E0789179A3}.Release|Any CPU.ActiveCfg = Release|Any CPU 45 | {FA8F7552-7E27-425B-9B81-09E0789179A3}.Release|Any CPU.Build.0 = Release|Any CPU 46 | {A0920311-8835-4915-9E9B-384F5D8F1113}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 47 | {A0920311-8835-4915-9E9B-384F5D8F1113}.Debug|Any CPU.Build.0 = Debug|Any CPU 48 | {A0920311-8835-4915-9E9B-384F5D8F1113}.Release|Any CPU.ActiveCfg = Release|Any CPU 49 | {A0920311-8835-4915-9E9B-384F5D8F1113}.Release|Any CPU.Build.0 = Release|Any CPU 50 | {A8374006-F0B8-4AF1-9DCA-A0B7ED193DC5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 51 | {A8374006-F0B8-4AF1-9DCA-A0B7ED193DC5}.Release|Any CPU.ActiveCfg = Release|Any CPU 52 | {EE04FE33-9AE6-42C1-A7B9-794196D52A4F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 53 | {EE04FE33-9AE6-42C1-A7B9-794196D52A4F}.Debug|Any CPU.Build.0 = Debug|Any CPU 54 | {EE04FE33-9AE6-42C1-A7B9-794196D52A4F}.Release|Any CPU.ActiveCfg = Release|Any CPU 55 | {EE04FE33-9AE6-42C1-A7B9-794196D52A4F}.Release|Any CPU.Build.0 = Release|Any CPU 56 | {F98BB94E-CF38-466B-ADFD-9BB26D8493B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 57 | {F98BB94E-CF38-466B-ADFD-9BB26D8493B7}.Debug|Any CPU.Build.0 = Debug|Any CPU 58 | {F98BB94E-CF38-466B-ADFD-9BB26D8493B7}.Release|Any CPU.ActiveCfg = Release|Any CPU 59 | {F98BB94E-CF38-466B-ADFD-9BB26D8493B7}.Release|Any CPU.Build.0 = Release|Any CPU 60 | EndGlobalSection 61 | GlobalSection(SolutionProperties) = preSolution 62 | HideSolutionNode = FALSE 63 | EndGlobalSection 64 | GlobalSection(NestedProjects) = preSolution 65 | {C2F6B56F-9586-421D-861C-92AF566D4F29} = {1BB4977B-68F4-4F4B-AE01-0E477A454E9A} 66 | EndGlobalSection 67 | GlobalSection(ExtensibilityGlobals) = postSolution 68 | SolutionGuid = {D8CD2B0A-41BD-4DFC-A181-0D69D54FBB71} 69 | EndGlobalSection 70 | EndGlobal 71 | -------------------------------------------------------------------------------- /publish-manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/vsix-publish", 3 | "categories": [ "coding", "programming languages" ], 4 | "identity": { 5 | "internalName": "microscope" 6 | }, 7 | "overview": "README.md", 8 | "priceCategory": "free", 9 | "publisher": "bert", 10 | "private": false, 11 | "qna": true, 12 | "repo": "https://github.com/bert2/microscope", 13 | "assetFiles": [ 14 | { 15 | "pathOnDisk": "img\\usage.gif", 16 | "targetPath": "img/usage.gif" 17 | }, 18 | { 19 | "pathOnDisk": "img\\usage-csc-gen.gif", 20 | "targetPath": "img/usage-csc-gen.gif" 21 | }, 22 | { 23 | "pathOnDisk": "img\\usage-opt.gif", 24 | "targetPath": "img/usage-opt.gif" 25 | }, 26 | { 27 | "pathOnDisk": "img\\settings-page.png", 28 | "targetPath": "img/settings-page.png" 29 | } 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /research/references-code-lens-call-graph.drawio: -------------------------------------------------------------------------------- 1 | 3V1Zc+K4Fv41VHU/QFnyBo9pSCd9u6d6yWx5mjJYgG8biysbAvPrr4UlL5INgnhLV6USrM3W2c+nYzLQp5vDA3G269+wi/wB1NzDQJ8NIARjCAf0R3OPSUvasCKemzRpWcOT9y9iM3nrznNRyNqSpghjP/K2xcYFDgK0iAptDiH4pThsiX230LB1VqjwGLThaeH4SBr2l+dGa7YLMzf6EXmrNb8z0FjPxuGDWUO4dlz8kmvS7wf6lGAcJZ82hynyKfGKdPlY0Zs+GEFBpDLhd/D4fPj6ffrH/vuf2ofZ4fD4cTpkq+wdf8c2/AMtUbzkAk1jXn5BQfiN4H3MA8J2ER05aQjeBS6iq4OB/uFl7UXoaessaO9LLAxx2zra+Kxbflp+a0QidMg1sad/QHiDInKMh7BeA5jJFCZKBiPsS8YXMGZt6xxPLNbmMFFYpStn1Io/MIJdQTxbIt6nYI9/orvwGCzeDaD1vx1lbrx3y6d/lzjeOxVVH5PT+GyAbtnOfLIszFnRv584G6bxZHSIRg8oyrFoF0Snu/FbxPtI7pLMztZ7L7EPubGgs0tMojVe4cDx77PWDxmDtfgqG/MF4y1j639RFB2Z1jq7CBeZjg5e9DedPjLZ1XOuZ3ZgK58ujuyiUlBCvCMLdIYdzLBEDlmh6Mw4PRlH939W7AjyncjbFw1B7UIEJSGaOZHzDXuUi11rHFcdpnEAyio3aVPjxhKxuOCHWycoEIsLPlWH4dLZeH68ibsB3YHlbLaJ1ukGpRny9yjyFo7UQ0effp8WCU9iTpcAYHsQ+pL70s4Ak43jF7tfGHFov0E9BOv0Y/VBZBg//MILVqXzqdIPHd9bBUn3ImYnNcb5bi+WioAtr+Ue7dQZEScIl/GifPkApQNeMHGLd89PnzuLn6uTzA2ZzaIjyGr+zoAnQk7pdvIf36dzXS/c+g4juRf4Xu6uSx87Uf5pRKP3GoNZbh/fva+2kLw5ESHe/DasZcx2csxNopfP+b5s2unq9VZWV7SyRq+srC676tSxOr5PJf0Jkb0Xb70zo8uMLCwxsu3GNUalla0jgqlUxI6dnV70dbpZwgbYJhssiQ2xbaPBQWrR3pqNKliozGDVbqNMRRsFe2WjgGykpgQ5EUoDwh4wHuTYnglB3aG8KgNBrxhoVtpNj1s55mQed/PRIw6j0fTLj9FhbI3QAeXsotcboziEI4Wk22zRKgI5YaoO+d6agWwriJuo6le/FIy76JZZytkDBlf5L9cJ16mqosC9o3BkfDn38eJn0vTRowRIJeLv3OdmDayqANQexbOpDN/gZiZFEXjwNRHMR7KhDBXJS1H6GLcL1kT2vEJ28MULIxT0AAXVuU7ydKEsTrXbjFP5A5UlV6ldDjtPr9IwXxdcmj62OvZpPK3Iw/C74Afa4CgDk0/BwZzkgIsErArm4ZZhVXLTX/HdPwf4JcgCD/ZpRFl0F9vBY+iFJ/ym5A6nFtfbX3fTmpDvZP+VkvQKJDwdUdjarx0sMAhx5qNltt2bACBLNXiYKDoPHmtqIwAE6zYEBov3bvUwfAheLkPUiPOAsv3rY0R6TeZWlbLD5nJ2dbGyehWTAhktu2C4unOBTKlMTZccXtzapsOToY6PXuBmpOqBvvQ7gwOq6gJ7BnLJqGYPFeXA5d8ueKNSxdFajbXLMKa+6Ih2QUcuZMCFfNkJFmtMTk585hG0iDwcDIR8XFA20JyyGaq+SRUvyUIew7T010U4PLERcmjbEIQweXoph24zVAJlB/hvRXxvk7rrUKAWHMINMmpCrgEcBa5HZG3hzM021WAfaSHDFhYaXyv7fLNCjdlwrBcXalA3ZBAqCSTpQcHU91APCoJM8TjA7vyUFMoBRX9CyRvDwnbr5oyxaihp1h1KliuhBYraDDRFu1BbRg8lmXo6bubYp5LVAwzYMmGBQJYBZC0ErWqh7NiLWvgpmOHFboO6hUJaT9OgcimCXbduvY6fcp5R5OcTcshifR+sToV9XesDMAS/BMDEllWiXVC/pDw8pV9fDIlRTHCBbpSQrVV/rstoapOnCH2tRgO2LYj02JaNPNTTUe0wR+/EbP+C6ZoOFR2DrpqutVSCIYdG+YPEviB3gIdwaQjJbX/esJklumOOm6JcvWW1V9e5d6m3dq+hdNVimPpVsTz/AQKSB9JY/lpcBI7FlUTXUAGM1JVJ6XJ2LtuGNd7Md2E7dkETEQxLg7JbLQl4YFM+1SgLePriZHunq6pIvF77KXEFVmEKiYemWLp2eSUgrtSwrsKSk+xeVCHVXnI0N2194lYmC3msZ1QCJvb0Zdsby1SFwqB261CVscdri4m0kWVN2FO8VsV1EY4UT9Yuqnjzpwe6DNj8qkVIdoNFSKpZmXIRUnaIZkM4qUUewUSMYW53OuLBGQAi1F7hdOK82Dnmhm3pgLD6oU0e5mQxrX72ycQJJjMVmd4kj9C6pvGCxCvzuCt8Tl8xqWEqHGcgqZZfVb0tqa5iRsXJYQ8zatjrKF359RLYTpQOgTWCddlMaI2pD+o0VjesTsXvJi/eTyDWUD2hq19WX2f55ICvj0AsN9CpovAQ6xIO25zLkM/lxKPq6Y7QLX8jOL7sQy1yHWFzc1GzsgpBVRXKlZ4ZNpOguoEaeHOxmQiqpl8dUXfMPB4XbmSxcKv7EFihjLNNVNeaFI+xbZ7VdIbpyrV8nZiPN1F/xmlz2QOP24kWbVMEfERBuRXTnShm13Upqgk6EbsbvNaVL8u3/5UymqqPq72Qq0JIDUFIpXfmm5Yt+aXlu3kYEWcR9a3MydBEWpWVOVltRqFmp5U0v5RmqroPLrDNHwmK0ma3rJkyQlmpmewk7QRw/Z6AkGljP1BH+ci+VH0haEh9//P5n++flpq7ff6wM57I9GGynZV8bzKn8G8o1kr3K4mTx228x+NXcr+PN5+Q9i2RnxPbsGRiG02VhP75jDd/HH8Mn73PM/uf8Gn8DT6UfEXuV+J6gUOOCbH75m5MftBzjoSNvTdaSkKjS29zTd3mrd6mgVdBzyn+ZWdTO1pY4WwMwTbaimDEZYDEEl+iq++tm1IZNTuV0eYjoivrMpRk9Jy9zMvoOVluvUTq+jeTU8MqRFZ2bd8TFl9m/4ohGZ79Qwv9/v8= -------------------------------------------------------------------------------- /research/references-code-lens-call-graph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bert2/microscope/43743af1adadf9bfc2111fb85d58dd68dd84b3e5/research/references-code-lens-call-graph.png -------------------------------------------------------------------------------- /src/CodeAnalysis/AllParametersMatchExt.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.CodeAnalysis { 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | 8 | using Microsoft.CodeAnalysis; 9 | 10 | using Mono.Cecil; 11 | 12 | public static class AllParametersMatchExt { 13 | public static bool AllParametersMatch(this IMethodSymbol target, MethodDefinition candidate) 14 | => target.Parameters 15 | // `t.OriginalDefinition` returns `T` for generic type parameters and itself (`this`) otherwise. 16 | .Zip(candidate.Parameters, (t, c) => t.OriginalDefinition.Matches(c)) 17 | .All(methodParamMatched => methodParamMatched); 18 | 19 | private static bool Matches(this IParameterSymbol target, ParameterDefinition candidate) 20 | => target.MetadataName == candidate.Name 21 | && target.ParamTypeMatches(candidate); 22 | 23 | private static bool ParamTypeMatches(this IParameterSymbol target, ParameterDefinition candidate) { 24 | var t = target.Type; 25 | var c = candidate.ParameterType; 26 | return target.RefKind == RefKind.None 27 | ? t.Matches(c) 28 | : c.IsByReference && t.Matches(c.GetElementType()); 29 | } 30 | 31 | private static bool Matches(this ITypeSymbol target, TypeReference candidate) { 32 | // Mono.Cecil exposes generic type arguments only on the innermost type in a hierarchy 33 | // of nested types. We collect them all here and compare each with the type arguments 34 | // we encounter while traversing the Roslyn symbol hierarchy. 35 | var candidateTypeArgs = candidate is IGenericInstance _candidate 36 | ? new Stack(_candidate.GenericArguments) 37 | : new Stack(capacity: 0); 38 | 39 | return target.Matches(candidate, candidateTypeArgs); 40 | } 41 | 42 | // Chains of nested types will keep recursing into this method while consuming all `candidateTypeArgs`. 43 | private static bool Matches(this ITypeSymbol target, TypeReference candidate, Stack candidateTypeArgs) => 44 | target.TypeKind switch { 45 | TypeKind.Array => target.ArrayTypeMatches(candidate), 46 | TypeKind.Pointer => target.PointerTypeMatches(candidate), 47 | TypeKind.Dynamic => candidate.FullName == "System.Object", // `dynamic` gets compiled to `object`. 48 | _ => target.PlainTypeMatches(candidate, candidateTypeArgs) 49 | }; 50 | 51 | private static bool ArrayTypeMatches(this ITypeSymbol target, TypeReference candidate) { 52 | if (!candidate.IsArray) return false; 53 | 54 | var t = (IArrayTypeSymbol)target; 55 | var c = (ArrayType)candidate; 56 | 57 | return t.Rank == c.Rank && t.ElementType.Matches(c.ElementType); 58 | } 59 | 60 | private static bool PointerTypeMatches(this ITypeSymbol target, TypeReference candidate) { 61 | if (!candidate.IsPointer) return false; 62 | 63 | var t = (IPointerTypeSymbol)target; 64 | var c = (PointerType)candidate; 65 | 66 | return t.PointedAtType.Matches(c.ElementType); 67 | } 68 | 69 | private static bool PlainTypeMatches(this ITypeSymbol target, TypeReference candidate, Stack candidateTypeArgs) { 70 | if (target.MetadataName != candidate.Name) return false; 71 | 72 | // We can't compare with `==`, because the arity of a nested `TypeReference` is the sum 73 | // of the arities of all nesting `TypeReferences`. 74 | if (target.Arity() > candidate.Arity()) { 75 | return false; 76 | } 77 | 78 | if (target is INamedTypeSymbol _target 79 | && _target.IsGenericType 80 | && !_target.AllTypeArgsMatch(candidateTypeArgs)) { 81 | return false; 82 | } 83 | 84 | if (candidate.IsNested) { 85 | return target.IsNested() 86 | && target.ContainingType.Matches(candidate.DeclaringType, candidateTypeArgs); 87 | } else { 88 | return target.Namespace() == candidate.Namespace; 89 | } 90 | } 91 | 92 | private static int Arity(this ITypeSymbol type) => type is INamedTypeSymbol _type ? _type.Arity : 0; 93 | 94 | private static int Arity(this TypeReference type) => type is IGenericInstance _type 95 | ? _type.GenericArguments.Count 96 | : type.GenericParameters.Count; 97 | 98 | private static bool IsNested(this ITypeSymbol type) => type.ContainingType != null; 99 | 100 | private static bool AllTypeArgsMatch(this INamedTypeSymbol target, Stack candidateTypeArgs) { 101 | // Take as many of the candidate type args as the target requires. Using a stack 102 | // ensures we're taking the innermost first. Taken candidates have to be reversed 103 | // so they are in the same order as they were declared in the type. 104 | var _candidateTypeArgs = candidateTypeArgs 105 | .Pop(count: target.TypeArguments.Length) 106 | .Reverse(); 107 | 108 | return target.TypeArguments 109 | .Zip(_candidateTypeArgs, Matches) 110 | .All(typeArgMatched => typeArgMatched); 111 | } 112 | 113 | private static IEnumerable Pop(this Stack s, int count) { 114 | if (s.Count < count) throw new ArgumentOutOfRangeException(nameof(count), count, "Not enough elements."); 115 | return f(); 116 | IEnumerable f() { 117 | for (; count > 0; count--) yield return s.Pop(); 118 | } 119 | } 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /src/CodeAnalysis/CodeAnalysis.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {F98BB94E-CF38-466B-ADFD-9BB26D8493B7} 8 | Library 9 | Properties 10 | Microscope.CodeAnalysis 11 | Microscope.CodeAnalysis 12 | v4.8 13 | 8.0 14 | enable 15 | 512 16 | true 17 | 18 | 19 | true 20 | full 21 | false 22 | bin\Debug\ 23 | DEBUG;TRACE 24 | prompt 25 | 4 26 | 27 | 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 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 | 4.0.0-4.final 66 | 67 | 68 | 4.0.0-4.final 69 | 70 | 71 | 4.0.0-4.final 72 | 73 | 74 | 4.0.0-4.final 75 | 76 | 77 | 0.11.4 78 | 79 | 80 | 81 | 82 | {d6f37eec-cba3-4db2-b44c-5f036c6faa9f} 83 | Shared 84 | 85 | 86 | 87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /src/CodeAnalysis/CollectGeneratedCodeExt.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.CodeAnalysis { 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Runtime.CompilerServices; 8 | 9 | using Microscope.CodeAnalysis.Model; 10 | 11 | using Mono.Cecil; 12 | using Mono.Cecil.Rocks; 13 | 14 | public static class CollectGeneratedCodeExt { 15 | public static IReadOnlyList CollectGeneratedCode(this MethodDefinition method) 16 | => method 17 | .CollectGeneratedMethods(visited: new HashSet()) 18 | .GroupBy(m => m.DeclaringType) 19 | .Select(GeneratedType.From) 20 | .ToArray(); 21 | 22 | public static IReadOnlyList CollectGeneratedCode(this (MethodDefinition? get, MethodDefinition? set) property) { 23 | var visited = new HashSet(); 24 | var generatedByGet = property.get?.CollectGeneratedMethods(visited) ?? Enumerable.Empty(); 25 | var generatedBySet = property.set?.CollectGeneratedMethods(visited) ?? Enumerable.Empty(); 26 | return generatedByGet 27 | .Concat(generatedBySet) 28 | .GroupBy(m => m.DeclaringType) 29 | .Select(GeneratedType.From) 30 | .ToArray(); 31 | } 32 | 33 | public static IEnumerable CollectGeneratedMethods( 34 | this MethodDefinition method, 35 | ISet visited) 36 | => method 37 | .Body? 38 | .Instructions 39 | .Select(instr => instr.Operand) 40 | .OfType() 41 | .Select(TryResolve) 42 | .WhereNotNull() 43 | .Where(m => !m.IsGetter && !m.IsSetter) 44 | .Where(IsCompilerGenerated) 45 | .Where(visited.Add) 46 | .Aggregate( 47 | Enumerable.Empty(), 48 | (ms, m) => ms.Append(m).Concat(m.CollectGeneratedMethods(visited))) 49 | .Concat(method.CollectAsyncStateMachineMethods(visited)) 50 | .Concat(method.CollectIteratorStateMachineMethods(visited)) 51 | ?? Enumerable.Empty(); 52 | 53 | private static IEnumerable CollectAsyncStateMachineMethods( 54 | this MethodDefinition method, 55 | ISet visited) 56 | => method 57 | .TryGetCustomAttribute()? 58 | .GetStateMachineImplementation() 59 | .CollectMethod("MoveNext", visited) 60 | ?? Enumerable.Empty(); 61 | 62 | private static IEnumerable CollectIteratorStateMachineMethods( 63 | this MethodDefinition method, 64 | ISet visited) 65 | => method 66 | .TryGetCustomAttribute()? 67 | .GetStateMachineImplementation() 68 | .CollectMethod("MoveNext", visited) 69 | ?? Enumerable.Empty(); 70 | 71 | private static TypeDefinition GetStateMachineImplementation(this CustomAttribute a) 72 | => (TypeDefinition)a.ConstructorArguments.Single().Value; 73 | 74 | private static IEnumerable CollectMethod( 75 | this TypeDefinition type, 76 | string methodName, 77 | ISet visited) { 78 | var method = type.Methods.Single(m => m.Name == methodName); 79 | return visited.Add(method) 80 | ? method.CollectGeneratedMethods(visited).Prepend(method) 81 | : Enumerable.Empty(); 82 | } 83 | 84 | private static MethodDefinition? TryResolve(MethodReference method) { 85 | try { 86 | return method.Resolve(); 87 | } catch (AssemblyResolutionException) { 88 | return null; 89 | } 90 | } 91 | 92 | private static bool IsCompilerGenerated(MethodDefinition m) 93 | => m.HasCustomAttribute() 94 | || m.DeclaringType.HasCustomAttribute(); 95 | 96 | private static bool HasCustomAttribute(this ICustomAttributeProvider cap) 97 | where T : Attribute 98 | => cap.HasCustomAttributes 99 | && cap.CustomAttributes.Any(a => a.AttributeType.FullName == typeof(T).FullName); 100 | 101 | private static CustomAttribute? TryGetCustomAttribute(this ICustomAttributeProvider cap) 102 | where T : Attribute 103 | => cap.HasCustomAttributes 104 | ? cap.CustomAttributes.SingleOrDefault(a => a.AttributeType.FullName == typeof(T).FullName) 105 | : null; 106 | 107 | /// Filters `null`s and also turns the NRT elements into non-nullable elements. 108 | private static IEnumerable WhereNotNull(this IEnumerable source) 109 | where T : class 110 | => source.Where(x => x != null)!; 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/CodeAnalysis/CompileExt.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.CodeAnalysis { 4 | using System; 5 | using System.IO; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | 9 | using Microscope.Shared; 10 | 11 | using Microsoft.CodeAnalysis; 12 | 13 | using Mono.Cecil; 14 | 15 | public static class CompileExt { 16 | public static async Task Compile( 17 | this Project proj, 18 | Stream peStream, 19 | OptimizationLevel? optLvl, 20 | CancellationToken ct) { 21 | var compilation = await proj 22 | .WithOptimizationLevel(optLvl) 23 | .GetCompilationAsync(ct).Caf() 24 | ?? throw new InvalidOperationException($"Project {proj.FilePath} does not support compilation."); 25 | 26 | var result = compilation.Emit(peStream); 27 | if (!result.Success) return null; 28 | 29 | _ = peStream.Seek(0, SeekOrigin.Begin); 30 | return AssemblyDefinition.ReadAssembly(peStream); 31 | } 32 | 33 | private static Project WithOptimizationLevel(this Project proj, OptimizationLevel? optLvl) { 34 | if (!optLvl.HasValue) return proj; 35 | 36 | var buildCfg = proj.CompilationOptions? 37 | .WithOptimizationLevel(optLvl.Value) 38 | ?? throw new InvalidOperationException($"Failed to set build config {optLvl.Value} on project {proj.FilePath}."); 39 | 40 | return proj.WithCompilationOptions(buildCfg); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/CodeAnalysis/GetCodeLensDataForExt.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.CodeAnalysis { 4 | using Microscope.CodeAnalysis.Model; 5 | using Microscope.Shared; 6 | 7 | using Microsoft.CodeAnalysis; 8 | 9 | using Mono.Cecil; 10 | 11 | using System.Collections.Generic; 12 | using System.Linq; 13 | 14 | public static class GetCodeLensDataForExt { 15 | public static (CodeLensData, DetailsData) GetCodeLensDataFor(this AssemblyDefinition assembly, IMethodSymbol symbol) { 16 | var def = assembly.GetMethodDefinition(symbol); 17 | 18 | var details = DetailsData.ForMethod( 19 | methodInstructions: def.GetInstructions().ToArray(), 20 | compilerGeneratedTypes: def.CollectGeneratedCode()); 21 | 22 | var data = def.ToCodeLensData(); 23 | 24 | return (data, details); 25 | } 26 | 27 | public static (CodeLensData, DetailsData) GetCodeLensDataFor(this AssemblyDefinition assembly, IPropertySymbol symbol) { 28 | var getDef = symbol.GetMethod is null ? null : assembly.GetMethodDefinition(symbol.GetMethod); 29 | var setDef = symbol.SetMethod is null ? null : assembly.GetMethodDefinition(symbol.SetMethod); 30 | 31 | var details = DetailsData.ForProperty( 32 | propertyAccessors: (getDef, setDef).GetInstructions().ToArray(), 33 | compilerGeneratedTypes: (getDef, setDef).CollectGeneratedCode()); 34 | 35 | var data = (getDef, setDef).ToCodeLensData(); 36 | 37 | return (data, details); 38 | } 39 | 40 | private static IEnumerable GetInstructions(this MethodDefinition def) 41 | => def.HasBody ? def.Body.Instructions.Select(InstructionData.From) : Enumerable.Empty(); 42 | 43 | private static IEnumerable GetInstructions(this (MethodDefinition? get, MethodDefinition? set) prop) { 44 | if (prop.get != null) yield return GeneratedMethod.From(prop.get); 45 | if (prop.set != null) yield return GeneratedMethod.From(prop.set); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/CodeAnalysis/GetDocumentExt.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.CodeAnalysis { 4 | using System; 5 | using System.Collections.Immutable; 6 | using System.Linq; 7 | using System.Reflection; 8 | 9 | using Microsoft.CodeAnalysis; 10 | using Microsoft.VisualStudio.LanguageServices; 11 | 12 | public static class GetDocumentExt { 13 | private static readonly FieldInfo projectToGuidMapField = typeof(VisualStudioWorkspace).Assembly 14 | .GetType( 15 | "Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.VisualStudioWorkspaceImpl", 16 | throwOnError: true) 17 | .GetField("_projectToGuidMap", BindingFlags.NonPublic | BindingFlags.Instance); 18 | 19 | private static readonly MethodInfo getDocumentIdInCurrentContextMethod = typeof(Workspace).GetMethod( 20 | "GetDocumentIdInCurrentContext", 21 | BindingFlags.NonPublic | BindingFlags.Instance, 22 | binder: null, 23 | types: new[] { typeof(DocumentId) }, 24 | modifiers: null); 25 | 26 | // Code adapted from Microsoft.VisualStudio.LanguageServices.CodeLens.CodeLensCallbackListener.TryGetDocument() 27 | public static Document GetDocument(this VisualStudioWorkspace workspace, string filePath, Guid projGuid) { 28 | var projectToGuidMap = (ImmutableDictionary)projectToGuidMapField.GetValue(workspace); 29 | var sln = workspace.CurrentSolution; 30 | 31 | var candidateId = sln 32 | .GetDocumentIdsWithFilePath(filePath) 33 | // VS will create multiple `ProjectId`s for projects with multiple target frameworks. 34 | // We simply take the first one we find. 35 | .FirstOrDefault(candidateId => projectToGuidMap.GetValueOrDefault(candidateId.ProjectId) == projGuid) 36 | ?? throw new InvalidOperationException($"File {filePath} (project: {projGuid}) not found in solution {sln.FilePath}."); 37 | 38 | var currentContextId = workspace.GetDocumentIdInCurrentContext(candidateId); 39 | return sln.GetDocument(currentContextId) 40 | ?? throw new InvalidOperationException($"Document {currentContextId} not found in solution {sln.FilePath}."); 41 | } 42 | 43 | public static DocumentId? GetDocumentIdInCurrentContext(this Workspace workspace, DocumentId? documentId) 44 | => (DocumentId?)getDocumentIdInCurrentContextMethod.Invoke(workspace, new[] { documentId }); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/CodeAnalysis/GetMethodDefinitionExt.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.CodeAnalysis { 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | 8 | using Microsoft.CodeAnalysis; 9 | 10 | using Mono.Cecil; 11 | 12 | public static class GetMethodDefinitionExt { 13 | public static MethodDefinition GetMethodDefinition(this AssemblyDefinition assembly, IMethodSymbol methodSymbol) { 14 | var nameParts = methodSymbol.ContainingSymbol.GetFullNameParts(); 15 | var @namespace = nameParts.PopNamespace(); 16 | var typeName = nameParts.PopTypeName(); 17 | var type = assembly.MainModule.GetType(@namespace, typeName) 18 | ?? throw new InvalidOperationException($"Type {@namespace}.{typeName} could not be found in assembly {assembly.FullName}."); 19 | type = nameParts.PopNestedTypes(type); 20 | 21 | var candidates = type.Methods 22 | .Where(m 23 | => methodSymbol.MetadataName == m.Name 24 | && methodSymbol.Parameters.Length == m.Parameters.Count) 25 | .ToArray(); 26 | 27 | return candidates.Length == 1 28 | ? candidates[0] 29 | : candidates 30 | .SingleOrDefault(m => methodSymbol.AllParametersMatch(m)) 31 | ?? throw new InvalidOperationException($"Method {methodSymbol} could not be found in type {type.FullName}."); 32 | } 33 | 34 | private static TypeDefinition PopNestedTypes(this Stack nameParts, TypeDefinition type) { 35 | while (nameParts.Count > 0) { 36 | var nestedTypeName = nameParts.PopTypeName(); 37 | type = type.NestedTypes.SingleOrDefault(t => t.Name == nestedTypeName) 38 | ?? throw new InvalidOperationException($"Type {type.FullName} does not have a nested type named {nestedTypeName}."); 39 | } 40 | 41 | return type; 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/CodeAnalysis/GetSymbolAtExt.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.CodeAnalysis { 4 | using System; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | 8 | using Microscope.Shared; 9 | 10 | using Microsoft.CodeAnalysis; 11 | using Microsoft.CodeAnalysis.Text; 12 | 13 | public static class GetSymbolAtExt { 14 | public static async Task GetSymbolAt(this Document doc, TextSpan span, CancellationToken ct) { 15 | var rootNode = await doc.GetSyntaxRootAsync(ct).Caf() 16 | ?? throw new InvalidOperationException($"Document {doc.Name} does not have a syntax tree."); 17 | var syntaxNode = rootNode.FindNode(span); 18 | 19 | var semanticModel = await doc.GetSemanticModelAsync(ct).Caf() 20 | ?? throw new InvalidOperationException($"Document {doc.Name} does not have a semantic model."); 21 | 22 | return semanticModel.GetDeclaredSymbol(syntaxNode, ct) 23 | ?? throw new InvalidOperationException($"Node is not a symbol declaration: {syntaxNode}."); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/CodeAnalysis/Model/DetailsData.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.CodeAnalysis.Model { 4 | using System.Collections.Generic; 5 | 6 | public readonly struct DetailsData { 7 | public IReadOnlyList? MethodInstructions { get; } 8 | 9 | public IReadOnlyList? PropertyAccessors { get; } 10 | 11 | public IReadOnlyList CompilerGeneratedTypes { get; } 12 | 13 | public bool HasCompilerGeneratedTypes => CompilerGeneratedTypes.Count > 0; 14 | 15 | public bool IsMethod => MethodInstructions != null; 16 | 17 | public bool IsProperty => PropertyAccessors != null; 18 | 19 | public DetailsData( 20 | IReadOnlyList? methodInstructions, 21 | IReadOnlyList? propertyAccessors, 22 | IReadOnlyList compilerGeneratedTypes) { 23 | MethodInstructions = methodInstructions; 24 | PropertyAccessors = propertyAccessors; 25 | CompilerGeneratedTypes = compilerGeneratedTypes; 26 | } 27 | 28 | public static DetailsData ForMethod( 29 | IReadOnlyList methodInstructions, 30 | IReadOnlyList compilerGeneratedTypes) 31 | => new DetailsData(methodInstructions, propertyAccessors: null, compilerGeneratedTypes); 32 | 33 | public static DetailsData ForProperty( 34 | IReadOnlyList propertyAccessors, 35 | IReadOnlyList compilerGeneratedTypes) 36 | => new DetailsData(methodInstructions: null, propertyAccessors, compilerGeneratedTypes); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/CodeAnalysis/Model/GeneratedMethod.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.CodeAnalysis.Model { 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | 8 | using Mono.Cecil; 9 | 10 | public readonly struct GeneratedMethod { 11 | public string Name { get; } 12 | 13 | public string FullName { get; } 14 | 15 | public string ReturnTypeName { get; } 16 | 17 | public string ParameterList { get; } 18 | 19 | public IReadOnlyList Instructions { get; } 20 | 21 | public GeneratedMethod( 22 | string name, 23 | string fullName, 24 | string returnTypeName, 25 | string parameterList, 26 | IReadOnlyList instructions) { 27 | Name = name; 28 | FullName = fullName; 29 | ReturnTypeName = returnTypeName; 30 | ParameterList = parameterList; 31 | Instructions = instructions; 32 | } 33 | 34 | public static GeneratedMethod From(MethodDefinition method) => new GeneratedMethod( 35 | method.Name, 36 | method.FullName, 37 | method.ReturnType.FullName, 38 | GetParameterList(method), 39 | instructions: method.HasBody 40 | ? method.Body.Instructions.Select(InstructionData.From).ToArray() 41 | : Array.Empty()); 42 | 43 | public override string ToString() => Name; 44 | 45 | private static string GetParameterList(MethodDefinition m) { 46 | var parameterListStart = m.FullName.IndexOf('('); 47 | return m.FullName.Substring(parameterListStart); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/CodeAnalysis/Model/GeneratedType.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.CodeAnalysis.Model { 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | 7 | using Mono.Cecil; 8 | 9 | public readonly struct GeneratedType { 10 | public string Name { get; } 11 | 12 | public string FullName { get; } 13 | 14 | public IReadOnlyList Methods { get; } 15 | 16 | public GeneratedType(string name, string fullName, IReadOnlyList methods) { 17 | Name = name; 18 | FullName = fullName; 19 | Methods = methods; 20 | } 21 | 22 | public static GeneratedType From(IGrouping g) => new GeneratedType( 23 | g.Key.Name, 24 | g.Key.FullName, 25 | g.Select(GeneratedMethod.From).ToArray()); 26 | 27 | public override string ToString() => Name; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/CodeAnalysis/Model/InstructionData.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.CodeAnalysis.Model { 4 | using Mono.Cecil.Cil; 5 | 6 | public readonly struct InstructionData { 7 | public string Label { get; } 8 | 9 | public string OpCode { get; } 10 | 11 | public string Operand { get; } 12 | 13 | public string? Documentation { get; } 14 | 15 | public InstructionData(string label, string opCode, string operand, string? documentation) { 16 | Label = label; 17 | OpCode = opCode; 18 | Operand = operand; 19 | Documentation = documentation; 20 | } 21 | 22 | public static InstructionData From(Instruction instr) => new InstructionData( 23 | label: instr.PrintLabel(), 24 | opCode: instr.OpCode.Name, 25 | operand: instr.PrintOperand(), 26 | documentation: instr.OpCode.GetDocumentation()); 27 | 28 | public override string ToString() => OpCode; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/CodeAnalysis/PrintInstructionExt.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.CodeAnalysis { 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | 7 | using Mono.Cecil.Cil; 8 | 9 | public static class PrintInstructionExt { 10 | public static string PrintLabel(this Instruction instr) => $"IL_{instr.Offset:X4}"; 11 | 12 | // Code adapted from Mono.Cecil.Cil.Instruction.ToString(). 13 | public static string PrintOperand(this Instruction instr) { 14 | var operand = instr.Operand; 15 | 16 | if (operand == null) return ""; 17 | 18 | switch (instr.OpCode.OperandType) { 19 | case OperandType.InlineBrTarget: 20 | case OperandType.ShortInlineBrTarget: 21 | return ((Instruction)operand).PrintLabel(); 22 | case OperandType.InlineSwitch: 23 | return ((Instruction[])operand).Select(PrintLabel).Join(", "); 24 | case OperandType.InlineString: 25 | return $"\"{operand}\""; 26 | default: 27 | return operand.ToString(); 28 | } 29 | } 30 | 31 | private static string Join(this IEnumerable strs, string sep) => string.Join(sep, strs); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/CodeAnalysis/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("CodeAnalysis")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("CodeAnalysis")] 13 | [assembly: AssemblyCopyright("Copyright © 2020")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("f98bb94e-cf38-466b-adfd-9bb26d8493b7")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /src/CodeAnalysis/SymbolNameExt.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.CodeAnalysis { 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | using Microsoft.CodeAnalysis; 8 | 9 | public static class SymbolNameExt { 10 | public static Stack GetFullNameParts(this ISymbol symbol) { 11 | var nameParts = new Stack(capacity: 10); 12 | 13 | for (var s = symbol; !s.IsGlobalNamespace(); s = s.ContainingSymbol) { 14 | nameParts.Push(s); 15 | } 16 | 17 | return nameParts; 18 | } 19 | 20 | public static string Namespace(this ISymbol symbol) => symbol.Kind == SymbolKind.TypeParameter 21 | ? "" 22 | : symbol.GetFullNameParts().PopNamespace(); 23 | 24 | public static string PopNamespace(this Stack nameParts) { 25 | if (nameParts.Peek().Kind != SymbolKind.Namespace) return ""; 26 | 27 | var sb = new StringBuilder(nameParts.Pop().Name, capacity: 100); 28 | 29 | while (nameParts.Peek().Kind == SymbolKind.Namespace) { 30 | _ = sb.Append('.').Append(nameParts.Pop().Name); 31 | } 32 | 33 | return sb.ToString(); 34 | } 35 | 36 | public static string PopTypeName(this Stack nameParts) => nameParts.Pop().MetadataName; 37 | 38 | public static bool IsGlobalNamespace(this ISymbol s) => s is INamespaceSymbol ns && ns.IsGlobalNamespace; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/CodeAnalysis/ToCodeLensDataExt.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.CodeAnalysis { 4 | using Microscope.Shared; 5 | 6 | using Mono.Cecil; 7 | using Mono.Cecil.Cil; 8 | using Mono.Collections.Generic; 9 | 10 | using System; 11 | 12 | public static class ToCodeLensDataExt { 13 | public static CodeLensData ToCodeLensData(this MethodDefinition method) { 14 | var instrs = method.Body?.Instructions ?? new Collection(capacity: 0); 15 | var boxOpsCount = 0; 16 | var callvirtOpsCount = 0; 17 | 18 | foreach (var instr in instrs) { 19 | if (instr.OpCode.Code == Code.Box) 20 | boxOpsCount++; 21 | else if (instr.OpCode.Code == Code.Callvirt && instr.Previous.OpCode.Code != Code.Constrained) 22 | callvirtOpsCount++; 23 | } 24 | 25 | return CodeLensData.Success(instrs.Count, boxOpsCount, callvirtOpsCount, method.Body?.CodeSize ?? 0); 26 | } 27 | 28 | public static CodeLensData ToCodeLensData(this (MethodDefinition? get, MethodDefinition? set) property) 29 | => (property.get, property.set) switch { 30 | (null , null ) => throw new InvalidOperationException("Property must have a set or a get method."), 31 | (var get, null ) => get.ToCodeLensData(), 32 | (null , var set) => set.ToCodeLensData(), 33 | (var get, var set) => get.ToCodeLensData().Merge(set.ToCodeLensData()) 34 | }; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/CodeAnalysis/gen-opcode-doc-switch-cases.linq: -------------------------------------------------------------------------------- 1 | 2 | LoxSmoke.DocXml 3 | DocXml.Reflection 4 | LoxSmoke.DocXml 5 | LoxSmoke.DocXml.Reflection 6 | System.Threading.Tasks 7 | System.Reflection.Emit 8 | 9 | 10 | var r = new DocXmlReader(@"C:\Program Files (x86)\Microsoft SDKs\NuGetPackages\System.Reflection.Primitives\4.0.1\ref\netstandard1.0\System.Reflection.Primitives.xml"); 11 | 12 | string QuotedOpCode(FieldInfo f) => $"\"{((OpCode)f.GetValue(null)!).Name}\""; 13 | 14 | typeof(OpCodes) 15 | .GetFields() 16 | .OrderBy(f => f.Name) 17 | .Select(f => $"{QuotedOpCode(f),-16} => \"{r.GetMemberComment(f).Replace("\"", "\\\"")}\",") 18 | .Join("\n") 19 | .Dump(); -------------------------------------------------------------------------------- /src/CodeLensProvider/CodeLensDataPoint.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.CodeLensProvider { 4 | using System; 5 | using System.Linq; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | 9 | using Microscope.Shared; 10 | 11 | using Microsoft.VisualStudio.Language.CodeLens; 12 | using Microsoft.VisualStudio.Language.CodeLens.Remoting; 13 | using Microsoft.VisualStudio.Threading; 14 | 15 | using static Microscope.Shared.Logging; 16 | 17 | public class CodeLensDataPoint : IAsyncCodeLensDataPoint, IDisposable { 18 | private static readonly CodeLensDetailEntryCommand refreshCmdId = new CodeLensDetailEntryCommand { 19 | // Defined in file `src/VSExtension/MicroscopeCommands.vsct`. 20 | CommandSet = new Guid("32872e4d-3d0e-4b26-9ef8-d3a90080429f"), 21 | CommandId = 0x0100 22 | }; 23 | 24 | public readonly Guid id = Guid.NewGuid(); 25 | private readonly ManualResetEventSlim dataLoaded = new ManualResetEventSlim(initialState: false); 26 | private readonly ICodeLensCallbackService callbackService; 27 | private VisualStudioConnectionHandler? visualStudioConnection; 28 | private volatile CodeLensData? data; 29 | 30 | public CodeLensDescriptor Descriptor { get; } 31 | 32 | public event AsyncEventHandler? InvalidatedAsync; 33 | 34 | public CodeLensDataPoint(ICodeLensCallbackService callbackService, CodeLensDescriptor descriptor) { 35 | this.callbackService = callbackService; 36 | Descriptor = descriptor; 37 | } 38 | 39 | public void Dispose() { 40 | visualStudioConnection?.Dispose(); 41 | dataLoaded.Dispose(); 42 | } 43 | 44 | public async Task ConnectToVisualStudio(int vspid) => 45 | visualStudioConnection = await VisualStudioConnectionHandler.Create(owner: this, vspid).Caf(); 46 | 47 | public async Task GetDataAsync(CodeLensDescriptorContext context, CancellationToken ct) { 48 | try { 49 | data = await LoadInstructions(context, ct).Caf(); 50 | dataLoaded.Set(); 51 | 52 | var description = data.IsFailure 53 | ? "- instructions" 54 | : data.InstructionsCount!.Value.Labeled("instruction"); 55 | var tooltip = data.IsFailure 56 | ? data.ErrorMessage! 57 | : $"{data.BoxOpsCount!.Value.Labeled("boxing")}, " 58 | + $"{data.CallvirtOpsCount!.Value.Labeled("unconstrained virtual call")}, " 59 | + $"{data.MemberByteSize!.Value.Labeled("byte")}"; 60 | 61 | return new CodeLensDataPointDescriptor { 62 | Description = description, 63 | TooltipText = tooltip, 64 | ImageId = null, 65 | IntValue = data.InstructionsCount 66 | }; 67 | } catch (Exception ex) { 68 | LogCL(ex); 69 | throw; 70 | } 71 | } 72 | 73 | public async Task GetDetailsAsync(CodeLensDescriptorContext context, CancellationToken ct) { 74 | try { 75 | // When opening the details pane, the data point is re-created leaving `data` uninitialized. VS will 76 | // then call `GetDataAsync()` and `GetDetailsAsync()` concurrently. 77 | if (!dataLoaded.Wait(timeout: TimeSpan.FromSeconds(.5), ct)) 78 | data = await LoadInstructions(context, ct).Caf(); 79 | 80 | if (data!.IsFailure) 81 | throw new InvalidOperationException($"Getting CodeLens details for {context.FullName()} failed: {data.ErrorMessage}"); 82 | 83 | return new CodeLensDetailsDescriptor { 84 | // Since it's impossible to figure out how to use [DetailsTemplateName], we'll 85 | // just use the default grid template without any headers/entries and add 86 | // what we want to transmit to the custom data. 87 | Headers = Enumerable.Empty(), 88 | Entries = Enumerable.Empty(), 89 | CustomData = new[] { new CodeLensDetails(id) }, 90 | PaneNavigationCommands = new[] { 91 | new CodeLensDetailPaneCommand { 92 | CommandDisplayName = "Refresh", 93 | CommandId = refreshCmdId, 94 | CommandArgs = new[] { (object)id } 95 | } 96 | } 97 | }; 98 | } catch (Exception ex) { 99 | LogCL(ex); 100 | throw; 101 | } 102 | } 103 | 104 | // Called from VS via JSON RPC. 105 | public void Refresh() => _ = InvalidatedAsync?.InvokeAsync(this, EventArgs.Empty); 106 | 107 | private async Task LoadInstructions(CodeLensDescriptorContext ctx, CancellationToken ct) 108 | => await callbackService 109 | .InvokeAsync( 110 | this, 111 | nameof(IInstructionsProvider.LoadInstructions), 112 | new object[] { 113 | id, 114 | Descriptor.ProjectGuid, 115 | Descriptor.FilePath, 116 | ctx.ApplicableSpan != null 117 | ? ctx.ApplicableSpan.Value.Start 118 | : throw new InvalidOperationException($"No ApplicableSpan given for {ctx.FullName()}."), 119 | ctx.ApplicableSpan!.Value.Length 120 | }, 121 | ct).Caf(); 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /src/CodeLensProvider/CodeLensProvider.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.CodeLensProvider { 4 | using System; 5 | using System.ComponentModel.Composition; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | 9 | using Microscope.Shared; 10 | 11 | using Microsoft.VisualStudio.Language.CodeLens; 12 | using Microsoft.VisualStudio.Language.CodeLens.Remoting; 13 | using Microsoft.VisualStudio.Language.Intellisense; 14 | using Microsoft.VisualStudio.Utilities; 15 | 16 | using static Microscope.Shared.Logging; 17 | 18 | [Export(typeof(IAsyncCodeLensDataPointProvider))] 19 | [Name(ProviderId)] 20 | [LocalizedName(typeof(Resources), "Name")] 21 | [ContentType("CSharp")] 22 | [ContentType("Basic")] 23 | [Priority(210)] // sort after "references" CodeLens (200) 24 | public class CodeLensProvider : IAsyncCodeLensDataPointProvider { 25 | public const string ProviderId = "ILInstructions"; 26 | private readonly Lazy callbackService; 27 | 28 | [ImportingConstructor] 29 | public CodeLensProvider(Lazy callbackService) { 30 | this.callbackService = callbackService; 31 | LogCL(); // logs the PID of the out-of-process CodeLens engine 32 | } 33 | 34 | public async Task CanCreateDataPointAsync( 35 | CodeLensDescriptor descriptor, 36 | CodeLensDescriptorContext context, 37 | CancellationToken ct) 38 | => (descriptor.Kind is CodeElementKinds.Method || descriptor.Kind is CodeElementKinds.Property) 39 | && await callbackService.Value 40 | .InvokeAsync(this, nameof(IInstructionsProvider.IsMicroscopeEnabled)).Caf(); 41 | 42 | public async Task CreateDataPointAsync( 43 | CodeLensDescriptor descriptor, 44 | CodeLensDescriptorContext context, 45 | CancellationToken ct) { 46 | try { 47 | var dp = new CodeLensDataPoint(callbackService.Value, descriptor); 48 | 49 | var vspid = await callbackService.Value 50 | .InvokeAsync(this, nameof(IInstructionsProvider.GetVisualStudioPid)).Caf(); 51 | await dp.ConnectToVisualStudio(vspid).Caf(); 52 | 53 | return dp; 54 | } catch (Exception ex) { 55 | LogCL(ex); 56 | throw; 57 | } 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/CodeLensProvider/CodeLensProvider.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {FA8F7552-7E27-425B-9B81-09E0789179A3} 8 | Library 9 | Properties 10 | Microscope.CodeLensProvider 11 | Microscope.CodeLensProvider 12 | v4.8 13 | 8.0 14 | enable 15 | 512 16 | true 17 | 18 | 19 | true 20 | full 21 | false 22 | bin\Debug\ 23 | DEBUG;TRACE 24 | prompt 25 | 4 26 | 27 | 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | True 42 | True 43 | Resources.resx 44 | 45 | 46 | 47 | 48 | 49 | 50 | ResXFileCodeGenerator 51 | Resources.Designer.cs 52 | 53 | 54 | 55 | 56 | {D6F37EEC-CBA3-4DB2-B44C-5F036C6FAA9F} 57 | Shared 58 | 59 | 60 | 61 | 62 | 17.0.391-preview-g5e248c9073 63 | 64 | 65 | 16.10.10 66 | runtime; build; native; contentfiles; analyzers; buildtransitive 67 | all 68 | 69 | 70 | 2.8.28 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /src/CodeLensProvider/GetExt.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.CodeLensProvider { 4 | using Microsoft.VisualStudio.Language.CodeLens; 5 | 6 | public static class GetExt { 7 | public static T Get(this CodeLensDescriptorContext ctx, string key) => (T)ctx.Properties[key]; 8 | 9 | public static string FullName(this CodeLensDescriptorContext ctx) => ctx.Get("FullyQualifiedName"); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/CodeLensProvider/LabeledExt.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.CodeLensProvider { 4 | public static class LabeledExt { 5 | public static string Labeled(this int n, string singular, string? plural = null) => 6 | (n, plural) switch { 7 | (1, _) => $"{n} {singular}", 8 | (_, null) => $"{n} {singular}s", 9 | (_, _) => $"{n} {plural}" 10 | }; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/CodeLensProvider/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | [assembly: AssemblyTitle("Microscope.CodeLensProvider")] 5 | [assembly: AssemblyDescription("Support library for the microscope Visual Studio Extension.")] 6 | [assembly: AssemblyConfiguration("")] 7 | [assembly: AssemblyCompany("Robert Hofmann")] 8 | [assembly: AssemblyProduct("microscope")] 9 | [assembly: AssemblyCopyright("Robert Hofmann")] 10 | [assembly: AssemblyTrademark("")] 11 | [assembly: AssemblyCulture("")] 12 | [assembly: ComVisible(false)] 13 | [assembly: Guid("fa8f7552-7e27-425b-9b81-09e0789179a3")] 14 | [assembly: AssemblyVersion("0.0.0.0")] 15 | [assembly: AssemblyFileVersion("0.0.0.0")] 16 | [assembly: AssemblyInformationalVersion("0.0.0.0")] 17 | -------------------------------------------------------------------------------- /src/CodeLensProvider/Resources.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace Microscope.CodeLensProvider { 12 | using System; 13 | 14 | 15 | /// 16 | /// A strongly-typed resource class, for looking up localized strings, etc. 17 | /// 18 | // This class was auto-generated by the StronglyTypedResourceBuilder 19 | // class via a tool like ResGen or Visual Studio. 20 | // To add or remove a member, edit your .ResX file then rerun ResGen 21 | // with the /str option, or rebuild your VS project. 22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] 23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 25 | internal class Resources { 26 | 27 | private static global::System.Resources.ResourceManager resourceMan; 28 | 29 | private static global::System.Globalization.CultureInfo resourceCulture; 30 | 31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] 32 | internal Resources() { 33 | } 34 | 35 | /// 36 | /// Returns the cached ResourceManager instance used by this class. 37 | /// 38 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 39 | internal static global::System.Resources.ResourceManager ResourceManager { 40 | get { 41 | if (object.ReferenceEquals(resourceMan, null)) { 42 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microscope.CodeLensProvider.Resources", typeof(Resources).Assembly); 43 | resourceMan = temp; 44 | } 45 | return resourceMan; 46 | } 47 | } 48 | 49 | /// 50 | /// Overrides the current thread's CurrentUICulture property for all 51 | /// resource lookups using this strongly typed resource class. 52 | /// 53 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 54 | internal static global::System.Globalization.CultureInfo Culture { 55 | get { 56 | return resourceCulture; 57 | } 58 | set { 59 | resourceCulture = value; 60 | } 61 | } 62 | 63 | /// 64 | /// Looks up a localized string similar to instructions. 65 | /// 66 | internal static string Name { 67 | get { 68 | return ResourceManager.GetString("Name", resourceCulture); 69 | } 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/CodeLensProvider/Resources.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | 121 | instructions 122 | 123 | -------------------------------------------------------------------------------- /src/CodeLensProvider/VisualStudioConnectionHandler.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.CodeLensProvider { 4 | using System; 5 | using System.IO.Pipes; 6 | using System.Threading.Tasks; 7 | 8 | using Microscope.Shared; 9 | 10 | using StreamJsonRpc; 11 | 12 | public class VisualStudioConnectionHandler : IRemoteCodeLens, IDisposable { 13 | private readonly CodeLensDataPoint owner; 14 | private readonly NamedPipeClientStream stream; 15 | private JsonRpc? rpc; 16 | 17 | public async static Task Create(CodeLensDataPoint owner, int vspid) { 18 | var handler = new VisualStudioConnectionHandler(owner, vspid); 19 | await handler.Connect().Caf(); 20 | return handler; 21 | } 22 | 23 | public VisualStudioConnectionHandler(CodeLensDataPoint owner, int vspid) { 24 | this.owner = owner; 25 | stream = new NamedPipeClientStream( 26 | serverName: ".", 27 | PipeName.Get(vspid), 28 | PipeDirection.InOut, 29 | PipeOptions.Asynchronous); 30 | } 31 | 32 | public void Dispose() => stream.Dispose(); 33 | 34 | public async Task Connect() { 35 | await stream.ConnectAsync().Caf(); 36 | rpc = JsonRpc.Attach(stream, this); 37 | await rpc.InvokeAsync(nameof(IRemoteVisualStudio.RegisterCodeLensDataPoint), owner.id).Caf(); 38 | } 39 | 40 | public void Refresh() => owner.Refresh(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/Shared/CodeLensData.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.Shared { 4 | public class CodeLensData { 5 | public int? InstructionsCount { get; set; } 6 | public int? BoxOpsCount { get; set; } 7 | public int? CallvirtOpsCount { get; set; } 8 | public int? MemberByteSize { get; set; } 9 | public string? ErrorMessage { get; set; } 10 | 11 | public bool IsFailure => ErrorMessage != null; 12 | 13 | public CodeLensData(int? instructionsCount, int? boxOpsCount, int? callvirtOpsCount, int? memberByteSize, string? errorMessage) 14 | { 15 | InstructionsCount = instructionsCount; 16 | BoxOpsCount = boxOpsCount; 17 | CallvirtOpsCount = callvirtOpsCount; 18 | MemberByteSize = memberByteSize; 19 | ErrorMessage = errorMessage; 20 | } 21 | 22 | public static CodeLensData Success(int instructionsCount, int boxOpsCount, int callvirtOpsCount, int memberByteSize) 23 | => new CodeLensData(instructionsCount, boxOpsCount, callvirtOpsCount, memberByteSize, null); 24 | 25 | public static CodeLensData Failure(string message) => new CodeLensData(null, null, null, null, message); 26 | 27 | public static CodeLensData BuildError() => Failure("Cannot retrieve instructions due to build errors."); 28 | 29 | public CodeLensData Merge(CodeLensData other) => (IsFailure, other.IsFailure) switch { 30 | (true , _ ) => this, 31 | (false, true ) => other, 32 | (false, false) => Success( 33 | InstructionsCount!.Value + other.InstructionsCount!.Value, 34 | BoxOpsCount!.Value + other.BoxOpsCount!.Value, 35 | CallvirtOpsCount!.Value + other.CallvirtOpsCount!.Value, 36 | MemberByteSize!.Value + other.MemberByteSize!.Value) 37 | }; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/Shared/CodeLensDetails.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.Shared { 4 | using System; 5 | 6 | // Only holds the ID of the `CodeLensDataPoint` for which the details have been requested. The 7 | // actual instructions to display are stored in the VS process and can be accessed using the ID. 8 | public class CodeLensDetails { 9 | public Guid DataPointId { get; set; } 10 | public CodeLensDetails(Guid dataPointId) => DataPointId = dataPointId; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/Shared/ConfigureAwaitAlias.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.Shared { 4 | using System.Runtime.CompilerServices; 5 | using System.Threading.Tasks; 6 | 7 | public static class ConfigureAwaitAlias { 8 | /// Alias for `ConfigureAwait(false)`. 9 | public static ConfiguredTaskAwaitable Caf(this Task t) => t.ConfigureAwait(false); 10 | 11 | /// Alias for `ConfigureAwait(false)`. 12 | public static ConfiguredTaskAwaitable Caf(this Task t) => t.ConfigureAwait(false); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Shared/IInstructionsProvider.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.Shared { 4 | using System; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | 8 | public interface IInstructionsProvider { 9 | Task IsMicroscopeEnabled(); 10 | 11 | int GetVisualStudioPid(); 12 | 13 | Task LoadInstructions(Guid dataPointId, Guid projGuid, string filePath, int textStart, int textLen, CancellationToken ct); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Shared/Logging.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.Shared { 4 | using System; 5 | using System.Diagnostics; 6 | using System.IO; 7 | using System.Runtime.CompilerServices; 8 | using System.Threading; 9 | 10 | public static class Logging 11 | { 12 | private static readonly object @lock = new object(); 13 | 14 | // Logs go to: C:\Users\\AppData\Local\Temp\microscope.*.log 15 | // We're using one log file for each process to prevent concurrent file access. 16 | private static readonly string vsLogFile = $"{Path.GetTempPath()}/microscope.vs.log"; 17 | private static readonly string clLogFile = $"{Path.GetTempPath()}/microscope.codelens.log"; 18 | 19 | [Conditional("DEBUG")] 20 | public static void LogVS( 21 | object? data = null, 22 | [CallerFilePath] string? file = null, 23 | [CallerMemberName] string? method = null) 24 | => Log(vsLogFile, file!, method!, data); 25 | 26 | [Conditional("DEBUG")] 27 | public static void LogCL( 28 | object? data = null, 29 | [CallerFilePath] string? file = null, 30 | [CallerMemberName] string? method = null) 31 | => Log(clLogFile, file!, method!, data); 32 | 33 | public static void Log( 34 | string logFile, 35 | string callingFile, 36 | string callingMethod, 37 | object? data = null) { 38 | lock (@lock) { 39 | File.AppendAllText( 40 | logFile, 41 | $"{DateTime.Now:HH:mm:ss.fff} " 42 | + $"{Process.GetCurrentProcess().Id,5} " 43 | + $"{Thread.CurrentThread.ManagedThreadId,3} " 44 | + $"{Path.GetFileNameWithoutExtension(callingFile)}.{callingMethod}()" 45 | + $"{(data == null ? "" : $": {data}")}\n"); 46 | } 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/Shared/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | [assembly: AssemblyTitle("Microscope.Shared")] 5 | [assembly: AssemblyDescription("Support library for the microscope Visual Studio Extension.")] 6 | [assembly: AssemblyConfiguration("")] 7 | [assembly: AssemblyCompany("Robert Hofmann")] 8 | [assembly: AssemblyProduct("microscope")] 9 | [assembly: AssemblyCopyright("Robert Hofmann")] 10 | [assembly: AssemblyTrademark("")] 11 | [assembly: AssemblyCulture("")] 12 | [assembly: ComVisible(false)] 13 | [assembly: Guid("d6f37eec-cba3-4db2-b44c-5f036c6faa9f")] 14 | [assembly: AssemblyVersion("0.0.0.0")] 15 | [assembly: AssemblyFileVersion("0.0.0.0")] 16 | [assembly: AssemblyInformationalVersion("0.0.0.0")] 17 | -------------------------------------------------------------------------------- /src/Shared/RemoteConnection.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.Shared { 4 | using System; 5 | 6 | public static class PipeName { 7 | // Pipe needs to be scoped by PID so multiple VS instances don't compete for connecting CodeLenses. 8 | public static string Get(int pid) => $@"microscope\{pid}"; 9 | } 10 | 11 | public interface IRemoteCodeLens { 12 | void Refresh(); 13 | } 14 | 15 | public interface IRemoteVisualStudio { 16 | void RegisterCodeLensDataPoint(Guid id); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Shared/Shared.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {D6F37EEC-CBA3-4DB2-B44C-5F036C6FAA9F} 8 | Library 9 | Properties 10 | Microscope.Shared 11 | Microscope.Shared 12 | v4.8 13 | 8.0 14 | enable 15 | 512 16 | true 17 | 18 | 19 | true 20 | full 21 | false 22 | bin\Debug\ 23 | DEBUG;TRACE 24 | prompt 25 | 4 26 | 27 | 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | false 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /src/VSExtension/CodeLensConnectionHandler.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.VSExtension { 4 | using System; 5 | using System.Diagnostics; 6 | using System.IO.Pipes; 7 | using System.Linq; 8 | using System.Threading.Tasks; 9 | 10 | using Microscope.CodeAnalysis.Model; 11 | using Microscope.Shared; 12 | 13 | using Mono.Cecil.Cil; 14 | using Mono.Collections.Generic; 15 | 16 | using StreamJsonRpc; 17 | 18 | using static Microscope.Shared.Logging; 19 | 20 | using CodeLensConnections = System.Collections.Concurrent.ConcurrentDictionary; 21 | using CodeLensDetails = System.Collections.Concurrent.ConcurrentDictionary; 22 | 23 | public class CodeLensConnectionHandler : IRemoteVisualStudio, IDisposable { 24 | private static readonly CodeLensConnections connections = new CodeLensConnections(); 25 | private static readonly CodeLensDetails detailsData = new CodeLensDetails(); 26 | 27 | private JsonRpc? rpc; 28 | private Guid? dataPointId; 29 | 30 | public static async Task AcceptCodeLensConnections() { 31 | try { 32 | while (true) { 33 | var stream = new NamedPipeServerStream( 34 | PipeName.Get(Process.GetCurrentProcess().Id), 35 | PipeDirection.InOut, 36 | NamedPipeServerStream.MaxAllowedServerInstances, 37 | PipeTransmissionMode.Byte, 38 | PipeOptions.Asynchronous); 39 | await stream.WaitForConnectionAsync().Caf(); 40 | _ = HandleConnection(stream); 41 | } 42 | } catch (Exception ex) { 43 | LogVS(ex); 44 | throw; 45 | } 46 | 47 | static async Task HandleConnection(NamedPipeServerStream stream) { 48 | try { 49 | var handler = new CodeLensConnectionHandler(); 50 | var rpc = JsonRpc.Attach(stream, handler); 51 | handler.rpc = rpc; 52 | await rpc.Completion; 53 | handler.Dispose(); 54 | stream.Dispose(); 55 | } catch (Exception ex) { 56 | LogVS(ex); 57 | } 58 | } 59 | } 60 | 61 | public void Dispose() { 62 | if (dataPointId.HasValue) { 63 | _ = connections.TryRemove(dataPointId.Value, out var _); 64 | _ = detailsData.TryRemove(dataPointId.Value, out var _); 65 | } 66 | } 67 | 68 | // Called from each CodeLensDataPoint via JSON RPC. 69 | public void RegisterCodeLensDataPoint(Guid id) { 70 | dataPointId = id; 71 | connections[id] = this; 72 | } 73 | 74 | public static void StoreDetailsData(Guid id, DetailsData details) => detailsData[id] = details; 75 | 76 | public static DetailsData GetDetailsData(Guid id) => detailsData[id]; 77 | 78 | public static async Task RefreshCodeLensDataPoint(Guid id) { 79 | if (!connections.TryGetValue(id, out var conn)) 80 | throw new InvalidOperationException($"CodeLens data point {id} was not registered."); 81 | 82 | Debug.Assert(conn.rpc != null); 83 | await conn.rpc!.InvokeAsync(nameof(IRemoteCodeLens.Refresh)).Caf(); 84 | } 85 | 86 | public static async Task RefreshAllCodeLensDataPoints() 87 | => await Task.WhenAll(connections.Keys.Select(RefreshCodeLensDataPoint)).Caf(); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/VSExtension/InstructionsProvider.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.VSExtension { 4 | using System; 5 | using System.ComponentModel.Composition; 6 | using System.Diagnostics; 7 | using System.IO; 8 | using System.Threading; 9 | using System.Threading.Tasks; 10 | 11 | using Microscope.CodeAnalysis; 12 | using Microscope.Shared; 13 | using Microscope.VSExtension.Options; 14 | 15 | using Microsoft.CodeAnalysis; 16 | using Microsoft.CodeAnalysis.Text; 17 | using Microsoft.VisualStudio.Language.CodeLens; 18 | using Microsoft.VisualStudio.LanguageServices; 19 | using Microsoft.VisualStudio.Utilities; 20 | 21 | using static Microscope.Shared.Logging; 22 | 23 | [Export(typeof(ICodeLensCallbackListener))] 24 | [ContentType("CSharp")] 25 | [ContentType("Basic")] 26 | public class InstructionsProvider : ICodeLensCallbackListener, IInstructionsProvider { 27 | private readonly VisualStudioWorkspace workspace; 28 | 29 | [ImportingConstructor] 30 | public InstructionsProvider(VisualStudioWorkspace workspace) => this.workspace = workspace; 31 | 32 | public async Task IsMicroscopeEnabled() { 33 | var opts = await GeneralOptions.GetLiveInstanceAsync().Caf(); 34 | return opts.Enabled; 35 | } 36 | 37 | public int GetVisualStudioPid() => Process.GetCurrentProcess().Id; 38 | 39 | public async Task LoadInstructions( 40 | Guid dataPointId, 41 | Guid projGuid, 42 | string filePath, 43 | int textStart, 44 | int textLen, 45 | CancellationToken ct) { 46 | try { 47 | var document = workspace.GetDocument(filePath, projGuid); 48 | var symbol = await document.GetSymbolAt(new TextSpan(textStart, textLen), ct).Caf(); 49 | 50 | using var peStream = new MemoryStream(); 51 | using var assembly = await document.Project.Compile(peStream, await GetOptimizationLvl().Caf(), ct).Caf(); 52 | if (assembly is null) return CodeLensData.BuildError(); 53 | 54 | var (data, details) = symbol switch { 55 | IMethodSymbol m => assembly.GetCodeLensDataFor(m), 56 | IPropertySymbol p => assembly.GetCodeLensDataFor(p), 57 | _ => throw new InvalidOperationException($"Symbol {symbol} is not a method or property.") 58 | }; 59 | 60 | CodeLensConnectionHandler.StoreDetailsData(dataPointId, details); 61 | 62 | return data; 63 | } catch (Exception ex) { 64 | LogVS(ex); 65 | return CodeLensData.Failure(ex.ToString()); 66 | } 67 | } 68 | 69 | private async Task GetOptimizationLvl() { 70 | var opts = await GeneralOptions.GetLiveInstanceAsync().Caf(); 71 | return opts.BuildConfig switch { 72 | BuildConfig.Debug => OptimizationLevel.Debug, 73 | BuildConfig.Release => OptimizationLevel.Release, 74 | _ => null 75 | }; 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/VSExtension/MicroscopeCommands.cs: -------------------------------------------------------------------------------- 1 | // ------------------------------------------------------------------------------ 2 | // 3 | // This file was generated by VSIX Synchronizer 4 | // 5 | // ------------------------------------------------------------------------------ 6 | namespace Microscope.VSExtension 7 | { 8 | using System; 9 | 10 | /// 11 | /// Helper class that exposes all GUIDs used across VS Package. 12 | /// 13 | internal sealed partial class PackageGuids 14 | { 15 | public const string PackageIdString = "b798b46c-201a-470c-9e3e-fa0abb23dfa7"; 16 | public static Guid PackageId = new Guid(PackageIdString); 17 | 18 | public const string CmdSetIdString = "32872e4d-3d0e-4b26-9ef8-d3a90080429f"; 19 | public static Guid CmdSetId = new Guid(CmdSetIdString); 20 | } 21 | /// 22 | /// Helper class that encapsulates all CommandIDs uses across VS Package. 23 | /// 24 | internal sealed partial class PackageIds 25 | { 26 | public const int RefreshCommandId = 0x0100; 27 | } 28 | } -------------------------------------------------------------------------------- /src/VSExtension/MicroscopeCommands.vsct: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/VSExtension/MicroscopePackage.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.VSExtension { 4 | using System; 5 | using System.Runtime.InteropServices; 6 | using System.Threading; 7 | 8 | using Microscope.Shared; 9 | using Microscope.VSExtension.Options; 10 | 11 | using Microsoft.VisualStudio.Shell; 12 | using Microsoft.VisualStudio.Shell.Interop; 13 | 14 | using static Microscope.Shared.Logging; 15 | 16 | using Task = System.Threading.Tasks.Task; 17 | 18 | [PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)] 19 | [InstalledProductRegistration(Vsix.Name, Vsix.Description, Vsix.Version)] 20 | [Guid(PackageGuids.PackageIdString)] 21 | [ProvideMenuResource("Menus.ctmenu", 1)] 22 | [ProvideOptionPage(typeof(DialogPageProvider.General), "microscope", "General", 0, 0, true , new string[] { "instructions", "CIL", "MSIL", "intermediate language", "CodeLens" })] 23 | [ProvideProfile(typeof(DialogPageProvider.General), "microscope", Vsix.Name, 0, 0, true)] 24 | [ProvideAutoLoad(UIContextGuids80.SolutionExists, PackageAutoLoadFlags.BackgroundLoad)] 25 | public sealed class MicroscopePackage : AsyncPackage { 26 | protected override async Task InitializeAsync(CancellationToken ct, IProgress progress) { 27 | try { 28 | await base.InitializeAsync(ct, progress); 29 | await JoinableTaskFactory.SwitchToMainThreadAsync(ct); 30 | _ = CodeLensConnectionHandler.AcceptCodeLensConnections(); 31 | await RefreshCommand.Initialize(this, CodeLensConnectionHandler.RefreshCodeLensDataPoint).Caf(); 32 | } catch (Exception ex) { 33 | LogVS(ex); 34 | throw; 35 | } 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/VSExtension/Options/BaseOptionModel.cs: -------------------------------------------------------------------------------- 1 | // Code taken from https://github.com/microsoft/VSSDK-Extensibility-Samples/blob/master/Options/src/Options/BaseOptionModel.cs 2 | 3 | #pragma warning disable IDE0007 // Use implicit type 4 | #pragma warning disable IDE0022 // Use expression body for methods 5 | #pragma warning disable IDE0044 // Add readonly modifier 6 | #pragma warning disable IDE0063 // Use simple 'using' statement 7 | #pragma warning disable RCS1036 // Remove redundant empty line. 8 | #pragma warning disable RCS1090 // Call 'ConfigureAwait(false)'. 9 | #pragma warning disable RCS1169 // Make field read-only. 10 | #pragma warning disable VSTHRD102 // Implement internal logic asynchronously 11 | #pragma warning disable VSTHRD104 // Offer async methods 12 | 13 | namespace Microscope.VSExtension.Options { 14 | using System; 15 | using System.Collections.Generic; 16 | using System.IO; 17 | using System.Linq; 18 | using System.Reflection; 19 | using System.Runtime.Serialization.Formatters.Binary; 20 | using System.Threading.Tasks; 21 | 22 | using Microsoft; 23 | using Microsoft.VisualStudio.Settings; 24 | using Microsoft.VisualStudio.Shell; 25 | using Microsoft.VisualStudio.Shell.Interop; 26 | using Microsoft.VisualStudio.Shell.Settings; 27 | using Microsoft.VisualStudio.Threading; 28 | 29 | using Task = System.Threading.Tasks.Task; 30 | 31 | /// 32 | /// A base class for specifying options 33 | /// 34 | public abstract class BaseOptionModel where T : BaseOptionModel, new() { 35 | private static AsyncLazy liveModel = new AsyncLazy(CreateAsync, ThreadHelper.JoinableTaskFactory); 36 | private static AsyncLazy settingsManager = new AsyncLazy(GetSettingsManagerAsync, ThreadHelper.JoinableTaskFactory); 37 | private static Assembly myAssembly = typeof(BaseOptionModel).Assembly; 38 | 39 | static BaseOptionModel() { 40 | // Dirty hack: BinaryFormatter is unable to resolve the assembly for the 41 | // Microscope.VSExtension.Options.BuildConfig enum, even though it's in the 42 | // same assembly that does the deserialization... 43 | AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler((object _, ResolveEventArgs args) => args.Name == myAssembly.FullName ? myAssembly : null); 44 | } 45 | 46 | protected BaseOptionModel() { } 47 | 48 | /// 49 | /// A singleton instance of the options. MUST be called from UI thread only. 50 | /// 51 | /// 52 | /// Call instead if on a background thread or in an async context on the main thread. 53 | /// 54 | public static T Instance { 55 | get { 56 | ThreadHelper.ThrowIfNotOnUIThread(); 57 | 58 | #pragma warning disable VSTHRD104 // Offer async methods 59 | return ThreadHelper.JoinableTaskFactory.Run(GetLiveInstanceAsync); 60 | #pragma warning restore VSTHRD104 // Offer async methods 61 | } 62 | } 63 | 64 | /// 65 | /// Get the singleton instance of the options. Thread safe. 66 | /// 67 | public static Task GetLiveInstanceAsync() => liveModel.GetValueAsync(); 68 | 69 | /// 70 | /// Creates a new instance of the options class and loads the values from the store. For internal use only 71 | /// 72 | /// 73 | public static async Task CreateAsync() { 74 | var instance = new T(); 75 | await instance.LoadAsync(); 76 | return instance; 77 | } 78 | 79 | /// 80 | /// The name of the options collection as stored in the registry. 81 | /// 82 | protected virtual string CollectionName { get; } = typeof(T).FullName; 83 | 84 | /// 85 | /// Hydrates the properties from the registry. 86 | /// 87 | public virtual void Load() { 88 | ThreadHelper.JoinableTaskFactory.Run(LoadAsync); 89 | } 90 | 91 | /// 92 | /// Hydrates the properties from the registry asyncronously. 93 | /// 94 | public virtual async Task LoadAsync() { 95 | ShellSettingsManager manager = await settingsManager.GetValueAsync(); 96 | SettingsStore settingsStore = manager.GetReadOnlySettingsStore(SettingsScope.UserSettings); 97 | 98 | if (!settingsStore.CollectionExists(CollectionName)) { 99 | return; 100 | } 101 | 102 | foreach (PropertyInfo property in GetOptionProperties()) { 103 | try { 104 | string serializedProp = settingsStore.GetString(CollectionName, property.Name); 105 | object value = DeserializeValue(serializedProp, property.PropertyType); 106 | property.SetValue(this, value); 107 | } catch (Exception ex) { 108 | System.Diagnostics.Debug.Write(ex); 109 | } 110 | } 111 | } 112 | 113 | /// 114 | /// Saves the properties to the registry. 115 | /// 116 | public virtual void Save() { 117 | ThreadHelper.JoinableTaskFactory.Run(SaveAsync); 118 | } 119 | 120 | /// 121 | /// Saves the properties to the registry asyncronously. 122 | /// 123 | public virtual async Task SaveAsync() { 124 | ShellSettingsManager manager = await settingsManager.GetValueAsync(); 125 | WritableSettingsStore settingsStore = manager.GetWritableSettingsStore(SettingsScope.UserSettings); 126 | 127 | if (!settingsStore.CollectionExists(CollectionName)) { 128 | settingsStore.CreateCollection(CollectionName); 129 | } 130 | 131 | foreach (PropertyInfo property in GetOptionProperties()) { 132 | string output = SerializeValue(property.GetValue(this)); 133 | settingsStore.SetString(CollectionName, property.Name, output); 134 | } 135 | 136 | T liveModel = await GetLiveInstanceAsync(); 137 | 138 | if (this != liveModel) { 139 | await liveModel.LoadAsync(); 140 | } 141 | } 142 | 143 | /// 144 | /// Serializes an object value to a string using the binary serializer. 145 | /// 146 | protected virtual string SerializeValue(object value) { 147 | using (var stream = new MemoryStream()) { 148 | var formatter = new BinaryFormatter(); 149 | formatter.Serialize(stream, value); 150 | stream.Flush(); 151 | return Convert.ToBase64String(stream.ToArray()); 152 | } 153 | } 154 | 155 | /// 156 | /// Deserializes a string to an object using the binary serializer. 157 | /// 158 | protected virtual object DeserializeValue(string value, Type type) { 159 | byte[] b = Convert.FromBase64String(value); 160 | 161 | using (var stream = new MemoryStream(b)) { 162 | var formatter = new BinaryFormatter(); 163 | return formatter.Deserialize(stream); 164 | } 165 | } 166 | 167 | private static async Task GetSettingsManagerAsync() { 168 | #pragma warning disable VSTHRD010 169 | // False-positive in Threading Analyzers. Bug tracked here https://github.com/Microsoft/vs-threading/issues/230 170 | var svc = await AsyncServiceProvider.GlobalProvider.GetServiceAsync(typeof(SVsSettingsManager)) as IVsSettingsManager; 171 | #pragma warning restore VSTHRD010 172 | 173 | Assumes.Present(svc); 174 | 175 | return new ShellSettingsManager(svc); 176 | } 177 | 178 | private IEnumerable GetOptionProperties() { 179 | return GetType() 180 | .GetProperties() 181 | .Where(p => p.PropertyType.IsSerializable && p.PropertyType.IsPublic); 182 | } 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /src/VSExtension/Options/BaseOptionPage.cs: -------------------------------------------------------------------------------- 1 | // Code taken from https://github.com/microsoft/VSSDK-Extensibility-Samples/blob/master/Options/src/Options/BaseOptionPage.cs 2 | 3 | #pragma warning disable IDE0021 // Use expression body for constructors 4 | #pragma warning disable IDE0022 // Use expression body for methods 5 | #pragma warning disable IDE0044 // Add readonly modifier 6 | #pragma warning disable RCS1169 // Make field read-only. 7 | #pragma warning disable VSTHRD102 // Implement internal logic asynchronously 8 | 9 | namespace Microscope.VSExtension.Options { 10 | using Microsoft.VisualStudio.Shell; 11 | 12 | /// 13 | /// A base class for a DialogPage to show in Tools -> Options. 14 | /// 15 | public class BaseOptionPage : DialogPage where T : BaseOptionModel, new() { 16 | private BaseOptionModel _model; 17 | 18 | public BaseOptionPage() { 19 | #pragma warning disable VSTHRD104 // Offer async methods 20 | _model = ThreadHelper.JoinableTaskFactory.Run(BaseOptionModel.CreateAsync); 21 | #pragma warning restore VSTHRD104 // Offer async methods 22 | } 23 | 24 | public override object AutomationObject => _model; 25 | 26 | public override void LoadSettingsFromStorage() { 27 | _model.Load(); 28 | } 29 | 30 | public override void SaveSettingsToStorage() { 31 | _model.Save(); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/VSExtension/Options/DialogPageProvider.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.VSExtension.Options { 4 | public static class DialogPageProvider { 5 | public class General : BaseOptionPage { } 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/VSExtension/Options/GeneralOptions.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.VSExtension.Options { 4 | using System.ComponentModel; 5 | 6 | public enum BuildConfig { Auto, Debug, Release } 7 | 8 | public class GeneralOptions : BaseOptionModel { 9 | [Category("General")] 10 | [DisplayName("Enabled")] 11 | [Description("Specifies whether to activate the CodeLens for IL instructions or not.")] 12 | [DefaultValue(true)] 13 | public bool Enabled { get; set; } = true; 14 | 15 | [Category("General")] 16 | [DisplayName("Refresh on save")] 17 | [Description("Specifies whether the instructions should be refreshed everytime the current document is saved.")] 18 | [DefaultValue(true)] 19 | public bool RefreshOnSave { get; set; } = true; 20 | 21 | [Category("General")] 22 | [DisplayName("Build configuration")] 23 | [Description("Specifies whether to show optimized (Release) or unoptimized (Debug) instructions. Auto will use the build configuration set via Visual Studio.")] 24 | [DefaultValue(BuildConfig.Auto)] 25 | [TypeConverter(typeof(EnumConverter))] 26 | public BuildConfig BuildConfig { get; set; } = BuildConfig.Auto; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/VSExtension/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | using Microscope.VSExtension; 5 | 6 | [assembly: AssemblyTitle("Microscope.VSExtension")] 7 | [assembly: AssemblyDescription(Vsix.Description)] 8 | [assembly: AssemblyConfiguration("")] 9 | [assembly: AssemblyCompany(Vsix.Author)] 10 | [assembly: AssemblyProduct(Vsix.Name)] 11 | [assembly: AssemblyCopyright(Vsix.Author)] 12 | [assembly: AssemblyTrademark("")] 13 | [assembly: AssemblyCulture("")] 14 | [assembly: ComVisible(false)] 15 | 16 | [assembly: AssemblyVersion("0.0.0.0")] 17 | [assembly: AssemblyFileVersion("0.0.0.0")] 18 | [assembly: AssemblyInformationalVersion("0.0.0.0")] 19 | -------------------------------------------------------------------------------- /src/VSExtension/RefreshCommand.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.VSExtension { 4 | using System; 5 | using System.ComponentModel.Design; 6 | 7 | using Microscope.Shared; 8 | 9 | using Microsoft; 10 | using Microsoft.VisualStudio.Shell; 11 | 12 | using static Microscope.Shared.Logging; 13 | 14 | using Task = System.Threading.Tasks.Task; 15 | 16 | internal sealed class RefreshCommand { 17 | public static async Task Initialize(AsyncPackage pkg, Func refreshCodeLens) { 18 | await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(pkg.DisposalToken); 19 | 20 | var cmdService = await pkg.GetServiceAsync(); 21 | Assumes.Present(cmdService); 22 | 23 | var cmdId = new CommandID(PackageGuids.CmdSetId, PackageIds.RefreshCommandId); 24 | var cmd = new OleMenuCommand( 25 | (_, e) => ThreadHelper.JoinableTaskFactory.RunAsync(async delegate { 26 | await Execute(refreshCodeLens, (OleMenuCmdEventArgs)e).Caf(); 27 | }), 28 | cmdId); 29 | cmdService.AddCommand(cmd); 30 | } 31 | 32 | private static async Task Execute(Func refreshCodeLens, OleMenuCmdEventArgs e) { 33 | try { 34 | await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); 35 | 36 | var arg = e.InValue as string 37 | ?? throw new InvalidOperationException($"{nameof(RefreshCommand)} requires an argument."); 38 | 39 | if (!Guid.TryParse(arg, out var dataPointId)) 40 | throw new InvalidOperationException($"{nameof(RefreshCommand)} requires an argument of type Guid."); 41 | 42 | await refreshCodeLens(dataPointId).Caf(); 43 | } catch (Exception ex) { 44 | LogVS(ex); 45 | throw; 46 | } 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/VSExtension/Resources/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bert2/microscope/43743af1adadf9bfc2111fb85d58dd68dd84b3e5/src/VSExtension/Resources/icon.png -------------------------------------------------------------------------------- /src/VSExtension/SaveCommandHandler.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace CodeCleanupOnSave { 4 | using System; 5 | using System.ComponentModel.Composition; 6 | 7 | using Microscope.VSExtension; 8 | using Microscope.VSExtension.Options; 9 | 10 | using Microsoft.VisualStudio.Commanding; 11 | using Microsoft.VisualStudio.Shell; 12 | using Microsoft.VisualStudio.Text.Editor; 13 | using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; 14 | using Microsoft.VisualStudio.Utilities; 15 | 16 | using static Microscope.Shared.Logging; 17 | 18 | [Export(typeof(ICommandHandler))] 19 | [Name(nameof(SaveCommandHandler))] 20 | [ContentType("CSharp")] 21 | [ContentType("Basic")] 22 | [TextViewRole(PredefinedTextViewRoles.PrimaryDocument)] 23 | public class SaveCommandHandler : ICommandHandler { 24 | public string DisplayName => nameof(SaveCommandHandler); 25 | 26 | public bool ExecuteCommand(SaveCommandArgs args, CommandExecutionContext ctx) { 27 | try { 28 | var opts = GeneralOptions.Instance; 29 | 30 | if (opts.Enabled && opts.RefreshOnSave) { 31 | _ = ThreadHelper.JoinableTaskFactory.RunAsync(async delegate { 32 | // CodeLenses usually only live as long as the document is open so we just refresh all the connected ones. 33 | await CodeLensConnectionHandler.RefreshAllCodeLensDataPoints(); 34 | }); 35 | } 36 | 37 | return true; 38 | } catch (Exception ex) { 39 | LogVS(ex); 40 | throw; 41 | } 42 | } 43 | 44 | public CommandState GetCommandState(SaveCommandArgs args) => CommandState.Available; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/VSExtension/UI/CodeLensDetailsControl.xaml: -------------------------------------------------------------------------------- 1 |  10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 24 | 25 | 31 | 32 | 38 | 39 | 47 | 48 | 53 | 54 | 60 | 61 | 66 | 67 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 78 | 79 | 82 | 83 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 95 | 96 | 97 | 100 | 101 | 105 | 106 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 117 | 118 | 119 | 120 | 123 | 125 | 126 | 127 | 131 | 132 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | -------------------------------------------------------------------------------- /src/VSExtension/UI/CodeLensDetailsControl.xaml.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.VSExtension.UI { 4 | using System.Diagnostics; 5 | using System.Windows.Controls; 6 | using System.Windows.Input; 7 | 8 | using Microscope.CodeAnalysis.Model; 9 | using Microscope.Shared; 10 | 11 | public partial class CodeLensDetailsControl : UserControl { 12 | public CodeLensDetailsControl(CodeLensDetails details) { 13 | InitializeComponent(); 14 | DataContext = CodeLensConnectionHandler.GetDetailsData(details.DataPointId); 15 | } 16 | 17 | private void OnInstructionDoubleClick(object sender, MouseButtonEventArgs args) { 18 | if (sender is Control c && c.DataContext is InstructionData instr) { 19 | GoToDocumentation(instr); 20 | args.Handled = true; 21 | } 22 | } 23 | 24 | private void GoToDocumentation(InstructionData instr) { 25 | var opCode = instr.OpCode.TrimEnd('.').Replace('.', '_'); 26 | var url = $"https://docs.microsoft.com/dotnet/api/system.reflection.emit.opcodes.{opCode}"; 27 | _ = Process.Start(url); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/VSExtension/UI/ViewElementFactory.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.VSExtension.UI { 4 | using Microscope.Shared; 5 | 6 | using Microsoft.VisualStudio.Text.Adornments; 7 | using Microsoft.VisualStudio.Text.Editor; 8 | using Microsoft.VisualStudio.Utilities; 9 | 10 | using System.ComponentModel.Composition; 11 | using System.Windows; 12 | 13 | [Export(typeof(IViewElementFactory))] 14 | [Name("CodeLens details view element factory")] 15 | [TypeConversion(from: typeof(CodeLensDetails), to: typeof(FrameworkElement))] 16 | [Order] 17 | public class ViewElementFactory : IViewElementFactory { 18 | public TView? CreateViewElement(ITextView textView, object model) where TView : class 19 | => new CodeLensDetailsControl((CodeLensDetails)model) as TView; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/VSExtension/VS2019/Microsoft.VisualStudio.CodeSense.Common.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bert2/microscope/43743af1adadf9bfc2111fb85d58dd68dd84b3e5/src/VSExtension/VS2019/Microsoft.VisualStudio.CodeSense.Common.dll -------------------------------------------------------------------------------- /src/VSExtension/VSExtension.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 16.0 6 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 7 | 8 | true 9 | 10 | 11 | false 12 | 13 | 14 | 15 | 16 | 17 | 18 | Debug 19 | AnyCPU 20 | 2.0 21 | {82b43b9b-a64c-4715-b499-d71e9ca2bd60};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 22 | {A0920311-8835-4915-9E9B-384F5D8F1113} 23 | Library 24 | Properties 25 | Microscope.VSExtension 26 | Microscope.VSExtension 27 | v4.8 28 | 8.0 29 | enable 30 | true 31 | true 32 | true 33 | true 34 | true 35 | false 36 | Program 37 | $(DevEnvDir)devenv.exe 38 | /rootsuffix Exp 39 | 40 | 41 | true 42 | full 43 | false 44 | bin\Debug\ 45 | DEBUG;TRACE 46 | prompt 47 | 4 48 | 49 | 50 | pdbonly 51 | true 52 | bin\Release\ 53 | TRACE 54 | prompt 55 | 4 56 | 57 | 58 | 59 | 60 | CodeLensDetailsControl.xaml 61 | 62 | 63 | 64 | 65 | Component 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | True 74 | True 75 | MicroscopeCommands.vsct 76 | 77 | 78 | 79 | 80 | True 81 | True 82 | source.extension.vsixmanifest 83 | 84 | 85 | 86 | 87 | Resources\LICENSE 88 | true 89 | 90 | 91 | 92 | Designer 93 | VsixManifestGenerator 94 | source.extension.cs 95 | 96 | 97 | 98 | 99 | VsctGenerator 100 | Menus.ctmenu 101 | MicroscopeCommands.cs 102 | 103 | 104 | PreserveNewest 105 | true 106 | 107 | 108 | 109 | 110 | {f98bb94e-cf38-466b-adfd-9bb26d8493b7} 111 | CodeAnalysis 112 | 113 | 114 | {FA8F7552-7E27-425B-9B81-09E0789179A3} 115 | CodeLensProvider 116 | BuiltProjectOutputGroup%3bBuiltProjectOutputGroupDependencies%3bGetCopyToOutputDirectoryItems%3bSatelliteDllsProjectOutputGroup%3b 117 | 118 | 119 | {D6F37EEC-CBA3-4DB2-B44C-5F036C6FAA9F} 120 | Shared 121 | 122 | 123 | 124 | 125 | 4.0.0-4.final 126 | 127 | 128 | 4.0.0-4.final 129 | 130 | 131 | 4.0.0-4.final 132 | 133 | 134 | 4.0.0-4.final 135 | 136 | 137 | 17.0.0-previews-4-31709-430 138 | compile; build; native; contentfiles; analyzers; buildtransitive 139 | 140 | 141 | 17.0.5217-preview5 142 | runtime; build; native; contentfiles; analyzers; buildtransitive 143 | all 144 | 145 | 146 | 0.11.4 147 | 148 | 149 | 2.8.28 150 | 151 | 152 | 153 | 154 | 155 | False 156 | VS2019\Microsoft.VisualStudio.CodeSense.Common.dll 157 | False 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | Designer 173 | MSBuild:Compile 174 | 175 | 176 | 177 | 178 | -------------------------------------------------------------------------------- /src/VSExtension/source.extension.cs: -------------------------------------------------------------------------------- 1 | // ------------------------------------------------------------------------------ 2 | // 3 | // This file was generated by VSIX Synchronizer 4 | // 5 | // ------------------------------------------------------------------------------ 6 | namespace Microscope.VSExtension 7 | { 8 | internal sealed partial class Vsix 9 | { 10 | public const string Id = "ede7ef0f-017b-4b33-b7b3-c7480d3cc713"; 11 | public const string Name = "microscope"; 12 | public const string Description = @"Provides a CodeLens to inspect the intermediate language instructions of a method."; 13 | public const string Language = "en-US"; 14 | public const string Version = "0.0.0.0"; 15 | public const string Author = "Robert Hofmann"; 16 | public const string Tags = "CodeLens, CIL, MSIL, IL, intermediate language"; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/VSExtension/source.extension.vsixmanifest: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | microscope 6 | Provides a CodeLens to inspect the intermediate language instructions of a method. 7 | https://github.com/bert2/microscope 8 | Resources\LICENSE 9 | https://github.com/bert2/microscope#changelog 10 | Resources\icon.png 11 | Resources\icon.png 12 | CodeLens, CIL, MSIL, IL, intermediate language 13 | false 14 | 15 | 16 | 17 | amd64 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /tests/CollectGeneratedCodeExtTestData.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.Tests { 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Threading.Tasks; 7 | 8 | public class CollectGeneratedCodeExtTestData { 9 | public bool Lambda() => new int[0].Any(x => x > 0); 10 | 11 | public bool Closure(int x) => new int[0].Any(y => y > x); 12 | 13 | public bool ClosureNestedInLambda() => new int[0].Any(x => new int[0].Any(y => y > x)); 14 | 15 | public bool NestedLambda() => new int[0].Any(x => new int[0].Any(y => x > y)); 16 | 17 | public bool GenericLambda() => new string[0].Any(s => s == typeof(T).FullName); 18 | 19 | public IEnumerable Iterator() { 20 | yield return 1; 21 | } 22 | 23 | public async Task AsyncMethod() => await Task.Delay(0); 24 | 25 | public async Task AsyncMethodWithLambda() { 26 | await Task.Delay(0); 27 | _ = new int[0].Any(x => x > 0); 28 | } 29 | 30 | public void LocalFunction() { 31 | Foo(); 32 | 33 | static void Foo() { } 34 | } 35 | 36 | public void LocalFunctionCalledTwice() { 37 | Foo(); 38 | Foo(); 39 | 40 | static void Foo() { } 41 | } 42 | 43 | public int MyProperty { get; set; } 44 | public int AutoProperty() { 45 | MyProperty = 1; 46 | return MyProperty; 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /tests/CollectGeneratedCodeExtTests.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed 4 | 5 | namespace Microscope.Tests { 6 | using System; 7 | using System.Collections.Generic; 8 | using System.Linq; 9 | using System.Linq.Expressions; 10 | 11 | using FluentAssertions; 12 | 13 | using Microscope.CodeAnalysis; 14 | using Microscope.Tests.Util; 15 | 16 | using Microsoft.VisualStudio.TestTools.UnitTesting; 17 | 18 | using Mono.Cecil; 19 | using Mono.Cecil.Rocks; 20 | 21 | [TestClass] 22 | public class CollectGeneratedCodeExtTests { 23 | private static readonly Dictionary testDataMethods = AssemblyDefinition 24 | .ReadAssembly(typeof(CollectGeneratedCodeExtTestData).Assembly.Location) 25 | .MainModule 26 | .GetType(typeof(CollectGeneratedCodeExtTestData).FullName) 27 | .GetMethods() 28 | .ToDictionary(m => m.Name); 29 | 30 | private readonly HashSet empty = new HashSet(); 31 | 32 | [TestMethod] public void FindsMethodGeneratedForLambda() => 33 | Method(x => x.Lambda()) 34 | .CollectGeneratedMethods(visited: empty) 35 | .Should().ContainSingle().Which 36 | .Should().Satisfy(m => m.Name.Should().Be("b__0_0")) 37 | .And.Satisfy(m => m.DeclaringType.Name.Should().Be("<>c")); 38 | 39 | [TestMethod] public void FindsMethodsGeneratedForClosure() => 40 | Method(x => x.Closure(0)) 41 | .CollectGeneratedMethods(visited: empty) 42 | .Should().SatisfyRespectively( 43 | ctor => ctor 44 | .Should().Satisfy(m => m.Name.Should().Be(".ctor")) 45 | .And.Satisfy(m => m.DeclaringType.Name.Should().Be("<>c__DisplayClass1_0")), 46 | closure => closure 47 | .Should().Satisfy(m => m.Name.Should().Be("b__0")) 48 | .And.Satisfy(m => m.DeclaringType.Name.Should().Be("<>c__DisplayClass1_0"))); 49 | 50 | [TestMethod] public void FindsMethodsGeneratedForClosureNestedInLambda() => 51 | Method(x => x.ClosureNestedInLambda()) 52 | .CollectGeneratedMethods(visited: empty) 53 | .Should().SatisfyRespectively( 54 | lambda => lambda 55 | .Should().Satisfy(m => m.Name.Should().Be("b__2_0")) 56 | .And.Satisfy(m => m.DeclaringType.Name.Should().Be("<>c")), 57 | ctor => ctor 58 | .Should().Satisfy(m => m.Name.Should().Be(".ctor")) 59 | .And.Satisfy(m => m.DeclaringType.Name.Should().Be("<>c__DisplayClass2_0")), 60 | closure => closure 61 | .Should().Satisfy(m => m.Name.Should().Be("b__1")) 62 | .And.Satisfy(m => m.DeclaringType.Name.Should().Be("<>c__DisplayClass2_0"))); 63 | 64 | [TestMethod] public void FindsMethodGeneratedForGenericLambda() => 65 | Method(x => x.GenericLambda()) 66 | .CollectGeneratedMethods(visited: empty) 67 | .Should().ContainSingle().Which 68 | .Should().Satisfy(m => m.Name.Should().Be("b__4_0")) 69 | .And.Satisfy(m => m.DeclaringType.Name.Should().Be("<>c__4`1")); 70 | 71 | [TestMethod] public void FindsMethodGeneratedForLocalFunction() => 72 | Method(x => x.LocalFunction()) 73 | .CollectGeneratedMethods(visited: empty) 74 | .Should().ContainSingle().Which 75 | .Should().Satisfy(m => m.Name.Should().Be("g__Foo|8_0")) 76 | .And.Satisfy(m => m.DeclaringType.Name.Should().Be("CollectGeneratedCodeExtTestData")); 77 | 78 | [TestMethod] public void FindsMethodsGeneratedForIterator() => 79 | Method(x => x.Iterator()) 80 | .CollectGeneratedMethods(visited: empty) 81 | .Should().SatisfyRespectively( 82 | ctor => ctor 83 | .Should().Satisfy(m => m.Name.Should().Be(".ctor")) 84 | .And.Satisfy(m => m.DeclaringType.Name.Should().Be("d__5")), 85 | moveNext => moveNext 86 | .Should().Satisfy(m => m.Name.Should().Be("MoveNext")) 87 | .And.Satisfy(m => m.DeclaringType.Name.Should().Be("d__5"))); 88 | 89 | [TestMethod] public void FindsMethodsGeneratedForAsyncMethod() => 90 | Method(x => x.AsyncMethod()) 91 | .CollectGeneratedMethods(visited: empty) 92 | .Should().SatisfyRespectively( 93 | #if DEBUG // ctor call is optimized away in release builds 94 | ctor => ctor 95 | .Should().Satisfy(m => m.Name.Should().Be(".ctor")) 96 | .And.Satisfy(m => m.DeclaringType.Name.Should().Be("d__6")), 97 | #endif 98 | moveNext => moveNext 99 | .Should().Satisfy(m => m.Name.Should().Be("MoveNext")) 100 | .And.Satisfy(m => m.DeclaringType.Name.Should().Be("d__6"))); 101 | 102 | [TestMethod] public void FindsMethodGeneratedForLambdaInAsyncMethod() => 103 | Method(x => x.AsyncMethodWithLambda()) 104 | .CollectGeneratedMethods(visited: empty) 105 | .Should().SatisfyRespectively( 106 | #if DEBUG // ctor call is optimized away in release builds 107 | ctor => ctor 108 | .Should().Satisfy(m => m.Name.Should().Be(".ctor")) 109 | .And.Satisfy(m => m.DeclaringType.Name.Should().Be("d__7")), 110 | #endif 111 | moveNext => moveNext 112 | .Should().Satisfy(m => m.Name.Should().Be("MoveNext")) 113 | .And.Satisfy(m => m.DeclaringType.Name.Should().Be("d__7")), 114 | lambda => lambda 115 | .Should().Satisfy(m => m.Name.Should().Be("b__7_0")) 116 | .And.Satisfy(m => m.DeclaringType.Name.Should().Be("<>c"))); 117 | 118 | [TestMethod] public void RemovesDuplicates() => 119 | Method(x => x.LocalFunctionCalledTwice()) 120 | .CollectGeneratedMethods(visited: empty) 121 | .Should().OnlyHaveUniqueItems(); 122 | 123 | [TestMethod] public void IgnoresAutoProperties() => 124 | Method(x => x.AutoProperty()) 125 | .CollectGeneratedMethods(visited: empty) 126 | .Should().BeEmpty(); 127 | 128 | private static MethodDefinition Method(Expression> selector) 129 | => testDataMethods[((MethodCallExpression)selector.Body).Method.Name]; 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /tests/DocumentationTests.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.Tests { 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | 7 | using FluentAssertions; 8 | 9 | using Microscope.CodeAnalysis; 10 | 11 | using Microsoft.VisualStudio.TestTools.UnitTesting; 12 | 13 | using Mono.Cecil.Cil; 14 | 15 | [TestClass] 16 | public class DocumentationTests { 17 | // `System.Reflection.Emit.OpCodes` doesn't know of `ldelem.any`. 18 | [TestMethod] public void ReturnsNullForUnknownOpCode() => 19 | OpCodes.Ldelem_Any 20 | .GetDocumentation() 21 | .Should().BeNull(); 22 | 23 | [TestMethod] public void KnowsAllOpCodes() => 24 | AllKnownInstructions 25 | .Where(i => i.GetRawDocumentation() == null) 26 | .Should().BeEmpty(); 27 | 28 | [TestMethod] public void RemovesParamrefTags() => 29 | OpCodes.Brtrue 30 | .GetDocumentation() 31 | .Should().Be("Transfers control to a target instruction if `value` is true, not null, or non-zero."); 32 | 33 | [TestMethod] public void RemovesSeeCrefTags() => 34 | OpCodes.Ckfinite 35 | .GetDocumentation() 36 | .Should().Be("Throws `System.ArithmeticException` if value is not a finite number."); 37 | 38 | [TestMethod] public void ReturnsDocumentationForInstructionWithTrailingDot() => 39 | OpCodes.Constrained 40 | .GetDocumentation() 41 | .Should().Be("Constrains the type on which a virtual method call is made."); 42 | 43 | // The documentation was generated from all opcodes in `System.Reflection.Emit.OpCodes`, but the 44 | // actual instructions are retrieved as `Mono.Cecil.Cil.OpCodes`. 45 | private static IEnumerable AllKnownInstructions => typeof(System.Reflection.Emit.OpCodes) 46 | .GetFields() 47 | .Select(f => ((System.Reflection.Emit.OpCode)f.GetValue(null)).Name); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /tests/GetDocumentExtTests.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.Tests { 4 | using System; 5 | using System.Collections.Immutable; 6 | using System.Reflection; 7 | 8 | using FluentAssertions; 9 | 10 | using Microsoft.CodeAnalysis; 11 | using Microsoft.VisualStudio.LanguageServices; 12 | using Microsoft.VisualStudio.TestTools.UnitTesting; 13 | 14 | [TestClass] 15 | public class GetDocumentExtTests { 16 | [TestMethod] 17 | public void VisualStudioWorkspaceImplTypeExists() => typeof(VisualStudioWorkspace).Assembly 18 | .GetType( 19 | "Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.VisualStudioWorkspaceImpl") 20 | .Should().NotBeNull(); 21 | 22 | [TestMethod] 23 | public void ProjectToGuidMapFieldExists() => typeof(VisualStudioWorkspace).Assembly 24 | .GetType( 25 | "Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.VisualStudioWorkspaceImpl", 26 | throwOnError: true) 27 | .GetField("_projectToGuidMap", BindingFlags.NonPublic | BindingFlags.Instance) 28 | .Should().NotBeNull(); 29 | 30 | [TestMethod] 31 | public void ProjectToGuidMapFieldIsImmutableDictionary() => typeof(VisualStudioWorkspace).Assembly 32 | .GetType( 33 | "Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.VisualStudioWorkspaceImpl", 34 | throwOnError: true) 35 | .GetField("_projectToGuidMap", BindingFlags.NonPublic | BindingFlags.Instance) 36 | .FieldType 37 | .Should().Be(typeof(ImmutableDictionary)); 38 | 39 | [TestMethod] 40 | public void GetDocumentIdInCurrentContextMethodExists() => typeof(Workspace) 41 | .GetMethod( 42 | "GetDocumentIdInCurrentContext", 43 | BindingFlags.NonPublic | BindingFlags.Instance, 44 | binder: null, 45 | types: new[] { typeof(DocumentId) }, 46 | modifiers: null) 47 | .Should().NotBeNull(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /tests/GetMethodDefinitionExtTestData.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | #pragma warning disable RCS1164 // Unused type parameter. 4 | #pragma warning disable RCS1163 // Unused parameter. 5 | #pragma warning disable IDE0060 // Remove unused parameter 6 | #pragma warning disable RCS1158 // Static member in generic type should use a type parameter. 7 | #pragma warning disable RCS1102 // Make class static. 8 | 9 | namespace Microscope.Tests.TestData { 10 | using System; 11 | using System.Collections.Generic; 12 | 13 | using MyAlias = System.String; 14 | 15 | public class Class { 16 | public void InstanceMethod() { } 17 | public static void StaticMethod() { } 18 | public void GenericInstanceMethod() { } 19 | public static void GenericStaticMethod() { } 20 | 21 | public void InstanceMethodWithParam(int x) { } 22 | public static void StaticMethodWithParam(bool x) { } 23 | public void GenericInstanceMethodWithParam(T x) { } 24 | public static void GenericStaticMethodWithParam(T x) { } 25 | 26 | public class NestedClass { 27 | public void Method() { } 28 | 29 | public class NestedNestedClass { 30 | public void Method() { } 31 | } 32 | } 33 | } 34 | 35 | public class GenericClass { 36 | public void Method(T x) { } 37 | public void GenericMethod(T x, U y) { } 38 | } 39 | 40 | public class AmbiguousClass { 41 | public void Method(int x) { } 42 | } 43 | 44 | public class AmbiguousClass { 45 | public void Method(T x) { } 46 | } 47 | 48 | public class Overloads { 49 | public void Method() { } 50 | public void Method(int x) { } 51 | public void Method(string x) { } 52 | public void Method(T x) { } 53 | public void Method(List x) { } 54 | public void Method(List x) { } 55 | } 56 | 57 | public class MoreOverloads { 58 | public void Method(List> x) { } 59 | public void Method(List> x) { } 60 | public void Method(List[] x) { } 61 | public void Method(List x) { } 62 | public void Method(List x) { } 63 | public void Method(Dictionary> x) { } 64 | public void Method(Name1.Space1.Foo x) { } 65 | public void Method(Name2.Space2.Foo x) { } 66 | public void Method(Foo.Bar x) { } 67 | public void Method(Foo.Bar x) { } 68 | 69 | public class Foo { 70 | public class Bar { } 71 | } 72 | } 73 | 74 | public class Arrays { 75 | public void Method(int[] xs) { } 76 | public void Method(int[][][] xs) { } 77 | public void Method(int[,,] xs) { } 78 | public void Method(params char[] xs) { } 79 | 80 | public void Method(T[] xs) { } 81 | public void Method(T[][][] xs) { } 82 | public void Method(T[,,] xs) { } 83 | 84 | public void Method(Dictionary[] xs) { } 85 | public void Method(Dictionary[] xs) { } 86 | public void Method(MoreOverloads.Foo.Bar[] xs) { } 87 | } 88 | 89 | public class Refs { 90 | public void Method(ref int x) { } 91 | public void Method(in char x) { } 92 | public void Method(out float x) => x = .0f; 93 | 94 | public void MethodWithInParamOverload(in string s) { } 95 | public void MethodWithInParamOverload(string s) { } 96 | } 97 | 98 | public class Pointers { 99 | public unsafe void Method(int* x) { } 100 | public unsafe void Method(int** x) { } 101 | public unsafe void Method(int*[] xs) { } 102 | public unsafe void Method(void* x) { } 103 | } 104 | 105 | public class Dynamic { 106 | public void Method(int x) { } 107 | public void Method(dynamic x) { } 108 | } 109 | 110 | public class Delegates { 111 | public delegate string Qux(int x); 112 | public void Method(Func x) { } 113 | public void Method(Qux x) { } 114 | } 115 | 116 | public class Alias { 117 | public void Method(int x) { } 118 | public void Method(MyAlias x) { } 119 | } 120 | } 121 | 122 | namespace Name1.Space1 { 123 | public class Foo { } 124 | } 125 | 126 | namespace Name2.Space2 { 127 | public class Foo { } 128 | } 129 | -------------------------------------------------------------------------------- /tests/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | [assembly: AssemblyTitle("Tests")] 6 | [assembly: AssemblyDescription("")] 7 | [assembly: AssemblyConfiguration("")] 8 | [assembly: AssemblyCompany("")] 9 | [assembly: AssemblyProduct("Tests")] 10 | [assembly: AssemblyCopyright("Copyright © 2020")] 11 | [assembly: AssemblyTrademark("")] 12 | [assembly: AssemblyCulture("")] 13 | 14 | [assembly: ComVisible(false)] 15 | 16 | [assembly: Guid("ee04fe33-9ae6-42c1-a7b9-794196d52a4f")] 17 | 18 | // [assembly: AssemblyVersion("1.0.*")] 19 | [assembly: AssemblyVersion("1.0.0.0")] 20 | [assembly: AssemblyFileVersion("1.0.0.0")] 21 | -------------------------------------------------------------------------------- /tests/Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {EE04FE33-9AE6-42C1-A7B9-794196D52A4F} 8 | Library 9 | Properties 10 | Microscope.Tests 11 | Microscope.Tests 12 | v4.8 13 | 8.0 14 | enable 15 | 512 16 | {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 17 | 15.0 18 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 19 | $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages 20 | False 21 | UnitTest 22 | 23 | 24 | 25 | 26 | true 27 | full 28 | false 29 | bin\Debug\ 30 | DEBUG;TRACE 31 | prompt 32 | 4 33 | true 34 | 35 | 36 | pdbonly 37 | true 38 | bin\Release\ 39 | TRACE 40 | prompt 41 | 4 42 | true 43 | 44 | 45 | true 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 6.1.0 66 | 67 | 68 | 16.11.0 69 | runtime 70 | compile; build; native; contentfiles; analyzers; buildtransitive 71 | 72 | 73 | 1.4.1 74 | 75 | 76 | 16.11.0 77 | runtime 78 | compile; build; native; contentfiles; analyzers; buildtransitive 79 | 80 | 81 | 16.11.0 82 | runtime 83 | compile; build; native; contentfiles; analyzers; buildtransitive 84 | 85 | 86 | 4.0.0-4.final 87 | 88 | 89 | 4.0.0-4.final 90 | 91 | 92 | 4.0.0-4.final 93 | 94 | 95 | 4.0.0-4.final 96 | 97 | 98 | 4.0.0-4.final 99 | 100 | 101 | 0.11.4 102 | 103 | 104 | 2.2.7 105 | 106 | 107 | 2.2.7 108 | 109 | 110 | 5.0.0 111 | 112 | 113 | 114 | 115 | PreserveNewest 116 | 117 | 118 | 119 | 120 | {f98bb94e-cf38-466b-adfd-9bb26d8493b7} 121 | CodeAnalysis 122 | 123 | 124 | {FA8F7552-7E27-425B-9B81-09E0789179A3} 125 | CodeLensProvider 126 | 127 | 128 | {D6F37EEC-CBA3-4DB2-B44C-5F036C6FAA9F} 129 | Shared 130 | 131 | 132 | 133 | 134 | -------------------------------------------------------------------------------- /tests/Util/DebugExt.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.Tests.Util { 4 | using System; 5 | 6 | public static class DebugExt { 7 | public static T Debug(this T x, Action f) { 8 | f(x); 9 | return x; 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /tests/Util/FluentAssertionsExt.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.Tests.Util { 4 | using System; 5 | 6 | using FluentAssertions; 7 | using FluentAssertions.Primitives; 8 | 9 | using Mono.Cecil; 10 | 11 | public static class FluentAssertionsExt { 12 | public static AndConstraint Satisfy( 13 | this ObjectAssertions parent, 14 | Action inspector) { 15 | inspector((MethodDefinition)parent.Subject); 16 | return new AndConstraint(parent); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /tests/Util/SymbolResolver.cs: -------------------------------------------------------------------------------- 1 | #nullable enable 2 | 3 | namespace Microscope.Tests.Util { 4 | using System; 5 | using System.Diagnostics.CodeAnalysis; 6 | using System.IO; 7 | using System.Linq; 8 | using System.Runtime.CompilerServices; 9 | using System.Threading; 10 | using System.Threading.Tasks; 11 | 12 | using Microscope.Shared; 13 | 14 | using Microsoft.Build.Locator; 15 | using Microsoft.CodeAnalysis; 16 | using Microsoft.CodeAnalysis.CSharp.Syntax; 17 | using Microsoft.CodeAnalysis.MSBuild; 18 | 19 | /// 20 | /// In order to test that `GetMethodDefinitionExt.GetMethodDefinition(this AssemblyDefinition, IMethodSymbol)` 21 | /// can resolve methods with ambiguous names in an `AssemblyDefinition` we need a reliable way to get an 22 | /// `IMethodSymbol` for a given method from the `TestData` namespace. 23 | /// One way would be to compile the test project in memory and then look up the method symbol by name. This 24 | /// has the major disadvantage that we'd have to implement the logic to resolve ambiguous method names again. 25 | /// Instead we are using a special method `Get()` that can locate its own call in the syntax tree and in turn 26 | /// analyze the syntax of the arguments passed to it. Hence the only purpose of the lambda passed to `Get()` 27 | /// is to reference the method which we want the `IMethodSymbol` for. 28 | /// 29 | public class SymbolResolver : IDisposable { 30 | private const string get = nameof(SymbolResolver) + "." + nameof(Get) + "()"; 31 | private readonly MSBuildWorkspace workspace; 32 | private readonly SyntaxTree syntaxTree; 33 | private readonly SemanticModel semanticModel; 34 | 35 | static SymbolResolver() { 36 | var latest = MSBuildLocator 37 | .QueryVisualStudioInstances() 38 | .OrderByDescending(vs => vs.Version) 39 | .First(); 40 | MSBuildLocator.RegisterInstance(latest); 41 | } 42 | 43 | public SymbolResolver(MSBuildWorkspace workspace, Compilation compilation, SyntaxTree syntaxTree) { 44 | this.workspace = workspace; 45 | this.syntaxTree = syntaxTree; 46 | semanticModel = compilation.GetSemanticModel(syntaxTree); 47 | } 48 | 49 | public void Dispose() => workspace.Dispose(); 50 | 51 | public static async Task ForMyTests(CancellationToken ct, [CallerFilePath] string? testClassFile = null) { 52 | var workspace = MSBuildWorkspace.Create(); 53 | workspace.WorkspaceFailed += (_, e) => { 54 | if (e.Diagnostic.Kind == WorkspaceDiagnosticKind.Failure) 55 | throw new InvalidOperationException(e.Diagnostic.ToString()); 56 | }; 57 | 58 | var testProjPath = Path.Combine(Path.GetDirectoryName(testClassFile), "Tests.csproj"); 59 | var testProj = await workspace.OpenProjectAsync(testProjPath, progress: null, ct).Caf(); 60 | 61 | var testClassDocId = testProj.Solution.GetDocumentIdsWithFilePath(testClassFile).SingleOrDefault() 62 | ?? throw new InvalidOperationException($"Could not find file {testClassFile} in project {testProj.Name}."); 63 | var testClassDoc = testProj.GetDocument(testClassDocId) 64 | ?? throw new InvalidOperationException($"Could not find document with id {testClassDocId} in project {testProj.Name}."); 65 | var syntaxTree = await testClassDoc.GetSyntaxTreeAsync(ct).Caf() 66 | ?? throw new InvalidOperationException($"Document {testClassDoc.Name} does not have a syntax tree."); 67 | 68 | var compilation = await testProj.GetCompilationAsync(ct).Caf() 69 | ?? throw new InvalidOperationException($"Project {testProj.Name} does not support compilation."); 70 | 71 | return new SymbolResolver(workspace, compilation, syntaxTree); 72 | } 73 | 74 | [SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Param `selector` needed indirectly.")] 75 | public IMethodSymbol Get(Action selector, [CallerLineNumber] int line = 0) 76 | => ResolveReferencedMethodAt(line); 77 | 78 | [SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Param `selector` needed indirectly.")] 79 | public IMethodSymbol Get(Action selector, [CallerLineNumber] int line = 0) 80 | => ResolveReferencedMethodAt(line); 81 | 82 | private IMethodSymbol ResolveReferencedMethodAt(int line) { 83 | var span = syntaxTree.GetText().Lines[line - 1].Span; 84 | var node = syntaxTree.GetRoot().FindNode(span); 85 | 86 | var symbolResolverGetCall = node 87 | .DescendantNodes() 88 | .OfType() 89 | .SingleOrDefault(call 90 | => call.Expression is MemberAccessExpressionSyntax ma 91 | && ma.Name.Identifier.ValueText == nameof(Get) 92 | && semanticModel.GetSymbolInfo(ma).Symbol?.ContainingType.Name == nameof(SymbolResolver)) 93 | ?? throw new InvalidOperationException($"Could not find call to {get} at line {line} (node: {node})."); 94 | 95 | var args = symbolResolverGetCall.ArgumentList.Arguments; 96 | 97 | if (args.Count > 1) 98 | throw new ArgumentException($"Don't pass argument '{nameof(line)}' to {get}."); 99 | 100 | var invocation = args[0].Expression switch { 101 | MemberAccessExpressionSyntax ma => ma, // when using method group: `Get(Foo.Bar)` 102 | LambdaExpressionSyntax l => GetMemberAccess(l), // when using lambda: `Get(foo => foo.Bar())` 103 | _ => throw new InvalidOperationException($"Unexpected argument expression {args}.") 104 | }; 105 | 106 | var symbol = semanticModel.GetSymbolInfo(invocation).Symbol 107 | ?? throw new InvalidOperationException($"Failed to get symbol for {invocation}."); 108 | 109 | return (IMethodSymbol)symbol; 110 | } 111 | 112 | private MemberAccessExpressionSyntax GetMemberAccess(LambdaExpressionSyntax l) 113 | => l.ExpressionBody is null 114 | ? throw new ArgumentException($"Don't pass a statement block to {get}. Use an expression body instead.") 115 | : !(l.ExpressionBody is InvocationExpressionSyntax inv) 116 | ? throw new ArgumentException($"Lambda passed to {get} must be a method call.") 117 | : !(inv.Expression is MemberAccessExpressionSyntax ma) 118 | ? throw new ArgumentException($"Lambda passed to {get} must be a call of a class method.") 119 | : ma; 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /tests/app.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | --------------------------------------------------------------------------------