예제 #1
0
        //private Queue<Location> CreatePathFrom(Location start)
        //{
        //    var synclist = Locations;
        //    var position = synclist.FindIndex(l => l == start);
        //    var queue = new Queue<Location>(synclist);
        //    for (int i = 0; i < position; i++)
        //        queue.Dequeue();
        //    return queue;
        //}
        public override void OnStart()
        {
            LastIndex = 0;
            currentLocation = null;
            Locations.Clear();

            Print("Starting breadcrumb system!");

            var tank = WoWParty.Members.OrderByDescending(m => m.MaxHealth).First() ?? WoWUnit.Invalid;
            if (tank.IsValid)
            {
                if (tank.InLoS)
                {
                    FollowUnit = tank;
                    UnitFacing = tank.Facing;
                    Locations.Add(FollowUnit.Location);
                    currentLocation = Locations[0];
                }
                else
                {
                    Print("Get in LoS of {0}.", tank.Name);
                    Stop();
                }
            }
            else
            {
                Print("No suitable unit to follow found, are you in group?");
                Stop();
            }
        }
예제 #2
0
 public IntValueNode(Location?location, byte value)
 {
     Location    = location;
     _byteValue  = value;
     _shortValue = value;
 }
예제 #3
0
 public EdgeLabel(string text, Location?location)
 {
     this.text     = text;
     this.location = location;
 }
예제 #4
0
        public void EmitPredefined(EmitContext ec, MethodSpec method, Arguments Arguments, bool statement = false, Location?loc = null)
        {
            Expression instance_copy = null;

            if (!HasAwaitArguments && ec.HasSet(BuilderContext.Options.AsyncBody))
            {
                HasAwaitArguments = Arguments != null && Arguments.ContainsEmitWithAwait();
                if (HasAwaitArguments && InstanceExpressionOnStack)
                {
                    throw new NotSupportedException();
                }
            }

            OpCode         call_op;
            LocalTemporary lt = null;

            if (method.IsStatic)
            {
                call_op = OpCodes.Call;
            }
            else
            {
                call_op = IsVirtualCallRequired(InstanceExpression, method) ? OpCodes.Callvirt : OpCodes.Call;

                if (HasAwaitArguments)
                {
                    instance_copy = InstanceExpression.EmitToField(ec);
                    var ie = new InstanceEmitter(instance_copy, IsAddressCall(instance_copy, call_op, method.DeclaringType));

                    if (Arguments == null)
                    {
                        ie.EmitLoad(ec, true);
                    }
                }
                else if (!InstanceExpressionOnStack)
                {
                    var ie = new InstanceEmitter(InstanceExpression, IsAddressCall(InstanceExpression, call_op, method.DeclaringType));
                    ie.Emit(ec, ConditionalAccess);

                    if (DuplicateArguments)
                    {
                        ec.Emit(OpCodes.Dup);
                        if (Arguments != null && Arguments.Count != 0)
                        {
                            lt = new LocalTemporary(ie.GetStackType(ec));
                            lt.Store(ec);
                            instance_copy = lt;
                        }
                    }
                }
            }

            if (Arguments != null && !InstanceExpressionOnStack)
            {
                EmittedArguments = Arguments.Emit(ec, DuplicateArguments, HasAwaitArguments);
                if (EmittedArguments != null)
                {
                    if (instance_copy != null)
                    {
                        var ie = new InstanceEmitter(instance_copy, IsAddressCall(instance_copy, call_op, method.DeclaringType));
                        ie.Emit(ec, ConditionalAccess);

                        if (lt != null)
                        {
                            lt.Release(ec);
                        }
                    }

                    EmittedArguments.Emit(ec);
                }
            }

            if (call_op == OpCodes.Callvirt && (InstanceExpression.Type.IsGenericParameter || InstanceExpression.Type.IsStructOrEnum))
            {
                ec.Emit(OpCodes.Constrained, InstanceExpression.Type);
            }

            if (loc != null)
            {
                //
                // Emit explicit sequence point for expressions like Foo.Bar () to help debugger to
                // break at right place when LHS expression can be stepped-into
                //
                ec.MarkCallEntry(loc.Value);
            }

            //
            // Set instance expression to actual result expression. When it contains await it can be
            // picked up by caller
            //
            InstanceExpression = instance_copy;

            if (method.Parameters.HasArglist)
            {
                var varargs_types = GetVarargsTypes(method, Arguments);
                ec.Emit(call_op, method, varargs_types);
            }
            else
            {
                //
                // If you have:
                // this.DoFoo ();
                // and DoFoo is not virtual, you can omit the callvirt,
                // because you don't need the null checking behavior.
                //
                ec.Emit(call_op, method);
            }

            //
            // Pop the return value if there is one and stack should be empty
            //
            if (statement && method.ReturnType.Kind != MemberKind.Void)
            {
                ec.Emit(OpCodes.Pop);
            }
        }
예제 #5
0
            /// <param name="symbol">The symbol to analyze.</param>
            /// <param name="reportDiagnostic">Action called to actually report a diagnostic.</param>
            /// <param name="isImplicitlyDeclaredConstructor">If the symbol is an implicitly declared constructor.</param>
            /// <param name="explicitLocation">A location to report the diagnostics for a symbol at. If null, then
            /// the location of the symbol will be used.</param>
            private void OnSymbolActionCore(ISymbol symbol, Action <Diagnostic> reportDiagnostic, bool isImplicitlyDeclaredConstructor, Location?explicitLocation = null)
            {
                Debug.Assert(IsPublicAPI(symbol));

                ApiName publicApiName = GetPublicApiName(symbol);

                _visitedApiList.TryAdd(publicApiName.Name, default);
                _visitedApiList.TryAdd(publicApiName.NameWithNullability, default);

                List <Location> locationsToReport = new List <Location>();

                if (explicitLocation != null)
                {
                    locationsToReport.Add(explicitLocation);
                }
                else
                {
                    var locations = isImplicitlyDeclaredConstructor ? symbol.ContainingType.Locations : symbol.Locations;
                    locationsToReport.AddRange(locations.Where(l => l.IsInSource));
                }

                ApiLine foundApiLine;

                if (_useNullability)
                {
                    var hasPublicApiEntryWithNullability = _publicApiMap.TryGetValue(publicApiName.NameWithNullability, out foundApiLine);
                    if (!hasPublicApiEntryWithNullability)
                    {
                        var hasPublicApiEntryWithoutNullability = _publicApiMap.TryGetValue(publicApiName.Name, out foundApiLine);
                        if (!hasPublicApiEntryWithoutNullability)
                        {
                            reportDeclareNewApi(symbol, isImplicitlyDeclaredConstructor, publicApiName.NameWithNullability);
                        }
                        else
                        {
                            reportAnnotateApi(symbol, isImplicitlyDeclaredConstructor, publicApiName, foundApiLine.IsShippedApi);
                        }
                    }
                }
                else
                {
                    var hasPublicApiEntryWithoutNullability = _publicApiMap.TryGetValue(publicApiName.Name, out foundApiLine);
                    if (!hasPublicApiEntryWithoutNullability)
                    {
                        reportDeclareNewApi(symbol, isImplicitlyDeclaredConstructor, publicApiName.Name);
                    }

                    if (publicApiName.Name != publicApiName.NameWithNullability)
                    {
                        // '#nullable enable' would be useful and should be set
                        reportDiagnosticAtLocations(ShouldAnnotateApiFilesRule, ImmutableDictionary <string, string> .Empty);
                    }
                }

                if (symbol.Kind == SymbolKind.Method)
                {
                    var method             = (IMethodSymbol)symbol;
                    var isMethodShippedApi = foundApiLine?.IsShippedApi == true;

                    // Check if a public API is a constructor that makes this class instantiable, even though the base class
                    // is not instantiable. That API pattern is not allowed, because it causes protected members of
                    // the base class, which are not considered public APIs, to be exposed to subclasses of this class.
                    if (!isMethodShippedApi &&
                        method.MethodKind == MethodKind.Constructor &&
                        method.ContainingType.TypeKind == TypeKind.Class &&
                        !method.ContainingType.IsSealed &&
                        method.ContainingType.BaseType != null &&
                        IsPublicApiCore(method.ContainingType.BaseType) &&
                        !CanTypeBeExtendedPublicly(method.ContainingType.BaseType))
                    {
                        string errorMessageName = GetErrorMessageName(method, isImplicitlyDeclaredConstructor);
                        ImmutableDictionary <string, string> propertyBag = ImmutableDictionary <string, string> .Empty;
                        var locations = isImplicitlyDeclaredConstructor ? method.ContainingType.Locations : method.Locations;
                        reportDiagnostic(Diagnostic.Create(ExposedNoninstantiableType, locations[0], propertyBag, errorMessageName));
                    }

                    // Flag public API with optional parameters that violate backcompat requirements: https://github.com/dotnet/roslyn/blob/master/docs/Adding%20Optional%20Parameters%20in%20Public%20API.md.
                    if (method.HasOptionalParameters())
                    {
                        foreach (var overload in method.GetOverloads())
                        {
                            if (!IsPublicAPI(overload))
                            {
                                continue;
                            }

                            // Don't flag overloads which have identical params (e.g. overloading a generic and non-generic method with same parameter types).
                            if (overload.Parameters.Length == method.Parameters.Length &&
                                overload.Parameters.Select(p => p.Type).SequenceEqual(method.Parameters.Select(p => p.Type)))
                            {
                                continue;
                            }

                            // RS0026: Symbol '{0}' violates the backcompat requirement: 'Do not add multiple overloads with optional parameters'. See '{1}' for details.
                            var overloadHasOptionalParams = overload.HasOptionalParameters();
                            if (overloadHasOptionalParams)
                            {
                                // Flag only if 'method' is a new unshipped API with optional parameters.
                                if (!isMethodShippedApi)
                                {
                                    string errorMessageName = GetErrorMessageName(method, isImplicitlyDeclaredConstructor);
                                    reportDiagnosticAtLocations(AvoidMultipleOverloadsWithOptionalParameters, ImmutableDictionary <string, string> .Empty, errorMessageName, AvoidMultipleOverloadsWithOptionalParameters.HelpLinkUri);
                                    break;
                                }
                            }

                            // RS0027: Symbol '{0}' violates the backcompat requirement: 'Public API with optional parameter(s) should have the most parameters amongst its public overloads'. See '{1}' for details.
                            if (method.Parameters.Length <= overload.Parameters.Length)
                            {
                                // 'method' is unshipped: Flag regardless of whether the overload is shipped/unshipped.
                                // 'method' is shipped:   Flag only if overload is unshipped and has no optional parameters (overload will already be flagged with RS0026)
                                if (!isMethodShippedApi)
                                {
                                    string errorMessageName = GetErrorMessageName(method, isImplicitlyDeclaredConstructor);
                                    reportDiagnosticAtLocations(OverloadWithOptionalParametersShouldHaveMostParameters, ImmutableDictionary <string, string> .Empty, errorMessageName, OverloadWithOptionalParametersShouldHaveMostParameters.HelpLinkUri);
                                    break;
                                }
                                else if (!overloadHasOptionalParams)
                                {
                                    var overloadPublicApiName = GetPublicApiName(overload);
                                    var isOverloadUnshipped   = !lookupPublicApi(overloadPublicApiName, out ApiLine overloadPublicApiLine) ||
                                                                !overloadPublicApiLine.IsShippedApi;
                                    if (isOverloadUnshipped)
                                    {
                                        string errorMessageName = GetErrorMessageName(method, isImplicitlyDeclaredConstructor);
                                        reportDiagnosticAtLocations(OverloadWithOptionalParametersShouldHaveMostParameters, ImmutableDictionary <string, string> .Empty, errorMessageName, OverloadWithOptionalParametersShouldHaveMostParameters.HelpLinkUri);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }

                return;

                // local functions
                void reportDiagnosticAtLocations(DiagnosticDescriptor descriptor, ImmutableDictionary <string, string> propertyBag, params object[] args)
                {
                    foreach (var location in locationsToReport)
                    {
                        reportDiagnostic(Diagnostic.Create(descriptor, location, propertyBag, args));
                    }
                }

                void reportDeclareNewApi(ISymbol symbol, bool isImplicitlyDeclaredConstructor, string publicApiName)
                {
                    // TODO: workaround for https://github.com/dotnet/wpf/issues/2690
                    if (publicApiName == "XamlGeneratedNamespace.GeneratedInternalTypeHelper" ||
                        publicApiName == "XamlGeneratedNamespace.GeneratedInternalTypeHelper.GeneratedInternalTypeHelper() -> void")
                    {
                        return;
                    }

                    // Unshipped public API with no entry in public API file - report diagnostic.
                    string errorMessageName = GetErrorMessageName(symbol, isImplicitlyDeclaredConstructor);
                    // Compute public API names for any stale siblings to remove from unshipped text (e.g. during signature change of unshipped public API).
                    var siblingPublicApiNamesToRemove = GetSiblingNamesToRemoveFromUnshippedText(symbol);
                    ImmutableDictionary <string, string> propertyBag = ImmutableDictionary <string, string> .Empty
                                                                       .Add(PublicApiNamePropertyBagKey, publicApiName)
                                                                       .Add(MinimalNamePropertyBagKey, errorMessageName)
                                                                       .Add(PublicApiNamesOfSiblingsToRemovePropertyBagKey, siblingPublicApiNamesToRemove);

                    reportDiagnosticAtLocations(DeclareNewApiRule, propertyBag, errorMessageName);
                }

                void reportAnnotateApi(ISymbol symbol, bool isImplicitlyDeclaredConstructor, ApiName publicApiName, bool isShipped)
                {
                    // Public API missing annotations in public API file - report diagnostic.
                    string errorMessageName = GetErrorMessageName(symbol, isImplicitlyDeclaredConstructor);
                    ImmutableDictionary <string, string> propertyBag = ImmutableDictionary <string, string> .Empty
                                                                       .Add(PublicApiNamePropertyBagKey, publicApiName.Name)
                                                                       .Add(PublicApiNameWithNullabilityPropertyBagKey, publicApiName.NameWithNullability)
                                                                       .Add(MinimalNamePropertyBagKey, errorMessageName)
                                                                       .Add(PublicApiIsShippedPropertyBagKey, isShipped ? "true" : "false");

                    reportDiagnosticAtLocations(AnnotateApiRule, propertyBag, errorMessageName);
                }

                bool lookupPublicApi(ApiName overloadPublicApiName, out ApiLine overloadPublicApiLine)
                {
                    if (_useNullability)
                    {
                        return(_publicApiMap.TryGetValue(overloadPublicApiName.NameWithNullability, out overloadPublicApiLine) ||
                               _publicApiMap.TryGetValue(overloadPublicApiName.Name, out overloadPublicApiLine));
                    }
                    else
                    {
                        return(_publicApiMap.TryGetValue(overloadPublicApiName.Name, out overloadPublicApiLine));
                    }
                }
            }
예제 #6
0
파일: Log.cs 프로젝트: benwitman/BuildXL
        /// <inheritdoc />
        protected override void InspectMessage(int logEventId, EventLevel level, string message, Location?location = null)
        {
            m_forwardDiagnosticsTo?.InspectMessage(logEventId, level, message, location);

            var diagnostic = new Diagnostic(logEventId, level, message, location);

            if (m_preserveLogEvents)
            {
                m_capturedDiagnostics.Enqueue(diagnostic);
            }

            foreach (var observer in m_messageObservers)
            {
                observer.OnMessage(diagnostic);
            }

            if (level.IsError())
            {
                Interlocked.Increment(ref m_errorCount);
            }
        }
예제 #7
0
 public void Warning(Location?loc, string message)
 {
     log.Message(Log.MsgKind.WARNING, loc, message);
 }
예제 #8
0
 public EnumValueNode(Location?location, string value)
 {
     Location = location;
     _value   = value ?? throw new ArgumentNullException(nameof(value));
 }
예제 #9
0
 public UnionTypeExtensionNode WithLocation(Location?location)
 {
     return(new UnionTypeExtensionNode(
                location, Name, Directives, Types));
 }
예제 #10
0
 public DijkstraData(Location?from, long cost)
 {
     From    = from;
     Cost    = cost;
     Oppened = false;
 }
예제 #11
0
 public GeometrySlowCollider(RWGeometry geometry, Location?location)
 {
     Geometry = geometry;
     Location = location ?? new Location();
 }
예제 #12
0
 public static IIntersectionable CreateFor(RWGeometry geometry, Location?location) =>
 geometry.FindChildById(SectionId.CollisionPLG, recursive: true) == null
     ? new GeometrySlowCollider(geometry, location)
     : new GeometryTreeCollider(geometry, location);
            void ILocationListener.OnLocationChanged(Location?location)
            {
                if (location?.Provider != LocationManager.GpsProvider)
                {
                    Accuracy = float.NaN;
                    return;
                }
                Accuracy = location.HasAccuracy ? location.Accuracy : float.NaN;
                if (_isNmeaSupported)
                {
                    return;
                }
                // Not all Android devices support reporting NMEA, so we'll fallback to just generating
                // simple RMC and GGA message so the provider continues to work across multiple devices
                // $GPRMC:
                List <string> values = new List <string>(12);

                values.Add("$GPRMC");
                DateTimeOffset d = DateTimeOffset.FromUnixTimeMilliseconds(location.Time);

                values.Add(d.ToString("hhmmss"));
                values.Add("A");
                var lat     = Math.Floor(Math.Abs(location.Latitude));
                var latfrac = (Math.Abs(location.Latitude) - lat) * 60;

                values.Add($"{lat.ToString("00")}{latfrac.ToString(CultureInfo.InvariantCulture)}");
                values.Add(location.Latitude < 0 ? "S" : "N");
                var lon     = Math.Floor(Math.Abs(location.Longitude));
                var lonfrac = (Math.Abs(location.Longitude) - lon) * 60;

                values.Add($"{lon.ToString("000")}{lonfrac.ToString(CultureInfo.InvariantCulture)}");
                values.Add(location.Longitude < 0 ? "W" : "E");
                values.Add(location.HasSpeed ? location.Speed.ToString(CultureInfo.InvariantCulture) : "");
                values.Add(location.HasBearing ? location.Bearing.ToString(CultureInfo.InvariantCulture) : "");
                values.Add(d.ToString("ddMMyy"));
                values.Add(""); //Variation
                values.Add(""); //East/West
                NmeaMessage?.Invoke(this, string.Join(",", values) + "\n");
                // $GPGGA:
                int satellites = 0;

                if (location.Extras != null && location.Extras.ContainsKey("satellites"))
                {
                    satellites = Convert.ToInt32(location.Extras.Get("satellites"));
                }
                values = new List <string>(13);
                values.Add("$GPGGA");
                values.Add(d.ToString("hhmmss"));
                values.Add($"{lat.ToString("00")}{latfrac.ToString(CultureInfo.InvariantCulture)}");
                values.Add(location.Latitude < 0 ? "S" : "N");
                values.Add($"{lon.ToString("000")}{lonfrac.ToString(CultureInfo.InvariantCulture)}");
                values.Add(location.Longitude < 0 ? "W" : "E");
                values.Add("1");                   //Fix Quality:
                values.Add(satellites.ToString()); //Number of Satellites
                values.Add("");                    //HDOP
                values.Add(location.HasAltitude ? location.Altitude.ToString(CultureInfo.InvariantCulture) : "");
                values.Add("M");                   //Altitude units
                values.Add("");                    //Height of geoid above WGS84 ellipsoid
                values.Add("");                    //Geoid height units
                values.Add("");                    //Time since last DGPS update
                values.Add("");                    //DGPS reference station id
                NmeaMessage?.Invoke(this, string.Join(",", values) + "\n");
            }
예제 #14
0
 public CardButton(Location?i_CardLocation)
     : base()
 {
     r_CardLocation = i_CardLocation;
 }
예제 #15
0
 public override Tokenizer Tokenize(Character character)
 {
     if(location == null) {
         location = character.Location;
         startColumn = location.Value.Column;
         RootTokenizer.OnToken(
             parser => parser.ParseStringLiteral(() => stringBuilder.ToString(), GetStringLiteralRegion()));
     }
     if(justUninterpolated) {
         startColumn = character.Location.Column;
         justUninterpolated = false;
     }
     if(potentiallyInterpolated) {
         Tokenizer tokenizer;
         if(character.Char == '{') {
             stringBuilder.Append('{');
             tokenizer = this;
         } else {
             tokenizer = OnFirstInterpolatedCharacter(character);
         }
         potentiallyInterpolated = false;
         endColumn = character.Location.Column; // TODO get rid of this?
         return tokenizer;
     } else if(potentiallyUninterpolated) {
         if(character.Char == '}') {
             stringBuilder.Append('}');
             potentiallyUninterpolated = false;
         } else {
             OnError(character.Location, TokenizationError.UnexpectedRightCurlyBracket);
         }
         endColumn = character.Location.Column;
         return this;
     } else if(escaped) {
         OnEspacedCharacter(character);
         return this;
     } else {
         return OnRegularCharacter(character);
     }
 }
예제 #16
0
        public override void OnTick()
        {
            if (FollowUnit.IsValid)
            {
                var newFacing = FollowUnit.Facing;
                var span = DateTime.Now - LastAddition;
                if (Math.Abs(newFacing - UnitFacing) > 0.3f || (span.TotalSeconds > 2 && FollowUnit.Distance > 4f))
                {
                    Locations.Add(FollowUnit.Location);
                    UnitFacing = newFacing;
                    LastAddition = DateTime.Now;
                }
            }

            if (!Manager.LocalPlayer.IsCasting && !Manager.LocalPlayer.IsClickMoving)
            {
                currentLocation = Locations[LastIndex];
                if (currentLocation.HasValue && Manager.LocalPlayer.Location.DistanceTo(currentLocation.Value) < 3f && LastIndex + 1 < Locations.Count)
                    currentLocation = Locations[LastIndex++];

                if (currentLocation.HasValue && (FollowUnit.Distance > 6f || !FollowUnit.InLoS))
                {
                    Manager.LocalPlayer.ClickToMove(currentLocation.Value);
                }
            }
        }
예제 #17
0
 public static bool IsLocationMaskedToPlayer(Location?whichLocation, Player_?whichPlayer) => throw new NotImplementedException();
예제 #18
0
 public void Message(Location?loc, string message)
 {
     log.Message(Log.MsgKind.MESSAGE, loc, message);
 }
예제 #19
0
 /// <summary>
 /// Hook for inspecting log messages on a logger
 /// </summary>
 protected virtual void InspectMessage(int logEventId, EventLevel level, string message, Location?location = null)
 {
     // Do nothing. Must be overridden to enable this functionality.
 }
예제 #20
0
 public void Error(Location?loc, string message)
 {
     log.Message(Log.MsgKind.ERROR, loc, message);
 }
예제 #21
0
 protected Expr(Location?location)
 {
     Location = location ?? new Location(0, 0);
 }
예제 #22
0
            /// <param name="symbol">The symbol to analyze. Will also analyze implicit constructors too.</param>
            /// <param name="reportDiagnostic">Action called to actually report a diagnostic.</param>
            /// <param name="explicitLocation">A location to report the diagnostics for a symbol at. If null, then
            /// the location of the symbol will be used.</param>
            private void OnSymbolActionCore(ISymbol symbol, Action <Diagnostic> reportDiagnostic, Location?explicitLocation = null)
            {
                if (!IsPublicAPI(symbol))
                {
                    return;
                }

                Debug.Assert(!symbol.IsImplicitlyDeclared);
                OnSymbolActionCore(symbol, reportDiagnostic, isImplicitlyDeclaredConstructor: false, explicitLocation: explicitLocation);

                // Handle implicitly declared public constructors.
                if (symbol.Kind == SymbolKind.NamedType)
                {
                    var namedType = (INamedTypeSymbol)symbol;
                    if (namedType.InstanceConstructors.Length == 1 &&
                        (namedType.TypeKind == TypeKind.Class || namedType.TypeKind == TypeKind.Struct))
                    {
                        var instanceConstructor = namedType.InstanceConstructors[0];
                        if (instanceConstructor.IsImplicitlyDeclared)
                        {
                            OnSymbolActionCore(instanceConstructor, reportDiagnostic, isImplicitlyDeclaredConstructor: true, explicitLocation: explicitLocation);
                        }
                    }
                }
            }
예제 #23
0
 protected internal GeoEntity(IPAddress query, IPSubnetBlock block, Location?location)
 {
     Query    = query;
     Block    = block;
     Location = location;
 }
예제 #24
0
 public DocumentNode WithLocation(Location? location)
 {
     return new DocumentNode(location, Definitions);
 }
 public OperationTypeDefinitionNode WithLocation(Location?location)
 {
     return(new OperationTypeDefinitionNode(
                location, Operation, Type));
 }
예제 #26
0
 public EdgeLabel(string text)
 {
     this.text     = text;
     this.location = null;
 }
        public override BoundNode?VisitLocalFunctionStatement(BoundLocalFunctionStatement localFunc)
        {
            if (localFunc.Symbol.IsExtern)
            {
                // an extern local function is not permitted to have a body and thus shouldn't be flow analyzed
                return(null);
            }

            var oldSymbol       = this.CurrentSymbol;
            var localFuncSymbol = localFunc.Symbol;

            this.CurrentSymbol = localFuncSymbol;

            var oldPending = SavePending(); // we do not support branches into a lambda

            // SPEC: The entry point to a local function is always reachable.
            // Captured variables are definitely assigned if they are definitely assigned on
            // all branches into the local function.

            var savedState = this.State;

            this.State = this.TopState();

            Optional <TLocalState> savedNonMonotonicState = NonMonotonicState;

            if (_nonMonotonicTransfer)
            {
                NonMonotonicState = ReachableBottomState();
            }

            if (!localFunc.WasCompilerGenerated)
            {
                EnterParameters(localFuncSymbol.Parameters);
            }

            // State changes to captured variables are recorded, as calls to local functions
            // transition the state of captured variables if the variables have state changes
            // across all branches leaving the local function

            var localFunctionState      = GetOrCreateLocalFuncUsages(localFuncSymbol);
            var savedLocalFunctionState = LocalFunctionStart(localFunctionState);

            var oldPending2 = SavePending();

            // If this is an iterator, there's an implicit branch before the first statement
            // of the function where the enumerable is returned.
            if (localFuncSymbol.IsIterator)
            {
                PendingBranches.Add(new PendingBranch(null, this.State, null));
            }

            VisitAlways(localFunc.Body);
            RestorePending(oldPending2); // process any forward branches within the lambda body
            ImmutableArray <PendingBranch> pendingReturns = RemoveReturns();

            RestorePending(oldPending);

            Location?location = null;

            if (!localFuncSymbol.Locations.IsDefaultOrEmpty)
            {
                location = localFuncSymbol.Locations[0];
            }

            LeaveParameters(localFuncSymbol.Parameters, localFunc.Syntax, location);

            // Intersect the state of all branches out of the local function
            var stateAtReturn = this.State;

            foreach (PendingBranch pending in pendingReturns)
            {
                this.State = pending.State;
                BoundNode branch = pending.Branch;

                // Pass the local function identifier as a location if the branch
                // is null or compiler generated.
                LeaveParameters(localFuncSymbol.Parameters,
                                branch?.Syntax,
                                branch?.WasCompilerGenerated == false ? null : location);

                Join(ref stateAtReturn, ref this.State);
            }

            // Record any changes to the state of captured variables
            if (RecordStateChange(
                    savedLocalFunctionState,
                    localFunctionState,
                    ref stateAtReturn) &&
                localFunctionState.Visited)
            {
                // If the sets have changed and we already used the results
                // of this local function in another computation, the previous
                // calculations may be invalid. We need to analyze until we
                // reach a fixed-point.
                stateChangedAfterUse       = true;
                localFunctionState.Visited = false;
            }

            this.State         = savedState;
            NonMonotonicState  = savedNonMonotonicState;
            this.CurrentSymbol = oldSymbol;

            return(null);
        }
예제 #28
0
파일: Extensions.cs 프로젝트: IustinT/shiny
 public static void Log(this GeneratorExecutionContext context, string id, string message, DiagnosticSeverity severity = DiagnosticSeverity.Warning, Location?location = null)
 {
     location ??= Location.None;
     context.ReportDiagnostic(
         Diagnostic.Create(
             new DiagnosticDescriptor(
                 id,
                 message,
                 message,
                 "Shiny",
                 severity,
                 true
                 ),
             location
             )
         );
 }
예제 #29
0
 public ListTypeNode WithLocation(Location?location)
 {
     return(new ListTypeNode(location, Type));
 }
예제 #30
0
파일: IGeoLookup.cs 프로젝트: itadapter/nfx
 protected internal GeoEntity(IPAddress query, IPSubnetBlock block, Location? location)
 {
     Query = query;
       Block = block;
       Location = location;
 }
예제 #31
0
 private void Diag(DiagnosticDescriptor desc, Location?location, params object?[]?messageArgs)
 {
     _reportDiagnostic(Diagnostic.Create(desc, location, messageArgs));
 }
예제 #32
0
 public EnumTypeExtensionNode WithLocation(Location?location)
 {
     return(new EnumTypeExtensionNode(
                location, Name,
                Directives, Values));
 }
            private bool AnalyzeMemberWithinContext(ITypeSymbol type, ISymbol?symbol, SyntaxNodeAnalysisContext context, Location?focusDiagnosticOn = null)
            {
                if (type is null)
                {
                    throw new ArgumentNullException(nameof(type));
                }

                bool requiresUIThread = (type.TypeKind == TypeKind.Interface || type.TypeKind == TypeKind.Class) &&
                                        this.MembersRequiringMainThread.Contains(type, symbol);

                if (requiresUIThread)
                {
                    ThreadingContext threadingContext  = ThreadingContext.Unknown;
                    SyntaxNode?      methodDeclaration = context.Node.FirstAncestorOrSelf <SyntaxNode>(n => CSharpCommonInterest.MethodSyntaxKinds.Contains(n.Kind()));
                    if (methodDeclaration is object)
                    {
                        threadingContext = this.methodDeclarationNodes.GetValueOrDefault(methodDeclaration);
                    }

                    if (threadingContext != ThreadingContext.MainThread)
                    {
                        CSharpUtils.ContainingFunctionData function = CSharpUtils.GetContainingFunction((CSharpSyntaxNode)context.Node);
                        Location             location   = focusDiagnosticOn ?? context.Node.GetLocation();
                        DiagnosticDescriptor?descriptor = function.IsAsync ? DescriptorAsync : DescriptorSync;
                        var formattingArgs = function.IsAsync ? new object[] { type.Name } : new object[] { type.Name, this.MainThreadAssertingMethods.FirstOrDefault() };
                        context.ReportDiagnostic(Diagnostic.Create(descriptor, location, this.DiagnosticProperties, formattingArgs));
                        return(true);
                    }
                }

                return(false);
            }
		//---------------------------------------------------------------------

		private void Initialize(IInputGrid<bool> activeSites)
		{
			this.firstActive = null;
			this.firstInactive = null;

			this.rowIntervals    = new List<Interval>();
			this.activeRows      = new List<ActiveRow>();
			this.columnIntervals = new List<Interval>();

			bool inRowInterval = false;
			Interval rowInterval = new Interval();
			for (uint row = 1; row <= activeSites.Rows; ++row) {
				uint colIntervalCount = 0;
				uint firstColIntervalIndex = 0;
				bool inColumnInterval = false;
				Interval columnInterval = new Interval();
				for (uint column = 1; column <= activeSites.Columns; ++column) {
					if (activeSites.ReadValue()) {
						this.count++;
						if (! this.firstActive.HasValue)
							this.firstActive = new Location(row, column);

						if (inColumnInterval) {
							//  extend column interval
							columnInterval.End = column;
						}
						else {
							//  start a new column interval
							columnInterval = new Interval(column, column,
							                              count - 1);
							inColumnInterval = true;
							colIntervalCount++;
							if (colIntervalCount == 1)
								firstColIntervalIndex = (uint)
														columnIntervals.Count;
						}
					}
					else {
						// current site is inactive
						if (! this.firstInactive.HasValue)
							this.firstInactive = new Location(row, column);

						if (inColumnInterval) {
							//  end of current column interval
							this.columnIntervals.Add(columnInterval);
							inColumnInterval = false;
						}
					}
				}  // for each column

				// at end of current row
				if (colIntervalCount > 0) {
					//  current row is an active row
					if (inColumnInterval) {
						//  last column was active, so add its interval
						this.columnIntervals.Add(columnInterval);
					}
					this.activeRows.Add(new ActiveRow(colIntervalCount,
					                             	  firstColIntervalIndex));
					if (inRowInterval) {
						//  extend row interval
						rowInterval.End = row;
					}
					else {
						//	start a new row interval
						rowInterval = new Interval(row, row,
						                           (uint)(activeRows.Count-1));
						inRowInterval = true;
					}
				}
				else {
					//	current row is not an active row
					if (inRowInterval) {
						this.rowIntervals.Add(rowInterval);
						inRowInterval = false;
					}
				}
			}  // for each row

			if (inRowInterval) {
				//	last row was an active row, so add its row interval
				this.rowIntervals.Add(rowInterval);
			}

			if (logger.IsDebugEnabled) {
				LogDebug("Active Site Map");
				LogDebug("");
				LogDebug("Input Grid: {0}", activeSites.Dimensions);
				LogDebug("");
				LogDebug("Row Intervals");
				LogDebug("  index: start to end (index of start row in active rows");
				for (int i = 0; i < rowIntervals.Count; i++) {
					Interval interval = rowIntervals[i];
					LogDebug("  {0}: {1} to {2} ({3})", i, interval.Start, interval.End, interval.StartOffset);
				}

				LogDebug("");
				LogDebug("Active Rows");
				LogDebug("  index: # column intervals, index of 1st column interval");
				for (int i = 0; i < activeRows.Count; i++) {
					ActiveRow activeRow = ActiveRows[i];
					LogDebug("  {0}: {1}, {2}", i, activeRow.IntervalCount, activeRow.FirstIntervalOffset);
				}

				LogDebug("");
				LogDebug("Column Intervals");
				LogDebug("  index: start to end (data index of start column");
				for (int i = 0; i < columnIntervals.Count; i++) {
					Interval interval = columnIntervals[i];
					LogDebug("  {0}: {1} to {2} ({3})", i, interval.Start, interval.End, interval.StartOffset);
				}
			}
		}
예제 #35
0
 public EnumValueNode WithLocation(Location?location)
 {
     return(new EnumValueNode(location, Value));
 }