aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Scripting/Tango.Scripting.Basic/Project.cs
blob: ddf61e124e4151bb05c393b0e18ea25a7d5a3bcb (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
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tango.Core;
using Tango.Core.IO;
using Tango.Scripting.Core;
using System.IO;

namespace Tango.Scripting.Basic
{
    public class Project : ExtendedObject
    {
        public String Name { get; set; }

        public ApartmentState ApartmentState { get; set; }

        public ObservableCollection<ReferenceAssembly> ReferenceAssemblies { get; set; }

        [JsonIgnore]
        public ObservableCollection<Assembly> ReferenceAssembliesLoaded { get; set; }

        public ObservableCollection<Script> Scripts { get; set; }

        public ObservableCollection<IScriptSource> AdditionalScripts
        {
            get
            {
                return Scripts.Where(x => !x.IsEntryPoint).Cast<IScriptSource>().ToObservableCollection();
            }
        }

        public Project()
        {
            ApartmentState = ApartmentState.MTA;

            ReferenceAssemblies = new ObservableCollection<ReferenceAssembly>();
            ReferenceAssemblies.CollectionChanged += ReferenceAssemblies_CollectionChanged;

            ReferenceAssembliesLoaded = new ObservableCollection<Assembly>();
            Scripts = new ObservableCollection<Script>();
            Scripts.CollectionChanged += (x, e) => { RaisePropertyChanged(nameof(AdditionalScripts)); };
        }

        private void ReferenceAssemblies_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            LoadReferenceAssemblies();
        }

        private void LoadReferenceAssemblies()
        {
            ReferenceAssembliesLoaded.Clear();

            foreach (var type in ReferenceAssemblies)
            {
                ReferenceAssembliesLoaded.Add(type.FromType.Assembly);
            }
        }

        public static Project New(String name, String code)
        {
            Project p = new Project();

            p.Name = name;

            p.ReferenceAssemblies.Add(new ReferenceAssembly() { FromType = typeof(String) });
            p.ReferenceAssemblies.Add(new ReferenceAssembly() { FromType = typeof(Enumerable) });
            p.ReferenceAssemblies.Add(new ReferenceAssembly() { FromType = typeof(Form) });
            p.ReferenceAssemblies.Add(new ReferenceAssembly() { FromType = typeof(Project) });

            p.Scripts.Add(new Script()
            {
                Name = "main.csx",
                IsEntryPoint = true,
                Code = code,
            });

            return p;
        }

        public Task<CompilationResult> Compile()
        {
            return Task.Factory.StartNew<CompilationResult>(() =>
            {
                var result = new CompilationResult();
                var tempFolder = TemporaryManager.CreateFolder(Name);
                result.TemporaryProjectPath = tempFolder;

                String mainScriptCode = String.Empty;

                foreach (var script in Scripts)
                {
                    String code = script.Code;
                    String codeFile = Path.Combine(tempFolder, script.Name);

                    String loadingString = String.Empty;

                    foreach (var file in Scripts.Where(x => !x.IsEntryPoint && script != x).Select(x => Path.Combine(tempFolder, x.Name)))
                    {
                        loadingString = $"#load \"{file}\"\n";
                    }

                    code = loadingString + code;

                    if (!script.IsEntryPoint)
                    {


                        //foreach (var match in Regex.Matches(code, "#load \".+\"").OfType<Match>())
                        //{
                        //    String line = match.ToString();
                        //    var pathMatch = Regex.Match(line, "(?<=\")(.*?)(?=\")");
                        //    if (pathMatch.Success)
                        //    {
                        //        String path = pathMatch.ToString();

                        //        if (!System.IO.Path.IsPathRooted(path))
                        //        {
                        //            StringBuilder builder = new StringBuilder(code);
                        //            builder.Insert(match.Index + pathMatch.Index, System.IO.Path.GetFullPath(tempFolder + "\\"));
                        //            code = builder.ToString();
                        //        }
                        //    }
                        //}



                        File.WriteAllText(codeFile, code);
                    }
                    else
                    {
                        code += Environment.NewLine + Environment.NewLine + "return new Program().OnExecute(GlobalContext);";
                        mainScriptCode = code;
                    }
                }

                var scriptOptions = ScriptOptions.Default.WithReferences(ReferenceAssembliesLoaded);

                var s = CSharpScript.Create<object>(mainScriptCode, scriptOptions, typeof(GlobalObject));
                result.Script = s;

                var compileResults = s.Compile();

                foreach (var error in compileResults.Where(x => x.Severity == Microsoft.CodeAnalysis.DiagnosticSeverity.Error || x.Severity == Microsoft.CodeAnalysis.DiagnosticSeverity.Warning))
                {
                    CompilationError cError = new CompilationError();
                    cError.File = System.IO.Path.GetFileName(error.Location.SourceTree.FilePath);
                    cError.Message = error.GetMessage();
                    cError.Severity = error.Severity;
                    var line = error.Location.GetMappedLineSpan();
                    cError.Line = line.StartLinePosition.Line + 1;
                    cError.Column = line.StartLinePosition.Character + 1;
                    cError.Length = line.EndLinePosition.Character - line.StartLinePosition.Character;
                    result.Errors.Add(cError);
                }

                return result;
            });
        }

        public async Task<ProjectSession> Run(IContext context)
        {
            var result = await Compile();

            if (result.Errors.Count > 0)
            {
                throw new InvalidOperationException("There were compilation errors.");
            }

            Thread scriptThread = null;
            ProjectSession session = null;

            session = new ProjectSession(this, () =>
            {
                scriptThread.Abort();
            });

            scriptThread = new Thread(() =>
            {
                try
                {
                    var runResult = result.Script.RunAsync(globals: new GlobalObject() { GlobalContext = context }).Result;
                    session.Completed(runResult.ReturnValue);
                }
                catch (ThreadAbortException)
                {

                }
                catch (Exception ex)
                {
                    session.Failed(ex.InnerException);
                }
            });

            scriptThread.SetApartmentState(ApartmentState);
            scriptThread.IsBackground = true;
            scriptThread.Start();

            return session;
        }
    }
}