Beispiel #1
0
        /// <summary>
        /// Register an action to be executed at completion of parsing of a code document. A syntax tree action reports
        /// diagnostics about the <see cref="SyntaxTree"/> of a document.
        /// </summary>
        /// <remarks>This method honors exclusions.</remarks>
        /// <param name="context">The analysis context.</param>
        /// <param name="action">Action to be executed at completion of parsing of a document.</param>
        public static void RegisterSyntaxTreeActionHonorExclusions(this CompilationStartAnalysisContext context, Action <SyntaxTreeAnalysisContext, StyleCopSettings> action)
        {
            Compilation compilation = context.Compilation;
            ConcurrentDictionary <SyntaxTree, bool> cache         = GetOrCreateGeneratedDocumentCache(compilation);
            StrongBox <StyleCopSettings>            settingsCache = GetOrCreateStyleCopSettingsCache(compilation);

            context.RegisterSyntaxTreeAction(
                c =>
            {
                if (c.IsGeneratedDocument(cache))
                {
                    return;
                }

                // Honor the containing document item's ExcludeFromStylecop=True
                // MSBuild metadata, if analyzers have access to it.
                //// TODO: code here

                StyleCopSettings settings = settingsCache.Value;
                if (settings == null)
                {
                    StyleCopSettings updatedSettings = SettingsHelper.GetStyleCopSettings(c.Options, c.CancellationToken);
                    StyleCopSettings previous        = Interlocked.CompareExchange(ref settingsCache.Value, updatedSettings, null);
                    settings = previous ?? updatedSettings;
                }

                action(c, settings);
            });
        }
Beispiel #2
0
            public unsafe void Read()
            {
                var   buffer = Writer.Alloc(2048);
                void *pointer;

                if (!buffer.Memory.TryGetPointer(out pointer))
                {
                    throw new InvalidOperationException("Memory needs to be pinned");
                }
                var data  = (IntPtr)pointer;
                var count = buffer.Memory.Length;

                var overlapped = ThreadPoolBoundHandle.AllocateNativeOverlapped(PreAllocatedOverlapped);

                overlapped->OffsetLow = Offset;

                Overlapped = overlapped;

                BoxedBuffer = new StrongBox <WritableBuffer>(buffer);

                int r = ReadFile(FileHandle, data, count, IntPtr.Zero, overlapped);

                // TODO: Error handling

                // 997
                int hr = Marshal.GetLastWin32Error();

                if (hr != 997)
                {
                    Writer.Complete(Marshal.GetExceptionForHR(hr));
                }
            }
Beispiel #3
0
            public ReferenceCountedDisposable <TTo> AddReference <TTo>() where TTo : class, IDisposable
            {
                WeakReference <T>?weakInstance = _weakInstance;

                if (weakInstance == null || !weakInstance.TryGetTarget(out var target))
                {
                    throw new ObjectDisposedException(nameof(WeakReference));
                }

                StrongBox <int>?referenceCount = _boxedReferenceCount;

                if (referenceCount == null)
                {
                    throw new ObjectDisposedException(nameof(WeakReference));
                }

                ReferenceCountedDisposable <TTo>?newReference =
                    TryAddReferenceImpl <T, TTo>(target, referenceCount, out CreateResult result);

                if (newReference != null)
                {
                    return(newReference);
                }

                throw result switch
                      {
                          CreateResult.Disposed => new ObjectDisposedException(nameof(ReferenceCountedDisposable <T>)),
                          CreateResult.NotCastable => new InvalidCastException(),
                          _ => new NotSupportedException("This exception should never be thrown.")
                      };
            }
        }
Beispiel #4
0
            /// <inheritdoc />
            public override async Task ExecuteAsync(Func <Task> operation, CancellationToken cancellationToken = default)
            {
                Requires.NotNull(operation, nameof(operation));
                this.ThrowIfFaulted();

                StrongBox <bool> ownedBox = this.reentrancyDetection.Value;

                if (ownedBox?.Value ?? false)
                {
                    throw Verify.FailOperation("Semaphore is already held and reentrancy setting is '{0}'.", ReentrancyMode.NotAllowed);
                }

                await this.ExecuteCoreAsync(async delegate
                {
                    using (this.joinableTaskCollection?.Join())
                    {
                        AsyncSemaphore.Releaser releaser = await this.semaphore.EnterAsync(cancellationToken).ConfigureAwait(true);
                        try
                        {
                            this.reentrancyDetection.Value = ownedBox = new StrongBox <bool>(true);
                            await operation().ConfigureAwaitRunInline();
                        }
                        finally
                        {
                            // Make it clear to any forks of our ExecutionContexxt that the semaphore is no longer owned.
                            ownedBox.Value = false;
                            DisposeReleaserNoThrow(releaser);
                        }
                    }
                });
            }
        /// <summary>
        /// Checks whether the given document is auto generated by a tool
        /// (based on filename or comment header).
        /// </summary>
        /// <remarks>
        /// <para>The exact conditions used to identify generated code are subject to change in future releases.
        /// The current algorithm uses the following checks.</para>
        /// <para>Code is considered generated if it meets any of the following conditions.</para>
        /// <list type="bullet">
        /// <item>The code is contained in a file which starts with a comment containing the text
        /// <c>&lt;auto-generated</c>.</item>
        /// <item>The code is contained in a file with a name matching certain patterns (case-insensitive):
        /// <list type="bullet">
        /// <item>*.designer.cs</item>
        /// </list>
        /// </item>
        /// </list>
        /// </remarks>
        /// <param name="tree">The syntax tree to examine.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that the task will observe.</param>
        /// <returns>
        /// <para><see langword="true"/> if <paramref name="tree"/> is located in generated code; otherwise,
        /// <see langword="false"/>. If <paramref name="tree"/> is <see langword="null"/>, this method returns
        /// <see langword="false"/>.</para>
        /// </returns>
        public static bool IsGeneratedDocument(this SyntaxTree tree, CancellationToken cancellationToken)
        {
            bool result = false;

            if (tree != null)
            {
                StrongBox <bool?> cachedResult = GeneratedHeaderPresentCheck.GetOrCreateValue(tree);
                if (cachedResult.Value.HasValue)
                {
                    result = cachedResult.Value.Value;
                }
                else
                {
                    bool autoGenerated = IsGeneratedDocumentNoCache(tree, cancellationToken);

                    // Update the strongbox's value with our computed result.
                    // This doesn't change the strongbox reference, and its presence in the
                    // ConditionalWeakTable is already assured, so we're updating in-place.
                    // In the event of a race condition with another thread that set the value,
                    // we'll just be re-setting it to the same value.
                    cachedResult.Value = autoGenerated;

                    result = autoGenerated;
                }
            }

            return(result);
        }
Beispiel #6
0
 internal void BoxLocals() {
     var boxedLocals = Interpreter._boxedLocals;
     for (int i = 0; i < boxedLocals.Length; i++) {
         int index = boxedLocals[i];
         Data[index] = new StrongBox<object>(Data[index]);
     }
 }
Beispiel #7
0
        public override int Run(InterpretedFrame frame)
        {
            StrongBox <object> box = frame.Closure[base._index];

            frame.Data[frame.StackIndex++] = box;
            return(1);
        }
        public static async Task WhenAny()
        {
            var box     = new StrongBox <int>(0);
            var source1 = new ValueTaskCompletionSource();
            var source2 = new ValueTaskCompletionSource();
            var source3 = new ValueTaskCompletionSource();

            ThreadPool.QueueUserWorkItem(state =>
            {
                box.Value.VolatileWrite(1);
                Thread.Sleep(50);
                source1.Complete();
            });
            ThreadPool.QueueUserWorkItem(state =>
            {
                box.Value.VolatileWrite(2);
                Thread.Sleep(200);
                source2.Complete();
            });
            ThreadPool.QueueUserWorkItem(state =>
            {
                box.Value.VolatileWrite(3);
                Thread.Sleep(150);
                source3.Complete();
            });
            var completedTask = await ValueTaskSynchronization.WhenAny(source1.Task, source2.Task, source3.Task);

            True(completedTask == source1.Task);
            False(completedTask == source2.Task);
            False(completedTask == source3.Task);
        }
        /// <summary>Creates a value for the current thread and stores it in the central list of values.</summary>
        /// <returns>The boxed value.</returns>
        private StrongBox <T> CreateValue()
        {
            var s = new StrongBox <T>(_seedFactory != null ? _seedFactory() : default(T));

            _values.Enqueue(s);
            return(s);
        }
        public void EqualityComparer_IEqualityComparerEqualsWithObjectsNotOfMatchingType()
        {
            // EqualityComparer<T> implements IEqualityComparer for back-compat reasons.
            // The explicit implementation of IEqualityComparer.Equals(object, object) should
            // throw if the inputs are not reference-equal, both non-null and either of them
            // is not of type T.
            IEqualityComparer comparer   = EqualityComparer <T> .Default;
            StrongBox <T>     notOfTypeT = new StrongBox <T>(default(T));

            Assert.True(comparer.Equals(default(T), default(T))); // This should not throw since both inputs will either be null or Ts.
            Assert.True(comparer.Equals(notOfTypeT, notOfTypeT)); // This should not throw since the inputs are reference-equal.

            // Null inputs should never raise an exception.
            Assert.Equal(default(T) == null, comparer.Equals(default(T), null));
            Assert.Equal(default(T) == null, comparer.Equals(null, default(T)));
            Assert.True(comparer.Equals(null, null));

            if (default(T) != null)                                                                               // if default(T) is null this assert will fail as IEqualityComparer.Equals returns early if either input is null
            {
                AssertExtensions.Throws <ArgumentException>(null, () => comparer.Equals(notOfTypeT, default(T))); // lhs is the problem
                AssertExtensions.Throws <ArgumentException>(null, () => comparer.Equals(default(T), notOfTypeT)); // rhs is the problem
            }

            if (!(notOfTypeT is T)) // catch cases where StrongBox<T> actually is a T, such as T == object
            {
                AssertExtensions.Throws <ArgumentException>(null, () => comparer.Equals(notOfTypeT, new StrongBox <T>(default(T))));
            }
        }
Beispiel #11
0
        public override int Run(InterpretedFrame frame)
        {
            StrongBox <object> box = frame.Closure[base._index];

            box.Value = frame.Peek();
            return(1);
        }
Beispiel #12
0
 internal StringSwitchInstruction(Dictionary <string, int> cases, StrongBox <int> nullCase)
 {
     Assert.NotNull(cases);
     Assert.NotNull(nullCase);
     _cases    = cases;
     _nullCase = nullCase;
 }
        public void TestCollectionConstructorUsesCorrectComparer()
        {
            var key1 = new StrongBox <int>(1);
            var key2 = new StrongBox <int>(2);

            KeyValuePair <StrongBox <int>, int>[] pairs =
            {
                new KeyValuePair <StrongBox <int>, int>(key1, 1),
                new KeyValuePair <StrongBox <int>, int>(key2, 2),
            };

            var comparer         = new ComparisonComparer <StrongBox <int> >((x, y) => Comparer <int> .Default.Compare(x.Value, y.Value));
            var objectDictionary = ImmutableSortedTreeDictionary.CreateRange(comparer, pairs);

            Assert.Same(comparer, objectDictionary.KeyComparer);
            Assert.Equal(2, objectDictionary.Count);
            Assert.Equal(new[] { new KeyValuePair <StrongBox <int>, int>(key1, 1), new KeyValuePair <StrongBox <int>, int>(key2, 2) }, objectDictionary);

            var stringDictionary = ImmutableSortedTreeDictionary.Create <string, int>();

            Assert.Same(Comparer <string> .Default, stringDictionary.KeyComparer);

            stringDictionary = ImmutableSortedTreeDictionary.Create <string, int>(StringComparer.OrdinalIgnoreCase);
            Assert.Same(StringComparer.OrdinalIgnoreCase, stringDictionary.KeyComparer);

            KeyValuePair <StrongBox <int>, int>[] pairsWithDuplicateKey =
            {
                new KeyValuePair <StrongBox <int>, int>(key1, 1),
                new KeyValuePair <StrongBox <int>, int>(key2, 2),
                new KeyValuePair <StrongBox <int>, int>(key1, 3),
            };

            Assert.Throws <ArgumentException>(() => ImmutableSortedTreeDictionary.CreateRange(comparer, pairsWithDuplicateKey));
        }
        public void Saving_Example()
        {
            using (var f = new TempfileLife()) {
                var rpath = JsonSettings.ResolvePath(f);

                StrongBox <int> saved = new StrongBox <int>(0);
                var             o     = JsonSettings.Load <ExampleNotifyingSettings>(f).EnableAutosave();
                saved.Value.Should().Be(0);
                o.AfterSave += (s, destinition) => { saved.Value++; };
                o.Residents.Add("Cookie Monster");                             //Boom! saves.
                saved.Value.Should().Be(1);
                o.Residents = new ObservableCollection <string>();             //Boom! saves.
                saved.Value.Should().Be(2);
                o.Residents.Add("Cookie Monster");                             //Boom! saves.
                saved.Value.Should().Be(3);
                o.NonAutosavingProperty = new ObservableCollection <object>(); //doesn't save
                o.NonAutosavingProperty.Add("Jim");                            //doesn't save
                saved.Value.Should().Be(3);
                o.Street += "-1";                                              //Boom! saves.
                saved.Value.Should().Be(4);
                o.AutoProperty = "Hello";                                      //Boom! saves.
                saved.Value.Should().Be(5);
                o.IgnoredFromAutosaving = "Hello";                             //doesn't save
                saved.Value.Should().Be(5);
            }
        }
        public static async Task ThrowInCatchBlock()
        {
            var result = new StrongBox <int>();
            var lambda = AsyncLambda <Func <StrongBox <int>, Task> >(fun =>
            {
                Try(() =>
                {
                    Await(Expression.Call(typeof(Task), nameof(Task.Yield), Type.EmptyTypes));
                    Throw <InvalidOperationException>();
                })
                .Catch(typeof(InvalidOperationException), e =>
                {
                    Throw <ArithmeticException>();
                })
                .Finally(() =>
                {
                    Assign(Expression.Field(fun[0], "Value"), 45.Const());
                })
                .End();
            }).Compile();

            await ThrowsAsync <ArithmeticException>(() => lambda(result));

            Equal(45, result.Value);
        }
Beispiel #16
0
        public void Case2()
        {
            using (var f = new TempfileLife()) {
                StrongBox <bool> saved = new StrongBox <bool>(false);
                var o = JsonSettings.Load <AutosaveTests.Settings>(f.FileName)
                        .EnableAutosave();
                o.AfterSave += (s, destinition) => { saved.Value = true; };
                var module = o.Modulation.GetModule <AutosaveModule>();

                //act
                module.AutosavingState.Should().Be(AutosavingState.Running);

                var suspender = o.SuspendAutosave();
                module.AutosavingState.Should().Be(AutosavingState.Suspended);

                saved.Value.ShouldBeEquivalentTo(false);
                o.property = "hi";
                saved.Value.ShouldBeEquivalentTo(false);
                module.AutosavingState.Should().Be(AutosavingState.SuspendedChanged);
                suspender.Resume();

                //resuming/disposing twice should have any effect
                saved.Value.ShouldBeEquivalentTo(true);
                saved.Value = false;
                suspender.Resume();
                saved.Value.ShouldBeEquivalentTo(false);
            }
        }
Beispiel #17
0
        private static XElement CreateElementForCompilation(Compilation compilation)
        {
            StrongBox <int> compilationId;

            if (!s_CompilationIds.TryGetValue(compilation, out compilationId))
            {
                compilationId = new StrongBox <int>(s_NextCompilationId++);
                s_CompilationIds.Add(compilation, compilationId);
            }

            var namespaces   = new Queue <INamespaceSymbol>();
            var typesElement = new XElement("types");

            namespaces.Enqueue(compilation.Assembly.GlobalNamespace);

            while (namespaces.Count > 0)
            {
                var @ns = namespaces.Dequeue();

                foreach (var type in @ns.GetTypeMembers())
                {
                    typesElement.Add(new XElement("type", new XAttribute("name", type.ToDisplayString())));
                }

                foreach (var childNamespace in @ns.GetNamespaceMembers())
                {
                    namespaces.Enqueue(childNamespace);
                }
            }

            return(new XElement("compilation",
                                new XAttribute("objectId", compilationId.Value),
                                new XAttribute("assemblyIdentity", compilation.Assembly.Identity.ToString()),
                                typesElement));
        }
Beispiel #18
0
 public DelayedTupleExpression(int index, StrongBox <ParameterExpression> tupleExpr, StrongBox <Type> tupleType, Type type)
 {
     Index      = index;
     _tupleType = tupleType;
     _tupleExpr = tupleExpr;
     _type      = type;
 }
Beispiel #19
0
        /// <summary>Creates a value for the current thread and stores it in the central list of values.</summary>
        /// <returns>The boxed value.</returns>
        private StrongBox <T> CreateValue()
        {
            StrongBox <T> item = new StrongBox <T>((this._seedFactory != null) ? this._seedFactory() : default(T));

            this._values.Enqueue(item);
            return(item);
        }
Beispiel #20
0
        private ReferenceCountedDisposable(T instance, StrongBox <int> referenceCount)
        {
            _instance = instance ?? throw new ArgumentNullException(nameof(instance));

            // The reference count has already been incremented for this instance
            _boxedReferenceCount = referenceCount;
        }
Beispiel #21
0
        internal static bool ContainsUsingAlias(this SyntaxTree tree)
        {
            if (tree == null)
            {
                return(false);
            }

            StrongBox <bool?> cachedResult = UsingAliasPresentCheck.GetOrCreateValue(tree);

            if (cachedResult.Value.HasValue)
            {
                return(cachedResult.Value.Value);
            }

            bool hasUsingAlias = ContainsUsingAliasNoCache(tree);

            // Update the strongbox's value with our computed result.
            // This doesn't change the strongbox reference, and its presence in the
            // ConditionalWeakTable is already assured, so we're updating in-place.
            // In the event of a race condition with another thread that set the value,
            // we'll just be re-setting it to the same value.
            cachedResult.Value = hasUsingAlias;

            return(hasUsingAlias);
        }
Beispiel #22
0
            public unsafe void Read()
            {
                var buffer = Writer.Alloc(2048);

                fixed(byte *source = &buffer.Buffer.Span.DangerousGetPinnableReference())
                {
                    var count = buffer.Buffer.Length;

                    var overlapped = ThreadPoolBoundHandle.AllocateNativeOverlapped(PreAllocatedOverlapped);

                    overlapped->OffsetLow = Offset;

                    Overlapped = overlapped;

                    BoxedBuffer = new StrongBox <WritableBuffer>(buffer);

                    int r = ReadFile(FileHandle, (IntPtr)source, count, IntPtr.Zero, overlapped);

                    // TODO: Error handling

                    // 997
                    int hr = Marshal.GetLastWin32Error();

                    if (hr != 997)
                    {
                        Writer.Complete(Marshal.GetExceptionForHR(hr));
                    }
                }
            }
Beispiel #23
0
        /// <summary>
        /// Provides the implementation for <see cref="TryAddReference"/> and
        /// <see cref="WeakReference.TryAddReference"/>.
        /// </summary>
        private static ReferenceCountedDisposable <T> TryAddReferenceImpl(T target, StrongBox <int> referenceCount)
        {
            lock (referenceCount)
            {
                if (referenceCount.Value == 0)
                {
                    // The target is already disposed, and cannot be reused
                    return(null);
                }

                if (target == null)
                {
                    // The current reference has been disposed, so even though it isn't disposed yet we don't have a
                    // reference to the target
                    return(null);
                }

                checked
                {
                    referenceCount.Value++;
                }

                // Must return a new instance, in order for the Dispose operation on each individual instance to
                // be idempotent.
                return(new ReferenceCountedDisposable <T>(target, referenceCount));
            }
        }
Beispiel #24
0
        public async void TestShutdown()
        {
            var index          = new StrongBox <int>();
            var clientManager  = new TestClientConnectionManager(index);
            var serviceManager = new TestServiceConnectionManager <Hub>(index);

            var options = new TestOptions();

            options.Value.GracefulShutdown = new GracefulShutdownOptions()
            {
                Timeout = TimeSpan.FromSeconds(1),
                Mode    = GracefulShutdownMode.WaitForClientsClose
            };

            var dispatcher = new ServiceHubDispatcher <Hub>(
                null,
                serviceManager,
                clientManager,
                null,
                options,
                NullLoggerFactory.Instance,
                new TestRouter(),
                null,
                null,
                null
                );

            await dispatcher.ShutdownAsync();

            Assert.Equal(3, serviceManager.StopIndex);
            Assert.Equal(2, clientManager.CompleteIndex);
            Assert.Equal(1, serviceManager.OfflineIndex);
        }
 private Node(int nbLevels, TK key, TV value)
 {
     NbLevels = nbLevels;
     Key      = key;
     Forward  = new ForwardNodesCollection(nbLevels);
     Data     = new StrongBox <TV>(value);
 }
        public async Task MultipleWorkers_Limited_1()
        {
            var max = new StrongBox <int>(0);

            var queue = Using(new HybridDbMessageQueue(
                                  store,
                                  MaxConcurrencyCounter(max),
                                  new MessageQueueOptions
            {
                MaxConcurrency = 1
            }.ReplayEvents(TimeSpan.FromSeconds(60))));

            using (var session = store.OpenSession())
            {
                foreach (var i in Enumerable.Range(1, 200))
                {
                    session.Enqueue(new MyMessage(Guid.NewGuid().ToString(), i.ToString()));
                }

                session.SaveChanges();
            }

            var threads = await queue.Events.OfType <MessageHandled>()
                          .Take(200)
                          .ToList()
                          .FirstAsync();

            max.Value.ShouldBe(1);
        }
        internal Delegate CreateDelegate(StrongBox<object>[] closure) {
            if (_compiled != null) {
                // If the delegate type we want is not a Func/Action, we can't
                // use the compiled code directly. So instead just fall through
                // and create an interpreted LightLambda, which will pick up
                // the compiled delegate on its first run.
                //
                // Ideally, we would just rebind the compiled delegate using
                // Delegate.CreateDelegate. Unfortunately, it doesn't work on
                // dynamic methods.
                if (SameDelegateType) {
                    return CreateCompiledDelegate(closure);
                }
            }

            if (_interpreter == null) {
                // We can't interpret, so force a compile
                Compile(null);
                Delegate compiled = CreateCompiledDelegate(closure);
                Debug.Assert(compiled.GetType() == _lambda.Type);
                return compiled;
            }

            // Otherwise, we'll create an interpreted LightLambda
            return new LightLambda(this, closure, _interpreter._compilationThreshold).MakeDelegate(_lambda.Type);
        }
Beispiel #28
0
        internal static RubyArray SortInPlace(
            BinaryOpStorage /*!*/ comparisonStorage,
            BinaryOpStorage /*!*/ lessThanStorage,
            BinaryOpStorage /*!*/ greaterThanStorage,
            BlockParam block,
            RubyArray /*!*/ self,
            out StrongBox <object> breakResult)
        {
            breakResult = null;
            var context = comparisonStorage.Context;

            // TODO: this does more comparisons (and in a different order) than
            // Ruby's sort. Also, control flow won't work because List<T>.Sort wraps
            // exceptions from the comparer & rethrows. We need to rewrite a version of quicksort
            // that behaves like Ruby's sort.
            if (block == null)
            {
                self.Sort((x, y) => Protocols.Compare(comparisonStorage, lessThanStorage, greaterThanStorage, x, y));
            }
            else
            {
                object nonRefBreakResult = null;
                try {
                    self.Sort((x, y) =>
                    {
                        object result = null;
                        if (block.Yield(x, y, out result))
                        {
                            nonRefBreakResult = result;
                            throw new BreakException();
                        }

                        if (result == null)
                        {
                            throw RubyExceptions.MakeComparisonError(context, x, y);
                        }

                        return(Protocols.ConvertCompareResult(lessThanStorage, greaterThanStorage, result));
                    });
                } catch (InvalidOperationException e) {
                    if (e.InnerException == null)
                    {
                        throw;
                    }

                    if (e.InnerException is BreakException)
                    {
                        breakResult = new StrongBox <object>(nonRefBreakResult);
                        return(null);
                    }
                    else
                    {
                        throw e.InnerException;
                    }
                }
            }

            return(self);
        }
        public void CanAddSuffix()
        {
            var structure = new StructureTest.TestStructure();
            var strongBox = new StrongBox <bool>(false);

            structure.TestAddInstanceSuffix("FOO", new Suffix <bool>(BuildBasicGetter(strongBox)));
            Assert.IsFalse((bool)structure.GetSuffix("FOO"));
        }
Beispiel #30
0
        private static void StrongBoxDemo()
        {
            StrongBox <int> sint = new StrongBox <int>(123465);

            Console.WriteLine(sint.Value);
            StrongBoxInt(sint);
            Console.WriteLine(sint.Value);
        }
 protected override void Dispose(bool disposing)
 {
     if (_pinned != null)
     {
         _pinned.Value.Free();
         _pinned = null;
     }
 }
        public static PhonesActivityWindowManger Init(int window, int numOfNodes, int amsVectorLength, HashFunctionTable[] hashFunctionTable, PhonesActivityDataParser phonesActivityDataParser, GeographicalDistributing distributingMethod)
        {
            StrongBox <PhonesActivityWindowManger> phonesActivityWindowManager = new StrongBox <PhonesActivityWindowManger>(null);
            var lazyWindow = new Lazy <WindowedStatistics>(() => WindowedStatistics.Init(ArrayUtils.Init(window, _ => phonesActivityWindowManager.Value.GetNextAmsVectors())));

            phonesActivityWindowManager.Value = new PhonesActivityWindowManger(numOfNodes, amsVectorLength, hashFunctionTable, phonesActivityDataParser, lazyWindow, distributingMethod);
            return(phonesActivityWindowManager.Value);
        }
 protected override void Dispose(bool disposing)
 {
     if (_pinned != null)
     {
         _pinned.Value.Free();
         _pinned = null;
     }
 }
Beispiel #34
0
 internal Delegate CreateCompiledDelegate(StrongBox<object>[] closure)
 {
     if (this.HasClosure)
     {
         Func<StrongBox<object>[], Delegate> func = (Func<StrongBox<object>[], Delegate>) this._compiled;
         return func(closure);
     }
     return this._compiled;
 }
Beispiel #35
0
 internal void BoxLocals() {
     bool[] boxedLocals = Interpreter._localIsBoxed;
     if (boxedLocals != null) {
         for (int i = 0; i < boxedLocals.Length; i++) {
             if (boxedLocals[i]) {
                 Data[i] = new StrongBox<object>(Data[i]);
             }
         }
     }
 }
Beispiel #36
0
        public static void TestCtor()
        {
            StrongBox<int> boxedInt32 = new StrongBox<int>();
            Assert.Equal(default(int), boxedInt32.Value);
            boxedInt32 = new StrongBox<int>(42);
            Assert.Equal(42, boxedInt32.Value);

            StrongBox<string> boxedString = new StrongBox<string>();
            Assert.Equal(default(string), boxedString.Value);
            boxedString = new StrongBox<string>("test");
            Assert.Equal("test", boxedString.Value);
        }
Beispiel #37
0
        internal InterpretedFrame(Interpreter interpreter, StrongBox<object>[] closure) {
            Interpreter = interpreter;
            StackIndex = interpreter.Locals.LocalCount;
            Data = new object[StackIndex + interpreter.Instructions.MaxStackDepth];

            int c = interpreter.Instructions.MaxContinuationDepth;
            if (c > 0) {
                _continuations = new int[c];
            }

            Closure = closure;
        }
Beispiel #38
0
 internal Delegate CreateDelegate(StrongBox<object>[] closure)
 {
     if ((this._compiled != null) && this.SameDelegateType)
     {
         return this.CreateCompiledDelegate(closure);
     }
     if (this._interpreter == null)
     {
         this.Compile(null);
         return this.CreateCompiledDelegate(closure);
     }
     return new LightLambda(this, closure, this._interpreter._compilationThreshold).MakeDelegate(this.DelegateType);
 }
Beispiel #39
0
 internal InterpretedFrame(System.Management.Automation.Interpreter.Interpreter interpreter, StrongBox<object>[] closure)
 {
     this.Interpreter = interpreter;
     this.StackIndex = interpreter.LocalCount;
     this.Data = new object[this.StackIndex + interpreter.Instructions.MaxStackDepth];
     int maxContinuationDepth = interpreter.Instructions.MaxContinuationDepth;
     if (maxContinuationDepth > 0)
     {
         this._continuations = new int[maxContinuationDepth];
     }
     this.Closure = closure;
     this._pendingContinuation = -1;
     this._pendingValue = System.Management.Automation.Interpreter.Interpreter.NoValue;
 }
Beispiel #40
0
        public static void TestValue()
        {
            StrongBox<int> sb = new StrongBox<int>();
            Assert.Equal(0, sb.Value);
            sb.Value = 42;
            Assert.Equal(42, sb.Value);

            IStrongBox isb = sb;
            Assert.Equal(42, (int)isb.Value);
            isb.Value = 84;
            Assert.Equal(84, sb.Value);
            Assert.Equal(84, (int)isb.Value);

            Assert.Throws<InvalidCastException>(() => isb.Value = "test");
        }
        private Delegate CreateCompiledDelegate(StrongBox<object>[] closure) {
            // It's already compiled, and the types match, just use the
            // delegate directly.
            Delegate d = _compiled(closure);

            // The types might not match, if the delegate type we want is
            // not a Func/Action. In that case, use LightLambda to create
            // a new delegate of the right type. This is not the most
            // efficient approach, but to do better we need the ability to
            // compile into a DynamicMethod that we created.
            if (d.GetType() != _lambda.Type) {
                var ret = new LightLambda(_interpreter, closure, this);
                ret.Compiled = d;
                d = ret.MakeDelegate(_lambda.Type);
            }

            return d;
        }
 public override int Run(InterpretedFrame frame)
 {
     StrongBox<object>[] boxArray;
     if (this.ConsumedStack > 0)
     {
         boxArray = new StrongBox<object>[this.ConsumedStack];
         for (int i = boxArray.Length - 1; i >= 0; i--)
         {
             boxArray[i] = (StrongBox<object>) frame.Pop();
         }
     }
     else
     {
         boxArray = null;
     }
     Delegate delegate2 = this._creator.CreateDelegate(boxArray);
     frame.Push(delegate2);
     return 1;
 }
        private HistorySavingComponent()
        {
            // Initialize the workqueue.
            this.queue = new WorkQueue();

            // Disallow the concurrency for this component.
            this.queue.ConcurrentLimit = 1;

            // Log the event if an item failed.
            this.queue.FailedWorkItem += onFailedWorkItem;

            // Initiate the component timer.
            this.timer = new ComponentTimer( TIME_INTERVAL, TimeUpHandler);

            // Initialize the logger used in this component.
            logger = NLoggerUtil.GetNLogger(typeof (HistorySavingComponent));

            activeDocumentBox = new StrongBox<IDocument>();
        }
        internal Delegate CreateDelegate(StrongBox<object>[] closure) {
            if (_compiled != null) {
                return CreateCompiledDelegate(closure);
            }

            // Otherwise, we'll create an interpreted LightLambda
            var ret = new LightLambda(_interpreter, closure, this);
            
            lock (this) {
                // If this field is now null, it means a compile happened
                if (_lightLambdas != null) {
                    _lightLambdas.Add(ret);
                }
            }

            if (_lightLambdas == null) {
                return CreateCompiledDelegate(closure);
            }

            return ret.MakeDelegate(_lambda.Type);
        }
Beispiel #45
0
 internal InterpretedFrame(Interpreter interpreter, StrongBox<object>[] closure) {
     Interpreter = interpreter;
     StackIndex = interpreter._numberOfLocals;
     Data = new object[interpreter._numberOfLocals + interpreter._maxStackDepth];
     Closure = closure;
 }
Beispiel #46
0
 public ImportStatementInfo(Statement statement, StrongBox<int> siblings) {
     Statement = statement;
     Siblings = siblings;
 }
 public DelayedTupleExpression(int index, StrongBox<ParameterExpression> tupleExpr, StrongBox<Type> tupleType, Type type)
 {
     Index = index;
     _tupleType = tupleType;
     _tupleExpr = tupleExpr;
     _type = type;
 }
Beispiel #48
0
            private void TrackImport(Statement node, string name) {
                var parent = _scopes[_scopes.Count - 1];
                StrongBox<int> statementCount;

                if (!_statementCount.TryGetValue(parent, out statementCount)) {
                    PythonAst outerParent = parent as PythonAst;
                    if (outerParent != null) {
                        // we don't care about the number of children at the top level
                        statementCount = new StrongBox<int>(-1);
                    } else {
                        FunctionDefinition funcDef = parent as FunctionDefinition;
                        if (funcDef != null) {
                            statementCount = GetNumberOfChildStatements(funcDef.Body);
                        } else {
                            var classDef = (ClassDefinition)parent;
                            statementCount = GetNumberOfChildStatements(classDef.Body);
                        }
                    }
                    _statementCount[parent] = statementCount;
                }

                List<ImportStatementInfo> imports;
                if (!_importedNames.TryGetValue(name, out imports)) {
                    _importedNames[name] = imports = new List<ImportStatementInfo>();
                }
                imports.Add(new ImportStatementInfo(node, statementCount));
            }
        /// <summary>
        /// Used by LightLambda to get the compiled delegate.
        /// </summary>
        internal Delegate CreateCompiledDelegate(StrongBox<object>[] closure) {
            Debug.Assert(HasClosure == (closure != null));

            if (HasClosure) {
                // We need to apply the closure to get the actual delegate.
                var applyClosure = (Func<StrongBox<object>[], Delegate>)_compiled;
                return applyClosure(closure);
            }
            return _compiled;
        }
Beispiel #50
0
            public ImportRemovalInfo(ImportStatementInfo statementInfo) {
                var node = statementInfo.Statement;
                SiblingCount = statementInfo.Siblings;

                if (node is FromImportStatement) {
                    Statement = new RemovedFromImportStatement((FromImportStatement)node);
                } else {
                    Statement = new RemovedImportStatement((ImportStatement)node);
                }
            }
 // Silverlight doesn't have ModuleInfo.ResolveField so we need to
 // get something which can be updated w/ the final type instead.
 public FieldBuilderExpression(FieldBuilder builder, StrongBox<Type> finishedType) {
     _builder = builder;
     _finishedType = finishedType;
 }
 public UpdateActiveDocumentWorkItem(StrongBox<IDocument> documentBox, IDocument document)
 {
     this.documentBox = documentBox;
     this.document = document;
 }
Beispiel #53
0
 public EnumerableTest(StrongBox<bool> disposed) {
     _disposed = disposed;
 }
Beispiel #54
0
 public static RubyRegex/*!*/ CreateRegexN(object[]/*!*/ strings, RubyEncoding/*!*/ encoding, RubyRegexOptions options, StrongBox<RubyRegex> regexpCache) {
     Func<RubyRegex> createRegex = delegate { return new RubyRegex(CreateMutableStringN(strings, encoding), options); };
     return CreateRegexWorker(options, regexpCache, false, createRegex);
 }
Beispiel #55
0
        internal static RubyArray SortInPlace(ComparisonStorage/*!*/ comparisonStorage, BlockParam block, RubyArray/*!*/ self, out StrongBox<object> breakResult) {
            breakResult = null;
            var context = comparisonStorage.Context;

            // TODO: this does more comparisons (and in a different order) than
            // Ruby's sort. Also, control flow won't work because List<T>.Sort wraps
            // exceptions from the comparer & rethrows. We need to rewrite a version of quicksort
            // that behaves like Ruby's sort.
            if (block == null) {
                self.Sort((x, y) => Protocols.Compare(comparisonStorage, x, y));
            } else {
                object nonRefBreakResult = null;
                try {
                    self.Sort((x, y) =>
                    {
                        object result = null;
                        if (block.Yield(x, y, out result)) {
                            nonRefBreakResult = result;
                            throw new BreakException();
                        }

                        if (result == null) {
                            throw RubyExceptions.MakeComparisonError(context, x, y);
                        }

                        return Protocols.ConvertCompareResult(comparisonStorage, result);
                    });
                } catch (InvalidOperationException e) {
                    if (e.InnerException == null) {
                        throw;
                    }

                    if (e.InnerException is BreakException) {
                        breakResult = new StrongBox<object>(nonRefBreakResult);
                        return null;
                    } else {
                        throw e.InnerException;
                    }
                }
            }

            return self;
        }
Beispiel #56
0
 public MyEnumerator(StrongBox<bool> disposed) {
     _disposed = disposed;
 }
Beispiel #57
0
 internal StackFrame MakeFrame(StrongBox<object>[] closure) {
     var ret = new StackFrame(_numberOfLocals, _maxStackDepth);
     ret.Closure = closure;
     
     return ret;
 }
Beispiel #58
0
        static void Assign5()
        {
            Title();

            var box = new StrongBox<int> { Value = 3 };
            var obj = Log(Expression.Constant(box), "Box");
            var val = box.GetType().GetField("Value");
            var fld = Expression.Field(obj, val);
            var res = Expression.Lambda<Func<int>>(CSharpExpression.PreIncrementAssignChecked(fld)).Compile()();

            Console.WriteLine($"{res} == (++3) --> {box.Value}");
        }
Beispiel #59
0
            public unsafe void Read()
            {
                var buffer = Writer.Alloc(2048);
                void* pointer;
                if (!buffer.Memory.TryGetPointer(out pointer))
                {
                    throw new InvalidOperationException("Memory needs to be pinned");
                }
                var data = (IntPtr)pointer;
                var count = buffer.Memory.Length;

                var overlapped = ThreadPoolBoundHandle.AllocateNativeOverlapped(PreAllocatedOverlapped);
                overlapped->OffsetLow = Offset;

                Overlapped = overlapped;

                BoxedBuffer = new StrongBox<WritableBuffer>(buffer);

                int r = ReadFile(FileHandle, data, count, IntPtr.Zero, overlapped);

                // TODO: Error handling

                // 997
                int hr = Marshal.GetLastWin32Error();
                if (hr != 997)
                {
                    Writer.Complete(Marshal.GetExceptionForHR(hr));
                }
            }
Beispiel #60
0
        private static RubyRegex/*!*/ CreateRegexWorker(
            RubyRegexOptions options, 
            StrongBox<RubyRegex> regexpCache, 
            bool isLiteralWithoutSubstitutions,
            Func<RubyRegex> createRegex) {

            try {
                bool once = ((options & RubyRegexOptions.Once) == RubyRegexOptions.Once) || isLiteralWithoutSubstitutions;
                if (once) {
                    // Note that the user is responsible for thread synchronization
                    if (regexpCache.Value == null) {
                        regexpCache.Value = createRegex();
                    }
                    return regexpCache.Value;
                } else {
                    // In the future, we can consider caching the last Regexp. For some regexp literals 
                    // with substitution, the substition will be the same most of the time
                    return createRegex();
                }
            } catch (RegexpError e) {
                if (isLiteralWithoutSubstitutions) {
                    // Ideally, this should be thrown during parsing of the source, even if the 
                    // expression happens to be unreachable at runtime.
                    throw new SyntaxError(e.Message);
                } else {
                    throw;
                }
            }
        }