Roslyn entry (b) -C # semantics

1 | 0 prerequisite


Visual Studio 2017

.NET Compiler Platform SDK

Rosyln entry (a) -C # parsing

2 | 0 Profile


Today, Visual Basic and C # compiler is a black box: a text input and output bytes, an intermediate stage of the pipeline is not compiled transparency. Use .NET compiler platform (formerly known as "Roslyn"), and tool developers can use to analyze and understand the code compiler uses the same data structures and algorithms.

In this article, we will explore Symbol and BindingAPI. To see through the API syntax parser, the syntax tree for reasoning and construct their utility.

3 | 0 understanding compile and symbols


This syntax API allows you to see the structure of the program. Usually, however, you need more extensive information about the program semantics or meaning. Although loosely code fragment can be parsed separately, but isolated proposed, such as "What type of the variable is" not the type of problems makes sense. Meaning Type the name may depend assembly references, namespace import or other code files. That's where Compilation class.

Compile a single project similar to the compiler sees, represents everything you need to compile the Visual Basic or C # programs, such as assembly references, and compiler options to compile the source file set. With this context, you can deduce the meaning of the code. Compiler allows you to find symbol - type, namespace, and members of entities such as variable names and other expressions references. The procedure name and expressions and symbols (Symbols) associated with the called Binding.

Like with SyntaxTree, Compilation is an abstract class derived class has a specific language. When you create Compilation instance, you must call the factory method on CSharpCompilation (or VisualBasicCompilation) class.

4 | 0 Demo - create compilation


  • Introduced Nuget
  Microsoft.CodeAnalysis.CSharp
 
  Microsoft.CodeAnalysis.CSharp.Workspaces
  • Main presentation on the code mentioned in 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 CSharpCompilation objects at the end of the Main method
var compilation = CSharpCompilation.Create("HelloWorld")
                                               .AddReferences(
                                                    MetadataReference.CreateFromFile(
                                                        typeof(object).Assembly.Location))
                                               .AddSyntaxTrees(tree);
  • Set breakpoints, start the debugger, see the tips of the compilation.

5 | 0 semantic model SemanticModel


Once you have compiled, you can ask it to provide SemanticModel for any SyntaxTree compilation contains. You can check SemanticModel to answer questions such as "What is the scope of this position is the name?", "Which members can be obtained from this approach?", "What are the variables used in this text block?" And "name / expression refers to What? questions "like.

5 | 1 Example - Bind name


This example shows how to get SemanticModel object HelloWorld SyntaxTree. After obtaining SemanticModel, using a name of the first instruction symbol binding namespace System.

  • Code into the lower 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 System namespace sub-namespace and name printed to the console:

 foreach (var ns in systemSymbol.GetNamespaceMembers())
            {
                Console.WriteLine(ns.Name);
            }
  • Debug debugging enter to view the values ​​for each node. Console Output results are as follows:
Buffers
Collections
ComponentModel
Configuration
Diagnostics
Globalization
IO
Numerics
Reflection
Resources
Runtime
Security
StubHelpers
Text
Threading

5 | 2 Example - binding expression


The preceding example shows how to bind the name to find Symbol. However, in a C # program other than Name of expression can be bound. This example shows how to bind for use with other types of expression - in this case the simple text string.

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, see the value of the relevant node, Console output results are as follows
Intern
IsInterned
Create
Copy
ToString
Normalize
Concat
Format
Insert
Join
PadLeft
PadRight
Remove
Replace
Substring
ToLower
ToLowerInvariant
ToUpper
ToUpperInvariant
Trim
TrimStart
TrimEnd

6 | 0 summary


This article demonstrates the semantic analysis, two examples demonstrate binding Name Symbol lookup and binding expressions we can obtain the following knowledge points are:

Get the syntax tree root: (CompilationUnitSyntax) tree.GetRoot ()

用于创建CSharpCompilation对象:CSharpCompilation.Create("HelloWorld").AddReferences( MetadataReference.CreateFromFile( typeof(object).Assembly.Location)) .AddSyntaxTrees(tree)

Configured to acquire model: compilation.GetSemanticModel (tree);

Get the Name Information Symbol: model.GetSymbolInfo (root.Usings [0] .Name);

You can get specific namespace name: (INamespaceSymbol) nameInfo.Symbol;

Get the current namespace at all members: systemSymbol.GetNamespaceMembers ()

Get literal expression: root.DescendantNodes () OfType <LiteralExpressionSyntax> ().

Gets the Type information model.GetTypeInfo (helloWorldString)

For specific Type Type (INamedTypeSymbol) literalInfo.Type;

The return value is acquired string, the disclosed method of the type: Method in stringTypeSymbol.GetMembers from () OfType <IMethodSymbol> () WHERE method.ReturnType.Equals (stringTypeSymbol) && method.DeclaredAccessibility == Accessibility.Public SELECT.  Method.Name

7 | 0 Source


csharpfandemo

8 | 0 reference links


Getting Started C# Semantic Analysis

 

Original article: https://www.cnblogs.com/fancunwei/p/9855834.html

1 | 0 prerequisite


Visual Studio 2017

.NET Compiler Platform SDK

Rosyln entry (a) -C # parsing

2 | 0 Profile


Today, Visual Basic and C # compiler is a black box: a text input and output bytes, an intermediate stage of the pipeline is not compiled transparency. Use .NET compiler platform (formerly known as "Roslyn"), and tool developers can use to analyze and understand the code compiler uses the same data structures and algorithms.

In this article, we will explore Symbol and BindingAPI. To see through the API syntax parser, the syntax tree for reasoning and construct their utility.

3 | 0 understanding compile and symbols


This syntax API allows you to see the structure of the program. Usually, however, you need more extensive information about the program semantics or meaning. Although loosely code fragment can be parsed separately, but isolated proposed, such as "What type of the variable is" not the type of problems makes sense. Meaning Type the name may depend assembly references, namespace import or other code files. That's where Compilation class.

Compile a single project similar to the compiler sees, represents everything you need to compile the Visual Basic or C # programs, such as assembly references, and compiler options to compile the source file set. With this context, you can deduce the meaning of the code. Compiler allows you to find symbol - type, namespace, and members of entities such as variable names and other expressions references. The procedure name and expressions and symbols (Symbols) associated with the called Binding.

Like with SyntaxTree, Compilation is an abstract class derived class has a specific language. When you create Compilation instance, you must call the factory method on CSharpCompilation (or VisualBasicCompilation) class.

4 | 0 Demo - create compilation


  • Introduced Nuget
  Microsoft.CodeAnalysis.CSharp
 
  Microsoft.CodeAnalysis.CSharp.Workspaces
  • Main presentation on the code mentioned in 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 CSharpCompilation objects at the end of the Main method
var compilation = CSharpCompilation.Create("HelloWorld")
                                               .AddReferences(
                                                    MetadataReference.CreateFromFile(
                                                        typeof(object).Assembly.Location))
                                               .AddSyntaxTrees(tree);
  • Set breakpoints, start the debugger, see the tips of the compilation.

5 | 0 semantic model SemanticModel


Once you have compiled, you can ask it to provide SemanticModel for any SyntaxTree compilation contains. You can check SemanticModel to answer questions such as "What is the scope of this position is the name?", "Which members can be obtained from this approach?", "What are the variables used in this text block?" And "name / expression refers to What? questions "like.

5 | 1 Example - Bind name


This example shows how to get SemanticModel object HelloWorld SyntaxTree. After obtaining SemanticModel, using a name of the first instruction symbol binding namespace System.

  • Code into the lower 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 System namespace sub-namespace and name printed to the console:

 foreach (var ns in systemSymbol.GetNamespaceMembers())
            {
                Console.WriteLine(ns.Name);
            }
  • Debug debugging enter to view the values ​​for each node. Console Output results are as follows:
Buffers
Collections
ComponentModel
Configuration
Diagnostics
Globalization
IO
Numerics
Reflection
Resources
Runtime
Security
StubHelpers
Text
Threading

5 | 2 Example - binding expression


The preceding example shows how to bind the name to find Symbol. However, in a C # program other than Name of expression can be bound. This example shows how to bind for use with other types of expression - in this case the simple text string.

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, see the value of the relevant node, Console output results are as follows
Intern
IsInterned
Create
Copy
ToString
Normalize
Concat
Format
Insert
Join
PadLeft
PadRight
Remove
Replace
Substring
ToLower
ToLowerInvariant
ToUpper
ToUpperInvariant
Trim
TrimStart
TrimEnd

6 | 0 summary


This article demonstrates the semantic analysis, two examples demonstrate binding Name Symbol lookup and binding expressions we can obtain the following knowledge points are:

Get the syntax tree root: (CompilationUnitSyntax) tree.GetRoot ()

用于创建CSharpCompilation对象:CSharpCompilation.Create("HelloWorld").AddReferences( MetadataReference.CreateFromFile( typeof(object).Assembly.Location)) .AddSyntaxTrees(tree)

Configured to acquire model: compilation.GetSemanticModel (tree);

Get the Name Information Symbol: model.GetSymbolInfo (root.Usings [0] .Name);

You can get specific namespace name: (INamespaceSymbol) nameInfo.Symbol;

Get the current namespace at all members: systemSymbol.GetNamespaceMembers ()

Get literal expression: root.DescendantNodes () OfType <LiteralExpressionSyntax> ().

Gets the Type information model.GetTypeInfo (helloWorldString)

For specific Type Type (INamedTypeSymbol) literalInfo.Type;

The return value is acquired string, the disclosed method of the type: Method in stringTypeSymbol.GetMembers from () OfType <IMethodSymbol> () WHERE method.ReturnType.Equals (stringTypeSymbol) && method.DeclaredAccessibility == Accessibility.Public SELECT.  Method.Name

7 | 0 Source


csharpfandemo

8 | 0 reference links


Getting Started C# Semantic Analysis

 

Original article: https://www.cnblogs.com/fancunwei/p/9855834.html

Guess you like

Origin www.cnblogs.com/bigmango/p/11407214.html