コード例 #1
0
        public override void Process(LOLMethod lm, CompilerErrorCollection errors, ILGenerator gen)
        {
            breakIdx = lm.breakables.Count - 1;
            if (label == null)
            {
                while (breakIdx >= 0 && !lm.breakables[breakIdx].ContinueLabel.HasValue)
                {
                    breakIdx--;
                }
            }
            else
            {
                while (breakIdx >= 0 && (lm.breakables[breakIdx].Name != label || !lm.breakables[breakIdx].ContinueLabel.HasValue))
                {
                    breakIdx--;
                }
            }

            if (breakIdx < 0)
            {
                if (label == null)
                {
                    errors.Add(new CompilerError(location.filename, location.startLine, location.startColumn, null, "MOAR encountered, but nothing to continue!"));
                }
                else
                {
                    errors.Add(new CompilerError(location.filename, location.startLine, location.startColumn, null, string.Format("Named MOAR \"{0}\" encountered, but nothing by that name exists to continue!", label)));
                }
            }
        }
コード例 #2
0
        public override CompilerResults CompileAssemblyFromFile(CompilerParameters options, params string[] fileNames)
        {
            var units  = new CodeCompileUnit[fileNames.Length];
            var errors = new CompilerErrorCollection();
            var syntax = new Parser(options);

            for (int i = 0; i < fileNames.Length; i++)
            {
                try
                {
                    units[i] = syntax.Parse(new StreamReader(fileNames[i]), fileNames[i]);
                }
#if !DEBUG
                catch (ParseException e)
                {
                    errors.Add(new CompilerError(e.Source, e.Line, 0, e.Message.GetHashCode().ToString(), e.Message));
                }
                catch (Exception e)
                {
                    errors.Add(new CompilerError {
                        ErrorText = e.Message
                    });
                }
#endif
                finally
                {
                }
            }

            var results = CompileAssemblyFromDom(options, units);
            results.Errors.AddRange(errors);

            return(results);
        }
コード例 #3
0
ファイル: TemplateParser.cs プロジェクト: chenrensong/T4
        /// <summary>
        /// Check to make sure that the blocks are in correct sequence i.e.
        /// * no statements after the first classfeature block, and
        /// * if the template contains a class block then it ends with a class block.
        /// If not, log errors.
        /// </summary>
        private static void CheckBlockSequence(IList <Block> blocks, CompilerErrorCollection errors)
        {
            bool flag  = false;
            bool flag2 = false;

            foreach (Block block2 in blocks)
            {
                if (!flag)
                {
                    if (block2.Type == BlockType.ClassFeature)
                    {
                        flag = true;
                    }
                }
                else if (block2.Type == BlockType.Directive || block2.Type == BlockType.Statement)
                {
                    CompilerError compilerError = new CompilerError(block2.FileName, block2.StartLineNumber, block2.StartColumnNumber, null, string.Format(CultureInfo.CurrentCulture, Resources.WrongBlockSequence, Enum.GetName(typeof(BlockType), block2.Type)));
                    compilerError.IsWarning = false;
                    errors.Add(compilerError);
                    flag2 = true;
                }
            }
            if (flag && !flag2)
            {
                Block block = blocks[blocks.Count - 1];
                if (block.Type != BlockType.ClassFeature && (block.Type != BlockType.BoilerPlate || !allNewlineRegex.Match(block.Text).Success))
                {
                    CompilerError compilerError2 = new CompilerError(block.FileName, block.StartLineNumber, block.StartColumnNumber, null, Resources.WrongFinalBlockType);
                    compilerError2.IsWarning = false;
                    errors.Add(compilerError2);
                }
            }
        }
コード例 #4
0
        public override void Process(LOLMethod lm, CompilerErrorCollection errors, ILGenerator gen)
        {
            m_breakLabel = gen.DefineLabel();
            if (defaultCase != null)
            {
                defaultLabel = gen.DefineLabel();
            }

            Type t = null;

            foreach (Case c in cases)
            {
                if (c.name.GetType() != t)
                {
                    if (t != null)
                    {
                        errors.Add(new CompilerError(location.filename, location.startLine, location.startColumn, null, "A WTF statement cannot have OMGs with more than one type"));
                        break;
                    }
                    else
                    {
                        t = c.name.GetType();
                    }
                }
            }

            if (t != typeof(int) && t != typeof(string))
            {
                errors.Add(new CompilerError(location.filename, location.startLine, location.startColumn, null, "OMG labels must be NUMBARs or YARNs"));
            }

            //Sort the cases
            sortedCases = new Case[cases.Count];
            cases.CopyTo(sortedCases);
            Array.Sort <Case>(sortedCases);

            //Check for duplicates
            for (int i = 1; i < sortedCases.Length; i++)
            {
                if (sortedCases[i - 1].CompareTo(sortedCases[i]) == 0)
                {
                    errors.Add(new CompilerError(location.filename, location.startLine, location.startColumn, null, string.Format("Duplicate OMG label: \"{0}\"", sortedCases[i].name)));
                }
            }

            //Process child statements
            lm.breakables.Add(this);
            control.Process(lm, errors, gen);
            foreach (Case c in cases)
            {
                c.statement.Process(lm, errors, gen);
            }
            defaultCase.Process(lm, errors, gen);
            lm.breakables.RemoveAt(lm.breakables.Count - 1);
        }
コード例 #5
0
        private bool BuildHashConfiguration(Block block)
        {
            _skip    = false;
            _applied = true;

            if (!block.IsEmpty)
            {
                for (int i = 0; i < block.Statements.Count;)
                {
                    var statement  = block.Statements[i];
                    var expression = statement as ExpressionStatement;

                    if (expression == null)
                    {
                        _compileErrors.Add(CompilerErrorFactory.CustomError(
                                               statement.LexicalInfo, "Unrecgonized configuration syntax"));
                        return(false);
                    }

                    _found = false;
                    Visit(expression.Expression);

                    if (_found == false)
                    {
                        _compileErrors.Add(CompilerErrorFactory.CustomError(
                                               expression.LexicalInfo, "Unrecgonized configuration syntax"));
                        return(false);
                    }

                    if (_applied)
                    {
                        if (_skip == false)
                        {
                            block.Statements.RemoveAt(i);
                        }
                        else
                        {
                            ++i;
                        }
                    }
                    else
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
コード例 #6
0
        private Assembly CompileAssembly(Node node, string url, CompilerErrorCollection errors)
        {
            CompilerContext result = Compile(url);

            if (result.Errors.Count > 0)
            {
                errors.Add(new CompilerError(node.LexicalInfo, "Failed to add a file reference"));
                foreach (CompilerError err in result.Errors)
                {
                    errors.Add(err);
                }
                return(null);
            }
            return(result.GeneratedAssembly);
        }
コード例 #7
0
        public CompilerErrorCollection TryCompileModule(dynamic moduleObject)
        {
            RequireSystemSigned();

            CompilerErrorCollection compilerErrors = new CompilerErrorCollection();

            Contract.Module module = ModuleManager.Session.Modules.Where(P => P.ID == moduleObject.ID).FirstOrDefault();

            if (module != null && !module.Locked)
            {
                module            = Contract.Module.FromString(module.ToString()); // Create a copy of the module
                module.References = ((ThirdParty.JsonArray)moduleObject.References).Select(r => (string)r).ToList();

                ModuleReversion moduleReversion = new ModuleReversion()
                {
                    Version = module.LatestReversion.Version + 1, Updated = DateTime.UtcNow, Classes = new List <ModuleClass>()
                };
                moduleReversion.Classes = ((ThirdParty.JsonArray)moduleObject.LatestReversion.Classes).Select(p => new ModuleClass()
                {
                    Name = ((dynamic)p).Name, Data = ((dynamic)p).Data
                }).ToList();

                module.LatestReversion = moduleReversion;
                module.CompileClasses(out compilerErrors, false);
            }
            else
            {
                compilerErrors.Add(new CompilerError("", 0, 0, "", "Module is locked."));
            }

            return(compilerErrors);
        }
コード例 #8
0
        public bool InitializeExtension(MethodInvocationExpression extension,
                                        MacroStatement macro,
                                        CompilerErrorCollection compileErrors)
        {
            _extension     = extension;
            _compileErrors = compileErrors;

            if (macro.Body.IsEmpty)
            {
                if (macro.Arguments.Count != 1 ||
                    (ExtractMethod(macro.Arguments[0]) == false && _instanceAcessor == null))
                {
                    _compileErrors.Add(CompilerErrorFactory.CustomError(macro.LexicalInfo,
                                                                        "A createUsing statement must be in the form (@factory.<CreateMethod> | InstanceMethod)"));
                    return(false);
                }
                ConfigureFactoryAccessor();
            }
            else
            {
                ConfigureFactoryMethod(macro);
            }

            return(true);
        }
コード例 #9
0
        private Expression CreateBuilderIfNeeded(MethodInvocationExpression child, string name)
        {
            int argsCount = child.Arguments.Count;

            if (argsCount >= 1)
            {
                ReferenceExpression builder = child.Arguments[0] as ReferenceExpression;
                if (builder != null)
                {
                    Block block;
                    if (argsCount > 2 || (argsCount == 2 && !MacroHelper.IsNewBlock(child, out block)))
                    {
                        _compileErrors.Add(CompilerErrorFactory.CustomError(
                                               child.Arguments[0].LexicalInfo,
                                               "Builder syntax must be in the format builder, prop: value,..."));
                        return(null);
                    }

                    MethodInvocationExpression builderCtor = new MethodInvocationExpression(builder);
                    builderCtor.Arguments.Add(new StringLiteralExpression(name));
                    builderCtor.NamedArguments.Extend(child.NamedArguments);
                    return(builderCtor);
                }
            }

            return(new StringLiteralExpression(name));
        }
コード例 #10
0
        public CompilerError AddCompilerError()
        {
            var error = new CompilerError();

            Errors.Add(error);
            return(error);
        }
コード例 #11
0
            private void LogError(bool isError, int line, int column, string token, string message)
            {
                var error = new CompilerError(m_filePath, line, column, token, message);

                error.IsWarning = !isError;
                m_errors.Add(error);
            }
コード例 #12
0
        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;
            }
        }
コード例 #13
0
        public override void Process(LOLMethod lm, CompilerErrorCollection errors, ILGenerator gen)
        {
            if (arguments.Count != func.Arity && !func.IsVariadic)
            {
                errors.Add(new CompilerError(location.filename, location.startLine, location.startColumn, null, string.Format("Function \"{0}\" requires {1} arguments, passed {2}.", func.Name, func.Arity, arguments.Count)));
            }
            else if (arguments.Count < func.Arity && func.IsVariadic)
            {
                errors.Add(new CompilerError(location.filename, location.startLine, location.startColumn, null, string.Format("Function \"{0}\" requires at least {1} arguments, passed {2}.", func.Name, func.Arity, arguments.Count)));
            }

            foreach (Expression arg in arguments)
            {
                arg.Process(lm, errors, gen);
            }
        }
コード例 #14
0
        public bool InitializeExtension(MethodInvocationExpression extension,
                                        MacroStatement macro,
                                        CompilerErrorCollection compileErrors)
        {
            _extension     = extension;
            _compileErrors = compileErrors;

            if (macro.Arguments.Count != 1 ||
                (!ExtractMethod(macro.Arguments[0]) && _instanceAcessor == null))
            {
                _compileErrors.Add(CompilerErrorFactory.CustomError(macro.LexicalInfo,
                                                                    "A createUsing statement must be in the form @factory.<CreateMethod>[()]"));
                return(false);
            }

            if (_instanceAcessor == null)
            {
                _extension.Arguments.Add(Component);
                _extension.Arguments.Add(Method);
            }
            else
            {
                _extension.Arguments.Add(_instanceAcessor);
            }

            return(true);
        }
コード例 #15
0
        public CompilerErrorCollection UpdateModule(dynamic moduleObject)
        {
            RequireSystemSigned();

            CompilerErrorCollection compilerErrors = new CompilerErrorCollection();

            Contract.Module module = ModuleManager.Session.Modules.Where(P => P.ID == moduleObject.ID).FirstOrDefault();

            if (module == null)
            {
                module = new Contract.Module()
                {
                    ID         = moduleObject.ID,
                    References = ((ThirdParty.JsonArray)moduleObject.References).Select(r => (string)r).ToList(),
                };

                ModuleReversion moduleReversion = new ModuleReversion()
                {
                    Version = 1, Updated = DateTime.UtcNow, Classes = new List <ModuleClass>()
                };
                moduleReversion.Classes = ((ThirdParty.JsonArray)moduleObject.LatestReversion.Classes).Select(p => new ModuleClass()
                {
                    Name = ((dynamic)p).Name, Data = ((dynamic)p).Data
                }).ToList();

                module.LatestReversion = moduleReversion;
                ModuleManager.Session.AppendModuleReversion(module.ID, moduleReversion);

                ModuleManager.Session.Modules.Add(module);
                module.CompileClasses(out compilerErrors);
                module.Save();
            }
            else if (!module.Locked)
            {
                module.References = ((ThirdParty.JsonArray)moduleObject.References).Select(r => (string)r).ToList();
                ModuleReversion moduleReversion = new ModuleReversion()
                {
                    Version = module.LatestReversion.Version + 1, Updated = DateTime.UtcNow, Classes = new List <ModuleClass>()
                };
                moduleReversion.Classes = ((ThirdParty.JsonArray)moduleObject.LatestReversion.Classes).Select(p => new ModuleClass()
                {
                    Name = ((dynamic)p).Name, Data = ((dynamic)p).Data
                }).ToList();

                module.LatestReversion = moduleReversion;
                ModuleManager.Session.AppendModuleReversion(module.ID, moduleReversion);

                module.CompileClasses(out compilerErrors);
                module.Save();
            }
            else
            {
                compilerErrors.Add(new CompilerError("", 0, 0, "", "Module is locked"));
            }

            return(compilerErrors);
        }
コード例 #16
0
        CompilerError AddError(string message)
        {
            CompilerError err = new CompilerError();

            err.Column    = err.Line = -1;
            err.ErrorText = message;
            errors.Add(err);
            return(err);
        }
コード例 #17
0
        public string GenerateCode(out CompilerErrorCollection errors)
        {
            errors = new CompilerErrorCollection();

            // Create the engine
            RazorTemplateEngine engine = new RazorTemplateEngine(this);

            // Generate code
            GeneratorResults results = null;

            try
            {
                Stream stream = File.OpenRead(_fullPath);
                using (var reader = new StreamReader(stream, Encoding.Default, detectEncodingFromByteOrderMarks: true))
                {
                    results = engine.GenerateCode(reader, className: DefaultClassName, rootNamespace: DefaultNamespace, sourceFileName: _fullPath);
                }
            } catch (Exception e) {
                errors.Add(new CompilerError(FullPath, 1, 1, null, e.ToString()));
                //Returning null signifies that generation has failed
                return(null);
            }

            // Output errors
            foreach (RazorError error in results.ParserErrors)
            {
                errors.Add(new CompilerError(FullPath, error.Location.LineIndex + 1, error.Location.CharacterIndex + 1, null, error.Message));
            }

            try
            {
                using (StringWriter writer = new StringWriter()) {
                    //Generate the code
                    writer.WriteLine("#pragma warning disable 1591");
                    _codeDomProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, writer, _codeGeneratorOptions);
                    writer.WriteLine("#pragma warning restore 1591");
                    return(writer.ToString());
                }
            } catch (Exception e) {
                errors.Add(new CompilerError(FullPath, 1, 1, null, e.ToString()));
                //Returning null signifies that generation has failed
                return(null);
            }
        }
コード例 #18
0
        /// <summary>
        /// Creates an Assembly from DynamicAssembly definition
        /// </summary>
        /// <param name="assemblyDefinition">assembly description</param>
        /// <returns>result with assembly or error info</returns>
        public static CompileResult CompileDynamicAssembly(DynamicAssembly assemblyDefinition)
        {
            CodeDomProvider    codeDomProvider    = CodeDomProvider.CreateProvider("CSharp");
            CompilerParameters compilerParameters = new CompilerParameters();

            compilerParameters.CompilerOptions = "/t:library /platform:anycpu /lib:" + "\"" +
                                                 (String.IsNullOrWhiteSpace(assemblyDefinition.ReferencesPath) ? GetCurrentPath() : assemblyDefinition.ReferencesPath) + "\"";
            compilerParameters.IncludeDebugInformation = false;
            //compilerParameters.OutputAssembly = assemblyDefinition.Name;
            compilerParameters.GenerateInMemory   = true;
            compilerParameters.GenerateExecutable = false;

            foreach (var item in assemblyDefinition.References)
            {
                compilerParameters.ReferencedAssemblies.Add(item);
            }

            List <string> codeModules = new List <string>();

            foreach (DynamicClass item in assemblyDefinition.Classes)
            {
                string code = DynamicClass.Template;
                code = DynamicClass.AddUsingsToTemplate(item, code);
                code = DynamicClass.AddInterfacesToTemplate(item, code);
                code = DynamicClass.AddNamespaceToTemplate(String.IsNullOrWhiteSpace(item.Namespace) ? assemblyDefinition.Name : item.Namespace, code);
                code = DynamicClass.AddNameToTemplate(item, code);
                code = DynamicClass.AddPropertiesToTemplate(item, code);
                code = DynamicClass.AddMethodsToTemplate(item, code);
                codeModules.Add(code);
            }

            foreach (DynamicCustomClass item in assemblyDefinition.CustomClasses)
            {
                codeModules.Add(item.Code);
            }

            // we dont allow empty class definitions(fun fact: its okay for the c# compiler)
            foreach (DynamicCustomClass item in assemblyDefinition.CustomClasses)
            {
                if (String.IsNullOrWhiteSpace(item.Code))
                {
                    CompilerErrorCollection collection  = new CompilerErrorCollection();
                    CompilerError           customError = new CompilerError("CustomClass", 0, 0, "Custom", "Unable to compile an empty code module.");
                    collection.Add(customError);
                    return(new CompileResult(codeModules.ToArray(), collection, null));
                }
            }

            CompilerResults compilerResults = codeDomProvider.CompileAssemblyFromSource(compilerParameters, codeModules.ToArray());

            codeDomProvider.Dispose();

            return(new CompileResult(codeModules.ToArray(), compilerResults.Errors, compilerResults.Errors.Count > 0 ? null : compilerResults.CompiledAssembly));
        }
コード例 #19
0
            public override void Done(CompilerErrorCollection result)
            {
                if (!FileSystemHelper.FileCompare(TempFilePath, FilePath))
                {
                    string message = String.Format("Error during file generation. The target file '{0}' is read-only, but different from the transformation result. This problem can be a sign of an inconsistent source code package. Compile and check-in the current version of the file from the development environment or remove the read-only flag from the generation result. To compile a solution that contains messaging project on a build server, you can also exclude the messaging project from the build-server solution or set the <OverwriteReadOnlyFiles> msbuild project parameter to 'true' in the messaging project file.",
                                                   Path.GetFullPath(FilePath));
                    result.Add(new CompilerError(String.Empty, 0, 0, null, message));
                }

                base.Done(result);
            }
コード例 #20
0
        public static void OnTransformationEnded(TextTransformation transformation)
        {
            try
            {
                if (transformation == null)
                {
                    throw new ArgumentNullException("transformation");
                }

                if (TransformationContext.transformation != null && !TransformationContext.Errors.HasErrors)
                {
                    //Update the files in the default AppDomain to avoid remoting errors on Database projects
                    //BindingFlags invokeInternalStaticMethod = BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.NonPublic;
                    //AppDomain defaultDomain = (AppDomain)typeof(AppDomain).InvokeMember("GetDefaultDomain", invokeInternalStaticMethod, null, null, null, CultureInfo.InvariantCulture);

                    //var bd1 = defaultDomain.BaseDirectory;

                    //var setup = new AppDomainSetup();
                    //setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
                    //AppDomain serverAppDomain = AppDomain.CreateDomain("ServerAppDomain", null, setup);

                    //var udf = TransformationContext.outputManager;
                    //defaultDomain.DoCallBack(udf.UpdateFiles);

                    OutputProcessor.Host = Host;
                    outputManager.UpdateFiles();
                }

                TransformationContext.transformation = null;
                TransformationContext.outputManager  = null;
                TransformationContext.project        = null;
                TransformationContext.projectItem    = null;
                TransformationContext.dte            = null;

                if (TransformationContext.TransformationEnded != null)
                {
                    TransformationContext.TransformationEnded(null, EventArgs.Empty);
                }
            }
            catch (TransformationException e)
            {
                // Display expected errors in the Error List window without the call stack
                CompilerErrorCollection errors = new CompilerErrorCollection();
                CompilerError           error  = new CompilerError();
                error.ErrorText = e.Message;
                error.FileName  = Host.TemplateFile;
                errors.Add(error);
                TransformationContext.Host.LogErrors(errors);
            }
            finally
            {
                DestroyTraceListener();
            }
        }
コード例 #21
0
ファイル: TemplateParser.cs プロジェクト: chenrensong/T4
 /// <summary>
 /// Adds warnings to the error collection if unexpected unescaped start/end tags are found within the template
 /// </summary>
 private static void WarnAboutUnexpectedTags(IEnumerable <Block> blocks, CompilerErrorCollection errors)
 {
     foreach (Block block in blocks)
     {
         if (unescapedTagFindingRegex.Match(block.Text).Success)
         {
             CompilerError compilerError = new CompilerError(block.FileName, block.StartLineNumber, block.StartColumnNumber, null, Resources.UnexpectedTag);
             compilerError.IsWarning = false;
             errors.Add(compilerError);
         }
     }
 }
コード例 #22
0
        public string GenerateCode(out CompilerErrorCollection errors)
        {
            errors = new CompilerErrorCollection();

            var engine = new RewritingRazorTemplateEngine(this, new PreprocessedAttributeRewriter());

            // Generate code
            GeneratorResults results;

            try {
                Stream stream = File.OpenRead(FullPath);
                using (var reader = new StreamReader(stream, Encoding.Default, true)) {
                    results = engine.GenerateCode(reader, DefaultClassName, DefaultNamespace, FullPath);
                }
            } catch (Exception e) {
                errors.Add(new CompilerError(FullPath, 1, 1, null, e.ToString()));
                //Returning null signifies that generation has failed
                return(null);
            }

            // Output errors
            foreach (RazorError error in results.ParserErrors)
            {
                errors.Add(new CompilerError(FullPath, error.Location.LineIndex + 1, error.Location.CharacterIndex + 1, null, error.Message));
            }

            try {
                using (var writer = new StringWriter()) {
                    writer.WriteLine("#pragma warning disable 1591");
                    _codeDomProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, writer, codeGeneratorOptions);
                    writer.WriteLine("#pragma warning restore 1591");
                    string s = writer.ToString();
                    return(MakeLineDirectivePathsRelative(Path.GetDirectoryName(FullPath), s));
                }
            } catch (Exception e) {
                errors.Add(new CompilerError(FullPath, 1, 1, null, e.ToString()));
                //Returning null signifies that generation has failed
                return(null);
            }
        }
        /// <summary>
        /// Load a SFSchemaLanguage model
        /// </summary>
        /// <param name="store"></param>
        /// <param name="inputFile"></param>
        /// <returns></returns>
        public static ISpySoft.SFSchemaLanguage.DomainModel.SchemaModel Load(CompilerErrorCollection errors, Store store, string inputFile)
        {
            if (errors == null)
            {
                throw new ArgumentNullException("errors");
            }
            if (store == null)
            {
                throw new ArgumentNullException("store");
            }
            if (inputFile == null)
            {
                throw new ArgumentNullException("inputFile");
            }

            using (System.IO.FileStream fileStream = File.OpenRead(inputFile))
            {
                // Get the set before we load the file
                IList previousSet = store.ElementDirectory.GetElements(ISpySoft.SFSchemaLanguage.DomainModel.SchemaModel.MetaClassGuid);
                try
                {
                    using (Transaction t = store.TransactionManager.BeginTransaction("ProcessorLoad", true))
                    {
                        XmlSerialization.DeserializeStore(store, fileStream, 1, 1, SFSchemaLanguageFileLoader.UpgradeFileFormat, SFSchemaLanguageFileLoader.Deserialized);
                        t.Commit();
                    }
                }
                catch (Exception e)
                {
                    errors.Add(new CompilerError(inputFile, -1, -1, "", e.ToString()));
                }

                IList candidates = store.ElementDirectory.GetElements(ISpySoft.SFSchemaLanguage.DomainModel.SchemaModel.MetaClassGuid);
                // Remove the previous items from the new list, to leave just the newly added item
                foreach (ISpySoft.SFSchemaLanguage.DomainModel.SchemaModel previous in previousSet)
                {
                    if (previous != null)
                    {
                        candidates.Remove(previous);
                    }
                }

                foreach (ISpySoft.SFSchemaLanguage.DomainModel.SchemaModel candidate in candidates)
                {
                    if (candidate != null)
                    {
                        return(candidate as ISpySoft.SFSchemaLanguage.DomainModel.SchemaModel);
                    }
                }
            }
            return(null);
        }
コード例 #24
0
        public bool GetNode(Expression expression, bool asAttribute,
                            CompilerErrorCollection compileErrors)
        {
            _isAttribute   = asAttribute;
            _compileErrors = compileErrors;

            Visit(expression);

            if (_node == null)
            {
                _compileErrors.Add(CompilerErrorFactory.CustomError(expression.LexicalInfo,
                                                                    "Unrecgonized configuration node syntax"));
                return(false);
            }

            return(true);
        }
コード例 #25
0
 public static CompilerErrorCollection ParseOutput(string output)
 {
     using (var reader = new StringReader(output))
     {
         var    errors = new CompilerErrorCollection();
         string line;
         while ((line = reader.ReadLine()) != null)
         {
             var err = ParseError(line);
             if (err != null)
             {
                 errors.Add(err);
             }
         }
         return(errors);
     }
 }
コード例 #26
0
        public static CompilerErrorCollection Compile(string name, string outputPath, string[] references, string[] files, bool includePdb)
        {
            var pdbPath = Path.ChangeExtension(outputPath, "pdb");

            var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                          .WithOptimizationLevel(OptimizationLevel.Debug)       // currently no way to specify debug vs release. We still want pdb files with release mode for bug reports
                          .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default);

            var parseOptions = new CSharpParseOptions(LanguageVersion.Latest);

            var emitOptions = new EmitOptions();

            if (Type.GetType("Mono.Runtime") != null)
            {
                emitOptions = emitOptions.WithDebugInformationFormat(DebugInformationFormat.PortablePdb);
            }

            var refs = references.Select(s => MetadataReference.CreateFromFile(s));
            var src  = files.Select(f => SyntaxFactory.ParseSyntaxTree(File.ReadAllText(f), parseOptions, f, Encoding.UTF8));
            var comp = CSharpCompilation.Create(name, src, refs, options);

            EmitResult results;

            using (var peStream = File.OpenWrite(outputPath))
                using (var pdbStream = includePdb ? File.OpenWrite(pdbPath) : null) {
                    results = comp.Emit(peStream, pdbStream, options: emitOptions);
                }

            var errors = new CompilerErrorCollection();

            foreach (var d in results.Diagnostics.Where(d => d.Severity >= DiagnosticSeverity.Warning))
            {
                var loc = d.Location.GetLineSpan();
                errors.Add(new CompilerError {
                    ErrorNumber = d.Id,
                    IsWarning   = d.Severity == DiagnosticSeverity.Warning,
                    ErrorText   = d.GetMessage(),
                    FileName    = loc.Path ?? "",
                    Line        = loc.StartLinePosition.Line,
                    Column      = loc.StartLinePosition.Character
                });
            }

            return(errors);
        }
コード例 #27
0
        protected bool Compile(string outFile, string[] sourceFiles, params string[] references)
        {
            CSharpCodeProvider provider = new CSharpCodeProvider();
            CompilerParameters cp       = new CompilerParameters();

            cp.ReferencedAssemblies.AddRange(references);
            cp.GenerateExecutable = false;
            cp.OutputAssembly     = outFile;
            cp.GenerateInMemory   = false;
            //生成调试文件
            cp.IncludeDebugInformation = CompilerConfig.EnableDebug;
            try
            {
                CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceFiles);
                if (cr.Errors.Count > 0)
                {
                    if (OnCompileFailed != null)
                    {
                        CompileException exp = new CompileException(sourceFiles, cr.PathToAssembly, cr.Errors);
                        OnCompileFailed(exp);
                    }
                }
                else
                {
                    if (OnCompileSuccess != null)
                    {
                        OnCompileSuccess(sourceFiles, outFile);
                    }
                }
                return(cr.Errors.Count == 0);
            }
            catch (Exception e) {
                if (OnCompileFailed != null)
                {
                    CompilerErrorCollection t = new CompilerErrorCollection();
                    t.Add(new CompilerError()
                    {
                        ErrorText = e.Message
                    });
                    CompileException exp = new CompileException(sourceFiles, outFile, t);
                    OnCompileFailed(exp);
                }
                return(false);
            }
        }
コード例 #28
0
        public override void Process(LOLMethod lm, CompilerErrorCollection errors, ILGenerator gen)
        {
            if (operation != null)
            {
                FunctionRef fr = ((operation as AssignmentStatement).rval as FunctionExpression).func;
                if (fr.Arity > 1 || (fr.IsVariadic && fr.Arity != 0))
                {
                    errors.Add(new CompilerError(location.filename, location.startLine, location.startColumn, null, "Function used in loop must take 1 argument"));
                }
            }

            m_breakLabel    = gen.DefineLabel();
            m_continueLabel = gen.DefineLabel();

            lm.breakables.Add(this);
            statements.Process(lm, errors, gen);
            lm.breakables.RemoveAt(lm.breakables.Count - 1);
        }
コード例 #29
0
        public void Constructor1_Deny_Unrestricted()
        {
            CompilerErrorCollection coll = new CompilerErrorCollection(array);

            coll.CopyTo(array, 0);
            Assert.AreEqual(1, coll.Add(ce), "Add");
            Assert.AreSame(ce, coll[0], "this[int]");
            coll[0] = ce;
            coll.AddRange(array);
            coll.AddRange(coll);
            Assert.IsTrue(coll.Contains(ce), "Contains");
            Assert.AreEqual(0, coll.IndexOf(ce), "IndexOf");
            coll.Insert(0, ce);
            coll.Remove(ce);
            ce.IsWarning = true;
            Assert.IsFalse(coll.HasErrors, "HasErrors");
            Assert.IsTrue(coll.HasWarnings, "HasWarnings");
        }
コード例 #30
0
        private void LogError(string message, Location location, bool isWarning)
        {
            var err = new CompilerError();

            err.ErrorText = message;
            if (location.FileName != null)
            {
                err.Line     = location.Line;
                err.Column   = location.Column;
                err.FileName = location.FileName ?? string.Empty;
            }
            else
            {
                err.FileName = rootFileName ?? string.Empty;
            }
            err.IsWarning = isWarning;
            errors.Add(err);
        }