public Level2(Quote quote, SymbolInfo info) { this.CreatingTime = quote.CreatingTime; this.Symbol = quote.Symbol; this.Bids = Level2EntriesFromQuoteEntries(quote.Bids, info.RoundLot); this.Asks = Level2EntriesFromQuoteEntries(quote.Asks, info.RoundLot); }
public override FlatOperand Resolve(ExpressionSyntax expression, ArgumentListSyntax argumentList, TypeInfo result_type, SymbolInfo si, FlatOperand into_lvalue, Function function, List<FlatStatement> instructions) { FlatOperand fop_subject; if (expression is IdentifierNameSyntax) { // typeof this fop_subject = FlatOperand.ThisRef(FlatValue.FromType(result_type.ConvertedType)); } else if (expression is MemberAccessExpressionSyntax) { MemberAccessExpressionSyntax meas = (MemberAccessExpressionSyntax)expression; fop_subject = function.ResolveExpression(meas.Expression, null, instructions); } else { throw new NotImplementedException("GetMetaTable on expression type " + expression.GetType().ToString()); } if (into_lvalue == null) { FlatOperand fop_register = function.AllocateRegister(""); into_lvalue = fop_register.GetLValue(function, instructions); } instructions.Add(FlatStatement.GETMETATABLE(into_lvalue, fop_subject)); return into_lvalue.AsRValue(FlatValue.Table()); }
private bool TryClassifySymbol( NameSyntax name, SymbolInfo symbolInfo, SemanticModel semanticModel, CancellationToken cancellationToken, out IEnumerable<ClassifiedSpan> result) { if (symbolInfo.CandidateReason == CandidateReason.Ambiguous) { return TryClassifyAmbiguousSymbol(name, symbolInfo, semanticModel, cancellationToken, out result); } // Only classify if we get one good symbol back, or if it bound to a constructor symbol with // overload resolution/accessibility errors, or bound to type/constructor and type wasn't creatable. var symbol = TryGetSymbol(name, symbolInfo, semanticModel); ClassifiedSpan classifiedSpan; if (TryClassifySymbol(name, symbol, semanticModel, cancellationToken, out classifiedSpan)) { result = SpecializedCollections.SingletonEnumerable(classifiedSpan); return true; } result = null; return false; }
static SyntaxNode ToStaticMethodInvocation(SemanticModel model, InvocationExpressionSyntax invocation, MemberAccessExpressionSyntax memberAccess, SymbolInfo invocationRR) { var newArgumentList = invocation.ArgumentList.Arguments.ToList(); newArgumentList.Insert(0, SyntaxFactory.Argument(memberAccess.Expression.WithoutLeadingTrivia())); var newTarget = memberAccess.WithExpression(SyntaxFactory.ParseTypeName(invocationRR.Symbol.ContainingType.ToMinimalDisplayString(model, memberAccess.SpanStart))); return SyntaxFactory.InvocationExpression(newTarget, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList<ArgumentSyntax>(newArgumentList))); }
public static double CalculatePriceBid(SymbolInfo symbol) { FinancialCalculator financialCalculator = FdkStatic.Calculator; double? rateK = financialCalculator.CalculateAssetRate(1, symbol.SettlementCurrency, "USD"); if (!rateK.HasValue) return double.NaN; return rateK.Value; }
static void Main(string[] args) { string strConn = ConfigurationManager.ConnectionStrings["DBModel.Properties.Settings.StockDataConnectionString"].ConnectionString; List<SymbolInfo> symbolList = new List<SymbolInfo>(); //Load Symbols From CSV using (StreamReader sr = File.OpenText(@"F:\Projects\Git\StockDownloader\LoadSymbol\ETF_List.csv")) { var line = sr.ReadLine(); while(line != null) { var items = line.Split(new char[] { ',' }); if(items.Length ==4) { var si = new SymbolInfo(); si.NativeSymbol = items[0]; si.Name = items[1]; si.Exchange = items[2]; si.NativeCountry = items[3]; if(si.IsValid()) { symbolList.Add(si); } } line = sr.ReadLine(); } sr.Close(); } using (StockDBDataContext dbContext = new StockDBDataContext(strConn)) { foreach(var si in symbolList) { var stockSymbol = dbContext.StockSymbols.Where(s => s.Symbol == si.Symbol).SingleOrDefault(); if(stockSymbol == null) { stockSymbol = new StockSymbol() { Symbol = si.Symbol, StockName = si.Name, Country = si.Country, ETF = si.ETF }; dbContext.StockSymbols.InsertOnSubmit(stockSymbol); } else { stockSymbol.StockName = si.Name; stockSymbol.Country = si.Country; stockSymbol.ETF = si.ETF; } } dbContext.SubmitChanges(); } }
public static bool SymbolInfosAreCompatible(SymbolInfo originalSymbolInfo, SymbolInfo newSymbolInfo, bool performEquivalenceCheck, bool requireNonNullSymbols = false) { try { return (bool)symbolInfosAreCompatibleMethod.Invoke (null, new object [] { originalSymbolInfo, newSymbolInfo, performEquivalenceCheck, requireNonNullSymbols }); } catch (TargetInvocationException ex) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); return false; } }
public void Add(SymbolInfo symbol) { if (symbol is SymData32) Add(((SymData32)symbol).Name, symbol); else if (symbol is SymGProcRef) Add(((SymGProcRef)symbol).Name, symbol); else throw new ApplicationException("Invalid symbol type in call to GlobalsHash.Add(): " + symbol.ToString()); }
private void Add(string name, SymbolInfo symbol) { int hashVal = (int)PdbWriter.Hash(name, HASH_MODULO); if (!m_occupiedHash[hashVal]) { m_occupiedHash[hashVal] = true; m_table[hashVal] = new List<KeyValuePair<string, SymbolInfo>>(); } m_table[hashVal].Add(new KeyValuePair<string,SymbolInfo>(name, symbol)); m_numGlobals++; }
public static double CalculatePipsValue(SymbolInfo symbol) { FinancialCalculator financialCalculator = FdkStatic.Calculator; int decimals = symbol.Precision; double contractSize = symbol.ContractMultiplier; double? rateK = financialCalculator.CalculateAssetRate(1, symbol.SettlementCurrency, "USD"); if (!rateK.HasValue) throw new InvalidOperationException( string.Format("No rate for currency pair: {0}/USD", symbol.SettlementCurrency)); double formula = Math.Pow(10, -decimals) * contractSize * rateK.Value; return formula; }
public static SymbolInfo split_lists(SymbolInfo si_left,SymbolInfo si_right) { if (si_left==null) { return si_right; } if (si_right==null) { return si_left; } SymbolInfo si=si_left; while(si.Next!=null) { si=si.Next; } si.Next=si_right; return si_left; }
public override FlatOperand Resolve(InvocationExpressionSyntax node, TypeInfo result_type, SymbolInfo si, FlatOperand into_lvalue, Function function, List<FlatStatement> instructions) { if (!(node.Expression is MemberAccessExpressionSyntax)) { throw new NotImplementedException("GETPROPERTY not on MemberAccessExpressionSyntax"); } MemberAccessExpressionSyntax meas = (MemberAccessExpressionSyntax)node.Expression; FlatOperand fop_subject = function.ResolveExpression(meas.Expression, null, instructions); if (into_lvalue == null) { FlatOperand fop_register = function.AllocateRegister(""); into_lvalue = fop_register.GetLValue(function, instructions); } instructions.Add(FlatStatement.STRINGVAL(into_lvalue, fop_subject)); return into_lvalue.AsRValue(FlatValue.String(string.Empty)); }
// we use the semantic model to get the type information of the method being called private static bool CanRewriteSymbol(SymbolInfo symbolInfo, out bool appendNewLine) { appendNewLine = false; IMethodSymbol methodSymbol = symbolInfo.Symbol as IMethodSymbol; if (methodSymbol == null) return false; switch (methodSymbol.Name) { case "AppendLine": case "Append": if (methodSymbol.ContainingType.ToString() == "System.Text.StringBuilder") { appendNewLine = methodSymbol.Name == "AppendLine"; return true; } break; } return false; }
private static ISymbol TryGetSymbol(NameSyntax name, SymbolInfo symbolInfo, SemanticModel semanticModel) { if (symbolInfo.Symbol == null && symbolInfo.CandidateSymbols.Length > 0) { var firstSymbol = symbolInfo.CandidateSymbols[0]; switch (symbolInfo.CandidateReason) { case CandidateReason.NotAValue: return firstSymbol; case CandidateReason.NotCreatable: // We want to color types even if they can't be constructed. if (firstSymbol.IsConstructor() || firstSymbol is ITypeSymbol) { return firstSymbol; } break; case CandidateReason.OverloadResolutionFailure: // If we couldn't bind to a constructor, still classify the type. if (firstSymbol.IsConstructor()) { return firstSymbol; } break; case CandidateReason.Inaccessible: // If a constructor wasn't accessible, still classify the type if it's accessible. if (firstSymbol.IsConstructor() && semanticModel.IsAccessible(name.SpanStart, firstSymbol.ContainingType)) { return firstSymbol; } break; } } return symbolInfo.Symbol; }
public void add_name(string name,SymbolInfo si) { name=name_to_symtab(name); object o=ht[name]; if (o==null) { SymbolInfoArrayList syal=new SymbolInfoArrayList(); syal.Add(si); ht[name]=syal; return; } else { /*if (si.symbol_kind==symbol_kind.sk_none) { throw new CompilerInternalError("Duplicate name definition"); }*/ SymbolInfoArrayList syal1=(SymbolInfoArrayList)o; syal1.Add(si); return; } }
public static IMethodSymbol GetDelegatingConstructor( SemanticDocument document, SymbolInfo symbolInfo, ISet<IMethodSymbol> candidateInstanceConstructors, INamedTypeSymbol containingType, IList<ITypeSymbol> parameterTypes) { var symbol = symbolInfo.Symbol as IMethodSymbol; if (symbol == null && symbolInfo.CandidateSymbols.Length == 1) { // Even though the symbol info has a non-viable candidate symbol, we are trying // to speculate a base constructor invocation from a different position then // where the invocation to it would be generated. Passed in candidateInstanceConstructors // actually represent all accessible and invocable constructor symbols. So, we allow // candidate symbol for inaccessible OR not creatable candidate reason if it is in // the given candidateInstanceConstructors. // // Note: if we get either of these cases, we ensure that we can at least convert // the parameter types we have to the constructor parameter types. This way we // don't accidently think we delegate to a constructor in an abstract base class // when the parameter types don't match. if (symbolInfo.CandidateReason == CandidateReason.Inaccessible || (symbolInfo.CandidateReason == CandidateReason.NotCreatable && containingType.IsAbstract)) { var method = symbolInfo.CandidateSymbols.Single() as IMethodSymbol; if (ParameterTypesMatch(document, parameterTypes, method)) { symbol = method; } } } if (symbol != null && candidateInstanceConstructors.Contains(symbol)) { return symbol; } return null; }
Document ImportStaticClassWithUsing(Document document, SemanticModel model, SyntaxNode root, SyntaxNode node, SymbolInfo info, CancellationToken cancellationToken) { var cu = root as CompilationUnitSyntax; var visitor = new SearchImportReplacementsVisitor(model, info, cancellationToken); visitor.Visit(root); cu = (CompilationUnitSyntax)root.TrackNodes(visitor.ReplaceNodes); foreach (var ma in visitor.ReplaceNodes) { var current = cu.GetCurrentNode<MemberAccessExpressionSyntax>(ma); cu = cu.ReplaceNode(current, current.Name.WithAdditionalAnnotations(Formatter.Annotation)); } var staticUsing = SyntaxFactory .UsingDirective(SyntaxFactory.ParseName(info.Symbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat))) .WithStaticKeyword(SyntaxFactory.Token(SyntaxKind.StaticKeyword)) .WithAdditionalAnnotations(Formatter.Annotation); cu = cu.AddUsingDirective(staticUsing, node, true); return document.WithSyntaxRoot(cu); }
public static IMethodSymbol GetDelegatingConstructor(SymbolInfo symbolInfo, ISet<IMethodSymbol> candidateInstanceConstructors, INamedTypeSymbol containingType) { var symbol = symbolInfo.Symbol as IMethodSymbol; if (symbol == null && symbolInfo.CandidateSymbols.Count() == 1) { // Even though the symbol info has a non-viable candidate symbol, we are trying to speculate a base constructor // invocation from a different position then where the invocation to it would be generated. // Passed in candidateInstanceConstructors actually represent all accessible and invocable constructor symbols. // So, we allow candidate symbol for inaccessible OR not creatable candidate reason if it is in the given candidateInstanceConstructors. if (symbolInfo.CandidateReason == CandidateReason.Inaccessible || (symbolInfo.CandidateReason == CandidateReason.NotCreatable && containingType.IsAbstract)) { symbol = symbolInfo.CandidateSymbols.Single() as IMethodSymbol; } } if (symbol != null && candidateInstanceConstructors.Contains(symbol)) { return symbol; } return null; }
/*public override base_scope top_scope { get { return _up_scope; } }*/ public override SymbolInfo Find(string name) { SymbolInfo si=null; if (NetHelper.IsNetNamespace(name.ToLower()) == true) { compiled_namespace_node cnn = new compiled_namespace_node(name); si = new SymbolInfo(cnn); } else { //Type t = Type.GetType("System."+name,false,true); Type t=null; int i=0; t = NetHelper.FindType(name); if (t != null) { compiled_type_node ctn = compiled_type_node.get_type_node(t); ctn.Scope = new NetTypeScope(ctn.compiled_type); si = new SymbolInfo(ctn); } else { while ((t==null)&&(i<_unar.Count)) { t=_assembly.GetType(_unar[i].namespace_name+"."+name,false,true); i++; } if (t != null) { compiled_type_node ctn = compiled_type_node.get_type_node(t); ctn.Scope = new NetTypeScope(ctn.compiled_type); si = new SymbolInfo(ctn); NetHelper.AddType(name,t); } } } return si; }
private bool TryClassifyNameOfIdentifier(NameSyntax name, SymbolInfo symbolInfo, out IEnumerable<ClassifiedSpan> result) { var identifierName = name as IdentifierNameSyntax; if (identifierName != null && identifierName.Identifier.IsKindOrHasMatchingText(SyntaxKind.NameOfKeyword) && symbolInfo.Symbol == null && !symbolInfo.CandidateSymbols.Any()) { result = SpecializedCollections.SingletonEnumerable(new ClassifiedSpan(identifierName.Identifier.Span, ClassificationTypeNames.Keyword)); return true; } result = null; return false; }
private bool TryClassifyAmbiguousSymbol( NameSyntax name, SymbolInfo symbolInfo, SemanticModel semanticModel, CancellationToken cancellationToken, out IEnumerable<ClassifiedSpan> result) { // If everything classifies the same way, then just pick that classification. var set = new HashSet<ClassifiedSpan>(); foreach (var symbol in symbolInfo.CandidateSymbols) { ClassifiedSpan classifiedSpan; if (TryClassifySymbol(name, symbol, semanticModel, cancellationToken, out classifiedSpan)) { set.Add(classifiedSpan); } } if (set.Count == 1) { result = SpecializedCollections.SingletonEnumerable(set.First()); return true; } result = null; return false; }
internal virtual bool IsIndexerAccess(SymbolInfo member) { return(Utilities.GetFullMetadataName(member.Symbol.ContainingType) == "System.Numerics.Matrix4x4" && member.Symbol.Name[0] == 'M' && char.IsDigit(member.Symbol.Name[1])); }
public static string GetSymbolName(InvocationExpressionSyntax node, SymbolInfo si, string name, SemanticModel semanticModel) { var symbol = si.Symbol; if (symbol == null && si.CandidateSymbols.Any()) { symbol = si.CandidateSymbols.First(); } if (symbol != null && symbol.Kind != SymbolKind.Namespace) { //bool preserveMemberChange = !(symbol.Kind == SymbolKind.Method || symbol.Kind == SymbolKind.Property); int enumMode = -1; if (symbol.ContainingType != null && symbol.ContainingType.TypeKind == TypeKind.Enum && symbol is IFieldSymbol) { string enumAttr = Translator.H5_ASSEMBLY + ".EnumAttribute"; enumMode = 7; foreach (var attr in symbol.ContainingType.GetAttributes()) { if (attr.AttributeClass != null && attr.AttributeClass.FullyQualifiedName() == enumAttr && attr.ConstructorArguments.Any()) { enumMode = (int)attr.ConstructorArguments.First().Value; break; } } } var nameAttr = GetInheritedAttribute(symbol, Translator.H5_ASSEMBLY + ".NameAttribute"); bool isIgnore = symbol.ContainingType != null && IsExternalType(symbol.ContainingType); name = symbol.Name; if (nameAttr != null) { var value = nameAttr.ConstructorArguments.First().Value; if (value is string) { name = value.ToString(); name = Helpers.ConvertNameTokens(name, symbol.Name); if (!isIgnore && symbol.IsStatic && Helpers.IsReservedStaticName(name)) { name = Helpers.ChangeReservedWord(name); } return(name); } //preserveMemberChange = !(bool)value; enumMode = -1; } if (enumMode > 6) { switch (enumMode) { case 7: break; case 8: name = name.ToLowerInvariant(); break; case 9: name = name.ToUpperInvariant(); break; } } /*else * { * name = !preserveMemberChange ? Object.Net.Utilities.StringUtils.ToLowerCamelCase(name) : name; * }*/ if (!isIgnore && symbol.IsStatic && Helpers.IsReservedStaticName(name)) { name = Helpers.ChangeReservedWord(name); } } return(name); }
public CreateOrChangeOrderDefault(OrderAction orderAction, SymbolInfo symbol, LogicalOrder logical, OrderSide side, int size, double price) : this(OrderState.Pending, symbol, logical, side, size, price) { binary.action = orderAction; instanceId = ++nextInstanceId; }
public static bool TryGetSymbolInfo(this SyntaxNodeAnalysisContext context, SyntaxNode node, out SymbolInfo symbolInfo) { try { //NOTE: The Call below fixes many issues where the symbol cannot be found - but there are still cases where an argumentexception is thrown // which seems to resemble this issue: https://github.com/dotnet/roslyn/issues/11193 var semanticModel = SemanticModelFor(context.SemanticModel, node); symbolInfo = semanticModel.GetSymbolInfo(node); //context.SemanticModel.GetSymbolInfo(node); return(true); } catch (Exception generalException) { Debug.WriteLine("Unable to find Symbol: " + node); Debug.WriteLine(generalException); } symbolInfo = default(SymbolInfo); return(false); }
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false); if (!TryFindFirstAncestorOrSelf(root, context.Span, out ArgumentSyntax argument)) { return; } foreach (Diagnostic diagnostic in context.Diagnostics) { switch (diagnostic.Id) { case CompilerDiagnosticIdentifiers.ArgumentMustBePassedWithRefOrOutKeyword: { if (!Settings.IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddOutModifierToArgument)) { return; } SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); IParameterSymbol parameter = semanticModel.DetermineParameter(argument, allowCandidate: true, cancellationToken: context.CancellationToken); if (parameter == null) { return; } SyntaxToken refOrOutKeyword = default; if (parameter.RefKind == RefKind.Out) { refOrOutKeyword = Token(SyntaxKind.OutKeyword); } else if (parameter.RefKind == RefKind.Ref) { refOrOutKeyword = Token(SyntaxKind.RefKeyword); } else { return; } CodeAction codeAction = CodeAction.Create( $"Add '{SyntaxFacts.GetText(refOrOutKeyword.Kind())}' modifier", cancellationToken => { ArgumentSyntax newArgument = argument .WithRefOrOutKeyword(refOrOutKeyword) .WithFormatterAnnotation(); return(context.Document.ReplaceNodeAsync(argument, newArgument, cancellationToken)); }, GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); break; } case CompilerDiagnosticIdentifiers.ArgumentShouldNotBePassedWithRefOrOutKeyword: { if (!Settings.IsEnabled(diagnostic.Id, CodeFixIdentifiers.RemoveRefModifier)) { return; } CodeAction codeAction = CodeAction.Create( "Remove 'ref' modifier", cancellationToken => { ArgumentSyntax newArgument = argument .WithRefOrOutKeyword(default(SyntaxToken)) .PrependToLeadingTrivia(argument.RefOrOutKeyword.GetAllTrivia()) .WithFormatterAnnotation(); return(context.Document.ReplaceNodeAsync(argument, newArgument, cancellationToken)); }, GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); break; } case CompilerDiagnosticIdentifiers.CannotConvertArgumentType: { if (Settings.IsEnabled(diagnostic.Id, CodeFixIdentifiers.ReplaceNullLiteralExpressionWithDefaultValue)) { ExpressionSyntax expression = argument.Expression; if (expression.Kind() == SyntaxKind.NullLiteralExpression && argument.Parent is ArgumentListSyntax argumentList) { SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); ImmutableArray <IParameterSymbol> parameterSymbols = FindParameters(argumentList, semanticModel, context.CancellationToken); if (!parameterSymbols.IsDefault) { int index = argumentList.Arguments.IndexOf(argument); IParameterSymbol parameterSymbol = parameterSymbols[index]; ITypeSymbol typeSymbol = parameterSymbol.Type; if (typeSymbol.IsValueType) { CodeFixRegistrator.ReplaceNullWithDefaultValue( context, diagnostic, expression, typeSymbol, CodeFixIdentifiers.ReplaceNullLiteralExpressionWithDefaultValue); } } } } if (Settings.IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddArgumentList)) { ExpressionSyntax expression = argument.Expression; if (expression.IsKind( SyntaxKind.IdentifierName, SyntaxKind.GenericName, SyntaxKind.SimpleMemberAccessExpression)) { InvocationExpressionSyntax invocationExpression = InvocationExpression( expression.WithoutTrailingTrivia(), ArgumentList().WithTrailingTrivia(expression.GetTrailingTrivia())); SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); if (semanticModel.GetSpeculativeMethodSymbol(expression.SpanStart, invocationExpression) != null) { CodeAction codeAction = CodeAction.Create( "Add argument list", cancellationToken => { ArgumentSyntax newNode = argument.WithExpression(invocationExpression); return(context.Document.ReplaceNodeAsync(argument, newNode, cancellationToken)); }, GetEquivalenceKey(diagnostic, CodeFixIdentifiers.AddArgumentList)); context.RegisterCodeFix(codeAction, diagnostic); break; } } } if (Settings.IsEnabled(diagnostic.Id, CodeFixIdentifiers.CreateSingletonArray)) { ExpressionSyntax expression = argument.Expression; if (expression?.IsMissing == false) { SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(expression); if (typeSymbol?.IsErrorType() == false) { foreach (ITypeSymbol typeSymbol2 in DetermineParameterTypeHelper.DetermineParameterTypes(argument, semanticModel, context.CancellationToken)) { if (!SymbolEqualityComparer.Default.Equals(typeSymbol, typeSymbol2) && typeSymbol2 is IArrayTypeSymbol arrayType && semanticModel.IsImplicitConversion(expression, arrayType.ElementType)) { CodeAction codeAction = CodeAction.Create( "Create singleton array", cancellationToken => CreateSingletonArrayRefactoring.RefactorAsync(context.Document, expression, arrayType.ElementType, semanticModel, cancellationToken), GetEquivalenceKey(diagnostic, CodeFixIdentifiers.CreateSingletonArray)); context.RegisterCodeFix(codeAction, diagnostic); break; } } } } } break; } case CompilerDiagnosticIdentifiers.ReadOnlyFieldCannotBePassedAsRefOrOutValue: { if (!Settings.IsEnabled(diagnostic.Id, CodeFixIdentifiers.MakeFieldWritable)) { return; } SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); SymbolInfo symbolInfo = semanticModel.GetSymbolInfo(argument.Expression, context.CancellationToken); if (symbolInfo.CandidateReason != CandidateReason.NotAVariable) { return; } if (!(symbolInfo.CandidateSymbols.SingleOrDefault(shouldThrow: false) is IFieldSymbol fieldSymbol)) { return; } if (fieldSymbol.DeclaredAccessibility != Accessibility.Private) { return; } if (!(fieldSymbol.GetSyntax().Parent.Parent is FieldDeclarationSyntax fieldDeclaration)) { return; } TypeDeclarationSyntax containingTypeDeclaration = fieldDeclaration.FirstAncestor <TypeDeclarationSyntax>(); if (!argument.Ancestors().Any(f => f == containingTypeDeclaration)) { return; } ModifiersCodeFixRegistrator.RemoveModifier( context, diagnostic, fieldDeclaration, SyntaxKind.ReadOnlyKeyword, title: $"Make '{fieldSymbol.Name}' writable", additionalKey: CodeFixIdentifiers.MakeFieldWritable); break; } } } }
public override void OnStopSymbol(SymbolInfo symbol) { RequestStopSymbol(symbol); }
private static void CreateDiagnosticIfExpressionsMatch(SyntaxNodeAnalysisContext context, Location diagnosticLocation, SymbolInfo ifConditionIdentifier, SymbolInfo memberAccessIdentifier) { if ((ifConditionIdentifier.Symbol ?? memberAccessIdentifier.Symbol) == null) { return; } if (ifConditionIdentifier.Equals(memberAccessIdentifier)) { var diagnostic = Diagnostic.Create(Rule, diagnosticLocation, "You can use the existence operator."); context.ReportDiagnostic(diagnostic); } }
private ImmutableArray <ISymbol> GetSymbolsOffOfBoundExpression( ExpressionSyntax originalExpression, ExpressionSyntax expression, SymbolInfo leftHandBinding, INamespaceOrTypeSymbol container) { var useBaseReferenceAccessibility = false; var excludeInstance = false; var excludeStatic = false; var symbol = leftHandBinding.GetAnySymbol(); ImmutableArray <ISymbol> symbols = default; if (symbol != null) { // If the thing on the left is a type, namespace or alias and the original // expression was parenthesized, we shouldn't show anything in IntelliSense. if (originalExpression.IsKind(SyntaxKind.ParenthesizedExpression) && symbol.MatchesKind(SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Alias)) { return(ImmutableArray <ISymbol> .Empty); } // If the thing on the left is a lambda expression, we shouldn't show anything. if (symbol.Kind == SymbolKind.Method && ((IMethodSymbol)symbol).MethodKind == MethodKind.AnonymousFunction) { return(ImmutableArray <ISymbol> .Empty); } // If the thing on the left is a method name identifier, we shouldn't show anything. var originalExpressionKind = originalExpression.Kind(); if (symbol.Kind == SymbolKind.Method && (originalExpressionKind == SyntaxKind.IdentifierName || originalExpressionKind == SyntaxKind.GenericName)) { return(ImmutableArray <ISymbol> .Empty); } // If the thing on the left is an event that can't be used as a field, we shouldn't show anything if (symbol.Kind == SymbolKind.Event && !_context.SemanticModel.IsEventUsableAsField(originalExpression.SpanStart, (IEventSymbol)symbol)) { return(ImmutableArray <ISymbol> .Empty); } // If the thing on the left is a this parameter (e.g. this or base) and we're in a static context, // we shouldn't show anything if (symbol.IsThisParameter() && expression.IsInStaticContext()) { return(ImmutableArray <ISymbol> .Empty); } // What is the thing on the left? switch (symbol.Kind) { case SymbolKind.NamedType: case SymbolKind.Namespace: excludeInstance = true; container = (INamespaceOrTypeSymbol)symbol; break; case SymbolKind.Alias: excludeInstance = true; container = ((IAliasSymbol)symbol).Target; break; case SymbolKind.Parameter: var parameter = (IParameterSymbol)symbol; excludeStatic = true; symbols = GetSymbols(parameter, originalExpression.SpanStart); // case: // base.| if (parameter.IsThis && !object.Equals(parameter.Type, container)) { useBaseReferenceAccessibility = true; } break; default: excludeStatic = true; break; } } else if (container != null) { excludeStatic = true; } else { return(ImmutableArray <ISymbol> .Empty); } Debug.Assert(!excludeInstance || !excludeStatic); Debug.Assert(!excludeInstance || !useBaseReferenceAccessibility); // nameof(X.| // Show static and instance members. if (_context.IsNameOfContext) { excludeInstance = false; excludeStatic = false; } if (symbols.IsDefault) { symbols = GetSymbols( container, position: originalExpression.SpanStart, excludeInstance: excludeInstance, useBaseReferenceAccessibility: useBaseReferenceAccessibility); } // If we're showing instance members, don't include nested types return(excludeStatic ? symbols.WhereAsArray(s => !s.IsStatic && !(s is ITypeSymbol)) : symbols); }
public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, IDictionary <EncodeHintType, object> hints) { if (String.IsNullOrEmpty(contents)) { throw new ArgumentException("Found empty contents", contents); } if (format != BarcodeFormat.DATA_MATRIX) { throw new ArgumentException("Can only encode DATA_MATRIX, but got " + format); } if (width < 0 || height < 0) { throw new ArgumentException("Requested dimensions are too small: " + width + 'x' + height); } // Try to get force shape & min / max size var shape = SymbolShapeHint.FORCE_NONE; var defaultEncodation = Encodation.ASCII; Dimension minSize = null; Dimension maxSize = null; if (hints != null) { if (hints.ContainsKey(EncodeHintType.DATA_MATRIX_SHAPE)) { var requestedShape = hints[EncodeHintType.DATA_MATRIX_SHAPE]; if (requestedShape is SymbolShapeHint) { shape = (SymbolShapeHint)requestedShape; } else { if (Enum.IsDefined(typeof(SymbolShapeHint), requestedShape.ToString())) { shape = (SymbolShapeHint)Enum.Parse(typeof(SymbolShapeHint), requestedShape.ToString(), true); } } } var requestedMinSize = hints.ContainsKey(EncodeHintType.MIN_SIZE) ? hints[EncodeHintType.MIN_SIZE] as Dimension : null; if (requestedMinSize != null) { minSize = requestedMinSize; } var requestedMaxSize = hints.ContainsKey(EncodeHintType.MAX_SIZE) ? hints[EncodeHintType.MAX_SIZE] as Dimension : null; if (requestedMaxSize != null) { maxSize = requestedMaxSize; } if (hints.ContainsKey(EncodeHintType.DATA_MATRIX_DEFAULT_ENCODATION)) { var requestedDefaultEncodation = hints[EncodeHintType.DATA_MATRIX_DEFAULT_ENCODATION]; if (requestedDefaultEncodation != null) { defaultEncodation = Convert.ToInt32(requestedDefaultEncodation.ToString()); } } } //1. step: Data encodation String encoded = HighLevelEncoder.encodeHighLevel(contents, shape, minSize, maxSize, defaultEncodation); SymbolInfo symbolInfo = SymbolInfo.lookup(encoded.Length, shape, minSize, maxSize, true); //2. step: ECC generation String codewords = ErrorCorrection.encodeECC200(encoded, symbolInfo); //3. step: Module placement in Matrix var placement = new DefaultPlacement(codewords, symbolInfo.getSymbolDataWidth(), symbolInfo.getSymbolDataHeight()); placement.place(); //4. step: low-level encoding return(encodeLowLevel(placement, symbolInfo)); }
public CapturedSymbolInfo(syntax_tree_node syntaxTreeNodeWithVarDeclaration, SymbolInfo symbolInfo) { ReferencingLambdas = new List <CapturedVariablesTreeNodeLambdaScope>(); SyntaxTreeNodeWithVarDeclaration = syntaxTreeNodeWithVarDeclaration; SymbolInfo = symbolInfo; }
internal static extern bool SymFromName(SafeProcessHandle processHandle, string name, out SymbolInfo symbolInfo);
protected abstract bool ConstructorDoesNotExist(SyntaxNode node, SymbolInfo info, SemanticModel semanticModel);
public MonteCarloPass(SymbolInfo symbol, InventoryGroupTest.PriceChange[] priceChanges) { this.symbol = symbol; this.priceChanges = priceChanges; }
private void RequestStartSymbol(SymbolInfo symbol) { var handler = GetSymbolHandler(symbol, receiver); string quoteType = ""; switch (symbol.QuoteType) { case QuoteType.Level1: quoteType = "20000"; break; case QuoteType.Level2: quoteType = "20001"; break; case QuoteType.None: quoteType = null; break; default: SendError("Unknown QuoteType " + symbol.QuoteType + " for symbol " + symbol + "."); return; } string tradeType = ""; switch (symbol.TimeAndSales) { case TimeAndSales.ActualTrades: tradeType = "20003"; break; case TimeAndSales.Extrapolated: tradeType = null; break; case TimeAndSales.None: tradeType = null; break; default: SendError("Unknown TimeAndSales " + symbol.TimeAndSales + " for symbol " + symbol + "."); return; } if (tradeType != null) { Packet packet = Socket.CreatePacket(); string message = "S|1003=" + symbol.Symbol + ";2000=" + tradeType + "\n"; if (debug) { log.Debug("Symbol request: " + message); } packet.DataOut.Write(message.ToCharArray()); while (!Socket.TrySendPacket(packet)) { if (IsInterrupted) { return; } Factory.Parallel.Yield(); } } if (quoteType != null) { Packet packet = Socket.CreatePacket(); string message = "S|1003=" + symbol.Symbol + ";2000=" + quoteType + "\n"; if (debug) { log.Debug("Symbol request: " + message); } packet.DataOut.Write(message.ToCharArray()); while (!Socket.TrySendPacket(packet)) { if (IsInterrupted) { return; } Factory.Parallel.Yield(); } } while (!receiver.OnEvent(symbol, (int)EventType.StartRealTime, null)) { if (IsInterrupted) { return; } Factory.Parallel.Yield(); } }
internal override SymbolInfo GetSymbolInfoWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)) { ValidateSymbolInfoOptions(options); // in case this is right side of a qualified name or member access (or part of a cref) node = SyntaxFactory.GetStandaloneNode(node); var model = this.GetMemberModel(node); SymbolInfo result; XmlNameAttributeSyntax attrSyntax; CrefSyntax crefSyntax; if (model != null) { // Expression occurs in an executable code (method body or initializer) context. Use that // model to get the information. result = model.GetSymbolInfoWorker(node, options, cancellationToken); // If we didn't get anything and were in Type/Namespace only context, let's bind normally and see // if any symbol comes out. if ((object)result.Symbol == null && result.CandidateReason == CandidateReason.None && node is ExpressionSyntax && SyntaxFacts.IsInNamespaceOrTypeContext((ExpressionSyntax)node)) { var binder = this.GetEnclosingBinder(GetAdjustedNodePosition(node)); if (binder != null) { // Wrap the binder in a LocalScopeBinder because Binder.BindExpression assumes there // will be one in the binder chain and one isn't necessarily required for the batch case. binder = new LocalScopeBinder(binder); var diagnostics = DiagnosticBag.GetInstance(); BoundExpression bound = binder.BindExpression((ExpressionSyntax)node, diagnostics); diagnostics.Free(); SymbolInfo info = GetSymbolInfoForNode(options, bound, bound, boundNodeForSyntacticParent: null, binderOpt: null); if ((object)info.Symbol != null) { result = new SymbolInfo(null, ImmutableArray.Create<ISymbol>(info.Symbol), CandidateReason.NotATypeOrNamespace); } else if (!info.CandidateSymbols.IsEmpty) { result = new SymbolInfo(null, info.CandidateSymbols, CandidateReason.NotATypeOrNamespace); } } } } else if (node.Parent.Kind() == SyntaxKind.XmlNameAttribute && (attrSyntax = (XmlNameAttributeSyntax)node.Parent).Identifier == node) { result = SymbolInfo.None; var binder = this.GetEnclosingBinder(GetAdjustedNodePosition(node)); if (binder != null) { HashSet<DiagnosticInfo> useSiteDiagnostics = null; var symbols = binder.BindXmlNameAttribute(attrSyntax, ref useSiteDiagnostics); // NOTE: We don't need to call GetSymbolInfoForSymbol because the symbols // can only be parameters or type parameters. Debug.Assert(symbols.All(s => s.Kind == SymbolKind.TypeParameter || s.Kind == SymbolKind.Parameter)); switch (symbols.Length) { case 0: result = SymbolInfo.None; break; case 1: result = SymbolInfoFactory.Create(symbols, LookupResultKind.Viable, isDynamic: false); break; default: result = SymbolInfoFactory.Create(symbols, LookupResultKind.Ambiguous, isDynamic: false); break; } } } else if ((crefSyntax = node as CrefSyntax) != null) { int adjustedPosition = GetAdjustedNodePosition(crefSyntax); result = GetCrefSymbolInfo(adjustedPosition, crefSyntax, options, HasParameterList(crefSyntax)); } else { // if expression is not part of a member context then caller may really just have a // reference to a type or namespace name var symbol = GetSemanticInfoSymbolInNonMemberContext(node, bindVarAsAliasFirst: (options & SymbolInfoOptions.PreserveAliases) != 0); result = (object)symbol != null ? GetSymbolInfoForSymbol(symbol, options) : SymbolInfo.None; } return result; }
protected abstract void TrySendTick(SymbolInfo symbol, TickIO tick);
//returns the valueClause of the return statement from SupportedDiagnostics and the return declaration, empty list if failed internal SuppDiagReturnSymbolInfo SuppDiagReturnSymbol(CompilationAnalysisContext context, SymbolInfo returnSymbolInfo, Location getAccessorKeywordLocation) { SuppDiagReturnSymbolInfo result = new SuppDiagReturnSymbolInfo(); ILocalSymbol returnSymbol = null; if (returnSymbolInfo.CandidateSymbols.Count() == 0) { returnSymbol = returnSymbolInfo.Symbol as ILocalSymbol; } else { returnSymbol = returnSymbolInfo.CandidateSymbols[0] as ILocalSymbol; } if (returnSymbol == null) { ReportDiagnostic(context, IncorrectAccessorReturnRule, getAccessorKeywordLocation); return result; } if (returnSymbol.Type.ToString() != "System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.DiagnosticDescriptor>" && returnSymbol.Type.Kind.ToString() != "ErrorType") { ReportDiagnostic(context, IncorrectAccessorReturnRule, returnSymbol.Locations[0]); return result; } var variableDeclaration = returnSymbol.DeclaringSyntaxReferences[0].GetSyntax() as VariableDeclaratorSyntax; ReturnStatementSyntax returnDeclaration = returnSymbol.DeclaringSyntaxReferences[0].GetSyntax() as ReturnStatementSyntax; if (variableDeclaration == null) { ReportDiagnostic(context, IncorrectAccessorReturnRule, returnSymbol.Locations[0]); return result; } var equalsValueClause = variableDeclaration.Initializer as EqualsValueClauseSyntax; if (equalsValueClause == null) { ReportDiagnostic(context, IncorrectAccessorReturnRule, returnDeclaration.ReturnKeyword.GetLocation()); return result; } var valueClause = equalsValueClause.Value as InvocationExpressionSyntax; if (valueClause == null) { ReportDiagnostic(context, IncorrectAccessorReturnRule, returnDeclaration.GetLocation()); return result; } result.ValueClause = valueClause; result.ReturnDeclaration = returnDeclaration; return result; }
internal virtual string CorrectFieldAccess(SymbolInfo symbolInfo) { string mapped = CSharpToShaderIdentifierName(symbolInfo); return(CorrectIdentifier(mapped)); }
public SearchImportReplacementsVisitor(Microsoft.CodeAnalysis.SemanticModel model, Microsoft.CodeAnalysis.SymbolInfo info, CancellationToken cancellationToken) { this.cancellationToken = cancellationToken; this.model = model; this.info = info; }
private static IEnumerable <ISymbol> GetSymbolsOffOfBoundExpression( CSharpSyntaxContext context, ExpressionSyntax originalExpression, ExpressionSyntax expression, SymbolInfo leftHandBinding, INamespaceOrTypeSymbol container, CancellationToken cancellationToken) { var useBaseReferenceAccessibility = false; var excludeInstance = false; var excludeStatic = false; var symbol = leftHandBinding.GetBestOrAllSymbols().FirstOrDefault(); if (symbol != null) { // If the thing on the left is a type, namespace or alias and the original // expression was parenthesized, we shouldn't show anything in IntelliSense. if (originalExpression.IsKind(SyntaxKind.ParenthesizedExpression) && symbol.MatchesKind(SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Alias)) { return(SpecializedCollections.EmptyEnumerable <ISymbol>()); } // If the thing on the left is a lambda expression, we shouldn't show anything. if (symbol.Kind == SymbolKind.Method && ((IMethodSymbol)symbol).MethodKind == MethodKind.AnonymousFunction) { return(SpecializedCollections.EmptyEnumerable <ISymbol>()); } // If the thing on the left is an event that can't be used as a field, we shouldn't show anything if (symbol.Kind == SymbolKind.Event && !context.SemanticModel.IsEventUsableAsField(originalExpression.SpanStart, (IEventSymbol)symbol)) { return(SpecializedCollections.EmptyEnumerable <ISymbol>()); } // If the thing on the left is a this parameter (e.g. this or base) and we're in a static context, // we shouldn't show anything if (symbol.IsThisParameter() && expression.IsInStaticContext()) { return(SpecializedCollections.EmptyEnumerable <ISymbol>()); } // What is the thing on the left? switch (symbol.Kind) { case SymbolKind.NamedType: case SymbolKind.Namespace: excludeInstance = true; container = (INamespaceOrTypeSymbol)symbol; break; case SymbolKind.Alias: excludeInstance = true; container = ((IAliasSymbol)symbol).Target; break; case SymbolKind.Parameter: var parameter = (IParameterSymbol)symbol; excludeStatic = true; // case: // base.| if (parameter.IsThis && !object.Equals(parameter.Type, container)) { useBaseReferenceAccessibility = true; } break; default: excludeStatic = true; break; } } else if (container != null) { excludeStatic = true; } else { return(SpecializedCollections.EmptyEnumerable <ISymbol>()); } Debug.Assert(!excludeInstance || !excludeStatic); Debug.Assert(!excludeInstance || !useBaseReferenceAccessibility); // nameof(X.| // Show static and instance members. if (context.IsNameOfContext) { excludeInstance = false; excludeStatic = false; } var position = originalExpression.SpanStart; IEnumerable <ISymbol> symbols = useBaseReferenceAccessibility ? context.SemanticModel.LookupBaseMembers(position) : excludeInstance ? context.SemanticModel.LookupStaticMembers(position, container) : context.SemanticModel.LookupSymbols(position, container, includeReducedExtensionMethods: true); // If we're showing instance members, don't include nested types return(excludeStatic ? symbols.Where(s => !s.IsStatic && !(s is ITypeSymbol)) : symbols); }
public SymbolFeed(string market, SymbolInfo symbol) { this.Symbol = symbol; this.Market = market; }
public static SemanticInfoSummary GetSemanticInfoSummary(this SemanticModel semanticModel, SyntaxNode node) { SemanticInfoSummary summary = new SemanticInfoSummary(); // The information that is available varies by the type of the syntax node. SymbolInfo symbolInfo = SymbolInfo.None; if (node is ExpressionSyntax expr) { symbolInfo = semanticModel.GetSymbolInfo(expr); summary.ConstantValue = semanticModel.GetConstantValue(expr); var typeInfo = semanticModel.GetTypeInfo(expr); summary.Type = typeInfo.Type; summary.ConvertedType = typeInfo.ConvertedType; summary.Nullability = typeInfo.Nullability; summary.ConvertedNullability = typeInfo.ConvertedNullability; summary.ImplicitConversion = semanticModel.GetConversion(expr); summary.MemberGroup = semanticModel.GetMemberGroup(expr); } else if (node is AttributeSyntax attribute) { symbolInfo = semanticModel.GetSymbolInfo(attribute); var typeInfo = semanticModel.GetTypeInfo(attribute); summary.Type = typeInfo.Type; summary.ConvertedType = typeInfo.ConvertedType; summary.ImplicitConversion = semanticModel.GetConversion(attribute); summary.MemberGroup = semanticModel.GetMemberGroup(attribute); } else if (node is OrderingSyntax ordering) { symbolInfo = semanticModel.GetSymbolInfo(ordering); } else if (node is SelectOrGroupClauseSyntax selectOrGroupClause) { symbolInfo = semanticModel.GetSymbolInfo(selectOrGroupClause); } else if (node is ConstructorInitializerSyntax initializer) { symbolInfo = semanticModel.GetSymbolInfo(initializer); var typeInfo = semanticModel.GetTypeInfo(initializer); summary.Type = typeInfo.Type; summary.ConvertedType = typeInfo.ConvertedType; summary.ImplicitConversion = semanticModel.GetConversion(initializer); summary.MemberGroup = semanticModel.GetMemberGroup(initializer); } else if (node is PatternSyntax pattern) { symbolInfo = semanticModel.GetSymbolInfo(pattern); var typeInfo = semanticModel.GetTypeInfo(pattern); summary.Type = typeInfo.Type; summary.ConvertedType = typeInfo.ConvertedType; summary.Nullability = typeInfo.Nullability; summary.ConvertedNullability = typeInfo.ConvertedNullability; summary.ImplicitConversion = semanticModel.GetConversion(pattern); summary.MemberGroup = semanticModel.GetMemberGroup(pattern); } else { throw ExceptionUtilities.UnexpectedValue(node); } summary.Symbol = symbolInfo.Symbol; summary.CandidateReason = symbolInfo.CandidateReason; summary.CandidateSymbols = symbolInfo.CandidateSymbols; if (node is IdentifierNameSyntax identifier) { summary.Alias = semanticModel.GetAliasInfo(identifier); } return(summary); }
private SymbolInfo GetSymbolInfo(LinkerSymbol linkerSymbol) { SymbolInfo symbolInfo = null; lock (symbolData) { if (!symbolData.TryGetValue(linkerSymbol, out symbolInfo)) { symbolInfo = new SymbolInfo(); symbolData.Add(linkerSymbol, symbolInfo); } } return symbolInfo; }
private bool TryClassifyValueIdentifier( NameSyntax name, SymbolInfo symbolInfo, out IEnumerable<ClassifiedSpan> result) { var identifierName = name as IdentifierNameSyntax; if (symbolInfo.Symbol.IsImplicitValueParameter()) { result = SpecializedCollections.SingletonEnumerable( new ClassifiedSpan(identifierName.Identifier.Span, ClassificationTypeNames.Keyword)); return true; } result = null; return false; }
private static bool IsInterfaceMember(SymbolInfo symbolInfo) { return(symbolInfo.Symbol?.ContainingType?.TypeKind == TypeKind.Interface); }
public static ISymbol?GetAnySymbol(this SymbolInfo info) => Shared.Extensions.SymbolInfoExtensions.GetAnySymbol(info);
private unsafe void TimeAndSalesUpdate(PacketMBTQuotes packet) { SymbolHandler handler = null; MemoryStream data = packet.Data; data.Position += 2; string time = null; string date = null; SymbolInfo symbolInfo = null; fixed(byte *bptr = data.GetBuffer()) { byte *ptr = bptr + data.Position; while (ptr - bptr < data.Length) { int key = packet.GetKey(ref ptr); switch (key) { case 1003: // Symbol string symbol = packet.GetString(ref ptr); symbolInfo = Factory.Symbol.LookupSymbol(symbol); handler = symbolHandlers[symbolInfo.BinaryIdentifier]; break; case 2014: // Time time = packet.GetString(ref ptr); break; case 2015: // Date date = packet.GetString(ref ptr); break; case 2002: // Last Trade Price handler.Last = packet.GetDouble(ref ptr); if (trace) { log.Trace("Got last trade price: " + handler.Last); // + "\n" + packet); } break; case 2007: // Last Trade Size handler.LastSize = packet.GetInt(ref ptr); break; case 2082: // Condition int condition = packet.GetInt(ref ptr); if (condition != 0 && condition != 53 && condition != 45) { log.Info("Trade quote received with non-zero condition: " + condition); } break; case 2083: // Status int status = packet.GetInt(ref ptr); if (status != 0) { log.Info("Trade quote received with non-zero status: " + status); } break; case 2084: // Type int type = packet.GetInt(ref ptr); if (type != 0) { log.Info("Trade quote received with non-zero type: " + type); } break; default: packet.SkipValue(ref ptr); break; } if (*(ptr - 1) == 10) { if (UseLocalTickTime) { var currentTime = TimeStamp.UtcNow; if (currentTime <= prevTime) { currentTime.Internal = prevTime.Internal + 1; } prevTime = currentTime; handler.Time = currentTime; } else { var strings = date.Split(new char[] { '/' }); date = strings[2] + "/" + strings[0] + "/" + strings[1]; handler.Time = new TimeStamp(date + " " + time); } if (handler.Last == 0D) { log.Warn("About to call SendTimeAndSales with Last price = zero."); } handler.SendTimeAndSales(); data.Position++; return; } } } throw new ApplicationException("Expected Trade Quote to end with new line character."); }
private static bool IsProperty(SymbolInfo symbolInfo) { return(symbolInfo.Symbol?.Kind == SymbolKind.Property); }
private void HandleNamedType(SymbolAnalysisContext context) { INamedTypeSymbol symbol = (INamedTypeSymbol)context.Symbol; if (symbol.TypeKind != TypeKind.Class) { return; } if (!symbol.IsExtensibleJsonObject()) { return; } foreach (var propertySymbol in symbol.GetMembers().OfType <IPropertySymbol>()) { if (propertySymbol.SetMethod != null) { continue; } var locations = propertySymbol.Locations; if (locations.IsDefaultOrEmpty) { continue; } var tree = locations[0].SourceTree; if (tree == null) { continue; } var root = tree.GetRoot(context.CancellationToken); var node = root.FindNode(locations[0].SourceSpan, getInnermostNodeForTie: true); var propertySyntax = node.FirstAncestorOrSelf <PropertyDeclarationSyntax>(); var getter = propertySyntax.AccessorList?.Accessors.FirstOrDefault(i => i.Keyword.IsKind(SyntaxKind.GetKeyword)); if (getter?.Body?.Statements.Count == 1) { ReturnStatementSyntax returnStatement = getter?.Body?.Statements.FirstOrDefault() as ReturnStatementSyntax; ExpressionSyntax returnExpression = returnStatement.Expression; if (returnExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { MemberAccessExpressionSyntax memberAccess = (MemberAccessExpressionSyntax)returnExpression; if (!memberAccess.Expression.IsKind(SyntaxKind.ThisExpression)) { continue; } } SymbolInfo symbolInfo = context.Compilation.GetSemanticModel(tree).GetSymbolInfo(returnExpression, context.CancellationToken); IFieldSymbol fieldSymbol = symbolInfo.Symbol as IFieldSymbol; if (fieldSymbol.ContainingType != propertySymbol.ContainingType) { continue; } context.ReportDiagnostic(Diagnostic.Create(Descriptor, locations.FirstOrDefault(), locations.Skip(1))); } } }
private static void CreateDiagnosticIfExpressionsMatch(SyntaxNodeAnalysisContext context, Location diagnosticLocation, SymbolInfo ifConditionIdentifier, SymbolInfo memberAccessIdentifier) { if ((ifConditionIdentifier.Symbol ?? memberAccessIdentifier.Symbol) == null) return; if (ifConditionIdentifier.Equals(memberAccessIdentifier)) { var diagnostic = Diagnostic.Create(Rule, diagnosticLocation, "You can use the existence operator."); context.ReportDiagnostic(diagnostic); } }
private bool InfoBoundSuccessfully(SymbolInfo symbolInfo) { return(InfoBoundSuccessfully(symbolInfo.Symbol)); }
protected override void OnTestMethod(SyntaxNodeAnalysisContext context, MethodDeclarationSyntax methodDeclaration, IMethodSymbol methodSymbol, bool isDataTestMethod) { int dynamicDataCount = 0; int dataRowCount = 0; bool hasTestSource = false; foreach (AttributeSyntax attribute in methodDeclaration.AttributeLists.SelectMany(x => x.Attributes)) { if (Helper.IsDataRowAttribute(attribute, context)) { dataRowCount++; continue; } if (Helper.IsAttribute(attribute, context, MsTestFrameworkDefinitions.DynamicDataAttribute, out _, out _)) { dynamicDataCount++; continue; } SymbolInfo symbol = context.SemanticModel.GetSymbolInfo(attribute); if (symbol.Symbol != null && symbol.Symbol is IMethodSymbol method) { if (method.ContainingType.AllInterfaces.Contains(Definitions.ITestSourceSymbol)) { hasTestSource = true; } } } if (isDataTestMethod) { if (dataRowCount != 0 && dynamicDataCount == 0) { return; } if (dataRowCount == 0 && dynamicDataCount == 1) { return; } if (dataRowCount != 0 && dynamicDataCount != 0) { context.ReportDiagnostic(Diagnostic.Create(Rule, methodDeclaration.Identifier.GetLocation(), methodDeclaration.Identifier.ToString(), dataRowCount, dynamicDataCount)); } else if (!hasTestSource) { context.ReportDiagnostic(Diagnostic.Create(RuleShouldBeTestMethod, methodDeclaration.Identifier.GetLocation())); } } else { if (dataRowCount == 0 && dynamicDataCount == 0) { return; } context.ReportDiagnostic(Diagnostic.Create(RuleShouldBeDataTestMethod, methodDeclaration.Identifier.GetLocation())); } }
private unsafe void Level1Update(PacketMBTQuotes packet) { SymbolHandler handler = null; MemoryStream data = packet.Data; data.Position += 2; string time = null; string date = null; fixed(byte *bptr = data.GetBuffer()) { byte *ptr = bptr + data.Position; while (ptr - bptr < data.Length) { int key = packet.GetKey(ref ptr); switch (key) { case 1003: // Symbol string symbol = packet.GetString(ref ptr); SymbolInfo symbolInfo = Factory.Symbol.LookupSymbol(symbol); handler = symbolHandlers[symbolInfo.BinaryIdentifier]; break; case 2014: // Time time = packet.GetString(ref ptr); break; case 2015: // Date date = packet.GetString(ref ptr); break; case 2003: // Bid handler.Bid = packet.GetDouble(ref ptr); break; case 2004: // Ask handler.Ask = packet.GetDouble(ref ptr); break; case 2005: // Bid Size handler.AskSize = packet.GetInt(ref ptr); break; case 2006: // Ask Size handler.BidSize = packet.GetInt(ref ptr); break; default: packet.SkipValue(ref ptr); break; } if (*(ptr - 1) == 10) { if (UseLocalTickTime) { var currentTime = TimeStamp.UtcNow; if (currentTime == prevTime) { currentTime.Internal = prevTime.Internal + 1; } prevTime = currentTime; handler.Time = currentTime; } else { var strings = date.Split(new char[] { '/' }); date = strings[2] + "/" + strings[0] + "/" + strings[1]; handler.Time = new TimeStamp(date + " " + time); } handler.SendQuote(); data.Position++; return; } } } throw new ApplicationException("Expected Level 1 Quote to end with new line character. Packet:\n" + packet); }
private static bool AreEquals( SemanticModel semanticModel1, SemanticModel semanticModel2, SymbolInfo info1, SymbolInfo info2) { if (semanticModel1 == semanticModel2) { return EqualityComparer<ISymbol>.Default.Equals(info1.Symbol, info2.Symbol); } else { return SymbolEquivalenceComparer.Instance.Equals(info1.Symbol, info2.Symbol); } }
private static bool IsMethod(SymbolInfo symbolInfo) { return(symbolInfo.Symbol?.Kind == SymbolKind.Method); }
private static ImmutableArray<ISymbol> GetSymbolsOffOfBoundExpression( CSharpSyntaxContext context, ExpressionSyntax originalExpression, ExpressionSyntax expression, SymbolInfo leftHandBinding, INamespaceOrTypeSymbol container, CancellationToken cancellationToken) { var useBaseReferenceAccessibility = false; var excludeInstance = false; var excludeStatic = false; var symbol = leftHandBinding.GetBestOrAllSymbols().FirstOrDefault(); if (symbol != null) { // If the thing on the left is a type, namespace or alias and the original // expression was parenthesized, we shouldn't show anything in IntelliSense. if (originalExpression.IsKind(SyntaxKind.ParenthesizedExpression) && symbol.MatchesKind(SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Alias)) { return ImmutableArray<ISymbol>.Empty; } // If the thing on the left is a lambda expression, we shouldn't show anything. if (symbol.Kind == SymbolKind.Method && ((IMethodSymbol)symbol).MethodKind == MethodKind.AnonymousFunction) { return ImmutableArray<ISymbol>.Empty; } // If the thing on the left is an event that can't be used as a field, we shouldn't show anything if (symbol.Kind == SymbolKind.Event && !context.SemanticModel.IsEventUsableAsField(originalExpression.SpanStart, (IEventSymbol)symbol)) { return ImmutableArray<ISymbol>.Empty; } // If the thing on the left is a this parameter (e.g. this or base) and we're in a static context, // we shouldn't show anything if (symbol.IsThisParameter() && expression.IsInStaticContext()) { return ImmutableArray<ISymbol>.Empty; } // What is the thing on the left? switch (symbol.Kind) { case SymbolKind.NamedType: case SymbolKind.Namespace: excludeInstance = true; container = (INamespaceOrTypeSymbol)symbol; break; case SymbolKind.Alias: excludeInstance = true; container = ((IAliasSymbol)symbol).Target; break; case SymbolKind.Parameter: var parameter = (IParameterSymbol)symbol; excludeStatic = true; // case: // base.| if (parameter.IsThis && !object.Equals(parameter.Type, container)) { useBaseReferenceAccessibility = true; } break; default: excludeStatic = true; break; } } else if (container != null) { excludeStatic = true; } else { return ImmutableArray<ISymbol>.Empty; } Debug.Assert(!excludeInstance || !excludeStatic); Debug.Assert(!excludeInstance || !useBaseReferenceAccessibility); // nameof(X.| // Show static and instance members. if (context.IsNameOfContext) { excludeInstance = false; excludeStatic = false; } var position = originalExpression.SpanStart; var symbols = useBaseReferenceAccessibility ? context.SemanticModel.LookupBaseMembers(position) : excludeInstance ? context.SemanticModel.LookupStaticMembers(position, container) : SuppressDefaultTupleElements(container, context.SemanticModel.LookupSymbols(position, container, includeReducedExtensionMethods: true)); // If we're showing instance members, don't include nested types return excludeStatic ? symbols.WhereAsArray(s => !s.IsStatic && !(s is ITypeSymbol)) : symbols; }
void IReferenceSourceProvider.Navigate(SymbolInfo symbol) { LastSymbol = symbol; }
//Returns the valueClause of the return statement from SupportedDiagnostics and the return declaration, empty list if failed private SuppDiagReturnSymbolInfo SuppDiagReturnSymbol(CompilationAnalysisContext context, SymbolInfo returnSymbolInfo, Location getAccessorKeywordLocation, PropertyDeclarationSyntax propertyDeclaration) { SuppDiagReturnSymbolInfo result = new SuppDiagReturnSymbolInfo(); ILocalSymbol returnSymbol = null; if (returnSymbolInfo.CandidateSymbols.Count() == 0) { returnSymbol = returnSymbolInfo.Symbol as ILocalSymbol; } else { returnSymbol = returnSymbolInfo.CandidateSymbols[0] as ILocalSymbol; } if (returnSymbol == null) { ReportDiagnostic(context, IncorrectAccessorReturnRule, getAccessorKeywordLocation); return result; } var variableDeclaration = returnSymbol.DeclaringSyntaxReferences[0].GetSyntax() as VariableDeclaratorSyntax; ReturnStatementSyntax returnDeclaration = returnSymbol.DeclaringSyntaxReferences[0].GetSyntax() as ReturnStatementSyntax; if (variableDeclaration == null) { ReportDiagnostic(context, IncorrectAccessorReturnRule, returnSymbol.Locations[0]); return result; } var equalsValueClause = variableDeclaration.Initializer as EqualsValueClauseSyntax; if (equalsValueClause == null) { ReportDiagnostic(context, IncorrectAccessorReturnRule, variableDeclaration.GetLocation()); return result; } var valueClause = equalsValueClause.Value as InvocationExpressionSyntax; if (valueClause == null) { ReportDiagnostic(context, IncorrectAccessorReturnRule, variableDeclaration.GetLocation()); return result; } var valueClauseMemberAccess = valueClause.Expression as MemberAccessExpressionSyntax; if (valueClauseMemberAccess == null) { ReportDiagnostic(context, IncorrectAccessorReturnRule, valueClause.GetLocation()); return result; } var valueClauseExpression = valueClauseMemberAccess.Expression as IdentifierNameSyntax; if (valueClauseExpression == null || valueClauseExpression.Identifier.Text != "ImmutableArray") { ReportDiagnostic(context, IncorrectAccessorReturnRule, valueClause.GetLocation()); return result; } var valueClauseName = valueClauseMemberAccess.Name as IdentifierNameSyntax; if (valueClauseName == null || valueClauseName.Identifier.Text != "Create") { ReportDiagnostic(context, SuppDiagReturnValueRule, valueClauseName.GetLocation(), propertyDeclaration.Identifier.Text); return result; } result.ValueClause = valueClause; result.ReturnDeclaration = returnDeclaration; return result; }
public void Reset() { LastSymbol = null; }