Пример #1
0
        public static string ReplaceStringLiteralsWithVariables(string text, IEnumerable<string> macros, Func<int, int, string, string, string> onReplace)
        {
            var setting = new CompilerSettings();
            foreach (var macro in macros) setting.ConditionalSymbols.Add(macro);

            var tree = SyntaxTree.Parse(text, string.Empty, setting);
            tree.Freeze();

            var doc = new StringBuilderDocument(text);
            using (var editor = new DocumentScript(doc, FormattingOptionsFactory.CreateAllman(), TextEditorOptions.Default)) {
                var originDoc = editor.OriginalDocument;

                foreach (var node in tree.Descendants.OfType<PrimitiveExpression>().Where(e => e.Value is string)) {
                    var line = originDoc.GetLineByNumber(node.StartLocation.Line);
                    var result = onReplace(node.StartLocation.Line, node.StartLocation.Column, originDoc.GetText(line), node.Value as string);
                    if (result != null) {
                        var names = result.Split('.');
                        Expression exp = new IdentifierExpression(names.First());
                        foreach (var name in names.Skip(1)) exp = exp.Member(name);

                        editor.Replace(node, exp);
                    }
                }
            }

            return doc.Text;
        }
Пример #2
0
        public static SyntaxTree Parse(ITextSource textSource, string fileName = "", CompilerSettings settings = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            cancellationToken.ThrowIfCancellationRequested();
            var parser = new CSharpParser(settings);

            return(parser.Parse(textSource, fileName));
        }
Пример #3
0
		public CSharpProjectContent()
		{
			this.unresolvedFiles = new Dictionary<string, IUnresolvedFile>(Platform.FileNameComparer);
			this.assemblyReferences = new List<IAssemblyReference>();
			this.compilerSettings = new CompilerSettings();
			compilerSettings.Freeze();
		}
Пример #4
0
 public CSharpProjectContent()
 {
     this.unresolvedFiles    = new Dictionary <string, IUnresolvedFile>(Platform.FileNameComparer);
     this.assemblyReferences = new List <IAssemblyReference>();
     this.compilerSettings   = new CompilerSettings();
     compilerSettings.Freeze();
 }
Пример #5
0
 protected CSharpProjectContent(CSharpProjectContent pc)
 {
     this.assemblyName       = pc.assemblyName;
     this.location           = pc.location;
     this.parsedFiles        = new Dictionary <string, IParsedFile>(pc.parsedFiles, Platform.FileNameComparer);
     this.assemblyReferences = new List <IAssemblyReference>(pc.assemblyReferences);
     this.compilerSettings   = pc.compilerSettings;
 }
		protected CSharpProjectContent(CSharpProjectContent pc)
		{
			this.assemblyName = pc.assemblyName;
			this.parsedFiles = new Dictionary<string, IParsedFile>(pc.parsedFiles, Platform.FileNameComparer);
			this.assemblyReferences = new List<IAssemblyReference>(pc.assemblyReferences);
			this.compilerSettings = pc.CompilerSettings;
			this.Location = pc.Location;
		}
Пример #7
0
		protected CSharpProjectContent(CSharpProjectContent pc)
		{
			this.assemblyName = pc.assemblyName;
			this.fullAssemblyName = pc.fullAssemblyName;
			this.projectFileName = pc.projectFileName;
			this.location = pc.location;
			this.unresolvedFiles = new Dictionary<string, IUnresolvedFile>(pc.unresolvedFiles, Platform.FileNameComparer);
			this.assemblyReferences = new List<IAssemblyReference>(pc.assemblyReferences);
			this.compilerSettings = pc.compilerSettings;
		}
Пример #8
0
        public static CompilationUnit Parse(Stream stream, string fileName = "", CompilerSettings settings = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            var parser = new CSharpParser();

            if (settings != null)
            {
                parser.CompilerSettings = settings;
            }
            return(parser.Parse(stream, fileName, 0));
        }
Пример #9
0
        public CSharpProject(CSharpSolution solution, string title, string fileName)
        {
            Files = new List<CSharpFile>();
            CompilerSettings = new CompilerSettings();
            Solution = solution;
            Title = title;
            FileName = fileName;

            LoadCSharpProject(solution, fileName);
        }
Пример #10
0
        public static ICSharpCode.NRefactory.CSharp.CompilerSettings GetCompilerArguments(MonoDevelop.Projects.Project project)
        {
            var compilerArguments = new ICSharpCode.NRefactory.CSharp.CompilerSettings();

            //		compilerArguments.TabSize = 1;

            if (project == null || MonoDevelop.Ide.IdeApp.Workspace == null)
            {
                compilerArguments.AllowUnsafeBlocks = true;
                return(compilerArguments);
            }

            var configuration = project.GetConfiguration(MonoDevelop.Ide.IdeApp.Workspace.ActiveConfiguration) as DotNetProjectConfiguration;

            if (configuration == null)
            {
                return(compilerArguments);
            }

            foreach (var sym in configuration.GetDefineSymbols())
            {
                compilerArguments.ConditionalSymbols.Add(sym);
            }

            var par = configuration.CompilationParameters as CSharpCompilerParameters;

            if (par == null)
            {
                return(compilerArguments);
            }

            compilerArguments.AllowUnsafeBlocks     = par.UnsafeCode;
            compilerArguments.LanguageVersion       = ConvertLanguageVersion(par.LangVersion);
            compilerArguments.CheckForOverflow      = par.GenerateOverflowChecks;
            compilerArguments.WarningLevel          = par.WarningLevel;
            compilerArguments.TreatWarningsAsErrors = par.TreatWarningsAsErrors;
            if (!string.IsNullOrEmpty(par.NoWarnings))
            {
                foreach (var warning in par.NoWarnings.Split(';', ',', ' ', '\t'))
                {
                    int w;
                    try {
                        w = int.Parse(warning);
                    } catch (Exception) {
                        continue;
                    }
                    compilerArguments.DisabledWarnings.Add(w);
                }
            }

            return(compilerArguments);
        }
Пример #11
0
 public static CompilerSettings ToCompilerSettings(StructEx.CompilerSettings settings)
 {
     var compilerSettings = new CompilerSettings
                                {
                                    AllowUnsafeBlocks = settings.AllowUnsafeBlocks,
                                    CheckForOverflow = settings.CheckForOverflow
                                };
     foreach(var symbol in settings.ConditionalSymbols)
     {
         compilerSettings.ConditionalSymbols.Add(symbol);
     }
     return compilerSettings;
 }
Пример #12
0
        public static void EnumStringLiterals(string fileName, IEnumerable<string> macros, Action<string, int, int, int, int, string> callback)
        {
            var setting = new CompilerSettings();
            foreach (var macro in macros) setting.ConditionalSymbols.Add(macro);

            var parser = new CSharpParser(setting);
            var tree = parser.Parse(File.ReadAllText(fileName, Encoding.Default), fileName);
            if (tree.Errors.Count > 0)
            {
                throw new Exception("Compile failed: " + string.Join("\n", tree.Errors.Select(e => e.Message)));
            }

            foreach (var node in tree.Descendants.OfType<PrimitiveExpression>().Where(n => n.Value is string))
            {
                callback(fileName, node.StartLocation.Line, node.StartLocation.Column, node.EndLocation.Line, node.EndLocation.Column, node.Value as string);
            }
        }
        public static SyntaxTree Parse(Stream stream, string fileName = "", CompilerSettings settings = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            var parser = new CSharpParser(settings);

            return(parser.Parse(stream, fileName));
        }
Пример #14
0
		protected override object CreateCompilerSettings()
		{
			// This method gets called when the project content is first created;
			// or when any of the ReparseSensitiveProperties has changed.
			CompilerSettings settings = new CompilerSettings();
			settings.AllowUnsafeBlocks = GetBoolProperty("AllowUnsafeBlocks") ?? false;
			settings.CheckForOverflow = GetBoolProperty("CheckForOverflowUnderflow") ?? false;
			
			string symbols = GetEvaluatedProperty("DefineConstants");
			if (symbols != null) {
				foreach (string symbol in symbols.Split(new char[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries)) {
					settings.ConditionalSymbols.Add(symbol.Trim());
				}
			}
			settings.Freeze();
			compilerSettings = settings;
			return settings;
		}
Пример #15
0
        void SetCompilerSettings(Microsoft.Build.Evaluation.Project p)
        {
            CompilerSettings = new CompilerSettings
            {
                AllowUnsafeBlocks = GetBoolProperty(p, "AllowUnsafeBlocks") ?? false,
                CheckForOverflow = GetBoolProperty(p, "CheckForOverflowUnderflow") ?? false
            };
            string[] defines = p.GetPropertyValue("DefineConstants")
                .Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string define in defines)
                CompilerSettings.ConditionalSymbols.Add(define);

            var config = ConfigurationLoader.Config;
            foreach (var define in config.Defines)
                CompilerSettings.ConditionalSymbols.Add(define);
        }
Пример #16
0
 public CSharpParser CreateParser()
 {
     var settings = new CompilerSettings();
     return new CSharpParser(settings);
 }
Пример #17
0
        public CSharpProject(ISolution solution, string title, string fileName, Guid id)
        {
            _solution = solution;
            Title = title;
            FileName = fileName.ForceNativePathSeparator();
            ProjectId = id;
            Files = new List<CSharpFile>();

            var p = new Microsoft.Build.Evaluation.Project(FileName);
            AssemblyName = p.GetPropertyValue("AssemblyName");

            _compilerSettings = new CompilerSettings
                {
                    AllowUnsafeBlocks = GetBoolProperty(p, "AllowUnsafeBlocks") ?? false,
                    CheckForOverflow = GetBoolProperty(p, "CheckForOverflowUnderflow") ?? false,
                };
            string[] defines = p.GetPropertyValue("DefineConstants").Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string define in defines)
                _compilerSettings.ConditionalSymbols.Add(define);

            foreach (var item in p.GetItems("Compile"))
            {
                try
                {
                    string path = Path.Combine(p.DirectoryPath, item.EvaluatedInclude).ForceNativePathSeparator();
                    if (File.Exists(path))
                    {
                        Files.Add(new CSharpFile(this, new FileInfo(path).FullName));
                    }
                    else
                    {
                        Console.WriteLine("File does not exist - " + path);
                    }
                }
                catch (NullReferenceException e)
                {
                    Console.WriteLine(e);
                }
            }

            References = new List<IAssemblyReference>();
            string mscorlib = FindAssembly(AssemblySearchPaths, "mscorlib");
            if (mscorlib != null)
                AddReference(LoadAssembly(mscorlib));
            else
                Console.WriteLine("Could not find mscorlib");

            bool hasSystemCore = false;
            foreach (var item in p.GetItems("Reference"))
            {

                string assemblyFileName = null;
                if (item.HasMetadata("HintPath"))
                {
                    assemblyFileName = Path.Combine(p.DirectoryPath, item.GetMetadataValue("HintPath")).ForceNativePathSeparator();
                    if (!File.Exists(assemblyFileName))
                        assemblyFileName = null;
                }
                //If there isn't a path hint or it doesn't exist, try searching
                if (assemblyFileName == null)
                    assemblyFileName = FindAssembly(AssemblySearchPaths, item.EvaluatedInclude);

                //If it isn't in the search paths, try the GAC
                if (assemblyFileName == null)
                    assemblyFileName = FindAssemblyInNetGac(item.EvaluatedInclude);

                if (assemblyFileName != null)
                {
                    if (Path.GetFileName(assemblyFileName).Equals("System.Core.dll", StringComparison.OrdinalIgnoreCase))
                        hasSystemCore = true;

                    Console.WriteLine("Loading assembly " + item.EvaluatedInclude);
                    try
                    {
                        AddReference(LoadAssembly(assemblyFileName));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }

                }
                else
                    Console.WriteLine("Could not find referenced assembly " + item.EvaluatedInclude);
            }
            if (!hasSystemCore && FindAssembly(AssemblySearchPaths, "System.Core") != null)
                AddReference(LoadAssembly(FindAssembly(AssemblySearchPaths, "System.Core")));

            foreach (var item in p.GetItems("ProjectReference"))
                AddReference(new ProjectReference(_solution, item.GetMetadataValue("Name")));

            this.ProjectContent = new CSharpProjectContent()
                .SetAssemblyName(AssemblyName)
                .AddAssemblyReferences(References)
                .AddOrUpdateFiles(Files.Select(f => f.ParsedFile));
        }
Пример #18
0
        public CSharpProject(
            ICSharpFileFactory cSharpFileFactory,
            MicrosoftBuildProject msBuildProject,
            string title)
        {
            Title = title;

            AssemblyName = msBuildProject.AssemblyName;
            FileName = msBuildProject.FileName;

            CompilerSettings =
                #region new CompilerSettings
                new CompilerSettings
                {
                    AllowUnsafeBlocks = msBuildProject.AllowUnsafeBlocks,
                    CheckForOverflow = msBuildProject.CheckForOverflowUnderflow,
                };

            CompilerSettings.ConditionalSymbols.AddRange(msBuildProject.DefineConstants);
            #endregion

            ProjectContent = new CSharpProjectContent();
            ProjectContent = ProjectContent.SetAssemblyName(msBuildProject.AssemblyName);
            ProjectContent = ProjectContent.SetProjectFileName(msBuildProject.FileName.FullPath);
            ProjectContent = ProjectContent.SetCompilerSettings(CompilerSettings);

            Files = msBuildProject.CompiledFileNames.Select(
                f => cSharpFileFactory.BuildCSharpFile(this, new FilePath(f))).ToList();

            ProjectContent = ProjectContent.AddOrUpdateFiles(
                Files.Select(f => f.UnresolvedTypeSystemForFile));

            ProjectContent = ProjectContent.AddAssemblyReferences(msBuildProject.ReferencedAssemblies);
        }
Пример #19
0
		// could depend just on IDocument
		SyntaxTree ParseDocument(ITextEditor editor, out IList<AstNode> parsedSpecials)
		{
			parsedSpecials = null;
			CompilerSettings compilerSettings = new CompilerSettings();
			var parser = new CSharpParser();
			if (parser == null) return null;
			var syntaxTree = parser.Parse(editor.Document.CreateReader());
			if (syntaxTree == null) return null;
			parsedSpecials = new List<AstNode>(syntaxTree.Descendants.OfType<Comment>());
			return syntaxTree;
		}