public void Test_That_SupressWarningsFrom_Filters_Out_A_Single_Warning()
        {
            // Arrange
            var jscBadTypeForBitOperationWarning = new CompilerError { Type = WarningCode.JscBadTypeForBitOperation };
            var jscConstructorNotCallableWarning = new CompilerError { Type = WarningCode.JscConstructorNotCallable };

            var results = new CompilerResults
            {
                Warnings = new List<CompilerError>
                {
                    new CompilerError { Type = WarningCode.JscBadDeleteOperand },
                    jscBadTypeForBitOperationWarning,
                    jscConstructorNotCallableWarning,
                }
            };

            var supressWarnings = new List<string>
            {
                WarningCode.JscBadDeleteOperand,
            };

            // Act
            results.SupressWarningsFrom(supressWarnings);

            // Assert
            Assert.Equal(2, results.Warnings.Count);
            Assert.True(results.Warnings.Any(w => w == jscBadTypeForBitOperationWarning));
            Assert.True(results.Warnings.Any(w => w == jscConstructorNotCallableWarning));
        }
示例#2
0
		public override Assembly Compile(string path, string outPath, bool cache)
		{
			Assembly asm = null;
			try
			{
				if (this.ExistsAndUpToDate(path, outPath) && cache)
					return Assembly.LoadFrom(outPath);

				// Precompile script to a temp file
				var precompiled = this.PreCompile(File.ReadAllText(path));
				var tmp = Path.GetTempFileName();
				File.WriteAllText(tmp, precompiled);

				// Compile
				var compiler = new Boo.Lang.Compiler.BooCompiler();
				compiler.Parameters.AddAssembly(typeof(Log).Assembly);
				compiler.Parameters.AddAssembly(Assembly.GetEntryAssembly());
				compiler.Parameters.Input.Add(new FileInput(tmp));
				compiler.Parameters.OutputAssembly = outPath;
				compiler.Parameters.Pipeline = new CompileToFile();

#if DEBUG
				compiler.Parameters.Debug = true;
#else
				compiler.Parameters.Debug = false;
#endif

				var context = compiler.Run();
				if (context.GeneratedAssembly == null)
				{
					var errors = context.Errors;
					var newExs = new CompilerErrorsException();

					foreach (var err in errors)
					{
						var newEx = new CompilerError(path, err.LexicalInfo.Line, err.LexicalInfo.Column, err.Message, false);
						newExs.Errors.Add(newEx);
					}

					throw newExs;
				}

				asm = context.GeneratedAssembly;
			}
			catch (CompilerErrorsException)
			{
				throw;
			}
			catch (UnauthorizedAccessException)
			{
				// Thrown if file can't be copied. Happens if script was
				// initially loaded from cache.
			}
			catch (Exception ex)
			{
				Log.Exception(ex);
			}

			return asm;
		}
		private void HandleException(Exception ex, ProjectFile file, SingleFileCustomToolResult result)
		{
			if (ex is SpecFlowParserException)
			{
				SpecFlowParserException sfpex = (SpecFlowParserException) ex;
			                
				if (sfpex.ErrorDetails == null || sfpex.ErrorDetails.Count == 0)
				{
					result.UnhandledException = ex;
				}
				else
				{
					var compilerErrors = new CompilerErrorCollection();
					
					foreach (var errorDetail in sfpex.ErrorDetails)
					{
						var compilerError = new CompilerError(file.Name, errorDetail.ForcedLine, errorDetail.ForcedColumn, "0", errorDetail.Message);
						compilerErrors.Add(compilerError);
					}
							
					result.Errors.AddRange(compilerErrors);
				}
			}
			else
			{
				result.UnhandledException = ex;
			}
		}
示例#4
0
        public override Assembly Compile(string path, string outPath)
        {
            Assembly asm = null;
            try
            {
                if (this.ExistsAndUpToDate(path, outPath))
                    return Assembly.LoadFrom(outPath);

                var compiler = new Boo.Lang.Compiler.BooCompiler();
                compiler.Parameters.AddAssembly(typeof(Log).Assembly);
                compiler.Parameters.AddAssembly(typeof(ScriptManager).Assembly);
                compiler.Parameters.Input.Add(new FileInput(path));
                compiler.Parameters.OutputAssembly = outPath;
                compiler.Parameters.Pipeline = new CompileToFile();

                var context = compiler.Run();
                if (context.GeneratedAssembly == null)
                {
                    var errors = context.Errors;
                    var newExs = new CompilerErrorsException();

                    foreach (var err in errors)
                    {
                        var newEx = new CompilerError(path, err.LexicalInfo.Line, err.LexicalInfo.Column, err.Message, false);
                        newExs.Errors.Add(newEx);
                    }

                    throw newExs;
                }

                asm = context.GeneratedAssembly;

                //this.SaveAssembly(asm, outPath);
            }
            catch (CompilerErrorsException)
            {
                throw;
            }
            catch (UnauthorizedAccessException)
            {
                // Thrown if file can't be copied. Happens if script was
                // initially loaded from cache.
            }
            catch (Exception ex)
            {
                Log.Exception(ex);
            }

            return asm;
        }
示例#5
0
        // The position of a compile error may be outside of all user code snippets (for example, in case of
        // unclosed '{'). In that case filename would be the name of the temporary file, and not the name
        // of the stylesheet file. Exposing the path of the temporary file is considered to be a security issue,
        // so here we check that filename is amongst user files
        public void FixFileName(CompilerError e) {
            string fileName = e.FileName;
            foreach (string scriptFile in scriptFiles) {
                if (fileName.Equals(scriptFile, StringComparison.OrdinalIgnoreCase)) {
                    // The error position is within one of user stylesheets, its filename may be reported
                    e.FileName = scriptFile;
                    return;
                }
            }

            // Error is outside user files, we should hide filename for security reasons.
            // Return filename and position of the end of the last script block for the given class.
            e.FileName  = this.endFileName;
            e.Line      = this.endLine;
            e.Column    = this.endPos;
        }
        private string GetUserFriendlyErrorDescription(CompilerError error)
        {
            string result;

            switch (error.ErrorNumber)
            {
                case "CS0117": result = "Invalid operation found"; break;
                case "CS0118": result = "Invalid use of operation or construct found"; break;
                case "CS1002": result = "Invalid statement found"; break;
                case "CS0103": result = "Invalid keyword found"; break;
                case "CS1525": result = "Invalid character found"; break;
                default:
                    result = error.ErrorText; break;
            }

            result += " at position {0}";

            result = string.Format(result, error.Column - 29);

            return result;
        }
        public void Test_That_SupressWarningsFrom_Doesnt_Suppress_Any_Warnings_When_Passed_A_Null_Suppression_List()
        {
            // Arrange
            var jscBadTypeForBitOperationWarning = new CompilerError { Type = WarningCode.JscBadTypeForBitOperation };
            var jscJscFunctionMasksVariableWarning = new CompilerError { Type = WarningCode.JscFunctionMasksVariable };

            var results = new CompilerResults
            {
                Warnings = new List<CompilerError>
                {
                    jscBadTypeForBitOperationWarning,
                    jscJscFunctionMasksVariableWarning,
                }
            };

            // Act
            results.SupressWarningsFrom(null);

            // Assert
            Assert.Equal(2, results.Warnings.Count);
            Assert.True(results.Warnings.Any(w => w == jscBadTypeForBitOperationWarning));
            Assert.True(results.Warnings.Any(w => w == jscJscFunctionMasksVariableWarning));
        }
示例#8
0
        public static void GenerateExecutable(string output, string[] source, string icon)
        {
            CSharpCodeProvider compiler = new CSharpCodeProvider();
            CompilerParameters parameters = new CompilerParameters
                                                {
                                                    GenerateExecutable = true,
                                                    OutputAssembly = output
                                                };
            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.ReferencedAssemblies.Add("System.Data.dll");
            parameters.ReferencedAssemblies.Add("System.Management");
            parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            parameters.ReferencedAssemblies.Add("System.Xml");

            string ico = Path.GetTempPath() + "\\comp.ico";

            if (!string.IsNullOrEmpty(icon))
            {
                File.Copy(icon, ico);
                parameters.CompilerOptions += " /win32icon:" + ico;
            }

            CompilerResults cResults = compiler.CompileAssemblyFromSource(parameters, source);
            if (cResults.Errors.Count > 0)
            {
                foreach (CompilerError compilerErrorLoopVariable in cResults.Errors)
                {
                    CompileError = compilerErrorLoopVariable;
                    MessageBox.Show("Error: " + CompileError.ErrorText, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            if (!string.IsNullOrEmpty(icon))
            {
                File.Delete(ico);
            }
        }
示例#9
0
        public static string GetCompilerErrorHint(CompilerError error)
        {
            switch (error.ErrorNumber)
            {
                case "CS0029":
                    return "The value which is being assigned to a variable or property is not the correct type.";

                case "CS0103":
                    return "Make sure the object which is being accessed has been declared. When accessing predefined Source and Target forms, helpers and constants make sure the correct letter case is used.";

                case "CS0266":
                    return "This error usually occurs when assigning a floating point value to an integer. If that is the case use methods Math.Round(), Math.Floor() or Math.Ceiling() to retrieve an integer value.";

                case "CS0428":
                    return "The most likely cause of this error is that parentheses are missing after the method name which is being invoked. Parentheses are required even when the method has not parameters.";

                case "CS1061":
                    return "Make sure the method or property is defined for the form, helper or another object on which it is invoked or accessed and the correct letter case is used.";

                case "CS1501":
                    return "Make sure to pass the correct number of arguments to the method.";

                case "CS1502":
                    return "Make sure the arguments passed to the method are the correct type.";

                case "CS1503":
                    return "The method was expecing an argument of different type.";

                case "CS1955":
                    return "The most likely cause of this error is that parentheses are used after the property name which is being accessed. Properties are accessed without parentheses.";

                default:
                    // No hint is offered
                    return string.Empty;
            }
        }
示例#10
0
        // CompilerErrorCollection
        public void CompilerErrorCollectionExample()
        {
            //<Snippet1>
            //<Snippet2>
            // Creates an empty CompilerErrorCollection.
            CompilerErrorCollection collection = new CompilerErrorCollection();

            //</Snippet2>

            //<Snippet3>
            // Adds a CompilerError to the collection.
            collection.Add(new CompilerError("Testfile.cs", 5, 10, "CS0001", "Example error text"));
            //</Snippet3>

            //<Snippet4>
            // Adds an array of CompilerError objects to the collection.
            CompilerError[] errors = { new CompilerError("Testfile.cs", 5, 10, "CS0001", "Example error text"), new CompilerError("Testfile.cs", 5, 10, "CS0001", "Example error text") };
            collection.AddRange(errors);

            // Adds a collection of CompilerError objects to the collection.
            CompilerErrorCollection errorsCollection = new CompilerErrorCollection();

            errorsCollection.Add(new CompilerError("Testfile.cs", 5, 10, "CS0001", "Example error text"));
            errorsCollection.Add(new CompilerError("Testfile.cs", 5, 10, "CS0001", "Example error text"));
            collection.AddRange(errorsCollection);
            //</Snippet4>

            //<Snippet5>
            // Tests for the presence of a CompilerError in the
            // collection, and retrieves its index if it is found.
            CompilerError testError = new CompilerError("Testfile.cs", 5, 10, "CS0001", "Example error text");
            int           itemIndex = -1;

            if (collection.Contains(testError))
            {
                itemIndex = collection.IndexOf(testError);
            }
            //</Snippet5>

            //<Snippet6>
            // Copies the contents of the collection, beginning at index 0,
            // to the specified CompilerError array.
            // 'errors' is a CompilerError array.
            collection.CopyTo(errors, 0);
            //</Snippet6>

            //<Snippet7>
            // Retrieves the count of the items in the collection.
            int collectionCount = collection.Count;

            //</Snippet7>

            //<Snippet8>
            // Inserts a CompilerError at index 0 of the collection.
            collection.Insert(0, new CompilerError("Testfile.cs", 5, 10, "CS0001", "Example error text"));
            //</Snippet8>

            //<Snippet9>
            // Removes the specified CompilerError from the collection.
            CompilerError error = new CompilerError("Testfile.cs", 5, 10, "CS0001", "Example error text");

            collection.Remove(error);
            //</Snippet9>

            //<Snippet10>
            // Removes the CompilerError at index 0.
            collection.RemoveAt(0);
            //</Snippet10>
            //</Snippet1>
        }
		protected void Error(CompilerError error)
		{
			Errors.Add(error);
		}
示例#12
0
        public static bool Compile(string commandName)
        {
            string divider = new string('-', 25);

            if (!File.Exists(sourcepath + "Cmd" + commandName + ".vb"))
            {
                bool         check  = File.Exists("logs/errors/compiler.log");
                StreamWriter errlog = new StreamWriter("logs/errors/compiler.log", check);
                if (check)
                {
                    errlog.WriteLine();
                    errlog.WriteLine(divider);
                    errlog.WriteLine();
                }
                errlog.WriteLine("File not found: Cmd" + commandName + ".vb");

                errlog.Dispose();
                return(false);
            }
            if (!Directory.Exists(dllpath))
            {
                Directory.CreateDirectory(dllpath);
            }
            parameters.GenerateExecutable = false;
            parameters.MainClass          = commandName;
            parameters.OutputAssembly     = dllpath + "Cmd" + commandName + ".dll";
            parameters.ReferencedAssemblies.Add("MCForge_.dll");
            StreamReader sr = new StreamReader(sourcepath + "cmd" + commandName + ".vb");

            results = compiler.CompileAssemblyFromSource(parameters, sr.ReadToEnd());
            sr.Dispose();
            switch (results.Errors.Count)
            {
            case 0:
                return(true);

            case 1:
                CompilerError error  = results.Errors[0];
                bool          exists = (File.Exists("logs/errors/compiler.log")) ? true : false;
                StringBuilder sb     = new StringBuilder();
                if (exists)
                {
                    sb.AppendLine();
                    sb.AppendLine(divider);
                    sb.AppendLine();
                }
                sb.AppendLine("Error " + error.ErrorNumber);
                sb.AppendLine("Message: " + error.ErrorText);
                sb.AppendLine("Line: " + error.Line);

                StreamWriter sw = new StreamWriter("logs/errors/compiler.log", exists);
                sw.Write(sb.ToString());
                sw.Dispose();
                return(false);

            default:
                exists = (File.Exists("logs/errors/compiler.log")) ? true : false;
                sb     = new StringBuilder();
                bool start = true;
                if (exists)
                {
                    sb.AppendLine();
                    sb.AppendLine(divider);
                    sb.AppendLine();
                    //  McFire.Gui.Window.thisWindow.txtCompErrors.AppendText(Environment.NewLine);
                    //   McFire.Gui.Window.thisWindow.txtCompErrors.AppendText(divider);
                    //  McFire.Gui.Window.thisWindow.txtCompErrors.AppendText(Environment.NewLine);
                }
                foreach (CompilerError err in results.Errors)
                {
                    if (!start)
                    {
                        sb.AppendLine();
                        sb.AppendLine(divider);
                        sb.AppendLine();
                        //  McFire.Gui.Window.thisWindow.txtCompErrors.AppendText(Environment.NewLine);
                        // McFire.Gui.Window.thisWindow.txtCompErrors.AppendText(divider);
                        // McFire.Gui.Window.thisWindow.txtCompErrors.AppendText(Environment.NewLine);
                    }
                    sb.AppendLine("Error #" + err.ErrorNumber);
                    sb.AppendLine("Message: " + err.ErrorText);
                    sb.AppendLine("Line: " + err.Line);

                    //   McFire.Gui.Window.thisWindow.txtCompErrors.AppendText("Error #" + err.ErrorNumber);
                    //   McFire.Gui.Window.thisWindow.txtCompErrors.AppendText("Message: " + err.ErrorText);

                    //   McFire.Gui.Window.thisWindow.txtCompErrors.AppendText("Line: " + err.Line);
                    if (start)
                    {
                        start = false;
                    }
                }
                sw = new StreamWriter("logs/errors/compiler.log", exists);
                sw.Write(sb.ToString());
                sw.Dispose();
                return(false);
            }
        }
示例#13
0
 protected void Error(CompilerError error)
 {
     Context.Errors.Add(error);
 }
 public CompilerErrorInfo(int line, CompilerError compilererror, string description)
 {
     this.line = line;
     this.compilererror = compilererror;
     this.description = description;
 }
示例#15
0
 void IErrorHandler.ReportWarning(CompilerError error)
 {
     compilationErrors.Add(error);
 }
示例#16
0
        public static CompilerError Parser(string compilerOutput)
        {
            // C:\Program Files\dotnet\sdk\2.1.300-preview1-008174\Sdks\Microsoft.NET.Sdk\build\Microsoft.NET.ConflictResolution.targets(59,5): error MSB4018: The "ResolvePackageFileConflicts" task failed unexpectedly. [C:\Users\%username%\AppData\Local\Temp\csscript.core\cache\1822444284\.build\script.cs\script.csproj]
            // script.cs(11,8): error CS1029: #error: 'this is the error...' [C:\Users\%username%\AppData\Local\Temp\csscript.core\cache\1822444284\.build\script.cs\script.csproj]
            // script.cs(10,10): warning CS1030: #warning: 'DEBUG is defined' [C:\Users\%username%\AppData\Local\Temp\csscript.core\cache\1822444284\.build\script.cs\script.csproj]
            // MSBUILD : error MSB1001: Unknown switch.

            if (compilerOutput.StartsWith("error CS"))
            {
                compilerOutput = "(0,0): " + compilerOutput;
            }

            bool isError      = compilerOutput.Contains("): error ");
            bool isWarning    = compilerOutput.Contains("): warning ");
            bool isBuildError = compilerOutput.Contains("MSBUILD : error");

            if (isBuildError)
            {
                var parts = compilerOutput.Replace("MSBUILD : error ", "").Split(":".ToCharArray(), 2);
                return(new CompilerError
                {
                    ErrorText = "MSBUILD: " + parts.Last().Trim(),        // MSBUILD error: Unknown switch.
                    ErrorNumber = parts.First()                           // MSB1001
                });
            }
            else if (isWarning || isError)
            {
                var result = new CompilerError();

                var rx    = new Regex(@".*\(\d+\,\d+\)\:");
                var match = rx.Match(compilerOutput, 0);
                if (match.Success)
                {
                    try
                    {
                        var m = Regex.Match(match.Value, @"\(\d+\,\d+\)\:");

                        var location_items    = m.Value.Substring(1, m.Length - 3).Split(separator: ',').ToArray();
                        var description_items = compilerOutput.Substring(match.Value.Length).Split(":".ToArray(), 2);

                        result.ErrorText   = description_items.Last();                          // #error: 'this is the error...'
                        result.ErrorNumber = description_items.First().Split(' ').Last();       // CS1029
                        result.IsWarning   = isWarning;
                        result.FileName    = match.Value.Substring(0, m.Index);                 // cript.cs
                        result.Line        = int.Parse(location_items[0]);                      // 11
                        result.Column      = int.Parse(location_items[1]);                      // 8

                        int desc_end = result.ErrorText.LastIndexOf("[");
                        if (desc_end != -1)
                        {
                            result.ErrorText = result.ErrorText.Substring(0, desc_end);
                        }

                        return(result);
                    }
                    catch (Exception e)
                    {
                        Trace.WriteLine(e);
                    }
                }
            }
            return(null);
        }
 public void FindErrorLine(CompilerError CompErr, object PositionMap, string script, out int LineN, out int CharN)
 {
     LineN = CompErr.Line;
     CharN = CompErr.Column;
 }
示例#18
0
        internal override bool CompileLump(string filename, ScriptConfiguration scriptconfig, List <CompilerError> errors)
        {
            // No compiling required
            if (scriptconfig.Compiler == null)
            {
                return(true);
            }

            // Initialize compiler
            Compiler compiler;

            try
            {
                compiler = scriptconfig.Compiler.Create();
            }
            catch (Exception e)
            {
                // Fail
                errors.Add(new CompilerError("Unable to initialize compiler. " + e.GetType().Name + ": " + e.Message));
                return(false);
            }

            // Extract the source file into the temporary directory
            string inputfile = Path.Combine(compiler.Location, Path.GetFileName(filename));

            using (MemoryStream stream = LoadFile(filename))
            {
                File.WriteAllBytes(inputfile, stream.ToArray());
            }

            // Make random output filename
            string outputfile = General.MakeTempFilename(compiler.Location, "tmp");

            // Run compiler
            compiler.Parameters       = scriptconfig.Parameters;
            compiler.InputFile        = inputfile;
            compiler.OutputFile       = Path.GetFileName(outputfile);
            compiler.SourceFile       = inputfile;
            compiler.WorkingDirectory = Path.GetDirectoryName(inputfile);
            if (compiler.Run())
            {
                // Fetch errors
                foreach (CompilerError e in compiler.Errors)
                {
                    CompilerError newerr = e;

                    // If the error's filename equals our temporary file, // replace it with the original source filename
                    if (String.Compare(e.filename, inputfile, true) == 0)
                    {
                        newerr.filename = filename;
                    }

                    errors.Add(newerr);
                }

                // No errors and output file exists?
                if (compiler.Errors.Length == 0)
                {
                    // Output file exists?
                    if (!File.Exists(outputfile))
                    {
                        // Fail
                        compiler.Dispose();
                        errors.Add(new CompilerError("Output file \"" + outputfile + "\" doesn't exist."));
                        return(false);
                    }

                    //mxd. Move and rename the result file
                    string targetfilename;
                    if (compiler is AccCompiler)
                    {
                        AccCompiler acccompiler = (AccCompiler)compiler;
                        targetfilename = Path.Combine(Path.GetDirectoryName(filename), acccompiler.Parser.LibraryName + ".o");
                    }
                    else
                    {
                        //mxd. No can't do...
                        if (String.IsNullOrEmpty(scriptconfig.ResultLump))
                        {
                            // Fail
                            compiler.Dispose();
                            errors.Add(new CompilerError("Unable to create target file: unable to determine target filename. Make sure \"ResultLump\" property is set in the \"" + scriptconfig + "\" script configuration."));
                            return(false);
                        }

                        targetfilename = Path.Combine(Path.GetDirectoryName(filename), scriptconfig.ResultLump);
                    }

                    // Rename and add to source archive
                    try
                    {
                        byte[] buffer = File.ReadAllBytes(outputfile);
                        using (MemoryStream stream = new MemoryStream(buffer.Length))
                        {
                            stream.Write(buffer, 0, buffer.Length);
                            SaveFile(stream, targetfilename);
                        }
                    }
                    catch (Exception e)
                    {
                        // Fail
                        compiler.Dispose();
                        errors.Add(new CompilerError("Unable to create library file \"" + targetfilename + "\". " + e.GetType().Name + ": " + e.Message));
                        return(false);
                    }
                }

                // Done
                compiler.Dispose();
                return(true);
            }

            // Fail
            compiler.Dispose();
            return(false);
        }
示例#19
0
 public void Add(CompilerError error)
 {
 }
示例#20
0
 public TemplateCodeCompilerException(CompilerError err) : base(err.ErrorText)
 {
     Error = err;
 }
示例#21
0
        private CompilerResults CompileFromFileBatch(CompilerParameters options, string[] fileNames)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            if (fileNames == null)
            {
                throw new ArgumentNullException("fileNames");
            }

            CompilerResults results = new CompilerResults(options.TempFiles);
            Process         vbnc    = new Process();

            string vbnc_output = "";

            string[] vbnc_output_lines;
            // FIXME: these lines had better be platform independent.
            if (Path.DirectorySeparatorChar == '\\')
            {
                vbnc.StartInfo.FileName  = windowsMonoPath;
                vbnc.StartInfo.Arguments = windowsvbncPath + ' ' + BuildArgs(options, fileNames);
            }
            else
            {
                vbnc.StartInfo.FileName  = "vbnc";
                vbnc.StartInfo.Arguments = BuildArgs(options, fileNames);
            }
            //Console.WriteLine (vbnc.StartInfo.Arguments);
            vbnc.StartInfo.CreateNoWindow         = true;
            vbnc.StartInfo.UseShellExecute        = false;
            vbnc.StartInfo.RedirectStandardOutput = true;
            try {
                vbnc.Start();
            } catch (Exception e) {
                Win32Exception exc = e as Win32Exception;
                if (exc != null)
                {
                    throw new SystemException(String.Format("Error running {0}: {1}", vbnc.StartInfo.FileName,
                                                            Win32Exception.W32ErrorMessage(exc.NativeErrorCode)));
                }
                throw;
            }

            try {
                vbnc_output = vbnc.StandardOutput.ReadToEnd();
                vbnc.WaitForExit();
            } finally {
                results.NativeCompilerReturnValue = vbnc.ExitCode;
                vbnc.Close();
            }

            bool loadIt = true;

            if (results.NativeCompilerReturnValue == 1)
            {
                loadIt            = false;
                vbnc_output_lines = vbnc_output.Split(Environment.NewLine.ToCharArray());
                foreach (string error_line in vbnc_output_lines)
                {
                    CompilerError error = CreateErrorFromString(error_line);
                    if (null != error)
                    {
                        results.Errors.Add(error);
                    }
                }
            }

            if ((loadIt == false && !results.Errors.HasErrors) ||          // Failed, but no errors? Probably couldn't parse the compiler output correctly.
                (results.NativeCompilerReturnValue != 0 && results.NativeCompilerReturnValue != 1))                // Neither success (0), nor failure (1), so it crashed.
            {
                // Show the entire output as one big error message.
                loadIt = false;
                CompilerError error = new CompilerError(string.Empty, 0, 0, "VBNC_CRASH", vbnc_output);
                results.Errors.Add(error);
            }
            ;

            if (loadIt)
            {
                if (options.GenerateInMemory)
                {
                    using (FileStream fs = File.OpenRead(options.OutputAssembly)) {
                        byte[] buffer = new byte[fs.Length];
                        fs.Read(buffer, 0, buffer.Length);
                        results.CompiledAssembly = Assembly.Load(buffer, null, options.Evidence);
                        fs.Close();
                    }
                }
                else
                {
                    results.CompiledAssembly = Assembly.LoadFrom(options.OutputAssembly);
                    results.PathToAssembly   = options.OutputAssembly;
                }
            }
            else
            {
                results.CompiledAssembly = null;
            }

            return(results);
        }
示例#22
0
 public void MapParsingMessage(CompilerError error)
 {
     MapParsingMessage(error.LexicalInfo);
 }
示例#23
0
 private void ProcessingError(CompilerError error)
 {
     Errors.Add(error);
     RemoveCurrentNode();
 }
 private string FormatError(CompilerError error)
 {
     return(string.Format(CultureInfo.CurrentCulture, "[{0}] {1}", error.ErrorNumber, error.ErrorText));
 }
示例#25
0
        /// <include file='doc\CSharpCodeProvider.uex' path='docs/doc[@for="CSharpCodeGenerator.ProcessCompilerOutputLine"]/*' />
        /// <devdoc>
        ///    <para>
        ///       Processes the <see cref='System.CodeDom.Compiler.CompilerResults'/> returned from compilation.
        ///    </para>
        /// </devdoc>
        protected override void ProcessCompilerOutputLine(CompilerResults results, string line) {
            if (outputReg == null)
                 outputReg = new Regex(@"(^([^(]+)(\(([0-9]+),([0-9]+)\))?: )?(error|warning) ([A-Z]+[0-9]+): (.*)");
            
            Match m = outputReg.Match(line);
            if (m.Success) {
                CompilerError ce = new CompilerError();
                // The second element is the optional section if the error can be traced to a file.
                // Without it, the file name is meaningless.
                if (m.Groups[3].Success) {
                    ce.FileName = m.Groups[2].Value;
                    ce.Line = int.Parse(m.Groups[4].Value);
                    ce.Column = int.Parse(m.Groups[5].Value);
                }
                if (string.Compare(m.Groups[6].Value, "warning", true, CultureInfo.InvariantCulture) == 0) {
                    ce.IsWarning = true;
                }
                ce.ErrorNumber = m.Groups[7].Value;
                ce.ErrorText = m.Groups[8].Value;

                results.Errors.Add(ce);
            }
        }
示例#26
0
 public Error(CompilerError error)
 {
     this.error = error;
 }
示例#27
0
 private void ImportError(Import import, CompilerError error)
 {
     Errors.Add(error);
     BindError(import);
 }
 private void ProcessCompilerOutputLine(CompilerResults results, string line)
 {
     bool flag;
     if (outputRegSimple == null)
     {
         outputRegWithFileAndLine = new Regex(@"(^(.*)(\(([0-9]+),([0-9]+)\)): )(error|warning) ([A-Z]+[0-9]+) ?: (.*)");
         outputRegSimple = new Regex("(error|warning) ([A-Z]+[0-9]+) ?: (.*)");
     }
     Match match = outputRegWithFileAndLine.Match(line);
     if (match.Success)
     {
         flag = true;
     }
     else
     {
         match = outputRegSimple.Match(line);
         flag = false;
     }
     if (match.Success)
     {
         CompilerError error = new CompilerError();
         if (flag)
         {
             error.FileName = match.Groups[2].Value;
             error.Line = int.Parse(match.Groups[4].Value, CultureInfo.InvariantCulture);
             error.Column = int.Parse(match.Groups[5].Value, CultureInfo.InvariantCulture);
         }
         if (string.Compare(match.Groups[flag ? 6 : 1].Value, "warning", StringComparison.OrdinalIgnoreCase) == 0)
         {
             error.IsWarning = true;
         }
         error.ErrorNumber = match.Groups[flag ? 7 : 2].Value;
         error.ErrorText = match.Groups[flag ? 8 : 3].Value;
         results.Errors.Add(error);
     }
 }
示例#29
0
        CompilerResults CompileAssemblyFromFileBatchImpl(CompilerParameters options, string[] fileNames)
        {
            //System.Diagnostics.Debug.Assert(false);
            CompilerResults retval = new CompilerResults(new TempFileCollection());

            string outputName = Path.GetFileNameWithoutExtension(options.OutputAssembly);
            string tempDir = Path.Combine(Path.GetTempPath(), "CSSCRIPT\\CPP\\" + System.Guid.NewGuid().ToString());
            string tempProj = Path.Combine(tempDir, outputName + ".csproj");
            string tempSln = Path.Combine(tempDir, outputName + ".sln");
            string outputFile = Path.Combine(tempDir, outputName + (options.GenerateExecutable ? ".exe" : ".dll"));

            if (Directory.Exists(tempDir))
                Directory.Delete(tempDir, true);

            Directory.CreateDirectory(tempDir);

            File.WriteAllText(tempSln, GetSolutionTemplateContent().Replace("$PROJECT_FILE$", outputName + ".csproj"));

            string content = GetProjTemplateContent();

            using (StreamWriter sw = new StreamWriter(tempProj))
            {
                content = content.Replace("$NAME$", outputName);
                content = content.Replace("$DEBUG_TYPE$", options.IncludeDebugInformation ? "<DebugType>full</DebugType>" : "");
                content = content.Replace("$OPTIMIZE$", options.IncludeDebugInformation ? "false" : "true");
                content = content.Replace("$DEBUG_CONST$", options.IncludeDebugInformation ? "DEBUG;" : "");
                content = content.Replace("$DEBUG$", options.IncludeDebugInformation ? "true" : "false");
                content = content.Replace("$OUPTUT_DIR$", tempDir);

                //Exe/WinExe/Library
                if (options.GenerateExecutable) //exe
                {
                    if (options.CompilerOptions != null && options.CompilerOptions.IndexOf("/target:winexe") != -1)
                    {
                        content = content.Replace("$TYPE$", "WinExe");	//WinForm
                    }
                    else
                    {
                        content = content.Replace("$TYPE$", "Exe");	//console
                    }
                }
                else //dll
                {
                    content = content.Replace("$TYPE$", "Library");	//dll
                }

                string references = "";
                foreach (string file in options.ReferencedAssemblies)
                    references += string.Format(reference_template, Path.GetFileName(file), file);
                content = content.Replace("$REFERENCES$", references);

                content = content.Replace("$MIN_CLR_VER$", "<MinFrameworkVersionRequired>4.0</MinFrameworkVersionRequired>");
                //content = content.Replace("$IMPORT_PROJECT$", "<Import Project=\"$(MSBuildBinPath)\\Microsoft.WinFX.targets\" />");
                content = content.Replace("$IMPORT_PROJECT$", "");
                string sources = "";

                foreach (string file in fileNames)
                {
                    if (file.ToLower().EndsWith(".xaml"))
                    {
                        if (IsAppXAML(file))
                            sources += "<ApplicationDefinition Include=\"" + file + "\" />\n";
                        else
                            sources += "<Page Include=\"" + file + "\" />\n";
                    }
                    else
                        sources += string.Format(include_template, file);
                }
                content = content.Replace("$SOURCE_FILES$", sources);

                sw.Write(content);
            }
             
            string compileLog = "";
            //Stopwatch sw1 = new Stopwatch();
            //sw1.Start();

            string msbuild = Path.Combine(Path.GetDirectoryName("".GetType().Assembly.Location), "MSBuild.exe");

            string args = string.Format(@"/nologo /verbosity:minimal /t:Clean,Build /p:Configuration=CSSBuild /p:Platform=""Any CPU"" ""{0}""", tempSln);

            compileLog = RunApp(Path.GetDirectoryName(tempProj), msbuild, args).Trim();
            //compileLog = RunApp(Path.GetDirectoryName(tempProj), msbuild, "\"" + tempProj + "\" /p:Configuration=\"CSSBuild\" /nologo /verbosity:m").Trim();

            //sw1.Stop();

            if (compileLog.EndsWith("-- FAILED."))
            {
                using (StringReader sr = new StringReader(compileLog))
                {
                    string line = "";
                    while ((line = sr.ReadLine()) != null)
                    {
                        line = line.Trim();

                        if (line == "")
                            continue;

                        if (line.EndsWith("Done building project"))
                            break;

                        int lineNumber = 0;
                        int colNumber = 0;
                        string fileName = "";
                        string errorNumber = "";
                        string errorText = "";
                        bool isWarning = false;

                        int fileEnd = line.IndexOf(": warning ");
                        if (fileEnd == -1)
                            fileEnd = line.IndexOf(": error ");
                        else
                            isWarning = true;

                        if (fileEnd == -1)
                            continue;

                        string filePart = line.Substring(0, fileEnd);
                        string errorPart = line.Substring(fileEnd + 2); //" :" == 2
                        int lineNumberStart = filePart.LastIndexOf("(");
                        int errorDescrStart = errorPart.IndexOf(":");

                        string[] erorLocation = filePart.Substring(lineNumberStart).Replace("(", "").Replace(")", "").Split(',');
                        lineNumber = filePart.EndsWith(")") ? int.Parse(erorLocation[0]) : -1;
                        colNumber = filePart.EndsWith(")") ? int.Parse(erorLocation[1]) : -1;
                        fileName = Path.GetFullPath(lineNumber == -1 ? filePart : filePart.Substring(0, lineNumberStart).Trim());
                        errorNumber = errorPart.Substring(0, errorDescrStart).Trim();
                        errorText = errorPart.Substring(errorDescrStart + 1).Trim();

                        CompilerError error = new CompilerError(fileName, lineNumber, colNumber, errorNumber, errorText);
                        error.IsWarning = isWarning;

                        retval.Errors.Add(error);
                    }
                }
            }

            if (File.Exists(outputFile))
            {
                if (File.Exists(options.OutputAssembly))
                    File.Copy(outputFile, options.OutputAssembly, true);
                else
                    File.Move(outputFile, options.OutputAssembly);
                try
                {
                    Directory.Delete(tempDir, true);
                }
                catch { }
            }

            if (options.IncludeDebugInformation)
            {
                string pdbSrcFile = Path.ChangeExtension(outputFile, ".pdb");
                string pdbDestFile = Path.ChangeExtension(options.OutputAssembly, ".pdb");
                if (File.Exists(pdbSrcFile))
                {
                    if (File.Exists(pdbDestFile))
                        File.Copy(pdbSrcFile, pdbDestFile, true);
                    else
                        File.Move(pdbSrcFile, pdbDestFile);
                }
            }
            return retval;
        }
示例#30
0
 /// <summary>
 /// Formats a Compilation Error
 /// </summary>
 /// <param name="err">The compiler error</param>
 /// <param name="code">The code that caused the compilation error</param>
 /// <returns>A formatted Error String</returns>
 public static string FormatCompilerError(CompilerError err, string code)
 {
     return("<b><span style='color: " + (err.IsWarning ? "GoldenRod" : "red") + ";'>Compilation " + (err.IsWarning ? "Warning" : "Error") + " " + err.ErrorNumber + "</span></b><pre style='white-space: pre-wrap; word-wrap: break-word;'>at <i>" + (CodeProcessor.GetStackTrace(code, err.Line) ?? "Generated code") + "</i>: \n    <b>" + new Regex(@"/\* File (.+?) Line [0-9]{1,} \*/").Replace(code.Split(new char[] { '\n' })[err.Line - 1].Trim(), "").Replace("<", "&lt;") + " </b>\n<u>Info:</u> " + err.ErrorText + "</pre>");
 }
示例#31
0
        private static Assembly CompileInternal(String outputAssembly, IEnumerable <String> references, CodeDomProvider provider, CompilerErrorCollection Errors, Template tmp)
        {
            var options = new CompilerParameters();

            foreach (var str in references)
            {
                options.ReferencedAssemblies.Add(str);
            }
            options.WarningLevel = 4;

            CompilerResults results = null;

            if (Debug)
            {
                //var sb = new StringBuilder();

                #region 调试状态,把生成的类文件和最终dll输出到XTemp目录下
                var tempPath = XTrace.TempPath.GetFullPath().EnsureDirectory(false);
                //if (!String.IsNullOrEmpty(outputAssembly)) tempPath = Path.Combine(tempPath, Path.GetFileNameWithoutExtension(outputAssembly));
                if (!String.IsNullOrEmpty(outputAssembly) && !outputAssembly.EqualIgnoreCase(".dll"))
                {
                    tempPath = Path.Combine(tempPath, Path.GetFileNameWithoutExtension(outputAssembly));
                }

                //if (!String.IsNullOrEmpty(tempPath) && !Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath);

                //var srcpath = tempPath.CombinePath("src").EnsureDirectory(false);

                var files = new List <String>();
                foreach (var item in tmp.Templates)
                {
                    // 输出模版内容,为了调试使用
                    File.WriteAllText(tempPath.CombinePath(item.Name).EnsureDirectory(true), item.Content);
                    if (item.Included)
                    {
                        continue;
                    }

                    var name = item.Name.EndsWithIgnoreCase(".cs") ? item.Name : item.ClassName;
                    // 猜测后缀
                    var p = name.LastIndexOf("_");
                    if (p > 0 && name.Length - p <= 5)
                    {
                        name = name.Substring(0, p) + "." + name.Substring(p + 1, name.Length - p - 1);
                    }
                    else if (!name.EndsWithIgnoreCase(".cs"))
                    {
                        name += ".cs";
                    }

                    //name = Path.Combine(tempPath, name);
                    //name = srcpath.CombinePath(name);
                    // 必须放在同一个目录,编译时会搜索源码所在目录
                    name = tempPath.CombinePath(Path.GetFileNameWithoutExtension(name) + "_src" + Path.GetExtension(name));
                    File.WriteAllText(name, item.Source);

                    //sb.AppendLine(item.Source);
                    files.Add(name);
                }
                #endregion

                if (!String.IsNullOrEmpty(outputAssembly) && !outputAssembly.EqualIgnoreCase(".dll"))
                {
                    options.TempFiles      = new TempFileCollection(tempPath, false);
                    options.OutputAssembly = Path.Combine(tempPath, outputAssembly);
                    //options.GenerateInMemory = true;
                    options.IncludeDebugInformation = true;
                }

                results = provider.CompileAssemblyFromFile(options, files.ToArray());
                // 必须从内存字符串编译,否则pdb会定向到最终源代码文件
                //results = provider.CompileAssemblyFromSource(options, new String[] { sb.ToString() });
            }
            else
            {
                options.GenerateInMemory = true;

                results = provider.CompileAssemblyFromSource(options, tmp.Templates.Where(e => !e.Included).Select(e => e.Source).ToArray());
            }

            #region 编译错误处理
            if (results.Errors.Count > 0)
            {
                Errors.AddRange(results.Errors);

                var           sb  = new StringBuilder();
                CompilerError err = null;
                foreach (CompilerError error in results.Errors)
                {
                    error.ErrorText = error.ErrorText;
                    //if (String.IsNullOrEmpty(error.FileName)) error.FileName = inputFile;

                    if (!error.IsWarning)
                    {
                        var msg = error.ToString();
                        if (sb.Length < 1)
                        {
                            String code = null;
                            // 屏蔽因为计算错误行而导致的二次错误
                            try
                            {
                                code = tmp.FindBlockCode(error.FileName, error.Line);
                            }
                            catch { }
                            if (code != null)
                            {
                                msg += Environment.NewLine;
                                msg += code;
                            }
                            err = error;
                        }
                        else
                        {
                            sb.AppendLine();
                        }

                        sb.Append(msg);
                    }
                }
                if (sb.Length > 0)
                {
                    var ex = new TemplateException(sb.ToString());
                    ex.Error = err;
                    throw ex;
                }
            }
            else
            {
                try
                {
                    options.TempFiles.Delete();
                }
                catch { }
            }
            #endregion

            if (!results.Errors.HasErrors)
            {
                try
                {
                    return(results.CompiledAssembly);
                }
                catch { }
            }
            return(null);
        }
示例#32
0
		protected void Error(CompilerError error)
		{
			Context.Errors.Add(error);
		}
        internal MobileErrorInfo(Exception e)
        {
            // Don't want any failure to escape here...
            try
            {
                // For some reason, the compile exception lives in the
                // InnerException.
                HttpCompileException compileException =
                    e.InnerException as HttpCompileException;

                if (compileException != null)
                {
                    this.Type        = SR.GetString(SR.MobileErrorInfo_CompilationErrorType);
                    this.Description = SR.GetString(SR.MobileErrorInfo_CompilationErrorDescription);
                    this.MiscTitle   = SR.GetString(SR.MobileErrorInfo_CompilationErrorMiscTitle);

                    CompilerErrorCollection errors = compileException.Results.Errors;

                    if (errors != null && errors.Count >= 1)
                    {
                        CompilerError error = errors[0];
                        this.LineNumber = error.Line.ToString(CultureInfo.InvariantCulture);
                        this.File       = error.FileName;
                        this.MiscText   = error.ErrorNumber + ":" + error.ErrorText;
                    }
                    else
                    {
                        this.LineNumber = SR.GetString(SR.MobileErrorInfo_Unknown);
                        this.File       = SR.GetString(SR.MobileErrorInfo_Unknown);
                        this.MiscText   = SR.GetString(SR.MobileErrorInfo_Unknown);
                    }

                    return;
                }

                HttpParseException parseException = e as HttpParseException;
                if (parseException != null)
                {
                    this.Type        = SR.GetString(SR.MobileErrorInfo_ParserErrorType);
                    this.Description = SR.GetString(SR.MobileErrorInfo_ParserErrorDescription);
                    this.MiscTitle   = SR.GetString(SR.MobileErrorInfo_ParserErrorMiscTitle);
                    this.LineNumber  = parseException.Line.ToString(CultureInfo.InvariantCulture);
                    this.File        = parseException.FileName;
                    this.MiscText    = parseException.Message;
                    return;
                }

                // We try to use the hacky way of parsing an HttpException of an
                // unknown subclass.
                HttpException httpException = e as HttpException;
                if (httpException != null && ParseHttpException(httpException))
                {
                    return;
                }
            }
            catch
            {
                // Don't need to do anything here, just continue to base case
                // below.
            }

            // Default to the most basic if none of the above succeed.
            this.Type        = e.GetType().FullName;
            this.Description = e.Message;
            this.MiscTitle   = SR.GetString(SR.MobileErrorInfo_SourceObject);
            String s = e.StackTrace;

            if (s != null)
            {
                int i = s.IndexOf('\r');
                if (i != -1)
                {
                    s = s.Substring(0, i);
                }
                this.MiscText = s;
            }
        }
示例#34
0
 internal virtual string GetMessageForError(CompilerError error)
 {
     return
         String.Format("{0}({1},{2}): Error {3}: {4}",
             error.FileName,
             error.Line,
             error.Column,
             error.ErrorNumber,
             error.ErrorText);
 }
示例#35
0
 static void DumpCompileError(CompilerError error)
 {
     DumpError(error.FileName, error.Line, error.IsWarning, error.ErrorNumber, error.ErrorText);
 }
 public virtual void ReportCompilerError(CompilerError error)
 {
 }
示例#37
0
 private void OutputError(CompilerError error, string[] actualSource)
 {
     if ((string.Equals(base.ParameterSetName, "FromPath", StringComparison.OrdinalIgnoreCase) || string.Equals(base.ParameterSetName, "FromLiteralPath", StringComparison.OrdinalIgnoreCase)) && !string.IsNullOrEmpty(error.FileName))
     {
         actualSource = File.ReadAllText(error.FileName).Split(new char[] { '\n' });
     }
     string message = StringUtil.Format(AddTypeStrings.CompilationErrorFormat, new object[] { error.FileName, error.Line, error.ErrorText }) + "\n";
     for (int i = error.Line - 1; i < (error.Line + 2); i++)
     {
         if (i > 0)
         {
             if (i > actualSource.Length)
             {
                 break;
             }
             string str2 = "";
             if (i == error.Line)
             {
                 str2 = str2 + ">>> ";
             }
             str2 = str2 + actualSource[i - 1];
             message = message + "\n" + StringUtil.Format(AddTypeStrings.CompilationErrorFormat, new object[] { error.FileName, i, str2 }) + "\n";
         }
     }
     ErrorRecord errorRecord = new ErrorRecord(new Exception(message), "SOURCE_CODE_ERROR", ErrorCategory.InvalidData, error);
     base.WriteError(errorRecord);
 }
示例#38
0
 public override void ReportCompilerError(CompilerError error)
 {
     DumpCompileError(error);
 }
        static void OnPostprocessAllAssets(
            string[] importedAssets,
            string[] deletedAssets,
            string[] movedAssets,
            string[] movedFromAssetPaths)
        {
            foreach (string assetPath in importedAssets)
            {
                // ======================================
                // Choose the importer for this file type

                string ext = Path.GetExtension(assetPath).ToLower();
                if (string.IsNullOrEmpty(ext))
                {
                    continue;
                }

                // Get the right importer for this type
                ext = ext.Substring(1);
                StoryImporter importer = null;
                Type          importerType;
                if (!ImporterTypes.TryGetValue(ext, out importerType))
                {
                    continue;
                }

                importer           = (StoryImporter)Activator.CreateInstance(importerType);
                importer.AssetPath = assetPath;

                // ======================================
                // Validate the file

                // Check that the file is relevant
                if (!importer.IsAssetRelevant())
                {
                    return;
                }

                // Check that the story name is valid
                string fileNameExt = Path.GetFileName(assetPath);
                string fileName    = Path.GetFileNameWithoutExtension(assetPath);
                string storyName   = NameSanitizer.Replace(fileName, string.Empty);
                if (storyName != fileName)
                {
                    Debug.LogErrorFormat("The story cannot be imported because \"{0}\" is not a valid Unity script name.", fileName);
                    continue;
                }

                using (importer.CodeDomProvider = new CSharpCodeProvider())
                {
                    // ======================================
                    // Initialize the importer - load data and choose transcoder

                    try
                    {
                        importer.Initialize();
                    }
                    catch (StoryImportException ex)
                    {
                        Debug.LogErrorFormat("Story import failed: {0} ({1})", ex.Message, fileNameExt);
                        continue;
                    }

                    // ======================================
                    // Run the transcoder

                    try
                    {
                        importer.Transcode();
                    }
                    catch (StoryFormatTranscodeException ex)
                    {
                        Debug.LogErrorFormat("Story format transcoding failed at passage {0}: {1} ({2})", ex.Passage, ex.Message, fileNameExt);
                        continue;
                    }

                    // ======================================
                    // Generate code

                    StoryFormatMetadata   storyFormatMetadata = importer.Metadata;
                    TemplatePassageData[] passageData         = importer.Passages.Select(p => new TemplatePassageData()
                    {
                        Pid       = p.Pid,
                        Name      = p.Name.Replace("\"", "\"\""),
                        Tags      = p.Tags,
                        Code      = p.Code.Main.Split(new string[] { Environment.NewLine }, StringSplitOptions.None),
                        Fragments = p.Code.Fragments.Select((frag, i) => new TemplatePassageFragment()
                        {
                            Pid    = p.Pid,
                            FragId = i,
                            Code   = frag.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)
                        }).ToArray()
                    }).ToArray();

                    // Get template file from this editor script's directory
                    string output = Nustache.Core.Render.FileToString(
                        EditorFileUtil.FindFile("Story.template"),
                        new Dictionary <string, object>()
                    {
                        { "version", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString() },
                        { "originalFile", Path.GetFileName(assetPath) },
                        { "storyFormatName", storyFormatMetadata.StoryFormatName },
                        { "storyFormatNamespace", storyFormatMetadata.StoryBaseType.Namespace },
                        { "storyFormatClass", storyFormatMetadata.StoryBaseType.FullName },
                        { "storyName", storyName },
                        { "startPassage", storyFormatMetadata.StartPassage ?? "Start" },
                        { "vars", importer.Vars },
                        { "macroLibs", importer.MacroLibs },
                        { "strictMode", storyFormatMetadata.StrictMode ? "true" : "false" },
                        { "passages", passageData }
                    }
                        );

                    // ======================================
                    // Compile

                    // Unity bug fix: This environment variable is not set on Mac for some reason - https://github.com/AngryAnt/Behave-release/issues/21
                    if (Application.platform == RuntimePlatform.OSXEditor)
                    {
                        string monoBinPath = Path.Combine(EditorApplication.applicationContentsPath, "Frameworks/Mono/bin");

                        // Unity 5.4 and up
                        if (!Directory.Exists(monoBinPath))
                        {
                            monoBinPath = Path.Combine(EditorApplication.applicationContentsPath, "Mono/bin");
                        }

                        // Huh?
                        if (!Directory.Exists(monoBinPath))
                        {
                            Debug.LogError("For some reason I can't find the Mono directory inside Unity.app. Please open an issue on github.com/daterre/Cradle");
                        }

                        Environment.SetEnvironmentVariable("PATH", string.Format("{0}:{1}",
                                                                                 Environment.GetEnvironmentVariable("PATH"),
                                                                                 monoBinPath
                                                                                 ));
                    }

                    // Detect syntax errors
                    var compilerSettings = new CompilerParameters()
                    {
                        GenerateInMemory   = true,
                        GenerateExecutable = false
                    };
                    foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
                    {
                        if (assembly.IsDynamic)
                        {
                            continue;
                        }

                        try
                        {
                            // On .NET 4+, the correct way to check this is Assembly.IsDynamic (otherwise NotSupportedException is thrown),
                            // but this doesn't exist in .NET 3.5 so a try catch block is used here for backward compatibility
                            if (!string.IsNullOrEmpty(assembly.Location))
                            {
                                compilerSettings.ReferencedAssemblies.Add(assembly.Location);
                            }
                        }
                        catch (NotSupportedException)
                        {
                            continue;
                        }
                    }

                    var results = importer.CodeDomProvider.CompileAssemblyFromSource(compilerSettings, output);

                    if (results.Errors.Count > 0)
                    {
                        int errorLineOffset = Application.platform == RuntimePlatform.OSXEditor ? 3 : 4;

                        bool errors = false;
                        for (int i = 0; i < results.Errors.Count; i++)
                        {
                            CompilerError error = results.Errors[i];

                            switch (error.ErrorNumber)
                            {
                            //case "CS0246":
                            case "CS0103":
                            case "":
                                continue;

                            // Single quotes instead of double quotes
                            case "CS1012":
                                error.ErrorText = "Strings must use \"double-quotes\", not 'single-quotes'.";
                                break;

                            // Double var accessor
                            case "CS1612":
                                error.ErrorText = "Can't set a nested property directly like that. Use a temporary variable in-between.";
                                break;
                            }

                            // Error only if not a warning
                            errors |= !error.IsWarning;

                            try
                            {
                                // Get some compilation metadata - relies on the template using the #frag# token
                                string[]            errorDirective = error.FileName.Split(new string[] { "#frag#" }, StringSplitOptions.None);
                                string              errorPassage   = errorDirective[0];
                                int                 errorFragment  = errorDirective.Length > 1 ? int.Parse(errorDirective[1]) : -1;
                                TemplatePassageData passage        = passageData.Where(p => p.Name == errorPassage).FirstOrDefault();
                                string              lineCode       = passage == null || error.Line < errorLineOffset ? "(code not available)" : errorFragment >= 0 ?
                                                                     passage.Fragments[errorFragment].Code[error.Line - errorLineOffset] :
                                                                     passage.Code[error.Line - errorLineOffset];

                                if (error.IsWarning)
                                {
                                    Debug.LogWarningFormat("Story compilation warning at passage '{0}': {1}\n\n\t{2}\n",
                                                           errorPassage,
                                                           error.ErrorText,
                                                           lineCode
                                                           );
                                }
                                else
                                {
                                    Debug.LogErrorFormat("Story compilation error at passage '{0}': {1}\n\n\t{2}\n",
                                                         errorPassage,
                                                         error.ErrorText,
                                                         lineCode
                                                         );
                                }
                            }
                            catch
                            {
                                if (error.IsWarning)
                                {
                                    Debug.LogWarningFormat("Story compilation warning: {0}\n",
                                                           error.ErrorText
                                                           );
                                }
                                else
                                {
                                    Debug.LogErrorFormat("Story compilation error: {0}\n",
                                                         error.ErrorText
                                                         );
                                }
                            }
                        }

                        if (errors)
                        {
                            Debug.LogErrorFormat("The story {0} has some errors and can't be imported (see console for details).",
                                                 Path.GetFileName(assetPath)
                                                 );
                            continue;
                        }
                    }

                    // Remove custom line directives so they won't interfere with debugging the final script
                    output = Regex.Replace(output, @"^\s*\#line\b.*$", string.Empty, RegexOptions.Multiline);

                    // Passed syntax check, save to file
                    string csFile = Path.Combine(Path.GetDirectoryName(assetPath), Path.GetFileNameWithoutExtension(assetPath) + ".cs");
                    File.WriteAllText(csFile, output, Encoding.UTF8);

                    // Need to do it twice - on the second time it compiles the script
                    // http://answers.unity3d.com/questions/14367/how-can-i-wait-for-unity-to-recompile-during-the-e.html
                    AssetDatabase.ImportAsset(csFile, ImportAssetOptions.ForceSynchronousImport);
                    AssetDatabase.ImportAsset(csFile, ImportAssetOptions.ForceSynchronousImport);

                    // ======================================
                    // Organize the assets

                    #region Disabled prefab creation because the story class can't be added during this asset import

                    /*
                     * // Find the story class
                     * string projectDir = Directory.GetParent((Path.GetFullPath(Application.dataPath))).FullName;
                     * Type storyClass = null;
                     * foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
                     * {
                     *      // Skip references external to the project
                     *      if (!string.IsNullOrEmpty(assembly.Location) && !Path.GetFullPath(assembly.Location).StartsWith(projectDir, StringComparison.OrdinalIgnoreCase))
                     *              continue;
                     *      foreach (Type type in assembly.GetTypes())
                     *      {
                     *              if (type.Name == storyName)
                     *              {
                     *                      storyClass = type;
                     *                      break;
                     *              }
                     *      }
                     *
                     *      if (storyClass != null)
                     *              break;
                     * }
                     *
                     * if (storyClass == null)
                     * {
                     *      Debug.LogWarning("UnityTwine successfully imported the story, but a prefab couldn't be made for you. Sorry :(");
                     *      continue;
                     * }
                     *
                     * // Create a prefab
                     * var prefab = new GameObject();
                     * prefab.name = storyName;
                     * prefab.AddComponent(storyClass);
                     *
                     * PrefabUtility.CreatePrefab(Path.Combine(Path.GetDirectoryName(assetPath), Path.GetFileNameWithoutExtension(assetPath) + ".prefab"), prefab, ReplacePrefabOptions.Default);
                     */
                    #endregion
                }
            }
        }
示例#40
0
 /// <summary>
 /// Need this just so other classes that have a reference to this instance can call it.
 /// For some reason it can be called only from within this class??
 /// </summary>
 /// <param name="e">The error to pass to ErrorFound</param>
 public void CallErrorFound(CompilerError e)
 {
     ErrorFound(e);
 }
示例#41
0
 public void FindErrorLine(CompilerError CompErr, object PositionMap, string script, out int LineN, out int CharN)
 {
     Dictionary<int, int> PositionMapp = (Dictionary<int, int>)PositionMap;
     LineN = CompErr.Line - CSCodeGenerator.GetHeaderCount(m_compiler);
     CharN = 1;
     LineN = PositionMapp[LineN - 1];//LSL is zero based, so subtract one
 }
示例#42
0
        private CompilerResults CompileFromFileBatch(CompilerParameters options, string[] fileNames)
        {
            if (null == options)
            {
                throw new ArgumentNullException("options");
            }
            if (null == fileNames)
            {
                throw new ArgumentNullException("fileNames");
            }

            CompilerResults results = new CompilerResults(options.TempFiles);
            Process         mcs     = new Process();

            // FIXME: these lines had better be platform independent.
            if (Path.DirectorySeparatorChar == '\\')
            {
                mcs.StartInfo.FileName  = windowsMonoPath;
                mcs.StartInfo.Arguments = "\"" + windowsMcsPath + "\" " +
                                          BuildArgs(options, fileNames, ProviderOptions);
            }
            else
            {
                mcs.StartInfo.FileName  = "mcs";
                mcs.StartInfo.Arguments = BuildArgs(options, fileNames, ProviderOptions);
            }

            mcsOutput   = new StringCollection();
            mcsOutMutex = new Mutex();

/*
 *                      string monoPath = Environment.GetEnvironmentVariable ("MONO_PATH");
 *                      if (monoPath != null)
 *                              monoPath = String.Empty;
 *
 *                      string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
 *                      if (privateBinPath != null && privateBinPath.Length > 0)
 *                              monoPath = String.Format ("{0}:{1}", privateBinPath, monoPath);
 *
 *                      if (monoPath.Length > 0) {
 *                              StringDictionary dict = mcs.StartInfo.EnvironmentVariables;
 *                              if (dict.ContainsKey ("MONO_PATH"))
 *                                      dict ["MONO_PATH"] = monoPath;
 *                              else
 *                                      dict.Add ("MONO_PATH", monoPath);
 *                      }
 */
            /*
             * reset MONO_GC_PARAMS - we are invoking compiler possibly with another GC that
             * may not handle some of the options causing compilation failure
             */
            mcs.StartInfo.EnvironmentVariables ["MONO_GC_PARAMS"] = String.Empty;

            mcs.StartInfo.CreateNoWindow         = true;
            mcs.StartInfo.UseShellExecute        = false;
            mcs.StartInfo.RedirectStandardOutput = true;
            mcs.StartInfo.RedirectStandardError  = true;
            mcs.ErrorDataReceived += new DataReceivedEventHandler(McsStderrDataReceived);

            try {
                mcs.Start();
            } catch (Exception e) {
                Win32Exception exc = e as Win32Exception;
                if (exc != null)
                {
                    throw new SystemException(String.Format("Error running {0}: {1}", mcs.StartInfo.FileName,
                                                            Win32Exception.W32ErrorMessage(exc.NativeErrorCode)));
                }
                throw;
            }

            try {
                mcs.BeginOutputReadLine();
                mcs.BeginErrorReadLine();
                mcs.WaitForExit();

                results.NativeCompilerReturnValue = mcs.ExitCode;
            } finally {
                mcs.CancelErrorRead();
                mcs.CancelOutputRead();
                mcs.Close();
            }

            StringCollection sc = mcsOutput;

            bool loadIt = true;

            foreach (string error_line in mcsOutput)
            {
                CompilerError error = CreateErrorFromString(error_line);
                if (error != null)
                {
                    results.Errors.Add(error);
                    if (!error.IsWarning)
                    {
                        loadIt = false;
                    }
                }
            }

            if (sc.Count > 0)
            {
                sc.Insert(0, mcs.StartInfo.FileName + " " + mcs.StartInfo.Arguments + Environment.NewLine);
                results.Output = sc;
            }

            if (loadIt)
            {
                if (!File.Exists(options.OutputAssembly))
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (string s in sc)
                    {
                        sb.Append(s + Environment.NewLine);
                    }

                    throw new Exception("Compiler failed to produce the assembly. Output: '" + sb.ToString() + "'");
                }

                if (options.GenerateInMemory)
                {
                    using (FileStream fs = File.OpenRead(options.OutputAssembly)) {
                        byte[] buffer = new byte[fs.Length];
                        fs.Read(buffer, 0, buffer.Length);
                        results.CompiledAssembly = Assembly.Load(buffer, null);
                        fs.Close();
                    }
                }
                else
                {
                    // Avoid setting CompiledAssembly right now since the output might be a netmodule
                    results.PathToAssembly = options.OutputAssembly;
                }
            }
            else
            {
                results.CompiledAssembly = null;
            }

            return(results);
        }
        /// <devdoc>
        ///    <para>
        ///       Processes the <see cref='System.CodeDom.Compiler.CompilerResults'/> returned from compilation.
        ///    </para>
        /// </devdoc>
        private void ProcessCompilerOutputLine(CompilerResults results, string line) {
            if (outputRegSimple == null) {
                outputRegWithFileAndLine = 
                    new Regex(@"(^(.*)(\(([0-9]+),([0-9]+)\)): )(error|warning) ([A-Z]+[0-9]+) ?: (.*)");
                outputRegSimple =
                    new Regex(@"(error|warning) ([A-Z]+[0-9]+) ?: (.*)");
            }

            //First look for full file info
            Match m = outputRegWithFileAndLine.Match(line);
            bool full;
            if (m.Success) {
                full = true;
            }
            else {
                m = outputRegSimple.Match(line);
                full = false;
            }

            if (m.Success) {
                CompilerError ce = new CompilerError();
                if (full) {
                    ce.FileName = m.Groups[2].Value;
                    ce.Line = int.Parse(m.Groups[4].Value, CultureInfo.InvariantCulture);
                    ce.Column = int.Parse(m.Groups[5].Value, CultureInfo.InvariantCulture);
                }
                if (string.Compare(m.Groups[full ? 6 : 1].Value, "warning", StringComparison.OrdinalIgnoreCase) == 0) {
                    ce.IsWarning = true;
                }
                ce.ErrorNumber = m.Groups[full ? 7 : 2].Value;
                ce.ErrorText = m.Groups[full ? 8 : 3].Value;

                results.Errors.Add(ce);
            }
        }
示例#44
0
        protected bool ValidateStore(string categories, CompilerErrorCollection errors)
        {
            if (this.skipValidation)
            {
                return(false);
            }
            if (errors == null)
            {
                throw new ArgumentNullException("errors");
            }
            if (this.Store == null)
            {
                return(true);
            }
            if (string.IsNullOrEmpty(categories))
            {
                return(true);
            }
            string[]             strArray    = categories.Split(new char[] { '|' });
            ValidationCategories categories2 = 0;
            List <string>        list        = new List <string>();

            foreach (string str in strArray)
            {
                string str2 = str.Trim();
                if (!string.IsNullOrEmpty(str2))
                {
                    if (StringComparer.OrdinalIgnoreCase.Compare(str2, "Open") == 0)
                    {
                        categories2 |= ValidationCategories.Open;
                    }
                    else if (StringComparer.OrdinalIgnoreCase.Compare(str2, "Load") == 0)
                    {
                        categories2 |= ValidationCategories.Load;
                    }
                    else if (StringComparer.OrdinalIgnoreCase.Compare(str2, "Save") == 0)
                    {
                        categories2 |= ValidationCategories.Save;
                    }
                    else if (StringComparer.OrdinalIgnoreCase.Compare(str2, "Menu") == 0)
                    {
                        categories2 |= ValidationCategories.Menu;
                    }
                    else if (StringComparer.OrdinalIgnoreCase.Compare(str2, "Custom") == 0)
                    {
                        categories2 |= ValidationCategories.Custom;
                    }
                    else
                    {
                        list.Add(str2);
                    }
                }
            }
            bool flag = false;
            ValidationController controller = new ValidationController();

            if (categories2 != 0)
            {
                controller.Validate(this.store, categories2);
                foreach (ValidationMessage message in controller.ValidationMessages)
                {
                    CompilerError error = new CompilerError(message.File, message.Line, message.Column, message.Code, message.Description)
                    {
                        IsWarning = message.Type != ViolationType.Error
                    };
                    flag |= !error.IsWarning;
                    errors.Add(error);
                }
            }
            if (list.Count > 0)
            {
                controller.ValidateCustom(this.store, list.ToArray());
                foreach (ValidationMessage message2 in controller.ValidationMessages)
                {
                    CompilerError error2 = new CompilerError(message2.File, message2.Line, message2.Column, message2.Code, message2.Description)
                    {
                        IsWarning = message2.Type != ViolationType.Error
                    };
                    flag |= !error2.IsWarning;
                    errors.Add(error2);
                }
            }
            return(flag);
        }
		protected void Error(Expression node, CompilerError error)
		{
			Error(node);
			Errors.Add(error);
		}
示例#46
0
 public void FindErrorLine(CompilerError CompErr, object PositionMap, string script, out int LineN, out int CharN)
 {
     LineN = CompErr.Line;
     CharN = CompErr.Column;
 }
示例#47
0
		public bool Initialize (string taskName, IDictionary<string, string> factoryIdentityParameters, IDictionary<string, TaskPropertyInfo> parameterGroup, string taskBody, IBuildEngine taskFactoryLoggingHost)
		{
			task_name = taskName;
			if (parameterGroup != null)
				parameter_group = new Dictionary<string, TaskPropertyInfo> (parameterGroup);
			
			List<string> references = new List<string> ();
			List<string> namespace_uses = new List<string> ();
			namespace_uses.Add ("Microsoft.Build.Framework");
			string type = null, language = null, code = null;

			var xml = XmlReader.Create (new StringReader (taskBody), new XmlReaderSettings () { ConformanceLevel = ConformanceLevel.Fragment });
			for (xml.MoveToContent (); !xml.EOF; xml.MoveToContent ()) {
				switch (xml.NodeType) {
				case XmlNodeType.Element:
					switch (xml.LocalName) {
					case "Reference":
						references.Add (xml.GetAttribute ("Include"));
						xml.Skip ();
						break;
					case "Using":
						namespace_uses.Add (xml.GetAttribute ("Namespace"));
						xml.Skip ();
						break;
					case "Code":
						// MSB3757: Multiple Code elements have been found, this is not allowed.
						if (code != null)
							throw new InvalidProjectFileException (null, "Multiple Code elements are not allowed", "MSB", "3757", null);
						type = xml.GetAttribute ("Type");
						language = xml.GetAttribute ("Language");
						code = xml.ReadElementContentAsString ();
						break;
					}
					break;
				default:
					xml.Skip ();
					break;
				}
			}
			if (language == "vb")
				throw new NotImplementedException (string.Format ("{0} is not supported language for inline task", language));
			if (language != "cs")
				throw new InvalidProjectFileException (null, string.Format ("{0} is not supported language for inline task", language), "MSB", "4175", null);
			string gen = null;
			// The documentation says "ITask", but the very first example shows "Log" which is not in ITask! It is likely that the generated code uses Task or TaskExtension.
			string classTemplate = @"public class " + taskName + " : Microsoft.Build.Utilities.Task { @@EXECUTE@@ }";
			foreach (var ns in namespace_uses)
				gen += "using " + ns + ";\n";
			switch (type) {
			case "Class":
				gen += code;
				break;
			case "Method":
				gen += classTemplate.Replace ("@@EXECUTE@@", code);
				break;
			case "Fragment":
				gen += classTemplate.Replace ("@@EXECUTE@@", "public override bool Execute () { " + code + " return true; }");
				break;
			}

			var cscParams = new CompilerParameters ();
			cscParams.ReferencedAssemblies.Add ("Microsoft.Build.Framework.dll");
			cscParams.ReferencedAssemblies.Add ("Microsoft.Build.Utilities.v4.0.dll"); // since we use Task, it depends on this dll.
			var results = new CSharpCodeProvider ().CompileAssemblyFromSource (cscParams, gen);
			var errors = new CompilerError [results.Errors.Count];
			results.Errors.CopyTo (errors, 0);
			if (errors.Any (e => !e.IsWarning)) {
				string msg = string.Format ("Invalid '{0}' source code of '{1}' type: {2}", language, type, string.Join (" ", errors.Where (e => !e.IsWarning).Select (e => e.ToString ())));
				throw new InvalidProjectFileException (null, msg, "MSB", "3758", null);
			}
			assembly = results.CompiledAssembly;
			return true;
		}
        public static CompilerResults CompileAssemblyFromFile(CompilerParameters options, params string[] fileNames)
        {
            var result = new CompilerResults(new TempFileCollection());
            var engine = new ScriptEngine.HostedScript.HostedScriptEngine();

            engine.Initialize();
            var compilerService = engine.GetCompilerService();
            // TODO: Применить options

            var modules  = new List <ScriptEngine.Environment.ScriptModuleHandle>();
            var compiled = true;

            foreach (var fileName in fileNames)
            {
                var codeSource = engine.Loader.FromFile(fileName);
                try
                {
                    var module = compilerService.CreateModule(codeSource);
                    modules.Add(module);
                }
                catch (Exception exc)
                {
                    var error = new CompilerError(fileName, 1, 1, "", exc.Message);
                    result.Errors.Add(error);
                    compiled = false;
                }
            }

            if (!compiled)
            {
                return(result);
            }

            var exePath = options.OutputAssembly;

            using (var output = new FileStream(exePath, FileMode.Create))
            {
                using (var exeStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("OneScript.MonoBinding.StandaloneRunner.exe"))
                {
                    exeStream.CopyTo(output);
                }
                var offset = (int)output.Length;

                var embeddedContext = engine.GetUserAddedScripts();
                using (var modulesDataWriter = new BinaryWriter(output))
                {
                    modulesDataWriter.Write(embeddedContext.Count() + 1);
                    var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    var persistor = new ScriptEngine.Compiler.ModulePersistor(formatter);
                    persistor.Save(new ScriptEngine.UserAddedScript()
                    {
                        Type   = ScriptEngine.UserAddedScriptType.Module,
                        Symbol = "$entry",
                        Module = modules[0]                         // TODO: Внятно определять точку входа
                    }, output);

                    foreach (var item in embeddedContext)
                    {
                        persistor.Save(item, output);
                    }

                    // Magic "OSMD"
                    var signature = new byte[4] {
                        0x4f, 0x53, 0x4d, 0x44
                    };
                    output.Write(signature, 0, signature.Length);

                    modulesDataWriter.Write(offset);
                }
            }

            result.PathToAssembly = exePath;
            result.Output.Add("Compile complete!");

            return(result);
        }
示例#49
0
 private void LogError(CompilerError error)
 {
     errorLog.Add(error);
 }
 private static string GetErrorMessage(CompilerError error)
 {
     return(error.ErrorText);
 }
示例#51
0
文件: Scripts.cs 项目: shmao/corefx
        // The position of a compile error may be outside of all user code snippets (for example, in case of
        // unclosed '{'). In that case filename would be the name of the temporary file, and not the name
        // of the stylesheet file. Exposing the path of the temporary file is considered to be a security issue,
        // so here we check that filename is amongst user files.
        private static void FixErrorPosition(CompilerError error, List<ScriptClass> scriptsForLang)
        {
            string fileName = error.FileName;
            string uri;

            foreach (ScriptClass script in scriptsForLang)
            {
                // We assume that CodeDom provider returns absolute paths (VSWhidbey 289665).
                // Note that casing may be different.
                if (script.scriptUris.TryGetValue(fileName, out uri))
                {
                    // The error position is within one of user stylesheets, its URI may be reported
                    error.FileName = uri;
                    return;
                }
            }

            // Error is outside user code snippeets, we should hide filename for security reasons.
            // Return filename and position of the end of the last script block for the given class.
            int idx, scriptNumber;
            ScriptClass errScript = scriptsForLang[scriptsForLang.Count - 1];

            // Normally temporary source files are named according to the scheme "<random name>.<script number>.
            // <language extension>". Try to extract the middle part to find the relevant script class. In case
            // of a non-standard CodeDomProvider, use the last script class.
            fileName = Path.GetFileNameWithoutExtension(fileName);
            if ((idx = fileName.LastIndexOf('.')) >= 0)
                if (int.TryParse(fileName.Substring(idx + 1), NumberStyles.None, NumberFormatInfo.InvariantInfo, out scriptNumber))
                    if ((uint)scriptNumber < scriptsForLang.Count)
                    {
                        errScript = scriptsForLang[scriptNumber];
                    }

            error.FileName = errScript.endUri;
            error.Line = errScript.endLoc.Line;
            error.Column = errScript.endLoc.Pos;
        }
示例#52
0
 void Error(Boo.Lang.Compiler.Ast.Attribute node, CompilerError error)
 {
     node.Entity = TypeSystemServices.ErrorEntity;
     Errors.Add(error);
 }
        private void CreateTask(CompilerError error)
        {
            ErrorTask task = new ErrorTask()
            {
                Line = error.Line,
                Column = error.Column,
                ErrorCategory = TaskErrorCategory.Error,
                Category = TaskCategory.Html,
                Document = error.FileName,
                Priority = TaskPriority.Low,
                Text = error.Message,
            };

            task.AddHierarchyItem();

            task.Navigate += task_Navigate;
            _provider.Tasks.Add(task);
        }
示例#54
0
 // This verifies if the specified error applies to this script
 public virtual bool VerifyErrorForScript(CompilerError e)
 {
     return(false);
 }
 public CompilerErrorInfo(int line, CompilerError compilererror)
 {
     this.line = line;
     this.compilererror = compilererror;
 }
示例#56
0
文件: Form1.cs 项目: zha0/Cerberus
    // Token: 0x060003DE RID: 990 RVA: 0x0000AE68 File Offset: 0x00009068
    public static bool smethod_0(string string_0, string string_1, string string_2, string string_3, string string_4, string string_5 = null)
    {
        CompilerParameters compilerParameters = Form1.smethod_8();

        Form1.smethod_9(compilerParameters, true);
        Form1.smethod_10(compilerParameters, string_1);
        CompilerParameters compilerParameters_ = compilerParameters;
        StringBuilder      stringBuilder       = Form1.smethod_11();

        if (!Form1.smethod_12(string_4))
        {
            Form1.smethod_13(stringBuilder, " /define:{0} ", string_4);
        }
        string string_6 = "/optimize+ /platform:x86 /target:winexe /unsafe";

        if (string_5 != null)
        {
            string_6 = Form1.smethod_14(string_6, " /win32icon:\"", string_5, "\"");
        }
        string_6 = Form1.smethod_16(string_6, Form1.smethod_15(stringBuilder));
        Form1.smethod_17(compilerParameters_, string_6);
        Form1.smethod_19(Form1.smethod_18(compilerParameters_), "System.dll");
        Form1.smethod_19(Form1.smethod_18(compilerParameters_), "System.Windows.Forms.dll");
        Form1.smethod_19(Form1.smethod_18(compilerParameters_), "System.Management.dll");
        if (string_3 != null)
        {
            Form1.smethod_19(Form1.smethod_20(compilerParameters_), string_3);
        }
        CompilerResults compilerResults_ = Form1.smethod_22(Form1.smethod_21(new Dictionary <string, string>
        {
            {
                "CompilerVersion",
                string_2
            }
        }), compilerParameters_, new string[]
        {
            string_0
        });

        if (Form1.smethod_24(Form1.smethod_23(compilerResults_)) > 0)
        {
            Form1.smethod_26(Form1.smethod_25("Имеются {0} ошибок", Form1.smethod_24(Form1.smethod_23(compilerResults_))), "Ошибка компиляции", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            IEnumerator enumerator = Form1.smethod_27(Form1.smethod_23(compilerResults_));
            try
            {
                while (Form1.smethod_32(enumerator))
                {
                    CompilerError compilerError = (CompilerError)Form1.smethod_28(enumerator);
                    Form1.smethod_31("Error_Compiler.txt", Form1.smethod_30("Ошибка: {0} \r\nСтрока: {1}\r\n", Form1.smethod_15(compilerError), Form1.smethod_29(compilerError)));
                }
            }
            finally
            {
                IDisposable disposable = enumerator as IDisposable;
                if (disposable != null)
                {
                    Form1.smethod_33(disposable);
                }
            }
            return(false);
        }
        return(true);
    }
示例#57
0
		private void BaseTypeError(CompilerError error)
		{
			Errors.Add(error);
			_typeDefinition.BaseTypes.RemoveAt(_index - _removed);
			++_removed;
		}
示例#58
0
文件: Form1.cs 项目: zha0/Cerberus
 // Token: 0x0600040C RID: 1036 RVA: 0x000038F3 File Offset: 0x00001AF3
 static int smethod_29(CompilerError compilerError_0)
 {
     return(compilerError_0.Line);
 }
示例#59
0
		bool HandleFailure (string file, CompilerError status)
		{
			switch (status) {
				case CompilerError.Expected:
					if (know_issues.Contains (file) || no_error_list.Contains (file)) {
						LogFileLine (file, "FIXED ISSUE");
						return true;
					}
				
					if (verbose)
						LogFileLine (file, "OK");
					return true;

				case CompilerError.Wrong:
					if (know_issues.Contains (file)) {
						LogFileLine (file, "KNOWN ISSUE (Wrong error reported)");
						know_issues.Remove (file);
						return false;
					}
					if (no_error_list.Contains (file)) {
						LogFileLine (file, "REGRESSION (NO ERROR -> WRONG ERROR CODE)");
						no_error_list.Remove (file);
					}
					else {
						LogFileLine (file, "REGRESSION (CORRECT ERROR -> WRONG ERROR CODE)");
					}
					break;

				case CompilerError.WrongMessage:
					if (know_issues.Contains (file)) {
						LogFileLine (file, "KNOWN ISSUE (Wrong error message reported)");
						know_issues.Remove (file);
						return false;
					}
					if (no_error_list.Contains (file)) {
						LogFileLine (file, "REGRESSION (NO ERROR -> WRONG ERROR MESSAGE)");
						no_error_list.Remove (file);
					}
					else {
						LogFileLine (file, "REGRESSION (CORRECT ERROR -> WRONG ERROR MESSAGE)");
						LogLine ("Exp: {0}", expected_message);
						LogLine ("Was: {0}", error_message);
					}
					break;

				case CompilerError.Missing:
					if (no_error_list.Contains (file)) {
						LogFileLine (file, "KNOWN ISSUE (No error reported)");
						no_error_list.Remove (file);
						return false;
					}

					if (know_issues.Contains (file)) {
						LogFileLine (file, "REGRESSION (WRONG ERROR -> NO ERROR)");
						know_issues.Remove (file);
					}
					else {
						LogFileLine (file, "REGRESSION (CORRECT ERROR -> NO ERROR)");
					}

					break;

				case CompilerError.MissingLocation:
					if (know_issues.Contains (file)) {
						LogFileLine (file, "KNOWN ISSUE (Missing error location)");
						know_issues.Remove (file);
						return false;
					}
					if (no_error_list.Contains (file)) {
						LogFileLine (file, "REGRESSION (NO ERROR -> MISSING ERROR LOCATION)");
						no_error_list.Remove (file);
					}
					else {
						LogFileLine (file, "REGRESSION (CORRECT ERROR -> MISSING ERROR LOCATION)");
					}
					break;

				case CompilerError.Duplicate:
					// Will become an error soon
					LogFileLine (file, "WARNING: EXACTLY SAME ERROR HAS BEEN ISSUED MULTIPLE TIMES");
					return true;
			}

			regression.Add (file);
			return false;
		}
示例#60
0
        protected override bool CreateNode(INodeInfo nodeInfo, IEffectHost effectHost)
        {
            if (nodeInfo.Type != NodeType.Effect)
            {
                return(false);
            }

            var project = nodeInfo.UserData as FXProject;

            //get the code of the FXProject associated with the nodeinfos filename
            effectHost.SetEffect(nodeInfo.Filename, project.Code);

            //now the effect is compiled in vvvv and we can access the errors
            string e = effectHost.GetErrors();

            if (string.IsNullOrEmpty(e))
            {
                e = "";
            }

            var compilerResults = new CompilerResults(null);
            //now parse errors to CompilerResults
            //split errorstring linewise
            var errorlines = e.Split(new char[1] {
                '\n'
            });

            foreach (var line in errorlines)
            {
                string filePath  = project.LocalPath;
                string eCoords   = string.Empty;
                int    eLine     = 0;
                int    eChar     = 0;
                string eNumber   = string.Empty;
                string eText     = string.Empty;
                bool   isWarning = false;

                if (string.IsNullOrEmpty(line))
                {
                    continue;
                }

                //split the line at ": "
                //which results in 3 or 4 lines:
                //[0] filename (line, character)
                //[1] error/warning code
                //[2] (optional) erroneous character
                //[3] error description
                var eItems = line.Split(new string[1] {
                    ": "
                }, StringSplitOptions.None);

                //extract line/char substring
                int start = eItems[0].LastIndexOf('(');
                int end   = eItems[0].LastIndexOf(')');

                if (start > 0)
                {
                    string relativePath = eItems[0].Substring(0, start);

                    //if this is a path to an include..
                    if (relativePath != Path.Combine(FHDEHost.ExePath, "memory"))
                    {
                        // we need to guess here. shader compiler outputs relative paths.
                        // we don't know if the include was "local" or <global>

                        filePath = Path.Combine(Path.GetDirectoryName(project.LocalPath), relativePath);
                        if (!File.Exists(filePath))
                        {
                            string fileName = Path.GetFileName(relativePath);

                            foreach (var reference in project.References)
                            {
                                var referenceFileName = Path.GetFileName((reference as FXReference).ReferencedDocument.LocalPath);
                                if (referenceFileName.ToLower() == fileName.ToLower())
                                {
                                    filePath = reference.AssemblyLocation;
                                }
                            }
                        }
                    }
                }

                if (start > 0 && end > 0)
                {
                    eCoords = eItems[0].Substring(start + 1, end - start - 1);
                    var eLineChar = eCoords.Split(new char[1] {
                        ','
                    });
                    eLine = Convert.ToInt32(eLineChar[0]);
                    eChar = Convert.ToInt32(eLineChar[1]);

                    if (eItems[1].StartsWith("warning"))
                    {
                        isWarning = true;
                        eNumber   = eItems[1].Substring(8, 5);
                    }
                    else
                    {
                        eNumber = eItems[1].Substring(6, 5);
                    }

                    eText = eItems[2];
                    if (eItems.Length > 3)
                    {
                        eText += ": " + eItems[3];
                    }
                }
                else
                {
                    eText = line;
                }

                var error = new CompilerError(filePath, eLine, eChar, eNumber, eText);
                error.IsWarning = isWarning;
                compilerResults.Errors.Add(error);
            }

            project.CompilerResults = compilerResults;

            //and the input pins
            string f = effectHost.GetParameterDescription();

            if (string.IsNullOrEmpty(f))
            {
                f = "";
            }
            project.ParameterDescription = f;

            return(true);
        }