public static Type GetTypeFromShortName(this AssemblyCSharpBuilder builder, string typeName)
        {
            Assembly assembly = builder.GetAssembly();

            if (assembly == null)
            {
                return(null);
            }


            var type = assembly.GetTypes().First(item => item.Name == typeName);

            if (type == null)
            {
                CompilationException exception = new CompilationException($"无法在程序集 {builder.Compiler.AssemblyName} 中找到该类型 {typeName}!");
                if (builder.Exceptions.Count == 0)
                {
                    exception.ErrorFlag = ExceptionKind.Type;
                }
                else
                {
                    exception.ErrorFlag = ExceptionKind.Assembly;
                }
                builder.Exceptions.Add(exception);
            }
            return(type);
        }
        public static Delegate GetDelegateFromShortName(this AssemblyCSharpBuilder builder, string typeName, string methodName, Type delegateType, object binder = null)
        {
            var info = builder.GetMethodFromShortName(typeName, methodName);

            if (info == null)
            {
                return(null);
            }


            try
            {
                return(info.CreateDelegate(delegateType, binder));
            }
            catch (Exception ex)
            {
                CompilationException exception = new CompilationException($"在类型 {typeName} 中找到的方法 {methodName} 向 {delegateType.FullName} 转换时出错!");
                if (builder.Exceptions.Count == 0)
                {
                    exception.ErrorFlag = ExceptionKind.Delegate;
                }
                else
                {
                    exception.ErrorFlag = ExceptionKind.Assembly;
                }
                builder.Exceptions.Add(exception);
            }
            return(null);
        }
Beispiel #3
0
 public IComplier()
 {
     ComplieException = new CompilationException();
     _domain          = DomainManagment.Default;
     References       = new List <PortableExecutableReference>(_domain.ReferencesCache);
     SyntaxInfos      = new SyntaxOption();
     SyntaxExceptions = SyntaxInfos.SyntaxExceptions;
 }
Beispiel #4
0
 public ICompiler()
 {
     CompileException = new CompilationException();
     _domain          = DomainManagment.Default;
     References       = new List <PortableExecutableReference>();
     SyntaxInfos      = new SyntaxOption();
     SyntaxExceptions = SyntaxInfos.SyntaxExceptions;
     ErrorActionType  = CompilerResultError.None;
     CompileTarget    = CompilerResultTarget.Stream;
 }
        public bool DisplayError(CompilationException error)
        {
            var viewModel = new CompilationErrorViewModel
            {
                PathToFile = error.Errors[0].LexicalInfo.FullPath,
                Error      = error.ToString()
            };

            using (var form = new CompilationErrorDetails(viewModel))
            {
                return(form.ShowDialog() == DialogResult.Retry);
            }
        }
Beispiel #6
0
        private string BuildParserErrorMessage(ParseTree result)
        {
            var builder = new StringBuilder(2000);

            builder.AppendLine("Failed to parse expression. See parser output below.");
            foreach (var msg in result.ParserMessages)
            {
                builder.AppendFormat("{0} - {1} at {2}: {3}", msg.ParserState, msg.Level,
                                     CompilationException.FormatLocationString(msg.Location, -1), msg.Message);
                builder.AppendLine();
            }

            return(builder.ToString());
        }
 private void HandlerErrors(CompilationException exception)
 {
     if (SyntaxErrorBehavior == ExceptionBehavior.Throw)
     {
         throw exception;
     }
     else if (SyntaxErrorBehavior == ExceptionBehavior.Log)
     {
         LogOperator.ErrorRecoder(exception);
     }
     else if (SyntaxErrorBehavior == (ExceptionBehavior.Log | ExceptionBehavior.Throw))
     {
         LogOperator.ErrorRecoder(exception);
         throw exception;
     }
 }
Beispiel #8
0
        public void Evaluator_ExecAddReferenceRequired()
        {
            // this should fail without the call to AddReference
            var eval = new Evaluator("message = ExampleClass.HelloWorld");

            eval.AddUsing("TestExternalReference");
            eval["message"] = "";

            CompilationException ex = Assert.Throws <CompilationException>(
                delegate
            {
                eval.Exec();
            });

            Assert.IsTrue(
                ex.Message.Contains("The type or namespace name 'TestExternalReference' could not be found (are you missing a using directive or an assembly reference?)"));
        }
Beispiel #9
0
        public static void Deconstruct(
            this string script,
            out Assembly Assembly,
            out CompilationException Exception)
        {
            AssemblyCSharpBuilder assembly = new AssemblyCSharpBuilder();

            assembly.Syntax.Add(script);
            Assembly = assembly.GetAssembly();
            if (assembly.Exceptions != null)
            {
                Exception = assembly.Exceptions[0];
            }
            else
            {
                Exception = null;
            }
        }
Beispiel #10
0
        protected internal bool GenerateDaoAssembly(TypeSchema typeSchema, out CompilationException compilationEx)
        {
            try
            {
                compilationEx = null;
                SchemaDefinition schema       = SchemaDefinitionCreateResult.SchemaDefinition;
                string           assemblyName = "{0}.dll"._Format(schema.Name);

                string                   writeSourceTo = TypeSchemaTempPathProvider(schema, typeSchema);
                CompilerResults          results       = GenerateAndCompile(assemblyName, writeSourceTo);
                GeneratedDaoAssemblyInfo info          = new GeneratedDaoAssemblyInfo(schema.Name, results)
                {
                    TypeSchema       = typeSchema,
                    SchemaDefinition = schema
                };
                info.Save();

                GeneratedAssemblies.SetAssemblyInfo(schema.Name, info);

                Message = "Type Dao Generation completed successfully";
                FireEvent(GenerateDaoAssemblySucceeded, new GenerateDaoAssemblyEventArgs(info));

                TryDeleteDaoTemp(writeSourceTo);

                return(true);
            }
            catch (CompilationException ex)
            {
                Message = ex.Message;
                if (!string.IsNullOrEmpty(ex.StackTrace))
                {
                    Message = "{0}:\r\nStackTrace: {1}"._Format(Message, ex.StackTrace);
                }
                compilationEx = ex;
                FireEvent(GenerateDaoAssemblyFailed, EventArgs.Empty);
                return(false);
            }
        }
        public override ResultTable Evaluate()
        {
            var watch = new Stopwatch();

            watch.Start();

            var query   = GetQuery();
            var plugins = LoadPlugins();

            if (Configuration.DebugInfo)
            {
                System.Console.WriteLine($"Loaded plugins ({plugins.Count}):");
                foreach (var plugin in plugins)
                {
                    System.Console.WriteLine($"Assembly {plugin.Value.FullName}");
                }
            }

            var tempDir = Path.Combine(Path.GetTempPath(), "Musoq", "Compiled");

            if (!Directory.Exists(tempDir))
            {
                Directory.CreateDirectory(tempDir);
            }

            byte[] queryHash;
            using (var hashCreator = new MD5CryptoServiceProvider())
            {
                queryHash = hashCreator.ComputeHash(Encoding.UTF8.GetBytes(query));
            }

            var queryHashString = BitConverter.ToString(queryHash).Replace("-", "");

            var dllPath = Path.Combine(tempDir, $"{queryHashString}.dll");
            var pdbPath = Path.Combine(tempDir, $"{queryHashString}.pdb");

            var schemaProvider = new DynamicSchemaProvider(plugins);

            Assembly assembly;

            if (!File.Exists(dllPath) || Configuration.CompileOnly)
            {
                var items = new BuildItems
                {
                    SchemaProvider = schemaProvider,
                    RawQuery       = query
                };

                new Environment().SetValue(Constants.NetStandardDllEnvironmentName, EnvironmentUtils.GetOrCreateEnvironmentVariable());

                var throwAfterSave       = false;
                CompilationException exc = null;
                try
                {
                    BuildChain chain = new CreateTree(
                        new TransformTree(
                            new TurnQueryIntoRunnableCode(null)));

                    chain.Build(items);
                }
                catch (CompilationException ce)
                {
                    throwAfterSave = true;
                    exc            = ce;
                }

                if (items.DllFile?.Length > 0)
                {
                    using (var writer = new BinaryWriter(File.OpenWrite(dllPath)))
                    {
                        writer.Write(items.DllFile);
                    }
                }

                if (items.PdbFile?.Length > 0)
                {
                    using (var writer = new BinaryWriter(File.OpenWrite(pdbPath)))
                    {
                        writer.Write(items.PdbFile);
                    }
                }

                if (!string.IsNullOrEmpty(Configuration.OutputTranslatedQuery))
                {
                    var path     = Configuration.OutputTranslatedQuery;
                    var fileInfo = new FileInfo(path);

                    if (fileInfo.Directory == null || !fileInfo.Directory.Exists)
                    {
                        throw new DirectoryNotFoundException(fileInfo.DirectoryName);
                    }

                    var builder = new StringBuilder();
                    using (var writer = new StringWriter(builder))
                    {
                        items.Compilation?.SyntaxTrees.ElementAt(0).GetRoot().WriteTo(writer);
                    }

                    using (var file = new StreamWriter(File.OpenWrite(path)))
                    {
                        file.Write(builder.ToString());
                    }
                }

                if (throwAfterSave)
                {
                    throw exc;
                }

                assembly = Assembly.Load(items.DllFile, items.PdbFile);
            }
            else
            {
                assembly = Assembly.LoadFile(dllPath);
            }

            if (Configuration.CompileOnly || !string.IsNullOrEmpty(Configuration.OutputTranslatedQuery))
            {
                return(new ResultTable(string.Empty, new string[0], new object[0][], new string[0], TimeSpan.Zero));
            }

            var runnableType = assembly.GetTypes().Single(type => type.FullName.ToLowerInvariant().Contains("query"));

            var instance = (IRunnable)Activator.CreateInstance(runnableType);

            instance.Provider = schemaProvider;

            var compiledQuery = new CompiledQuery(instance);
            var table         = compiledQuery.Run();

            watch.Stop();

            var columns = table.Columns.Select(f => f.ColumnName).ToArray();
            var rows    = table.Select(f => f.Values).ToArray();
            var result  = new ResultTable(table.Name, columns, rows, new string[0], watch.Elapsed);

            return(result);
        }
Beispiel #12
0
 public IComplier()
 {
     Exception     = new CompilationException();
     ComplierInfos = new ComplierModel();
 }
 public DaoGenerationException(string schemaName, string schemaHash, Type[] types, CompilationException compilationEx) : base(GetMessage(schemaName, schemaHash, types, compilationEx))
 {
 }
Beispiel #14
0
        /// <summary>
        /// Метод для логгирования исключений
        /// </summary>
        /// <param name="ex">Исключение</param>
        public void Log(CompilationException ex)
        {
            string msgForLog = $"{DateTime.Now}) - Exception, Info: {ex.Message}";

            Messages.Add(msgForLog);
        }
Beispiel #15
0
 public bool Equals(PluginAssemblyContainer other)
 {
     return
         (string.Compare(VirtualPath, other.VirtualPath, true) == 0 &&
          (CompilationAssembly != null && other.CompilationAssembly != null && (CompilationAssembly.FullName == other.CompilationAssembly.FullName)) &&
          (CompilationException != null && other.CompilationException != null && (CompilationException.ToString() == other.CompilationException.ToString())));
 }
Beispiel #16
0
        public static CompiledQuery CompileForExecution(string script, ISchemaProvider schemaProvider)
        {
            var items = new BuildItems
            {
                SchemaProvider = schemaProvider,
                RawQuery       = script
            };

            var compiled = true;

            BuildChain chain =
                new CreateTree(
                    new TransformTree(
                        new TurnQueryIntoRunnableCode(null)));

            CompilationException compilationError = null;

            try
            {
                chain.Build(items);
            }
            catch (CompilationException ce)
            {
                compilationError = ce;
                compiled         = false;
            }

            if (compiled && !Debugger.IsAttached)
            {
                return(new CompiledQuery(CreateRunnable(items)));
            }

            var tempPath     = Path.Combine(Path.GetTempPath(), "Musoq");
            var tempFileName = $"InMemoryAssembly";
            var assemblyPath = Path.Combine(tempPath, $"{tempFileName}.dll");
            var pdbPath      = Path.Combine(tempPath, $"{tempFileName}.pdb");
            var csPath       = Path.Combine(tempPath, $"{tempFileName}.cs");

            var builder = new StringBuilder();

            using (var writer = new StringWriter(builder))
            {
                items.Compilation?.SyntaxTrees.ElementAt(0).GetRoot().WriteTo(writer);
            }

            using (var file = new StreamWriter(File.Open(csPath, FileMode.Create)))
            {
                file.Write(builder.ToString());
            }

            if (items.DllFile != null && items.DllFile.Length > 0)
            {
                using (var file = new BinaryWriter(File.Open(assemblyPath, FileMode.Create)))
                {
                    if (items.DllFile != null)
                    {
                        file.Write(items.DllFile);
                    }
                }
            }

            if (items.PdbFile != null && items.PdbFile.Length > 0)
            {
                using (var file = new BinaryWriter(File.Open(pdbPath, FileMode.Create)))
                {
                    if (items.PdbFile != null)
                    {
                        file.Write(items.PdbFile);
                    }
                }
            }

            if (!compiled && compilationError != null)
            {
                throw compilationError;
            }

            var runnable = new RunnableDebugDecorator(CreateRunnable(items), csPath, assemblyPath, pdbPath);

            return(new CompiledQuery(runnable));
        }
        private static string GetMessage(string schemaName, string schemaHash, Type[] types, CompilationException compilationEx)
        {
            StringBuilder builder = new StringBuilder();

            builder.AppendFormat("Unable to Generate Dao Assembly for {0} ({1}).\r\nSpecified Types:\r\n", schemaName, schemaHash);
            foreach (Type type in types)
            {
                builder.AppendFormat("\t{0}\r\n", type.FullName);
            }

            builder.AppendLine();
            builder.AppendFormat("\t{0}", compilationEx.Message);

            return(builder.ToString());
        }
        void FillHtmlizedErrorValues(ExceptionPageTemplateValues values, HtmlizedException exc, ref ExceptionPageTemplateType pageType)
        {
            bool isParseException   = exc is ParseException;
            bool isCompileException = (!isParseException && exc is CompilationException);

            values.Add(ExceptionPageTemplate.Template_PageTitleName, HtmlEncode(exc.Title));
            values.Add(ExceptionPageTemplate.Template_DescriptionName, HtmlEncode(exc.Description));
            values.Add(ExceptionPageTemplate.Template_StackTraceName, HtmlEncode(exc.StackTrace));
            values.Add(ExceptionPageTemplate.Template_ExceptionTypeName, exc.GetType().ToString());
            values.Add(ExceptionPageTemplate.Template_ExceptionMessageName, HtmlEncode(exc.Message));
            values.Add(ExceptionPageTemplate.Template_DetailsName, HtmlEncode(exc.ErrorMessage));

            string origin;

            if (isParseException)
            {
                origin = "Parser";
            }
            else if (isCompileException)
            {
                origin = "Compiler";
            }
            else
            {
                origin = "Other";
            }
            values.Add(ExceptionPageTemplate.Template_HtmlizedExceptionOriginName, origin);
            if (exc.FileText != null)
            {
                pageType |= ExceptionPageTemplateType.SourceError;
                StringBuilder shortSource = new StringBuilder();
                StringBuilder longSource;

                if (isCompileException)
                {
                    longSource = new StringBuilder();
                }
                else
                {
                    longSource = null;
                }
                FormatSource(shortSource, longSource, exc);
                values.Add(ExceptionPageTemplate.Template_HtmlizedExceptionShortSourceName, shortSource.ToString());
                values.Add(ExceptionPageTemplate.Template_HtmlizedExceptionLongSourceName, longSource != null ? longSource.ToString() : null);

                if (exc.SourceFile != exc.FileName)
                {
                    values.Add(ExceptionPageTemplate.Template_HtmlizedExceptionSourceFileName, FormatSourceFile(exc.SourceFile));
                }
                else
                {
                    values.Add(ExceptionPageTemplate.Template_HtmlizedExceptionSourceFileName, FormatSourceFile(exc.FileName));
                }
                if (isParseException || isCompileException)
                {
                    int[] errorLines = exc.ErrorLines;
                    int   numErrors  = errorLines != null ? errorLines.Length : 0;
                    var   lines      = new StringBuilder();
                    for (int i = 0; i < numErrors; i++)
                    {
                        if (i > 0)
                        {
                            lines.Append(", ");
                        }
                        lines.Append(errorLines [i]);
                    }
                    values.Add(ExceptionPageTemplate.Template_HtmlizedExceptionErrorLinesName, lines.ToString());
                }
            }
            else
            {
                values.Add(ExceptionPageTemplate.Template_HtmlizedExceptionSourceFileName, FormatSourceFile(exc.FileName));
            }

            if (isCompileException)
            {
                CompilationException cex    = exc as CompilationException;
                StringCollection     output = cex.CompilerOutput;

                if (output != null && output.Count > 0)
                {
                    pageType |= ExceptionPageTemplateType.CompilerOutput;
                    var  sb    = new StringBuilder();
                    bool first = true;
                    foreach (string s in output)
                    {
                        sb.Append(HtmlEncode(s));
                        if (first)
                        {
                            sb.Append("<br/>");
                            first = false;
                        }
                        sb.Append("<br/>");
                    }

                    values.Add(ExceptionPageTemplate.Template_HtmlizedExceptionCompilerOutputName, sb.ToString());
                }
            }
        }
 public CompilationWrapperException(CompilationException compilationException)
     : base("Pipeline compilation failed", compilationException)
 {
     this._compilationException = compilationException;
 }
Beispiel #20
0
        string GetHtmlizedErrorMessage(HtmlizedException exc)
        {
            StringBuilder builder = new StringBuilder();

#if TARGET_J2EE
            bool isParseException   = false;
            bool isCompileException = false;
#else
            bool isParseException   = exc is ParseException;
            bool isCompileException = (!isParseException && exc is CompilationException);
#endif

            WriteFileTop(builder, exc.Title);
            builder.AppendFormat("<h2><em>{0}</em></h2>\r\n", exc.Title);
            builder.AppendFormat("<p><strong>Description: </strong>{0}\r\n</p>\r\n", HtmlEncode(exc.Description));
            string errorMessage = HtmlEncode(exc.ErrorMessage);

            builder.Append("<p><strong>");
            if (isParseException)
            {
                builder.Append("Parser ");
            }
            else if (isCompileException)
            {
                builder.Append("Compiler ");
            }

            builder.Append("Error Message: </strong>");
#if NET_2_0
            builder.AppendFormat("<code>{0}</code></p>", errorMessage);
#else
            builder.AppendFormat("<blockquote><pre>{0}</pre></blockquote></p>", errorMessage);
#endif

            StringBuilder longCodeVersion = null;

            if (exc.FileText != null)
            {
                if (isParseException || isCompileException)
                {
                    builder.Append("<p><strong>Source Error: </strong></p>\r\n");
                    builder.Append("<table summary=\"Source error\" class=\"sampleCode\">\r\n<tr><td>");

                    if (isCompileException)
                    {
                        longCodeVersion = new StringBuilder();
                    }
                    WriteSource(builder, longCodeVersion, exc);
                    builder.Append("</pre></code></td></tr>\r\n</table>\r\n");
                }
                else
                {
                    builder.Append("<table summary=\"Source file\" class=\"sampleCode\">\r\n<tr><td>");
                    WriteSource(builder, null, exc);
                    builder.Append("</pre></code></td></tr>\r\n</table>\r\n");
                }

                builder.Append("<br/><p><strong>Source File: </strong>");
                if (exc.SourceFile != exc.FileName)
                {
                    builder.Append(FormatSourceFile(exc.SourceFile));
                }
                else
                {
                    builder.Append(FormatSourceFile(exc.FileName));
                }

                if (isParseException || isCompileException)
                {
                    int[] errorLines = exc.ErrorLines;
                    int   numErrors  = errorLines != null ? errorLines.Length : 0;
                    if (numErrors > 0)
                    {
                        builder.AppendFormat("&nbsp;&nbsp;<strong>Line{0}: </strong>", numErrors > 1 ? "s" : String.Empty);
                        for (int i = 0; i < numErrors; i++)
                        {
                            if (i > 0)
                            {
                                builder.Append(", ");
                            }
                            builder.Append(exc.ErrorLines [i]);
                        }
                    }
                }
                builder.Append("</p>");
            }
            else if (exc.FileName != null)
            {
                builder.AppendFormat("{0}</p>", HtmlEncode(exc.FileName));
            }

            bool needToggleJS = false;

#if !TARGET_J2EE
            if (isCompileException)
            {
                CompilationException cex    = exc as CompilationException;
                StringCollection     output = cex.CompilerOutput;

                if (output != null && output.Count > 0)
                {
                    needToggleJS = true;
                    StringBuilder sb = new StringBuilder();
                    foreach (string s in output)
                    {
                        sb.Append(s + "\r\n");
                    }
                    WriteExpandableBlock(builder, "compilerOutput", "Show Detailed Compiler Output", sb.ToString());
                }
            }
#endif

            if (longCodeVersion != null && longCodeVersion.Length > 0)
            {
                WriteExpandableBlock(builder, "fullCode", "Show Complete Compilation Source", longCodeVersion.ToString());
                needToggleJS = true;
            }

            if (needToggleJS)
            {
                builder.Append("<script type=\"text/javascript\">\r\n" +
                               "function ToggleVisible (id)\r\n" +
                               "{\r\n" +
                               "\tvar e = document.getElementById (id);\r\n" +
                               "\tif (e.style.display == 'none')\r\n" +
                               "\t{\r\n" +
                               "\t\te.style.display = '';\r\n" +
                               "\t} else {\r\n" +
                               "\t\te.style.display = 'none';\r\n" +
                               "\t}\r\n" +
                               "}\r\n" +
                               "</script>\r\n");
            }

            WriteFileBottom(builder, true);

            return(builder.ToString());
        }
Beispiel #21
0
        void CreateContent()
        {
            StringBuilder b = new StringBuilder();

            if (exception is CompilationException)
            {
                CompilationException compilationException = (CompilationException)exception;

                b.Append("<head>");
                b.AppendFormat("<title>{0} {1}</title>", "Error", exception.GetType());
                b.Append("</head>");
                b.Append("<body>");
                b.Append("<pre>");

                string        s;
                int           line   = 0;
                TextReader    reader = new StringReader(compilationException.FileText);
                CompilerError ce     = (CompilerError)compilationException.Errors[0];
                while ((s = reader.ReadLine()) != null)
                {
                    line++;
                    if (ce.Line == line)
                    {
                        b.AppendFormat("<span style=\"color: blue\">{0}</span></br>", ce.ErrorText);
                        b.Append("<span style=\"color: red\">");
                        // b.AppendFormat("Line {0}: {1}\r\n", line, HtmlEncode(s));
                        // b.Append("</span>");
                    }

                    b.AppendFormat("Line {0}: {1}\r\n", line, HtmlEncode(s));
                    if (line == ce.Line)
                    {
                        b.Append("</span>");
                    }
                }

                b.Append("</pre>");
                b.Append("</body>\r\n");
            }
            else if (exception is DodoException)
            {
                DodoException ae = (DodoException)exception;
                b.Append("<head>");
                b.AppendFormat("<title>{0} {1}</title>", "Error", ae.typeException);
                b.Append("</head>");
                b.Append("<body>");
                b.AppendFormat("<h3>Exception type: {0}</h3>", ae.typeException);
                b.AppendFormat("<h4>Description: <b>{0}</b></h4>", ae.error_description);
                b.AppendFormat("Target site '{0}' happened in '{1}' </br>", ae.error_details, ae.errorLocation);
                b.Append("<pre>");
                b.AppendFormat("Stack: </br>{0}", ae.stackTrace);
                b.Append("</pre>");
                b.Append("</body>\r\n");
            }
            else
            {
                b.Append("<head>");
                b.AppendFormat("<title>{0} {1}</title>", "Error", exception.GetType());
                b.Append("</head>");
                b.Append("<body>");
                b.Append("<pre>");
                b.AppendFormat("<b>{0}</b> </br>", exception.Message);
                b.AppendFormat("{0} </br>", exception.Source);
                b.AppendFormat("{0} </br>", exception.StackTrace);
                b.Append("</pre>");
                b.Append("</body>\r\n");
            }
            LoadText(b.ToString());
        }