protected override Task<IEnumerable<CompletionData>> GetItemsWorkerAsync (CompletionResult completionResult, CompletionEngine engine, CompletionContext completionContext, CompletionTriggerInfo info, SyntaxContext ctx, CancellationToken cancellationToken) { var position = completionContext.Position; var document = completionContext.Document; var syntaxTree = ctx.SyntaxTree; if (syntaxTree.IsInNonUserCode(position, cancellationToken) || syntaxTree.IsPreProcessorDirectiveContext(position, cancellationToken)) return Task.FromResult (Enumerable.Empty<CompletionData> ()); if (!syntaxTree.IsRightOfDotOrArrowOrColonColon(position, cancellationToken)) return Task.FromResult (Enumerable.Empty<CompletionData> ()); var ma = ctx.LeftToken.Parent as MemberAccessExpressionSyntax; if (ma == null) return Task.FromResult (Enumerable.Empty<CompletionData> ()); var model = ctx.CSharpSyntaxContext.SemanticModel; var symbolInfo = model.GetSymbolInfo (ma.Expression); if (symbolInfo.Symbol == null || symbolInfo.Symbol.Kind != SymbolKind.Parameter) return Task.FromResult (Enumerable.Empty<CompletionData> ()); var list = new List<CompletionData> (); var within = model.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); var addedSymbols = new HashSet<string> (); foreach (var ano in ma.AncestorsAndSelf ().OfType<AnonymousMethodExpressionSyntax> ()) { Analyze (engine, model, ma.Expression, within, list, ano.ParameterList, symbolInfo.Symbol, addedSymbols, cancellationToken); } foreach (var ano in ma.AncestorsAndSelf ().OfType<ParenthesizedLambdaExpressionSyntax> ()) { Analyze (engine, model, ma.Expression, within, list, ano.ParameterList, symbolInfo.Symbol, addedSymbols, cancellationToken); } return Task.FromResult ((IEnumerable<CompletionData>)list); }
protected async override Task<IEnumerable<CompletionData>> GetItemsWorkerAsync (CompletionResult completionResult, CompletionEngine engine, CompletionContext completionContext, CompletionTriggerInfo info, SyntaxContext ctx, CancellationToken cancellationToken) { var document = completionContext.Document; var position = completionContext.Position; var tree = ctx.SyntaxTree; //DeclarationModifiers modifiers; SyntaxToken token; var semanticModel = ctx.SemanticModel; var enclosingSymbol = semanticModel.GetEnclosingSymbol (position, cancellationToken) as INamedTypeSymbol; // Only inside classes and structs if (enclosingSymbol == null || !(enclosingSymbol.TypeKind == TypeKind.Struct || enclosingSymbol.TypeKind == TypeKind.Class)) { return Enumerable.Empty<CompletionData> (); } if (!IsPartialCompletionContext (tree, position, cancellationToken/*, out modifiers*/, out token)) { if (enclosingSymbol != null && (token.IsKind (SyntaxKind.OpenBraceToken) || token.IsKind (SyntaxKind.CloseBraceToken) || token.IsKind (SyntaxKind.SemicolonToken))) { return CreateCompletionData (engine, semanticModel, position, enclosingSymbol, token, false, cancellationToken); } return Enumerable.Empty<CompletionData> (); } return CreateCompletionData (engine, semanticModel, position, enclosingSymbol, token, true, cancellationToken); }
protected override Task<IEnumerable<CompletionData>> GetItemsWorkerAsync (CompletionResult result, CompletionEngine engine, CompletionContext completionContext, CompletionTriggerInfo info, SyntaxContext ctx, CancellationToken cancellationToken) { var document = completionContext.Document; var position = completionContext.Position; var tree = ctx.SyntaxTree; var model = ctx.SemanticModel; if (tree.IsInNonUserCode (position, cancellationToken)) return Task.FromResult (Enumerable.Empty<CompletionData> ()); if (!ctx.CSharpSyntaxContext.IsAnyExpressionContext) return Task.FromResult (Enumerable.Empty<CompletionData> ()); var enclosingType = model.GetEnclosingNamedType (position, cancellationToken); var memberMethods = enclosingType.GetMembers ().OfType<IMethodSymbol> ().Where (m => m.MethodKind == MethodKind.Ordinary).ToArray (); var list = new List<CompletionData> (); foreach (var type in ctx.InferredTypes) { if (type.TypeKind != TypeKind.Delegate) continue; AddCompatibleMethods (engine, list, type, memberMethods, cancellationToken); string delegateName = null; if (ctx.TargetToken.IsKind (SyntaxKind.PlusEqualsToken)) { delegateName = GuessEventHandlerBaseName (ctx.LeftToken.Parent, ctx.ContainingTypeDeclaration); } AddDelegateHandlers (list, ctx.TargetToken.Parent, model, engine, result, type, position, delegateName, cancellationToken); } if (list.Count > 0) { result.AutoSelect = false; } return Task.FromResult ((IEnumerable<CompletionData>)list); }
protected async override Task<IEnumerable<CompletionData>> GetItemsWorkerAsync (CompletionResult completionResult, CompletionEngine engine, CompletionContext completionContext, CompletionTriggerInfo info, SyntaxContext ctx, CancellationToken cancellationToken) { var position = completionContext.Position; var document = completionContext.Document; var span = new TextSpan(position, 0); var semanticModel = await document.GetCSharpSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false); var syntaxTree = semanticModel.SyntaxTree; // var ctx = await completionContext.GetSyntaxContextAsync (engine.Workspace, cancellationToken).ConfigureAwait (false); if (syntaxTree.IsInNonUserCode(position, cancellationToken) || syntaxTree.IsPreProcessorDirectiveContext(position, cancellationToken)) { return Enumerable.Empty<CompletionData> (); } if (!syntaxTree.IsRightOfDotOrArrowOrColonColon(position, cancellationToken)) { return Enumerable.Empty<CompletionData> (); } var node = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken) .GetPreviousTokenIfTouchingWord(position) .Parent; if (node.Kind() == SyntaxKind.ExplicitInterfaceSpecifier) { return await GetCompletionsOffOfExplicitInterfaceAsync( engine, document, semanticModel, position, ((ExplicitInterfaceSpecifierSyntax)node).Name, cancellationToken).ConfigureAwait(false); } return Enumerable.Empty<CompletionData> (); }
/// <summary> /// Creates a new object storing the given callback and state. /// </summary> public BusAsyncResult(AsyncCallback callback, object state) { this.callback = callback; result = new CompletionResult(); result.State = state; sync = new ManualResetEvent(false); }
protected async override Task<IEnumerable<CompletionData>> GetItemsWorkerAsync (CompletionResult completionResult, CompletionEngine engine, CompletionContext completionContext, CompletionTriggerInfo info, SyntaxContext ctx, CancellationToken cancellationToken) { var document = completionContext.Document; var position = completionContext.Position; var semanticModel = ctx.SemanticModel; if (ctx.TargetToken.Parent != null && ctx.TargetToken.Parent.Parent != null && ctx.TargetToken.Parent.Parent.IsKind(SyntaxKind.Argument)) { SourceText text; if (!completionContext.Document.TryGetText (out text)) { text = await completionContext.Document.GetTextAsync (); } var currentChar = text [completionContext.Position - 1]; if (ctx.TargetToken.Parent == null || !ctx.TargetToken.Parent.IsKind(SyntaxKind.StringLiteralExpression) || ctx.TargetToken.Parent.Parent == null || !ctx.TargetToken.Parent.Parent.IsKind(SyntaxKind.Argument) || ctx.TargetToken.Parent.Parent.Parent == null || !ctx.TargetToken.Parent.Parent.Parent.IsKind(SyntaxKind.ArgumentList) || ctx.TargetToken.Parent.Parent.Parent.Parent == null || !ctx.TargetToken.Parent.Parent.Parent.Parent.IsKind(SyntaxKind.InvocationExpression)) { return Enumerable.Empty<CompletionData> (); } var formatArgument = GetFormatItemNumber(document, position); var invocationExpression = ctx.TargetToken.Parent.Parent.Parent.Parent as InvocationExpressionSyntax; return GetFormatCompletionData(engine, semanticModel, invocationExpression, formatArgument, currentChar); } return Enumerable.Empty<CompletionData> (); }
protected async override Task<IEnumerable<CompletionData>> GetItemsWorkerAsync (CompletionResult completionResult, CompletionEngine engine, CompletionContext completionContext, CompletionTriggerInfo info, SyntaxContext ctx, CancellationToken cancellationToken) { var model = ctx.SemanticModel; var tree = ctx.SyntaxTree; if (tree.IsInNonUserCode (completionContext.Position, cancellationToken)) return Enumerable.Empty<CompletionData> (); var token = tree.FindTokenOnLeftOfPosition (completionContext.Position, cancellationToken); if (token.IsMandatoryNamedParameterPosition ()) return Enumerable.Empty<CompletionData> (); var result = new List<CompletionData> (); // check if it's the first parameter and set autoselect == false if a parameterless version exists. if (token.IsKind (SyntaxKind.OpenParenToken)) { var parent = token.Parent?.Parent; if (parent == null) return Enumerable.Empty<CompletionData> (); var symbolInfo = model.GetSymbolInfo (parent); foreach (var symbol in new [] { symbolInfo.Symbol }.Concat (symbolInfo.CandidateSymbols)) { if (symbol != null && symbol.IsKind (SymbolKind.Method)) { if (symbol.GetParameters ().Length == 0) { completionResult.AutoSelect = false; break; } } } } foreach (var _type in ctx.InferredTypes) { var type = _type; if (type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T) { type = type.GetTypeArguments ().FirstOrDefault (); if (type == null) continue; } if (type.TypeKind != TypeKind.Enum) continue; if (!type.IsEditorBrowsable ()) continue; // Does type have any aliases? ISymbol alias = await type.FindApplicableAlias (completionContext.Position, model, cancellationToken).ConfigureAwait (false); var displayString = RoslynCompletionData.SafeMinimalDisplayString (type, model, completionContext.Position, SymbolDisplayFormat.CSharpErrorMessageFormat); if (string.IsNullOrEmpty (completionResult.DefaultCompletionString)) { completionResult.DefaultCompletionString = displayString; completionResult.AutoCompleteEmptyMatch = true; } if (!IsReachable (model, type, token.Parent)) result.Add (engine.Factory.CreateSymbolCompletionData (this, type, displayString)); foreach (IFieldSymbol field in type.GetMembers ().OfType<IFieldSymbol> ()) { if (field.DeclaredAccessibility == Accessibility.Public && (field.IsConst || field.IsStatic)) { result.Add (engine.Factory.CreateEnumMemberCompletionData (this, alias, field)); } } } return result; }
public OperationalSpeedCommand GetSpeedCommand() { OperationalVehicleState vs = Services.StateProvider.GetVehicleState(); OperationalSpeedCommand cmd = new OperationalSpeedCommand(); cmd.brakePressure = TahoeParams.brake_hold; cmd.engineTorque = 0; if (result != CompletionResult.Failed) { if (phase == Phase.Braking) { // chek if we can transition to shifting if (Math.Abs(vs.speed) < 0.05 && vs.brakePressure >= TahoeParams.brake_hold-1) { phase = Phase.Shifting; } } if (phase == Phase.Shifting) { cmd.transGear = gear; if (vs.transGear == gear) { result = CompletionResult.Completed; } } } return cmd; }
protected async override Task<IEnumerable<CompletionData>> GetItemsWorkerAsync (CompletionResult completionResult, CompletionEngine engine, CompletionContext completionContext, CompletionTriggerInfo info, SyntaxContext ctx, CancellationToken cancellationToken) { var document = completionContext.Document; var position = completionContext.Position; var tree = ctx.SyntaxTree; if (tree.IsInNonUserCode(position, cancellationToken)) return Enumerable.Empty<CompletionData> (); var targetToken = tree.FindTokenOnLeftOfPosition(position, cancellationToken).GetPreviousTokenIfTouchingWord(position); if (targetToken.IsKind(SyntaxKind.AliasKeyword) && targetToken.Parent.IsKind(SyntaxKind.ExternAliasDirective)) { var compilation = await document.GetCSharpCompilationAsync(cancellationToken).ConfigureAwait(false); var aliases = compilation.ExternalReferences.Where(r => r.Properties.Aliases != null).SelectMany(r => r.Properties.Aliases).ToSet(); if (aliases.Any()) { var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); var usedAliases = root.ChildNodes().OfType<ExternAliasDirectiveSyntax>().Where(e => !e.Identifier.IsMissing).Select(e => e.Identifier.ValueText); foreach (var used in usedAliases) { aliases.Remove (used); } aliases.Remove(MetadataReferenceProperties.GlobalAlias); return aliases.Select (e => engine.Factory.CreateGenericData (this, e, GenericDataType.Undefined)); } } return Enumerable.Empty<CompletionData> (); }
public TrackingData(double? engineTorque, double? brakePressure, TransmissionGear? gear, double? steeringAngle, CompletionResult result) { this.engineTorque = engineTorque; this.brakePressure = brakePressure; this.gear = gear; this.steeringAngle = steeringAngle; this.result = result; }
public TrajectoryBlockedReport(CompletionResult result, double distToBlockage, BlockageType blockageType, int trackID, bool reverseRecommended, Type behaviorType, string behaviorId) : base(behaviorType, behaviorId) { this.result = result; this.distToBlockage = distToBlockage; this.blockageType = blockageType; this.trackID = trackID; this.reverseRecommended = reverseRecommended; this.saudiLevel = SAUDILevel.None; }
protected async override Task<IEnumerable<CompletionData>> GetItemsWorkerAsync (CompletionResult completionResult, CompletionEngine engine, CompletionContext completionContext, CompletionTriggerInfo info, SyntaxContext ctx, CancellationToken cancellationToken) { var document = completionContext.Document; var position = completionContext.Position; return await document.GetUnionResultsFromDocumentAndLinks( UnionCompletionItemComparer.Instance, async (doc, ct) => await GetSpeculativeTCompletions(engine, doc, position, ct).ConfigureAwait(false), cancellationToken).ConfigureAwait(false); }
public TrajectoryBlockedReport(Type behaviorType) : base(behaviorType) { this.badStuffFlag = true; this.trackID = -1; this.blockageType = BlockageType.Static; this.reverseRecommended = true; this.distToBlockage = double.NaN; this.saudiLevel = SAUDILevel.L1; this.result = CompletionResult.Stopped; }
protected async override Task<IEnumerable<CompletionData>> GetItemsWorkerAsync (CompletionResult completionResult, CompletionEngine engine, CompletionContext completionContext, CompletionTriggerInfo info, SyntaxContext ctx, CancellationToken cancellationToken) { var document = completionContext.Document; var position = completionContext.Position; var syntaxTree = await document.GetCSharpSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (syntaxTree.IsInNonUserCode(position, cancellationToken) || syntaxTree.IsRightOfDotOrArrowOrColonColon(position, cancellationToken) || syntaxTree.GetContainingTypeOrEnumDeclaration(position, cancellationToken) is EnumDeclarationSyntax) { return Enumerable.Empty<CompletionData>(); } // var span = new TextSpan(position, 0); // var semanticModel = await document.GetCSharpSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false); if (syntaxTree.IsPreProcessorDirectiveContext(position, cancellationToken)) { var directive = syntaxTree.GetRoot(cancellationToken).FindTokenOnLeftOfPosition(position, includeDirectives: true).GetAncestor<DirectiveTriviaSyntax>(); if (directive.DirectiveNameToken.IsKind( SyntaxKind.IfKeyword, SyntaxKind.RegionKeyword, SyntaxKind.ElseKeyword, SyntaxKind.ElifKeyword, SyntaxKind.ErrorKeyword, SyntaxKind.LineKeyword, SyntaxKind.PragmaKeyword, SyntaxKind.EndIfKeyword, SyntaxKind.UndefKeyword, SyntaxKind.EndRegionKeyword, SyntaxKind.WarningKeyword)) { return Enumerable.Empty<CompletionData>(); } return await GetSnippetCompletionItemsAsync(cancellationToken).ConfigureAwait(false); } var tokenLeftOfPosition = syntaxTree.FindTokenOnLeftOfPosition (position, cancellationToken); if (syntaxTree.IsGlobalStatementContext(position, cancellationToken) || syntaxTree.IsExpressionContext(position, tokenLeftOfPosition, true, cancellationToken) || syntaxTree.IsStatementContext(position, tokenLeftOfPosition, cancellationToken) || syntaxTree.IsTypeContext(position, cancellationToken) || syntaxTree.IsTypeDeclarationContext(position, tokenLeftOfPosition, cancellationToken) || syntaxTree.IsNamespaceContext(position, cancellationToken) || syntaxTree.IsMemberDeclarationContext(position, tokenLeftOfPosition, cancellationToken) || syntaxTree.IsLabelContext(position, cancellationToken)) { return await GetSnippetCompletionItemsAsync(cancellationToken).ConfigureAwait(false); } return Enumerable.Empty<CompletionData>(); }
protected async override Task<IEnumerable<CompletionData>> GetItemsWorkerAsync (CompletionResult completionResult, CompletionEngine engine, CompletionContext completionContext, CompletionTriggerInfo info, SyntaxContext ctx, CancellationToken cancellationToken) { var model = ctx.SemanticModel; var result = new List<CompletionData> (); if (ctx.IsPreProcessorExpressionContext) { var parseOptions = model.SyntaxTree.Options as CSharpParseOptions; foreach (var define in parseOptions.PreprocessorSymbolNames) { result.Add(engine.Factory.CreateGenericData (this, define, GenericDataType.PreprocessorSymbol)); } } return result; }
protected async override Task<IEnumerable<CompletionData>> GetItemsWorkerAsync (CompletionResult completionResult, CompletionEngine engine, CompletionContext completionContext, CompletionTriggerInfo info, SyntaxContext ctx, CancellationToken cancellationToken) { // var ctx = await completionContext.GetSyntaxContextAsync (engine.Workspace, cancellationToken).ConfigureAwait (false); var document = completionContext.Document; var semanticModel = ctx.SemanticModel; var tree = ctx.SyntaxTree; if (tree.IsInNonUserCode(completionContext.Position, cancellationToken)) return Enumerable.Empty<CompletionData> (); var text = await document.GetTextAsync (cancellationToken).ConfigureAwait (false); var startLineNumber = text.Lines.IndexOf (completionContext.Position); // modifiers* override modifiers* type? | Accessibility seenAccessibility; //DeclarationModifiers modifiers; var token = tree.FindTokenOnLeftOfPosition(completionContext.Position, cancellationToken); if (token.Parent == null) return Enumerable.Empty<CompletionData> (); var parentMember = token.Parent.AncestorsAndSelf ().OfType<MemberDeclarationSyntax> ().FirstOrDefault (m => !m.IsKind (SyntaxKind.IncompleteMember)); if (!(parentMember is BaseTypeDeclarationSyntax) && /* May happen in case: * * override $ * public override string Foo () {} */ !(token.IsKind (SyntaxKind.OverrideKeyword) && token.Span.Start <= parentMember.Span.Start)) return Enumerable.Empty<CompletionData> (); var position = completionContext.Position; var startToken = token.GetPreviousTokenIfTouchingWord(position); ITypeSymbol returnType; SyntaxToken tokenBeforeReturnType; TryDetermineReturnType (startToken, semanticModel, cancellationToken, out returnType, out tokenBeforeReturnType); if (returnType == null) { var enclosingType = semanticModel.GetEnclosingSymbol (position, cancellationToken) as INamedTypeSymbol; if (enclosingType != null && (startToken.IsKind (SyntaxKind.OpenBraceToken) || startToken.IsKind (SyntaxKind.CloseBraceToken) || startToken.IsKind (SyntaxKind.SemicolonToken))) { return CreateCompletionData (engine, semanticModel, position, returnType, Accessibility.NotApplicable, startToken, tokenBeforeReturnType, false, cancellationToken); } } if (!TryDetermineModifiers(ref tokenBeforeReturnType, text, startLineNumber, out seenAccessibility/*, out modifiers*/) || !TryCheckForTrailingTokens (tree, text, startLineNumber, position, cancellationToken)) { return Enumerable.Empty<CompletionData> (); } return CreateCompletionData (engine, semanticModel, position, returnType, seenAccessibility, startToken, tokenBeforeReturnType, true, cancellationToken); }
protected async override Task<IEnumerable<CompletionData>> GetItemsWorkerAsync (CompletionResult completionResult, CompletionEngine engine, CompletionContext completionContext, CompletionTriggerInfo info, SyntaxContext ctx, CancellationToken cancellationToken) { var document = completionContext.Document; var position = completionContext.Position; var syntaxTree = ctx.SyntaxTree; if (syntaxTree.IsInNonUserCode(position, cancellationToken)) { return null; } var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); if (token.Kind() != SyntaxKind.OpenParenToken && token.Kind() != SyntaxKind.CommaToken) { return null; } var attributeArgumentList = token.Parent as AttributeArgumentListSyntax; var attributeSyntax = token.Parent.Parent as AttributeSyntax; if (attributeSyntax == null || attributeArgumentList == null) { return null; } // We actually want to collect two sets of named parameters to present the user. The // normal named parameters that come from the attribute constructors. These will be // presented like "foo:". And also the named parameters that come from the writable // fields/properties in the attribute. These will be presented like "bar =". var existingNamedParameters = GetExistingNamedParameters(attributeArgumentList, position); var workspace = document.Project.Solution.Workspace; var semanticModel = await document.GetCSharpSemanticModelForNodeAsync(attributeSyntax, cancellationToken).ConfigureAwait(false); var nameColonItems = await GetNameColonItemsAsync(engine, workspace, semanticModel, position, token, attributeSyntax, existingNamedParameters, cancellationToken).ConfigureAwait(false); var nameEqualsItems = await GetNameEqualsItemsAsync(engine, workspace, semanticModel, position, token, attributeSyntax, existingNamedParameters, cancellationToken).ConfigureAwait(false); // If we're after a name= parameter, then we only want to show name= parameters. if (IsAfterNameEqualsArgument(token)) { return nameEqualsItems; } return nameColonItems.Concat(nameEqualsItems); }
protected override Task<IEnumerable<CompletionData>> GetItemsWorkerAsync (CompletionResult completionResult, CompletionEngine engine, CompletionContext completionContext, CompletionTriggerInfo info, SyntaxContext ctx, CancellationToken cancellationToken) { var document = completionContext.Document; var position = completionContext.Position; var semanticModel = ctx.SemanticModel; if (info.TriggerCharacter == '\\') { if (ctx.TargetToken.Parent != null && ctx.TargetToken.Parent.Parent != null && ctx.TargetToken.Parent.Parent.IsKind (SyntaxKind.Argument)) { var argument = ctx.TargetToken.Parent.Parent as ArgumentSyntax; var symbolInfo = semanticModel.GetSymbolInfo (ctx.TargetToken.Parent.Parent.Parent.Parent); if (symbolInfo.Symbol == null) return TaskUtil.EmptyEnumerable<CompletionData> (); if (SemanticHighlightingVisitor<int>.IsRegexMatchMethod (symbolInfo)) { if (((ArgumentListSyntax)argument.Parent).Arguments [1] != argument) return TaskUtil.EmptyEnumerable<CompletionData> (); completionResult.AutoSelect = false; return Task.FromResult (GetFormatCompletionData (engine, argument.Expression.ToString () [0] == '@')); } if (SemanticHighlightingVisitor<int>.IsRegexConstructor (symbolInfo)) { if (((ArgumentListSyntax)argument.Parent).Arguments [0] != argument) return TaskUtil.EmptyEnumerable<CompletionData> (); completionResult.AutoSelect = false; return Task.FromResult (GetFormatCompletionData (engine, argument.Expression.ToString () [0] == '@')); } } } else { var ma = ctx.TargetToken.Parent as MemberAccessExpressionSyntax; if (ma != null) { var symbolInfo = semanticModel.GetSymbolInfo (ma.Expression); var typeInfo = semanticModel.GetTypeInfo (ma.Expression); var type = typeInfo.Type; if (type != null && type.Name == "Match" && type.ContainingNamespace.GetFullName () == "System.Text.RegularExpressions" ) { var items = new List<CompletionData>(); foreach (var grp in GetGroups (ctx, symbolInfo.Symbol)) { items.Add (engine.Factory.CreateGenericData (this, "Groups[\"" + grp + "\"]", GenericDataType.Undefined)); } return Task.FromResult ((IEnumerable<CompletionData>)items); } } } return TaskUtil.EmptyEnumerable<CompletionData> (); }
public TrackingManager(ICommandTransport commandTransport, bool testMode) { // check that the command transport is legit if (commandTransport == null) { throw new ArgumentNullException("commandTransport"); } this.testMode = testMode; // create the command queue deltaSteeringQueue = new TimeWindowQueue<double>(3); // store the command transport this.commandTransport = commandTransport; // set up a null tracking command initially currentCommand = new NullTrackingCommand(); // mark the current completion result as "working" currentResult = CompletionResult.Working; if (!testMode) { AsyncFlowControl? flowControl = null; if (!ExecutionContext.IsFlowSuppressed()) { flowControl = ExecutionContext.SuppressFlow(); } // set up the thread trackingThread = new Thread(TrackingProc); // set it as a background thread trackingThread.IsBackground = true; // set it as higher priority trackingThread.Priority = ThreadPriority.AboveNormal; // give it a useful name trackingThread.Name = "Tracking Thread"; // start her up trackingThread.Start(); if (flowControl != null) { flowControl.Value.Undo(); } } }
protected async override Task<IEnumerable<CompletionData>> GetItemsWorkerAsync (CompletionResult result, CompletionEngine engine, CompletionContext completionContext, CompletionTriggerInfo info, SyntaxContext ctx, CancellationToken cancellationToken) { var list = new List<CompletionData> (); var newExpression = GetObjectCreationNewExpression (ctx.SyntaxTree, completionContext.Position, cancellationToken); if (newExpression == null) { if (ctx.SyntaxTree.IsInNonUserCode(completionContext.Position, cancellationToken) || ctx.SyntaxTree.IsPreProcessorDirectiveContext(completionContext.Position, cancellationToken)) return Enumerable.Empty<CompletionData> (); // if (!nkr.IsValid (completionContext.Position, ctx.CSharpSyntaxContext, cancellationToken)) // return Enumerable.Empty<ICompletionData> (); var tokenOnLeftOfPosition = ctx.SyntaxTree.FindTokenOnLeftOfPosition (completionContext.Position, cancellationToken); if (!tokenOnLeftOfPosition.IsKind (SyntaxKind.EqualsToken) && !tokenOnLeftOfPosition.Parent.IsKind (SyntaxKind.EqualsValueClause)) return Enumerable.Empty<CompletionData> (); foreach (var inferredType in SyntaxContext.InferenceService.InferTypes (ctx.CSharpSyntaxContext.SemanticModel, completionContext.Position, cancellationToken)) { if (inferredType.IsEnumType () || inferredType.IsInterfaceType () || inferredType.IsAbstract) continue; foreach (var symbol in await GetPreselectedSymbolsWorker(ctx.CSharpSyntaxContext, inferredType, completionContext.Position - 1, cancellationToken)) { var symbolCompletionData = engine.Factory.CreateObjectCreation (this, inferredType, symbol, completionContext.Position, false); list.Add (symbolCompletionData); } } return list; } var type = SyntaxContext.InferenceService.InferType (ctx.CSharpSyntaxContext.SemanticModel, newExpression, objectAsDefault: false, cancellationToken: cancellationToken); foreach (var symbol in await GetPreselectedSymbolsWorker(ctx.CSharpSyntaxContext, type, completionContext.Position, cancellationToken)) { var symbolCompletionData = engine.Factory.CreateObjectCreation (this, type, symbol, newExpression.SpanStart, true); list.Add (symbolCompletionData); if (string.IsNullOrEmpty (result.DefaultCompletionString)) result.DefaultCompletionString = symbolCompletionData.DisplayText; } foreach (var keyword in primitiveTypesKeywords) { list.Add (engine.Factory.CreateGenericData (this, keyword, GenericDataType.Keyword)); } return list; }
protected async override Task<IEnumerable<CompletionData>> GetItemsWorkerAsync (CompletionResult completionResult, CompletionEngine engine, CompletionContext completionContext, CompletionTriggerInfo info, SyntaxContext ctx, CancellationToken cancellationToken) { var position = completionContext.Position; var document = completionContext.Document; var syntaxTree = ctx.SyntaxTree; if (syntaxTree.IsInNonUserCode(position, cancellationToken) || syntaxTree.IsPreProcessorDirectiveContext(position, cancellationToken)) return Enumerable.Empty<CompletionData> (); if (!syntaxTree.IsRightOfDotOrArrowOrColonColon(position, cancellationToken)) return Enumerable.Empty<CompletionData> (); var ma = ctx.LeftToken.Parent as MemberAccessExpressionSyntax; if (ma == null) return Enumerable.Empty<CompletionData> (); var model = ctx.CSharpSyntaxContext.SemanticModel; var symbolInfo = model.GetSymbolInfo (ma.Expression); if (symbolInfo.Symbol == null) return Enumerable.Empty<CompletionData> (); var list = new List<CompletionData> (); var within = model.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); var addedSymbols = new HashSet<string> (); foreach (var ifStmSyntax in ma.Expression.AncestorsAndSelf ().OfType<IfStatementSyntax> ()) { var condition = ifStmSyntax.Condition.SkipParens (); if (condition == null || !condition.IsKind (SyntaxKind.IsExpression)) continue; var isExpr = ((BinaryExpressionSyntax)condition); var leftSymbol = model.GetSymbolInfo (isExpr.Left); if (leftSymbol.Symbol == symbolInfo.Symbol) { var type = model.GetTypeInfo (isExpr.Right).Type; if (type != null) { Analyze (engine, ma.Expression, type, within, list, addedSymbols, cancellationToken); } } } return list; }
protected async override Task<IEnumerable<CompletionData>> GetItemsWorkerAsync (CompletionResult completionResult, CompletionEngine engine, CompletionContext completionContext, CompletionTriggerInfo info, SyntaxContext ctx, CancellationToken cancellationToken) { var model = ctx.SemanticModel; var tree = ctx.SyntaxTree; if (tree.IsInNonUserCode(completionContext.Position, cancellationToken)) return Enumerable.Empty<CompletionData> (); var token = tree.FindTokenOnLeftOfPosition(completionContext.Position, cancellationToken); if (token.IsMandatoryNamedParameterPosition()) return Enumerable.Empty<CompletionData> (); var result = new List<CompletionData> (); foreach (var _type in ctx.InferredTypes) { var type = _type; if (type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T) { type = type.GetTypeArguments().FirstOrDefault(); if (type == null) continue; } if (type.TypeKind != TypeKind.Enum) continue; if (!type.IsEditorBrowsable ()) continue; // Does type have any aliases? ISymbol alias = await type.FindApplicableAlias(completionContext.Position, model, cancellationToken).ConfigureAwait(false); if (string.IsNullOrEmpty(completionResult.DefaultCompletionString)) completionResult.DefaultCompletionString = type.Name; result.Add (engine.Factory.CreateSymbolCompletionData(this, type, RoslynCompletionData.SafeMinimalDisplayString (type, model, completionContext.Position, SymbolDisplayFormat.CSharpErrorMessageFormat))); foreach (IFieldSymbol field in type.GetMembers().OfType<IFieldSymbol>()) { if (field.DeclaredAccessibility == Accessibility.Public && (field.IsConst || field.IsStatic)) { result.Add (engine.Factory.CreateEnumMemberCompletionData(this, alias, field)); } } } return result; }
public void AddImportCompletionData (CompletionResult result, Document document, SemanticModel semanticModel, int position, CancellationToken cancellationToken = default(CancellationToken)) { var ns = new Stack<INamespaceOrTypeSymbol>(); ns.Push(semanticModel.Compilation.GlobalNamespace); semanticModel.LookupNamespacesAndTypes(position); }
protected override Task<IEnumerable<CompletionData>> GetItemsWorkerAsync (CompletionResult completionResult, CompletionEngine engine, CompletionContext completionContext, CompletionTriggerInfo info, SyntaxContext ctx, CancellationToken cancellationToken) { var semanticModel = ctx.SemanticModel; var result = new List<CompletionData> (); if (info.TriggerCharacter == ' ') { var newExpression = ObjectCreationContextHandler.GetObjectCreationNewExpression (ctx.SyntaxTree, completionContext.Position, cancellationToken); if (newExpression == null && info.CompletionTriggerReason == CompletionTriggerReason.CharTyped && !ctx.LeftToken.IsKind (SyntaxKind.EqualsToken) && !ctx.LeftToken.IsKind (SyntaxKind.EqualsEqualsToken)) return Task.FromResult (Enumerable.Empty<CompletionData> ()); completionResult.AutoCompleteEmptyMatch = false; } var parent = ctx.TargetToken.Parent; bool isInAttribute = ctx.CSharpSyntaxContext.IsAttributeNameContext; bool isInBaseList = parent != null && parent.IsKind (SyntaxKind.BaseList); bool isInUsingDirective = parent != null && parent.Parent != null && parent.Parent.IsKind (SyntaxKind.UsingDirective) && !parent.IsKind (SyntaxKind.QualifiedName); var isInQuery = ctx.CSharpSyntaxContext.IsInQuery; var completionDataLookup = new Dictionary<Tuple<string, SymbolKind>, ISymbolCompletionData> (); bool isInCatchTypeExpression = parent != null && parent.IsKind (SyntaxKind.CatchDeclaration) || parent.IsKind (SyntaxKind.QualifiedName) && parent.Parent != null && parent.Parent.IsKind (SyntaxKind.CatchDeclaration); Action<ISymbolCompletionData> addData = d => { var key = Tuple.Create (d.DisplayText, d.Symbol.Kind); ISymbolCompletionData data; if (completionDataLookup.TryGetValue (key, out data)) { data.AddOverload (d); return; } completionDataLookup.Add (key, d); result.Add (d); }; var completionCategoryLookup = new Dictionary<string, CompletionCategory> (); foreach (var symbol in Recommender.GetRecommendedSymbolsAtPosition (semanticModel, completionContext.Position, engine.Workspace, null, cancellationToken)) { if (symbol.Kind == SymbolKind.NamedType) { if (isInAttribute) { var type = (ITypeSymbol)symbol; if (type.IsAttribute ()) { var v = type.Name.Substring (0, type.Name.Length - "Attribute".Length); var needsEscaping = SyntaxFacts.GetKeywordKind(v) != SyntaxKind.None; needsEscaping = needsEscaping || (isInQuery && SyntaxFacts.IsQueryContextualKeyword(SyntaxFacts.GetContextualKeywordKind(v))); if (!needsEscaping) { addData (engine.Factory.CreateSymbolCompletionData (this, symbol, v)); continue; } } } if (isInBaseList) { var type = (ITypeSymbol)symbol; if (type.IsSealed || type.IsStatic) continue; } if (isInCatchTypeExpression) { var type = (ITypeSymbol)symbol; if (!IsException (type)) continue; } } if (isInUsingDirective && symbol.Kind != SymbolKind.Namespace) continue; var newData = engine.Factory.CreateSymbolCompletionData (this, symbol, symbol.Name.EscapeIdentifier (isInQuery)); ISymbol categorySymbol; var method = symbol as IMethodSymbol; if (method != null) { if (method.IsReducedExtension ()) { categorySymbol = method.ReceiverType; } else { categorySymbol = (ISymbol)symbol.ContainingType; } } else { categorySymbol = (ISymbol)symbol.ContainingType ?? symbol.ContainingNamespace; } if (categorySymbol != null) { CompletionCategory category; var key = categorySymbol.ToDisplayString (); if (!completionCategoryLookup.TryGetValue (key, out category)) { completionCategoryLookup [key] = category = engine.Factory.CreateCompletionDataCategory (categorySymbol); } newData.CompletionCategory = category; } addData (newData); } return Task.FromResult ((IEnumerable<CompletionData>)result); }
protected async override Task<IEnumerable<CompletionData>> GetItemsWorkerAsync (CompletionResult completionResult, CompletionEngine engine, CompletionContext completionContext, CompletionTriggerInfo info, SyntaxContext ctx, CancellationToken cancellationToken) { var document = completionContext.Document; var position = completionContext.Position; var workspace = document.Project.Solution.Workspace; var semanticModel = await document.GetSemanticModelForSpanAsync (new TextSpan (position, 0), cancellationToken).ConfigureAwait (false); var typeAndLocation = GetInitializedType (document, semanticModel, position, cancellationToken); if (typeAndLocation == null) return Enumerable.Empty<CompletionData> (); var initializedType = typeAndLocation.Item1 as INamedTypeSymbol; var initializerLocation = typeAndLocation.Item2; if (initializedType == null) return Enumerable.Empty<CompletionData> (); // Find the members that can be initialized. If we have a NamedTypeSymbol, also get the overridden members. IEnumerable<ISymbol> members = semanticModel.LookupSymbols (position, initializedType); members = members.Where (m => IsInitializable (m, initializedType) && m.CanBeReferencedByName && IsLegalFieldOrProperty (m) && !m.IsImplicitlyDeclared); // Filter out those members that have already been typed var alreadyTypedMembers = GetInitializedMembers (semanticModel.SyntaxTree, position, cancellationToken); var uninitializedMembers = members.Where (m => !alreadyTypedMembers.Contains (m.Name)); uninitializedMembers = uninitializedMembers.Where (m => m.IsEditorBrowsable ()); // var text = await semanticModel.SyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false); // var changes = GetTextChangeSpan(text, position); var list = new List<CompletionData> (); // Return the members foreach (var member in uninitializedMembers) { list.Add (engine.Factory.CreateSymbolCompletionData (this, member)); } return list; }
public async Task<CompletionResult> GetCompletionDataAsync(CompletionContext completionContext, CompletionTriggerInfo info, CancellationToken cancellationToken = default(CancellationToken)) { if (completionContext == null) throw new ArgumentNullException ("completionContext"); var document = completionContext.Document; var semanticModel = await completionContext.GetSemanticModelAsync (cancellationToken).ConfigureAwait(false); var position = completionContext.Position; var text = await document.GetTextAsync (cancellationToken).ConfigureAwait (false); var ctx = await completionContext.GetSyntaxContextAsync (workspace, cancellationToken); ctx.SemanticModel = semanticModel; // case lambda parameter (n1, $ if (ctx.TargetToken.IsKind (SyntaxKind.CommaToken) && ctx.TargetToken.Parent != null && ctx.TargetToken.Parent.Parent != null && ctx.TargetToken.Parent.Parent.IsKind(SyntaxKind.ParenthesizedLambdaExpression)) return CompletionResult.Empty; var result = new CompletionResult { SyntaxContext = ctx }; if (position > 0) { var nonExclusiveHandlers = new List<CompletionContextHandler> (); var exclusiveHandlers = new List<CompletionContextHandler> (); var toRetriggerHandlers = new List<CompletionContextHandler> (); IEnumerable<CompletionContextHandler> handlerList; if (completionContext.UseDefaultContextHandlers) { handlerList = handlers.Concat (completionContext.AdditionalContextHandlers); } else { handlerList = completionContext.AdditionalContextHandlers; } foreach (var handler in handlerList) { if (info.CompletionTriggerReason == CompletionTriggerReason.CompletionCommand || handler.IsTriggerCharacter (text, position - 1)) { if (await handler.IsExclusiveAsync (completionContext, ctx, info, cancellationToken)) { exclusiveHandlers.Add (handler); } else { nonExclusiveHandlers.Add (handler); } } else { toRetriggerHandlers.Add (handler); } } foreach (var handler in exclusiveHandlers) { var handlerResult = handler.GetCompletionDataAsync (result, this, completionContext, info, ctx, cancellationToken).Result; //if (handlerResult != null) { // Console.WriteLine ("-----" + handler); // foreach (var item in handlerResult) { // Console.WriteLine (item.DisplayText); // } //} else { // Console.WriteLine ("-----" + handler + " == NULL"); //} if (handlerResult != null) result.AddRange (handlerResult); } if (result.Count == 0) { foreach (var handler in nonExclusiveHandlers) { var handlerResult = await handler.GetCompletionDataAsync (result, this, completionContext, info, ctx, cancellationToken); //if (handlerResult != null) { // Console.WriteLine ("-----" + handler); // foreach (var item in handlerResult) { // Console.WriteLine (item.DisplayText); // } //} else { // Console.WriteLine ("-----" + handler + " == NULL"); //} if (handlerResult != null && handlerResult.Any ()) { result.AddRange (handlerResult); } else { toRetriggerHandlers.Add (handler); } } if (result.Count > 0) { info = info.WithCompletionTriggerReason (CompletionTriggerReason.RetriggerCommand); foreach (var handler in toRetriggerHandlers) { var handlerResult = await handler.GetCompletionDataAsync (result, this, completionContext, info, ctx, cancellationToken); if (handlerResult != null) result.AddRange (handlerResult); } } } } // prevent auto selection for "<number>." case if (ctx.TargetToken.IsKind(SyntaxKind.DotToken)) { var accessExpr = ctx.TargetToken.Parent as MemberAccessExpressionSyntax; if (accessExpr != null && accessExpr.Expression != null && accessExpr.Expression.IsKind(SyntaxKind.NumericLiteralExpression)) { result.AutoSelect = false; } } if (ctx.LeftToken.Parent != null && ctx.LeftToken.Parent.Parent != null && ctx.TargetToken.Parent != null && !ctx.TargetToken.Parent.IsKind(SyntaxKind.NameEquals) && ctx.LeftToken.Parent.Parent.IsKind(SyntaxKind.AnonymousObjectMemberDeclarator)) result.AutoSelect = false; if (ctx.TargetToken.IsKind (SyntaxKind.OpenParenToken) && ctx.TargetToken.GetPreviousToken ().IsKind (SyntaxKind.OpenParenToken)) { var validTypes = TypeGuessing.GetValidTypes (semanticModel, ctx.TargetToken.Parent, cancellationToken); result.AutoSelect = !validTypes.Any (t => t.IsDelegateType ()); } foreach (var type in ctx.InferredTypes) { if (type.TypeKind == TypeKind.Delegate) { result.AutoSelect = false; break; } } return result; }
public TrackingCompletedEventArgs(CompletionResult result, object failureData, ITrackingCommand command) { this.result = result; this.failureData = failureData; this.command = command; }
private void TrackingProc() { Trace.CorrelationManager.StartLogicalOperation("tracking loop"); OperationalTrace.ThreadTraceSource = TraceSource; double? lastSteeringCommand = null; using (MMWaitableTimer timer = new MMWaitableTimer((uint)(Settings.TrackingPeriod*1000))) { // loop infinitely while (true) { if (Services.DebuggingService.StepMode) { Services.DebuggingService.WaitOnSequencer(typeof(TrackingManager)); } else { // wait for the timer timer.WaitEvent.WaitOne(); } Services.Dataset.MarkOperation("tracking rate", LocalCarTimeProvider.LocalNow); // check if there's a new command to switch in ITrackingCommand newCommand = Interlocked.Exchange(ref queuedCommand, null); if (newCommand != null) { TraceSource.TraceEvent(TraceEventType.Verbose, 0, "received new command: {0}", newCommand); // set the current result to working currentResult = CompletionResult.Working; // set the current command to the new command currentCommand = newCommand; } // check if we've completed or had a failure if (currentResult == CompletionResult.Working) { TrackingData td = new TrackingData(null, null, null, null, CompletionResult.Failed); try { // get the tracking data Trace.CorrelationManager.StartLogicalOperation("process"); td = currentCommand.Process(); } catch (Exception ex) { // log this somehow // if we get here, the completion result retains the failed label, so we won't output anything TraceSource.TraceEvent(TraceEventType.Error, 1, "exception tracking command: {0}", ex); } finally { Trace.CorrelationManager.StopLogicalOperation(); } // check if there is a failure if (td.result == CompletionResult.Failed) { td = new TrackingData(null, null, null, null, CompletionResult.Failed); } // output the command try { Trace.CorrelationManager.StartLogicalOperation("command output"); commandTransport.SetCommand(td.engineTorque, td.brakePressure, td.steeringAngle, td.gear); } catch (Exception ex) { TraceSource.TraceEvent(TraceEventType.Error, 0, "error setting command on transport: {0}", ex); } finally { Trace.CorrelationManager.StopLogicalOperation(); } // queue the command lock (deltaSteeringQueue) { if (lastSteeringCommand != null && td.steeringAngle != null) { double delta = td.steeringAngle.Value - lastSteeringCommand.Value; deltaSteeringQueue.Add(delta, LocalCarTimeProvider.LocalNow.ts); } Services.Dataset.ItemAs<double>("delta steering sigma").Add(DeltaSteeringStdDev, LocalCarTimeProvider.LocalNow); lastSteeringCommand = td.steeringAngle; } if (td.brakePressure.HasValue && td.brakePressure.Value > 90) { td.brakePressure = 90; } // output the tracking commands to the UI CarTimestamp now = Services.RelativePose.CurrentTimestamp; if (td.steeringAngle.HasValue) { Services.Dataset.ItemAs<double>("commanded steering").Add(td.steeringAngle.Value, now); } if (td.engineTorque.HasValue) { Services.Dataset.ItemAs<double>("commanded engine torque").Add(td.engineTorque.Value, now); } if (td.brakePressure.HasValue) { Services.Dataset.ItemAs<double>("commanded brake pressure").Add(td.brakePressure.Value, now); } if (td.result != CompletionResult.Working && trackingCompleted != null) { Trace.CorrelationManager.StartLogicalOperation("tracking completed"); TraceSource.TraceEvent(TraceEventType.Information, 0, "tracking completed, invoking event, result {0}", td.result); // raise the completed event asynchronously so we can go on processing try { trackingCompleted.BeginInvoke(this, new TrackingCompletedEventArgs(td.result, null, currentCommand), OnTrackingCompletedFinished, trackingCompleted); } catch (Exception ex) { TraceSource.TraceEvent(TraceEventType.Error, 0, "exception thrown in beging invoke of tracking complete event: {0}", ex); } finally { Trace.CorrelationManager.StopLogicalOperation(); } } // update the current result currentResult = td.result; } // flush the command transport every iteration commandTransport.Flush(); if (Services.DebuggingService.StepMode) { Services.DebuggingService.SetCompleted(typeof(TrackingManager)); } } } }
void AddDelegateHandlers (List<CompletionData> completionList, SyntaxNode parent, SemanticModel semanticModel, CompletionEngine engine, CompletionResult result, ITypeSymbol delegateType, int position, string optDelegateName, CancellationToken cancellationToken) { var delegateMethod = delegateType.GetDelegateInvokeMethod (); result.PossibleDelegates.Add (delegateMethod); var thisLineIndent = ""; string EolMarker = "\n"; bool addSemicolon = true; bool addDefault = true; string delegateEndString = EolMarker + thisLineIndent + "}" + (addSemicolon ? ";" : ""); //bool containsDelegateData = completionList.Result.Any(d => d.DisplayText.StartsWith("delegate(")); CompletionData item; if (addDefault) { item = engine.Factory.CreateAnonymousMethod ( this, "delegate", "Creates anonymous delegate.", "delegate {" + EolMarker + thisLineIndent, delegateEndString ); if (!completionList.Any (i => i.DisplayText == item.DisplayText)) completionList.Add (item); //if (LanguageVersion.Major >= 5) item = engine.Factory.CreateAnonymousMethod ( this, "async delegate", "Creates anonymous async delegate.", "async delegate {" + EolMarker + thisLineIndent, delegateEndString ); if (!completionList.Any (i => i.DisplayText == item.DisplayText)) completionList.Add (item); } var sb = new StringBuilder ("("); var sbWithoutTypes = new StringBuilder ("("); for (int k = 0; k < delegateMethod.Parameters.Length; k++) { if (k > 0) { sb.Append (", "); sbWithoutTypes.Append (", "); } sb.Append (RoslynCompletionData.SafeMinimalDisplayString (delegateMethod.Parameters [k], semanticModel, position, overrideNameFormat)); sbWithoutTypes.Append (delegateMethod.Parameters [k].Name); } sb.Append (")"); sbWithoutTypes.Append (")"); var signature = sb.ToString () .Replace (", params ", ", ") .Replace ("(params ", "("); if (completionList.All (data => data.DisplayText != signature)) { item = engine.Factory.CreateAnonymousMethod ( this, signature + " =>", "Creates typed lambda expression.", signature + " => ", (addSemicolon ? ";" : "") ); if (!completionList.Any (i => i.DisplayText == item.DisplayText)) completionList.Add (item); // if (LanguageVersion.Major >= 5) { item = engine.Factory.CreateAnonymousMethod ( this, "async " + signature + " =>", "Creates typed async lambda expression.", "async " + signature + " => ", (addSemicolon ? ";" : "") ); if (!completionList.Any (i => i.DisplayText == item.DisplayText)) completionList.Add (item); var signatureWithoutTypes = sbWithoutTypes.ToString (); if (!delegateMethod.Parameters.Any (p => p.RefKind != RefKind.None) && completionList.All (data => data.DisplayText != signatureWithoutTypes)) { item = engine.Factory.CreateAnonymousMethod ( this, signatureWithoutTypes + " =>", "Creates typed lambda expression.", signatureWithoutTypes + " => ", (addSemicolon ? ";" : "") ); if (!completionList.Any (i => i.DisplayText == item.DisplayText)) completionList.Add (item); //if (LanguageVersion.Major >= 5) { item = engine.Factory.CreateAnonymousMethod ( this, "async " + signatureWithoutTypes + " =>", "Creates typed async lambda expression.", "async " + signatureWithoutTypes + " => ", (addSemicolon ? ";" : "") ); if (!completionList.Any (i => i.DisplayText == item.DisplayText)) completionList.Add (item); //} } } string varName = optDelegateName ?? "Handle" + delegateType.Name; var curType = semanticModel.GetEnclosingSymbol<INamedTypeSymbol> (position, cancellationToken); var uniqueName = new UniqueNameGenerator (semanticModel).CreateUniqueMethodName (parent, varName); item = engine.Factory.CreateNewMethodDelegate (this, delegateType, uniqueName, curType); if (!completionList.Any (i => i.DisplayText == item.DisplayText)) completionList.Add (item); }
protected async override Task<IEnumerable<CompletionData>> GetItemsWorkerAsync (CompletionResult completionResult, CompletionEngine engine, CompletionContext completionContext, CompletionTriggerInfo info, SyntaxContext ctx, CancellationToken cancellationToken) { if (info.IsDebugger) { return null; } var document = completionContext.Document; var position = completionContext.Position; var tree = await document.GetCSharpSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var token = tree.FindTokenOnLeftOfPosition(position, cancellationToken); var parentTrivia = token.GetAncestor<DocumentationCommentTriviaSyntax>(); if (parentTrivia == null) { return null; } var items = new List<CompletionData>(); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var span = GetTextChangeSpan(text, position); var attachedToken = parentTrivia.ParentTrivia.Token; if (attachedToken.Kind() == SyntaxKind.None) { return null; } var semanticModel = await document.GetCSharpSemanticModelForNodeAsync(attachedToken.Parent, cancellationToken).ConfigureAwait(false); ISymbol declaredSymbol = null; var memberDeclaration = attachedToken.GetAncestor<MemberDeclarationSyntax>(); if (memberDeclaration != null) { declaredSymbol = semanticModel.GetDeclaredSymbol(memberDeclaration, cancellationToken); } else { var typeDeclaration = attachedToken.GetAncestor<TypeDeclarationSyntax>(); if (typeDeclaration != null) { declaredSymbol = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken); } } if (declaredSymbol != null) { items.AddRange(GetTagsForSymbol(engine, declaredSymbol, span, parentTrivia, token)); } if (token.Parent.Kind() == SyntaxKind.XmlEmptyElement || token.Parent.Kind() == SyntaxKind.XmlText || (token.Parent.IsKind(SyntaxKind.XmlElementEndTag) && token.IsKind(SyntaxKind.GreaterThanToken)) || (token.Parent.IsKind(SyntaxKind.XmlName) && token.Parent.IsParentKind(SyntaxKind.XmlEmptyElement))) { if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement) { items.AddRange(GetNestedTags(engine, span)); } if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement && ((XmlElementSyntax)token.Parent.Parent).StartTag.Name.LocalName.ValueText == "list") { items.AddRange(GetListItems(engine, span)); } if (token.Parent.IsParentKind(SyntaxKind.XmlEmptyElement) & token.Parent.Parent.IsParentKind(SyntaxKind.XmlElement)) { var element = (XmlElementSyntax)token.Parent.Parent.Parent; if (element.StartTag.Name.LocalName.ValueText == "list") { items.AddRange(GetListItems(engine, span)); } } if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement && ((XmlElementSyntax)token.Parent.Parent).StartTag.Name.LocalName.ValueText == "listheader") { items.AddRange(GetListHeaderItems(engine, span)); } if (token.Parent.Parent is DocumentationCommentTriviaSyntax) { items.AddRange(GetTopLevelSingleUseNames(engine, parentTrivia, span)); items.AddRange(GetTopLevelRepeatableItems(engine, span)); } } if (token.Parent.Kind() == SyntaxKind.XmlElementStartTag) { var startTag = (XmlElementStartTagSyntax)token.Parent; if (token == startTag.GreaterThanToken && startTag.Name.LocalName.ValueText == "list") { items.AddRange(GetListItems(engine, span)); } if (token == startTag.GreaterThanToken && startTag.Name.LocalName.ValueText == "listheader") { items.AddRange(GetListHeaderItems(engine, span)); } } items.AddRange(GetAlwaysVisibleItems(engine, span)); return items; }