Rosyln (2)-C # Semantic Analysis

Source: Internet
Author: User
Prerequisites

Visual Studio 2017

. Net compiler Platform SDK

Rosyln entry (1)-C # syntax analysis

Introduction

Today, Visual Basic and C # compilers are black boxes: Input text and then output bytes. The intermediate stage of the compilation pipeline is not transparent. With the. NET compiler platform (formerly called "Roslyn"), tools and developers can analyze and understand the code using the exactly same data structure and algorithm used by the compiler.

In this article, we will explore symbol and bindingapi. You can use the syntax API to view the parser and syntax tree for reasoning and constructing their utilities.

Understand compilation and symbols

This syntax API allows you to view the program structure. However, you usually need more information about the semantics or meaning of the program. Although loose code snippets can be used for separate syntax analysis, it is not meaningful to put forward questions such as "what is the type of this variable" in isolation. The meaning of the type name may depend on the Assembly reference, namespace import, or other code files. This is the application of the compilation class.

Compilation is similar to a single project seen by the compiler. It indicates all the content required to compile Visual Basic or C # programs, such as Assembly reference, compiler options, and source file set to be compiled. With this context, you can infer the meaning of the Code. Compilation allows you to find the types, namespaces, members, variables, and other entities referenced by symbols-names and other expressions. The process of associating the name and expression with the symbol (symbols) is called binding.

Like syntaxtree, compilation is an abstract class with a derived class in a specific language. When creating a compilation instance, you must call the factory method on the csharpcompilation (or visualbasiccompilation) class.

Demo-create Compilation
  • Introduce nuget
  Microsoft.CodeAnalysis.CSharp   Microsoft.CodeAnalysis.CSharp.Workspaces
  • The demo Main Code mentioned in the previous section
  class Program   {       static void Main(string[] args)       {           SyntaxTree tree = CSharpSyntaxTree.ParseText(                       @"using System;                       using System.Collections.Generic;                       using System.Text;                                               namespace HelloWorld                       {                           class Program                           {                               static void Main(string[] args)                               {                                   Console.WriteLine(""Hello, World!"");                               }                           }                       }");           var root = (CompilationUnitSyntax)tree.GetRoot();        }   }           
  • Next, create a csharpcompilation object at the end of the main method.
var compilation = CSharpCompilation.Create("HelloWorld")                                               .AddReferences(                                                    MetadataReference.CreateFromFile(                                                        typeof(object).Assembly.Location))                                               .AddSyntaxTrees(tree);
  • Set breakpoints, start debugging, and view the prompt at compilation.
Semantic model semanticmodel

Once compiled, You can require it to provide semanticmodel for any syntaxtree contained in the compilation. You can query the semanticmodel to answer such questions as "What is the range of the location ?", "What members can be obtained from this method ?" , "What variables are used in this text block ?" And "what is this name/expression ?" And so on.

Example-bind name

This example shows how to obtain the semanticmodel object for helloworld syntaxtree. After obtaining the semanticmodel, the name in the first using command is bound to the system namespace symbol.

  • Put the following code at the end of main.
   var model = compilation.GetSemanticModel(tree);      var nameInfo = model.GetSymbolInfo(root.Usings[0].Name);      var systemSymbol = (INamespaceSymbol)nameInfo.Symbol;  

* Append the following code to enumerate the sub-namespace of the system namespace and print its name to the console:

 foreach (var ns in systemSymbol.GetNamespaceMembers())            {                Console.WriteLine(ns.Name);            }
  • Debug to debug and view the value of each node. The console output result is as follows:
BuffersCollectionsComponentModelConfigurationDiagnosticsGlobalizationIONumericsReflectionResourcesRuntimeSecurityStubHelpersTextThreading
Example -- binding expression

The preceding example shows how to bind the name to search for the symbol. However, there are other expressions in the C # program that are not names that can be bound. This example shows how to bind with other expression types-simple string text in this example.

var helloWorldString = root.DescendantNodes()                                       .OfType<LiteralExpressionSyntax>()                                       .First();                                       var literalInfo = model.GetTypeInfo(helloWorldString);var stringTypeSymbol = (INamedTypeSymbol)literalInfo.Type; Console.Clear();            foreach (var name in (from method in stringTypeSymbol.GetMembers()                                                      .OfType<IMethodSymbol>()                       where method.ReturnType.Equals(stringTypeSymbol) &&                             method.DeclaredAccessibility ==                                         Accessibility.Public                       select method.Name).Distinct()){    Console.WriteLine(name);}
  • Run debug to view the values of related nodes. The console output result is as follows:
InternIsInternedCreateCopyToStringNormalizeConcatFormatInsertJoinPadLeftPadRightRemoveReplaceSubstringToLowerToLowerInvariantToUpperToUpperInvariantTrimTrimStartTrimEnd
Summary

This article demonstrates semantic analysis. Two examples demonstrate how to bind a name to search for a symbol and a binding expression. We can obtain the following knowledge points:

Get the root node of the syntax tree: (compilationunitsyntax) tree. getroot ()

Used to create a csharpcompilation object: csharpcompilation. Create ("helloworld"). addreferences (metadatareference. createfromfile (typeof (object). Assembly. Location). addsyntaxtrees (tree)

Used to obtain the model: Compilation. getsemanticmodel (tree );

Obtain the Symbol Information of name: model. getsymbolinfo (root. usingS [0]. Name );

You can obtain the namespace name: (inamespacesymbol) nameinfo. symbol;

Get all the members in the current namespace: systemsymbol. getnamespacemembers ()

Get Text expression: Root. descendantnodes (). oftype <literalexpressionsyntax> ()

Get type information model. gettypeinfo (helloworldstring)

Obtain the specific type (inamedtypesymbol) literalinfo. type;

Returns a string. The method of the Public type is from method in stringtypesymbol. getmembers (). oftype <imethodsymbol> () Where method. returntype. equals (stringtypesymbol) & method. declaredaccessibility = accessibility. public select method. name

Source code

Csharpfandemo

Reference

Getting started C # Semantic Analysis

Rosyln (2)-C # Semantic Analysis

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.