Esempio n. 1
0
        public CompiledFile GenerateSource(Scope globalScope)
        {
            CompiledFile source = new CompiledFile(Context.Names.GetStateBaseFileName());

            WriteSourcePrologue(source.Stream);

            List <PEvent> events = new List <PEvent>();

            foreach (IPDecl decl in globalScope.AllDecls)
            {
                switch (decl)
                {
                case PEvent pEvent:
                    if (!pEvent.IsBuiltIn)
                    {
                        events.Add(pEvent);
                    }
                    break;

                default:
                    // Just ignore.
                    break;
                }
            }
            WriteStateBaseClass(source.Stream, events);

            return(source);
        }
Esempio n. 2
0
        public void WriteFile(CompiledFile file)
        {
            var fileName = Path.Combine(outputDirectory.FullName, file.FileName);

            File.WriteAllText(fileName, file.Contents);
            outputFiles.Add(new FileInfo(fileName));
        }
Esempio n. 3
0
        private CompiledFile WriteMonitor(Machine machine)
        {
            CompiledFile source = new CompiledFile(Context.GetAjFileName(machine));

            WriteSourcePrologue(source.Stream);
            WriteEventHandlerSignature(source.Stream, machine);
            WriteSpec(source.Stream, machine);

            return(source);
        }
Esempio n. 4
0
        private CompiledFile WriteMonitors(IEnumerable <Machine> specMachines)
        {
            CompiledFile source = new CompiledFile(Context.GetAjFileName());

            WriteSourcePrologue(source.Stream);
            WriteEventHandlerSignature(source.Stream, specMachines);
            WriteSpec(source.Stream);

            return(source);
        }
Esempio n. 5
0
        private CompiledFile WriteMonitors(IEnumerable <Machine> specMachines)
        {
            CompiledFile source = new CompiledFile(Context.GetAjFileName());

            WriteSourcePrologue(source.Stream);
            foreach (Machine machine in specMachines)
            {
                WriteParentClass(source.Stream, machine);
            }
            WriteBaseAspect(source.Stream, specMachines);

            return(source);
        }
Esempio n. 6
0
 public void WriteFile(CompiledFile file)
 {
     if (Path.GetExtension(file.FileName) == ".aj")
     {
         string outputPath = Path.Combine(aspectjOutputDirectory.FullName, file.FileName);
         File.WriteAllText(outputPath, file.Contents);
     }
     else
     {
         string outputPath = Path.Combine(outputDirectory.FullName, file.FileName);
         File.WriteAllText(outputPath, file.Contents);
     }
 }
Esempio n. 7
0
 public static void SaveFile(CompiledFile file)
 {
     using (var fileStream = new FileStream(file.FilePath, FileMode.OpenOrCreate))
     {
         using (var writer = new BinaryWriter(fileStream))
         {
             foreach (byte val in file.Bytes)
             {
                 writer.Write(val);
             }
         }
     }
 }
Esempio n. 8
0
 private void AddCompiledFile(string /*!*/ fullPath, ScriptCode /*!*/ compiledCode)
 {
     if (_context.RubyOptions.SavePath != null)
     {
         lock (_compiledFileMutex) {
             // TODO: allocate eagerly (as soon as config gets fixed)
             if (_compiledFiles == null)
             {
                 _compiledFiles = new Dictionary <string, CompiledFile>();
             }
             _compiledFiles[fullPath] = new CompiledFile(compiledCode);
         }
     }
 }
Esempio n. 9
0
        private bool TryGetCompiledFile(string /*!*/ fullPath, out CompiledFile compiledFile)
        {
            if (!_context.RubyOptions.LoadFromDisk)
            {
                compiledFile = default(CompiledFile);
                return(false);
            }

            lock (_compiledFileMutex) {
                if (_compiledFiles == null)
                {
                    _compiledFiles = LoadCompiledCode();
                }

                return(_compiledFiles.TryGetValue(fullPath, out compiledFile));
            }
        }
Esempio n. 10
0
        CompiledFile WriteEvents(List <PEvent> events)
        {
            CompiledFile source = new CompiledFile(Context.Names.GetEventFileName());

            WriteSourcePrologue(source.Stream);

            BeforeSeparator separator = new BeforeSeparator(() => Context.WriteLine(source.Stream));

            foreach (PEvent pEvent in events)
            {
                separator.beforeElement();
                WriteEventClass(source.Stream, pEvent);
            }

            WriteSourceEpilogue(source.Stream);

            return(source);
        }
        public static CompiledFile LoadFile(string filePath)
        {
            var file = new CompiledFile();

            file.FilePath = filePath;

            using (var readStream = new FileStream(filePath, FileMode.Open))
            {
                using (var reader = new BinaryReader(readStream))
                {
                    while (reader.BaseStream.Position != reader.BaseStream.Length)
                    {
                        file.Bytes.Add(reader.ReadByte());
                    }
                }
            }

            return(file);
        }
Esempio n. 12
0
        private Dictionary <string, CompiledFile> /*!*/ LoadCompiledCode()
        {
            Debug.Assert(_context.RubyOptions.LoadFromDisk);

            Dictionary <string, CompiledFile> result = new Dictionary <string, CompiledFile>();

            Utils.Log("LOADING", "LOADER");

            ScriptCode[] codes = SavableScriptCode.LoadFromAssembly(_context.DomainManager,
                                                                    Assembly.Load(Path.GetFileName(_context.RubyOptions.MainFile))
                                                                    );

            for (int i = 0; i < codes.Length; i++)
            {
                string path     = codes[i].SourceUnit.Path;
                string fullPath = Platform.GetFullPath(path);
                result[fullPath] = new CompiledFile(codes[i]);
            }

            return(result);
        }
Esempio n. 13
0
            public void WriteFile(CompiledFile file)
            {
                var nameLength  = file.FileName.Length;
                var headerWidth = Math.Max(40, nameLength + 4);
                var hdash       = new string('=', headerWidth);

                stdout.WriteLine(hdash);
                var prePadding  = (headerWidth - nameLength) / 2 - 1;
                var postPadding = headerWidth - prePadding - nameLength - 2;

                stdout.WriteLine($"={new string(' ', prePadding)}{file.FileName}{new string(' ', postPadding)}=");
                stdout.WriteLine(hdash);
                stdout.Write(file.Contents);
                if (!file.Contents.EndsWith(Environment.NewLine))
                {
                    stdout.WriteLine();
                }

                stdout.WriteLine(hdash);
                stdout.WriteLine();
            }
Esempio n. 14
0
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom")] // TODO
        private Dictionary<string, CompiledFile>/*!*/ LoadCompiledCode() {
            Debug.Assert(_context.RubyOptions.LoadFromDisk);

            Dictionary<string, CompiledFile> result = new Dictionary<string, CompiledFile>();
            Utils.Log("LOADING", "LOADER");

            ScriptCode[] codes = ScriptCode.LoadFromAssembly(_context.DomainManager,
                Assembly.Load(Path.GetFileName(_context.RubyOptions.MainFile))
            );

            for (int i = 0; i < codes.Length; i++) {
                string path = codes[i].SourceUnit.Path;
                string fullPath = Platform.GetFullPath(path);
                result[fullPath] = new CompiledFile(codes[i]);
            }

            return result;
        }
Esempio n. 15
0
 public CompiledFileViewModel()
 {
     m_UnderlyingFile       = new CompiledFile();
     m_AreAnyChangesUnsaved = false;
 }
Esempio n. 16
0
 public CompiledFileViewModel(CompiledFile underlying)
 {
     m_UnderlyingFile       = underlying;
     m_AreAnyChangesUnsaved = false;
 }
Esempio n. 17
0
        private static Dictionary <string, (int order, MemberInfo member)> FindCommands(CompiledFile compiledFile)
        {
            Dictionary <string, (int order, MemberInfo member)> members = new Dictionary <string, (int order, MemberInfo member)>();

            foreach (var command in Commands)
            {
                if (command.Value == PipeArrow)
                {
                    members.Add(command.Value, (command.Key, PipeMethod));
                }
                else
                {
                    foreach (var file in Files)
                    {
                        var memberCommand = compiledFile.Members.SingleOrDefault(x => StringEquals(x.Name, command.Value));
                        if (memberCommand != null)
                        {
                            if (members.ContainsKey(command.Value))
                            {
                                Console.Error.WriteLine($"Exit Code = -2; \"Duplicate command exists of name: {command}\"");
                                Environment.Exit(-2);
                            }

                            members.Add(command.Value, (command.Key, memberCommand));
                        }
                    }
                }
            }

            return(members);
        }
Esempio n. 18
0
        private void compileProcess_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
        {
            if (compileProcess != null) // Skip when cancelling compilation in MainForm
            {
                if (e.Data != null)
                {
                    compileResultTextList.Add(e.Data);
                }
                else
                {
                    compileProcess.Close();
                    compileProcess = null;

                    BeginInvoke((Action)(() =>
                    {
                        var cr = new CompileResult(compileResultTextList);

                        switch (settings.ResultForm)
                        {
                        case 0:              // Display
                            if (crf == null) // Closed compilation result form
                            {
                                crf = new CompileResultForm();
                                crf.FormClosed += (sender2, e2) => { crf = null; };
                                crf.SetResult(cr);
                                crf.Show();
                            }
                            else
                            {
                                crf.SetResult(cr);
                            }
                            break;

                        case 1:     // Display when compilation failed
                            if (cr.Success)
                            {
                                if (crf != null)
                                {
                                    crf.Close();
                                }
                            }
                            else
                            {
                                if (crf == null)        // Closed compilation result form
                                {
                                    crf = new CompileResultForm();
                                    crf.FormClosed += (sender2, e2) => { crf = null; };
                                    crf.SetResult(cr);
                                    crf.Show();
                                }
                                else
                                {
                                    crf.SetResult(cr);
                                }
                            }
                            break;

                        case 2:     // Hide
                            if (crf != null)
                            {
                                crf.Close();
                            }
                            break;

                        default:
                            break;
                        }

                        if (cr.Success)
                        {
                            toolStripStatusLabel.Text = "Compiled";
                        }
                        else
                        {
                            toolStripStatusLabel.Text = "Compilation failed";
                            if (settings.SoundNotification)
                            {
                                System.Media.SystemSounds.Hand.Play();
                            }
                        }

                        if (cr.Success && settings.AutoPlay)
                        {
                            if (!File.Exists(settings.PlayerPath))
                            {
                                MessageBox.Show("Player was not found.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                toolStripStatusLabel.Text = "Autoplay failed";
                                return;
                            }

                            toolStripStatusLabel.Text = "Sending the song to the player...";
                            statusStrip.Update();
                            try
                            {
                                playProcess?.Close();

                                playProcess = new System.Diagnostics.Process();
                                playProcess.StartInfo.FileName = settings.PlayerPath;
                                playProcess.StartInfo.Arguments = Path.Combine(Path.GetDirectoryName(settings.MMLPath), CompiledFile.GetFileName(settings.MMLPath));
                                playProcess.StartInfo.WorkingDirectory = Path.GetDirectoryName(settings.MMLPath);

                                playProcess.Start();
                            }
                            catch
                            {
                                playProcess.Close();
                                playProcess = null;
                                MessageBox.Show("Failed to play the compiled data.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                toolStripStatusLabel.Text = "Autoplay failed";
                                return;
                            }

                            toolStripStatusLabel.Text = "Success to send the song to the player";
                        }
                    }));
                }
            }
        }
Esempio n. 19
0
        static void Main(string[] args)
        {
            int i = 0;

            args.ToList().ForEach(x => Commands.Add(i++, x));


            LoadFiles();

            CompiledFile compiledFile = CompileAssembly();

            Dictionary <string, (int order, MemberInfo member)> commandMembers = FindCommands(compiledFile);

            List <MemberInfo> commandRunOrder = commandMembers.Select(x => x.Value).OrderBy(x => x.order).Select(x => x.member).ToList();

            object previousVariable = null;
            bool   pipe             = false;

            foreach (var command in commandRunOrder)
            {
                try
                {
                    if (command is MethodInfo mi)
                    {
                        object output;
                        if (pipe == true)
                        {
                            output = mi.Invoke(null, new object[] { previousVariable });
                        }
                        else
                        {
                            output = mi.Invoke(null, null);
                        }

                        if (output != null)
                        {
                            previousVariable = output;
                            Console.WriteLine(GetStringOutput(output));
                        }
                    }
                    else if (command is PropertyInfo pi)
                    {
                        var output = pi.GetValue(null);
                        previousVariable = output;
                        Console.WriteLine(GetStringOutput(output));
                    }
                    else if (command is FieldInfo fi)
                    {
                        if (command == PipeMethod)
                        {
                            pipe = true;
                            continue;
                        }

                        var output = fi.GetValue(null);
                        previousVariable = output;
                        Console.WriteLine(GetStringOutput(output));
                    }

                    pipe = false;
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine(ex.Message);
                    Exception wEx = ex;
                    while (wEx.InnerException != null)
                    {
                        Console.Error.WriteLine(wEx.InnerException.Message);
                        wEx = wEx.InnerException;
                    }

                    Console.Error.WriteLine($"Exit Code = -3; \"Command {command.Name} could not be run\"");

#if DEBUG
                    Console.ReadKey();
#endif

                    Environment.Exit(-3);
                }
            }
#if DEBUG
            Console.ReadKey();
#endif
        }
Esempio n. 20
0
        public void WriteFile(CompiledFile file)
        {
            string outputPath = Path.Combine(outputDirectory.FullName, file.FileName);

            File.WriteAllText(outputPath, file.Contents);
        }
Esempio n. 21
0
        private bool TryGetCompiledFile(string/*!*/ fullPath, out CompiledFile compiledFile) {
            if (!_context.RubyOptions.LoadFromDisk) {
                compiledFile = default(CompiledFile);
                return false;
            }

            lock (_compiledFileMutex) {
                if (_compiledFiles == null) {
                    _compiledFiles = LoadCompiledCode();
                }

                return _compiledFiles.TryGetValue(fullPath, out compiledFile);
            }
        }
Esempio n. 22
0
 private void AddCompiledFile(string/*!*/ fullPath, ScriptCode/*!*/ compiledCode) {
     if (_context.RubyOptions.SavePath != null) {
         lock (_compiledFileMutex) {
             // TODO: allocate eagerly (as soon as config gets fixed)
             if (_compiledFiles == null) {
                 _compiledFiles = new Dictionary<string, CompiledFile>();
             }
             _compiledFiles[fullPath] = new CompiledFile(compiledCode);
         }
     }
 }
Esempio n. 23
0
        public static CompiledFile Read(string fileName, string Code, List <string> foundAssemblies, out string RawCode)
        {
            string Name = $"CsTask{Guid.NewGuid().ToString().Replace("-", "")}";

            RawCode = Code;
            CompiledFile file = new CompiledFile();

            file.Name = fileName;

            SyntaxTree syntax     = null;
            bool       retry      = false;
            bool       wrapStatic = false;

            file.ReferencedAssemblies = foundAssemblies ?? new List <string>();

RETRY:

            file.ReferencedAssemblies = file.ReferencedAssemblies.Distinct().ToList();

            if (retry)            //Failed and a CS0116 error, retry with wrapping in static classs
            {
                var root   = syntax.GetRoot() as CompilationUnitSyntax;
                var usings = root.Usings.ToFullString();

                SyntaxList <MemberDeclarationSyntax> newMembers = new SyntaxList <MemberDeclarationSyntax>();

                var members = root.Members;
                foreach (var mem in members)
                {
                    var staticToken     = SyntaxFactory.Token(SyntaxKind.StaticKeyword);
                    var realStaticToken = staticToken.WithTrailingTrivia(SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " "));

                    if (mem is MethodDeclarationSyntax method)
                    {
                        if (!method.Modifiers.Any(x => x.Text == staticToken.Text))
                        {
                            newMembers = newMembers.Add(method.AddModifiers(realStaticToken));
                        }
                        else
                        {
                            newMembers = newMembers.Add(method);
                        }
                    }
                    else if (mem is PropertyDeclarationSyntax prop)
                    {
                        if (!prop.Modifiers.Any(x => x.Text == staticToken.Text))
                        {
                            newMembers = newMembers.Add(prop.AddModifiers(realStaticToken));
                        }
                        else
                        {
                            newMembers = newMembers.Add(prop);
                        }
                    }
                    else if (mem is FieldDeclarationSyntax field)
                    {
                        if (!field.Modifiers.Any(x => x.Text == staticToken.Text))
                        {
                            newMembers = newMembers.Add(field.AddModifiers(realStaticToken));
                        }
                        else
                        {
                            newMembers = newMembers.Add(field);
                        }
                    }
                    else
                    {
                        newMembers = newMembers.Add(mem);
                    }
                }

                root = root.WithMembers(newMembers);

                var txt     = root.GetText();
                var fullTxt = txt.ToString();
                RawCode = fullTxt;
                if (!string.IsNullOrWhiteSpace(usings))
                {
                    fullTxt = fullTxt.Replace(usings, "");
                }

                if (wrapStatic)
                {
                    Code =
                        $@"
{usings}

static class {Name}{{

{fullTxt}

}}

";
                }
                else
                {
                    Code =
                        $@"
{usings}

{fullTxt}


";
                }

                wrapStatic = false;
                retry      = false;
            }


            syntax = CSharpSyntaxTree.ParseText(Code);

            List <MetadataReference> references = new List <MetadataReference>
            {
                MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Enumerable).GetTypeInfo().Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Regex).GetTypeInfo().Assembly.Location)
            };

            foreach (var ass in file.ReferencedAssemblies)
            {
                Assembly loaded = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(ass));
                references.Add(MetadataReference.CreateFromFile(loaded.Location));
            }

            CSharpCompilation compilation = CSharpCompilation.Create(
                Name,
                syntaxTrees: new[] { syntax },
                references: references,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var ms = new MemoryStream())
            {
                EmitResult result = compilation.Emit(ms);

                if (!result.Success)
                {
                    if (result.Diagnostics.Any(x => x.ToString().Contains("CS0116")))                    //Failed and a CS0116 error, retry with wrapping in static classs
                    {
                        wrapStatic = true;
                        retry      = true;
                    }

                    IEnumerable <Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
                                                                                 diagnostic.IsWarningAsError ||
                                                                                 diagnostic.Severity == DiagnosticSeverity.Error);

                    if (failures.Any(x => x.Id == "CS0012"))
                    {
                        var infoMember      = failures.FirstOrDefault().GetType().GetMembers().SingleOrDefault(x => x.Name == "get_Info") as MethodInfo;
                        var argumentField   = infoMember.ReturnType.GetTypeInfo().GetDeclaredField("_arguments");
                        var errorAssemblies = failures.Where(x => x.Id == "CS0012").ToList();
                        foreach (var ass in errorAssemblies)
                        {
                            object   info         = infoMember.Invoke(ass, null);
                            object[] arguments    = argumentField.GetValue(info) as object[];
                            var      assemblyName = arguments[1].ToString();
                            file.ReferencedAssemblies.Add(assemblyName);
                        }

                        retry = true;
                    }

                    if (retry)
                    {
                        goto RETRY;
                    }

                    foreach (Diagnostic diagnostic in failures)
                    {
                        Console.Error.WriteLine(diagnostic.ToString());
                    }
                    Console.Error.WriteLine($"Exit Code = -1; \"Failed to compile\"");

#if DEBUG
                    Console.ReadKey();
#endif

                    Environment.Exit(-1);
                }
                else
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    file.LoadedAssembly = AssemblyLoadContext.Default.LoadFromStream(ms);
                }
            }

            ////Remove all get_, set_, k__BackingFields, and .cctor runtime members.
            file.Members = file.LoadedAssembly.DefinedTypes.SelectMany(x => x.DeclaredMembers.Where(y => !y.Name.Contains("k__BackingField"))).ToList();
            file.Members = file.Members.Where(x =>
            {
                if (x is MethodInfo mi)
                {
                    return(!mi.Attributes.HasFlag(MethodAttributes.SpecialName));
                }
                else if (x is ConstructorInfo ci)
                {
                    return(!ci.Attributes.HasFlag(MethodAttributes.SpecialName));
                }

                return(true);
            }).ToList();

            return(file);
        }