Ejemplo n.º 1
0
        public void TestArrayInitializerFormattingBugSimple()
        {
            var policy = FormattingOptionsFactory.CreateSharpDevelop();

            Test(policy, @"class Test
{
	static readonly AstNode forPattern =
		new Choice {
			new BinaryOperatorExpression(
				PatternHelper.OptionalParentheses(
					new AnyNode(""upperBound"")
				)
			)
		};
}
", @"class Test
{
	static readonly AstNode forPattern =
		new Choice {
			new BinaryOperatorExpression(
				PatternHelper.OptionalParentheses(
					new AnyNode(""upperBound"")
				)
			)
		};
}
");
        }
        public static string GetMethodBody(string sourceFilePath, string methodName, int callingLine)
        {
            if (!File.Exists(sourceFilePath))
            {
                return(string.Format("{0} file not found.", Path.GetFileName(sourceFilePath)));
            }

            try
            {
                var parser     = new CSharpParser();
                var syntaxTree = parser.Parse(File.ReadAllText(sourceFilePath));

                var result = syntaxTree.Descendants.OfType <MethodDeclaration>()
                             .FirstOrDefault(y => y.NameToken.Name == methodName && y.EndLocation.Line > callingLine);
                if (result != null)
                {
                    return(result.ToString(FormattingOptionsFactory.CreateSharpDevelop()).Trim());
                }

                result = syntaxTree.Descendants.OfType <MethodDeclaration>()
                         .FirstOrDefault(y => y.NameToken.Name == methodName);
                if (result != null)
                {
                    return(result.ToString(FormattingOptionsFactory.CreateSharpDevelop()).Trim());
                }
            }
            catch
            {
                return(readLines(sourceFilePath, callingLine));
            }

            return(readLines(sourceFilePath, callingLine));
        }
Ejemplo n.º 3
0
        private static CSharpFormattingOptions CreateOptionSet(FormattingOptionSet defaultOptionSet)
        {
            switch (defaultOptionSet)
            {
            case FormattingOptionSet.Orcomp:
                return(CreateOrcompOptions());

            case FormattingOptionSet.KRStyle:
                return(FormattingOptionsFactory.CreateKRStyle());

            case FormattingOptionSet.Mono:
                return(FormattingOptionsFactory.CreateMono());

            case FormattingOptionSet.SharpDevelop:
                return(FormattingOptionsFactory.CreateSharpDevelop());

            case FormattingOptionSet.VisualStudio:
                return(FormattingOptionsFactory.CreateAllman());

            case FormattingOptionSet.GNU:
                return(FormattingOptionsFactory.CreateGNU());

            case FormattingOptionSet.Whitesmiths:
                return(FormattingOptionsFactory.CreateWhitesmiths());

            default:
                return(FormattingOptionsFactory.CreateAllman());
            }
        }
Ejemplo n.º 4
0
        public static ILSpyUnresolvedFile Create(DecompiledTypeReference name, AstBuilder builder)
        {
            var writer = new StringWriter();
            var target = new TextWriterTokenWriter(writer)
            {
                IndentationString = "\t"
            };
            var output = new DebugInfoTokenWriterDecorator(TokenWriter.WrapInWriterThatSetsLocationsInAST(target));

            builder.RunTransformations();
            var syntaxTree = builder.SyntaxTree;

            syntaxTree.AcceptVisitor(new InsertParenthesesVisitor {
                InsertParenthesesForReadability = true
            });
            syntaxTree.AcceptVisitor(new CSharpOutputVisitor(output, FormattingOptionsFactory.CreateSharpDevelop()));
            ILSpyUnresolvedFile file = new ILSpyUnresolvedFile(name);
            var v = new TypeSystemConvertVisitor(file);

            syntaxTree.AcceptVisitor(v);

            file.MemberLocations = output.MemberLocations;
            file.DebugSymbols    = output.DebugSymbols;
            file.output          = writer.ToString();

            return(file);
        }
Ejemplo n.º 5
0
        public void TestGetoptionsWithSinglePropertyOverWrite()
        {
            const string propertyFileName = "SharpDevelopProperties.xml";
            var          expected         = FormattingOptionsFactory.CreateSharpDevelop();

            foreach (var propertyInfo in GetCSharpFormattingOptionsProperties())
            {
                var loaded = CSharpFormattingProperties.GetOptions(Path.Combine(TestFolder, propertyFileName));

                // Save the original property value to a one setting temp property file
                var tempFileName = CreateTempPropertyFileWithSingleProperty(propertyInfo, loaded);
                try
                {
                    CheckOptions(expected, loaded, 0);

                    ChangeAllProperties(loaded);
                    CheckOptions(expected, loaded, PropertyCount);

                    loaded = CSharpFormattingProperties.GetOptions(tempFileName, loaded);
                }
                finally
                {
                    File.Delete(tempFileName);
                }

                // Check we got back the original property
                var matchingPropertyNames = GetMatchingPropertyNames(expected, loaded);
                Assert.AreEqual(1, matchingPropertyNames.Count, matchingPropertyNames.ToString());
                Assert.AreEqual(propertyInfo.Name, matchingPropertyNames.FirstOrDefault());
            }
        }
Ejemplo n.º 6
0
        public static string DecompileCSharp(string assemblyFileName, DecompilerSettings settings = null)
        {
            if (settings == null)
            {
                settings = new DecompilerSettings();
            }
            using (var file = new FileStream(assemblyFileName, FileMode.Open, FileAccess.Read)) {
                var module   = new PEFile(assemblyFileName, file, PEStreamOptions.PrefetchEntireImage);
                var resolver = new UniversalAssemblyResolver(assemblyFileName, false,
                                                             module.Reader.DetectTargetFrameworkId(), PEStreamOptions.PrefetchMetadata);
                resolver.AddSearchDirectory(Path.GetDirectoryName(typeof(Span <>).Assembly.Location));
                var typeSystem = new DecompilerTypeSystem(module, resolver, settings);
                CSharpDecompiler decompiler = new CSharpDecompiler(typeSystem, settings);
                decompiler.AstTransforms.Insert(0, new RemoveEmbeddedAttributes());
                decompiler.AstTransforms.Insert(0, new RemoveCompilerAttribute());
                decompiler.AstTransforms.Insert(0, new RemoveNamespaceMy());
                decompiler.AstTransforms.Add(new EscapeInvalidIdentifiers());
                var syntaxTree = decompiler.DecompileWholeModuleAsSingleFile(sortTypes: true);

                StringWriter output  = new StringWriter();
                var          visitor = new CSharpOutputVisitor(output, FormattingOptionsFactory.CreateSharpDevelop());
                syntaxTree.AcceptVisitor(visitor);

                string fileName = Path.GetTempFileName();
                File.WriteAllText(fileName, output.ToString());

                return(fileName);
            }
        }
Ejemplo n.º 7
0
        public static string PrettyPrint(this AstNode code)
        {
            if (code == null)
            {
                return(string.Empty);
            }

            return(code.ToString(FormattingOptionsFactory.CreateSharpDevelop()));
        }
Ejemplo n.º 8
0
        public object GetSyntaxWithParameterHighlighted(int currentParameter)
        {
            var codeControl = CreateReadonlyCsTextEditor(AmbienceDescription);
            var finder      = new FindParameterTokenWriter(currentParameter);

            ambience.ConvertSymbol(Entity, finder, FormattingOptionsFactory.CreateSharpDevelop());
            codeControl.Select(finder.ParameterStart, finder.ParameterEnd - finder.ParameterStart);
            return(codeControl);
        }
Ejemplo n.º 9
0
        public static string ToText(AstNode node)
        {
            var stringWriter = new StringWriter();
            var output       = new CSharpOutputVisitor(stringWriter, FormattingOptionsFactory.CreateSharpDevelop());

            node.AcceptVisitor(output);

            return(stringWriter.GetStringBuilder().ToString());
        }
Ejemplo n.º 10
0
        public void TestLoadFullFromSimpleXml()
        {
            var actual   = CSharpFormattingProperties.GetOptions(Path.Combine(TestFolder, "Simple.xml"));
            var expected = FormattingOptionsFactory.CreateSharpDevelop();

            CheckOptions(expected, actual, 0);

            expected = FormattingOptionsFactory.CreateEmpty();
            CheckOptions(expected, actual, 82);
        }
Ejemplo n.º 11
0
        private static CSharpFormattingOptions CreateFormattingPolicyForTests()
        {
            var formattingPolicy = FormattingOptionsFactory.CreateSharpDevelop();

            formattingPolicy.StatementBraceStyle     = BraceStyle.NextLine;
            formattingPolicy.CatchNewLinePlacement   = NewLinePlacement.NewLine;
            formattingPolicy.ElseNewLinePlacement    = NewLinePlacement.NewLine;
            formattingPolicy.FinallyNewLinePlacement = NewLinePlacement.NewLine;
            formattingPolicy.SpaceBeforeAnonymousMethodParentheses = true;
            return(formattingPolicy);
        }
Ejemplo n.º 12
0
        public void TestAllIsOverWriting()
        {
            var actual   = CSharpFormattingProperties.GetOptions(Path.Combine(TestFolder, "SimpleComplement.xml"));
            var expected = FormattingOptionsFactory.CreateSharpDevelop();

            var x = GetMatchingPropertyNames(expected, actual);

            CheckOptions(expected, actual, PropertyCount);

            expected = CSharpFormattingProperties.GetOptions(Path.Combine(TestFolder, "Simple.xml"));
            CheckOptions(expected, actual, PropertyCount);
        }
Ejemplo n.º 13
0
        FlowDocumentScrollViewer GenerateHeader()
        {
            var ambience = new CSharpAmbience();

            ambience.ConversionFlags = ConversionFlags.StandardConversionFlags;
            var stringBuilder = new StringBuilder();
            var formatter     = new ParameterHighlightingOutputFormatter(stringBuilder, highlightedParameterIndex);

            ambience.ConvertSymbol(Method, formatter, FormattingOptionsFactory.CreateSharpDevelop());

            var documentation = XmlDocumentationElement.Get(Method);

            ambience.ConversionFlags = ConversionFlags.ShowTypeParameterList;

            var    b             = new CSharpDocumentationBuilder(ambience);
            string parameterName = null;

            if (Method.Parameters.Count > highlightedParameterIndex)
            {
                parameterName = Method.Parameters[highlightedParameterIndex].Name;
            }
            b.AddSignatureBlock(stringBuilder.ToString(), formatter.parameterStartOffset, formatter.parameterLength, parameterName);

            var b2 = new CSharpDocumentationBuilder(ambience);

            b2.ParameterName     = parameterName;
            b2.ShowAllParameters = false;

            if (documentation != null)
            {
                foreach (var child in documentation.Children)
                {
                    b2.AddDocumentationElement(child);
                }
            }

            content = new FlowDocumentScrollViewer {
                Document = b2.CreateFlowDocument(),
                VerticalScrollBarVisibility = ScrollBarVisibility.Auto
            };

            var flowDocument = b.CreateFlowDocument();

            flowDocument.PagePadding = new Thickness(0); // default is NOT Thickness(0), but Thickness(Auto), which adds unnecessary space

            return(new FlowDocumentScrollViewer {
                Document = flowDocument,
                VerticalScrollBarVisibility = ScrollBarVisibility.Auto
            });
        }
Ejemplo n.º 14
0
		/// <summary>
		/// Creates a <see cref="ICSharpCode.NRefactory.CSharp.CSharpFormattingOptions"/> instance from current
		/// container, resolving all options throughout container hierarchy.
		/// </summary>
		/// <returns>Created and filled <see cref="ICSharpCode.NRefactory.CSharp.CSharpFormattingOptions"/> instance.</returns>
		private CSharpFormattingOptions CreateCachedOptions()
		{
			var outputOptions = FormattingOptionsFactory.CreateSharpDevelop();
			
			// Look at all container options and try to set identically named properties of CSharpFormattingOptions
			foreach (PropertyInfo propertyInfo in typeof(CSharpFormattingOptions).GetProperties()) {
				object val = GetEffectiveOption(propertyInfo.Name);
				if ((val != null) && (val.GetType() == propertyInfo.PropertyType)) {
					propertyInfo.SetValue(outputOptions, val);
				}
			}
			
			return outputOptions;
		}
Ejemplo n.º 15
0
        public string GenerateCSharp()
        {
            string dllPath   = $"./fordebug.dll";
            var    generator = new AssemblyGenerator();

            generator.GenerateAssembly(Builder, dllPath);
            CSharpDecompiler decompiler = new CSharpDecompiler(dllPath, new ICSharpCode.Decompiler.DecompilerSettings());
            var          syntaxTree     = decompiler.DecompileWholeModuleAsSingleFile();
            StringWriter output         = new StringWriter();
            var          visitor        = new CSharpOutputVisitor(output, FormattingOptionsFactory.CreateSharpDevelop());

            syntaxTree.AcceptVisitor(visitor);
            return(output.ToString());
        }
        void GenerateHeader()
        {
            CSharpAmbience ambience = new CSharpAmbience();

            ambience.ConversionFlags = ConversionFlags.StandardConversionFlags;
            var stringBuilder = new StringBuilder();
            var formatter     = new ParameterHighlightingOutputFormatter(stringBuilder, highlightedParameterIndex);

            ambience.ConvertEntity(Method, formatter, FormattingOptionsFactory.CreateSharpDevelop());
            var inlineBuilder = new HighlightedInlineBuilder(stringBuilder.ToString());

            inlineBuilder.SetFontWeight(formatter.parameterStartOffset, formatter.parameterLength, FontWeights.Bold);
            header.Inlines.Clear();
            header.Inlines.AddRange(inlineBuilder.CreateRuns());
        }
Ejemplo n.º 17
0
        public string BuildExpression(Dictionary <string, Expression> selectExpressions)
        {
            var anonymousTypeCreateExpression = new AnonymousTypeCreateExpression();
            var crrv = new ChangeRootReferenceVisitor(FromIdentifier);

            foreach (var curExpr in selectExpressions.OrderBy(x => x.Key))
            {
                curExpr.Value.AcceptVisitor(crrv);
                anonymousTypeCreateExpression.Initializers.Add(
                    new AssignmentExpression(new IdentifierExpression(curExpr.Key), curExpr.Value.Clone()));
            }
            if (FromExpression == null)
            {
                FromExpression = new IdentifierExpression();
            }

            var queryExpr = new QueryExpression
            {
                Clauses =
                {
                    new QueryFromClause
                    {
                        Identifier = "doc",
                        Expression = FromExpression.Clone()
                    },
                    new QuerySelectClause
                    {
                        Expression = anonymousTypeCreateExpression.Clone()
                    }
                }
            };

            FromIdentifier = "doc";

            var printer        = new StringWriter();
            var printerVisitor = new CSharpOutputVisitor(printer, FormattingOptionsFactory.CreateSharpDevelop());

            queryExpr.AcceptVisitor(printerVisitor);

            var format = printer.GetStringBuilder().ToString();

            if (format.Substring(0, 3) == "\r\n\t")
            {
                format = format.Remove(0, 3);
            }
            format = format.Replace("\r\n\t", "\n");
            return(format);
        }
Ejemplo n.º 18
0
        private static CSharpFormattingOptions GetFormatter()
        {
            var formatter = FormattingOptionsFactory.CreateSharpDevelop();
            formatter.AnonymousMethodBraceStyle = BraceStyle.NextLine;
            formatter.MethodBraceStyle = BraceStyle.NextLine;
            formatter.StatementBraceStyle = BraceStyle.NextLine;
            formatter.PropertyBraceStyle = BraceStyle.NextLine;
            formatter.ConstructorBraceStyle = BraceStyle.NextLine;
            formatter.NewLineAfterConstructorInitializerColon = NewLinePlacement.NewLine;
            formatter.NewLineAferMethodCallOpenParentheses = NewLinePlacement.NewLine;
            formatter.ClassBraceStyle = BraceStyle.NextLine;
            formatter.ArrayInitializerBraceStyle = BraceStyle.NextLine;
            formatter.IndentPreprocessorDirectives = false;

            return formatter;
        }
Ejemplo n.º 19
0
        public object GetSyntaxWithParameterHighlighted(int currentParameter)
        {
            var codeControl = new CsTextEditor();

            codeControl.IsEnabled = false;
            codeControl.Text      = AmbienceDescription;
            codeControl.HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden;
            codeControl.VerticalScrollBarVisibility   = ScrollBarVisibility.Hidden;
            codeControl.Background = Brushes.Transparent;

            var finder = new FindParameterTokenWriter(currentParameter);

            ambience.ConvertSymbol(Entity, finder, FormattingOptionsFactory.CreateSharpDevelop());
            codeControl.Select(finder.ParameterStart, finder.ParameterEnd - finder.ParameterStart);
            return(codeControl);
        }
Ejemplo n.º 20
0
        public static string GenerateText(TypeDeclaration type,
                                          OrderedPartCollection <AbstractDynamicCompilationExtension> extensions,
                                          HashSet <string> namespaces = null)
        {
            var unit = new SyntaxTree();

            if (namespaces == null)
            {
                namespaces = new HashSet <string>
                {
                    typeof(SystemTime).Namespace,
                    typeof(AbstractViewGenerator).Namespace,
                    typeof(Enumerable).Namespace,
                    typeof(IEnumerable <>).Namespace,
                    typeof(IEnumerable).Namespace,
                    typeof(int).Namespace,
                    typeof(LinqOnDynamic).Namespace,
                    typeof(Field).Namespace,
                    typeof(CultureInfo).Namespace,
                    typeof(Regex).Namespace
                };
            }

            foreach (var extension in extensions)
            {
                foreach (var ns in extension.Value.GetNamespacesToImport())
                {
                    namespaces.Add(ns);
                }
            }

            foreach (var ns in namespaces)
            {
                unit.Members.Add(new UsingDeclaration(ns));
            }

            unit.Members.Add(new WindowsNewLine());

            unit.Members.Add(type);

            var stringWriter = new StringWriter();
            var output       = new CSharpOutputVisitor(stringWriter, FormattingOptionsFactory.CreateSharpDevelop());

            unit.AcceptVisitor(output);

            return(stringWriter.GetStringBuilder().ToString());
        }
        DocumentScript GetScript(string fileName)
        {
            DocumentScript script;
            var            fileNameObj = FileName.Create(fileName);

            if (scripts.TryGetValue(fileNameObj, out script))
            {
                return(script);
            }

            IDocument document = context.GetDocument(fileNameObj);
            var       ctx      = SDRefactoringContext.Create(fileNameObj, document);

            script = new DocumentScript(document, FormattingOptionsFactory.CreateSharpDevelop(), new TextEditorOptions());
            scripts.Add(fileNameObj, script);
            return(script);
        }
        public Script StartScript()
        {
            var formattingOptions = FormattingOptionsFactory.CreateSharpDevelop();

            if (editor != null)
            {
                return(new EditorScript(editor, this, formattingOptions));
            }
            else if (document == null || document is ReadOnlyDocument)
            {
                throw new InvalidOperationException("Cannot start a script in a read-only context");
            }
            else
            {
                return(new DocumentScript(document, formattingOptions, this.TextEditorOptions));
            }
        }
Ejemplo n.º 23
0
        void GenerateHeader()
        {
            CSharpAmbience ambience = new CSharpAmbience();

            ambience.ConversionFlags = ConversionFlags.StandardConversionFlags;
            var         stringBuilder = new StringBuilder();
            TokenWriter formatter     = new ParameterHighlightingOutputFormatter(stringBuilder, highlightedParameterIndex);

            ambience.ConvertSymbol(Method, formatter, FormattingOptionsFactory.CreateSharpDevelop());
            var documentation = XmlDocumentationElement.Get(Method);

            ambience.ConversionFlags = ConversionFlags.ShowTypeParameterList;

            var inlineBuilder = new HighlightedInlineBuilder(stringBuilder.ToString());

            header.Inlines.Clear();
            header.Inlines.AddRange(inlineBuilder.CreateRuns());
        }
Ejemplo n.º 24
0
        public static string DecompileCSharp(string assemblyFileName)
        {
            using (var module = ModuleDefinition.ReadModule(assemblyFileName)) {
                var typeSystem = new DecompilerTypeSystem(module);
                CSharpDecompiler decompiler = new CSharpDecompiler(typeSystem, new DecompilerSettings());
                decompiler.AstTransforms.Insert(0, new RemoveCompilerAttribute());
                decompiler.AstTransforms.Add(new EscapeInvalidIdentifiers());
                var syntaxTree = decompiler.DecompileWholeModuleAsSingleFile();

                StringWriter output  = new StringWriter();
                var          visitor = new CSharpOutputVisitor(output, FormattingOptionsFactory.CreateSharpDevelop());
                syntaxTree.AcceptVisitor(visitor);

                string fileName = Path.GetTempFileName();
                File.WriteAllText(fileName, output.ToString());

                return(fileName);
            }
        }
Ejemplo n.º 25
0
        private void TestCreateSequencePoints(string code, params string[] expectedSequencePoints)
        {
            var decompiler = Tester.GetDecompilerForSnippet(code);

            var firstType = decompiler.TypeSystem.Compilation.GetTopLevelTypeDefinitions().First(t => code.Contains(t.Name));
            var tree      = decompiler.DecompileType(firstType.FullTypeName);

            var output = new StringWriter();

            tree.AcceptVisitor(new InsertParenthesesVisitor {
                InsertParenthesesForReadability = true
            });
            TokenWriter tokenWriter = new TextWriterTokenWriter(output);

            tokenWriter = new InsertMissingTokensDecorator(tokenWriter, (ILocatable)tokenWriter);
            var formattingOptions = FormattingOptionsFactory.CreateSharpDevelop();

            tree.AcceptVisitor(new CSharpOutputVisitor(tokenWriter, formattingOptions));

            var functionsWithSequencePoints = decompiler.CreateSequencePoints(tree);
            var finalText = output.ToString();

            var lines = finalText.Split(new[] { output.NewLine }, StringSplitOptions.None);

            var actualSequencePoints = new List <string>();

            foreach (var sequencePoint in functionsWithSequencePoints.Values.First())
            {
                if (sequencePoint.IsHidden)
                {
                    continue;
                }

                var line = lines[sequencePoint.StartLine - 1];
                var text = line.Substring(sequencePoint.StartColumn - 1, sequencePoint.EndColumn - sequencePoint.StartColumn);
                actualSequencePoints.Add(text);
            }

            Assert.True(Enumerable.SequenceEqual(expectedSequencePoints, actualSequencePoints));
        }
Ejemplo n.º 26
0
        static void Decompile(string assemblyFileName, TextWriter output, string typeName = null)
        {
            ModuleDefinition module     = LoadModule(assemblyFileName);
            var typeSystem              = new DecompilerTypeSystem(module);
            CSharpDecompiler decompiler = new CSharpDecompiler(typeSystem, new DecompilerSettings());

            decompiler.AstTransforms.Add(new EscapeInvalidIdentifiers());
            SyntaxTree syntaxTree;

            if (typeName == null)
            {
                syntaxTree = decompiler.DecompileWholeModuleAsSingleFile();
            }
            else
            {
                syntaxTree = decompiler.DecompileTypes(module.GetTypes().Where(td => string.Equals(td.FullName, typeName, StringComparison.OrdinalIgnoreCase)));
            }

            var visitor = new CSharpOutputVisitor(output, FormattingOptionsFactory.CreateSharpDevelop());

            syntaxTree.AcceptVisitor(visitor);
        }
Ejemplo n.º 27
0
        public CodeCompletionResult GetMethodCompletion(IDocument document, int offset, bool controlSpace)
        {
            var result = new CodeCompletionResult();

            if (String.IsNullOrEmpty(document.FileName))
            {
                return(result);
            }

            var completionContext = new CSharpCompletionContext(document, offset, projectContent, null, null, null);

            var completionFactory = new CSharpCompletionDataFactory(completionContext.TypeResolveContextAtCaret, completionContext);
            var cce = new CSharpCompletionEngine(
                completionContext.Document,
                completionContext.CompletionContextProvider,
                completionFactory,
                completionContext.ProjectContent,
                completionContext.TypeResolveContextAtCaret
                );

            cce.EolMarker        = Environment.NewLine;
            cce.FormattingPolicy = FormattingOptionsFactory.CreateSharpDevelop();
            var completionChar = completionContext.Document.GetCharAt(completionContext.Offset - 1);
            var pce            = new CSharpParameterCompletionEngine(
                completionContext.Document,
                completionContext.CompletionContextProvider,
                completionFactory,
                completionContext.ProjectContent,
                completionContext.TypeResolveContextAtCaret
                );

            var parameterDataProvider = pce.GetParameterDataProvider(completionContext.Offset, completionChar);

            result.OverloadProvider = parameterDataProvider as IOverloadProvider;
            return(result);
        }
Ejemplo n.º 28
0
        public CodeCompletionResult GetCompletions(IDocument document, int offset, bool controlSpace, string usings, string variables = null)
        {
            var result = new CodeCompletionResult();

            if (String.IsNullOrEmpty(document.FileName))
            {
                return(result);
            }

            var completionContext = new CSharpCompletionContext(document, offset, projectContent, usings, variables);

            var completionFactory = new CSharpCompletionDataFactory(completionContext.TypeResolveContextAtCaret, completionContext);
            var cce = new CSharpCompletionEngine(
                completionContext.Document,
                completionContext.CompletionContextProvider,
                completionFactory,
                completionContext.ProjectContent,
                completionContext.TypeResolveContextAtCaret
                );

            cce.EolMarker        = Environment.NewLine;
            cce.FormattingPolicy = FormattingOptionsFactory.CreateSharpDevelop();


            var completionChar = completionContext.Document.GetCharAt(completionContext.Offset - 1);
            int startPos, triggerWordLength;
            IEnumerable <ICSharpCode.NRefactory.Completion.ICompletionData> completionData;

            if (controlSpace)
            {
                if (!cce.TryGetCompletionWord(completionContext.Offset, out startPos, out triggerWordLength))
                {
                    startPos          = completionContext.Offset;
                    triggerWordLength = 0;
                }
                completionData = cce.GetCompletionData(startPos, true);
                //this outputs tons of available entities
                //if (triggerWordLength == 0)
                //    completionData = completionData.Concat(cce.GetImportCompletionData(startPos));
            }
            else
            {
                startPos = completionContext.Offset;

                if (char.IsLetterOrDigit(completionChar) || completionChar == '_')
                {
                    if (startPos > 1 && char.IsLetterOrDigit(completionContext.Document.GetCharAt(startPos - 2)))
                    {
                        return(result);
                    }
                    completionData = cce.GetCompletionData(startPos, false);
                    startPos--;
                    triggerWordLength = 1;
                }
                else
                {
                    completionData    = cce.GetCompletionData(startPos, false);
                    triggerWordLength = 0;
                }
            }

            result.TriggerWordLength = triggerWordLength;
            result.TriggerWord       = completionContext.Document.GetText(completionContext.Offset - triggerWordLength, triggerWordLength);
            Debug.Print("Trigger word: '{0}'", result.TriggerWord);

            //cast to AvalonEdit completion data and add to results
            foreach (var completion in completionData)
            {
                var cshellCompletionData = completion as ICSharpCode.CodeCompletion.DataItems.CompletionData;
                if (cshellCompletionData != null)
                {
                    cshellCompletionData.TriggerWord       = result.TriggerWord;
                    cshellCompletionData.TriggerWordLength = result.TriggerWordLength;

                    if (completion is ICSharpCode.CodeCompletion.DataItems.EntityCompletionData)
                    {
                        string typename = String.Empty;

                        var entity = cshellCompletionData as ICSharpCode.CodeCompletion.DataItems.EntityCompletionData;

                        if (entity.Entity is ICSharpCode.NRefactory.TypeSystem.Implementation.DefaultResolvedTypeDefinition)
                        {
                            var def = entity.Entity as ICSharpCode.NRefactory.TypeSystem.Implementation.DefaultResolvedTypeDefinition;

                            typename = def.FullTypeName.ReflectionName;
                        }
                        else
                        {
                            typename = entity.Entity.DeclaringType.FullName;
                        }

                        Type type = Type.GetType(typename);

                        if (!AllowedType(type))
                        {
                            continue;
                        }
                    }

                    result.CompletionData.Add(cshellCompletionData);

                    // piggyback 'region' preprocessor to add our own
                    if (cshellCompletionData.DisplayText == "region")
                    {
                        DataItems.CompletionData import = new DataItems.CompletionData("import");
                        import.CompletionCategory = cshellCompletionData.CompletionCategory;
                        import.Image = cshellCompletionData.Image;
                        result.CompletionData.Add(import);
                    }
                }
            }

            //method completions
            if (!controlSpace)
            {
                // Method Insight
                var pce = new CSharpParameterCompletionEngine(
                    completionContext.Document,
                    completionContext.CompletionContextProvider,
                    completionFactory,
                    completionContext.ProjectContent,
                    completionContext.TypeResolveContextAtCaret
                    );

                var parameterDataProvider = pce.GetParameterDataProvider(completionContext.Offset, completionChar);
                result.OverloadProvider = parameterDataProvider as IOverloadProvider;
            }

            return(result);
        }
Ejemplo n.º 29
0
        public override void Complete(CompletionContext context)
        {
            if (declarationBegin > context.StartOffset)
            {
                base.Complete(context);
                return;
            }

            TypeSystemAstBuilder b = new TypeSystemAstBuilder(contextAtCaret);

            b.ShowTypeParameterConstraints = false;
            b.GenerateBody = true;

            var entityDeclaration = b.ConvertEntity(this.Entity);

            entityDeclaration.Modifiers &= ~(Modifiers.Virtual | Modifiers.Abstract);
            entityDeclaration.Modifiers |= Modifiers.Override;

            var       body = entityDeclaration.GetChildByRole(Roles.Body);
            Statement baseCallStatement = body.Children.OfType <Statement>().FirstOrDefault();

            if (!this.Entity.IsAbstract)
            {
                // modify body to call the base method
                if (this.Entity.SymbolKind == SymbolKind.Method)
                {
                    var baseCall = new BaseReferenceExpression().Invoke(this.Entity.Name, new Expression[] { });
                    if (((IMethod)this.Entity).ReturnType.IsKnownType(KnownTypeCode.Void))
                    {
                        baseCallStatement = new ExpressionStatement(baseCall);
                    }
                    else
                    {
                        baseCallStatement = new ReturnStatement(baseCall);
                    }

                    // Clear body of inserted method
                    entityDeclaration.GetChildByRole(Roles.Body).Statements.Clear();
                }
            }

            var          document          = context.Editor.Document;
            StringWriter w                 = new StringWriter();
            var          formattingOptions = FormattingOptionsFactory.CreateSharpDevelop();
            var          segmentDict       = SegmentTrackingOutputFormatter.WriteNode(w, entityDeclaration, formattingOptions, context.Editor.Options);

            using (document.OpenUndoGroup()) {
                InsertionContext insertionContext = new InsertionContext(context.Editor.GetService(typeof(TextArea)) as TextArea, declarationBegin);
                insertionContext.InsertionPosition = context.Editor.Caret.Offset;

                string newText = w.ToString().TrimEnd();
                document.Replace(declarationBegin, context.EndOffset - declarationBegin, newText);
                var throwStatement = entityDeclaration.Descendants.FirstOrDefault(n => n is ThrowStatement);
                if (throwStatement != null)
                {
                    var segment = segmentDict[throwStatement];
                    context.Editor.Select(declarationBegin + segment.Offset, segment.Length);
                }
                CSharpFormatterHelper.Format(context.Editor, declarationBegin, newText.Length, formattingOptions);

                var refactoringContext = SDRefactoringContext.Create(context.Editor, CancellationToken.None);
                var typeResolveContext = refactoringContext.GetTypeResolveContext();
                if (typeResolveContext == null)
                {
                    return;
                }
                var resolvedCurrent        = typeResolveContext.CurrentTypeDefinition;
                IEditorUIService uiService = context.Editor.GetService(typeof(IEditorUIService)) as IEditorUIService;

                ITextAnchor endAnchor = context.Editor.Document.CreateAnchor(context.Editor.Caret.Offset);
                endAnchor.MovementType = AnchorMovementType.AfterInsertion;

                ITextAnchor startAnchor = context.Editor.Document.CreateAnchor(context.Editor.Caret.Offset);
                startAnchor.MovementType = AnchorMovementType.BeforeInsertion;

                ITextAnchor insertionPos = context.Editor.Document.CreateAnchor(endAnchor.Offset);
                insertionPos.MovementType = AnchorMovementType.BeforeInsertion;

                var current = typeResolveContext.CurrentTypeDefinition;
                AbstractInlineRefactorDialog dialog = new OverrideEqualsGetHashCodeMethodsDialog(insertionContext, context.Editor, endAnchor, insertionPos, current, Entity as IMethod, baseCallStatement);

                dialog.Element = uiService.CreateInlineUIElement(insertionPos, dialog);

                insertionContext.RegisterActiveElement(new InlineRefactorSnippetElement(cxt => null, ""), dialog);
                insertionContext.RaiseInsertionCompleted(EventArgs.Empty);
            }
        }
Ejemplo n.º 30
0
 public void TestAllInOne_CSharpParser()
 {
     BeginFileTest("CSharpParser.cs", FormattingOptionsFactory.CreateSharpDevelop());
 }