Welcome to mirror list, hosted at ThFree Co, Russian Federation.

EvaluateExpression.cs « BrowserDebugProxy « wasm « sdks - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: d66d6d07f094e6ce6949a1cd0dfd804be3a7a46d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Emit;
using Newtonsoft.Json.Linq;

namespace Microsoft.WebAssembly.Diagnostics
{

    internal class EvaluateExpression
    {

        class FindThisExpression : CSharpSyntaxWalker
        {
            public List<string> thisExpressions = new List<string>();
            public SyntaxTree syntaxTree;
            public FindThisExpression(SyntaxTree syntax)
            {
                syntaxTree = syntax;
            }
            public override void Visit(SyntaxNode node)
            {
                if (node is ThisExpressionSyntax)
                {
                    if (node.Parent is MemberAccessExpressionSyntax thisParent && thisParent.Name is IdentifierNameSyntax)
                    {
                        IdentifierNameSyntax var = thisParent.Name as IdentifierNameSyntax;
                        thisExpressions.Add(var.Identifier.Text);
                        var newRoot = syntaxTree.GetRoot().ReplaceNode(node.Parent, thisParent.Name);
                        syntaxTree = syntaxTree.WithRootAndOptions(newRoot, syntaxTree.Options);
                        this.Visit(GetExpressionFromSyntaxTree(syntaxTree));
                    }
                }
                else
                    base.Visit(node);
            }

            public async Task CheckIfIsProperty(MonoProxy proxy, MessageId msg_id, int scope_id, CancellationToken token)
            {
                foreach (var var in thisExpressions)
                {
                    JToken value = await proxy.TryGetVariableValue(msg_id, scope_id, var, true, token);
                    if (value == null)
                        throw new Exception($"The property {var} does not exist in the current context");
                }
            }
        }

        class FindVariableNMethodCall : CSharpSyntaxWalker
        {
            public List<IdentifierNameSyntax> variables = new List<IdentifierNameSyntax>();
            public List<ThisExpressionSyntax> thisList = new List<ThisExpressionSyntax>();
            public List<InvocationExpressionSyntax> methodCall = new List<InvocationExpressionSyntax>();
            public List<object> values = new List<Object>();

            public override void Visit(SyntaxNode node)
            {
                if (node is IdentifierNameSyntax identifier && !variables.Any(x => x.Identifier.Text == identifier.Identifier.Text))
                    variables.Add(identifier);
                if (node is InvocationExpressionSyntax)
                {
                    methodCall.Add(node as InvocationExpressionSyntax);
                    throw new Exception("Method Call is not implemented yet");
                }
                if (node is AssignmentExpressionSyntax)
                    throw new Exception("Assignment is not implemented yet");
                base.Visit(node);
            }
            public async Task<SyntaxTree> ReplaceVars(SyntaxTree syntaxTree, MonoProxy proxy, MessageId msg_id, int scope_id, CancellationToken token)
            {
                CompilationUnitSyntax root = syntaxTree.GetCompilationUnitRoot();
                foreach (var var in variables)
                {
                    ClassDeclarationSyntax classDeclaration = root.Members.ElementAt(0) as ClassDeclarationSyntax;
                    MethodDeclarationSyntax method = classDeclaration.Members.ElementAt(0) as MethodDeclarationSyntax;

                    JToken value = await proxy.TryGetVariableValue(msg_id, scope_id, var.Identifier.Text, false, token);

                    if (value == null)
                        throw new Exception($"The name {var.Identifier.Text} does not exist in the current context");

                    values.Add(ConvertJSToCSharpType(value["value"]));

                    var updatedMethod = method.AddParameterListParameters(
                        SyntaxFactory.Parameter(
                            SyntaxFactory.Identifier(var.Identifier.Text))
                        .WithType(SyntaxFactory.ParseTypeName(GetTypeFullName(value["value"]))));
                    root = root.ReplaceNode(method, updatedMethod);
                }
                syntaxTree = syntaxTree.WithRootAndOptions(root, syntaxTree.Options);
                return syntaxTree;
            }

            private object ConvertJSToCSharpType(JToken variable)
            {
                var value = variable["value"];
                var type = variable["type"].Value<string>();
                var subType = variable["subtype"]?.Value<string>();

                switch (type)
                {
                    case "string":
                        return value?.Value<string>();
                    case "number":
                        return value?.Value<double>();
                    case "boolean":
                        return value?.Value<bool>();
                    case "object":
                        if (subType == "null")
                            return null;
                        break;
                }
                throw new Exception($"Evaluate of this datatype {type} not implemented yet");
            }

            private string GetTypeFullName(JToken variable)
            {
                var type = variable["type"].ToString();
                var subType = variable["subtype"]?.Value<string>();
                object value = ConvertJSToCSharpType(variable);

                switch (type)
                {
                    case "object":
                        {
                            if (subType == "null")
                                return variable["className"].Value<string>();
                            break;
                        }
                    default:
                        return value.GetType().FullName;
                }
                throw new Exception($"Evaluate of this datatype {type} not implemented yet");
            }
        }

        static SyntaxNode GetExpressionFromSyntaxTree(SyntaxTree syntaxTree)
        {
            CompilationUnitSyntax root = syntaxTree.GetCompilationUnitRoot();
            ClassDeclarationSyntax classDeclaration = root.Members.ElementAt(0) as ClassDeclarationSyntax;
            MethodDeclarationSyntax methodDeclaration = classDeclaration.Members.ElementAt(0) as MethodDeclarationSyntax;
            BlockSyntax blockValue = methodDeclaration.Body;
            ReturnStatementSyntax returnValue = blockValue.Statements.ElementAt(0) as ReturnStatementSyntax;
            InvocationExpressionSyntax expressionInvocation = returnValue.Expression as InvocationExpressionSyntax;
            MemberAccessExpressionSyntax expressionMember = expressionInvocation.Expression as MemberAccessExpressionSyntax;
            ParenthesizedExpressionSyntax expressionParenthesized = expressionMember.Expression as ParenthesizedExpressionSyntax;
            return expressionParenthesized.Expression;
        }

        internal static async Task<string> CompileAndRunTheExpression(MonoProxy proxy, MessageId msg_id, int scope_id, string expression, CancellationToken token)
        {
            FindVariableNMethodCall findVarNMethodCall = new FindVariableNMethodCall();
            string retString;
            SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(@"
				using System;
				public class CompileAndRunTheExpression
				{
					public string Evaluate()
					{
						return (" + expression + @").ToString(); 
					}
				}");

            FindThisExpression findThisExpression = new FindThisExpression(syntaxTree);
            var expressionTree = GetExpressionFromSyntaxTree(syntaxTree);
            findThisExpression.Visit(expressionTree);
            await findThisExpression.CheckIfIsProperty(proxy, msg_id, scope_id, token);
            syntaxTree = findThisExpression.syntaxTree;

            expressionTree = GetExpressionFromSyntaxTree(syntaxTree);
            findVarNMethodCall.Visit(expressionTree);

            syntaxTree = await findVarNMethodCall.ReplaceVars(syntaxTree, proxy, msg_id, scope_id, token);

            MetadataReference[] references = new MetadataReference[]
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location)
            };

            CSharpCompilation compilation = CSharpCompilation.Create(
                "compileAndRunTheExpression",
                syntaxTrees: new[] { syntaxTree },
                references: references,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
            using (var ms = new MemoryStream())
            {
                EmitResult result = compilation.Emit(ms);
                ms.Seek(0, SeekOrigin.Begin);
                Assembly assembly = Assembly.Load(ms.ToArray());
                Type type = assembly.GetType("CompileAndRunTheExpression");
                object obj = Activator.CreateInstance(type);
                var ret = type.InvokeMember("Evaluate",
                    BindingFlags.Default | BindingFlags.InvokeMethod,
                    null,
                    obj,
                    findVarNMethodCall.values.ToArray());
                retString = ret.ToString();
            }
            return retString;
        }
    }
}