Weaving on WebMAP

On WebMAP 5, weaving is leveraged to perform some of the changes required so the code can be run on web environments.

By weaving we mean a process that can insert or modify the application code during the compilation process, but in a way that the developers do not have to worry about these modifications, and also in a way that can improve performance, compared with others interception solutions, because it will add little overhead during runtime.

How does Weaving Work?

A program that takes source, and modifies it by inserting aspect-specific logic at joint points. The result are sections of non-visible code in the original code that are executed during runtime.

The point is to keep the modifications required to interact with WebMAP Core Services. To know where and what should we weave into, attributes are used as markers and during the weaving analyzer process the class meta data is recollected and determine the elements that need to be generated.

Creating a new Weaving Extension

A weaving extension is a .NET class library that will be published as a NuGet. It must have a NuGet reference to Mobilize.Weaving, and it will have a structure like:

  • Analyzers

    • Zero or more weaving analyzers

  • build

    • The .props file needed to update the @Plugins property

  • Builders

    • Utility classes for syntax emit

  • Extensions

    • Extensions method to ease some tasks

  • Injectors

    • Zero or more weaving injectors

  • State

    • Classes related to holding state that might be needed or collected by Analyzers or Injectors

Note: Developing Weaving Extensions requires some knowledge of the Roslyn Framework. For more information about Roslyn: https://github.com/dotnet/roslyn#get-started

Analyzer

An analyzer is a class that inherits from Mobilize.Weaving.Roslyn.Structure.Analyzer where T should be the syntax node that will be inspected. It should override the void Analyze(T node) method and inside this method either the AST will be traversed or the semantical model will be used to track information.

Injector

An injector is a class that inherits from Mobilize.Weaving.Roslyn.Structure.Mutation where T should be a syntax node.

This should override the public override T Apply(T node).

  • If you are not modifying this AST just return the same node parameter.

  • If you want to suppress this node return null.

  • If you want to modify this AST then create a new node and return it.

Data collected from previous Analyzers or the semantic model can be used here. Usually this Injector will use the classes from the Builder folder for common AST construction tasks.

Handling State

To hold state you will create a class that implements the IState interface like the following:

public class SomeState : IState
{
    private Dictionary States { get; set; } = new Dictionary();

    public void Add(SomeData state, string key) => this.States.Add(key, state);
    public bool Contains(string key) => this.States.ContainsKey(key);

    public SomeData Get(string key)
    {
        this.States.TryGetValue(key, out var value);
        return value;
    }
}

The previous example shows a state structure that can be used to map from a class qualified name to some SomeData structure.

To recover this state you can just do something like this:

var state = this.Storage.State();

Accessing the Semantic Model

All analyzers and injectors have access to the semantic model using the Model property:

var semanticModel = this.Storage.State().Model;

Debuggable Code Generation

We need to have some considerations when injecting code in order to maintain the debug experience for the user. When we inject code a new file will be generated. In this new file the injected code will introduce differences from the original file. The user will develop and debug based on the file without injection, but in the background the code that is been executed is specified in the generated file.

Useful C# preprocessor directives

#line

#line C# Reference

It lets you modify the compiler's line number and (optionally) the file name output for errors and warnings.

  • The #line default directive returns the line numbering to its default numbering, which counts the lines that were renumbered by the previous directive.

  • The #line 200 directive forces the line number to be 200 (although the default is another) and until the next #line directive.

  • The #line 200 "Form1.cs" directive will report the filename as "Form1.cs".

The #line directive might be used in an automated, intermediate step in the build process. For example, if lines were removed from the original source code file, but you still wanted the compiler to generate output based on the original line numbering in the file, you could remove lines and then simulate the original line numbering with #line.

The #line hidden directive hides the successive lines from the debugger, such that when the developer steps through the code, any lines between a #line hidden and the next #line directive (assuming that it is not another #line hidden directive) will be stepped over. This option can also be used to allow ASP.NET to differentiate between user-defined and machine-generated code. Although ASP.NET is the primary consumer of this feature, it is likely that more source generators will make use of it.

A #line hidden directive does not affect file names or line numbers in error reporting. That is, if an error is encountered in a hidden block, the compiler will report the current file name and line number of the error.

The #line filename directive specifies the file name you want to appear in the compiler output. By default, the actual name of the source code file is used. The file name must be in double quotation marks ("") and must be preceded by a line number.

A source code file can have any number of #line directives.

Code generation best practices

In order to provide a correct debugging behavior for the user, we need to follow some practices during the code generation. Basically to specify how the code been executed will match with the code provided by the user in which he will code and debug.

  1. Because new generated code will not have a corresponding code in the original file, we must generate #line hidden or #line default. If we use the #line hidden directive while debugging there will no be any corresponding line in the original, so this generated code will not be reachable for the debugging. If we use the #line default directive the generated code will be reachable. Notice that using the #line default directive will reset the counter to the generated file. So, if it is necessary to reference after that to the original file, the #line filename directive must be used.

  2. After injecting new code is necessary to reestablish the line counter to maintain the debugging experience. That means that if we have added some new code that would be hidden, after it, when it appears code that is also in the original code, we must specify the location of the code through the #line directive.

    Example

        [Intercepted]
        public Mobilize.WebMAP.WinForms.Button button1
#line 72
        {

#line 73
            get
#line hidden
{
    if ((_Mobilize_LoadedFlag_0 & _Mobilize_Loaded_button1) <= 0)
    {
      // Here some generated code
    }

    return this.button1_k__BackingField;
}
#line 73
  1. We must preserve trivias and compensate them with whitespaces according to the original character position to avoid wrong debug highlighting.

Example 1

In the original file:

        public string property1
        {
            get; set;
        }

In the generated file

#line 1
        public
#line 1
               string
#line 1
                       property1
#line 2
        {
#line 3
            get;
#line 3
                 set;
        }

Example 2

In the original file:

        public void Foo()
        {/*
            comments
            which are trailing trivia of
            method body open brace
                    */goo();//Original First statement
        }

In the generated file

        public void Foo()
        {/*
            comments
            which are trailing trivia of
            method body open brace
                    */
#line hidden
        woo();//new generated statement
#line 6
                      goo();//Original First statement
        }

Last updated