Converts from type system to the C# AST.
Exemplo n.º 1
0
		public override AstType CreateShortType (IType fullType)
		{
			AstNode node = Unit.GetNodeAt(Location);
			CSharpResolver csResolver = resolver.GetResolverStateBefore(node);
			var builder = new TypeSystemAstBuilder (csResolver);
			return builder.ConvertType (fullType);
		}
		public EnumMemberCompletionData(IType enumType, IEntity member, TypeSystemAstBuilder builder) : base(enumType.Name + "." + member.Name)
		{
			this.enumType = enumType;
			this.member = member;
			this.Image = ClassBrowserIconService.Const;
			this.CompletionText = builder.ConvertType(enumType).ToString() + "." + member.Name;
		}
		static string GeneratePartialClassContextStub(DebuggerCompletionContext context)
		{
			var compilation = SD.ParserService.GetCompilationForFile(context.FileName);
			var file = SD.ParserService.GetExistingUnresolvedFile(context.FileName);
			if (compilation == null || file == null)
				return "";
			var unresolvedMember = file.GetMember(context.Location);
			if (unresolvedMember == null)
				return "";
			var member = unresolvedMember.Resolve(new SimpleTypeResolveContext(compilation.MainAssembly));
			if (member == null)
				return "";
			var builder = new TypeSystemAstBuilder();
			MethodDeclaration decl;
			if (unresolvedMember is IMethod) {
				// If it's a method, convert it directly (including parameters + type parameters)
				decl = (MethodDeclaration)builder.ConvertEntity(member);
			} else {
				// Otherwise, create a method anyways, and copy the parameters
				decl = new MethodDeclaration();
				if (member is IParameterizedMember) {
					foreach (var p in ((IParameterizedMember)member).Parameters) {
						decl.Parameters.Add(builder.ConvertParameter(p));
					}
				}
			}
			decl.Name = "__DebuggerStub__";
			decl.ReturnType = builder.ConvertType(member.ReturnType);
			decl.Modifiers = unresolvedMember.IsStatic ? Modifiers.Static : Modifiers.None;
			// Make the method look like an explicit interface implementation so that it doesn't appear in CC
			decl.PrivateImplementationType = new SimpleType("__DummyType__");
			decl.Body = GenerateBodyFromContext(builder, context);
			return WrapInType(unresolvedMember.DeclaringTypeDefinition, decl).ToString();
		}
		protected string GetShortType (IType type)
		{
			if (builder == null) {
				var ctx = ext.CSharpUnresolvedFile.GetTypeResolveContext (ext.UnresolvedFileCompilation, ext.Document.Editor.Caret.Location) as CSharpTypeResolveContext;
				var state = new CSharpResolver (ctx);
				builder = new TypeSystemAstBuilder (state);
				var dt = state.CurrentTypeDefinition;
				var declaring = ctx.CurrentTypeDefinition != null ? ctx.CurrentTypeDefinition.DeclaringTypeDefinition : null;
				if (declaring != null) {
					while (dt != null) {
						if (dt.Equals (declaring)) {
							builder.AlwaysUseShortTypeNames = true;
							break;
						}
						dt = dt.DeclaringTypeDefinition;
					}
				}
			}
			try {
				return GLib.Markup.EscapeText (builder.ConvertType(type).ToString (ext.FormattingPolicy.CreateOptions ()));
			} catch (Exception e) {
				LoggingService.LogError ("Exception while getting short type.", e);
				return "";
			}
		}
            public override void VisitForeachStatement(ForeachStatement foreachStatement)
            {
                base.VisitForeachStatement(foreachStatement);
                var rr = ctx.Resolve(foreachStatement) as ForEachResolveResult;

                if (rr == null)
                {
                    return;
                }
                if (rr.ElementType.Kind == TypeKind.Unknown)
                {
                    return;
                }
                if (ReflectionHelper.GetTypeCode(rr.ElementType) == TypeCode.Object)
                {
                    return;
                }
                if (conversions == null)
                {
                    conversions = CSharpConversions.Get(ctx.Compilation);
                }
                Conversion c = conversions.ImplicitConversion(rr.ElementType, rr.ElementVariable.Type);

                if (c.IsValid)
                {
                    return;
                }
                var     csResolver   = ctx.GetResolverStateBefore(foreachStatement);
                var     builder      = new TypeSystemAstBuilder(csResolver);
                AstType elementType  = builder.ConvertType(rr.ElementType);
                AstType variableType = foreachStatement.VariableType;
                string  text         = ctx.TranslateString("Collection element type '{0}' is not implicitly convertible to '{1}'");

                AddIssue(variableType, string.Format(text, elementType.GetText(), variableType.GetText()));
            }
Exemplo n.º 6
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;
			
			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, ParametersToExpressions(this.Entity));
					var body = entityDeclaration.GetChildByRole(Roles.Body);
					body.Statements.Clear();
					if (((IMethod)this.Entity).ReturnType.IsKnownType(KnownTypeCode.Void))
						body.Statements.Add(new ExpressionStatement(baseCall));
					else
						body.Statements.Add(new ReturnStatement(baseCall));
				} else if (this.Entity.SymbolKind == SymbolKind.Indexer || this.Entity.SymbolKind == SymbolKind.Property) {
					Expression baseCall;
					if (this.Entity.SymbolKind == SymbolKind.Indexer)
						baseCall = new BaseReferenceExpression().Indexer(ParametersToExpressions(this.Entity));
					else
						baseCall = new BaseReferenceExpression().Member(this.Entity.Name);
					var getterBody = entityDeclaration.GetChildByRole(PropertyDeclaration.GetterRole).Body;
					if (!getterBody.IsNull) {
						getterBody.Statements.Clear();
						getterBody.Add(new ReturnStatement(baseCall.Clone()));
					}
					var setterBody = entityDeclaration.GetChildByRole(PropertyDeclaration.SetterRole).Body;
					if (!setterBody.IsNull) {
						setterBody.Statements.Clear();
						setterBody.Add(new AssignmentExpression(baseCall.Clone(), new IdentifierExpression("value")));
					}
				}
			}
			
			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()) {
				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);
			}
		}
Exemplo n.º 7
0
            private static AstType CreateShortType(BaseRefactoringContext refactoringContext, IType expressionType, AstNode node)
            {
                var csResolver = refactoringContext.Resolver.GetResolverStateBefore(node);
                var builder    = new TypeSystemAstBuilder(csResolver);

                return(builder.ConvertType(expressionType));
            }
		public override void Complete(CompletionContext context)
		{
			if (declarationBegin > context.StartOffset) {
				base.Complete(context);
				return;
			}
			
			TypeSystemAstBuilder b = new TypeSystemAstBuilder(contextAtCaret);
			b.GenerateBody = true;
			
			var entityDeclaration = b.ConvertEntity(this.Entity);
			entityDeclaration.Modifiers &= ~Modifiers.VisibilityMask; // remove visiblity
			entityDeclaration.Modifiers |= Modifiers.Partial;
			
			var document = context.Editor.Document;
			StringWriter w = new StringWriter();
			var formattingOptions = CSharpFormattingPolicies.Instance.GetProjectOptions(contextAtCaret.Compilation.GetProject());
			var segmentDict = SegmentTrackingOutputFormatter.WriteNode(
				w, entityDeclaration, formattingOptions.OptionsContainer.GetEffectiveOptions(), context.Editor.Options);
			
			using (document.OpenUndoGroup()) {
				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.OptionsContainer);
			}
		}
 public override void VisitForeachStatement(ForeachStatement foreachStatement)
 {
     base.VisitForeachStatement(foreachStatement);
     var rr = ctx.Resolve(foreachStatement) as ForEachResolveResult;
     if (rr == null)
         return;
     if (rr.ElementType.Kind == TypeKind.Unknown)
         return;
     if (ReflectionHelper.GetTypeCode(rr.ElementType) == TypeCode.Object)
         return;
     if (conversions == null) {
         conversions = CSharpConversions.Get(ctx.Compilation);
     }
     Conversion c = conversions.ImplicitConversion(rr.ElementType, rr.ElementVariable.Type);
     if (c.IsValid)
         return;
     var csResolver = ctx.GetResolverStateBefore(foreachStatement);
     var builder = new TypeSystemAstBuilder(csResolver);
     AstType elementType = builder.ConvertType(rr.ElementType);
     AstType variableType = foreachStatement.VariableType;
     string issueText = ctx.TranslateString("Collection element type '{0}' is not implicitly convertible to '{1}'");
     string fixText = ctx.TranslateString("Use type '{0}'");
     AddIssue(variableType, string.Format(issueText, elementType.GetText(), variableType.GetText()),
              new CodeAction(string.Format(fixText, elementType.GetText()),
                             script => script.Replace(variableType, elementType)));
 }
Exemplo n.º 10
0
		static string GeneratePartialClassContextStub(ICodeContext context)
		{
			var member = context.CurrentMember;
			if (member == null)
				return "";
			var builder = new TypeSystemAstBuilder();
			MethodDeclaration decl;
			if (member is IMethod) {
				// If it's a method, convert it directly (including parameters + type parameters)
				decl = (MethodDeclaration)builder.ConvertEntity(member);
			} else {
				// Otherwise, create a method anyways, and copy the parameters
				decl = new MethodDeclaration();
				if (member is IParameterizedMember) {
					foreach (var p in ((IParameterizedMember)member).Parameters) {
						decl.Parameters.Add(builder.ConvertParameter(p));
					}
				}
			}
			decl.Name = "__DebuggerStub__";
			decl.ReturnType = builder.ConvertType(member.ReturnType);
			decl.Modifiers = member.IsStatic ? Modifiers.Static : Modifiers.None;
			// Make the method look like an explicit interface implementation so that it doesn't appear in CC
			decl.PrivateImplementationType = new SimpleType("__DummyType__");
			decl.Body = GenerateBodyFromContext(builder, context.LocalVariables.ToArray());
			return WrapInType(context.CurrentTypeDefinition, decl).ToString();
		}
		public CSharpCompletionDataFactory(CSharpCompletionContext completionContext, CSharpResolver contextAtCaret)
		{
			Debug.Assert(completionContext != null);
			Debug.Assert(contextAtCaret != null);
			this.completionContext = completionContext;
			this.contextAtCaret = contextAtCaret;
			this.builder = new TypeSystemAstBuilder(contextAtCaret);
		}
        public static string GetOverrideTargetName
            (IMember m, CSharpTypeResolveContext resolveContext) {
            var builder = new TypeSystemAstBuilder
                (new CSharpResolver(resolveContext));

			return builder.ConvertEntity(m).ToString()
                // Builder automatically adds a trailing newline
                .TrimEnd(Environment.NewLine.ToCharArray());
        }
Exemplo n.º 13
0
		public SignatureMarkupCreator (CSharpResolver resolver, CSharpFormattingOptions formattingOptions)
		{
			this.colorStyle = SyntaxModeService.GetColorStyle (MonoDevelop.Ide.IdeApp.Preferences.ColorScheme);

			this.resolver = resolver;
			this.astBuilder = new TypeSystemAstBuilder (resolver) {
				ConvertUnboundTypeArguments = true,
				UseAliases = false
			};
			this.formattingOptions = formattingOptions;
		}
            public MemberCompletionData(IType type, IEntity member, TypeSystemAstBuilder builder)
            {
                DeclarationCategory = DeclarationCategory.Enumeration_Member;

                Type = type;
                Member = member;

                string typeName = builder.ConvertType(type).GetText();
                SetDefaultText(typeName + "." + member.Name);

                Documentation = member.Documentation;
            }
Exemplo n.º 15
0
		public ImportCompletionData(ITypeDefinition typeDef, CSharpResolver contextAtCaret, bool useFullName)
			: base(typeDef)
		{
			this.Description = "using " + typeDef.Namespace + ";";
			if (useFullName) {
				var astBuilder = new TypeSystemAstBuilder(contextAtCaret);
				insertionText = astBuilder.ConvertType(typeDef).ToString();
			} else {
				insertionText = typeDef.Name;
				insertUsing = typeDef.Namespace;
			}
		}
            IEnumerable <CodeAction> GetActions(BaseRefactoringContext context, Expression targetExpression,
                                                IMember member)
            {
                var    csResolver  = context.Resolver.GetResolverStateBefore(targetExpression);
                var    builder     = new TypeSystemAstBuilder(csResolver);
                var    newType     = builder.ConvertType(member.DeclaringType);
                string description = string.Format("{0} '{1}'", context.TranslateString("Use base class"), newType.GetText());

                yield return(new CodeAction(description, script => {
                    script.Replace(targetExpression, newType);
                }));
            }
Exemplo n.º 17
0
            IEnumerable <CodeAction> GetActions(ParameterDeclaration parameter, IEnumerable <IType> possibleTypes)
            {
                var csResolver = ctx.Resolver.GetResolverStateBefore(parameter);
                var astBuilder = new TypeSystemAstBuilder(csResolver);

                foreach (var type in possibleTypes)
                {
                    var localType = type;
                    var message   = String.Format(ctx.TranslateString("Demote parameter to '{0}'"), type.FullName);
                    yield return(new CodeAction(message, script => {
                        script.Replace(parameter.Type, astBuilder.ConvertType(localType));
                    }, parameter.NameToken));
                }
            }
Exemplo n.º 18
0
		public override void InsertEventHandler(ITypeDefinition target, string name, IEvent eventDefinition, bool jumpTo)
		{
			IUnresolvedTypeDefinition match = null;
			
			foreach (var part in target.Parts) {
				if (match == null || EntityModelContextUtils.IsBetterPart(part, match, ".cs"))
					match = part;
			}
			
			if (match == null) return;
			
			var view = SD.FileService.OpenFile(new FileName(match.Region.FileName), jumpTo);
			var editor = view.GetRequiredService<ITextEditor>();
			var last = match.Members.LastOrDefault() ?? (IUnresolvedEntity)match;
			editor.Caret.Location = last.BodyRegion.End;
			var context = SDRefactoringContext.Create(editor, CancellationToken.None);
			
			var node = context.RootNode.GetNodeAt<EntityDeclaration>(last.Region.Begin);
			var resolver = context.GetResolverStateAfter(node);
			var builder = new TypeSystemAstBuilder(resolver);
			var delegateDecl = builder.ConvertEntity(eventDefinition.ReturnType.GetDefinition()) as DelegateDeclaration;
			if (delegateDecl == null) return;
			var throwStmt = new ThrowStatement(new ObjectCreateExpression(context.CreateShortType("System", "NotImplementedException")));
			var decl = new MethodDeclaration() {
				ReturnType = delegateDecl.ReturnType.Clone(),
				Name = name,
				Body = new BlockStatement() {
					throwStmt
				}
			};
			var param = delegateDecl.Parameters.Select(p => p.Clone()).OfType<ParameterDeclaration>().ToArray();
			decl.Parameters.AddRange(param);
			
			using (Script script = context.StartScript()) {
				// FIXME : will not work properly if there are no members.
				if (last == match) {
					throw new NotImplementedException();
					// TODO InsertWithCursor not implemented!
					//script.InsertWithCursor("Insert event handler", Script.InsertPosition.End, decl).RunSynchronously();
				} else {
					// TODO does not jump correctly...
					script.InsertAfter(node, decl);
					editor.JumpTo(throwStmt.StartLocation.Line, throwStmt.StartLocation.Column);
				}
			}
		}
            public TypeCompletionData(ICSharpCode.NRefactory.TypeSystem.IType type, bool fullName, bool isInAttributeContext, TypeSystemAstBuilder builder, bool addForTypeCreation)
            {
                Type = type;
                FullName = fullName;
                IsInAttributeContext = isInAttributeContext;

                // Confirm that this doesn't also include other types, such as enums, structs, etc.
                //DeclarationCategory = DeclarationCategory.Class;
                DeclarationCategory = type.Kind.ResolveDeclarationCategoryFromTypeKind();

                string typeName = fullName ? builder.ConvertType(type).GetText() : type.Name;
                if (isInAttributeContext && typeName.EndsWith("Attribute") && typeName.Length > "Attribute".Length)
                {
                    typeName = typeName.Substring(0, typeName.Length - "Attribute".Length);
                }
                SetDefaultText(typeName);

                // for documentation, see type.GetDefinition().Documentation
                Documentation = type.GetDefinition().Documentation;
            }
Exemplo n.º 20
0
        public string ConvertSymbol(ISymbol symbol)
        {
            var stringWriter = new StringWriter();
            var astBuilder = new TypeSystemAstBuilder();
            astBuilder.AlwaysUseShortTypeNames = true;
            AstNode node = astBuilder.ConvertSymbol(symbol);
            var writer = new TextWriterTokenWriter (stringWriter);
            var rt = node.GetChildByRole (Roles.Type);
            if (!rt.IsNull)
            {
                rt.AcceptVisitor (new CSharpOutputVisitor (stringWriter, FormattingOptionsFactory.CreateMono()));

            }

            IProperty property = symbol as IProperty;
            if (property != null)
            {
                writer.Space ();
                writer.WriteToken (Roles.LBrace, "{");
                writer.Space ();
                if (property.CanGet)
                {
                    writer.WriteKeyword (PropertyDeclaration.GetKeywordRole, "get");
                    writer.WriteToken (Roles.Semicolon, ";");
                    writer.Space ();
                }
                if (property.CanSet)
                {
                    writer.WriteKeyword (PropertyDeclaration.SetKeywordRole, "set");
                    writer.WriteToken (Roles.Semicolon, ";");
                    writer.Space ();
                }
                writer.WriteToken (Roles.RBrace, "}");
            }
            return stringWriter.ToString();

            }
Exemplo n.º 21
0
		static string GeneratePartialClassContextStub(FileName fileName, TextLocation currentLocation, StackFrame context)
		{
			var compilation = SD.ParserService.GetCompilationForFile(fileName);
			var file = SD.ParserService.GetExistingUnresolvedFile(fileName);
			if (compilation == null || file == null)
				return "";
			var member = file.GetMember(currentLocation);
			if (member == null)
				return "";
			var builder = new TypeSystemAstBuilder();
			EntityDeclaration decl = builder.ConvertEntity(member.Resolve(new SimpleTypeResolveContext(compilation.MainAssembly)));
			decl.Name = "__DebuggerStub_" + decl.Name;
			decl.Modifiers &= (Modifiers.Static);
			switch (member.SymbolKind) {
				case SymbolKind.Property:
					break;
				case SymbolKind.Indexer:
					break;
				case SymbolKind.Event:
					break;
				case SymbolKind.Method:
					GenerateBodyFromContext(builder, context, (MethodDeclaration)decl);
					break;
				case SymbolKind.Operator:
					break;
				case SymbolKind.Constructor:
					break;
				case SymbolKind.Destructor:
					break;
				case SymbolKind.Accessor:
					break;
				default:
					throw new ArgumentOutOfRangeException();
			}
			return WrapInType(member.DeclaringTypeDefinition, decl.ToString());
		}
Exemplo n.º 22
0
        /// <summary>
        ///   Takes an editing context. Inserts an override
        ///   declaration of the chosen member in the context. Returns
        ///   the new context.
        /// </summary>
        /// <remarks>
        ///   The text editor cursor stays in the same line and column
        ///   it originally was.
        /// </remarks>
        public RunOverrideTargetResponse RunOverrideTarget
            (RunOverrideTargetRequest request) {
            var overrideContext = new OverrideContext(request, _parser);
            var refactoringContext = OmniSharpRefactoringContext.GetContext
                (overrideContext.BufferParser, request);

            var memberToOverride = overrideContext.GetOverridableMembers()
                .First(ot => {
                    var memberSignature =
                     GetOverrideTargetsResponse.GetOverrideTargetName
                      (ot, overrideContext.CompletionContext.ResolveContext);

                    return memberSignature == request.OverrideTargetName;});

            var builder = new TypeSystemAstBuilder
                (new CSharpResolver
                 (overrideContext.CompletionContext.ResolveContext))
                 // Will generate a "throw new
                 // NotImplementedException();" statement in the
                 // bodies
                 {GenerateBody = true};

            var newEditorContents = runOverrideTargetWorker
                ( request
                , refactoringContext
                , overrideContext.CompletionContext.ParsedContent
                , script: new OmniSharpScript(refactoringContext, _config)
                , memberDeclaration:
                    builder.ConvertEntity(memberToOverride));

            return new RunOverrideTargetResponse
                ( fileName : request.FileName
                , buffer   : newEditorContents.Text
                , line     : request.Line
                , column   : request.Column);
        }
Exemplo n.º 23
0
 TypeSystemAstBuilder CreateAstBuilder()
 {
     TypeSystemAstBuilder astBuilder = new TypeSystemAstBuilder();
     return astBuilder;
 }
		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;
				var entities = FindFieldsAndProperties(resolvedCurrent).ToList();
				if (entities.Any()) {
					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;

					AbstractInlineRefactorDialog dialog = new OverrideToStringMethodDialog(insertionContext, context.Editor, insertionPos, entities, baseCallStatement);
					dialog.Element = uiService.CreateInlineUIElement(insertionPos, dialog);
					
					insertionContext.RegisterActiveElement(new InlineRefactorSnippetElement(cxt => null, ""), dialog);
				} else {
					if (baseCallStatement != null) {
						// Add default base call
						MethodDeclaration insertedOverrideMethod = refactoringContext.GetNode().PrevSibling as MethodDeclaration;
						if (insertedOverrideMethod == null)
						{
							// We are not inside of a method declaration
							return;
						}
						using (Script script = refactoringContext.StartScript()) {
							script.AddTo(insertedOverrideMethod.Body, baseCallStatement);
						}
					}
				}
				
				insertionContext.RaiseInsertionCompleted(EventArgs.Empty);
			}
		}
Exemplo n.º 25
0
		string AddDelegateHandlers(CompletionDataWrapper completionList, IType delegateType, bool addSemicolon = true, bool addDefault = true, string optDelegateName = null)
		{
			IMethod delegateMethod = delegateType.GetDelegateInvokeMethod();
			PossibleDelegates.Add(delegateMethod);
			var thisLineIndent = GetLineIndent(location.Line);
			string delegateEndString = EolMarker + thisLineIndent + "}" + (addSemicolon ? ";" : "");
			//bool containsDelegateData = completionList.Result.Any(d => d.DisplayText.StartsWith("delegate("));
			if (addDefault && !completionList.AnonymousDelegateAdded) {
				completionList.AnonymousDelegateAdded = true;
				var oldDelegate = completionList.Result.FirstOrDefault(cd => cd.DisplayText == "delegate");
				if (oldDelegate != null)
					completionList.Result.Remove(oldDelegate);
				completionList.AddCustom(
					"delegate",
					"Creates anonymous delegate.",
					"delegate {" + EolMarker + thisLineIndent + IndentString + "|" + delegateEndString
				);
				if (LanguageVersion.Major >= 5) {
					completionList.AddCustom(
						"async delegate",
						"Creates anonymous async delegate.",
						"async delegate {" + EolMarker + thisLineIndent + IndentString + "|" + delegateEndString
					);
				}
			}
			var sb = new StringBuilder("(");
			var sbWithoutTypes = new StringBuilder("(");
			var state = GetState();
			var builder = new TypeSystemAstBuilder(state);

			for (int k = 0; k < delegateMethod.Parameters.Count; k++) {

				if (k > 0) {
					sb.Append(", ");
					sbWithoutTypes.Append(", ");
				}
				var convertedParameter = builder.ConvertParameter(delegateMethod.Parameters [k]);
				if (convertedParameter.ParameterModifier == ParameterModifier.Params)
					convertedParameter.ParameterModifier = ParameterModifier.None;
				sb.Append(convertedParameter.ToString(FormattingPolicy));
				sbWithoutTypes.Append(delegateMethod.Parameters [k].Name);
			}

			sb.Append(")");
			sbWithoutTypes.Append(")");
			var signature = sb.ToString();
			if (!completionList.HasAnonymousDelegateAdded(signature)) {
				completionList.AddAnonymousDelegateAdded(signature);

				completionList.AddCustom(
					"delegate" + signature,
					"Creates anonymous delegate.",
					"delegate" + signature + " {" + EolMarker + thisLineIndent + IndentString + "|" + delegateEndString
				);
				if (LanguageVersion.Major >= 5) {
					completionList.AddCustom(
						"async delegate" + signature,
						"Creates anonymous async delegate.",
						"async delegate" + signature + " {" + EolMarker + thisLineIndent + IndentString + "|" + delegateEndString
					);
				}
				if (!completionList.Result.Any(data => data.DisplayText == sb.ToString())) {
					completionList.AddCustom(
						signature,
						"Creates typed lambda expression.",
						signature + " => |" + (addSemicolon ? ";" : "")
					);
					if (LanguageVersion.Major >= 5) {
						completionList.AddCustom(
							"async " + signature,
							"Creates typed async lambda expression.",
							"async " + signature + " => |" + (addSemicolon ? ";" : "")
						);
					}

					if (!delegateMethod.Parameters.Any(p => p.IsOut || p.IsRef) && !completionList.Result.Any(data => data.DisplayText == sbWithoutTypes.ToString())) {
						completionList.AddCustom(
							sbWithoutTypes.ToString(),
							"Creates lambda expression.",
							sbWithoutTypes + " => |" + (addSemicolon ? ";" : "")
						);
						if (LanguageVersion.Major >= 5) {
							completionList.AddCustom(
								"async " + sbWithoutTypes,
								"Creates async lambda expression.",
								"async " + sbWithoutTypes + " => |" + (addSemicolon ? ";" : "")
							);
						}
					}
				}

			}

			string varName = "Handle" + delegateType.Name + optDelegateName;
			completionList.Add(factory.CreateEventCreationCompletionData(varName, delegateType, null, signature, currentMember, currentType));


			/*			 TODO:Make factory method out of it.
			// It's  needed to temporarly disable inserting auto matching bracket because the anonymous delegates are selectable with '('
			// otherwise we would end up with () => )
			if (!containsDelegateData) {
				var savedValue = MonoDevelop.SourceEditor.DefaultSourceEditorOptions.Instance.AutoInsertMatchingBracket;
				MonoDevelop.SourceEditor.DefaultSourceEditorOptions.Instance.AutoInsertMatchingBracket = false;
				completionList.Result.CompletionListClosed += delegate {
					MonoDevelop.SourceEditor.DefaultSourceEditorOptions.Instance.AutoInsertMatchingBracket = savedValue;
				};
			}*/
			return sb.ToString();
		}
Exemplo n.º 26
0
		static IEnumerable<PossibleNamespace> GetPossibleNamespaces (Document doc, AstNode node, ResolveResult resolveResult, DocumentLocation location)
		{
			var unit = doc.ParsedDocument.GetAst<SyntaxTree> ();
			if (unit == null)
				yield break;
			var project = doc.Project;
			if (project == null)
				yield break;
			int tc = GetTypeParameterCount (node);
			var attribute = unit.GetNodeAt<ICSharpCode.NRefactory.CSharp.Attribute> (location);
			bool isInsideAttributeType = attribute != null && attribute.Type.Contains (location);

			var compilations = new List<Tuple<ICompilation, MonoDevelop.Projects.ProjectReference>> ();
			compilations.Add (Tuple.Create (doc.Compilation, (MonoDevelop.Projects.ProjectReference)null));
			var referencedItems = IdeApp.Workspace != null ? project.GetReferencedItems (IdeApp.Workspace.ActiveConfiguration).ToList () : (IEnumerable<SolutionItem>) new SolutionItem[0];
			var solution = project != null ? project.ParentSolution : null;
			if (solution != null) {
				foreach (var curProject in solution.GetAllProjects ()) {
					if (curProject == project || referencedItems.Contains (curProject))
						continue;

					var otherRefes = IdeApp.Workspace != null ? curProject.GetReferencedItems (IdeApp.Workspace.ActiveConfiguration).ToList () : (IEnumerable<SolutionItem>) new SolutionItem[0];
					if (otherRefes.Contains (project))
						continue;

					var comp = TypeSystemService.GetCompilation (curProject);
					if (comp == null)
						continue;
					compilations.Add (Tuple.Create (comp, new MonoDevelop.Projects.ProjectReference (curProject)));
				}
			}

			var netProject = project as DotNetProject;
			if (netProject == null) 
				yield break;
			FrameworkLookup frameworkLookup;
			if (!TypeSystemService.TryGetFrameworkLookup (netProject, out frameworkLookup))
				frameworkLookup = null;
			if (frameworkLookup != null && resolveResult is UnknownMemberResolveResult) {
				var umResult = (UnknownMemberResolveResult)resolveResult;
				try {
					foreach (var r in frameworkLookup.GetExtensionMethodLookups (umResult)) {
						var systemAssembly = netProject.AssemblyContext.GetAssemblyFromFullName (r.FullName, r.Package, netProject.TargetFramework);
						if (systemAssembly == null)
							continue;
						if (CanBeReferenced (doc.Project, systemAssembly))
							compilations.Add (Tuple.Create (TypeSystemService.GetCompilation (systemAssembly, doc.Compilation), new MonoDevelop.Projects.ProjectReference (systemAssembly)));
					}
				} catch (Exception e) {
					if (!TypeSystemService.RecreateFrameworkLookup (netProject))
						LoggingService.LogError (string.Format ("Error while looking up extension method {0}", umResult.MemberName), e);
				}
			}
			bool foundIdentifier = false;
			var lookup = new MemberLookup (null, doc.Compilation.MainAssembly);
			foreach (var comp in compilations) {
				var compilation = comp.Item1;
				var requiredReference = comp.Item2;
				if (resolveResult is AmbiguousTypeResolveResult) {
					if (compilation != doc.Compilation)
						continue;
					var aResult = resolveResult as AmbiguousTypeResolveResult;
					var file = doc.ParsedDocument.ParsedFile as CSharpUnresolvedFile;
					var scope = file.GetUsingScope (location).Resolve (compilation);
					while (scope != null) {
						foreach (var u in scope.Usings) {
							foreach (var typeDefinition in u.Types) {
								if (typeDefinition.Name == aResult.Type.Name && 
								    typeDefinition.TypeParameterCount == tc &&
								    lookup.IsAccessible (typeDefinition, false)) {
									yield return new PossibleNamespace (typeDefinition.Namespace, true, requiredReference);
								}
							}
						}
						scope = scope.Parent;
					}
				}
				var allTypes =  compilation == doc.Compilation ? compilation.GetAllTypeDefinitions () : compilation.MainAssembly.GetAllTypeDefinitions ();
				if (resolveResult is UnknownIdentifierResolveResult) {
					var uiResult = resolveResult as UnknownIdentifierResolveResult;
					string possibleAttributeName = isInsideAttributeType ? uiResult.Identifier + "Attribute" : uiResult.Identifier;
					foreach (var typeDefinition in allTypes) {
						if ((typeDefinition.Name == possibleAttributeName || typeDefinition.Name == uiResult.Identifier) && typeDefinition.TypeParameterCount == tc &&
						    lookup.IsAccessible (typeDefinition, false)) {
							if (typeDefinition.DeclaringTypeDefinition != null) {
								var builder = new TypeSystemAstBuilder (new CSharpResolver (doc.Compilation));
								foundIdentifier = true;
								yield return new PossibleNamespace (builder.ConvertType (typeDefinition.DeclaringTypeDefinition).ToString (), false, requiredReference);
							} else {
								foundIdentifier = true;
								yield return new PossibleNamespace (typeDefinition.Namespace, true, requiredReference);
							}
						}
					}
				}

				if (resolveResult is UnknownMemberResolveResult) {
					var umResult = (UnknownMemberResolveResult)resolveResult;
					string possibleAttributeName = isInsideAttributeType ? umResult.MemberName + "Attribute" : umResult.MemberName;
					foreach (var typeDefinition in allTypes.Where (t => t.HasExtensionMethods)) {
						if (!lookup.IsAccessible (typeDefinition, false))
							continue;
						foreach (var method in typeDefinition.Methods.Where (m => m.IsExtensionMethod && (m.Name == possibleAttributeName || m.Name == umResult.MemberName))) {
							if (!lookup.IsAccessible (method, false))
								continue;
							IType[] inferredTypes;
							if (CSharpResolver.IsEligibleExtensionMethod (
								compilation.Import (umResult.TargetType),
								method,
								true,
								out inferredTypes
							)) {
								yield return new PossibleNamespace (typeDefinition.Namespace, true, requiredReference);
								goto skipType;
							}
						}
						skipType:
						;
					}
				}
				
				if (resolveResult is ErrorResolveResult) {
					var identifier = unit != null ? unit.GetNodeAt<Identifier> (location) : null;
					if (identifier != null) {
						var uiResult = resolveResult as UnknownIdentifierResolveResult;
						if (uiResult != null) {
							string possibleAttributeName = isInsideAttributeType ? uiResult.Identifier + "Attribute" : uiResult.Identifier;
							foreach (var typeDefinition in allTypes) {
								if ((identifier.Name == possibleAttributeName || identifier.Name == uiResult.Identifier) && 
									typeDefinition.TypeParameterCount == tc && 
									lookup.IsAccessible (typeDefinition, false))
									yield return new PossibleNamespace (typeDefinition.Namespace, true, requiredReference);
							}
						}
					}
				}
			}

			// Try to search framework types
			if (!foundIdentifier && frameworkLookup != null && resolveResult is UnknownIdentifierResolveResult && node is AstType) {
				var uiResult = resolveResult as UnknownIdentifierResolveResult;
				if (uiResult != null) {
					var lookups = new List<Tuple<FrameworkLookup.AssemblyLookup, SystemAssembly>> ();
					try {
						foreach (var r in frameworkLookup.GetLookups (uiResult, tc, isInsideAttributeType)) {
							var systemAssembly = netProject.AssemblyContext.GetAssemblyFromFullName (r.FullName, r.Package, netProject.TargetFramework);
							if (systemAssembly == null)
								continue;
							if (CanBeReferenced (doc.Project, systemAssembly))
								lookups.Add (Tuple.Create (r, systemAssembly));
						}
					} catch (Exception e) {
						if (!TypeSystemService.RecreateFrameworkLookup (netProject))
							LoggingService.LogError (string.Format ("Error while looking up identifier {0}", uiResult.Identifier), e);
					}
					foreach(var kv in lookups)
						yield return new PossibleNamespace (kv.Item1.Namespace, true, new MonoDevelop.Projects.ProjectReference (kv.Item2));

				}
			}
			if (!foundIdentifier && frameworkLookup != null && resolveResult is UnknownMemberResolveResult) {
				var uiResult = resolveResult as UnknownMemberResolveResult;
				if (uiResult != null) {
					var lookups = new List<Tuple<FrameworkLookup.AssemblyLookup, SystemAssembly>> ();
					try {
						foreach (var r in frameworkLookup.GetLookups (uiResult, node.ToString (), tc, isInsideAttributeType)) {
							var systemAssembly = netProject.AssemblyContext.GetAssemblyFromFullName (r.FullName, r.Package, netProject.TargetFramework);
							if (systemAssembly == null)
								continue;
							if (CanBeReferenced (doc.Project, systemAssembly))
								lookups.Add (Tuple.Create (r, systemAssembly));
						}
					} catch (Exception e) {
						if (!TypeSystemService.RecreateFrameworkLookup (netProject))
							LoggingService.LogError (string.Format ("Error while looking up member resolve result {0}", node), e);
					}
					foreach(var kv in lookups)
						yield return new PossibleNamespace (kv.Item1.Namespace, true, new MonoDevelop.Projects.ProjectReference (kv.Item2));
				}
			}

		}
Exemplo n.º 27
0
		string GetShortType(IType type, CSharpResolver state)
		{
			var builder = new TypeSystemAstBuilder(state);
			var dt = state.CurrentTypeDefinition;
			var declaring = type.DeclaringType != null ? type.DeclaringType.GetDefinition() : null;
			if (declaring != null) {
				while (dt != null) {
					if (dt.Equals(declaring)) {
						builder.AlwaysUseShortTypeNames = true;
						break;
					}
					dt = dt.DeclaringTypeDefinition;
				}
			}
			var shortType = builder.ConvertType(type);
			return shortType.GetText(FormattingPolicy);
		}
Exemplo n.º 28
0
		static void GenerateBodyFromContext(TypeSystemAstBuilder builder, StackFrame context, MethodDeclaration methodDeclaration)
		{
			methodDeclaration.Body = new BlockStatement();
			foreach (var v in context.GetLocalVariables())
				methodDeclaration.Body.Statements.Add(new VariableDeclarationStatement(builder.ConvertType(v.Type), v.Name));
			methodDeclaration.Body.Statements.Add(new ExpressionStatement(new IdentifierExpression("$__Caret_Point__$")));
		}
Exemplo n.º 29
0
        public static ICSharpCode.NRefactory.CSharp.AstType ConvertToAstType(this IType type)
        {
            var builder = new TypeSystemAstBuilder(MinimalResolveContext.Instance);

            return(builder.ConvertType(type));
        }
Exemplo n.º 30
0
		void AddAttribute(DomRegion region, IAttribute attribute, string target = "")
		{
			var view = SD.FileService.OpenFile(new FileName(region.FileName), false);
			var editor = view.GetRequiredService<ITextEditor>();
			var context = SDRefactoringContext.Create(editor.FileName, editor.Document, region.Begin, CancellationToken.None);
			var node = context.RootNode.GetNodeAt<EntityDeclaration>(region.Begin);
			var resolver = context.GetResolverStateBefore(node);
			var builder = new TypeSystemAstBuilder(resolver);
			
			using (Script script = context.StartScript()) {
				var attr = new AttributeSection();
				attr.AttributeTarget = target;
				attr.Attributes.Add(builder.ConvertAttribute(attribute));
				script.InsertBefore(node, attr);
			}
		}
Exemplo n.º 31
0
		static TypeSystemAstBuilder CreateBuilder (MonoDevelop.Ide.Gui.Document doc, int offset, ICompilation compilation)
		{
			var ctx = doc.ParsedDocument.ParsedFile.GetTypeResolveContext (doc.Compilation, doc.Editor.Caret.Location) as CSharpTypeResolveContext;
			var state = new CSharpResolver (ctx);
			var builder = new TypeSystemAstBuilder (state);
			builder.AddAnnotations = true;
			var dt = state.CurrentTypeDefinition;
			var declaring = ctx.CurrentTypeDefinition != null ? ctx.CurrentTypeDefinition.DeclaringTypeDefinition : null;
			if (declaring != null) {
				while (dt != null) {
					if (dt.Equals (declaring)) {
						builder.AlwaysUseShortTypeNames = true;
						break;
					}
					dt = dt.DeclaringTypeDefinition;
				}
			}
			return builder;
		}
Exemplo n.º 32
0
        public static ICSharpCode.NRefactory.CSharp.AstType ConvertToAstType(this IType type)
        {
            var builder = new TypeSystemAstBuilder();

            return(builder.ConvertType(type));
        }
Exemplo n.º 33
0
 TypeSystemAstBuilder CreateAstBuilder()
 {
     TypeSystemAstBuilder astBuilder = new TypeSystemAstBuilder();
     astBuilder.AddAnnotations = true;
     astBuilder.ShowModifiers = (ConversionFlags & ConversionFlags.ShowModifiers) == ConversionFlags.ShowModifiers;
     astBuilder.ShowAccessibility = (ConversionFlags & ConversionFlags.ShowAccessibility) == ConversionFlags.ShowAccessibility;
     astBuilder.AlwaysUseShortTypeNames = (ConversionFlags & ConversionFlags.UseFullyQualifiedTypeNames) != ConversionFlags.UseFullyQualifiedTypeNames;
     astBuilder.ShowParameterNames = (ConversionFlags & ConversionFlags.ShowParameterNames) == ConversionFlags.ShowParameterNames;
     return astBuilder;
 }
Exemplo n.º 34
0
 void WriteTypeDeclarationName(ITypeDefinition typeDef, TokenWriter writer, CSharpFormattingOptions formattingPolicy)
 {
     var astBuilder = new TypeSystemAstBuilder();
     EntityDeclaration node = astBuilder.ConvertEntity(typeDef);
     if (typeDef.DeclaringTypeDefinition != null)
     {
         WriteTypeDeclarationName(typeDef.DeclaringTypeDefinition, writer, formattingPolicy);
         writer.WriteToken(Roles.Dot, ".");
     }
     writer.WriteIdentifier(node.NameToken);
     WriteTypeParameters(writer, node.GetChildrenByRole(Roles.TypeParameter));
 }
Exemplo n.º 35
0
		/// <summary> Get the value of the node and update the UI text fields. </summary>
		/// <remarks> This should be only called once so the Value is not cached. </remarks>
		void GetValueAndUpdateUI()
		{
			try {
				Stopwatch watch = new Stopwatch();
				watch.Start();
				
				// Do not keep permanent reference
				Value val = this.getValue();
				
				if (val == null) {
					Value = string.Empty;
					Type  = string.Empty;
					GetChildren = null;
					VisualizerCommands = null;
					return;
				}
				
				// Note that the child collections are lazy-evaluated
				if (val.IsNull) {
					this.GetChildren = null;
				} else if (val.Type.IsPrimitiveType() || val.Type.IsKnownType(KnownTypeCode.String)) { // Must be before IsClass
					this.GetChildren = null;
				} else if (val.Type.Kind == TypeKind.Array) { // Must be before IsClass
					var dimBase = val.ArrayBaseIndicies;		// Eval now
					var dimSize = val.ArrayDimensions;		// Eval now
					if (val.ArrayLength > 0) {
						this.GetChildren = () => GetArrayChildren(dimBase, dimSize);
					}
				} else if (val.Type.Kind == TypeKind.Class || val.Type.Kind == TypeKind.Struct) {
					if (val.Type.IsKnownType(typeof(List<>))) {
						if ((int)val.GetFieldValue("_size").PrimitiveValue > 0)
							this.GetChildren = () => GetIListChildren(this.GetValue);
					} else {
						this.GetChildren = () => GetObjectChildren(val.Type);
					}
				} else if (val.Type.Kind == TypeKind.Pointer) {
					if (val.Dereference() != null) {
						this.GetChildren = () => new[] { new ValueNode(ClassBrowserIconService.LocalVariable, "*" + this.Name, () => GetValue().Dereference()) };
					}
				}
				
				// Do last since it may expire the object
				if (val.IsNull) {
					fullValue = "null";
				} else if (val.Type.IsInteger()) {
					var i = val.PrimitiveValue;
					if (DebuggingOptions.Instance.ShowIntegersAs == ShowIntegersAs.Decimal) {
						fullValue = i.ToString();
					} else {
						string hex = string.Format("0x{0:X4}", i);
						if (hex.Length > 6 ) hex = string.Format("0x{0:X8}", i);
						if (hex.Length > 10) hex = string.Format("0x{0:X16}", i);
						if (DebuggingOptions.Instance.ShowIntegersAs == ShowIntegersAs.Hexadecimal) {
							fullValue = hex;
						} else {
							fullValue = string.Format("{0} ({1})", i, hex);
						}
					}
				} else if (val.Type.Kind == TypeKind.Pointer) {
					fullValue = String.Format("0x{0:X}", val.PointerAddress);
				} else if (val.Type.IsKnownType(KnownTypeCode.String)) {
					fullValue = '"' + val.InvokeToString(WindowsDebugger.EvalThread).Replace("\n", "\\n").Replace("\t", "\\t").Replace("\r", "\\r").Replace("\0", "\\0").Replace("\b", "\\b").Replace("\a", "\\a").Replace("\f", "\\f").Replace("\v", "\\v").Replace("\"", "\\\"") + '"';
				} else if (val.Type.IsKnownType(KnownTypeCode.Char)) {
					fullValue = "'" + val.InvokeToString(WindowsDebugger.EvalThread).Replace("\n", "\\n").Replace("\t", "\\t").Replace("\r", "\\r").Replace("\0", "\\0").Replace("\b", "\\b").Replace("\a", "\\a").Replace("\f", "\\f").Replace("\v", "\\v").Replace("\"", "\\\"") + "'";
				} else if ((val.Type.Kind == TypeKind.Class || val.Type.Kind == TypeKind.Struct)) {
					fullValue = val.FormatByDebuggerDisplayAttribute(WindowsDebugger.EvalThread);
					if (fullValue == null)
						fullValue = val.InvokeToString(WindowsDebugger.EvalThread);
				} else if (val.Type.Kind == TypeKind.Enum) {
					var primitiveValue = val.PrimitiveValue;
					var builder = new TypeSystemAstBuilder();
					builder.AlwaysUseShortTypeNames = true;
					AstNode node = builder.ConvertConstantValue(val.Type, primitiveValue);
					fullValue = node + "=" + primitiveValue;
				} else {
					fullValue = val.AsString();
				}
				
				this.error = null;
				this.Value = (fullValue.Length > 256) ? fullValue.Substring(0, 256) + "..." : fullValue;
				this.Type = val.Type.Name;
				
				if (!val.IsNull) {
					this.VisualizerCommands = VisualizerDescriptors.GetAllDescriptors()
						.Where(descriptor => descriptor.IsVisualizerAvailable(val.Type))
						.Select(descriptor => descriptor.CreateVisualizerCommand(this.Name, this.GetValue))
						.ToList();
				}
				
				LoggingService.InfoFormatted("Evaluated node '{0}' in {1} ms", this.Name, watch.ElapsedMilliseconds);
				
			} catch (GetValueException e) {
				error = e;
				this.Value = e.Message;
				this.Type  = string.Empty;
				this.GetChildren = null;
				this.VisualizerCommands = null;
			} finally {
				if (error == null)
					ContextMenuAddInTreeEntry = "/AddIns/Debugger/Tooltips/ContextMenu/ValueNode";
				else
					ContextMenuAddInTreeEntry = "/AddIns/Debugger/Tooltips/ContextMenu/ErrorNode";
			}
		}
Exemplo n.º 36
0
		public string GetTypeReferenceString (IType type, bool highlight = true)
		{
			if (type == null)
				throw new ArgumentNullException ("type");
			if (type.Kind == TypeKind.Null)
				return "?";
			if (type.Kind == TypeKind.Array) {
				var arrayType = (ArrayType)type;
				return GetTypeReferenceString (arrayType.ElementType, highlight) + "[" + new string (',', arrayType.Dimensions - 1) + "]";
			}
			if (type.Kind == TypeKind.Pointer)
				return GetTypeReferenceString (((PointerType)type).ElementType, highlight) + "*";
			AstType astType;
			try {
				astType = astBuilder.ConvertType (type);
			} catch (Exception e) {
				var compilation = GetCompilation (type);
				if (compilation == null) {

					Console.WriteLine ("type:"+type.GetType ());
					Console.WriteLine ("got exception while conversion:" + e);
					return "?";
				}
				astType = new TypeSystemAstBuilder (new CSharpResolver (compilation)).ConvertType (type);
			}

			if (astType is PrimitiveType) {
				return Highlight (astType.ToString (formattingOptions), colorStyle.KeywordTypes);
			}
			var text = AmbienceService.EscapeText (astType.ToString (formattingOptions));
			return highlight ? HighlightSemantically (text, colorStyle.UserTypes) : text;
		}