text:
/* eslint-disable prefer-arrow-callback */
const jaja = require('../src/jaja');
describe.skip('Jaja', function JajaTests() {
  // POLYFILLS
  describe('console', function console() {
    assert.isDefined(jaja.console);
    assert.isFunction(jaja.console.assert);
  });

  // ARRAY
  describe('ArrayHelper', function ArrayHelper() {
    describe('new', function newArrayHelper() {
      it('should be a new ArrayHelper object.', function test() {
        assert.equal(jaja.array.constructor.name, 'ArrayHelper');
      });
    });

    describe('sum', function sum() {
      it('should return the sum of the numbers in the array', function test() {
        assert.equal(jaja.array.sum([1, 2, 3, 4, 5]), 15);
      });
    });

    describe('getAllIndexes', function getAllIndexes() {
      it('should return all the indexes of the number 2', function test() {
        const myArray = [0, 2, 0, 0, 2, 2, 5, 48, 1, 2, 4, 6, 34, 5, 3, 2];
        const indexesOfNumber2 = jaja.array.getAllIndexes(myArray, 2);
        assert.deepEqual(indexesOfNumber2, [1, 4, 5, 9, 15]);
      });
      it('should return empty array', function test() {
        const myArray = [0, 1, 2, 5, 12, 500];
        const indexesOfNumber2 = jaja.array.getAllIndexes(myArray, 46);
        assert.equal(indexesOfNumber2.length, 0);
      });
    });

    describe('findByProperty', function findByProperty() {
      it('should return the first object containing a "name" property with the value "foo"', function test() {
        const myArray = [0, 2, 0, { name: 'bar' }, 2, 5, 65, 48, 8, 9, { name: 'foo', info: 'bat' }, 11, 12, { name: 'foo', info: 'snafu' }, 3, 2];
        const myFooObject = jaja.array.findByProperty(myArray, 'name', 'foo', true);
        assert.deepEqual(myFooObject, { name: 'foo', info: 'bat' });
      });

      it('should throw an error', function test() {
        const myArray = [0, 2, 0, { name: 'bar' }];
        assert.throws(
          () => { jaja.array.findByProperty(myArray, 'name', 'uhoh', false); },
          Error,
          'Couldn\'t find object with property'
        );
      });

      it('should NOT throw an error. Should return null', function test() {
        const myArray = [0, 2, 0, { name: 'bar' }];
        const myUhohObject = jaja.array.findByProperty(myArray, 'name', 'uhoh', true);
        assert.isNull(myUhohObject);
      });
    });
    describe('findAllByProperty', function findAllByProperty() {
      it('should return an array of all objects containing a "name" property with the value "foo"', function test() {
        const myArray = [0, 2, 0, { name: 'bar' }, 9, { name: 'foo', info: 'bat' }, 11, 12, { name: 'foo', info: 'snafu' }, 3, 2];
        const myFooArray = jaja.array.findAllByProperty(myArray, 'name', 'foo', true);
        assert.deepEqual(myFooArray, [{ name: 'foo', info: 'bat' }, { name: 'foo', info: 'snafu' }]);
      });
    });

    describe('remove', function remove() {
      it('should remove all instances of the number 5 from the array', function test() {
        const myArray = [1, 2, 3, 4, 5, 5, 5, 6, 10, 'foo', '5', 4];
        jaja.array.remove(myArray, 5);
        assert.deepEqual(myArray, [1, 2, 3, 4, 6, 10, 'foo', '5', 4]);
      });

      it('should remove all instances of variables from the array', function test() {
        const myArray = [1, 2, true, 4, 5, '12', 10, 'foo', '5', 4, true, 'foo'];
        jaja.array.remove(myArray, '5', 'foo', true);
        assert.deepEqual(myArray, [1, 2, 4, 5, '12', 10, 4]);
      });

      it('should remove nothing from the array', function test() {
        const myArray = [1, 2, true, 4, 5, '12', 10, 'foo', '5', 4, true, 'foo'];
        jaja.array.remove(myArray, 1000);
        assert.deepEqual(myArray, [1, 2, true, 4, 5, '12', 10, 'foo', '5', 4, true, 'foo']);
      });

      // TODO: Make this test pass. Requires rewrite of Jaja.array.remove.
      it.skip('should remove objects from the array', function test() {
        const myArray = [1, 2, { number: 3 }];
        jaja.array.remove(myArray, { number: 3 });
        assert.deepEqual(myArray, [1, 2]);
      });
    });
  });
});


text:
import {
  MotionObservable,
} from '../observables/MotionObservable';

import {
  ObservableWithMotionOperators,
  Observer,
} from '../types';

// Passive event feature detection from
// https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
let supportsPassiveListeners = false;
try {
  const eventOptions: any = Object.defineProperty({}, 'passive', {
    get() {
      supportsPassiveListeners = true;
    }
  });
  window.addEventListener("test", () => {}, eventOptions);
} catch (e) {}

export function getEventStreamFromElement<U extends Event = Event>(type: string, element: Element, eventListenerOptions: AddEventListenerOptions = { passive: true }): ObservableWithMotionOperators<U> {
  return new MotionObservable<U>(
    (observer: Observer<U>) => {
      if (!supportsPassiveListeners) {
        eventListenerOptions = (eventListenerOptions.capture || false) as any as AddEventListenerOptions;
      }

      const next = observer.next.bind(observer);

      // For some reason, TypeScript has an interface for
      // AddEventListenerOptions, but its addEventListener signature hasn't been
      // updated to use it, so for now, we manually cast to boolean.
      //
      // https://github.com/Microsoft/TypeScript/issues/18136
      element.addEventListener(type, next, eventListenerOptions as any as boolean);

      return () => {
        element.removeEventListener(type, next, eventListenerOptions as any as boolean);
      };
    }
  );
}
export default getEventStreamFromElement;

redpajama_set_name: RedPajamaGithub


text:
#pragma once
#include <aws/networkmanager/NetworkManager_EXPORTS.h>
#include <aws/networkmanager/NetworkManagerRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSMap.h>
#include <utility>

namespace Aws
{
namespace NetworkManager
{
namespace Model
{

  /**
   */
  class AWS_NETWORKMANAGER_API UpdateNetworkResourceMetadataRequest : public NetworkManagerRequest
  {
  public:
    UpdateNetworkResourceMetadataRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "UpdateNetworkResourceMetadata"; }

    Aws::String SerializePayload() const override;

    /**
     *
The ID of the global network.

     */
    inline const Aws::String& GetGlobalNetworkId() const{ return m_globalNetworkId; }

    /**
     *
The ID of the global network.

     */
    inline bool GlobalNetworkIdHasBeenSet() const { return m_globalNetworkIdHasBeenSet; }

    /**
     *
The ID of the global network.

     */
    inline void SetGlobalNetworkId(const Aws::String& value) { m_globalNetworkIdHasBeenSet = true; m_globalNetworkId = value; }

    /**
     *
The ID of the global network.

     */
    inline void SetGlobalNetworkId(Aws::String&& value) { m_globalNetworkIdHasBeenSet = true; m_globalNetworkId = std::move(value); }

    /**
     *
The ID of the global network.

     */
    inline void SetGlobalNetworkId(const char* value) { m_globalNetworkIdHasBeenSet = true; m_globalNetworkId.assign(value); }

    /**
     *
The ID of the global network.

     */
    inline UpdateNetworkResourceMetadataRequest& WithGlobalNetworkId(const Aws::String& value) { SetGlobalNetworkId(value); return *this;}

    /**
     *
The ID of the global network.

     */
    inline UpdateNetworkResourceMetadataRequest& WithGlobalNetworkId(Aws::String&& value) { SetGlobalNetworkId(std::move(value)); return *this;}

    /**
     *
The ID of the global network.

     */
    inline UpdateNetworkResourceMetadataRequest& WithGlobalNetworkId(const char* value) { SetGlobalNetworkId(value); return *this;}

    /**
     *
The ARN of the resource.

     */
    inline const Aws::String& GetResourceArn() const{ return m_resourceArn; }

    /**
     *
The ARN of the resource.

     */
    inline bool ResourceArnHasBeenSet() const { return m_resourceArnHasBeenSet; }

    /**
     *
The ARN of the resource.

     */
    inline void SetResourceArn(const Aws::String& value) { m_resourceArnHasBeenSet = true; m_resourceArn = value; }

    /**
     *
The ARN of the resource.

     */
    inline void SetResourceArn(Aws::String&& value) { m_resourceArnHasBeenSet = true; m_resourceArn = std::move(value); }

    /**
     *
The ARN of the resource.

     */
    inline void SetResourceArn(const char* value) { m_resourceArnHasBeenSet = true; m_resourceArn.assign(value); }

    /**
     *
The ARN of the resource.

     */
    inline UpdateNetworkResourceMetadataRequest& WithResourceArn(const Aws::String& value) { SetResourceArn(value); return *this;}

    /**
     *
The ARN of the resource.

     */
    inline UpdateNetworkResourceMetadataRequest& WithResourceArn(Aws::String&& value) { SetResourceArn(std::move(value)); return *this;}

    /**
     *
The ARN of the resource.

     */
    inline UpdateNetworkResourceMetadataRequest& WithResourceArn(const char* value) { SetResourceArn(value); return *this;}

    /**
     *
The resource metadata.

     */
    inline const Aws::Map<Aws::String, Aws::String>& GetMetadata() const{ return m_metadata; }

    /**
     *
The resource metadata.

     */
    inline bool MetadataHasBeenSet() const { return m_metadataHasBeenSet; }

    /**
     *
The resource metadata.

     */
    inline void SetMetadata(const Aws::Map<Aws::String, Aws::String>& value) { m_metadataHasBeenSet = true; m_metadata = value; }

    /**
     *
The resource metadata.

     */
    inline void SetMetadata(Aws::Map<Aws::String, Aws::String>&& value) { m_metadataHasBeenSet = true; m_metadata = std::move(value); }

    /**
     *
The resource metadata.

     */
    inline UpdateNetworkResourceMetadataRequest& WithMetadata(const Aws::Map<Aws::String, Aws::String>& value) { SetMetadata(value); return *this;}

    /**
     *
The resource metadata.

     */
    inline UpdateNetworkResourceMetadataRequest& WithMetadata(Aws::Map<Aws::String, Aws::String>&& value) { SetMetadata(std::move(value)); return *this;}

    /**
     *
The resource metadata.

     */
    inline UpdateNetworkResourceMetadataRequest& AddMetadata(const Aws::String& key, const Aws::String& value) { m_metadataHasBeenSet = true; m_metadata.emplace(key, value); return *this; }

    /**
     *
The resource metadata.

     */
    inline UpdateNetworkResourceMetadataRequest& AddMetadata(Aws::String&& key, const Aws::String& value) { m_metadataHasBeenSet = true; m_metadata.emplace(std::move(key), value); return *this; }

    /**
     *
The resource metadata.

     */
    inline UpdateNetworkResourceMetadataRequest& AddMetadata(const Aws::String& key, Aws::String&& value) { m_metadataHasBeenSet = true; m_metadata.emplace(key, std::move(value)); return *this; }

    /**
     *
The resource metadata.

     */
    inline UpdateNetworkResourceMetadataRequest& AddMetadata(Aws::String&& key, Aws::String&& value) { m_metadataHasBeenSet = true; m_metadata.emplace(std::move(key), std::move(value)); return *this; }

    /**
     *
The resource metadata.

     */
    inline UpdateNetworkResourceMetadataRequest& AddMetadata(const char* key, Aws::String&& value) { m_metadataHasBeenSet = true; m_metadata.emplace(key, std::move(value)); return *this; }

    /**
     *
The resource metadata.

     */
    inline UpdateNetworkResourceMetadataRequest& AddMetadata(Aws::String&& key, const char* value) { m_metadataHasBeenSet = true; m_metadata.emplace(std::move(key), value); return *this; }

    /**
     *
The resource metadata.

     */
    inline UpdateNetworkResourceMetadataRequest& AddMetadata(const char* key, const char* value) { m_metadataHasBeenSet = true; m_metadata.emplace(key, value); return *this; }

  private:

    Aws::String m_globalNetworkId;
    bool m_globalNetworkIdHasBeenSet;

    Aws::String m_resourceArn;
    bool m_resourceArnHasBeenSet;

    Aws::Map<Aws::String, Aws::String> m_metadata;
    bool m_metadataHasBeenSet;
  };

} // namespace Model
} // namespace NetworkManager
} // namespace Aws


text:
<?php

namespace Prooph\Processing\Console;

use Prooph\Processing\Environment\Environment;
use Zend\Stdlib\ArrayUtils;
use ZF\Console\Route;

/**
 * Class AbstractCommand
 *
 * @package Prooph\Processing\Console
 * @author Alexander Miertsch <kontakt@codeliner.ws>
 */
class AbstractCommand
{
    const MESSAGE_PROCESSING_FAILED = 500;

    /**
     * @param \ZF\Console\Route $route
     * @param ConsoleWriter $consoleWriter
     * @return Environment
     */
    protected function loadEnvironment(Route $route, ConsoleWriter $consoleWriter)
    {
        $configPath = $route->getMatchedParam('config-file', getcwd() . DIRECTORY_SEPARATOR . 'processing.config.php');

        $additionalConfig = $route->getMatchedParam('config', json_encode([]));

        $additionalConfig = json_decode($additionalConfig, true);

        if (is_null($additionalConfig)) {
            $consoleWriter->writeError("Provided config is not a valid json string");
            $consoleWriter->writeError(json_last_error_msg());
            return self::MESSAGE_PROCESSING_FAILED;
        }

        if (file_exists($configPath)) {

            $config = include $configPath;

            $consoleWriter->writeInfo('Config loaded from ' . $configPath);

        } elseif (file_exists($configPath . '.dist')) {

            $config = include $configPath . '.dist';

            $consoleWriter->writeInfo('Config loaded from ' . $configPath);

        } else {

            $consoleWriter->writeInfo('No config file specified.');

            if (empty($additionalConfig)) {
                $consoleWriter->writeInfo('Falling back to default config');
            } else {
                $consoleWriter->writeInfo('Using config from argument');
            }

            return $additionalConfig;
        }

        $config = ArrayUtils::merge($config, $additionalConfig);

        $env = Environment::setUp($config);

        $env->getEventStore()->getActionEventDispatcher()->attachListenerAggregate(new PersistedEventsConsoleWriter($consoleWriter));

        return $env;
    }
}


text:
namespace blink {

void V0CustomElementMicrotaskQueueBase::dispatch() {
  RELEASE_ASSERT(!m_inDispatch);
  m_inDispatch = true;
  doDispatch();
  m_inDispatch = false;
}

DEFINE_TRACE(V0CustomElementMicrotaskQueueBase) {
  visitor->trace(m_queue);
}

#if !defined(NDEBUG)
void V0CustomElementMicrotaskQueueBase::show(unsigned indent) {
  for (const auto& step : m_queue) {
    if (step)
      step->show(indent);
    else
      fprintf(stderr, "%*snull\n", indent, "");
  }
}
#endif

}  // namespace blink


text:
var library = require('./../release/main');
var property = library.Property;
var validator = library.Validator;

var testPropertyValid = function(done, value, obj, errorCode) {
    obj['valid'](value, function(err, result){
        if (err) {
            done(err);
        } else {
            if (errorCode !== null) {
                if (result.isValid()) {
                    done(new Error('Expect error code: ' + errorCode + ', get valid result'));
                } else {
                    var errors = result.getErrors();
                    for (var i=0;i < errors.length; i++) {
                        if (errors[i]['code'] === errorCode) {
                            return done();
                        }
                    }
                    done(new Error('Expect error code: ' + errorCode + ', get another errors: ' + JSON.stringify(errors)));
                }
            } else {
                if (result.isValid()) {
                    done();
                } else {
                    done(new Error('Expect valid result, get error messages: ' + JSON.stringify(result.getErrors())));
                }
            }
        }
    });
};

describe("Property validator check allow null/undefined/empty", function(){
    it("Create property without any validator and without any allow options and send undefined", function(done){
        testPropertyValid(done, undefined, new property.Property({}), 'property_not_allowed_undefined');
    });
    it("Create property without any validator and without any allow options and send null", function(done){
        testPropertyValid(done, null, new property.Property({}), 'property_not_allowed_null');
    });
    it("Create property without any validator and without any allow options and send number", function(done){
        testPropertyValid(done, 23, new property.Property({}), null);
    });
    it("Create property without any validator and without any allow options and send string", function(done){
        testPropertyValid(done, 'asdasd', new property.Property({}), null);
    });
    it("Create property without any validator and without any allow options and send date object", function(done){
        testPropertyValid(done, new Date(), new property.Property({}), null);
    });
    it("Create property allowed null value and send null value", function(done){
        testPropertyValid(done, null, new property.Property({allowNull:true}), null);
    });
    it("Create property allowed null value and send number value", function(done){
        testPropertyValid(done, 2323, new property.Property({allowNull:true}), null);
    });
    it("Create property allowed null value and send undefined", function(done){
        testPropertyValid(done, undefined, new property.Property({allowNull:true}), 'property_not_allowed_undefined');
    });
    it("Create property allowed undefined value and send null undefined", function(done){
        testPropertyValid(done, undefined, new property.Property({allowUndefined:true}), null);
    });
    it("Create property allowed undefined value and send number value", function(done){
        testPropertyValid(done, 2323, new property.Property({allowUndefined:true}), null);
    });
    it("Create property allowed undefined value and send null", function(done){
        testPropertyValid(done, null, new property.Property({allowUndefined:true}), 'property_not_allowed_null');
    });
    it("Create property allowed empty value and send null", function(done){
        testPropertyValid(done, null, new property.Property({allowEmpty:true}), null);
    });
    it("Create property allowed empty value and send undefined", function(done){
        testPropertyValid(done, undefined, new property.Property({allowEmpty:true}), null);
    });
    it("Create property allowed empty value and send number value", function(done){
        testPropertyValid(done, 233, new property.Property({allowEmpty:true}), null);
    });
});

describe("Property validator with validators and allow null", function(){
    var v = new property.Property({allowNull:true, validators:[new validator.ValidatorNumber({max:30}), new validator.ValidatorNumber({min:10})]});
    it("Send null value", function(done){
        testPropertyValid(done, null, v, null);
    });
    it("Send undefined value", function(done){
        testPropertyValid(done, undefined, v, 'property_not_allowed_undefined');
    });
    it("Send number value which is validate", function(done){
        testPropertyValid(done, 16, v, null);
    });
    it("Send number value which is not validate by second validator", function(done){
        testPropertyValid(done, 6, v, 'value_is_too_less');
    });
    it("Send number value which is not validate by first validator", function(done){
        testPropertyValid(done, 33, v, 'value_is_too_greater');
    });
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	version="3.0" metadata-complete="true">

	<listener>
		<listener-class>westion.www.listener.ContextAndRequestListener</listener-class>
	</listener>

	<!-- 全局的配置文件的路径 -->
	<context-param>
		<param-name>config</param-name>
		<param-value>/WEB-INF/page.properties</param-value>
	</context-param>

	<!-- servlet -->
	<servlet>
		<servlet-name>IndexServlet</servlet-name>
		<servlet-class>westion.www.servlet.IndexServlet</servlet-class>
	</servlet>
	<servlet>
		<servlet-name>AdminServlet</servlet-name>
		<servlet-class>westion.www.servlet.AdminServlet</servlet-class>
	</servlet>
	<servlet>
		<servlet-name>LoginServlet</servlet-name>
		<servlet-class>westion.www.servlet.LoginServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>IndexServlet</servlet-name>
		<url-pattern>/api</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>AdminServlet</servlet-name>
		<url-pattern>/admin/api</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>LoginServlet</servlet-name>
		<url-pattern>/admin/login</url-pattern>
	</servlet-mapping>

	<!-- filter -->
	<filter>
		<filter-name>IsVaidFilter</filter-name>
		<filter-class>westion.www.filter.IsValidFilter</filter-class>
	</filter>
	<filter>
		<filter-name>LoginFilter</filter-name>
		<filter-class>westion.www.filter.LoginFilter</filter-class>
	</filter>

	<filter-mapping>
		<filter-name>IsVaidFilter</filter-name>
		<servlet-name>IndexServlet</servlet-name>
	</filter-mapping>
		<filter-mapping>
		<filter-name>IsVaidFilter</filter-name>
		<servlet-name>AdminServlet</servlet-name>
	</filter-mapping>
		<filter-mapping>
		<filter-name>IsVaidFilter</filter-name>
		<servlet-name>LoginServlet</servlet-name>
	</filter-mapping>

	<filter-mapping>
		<filter-name>LoginFilter</filter-name>
		<url-pattern>/admin/api</url-pattern>
	</filter-mapping>
</web-app>


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.PortableExecutable;
using System.Threading;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp.Emit
{
    internal abstract class PEModuleBuilder : PEModuleBuilder<CSharpCompilation, SourceModuleSymbol, AssemblySymbol, TypeSymbol, NamedTypeSymbol, MethodSymbol, SyntaxNode, NoPia.EmbeddedTypesManager, ModuleCompilationState>
    {
        // TODO: Need to estimate amount of elements for this map and pass that value to the constructor.
        protected readonly ConcurrentDictionary<Symbol, Cci.IModuleReference> AssemblyOrModuleSymbolToModuleRefMap = new ConcurrentDictionary<Symbol, Cci.IModuleReference>();
        private readonly ConcurrentDictionary<Symbol, object> _genericInstanceMap = new ConcurrentDictionary<Symbol, object>();
        private readonly ConcurrentSet<TypeSymbol> _reportedErrorTypesMap = new ConcurrentSet<TypeSymbol>();

        private readonly NoPia.EmbeddedTypesManager _embeddedTypesManagerOpt;
        public override NoPia.EmbeddedTypesManager EmbeddedTypesManagerOpt
            => _embeddedTypesManagerOpt;

        // Gives the name of this module (may not reflect the name of the underlying symbol).
        // See Assembly.MetadataName.
        private readonly string _metadataName;

        private ImmutableArray<Cci.ExportedType> _lazyExportedTypes;

        /// <summary>
        /// The compiler-generated implementation type for each fixed-size buffer.
        /// </summary>
        private Dictionary<FieldSymbol, NamedTypeSymbol> _fixedImplementationTypes;

        private bool _needsGeneratedIsReadOnlyAttribute_Value;
        private bool _needsGeneratedIsUnmanagedAttribute_Value;
        private bool _needsGeneratedAttributes_IsFrozen;
        private bool _needsGeneratedNullableAttribute_Value;

        /// <summary>
        /// Returns a value indicating whether this builder has a symbol that needs IsReadOnlyAttribute to be generated during emit phase.
        /// The value is set during lowering the symbols that need that attribute, and is frozen on first trial to get it.
        /// Freezing is needed to make sure that nothing tries to modify the value after the value is read.
        /// </summary>
        protected bool NeedsGeneratedIsReadOnlyAttribute
        {
            get
            {
                _needsGeneratedAttributes_IsFrozen = true;
                return Compilation.NeedsGeneratedIsReadOnlyAttribute || _needsGeneratedIsReadOnlyAttribute_Value;
            }
        }

        /// <summary>
        /// Returns a value indicating whether this builder has a symbol that needs IsByRefLikeAttribute to be generated during emit phase.
        /// </summary>
        protected bool NeedsGeneratedIsByRefLikeAttribute
        {
            get
            {
                return Compilation.NeedsGeneratedIsByRefLikeAttribute;
            }
        }

        internal bool NeedsGeneratedIsUnmanagedAttribute
        {
            get
            {
                _needsGeneratedAttributes_IsFrozen = true;
                return Compilation.NeedsGeneratedIsUnmanagedAttribute || _needsGeneratedIsUnmanagedAttribute_Value;
            }
        }

        protected bool NeedsGeneratedNullableAttribute
        {
            get
            {
                _needsGeneratedAttributes_IsFrozen = true;
                return Compilation.NeedsGeneratedNullableAttribute || _needsGeneratedNullableAttribute_Value;
            }
        }

        internal PEModuleBuilder(
            SourceModuleSymbol sourceModule,
            EmitOptions emitOptions,
            OutputKind outputKind,
            Cci.ModulePropertiesForSerialization serializationProperties,
            IEnumerable<ResourceDescription> manifestResources)
            : base(sourceModule.ContainingSourceAssembly.DeclaringCompilation,
                   sourceModule,
                   serializationProperties,
                   manifestResources,
                   outputKind,
                   emitOptions,
                   new ModuleCompilationState())
        {
            var specifiedName = sourceModule.MetadataName;

            _metadataName = specifiedName != Microsoft.CodeAnalysis.Compilation.UnspecifiedModuleAssemblyName ?
                            specifiedName :
                            emitOptions.OutputNameOverride ?? specifiedName;

            AssemblyOrModuleSymbolToModuleRefMap.Add(sourceModule, this);

            if (sourceModule.AnyReferencedAssembliesAreLinked)
            {
                _embeddedTypesManagerOpt = new NoPia.EmbeddedTypesManager(this);
            }
        }

        public override string Name
        {
            get { return _metadataName; }
        }

        internal sealed override string ModuleName
        {
            get { return _metadataName; }
        }

        internal sealed override Cci.ICustomAttribute SynthesizeAttribute(WellKnownMember attributeConstructor)
        {
            return Compilation.TrySynthesizeAttribute(attributeConstructor);
        }

        public sealed override IEnumerable<Cci.ICustomAttribute> GetSourceAssemblyAttributes(bool isRefAssembly)
        {
            return SourceModule.ContainingSourceAssembly
                .GetCustomAttributesToEmit(this, isRefAssembly, emittingAssemblyAttributesInNetModule: OutputKind.IsNetModule());
        }

        public sealed override IEnumerable<Cci.SecurityAttribute> GetSourceAssemblySecurityAttributes()
        {
            return SourceModule.ContainingSourceAssembly.GetSecurityAttributes();
        }

        public sealed override IEnumerable<Cci.ICustomAttribute> GetSourceModuleAttributes()
        {
            return SourceModule.GetCustomAttributesToEmit(this);
        }

        internal sealed override AssemblySymbol CorLibrary
        {
            get { return SourceModule.ContainingSourceAssembly.CorLibrary; }
        }

        public sealed override bool GenerateVisualBasicStylePdb => false;

        // C# doesn't emit linked assembly names into PDBs.
        public sealed override IEnumerable<string> LinkedAssembliesDebugInfo => SpecializedCollections.EmptyEnumerable<string>();

        // C# currently doesn't emit compilation level imports (TODO: scripting).
        public sealed override ImmutableArray<Cci.UsedNamespaceOrType> GetImports() => ImmutableArray<Cci.UsedNamespaceOrType>.Empty;

        // C# doesn't allow to define default namespace for compilation.
        public sealed override string DefaultNamespace => null;

        protected sealed override IEnumerable<Cci.IAssemblyReference> GetAssemblyReferencesFromAddedModules(DiagnosticBag diagnostics)
        {
            ImmutableArray<ModuleSymbol> modules = SourceModule.ContainingAssembly.Modules;

            for (int i = 1; i < modules.Length; i++)
            {
                foreach (AssemblySymbol aRef in modules[i].GetReferencedAssemblySymbols())
                {
                    yield return Translate(aRef, diagnostics);
                }
            }
        }

        private void ValidateReferencedAssembly(AssemblySymbol assembly, AssemblyReference asmRef, DiagnosticBag diagnostics)
        {
            AssemblyIdentity asmIdentity = SourceModule.ContainingAssembly.Identity;
            AssemblyIdentity refIdentity = asmRef.Identity;

            if (asmIdentity.IsStrongName && !refIdentity.IsStrongName &&
                asmRef.Identity.ContentType != AssemblyContentType.WindowsRuntime)
            {
                // Dev12 reported error, we have changed it to a warning to allow referencing libraries
                // built for platforms that don't support strong names.
                diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_ReferencedAssemblyDoesNotHaveStrongName, assembly), NoLocation.Singleton);
            }

            if (OutputKind != OutputKind.NetModule &&
               !string.IsNullOrEmpty(refIdentity.CultureName) &&
               !string.Equals(refIdentity.CultureName, asmIdentity.CultureName, StringComparison.OrdinalIgnoreCase))
            {
                diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_RefCultureMismatch, assembly, refIdentity.CultureName), NoLocation.Singleton);
            }

            var refMachine = assembly.Machine;
            // If other assembly is agnostic this is always safe
            // Also, if no mscorlib was specified for back compat we add a reference to mscorlib
            // that resolves to the current framework directory. If the compiler is 64-bit
            // this is a 64-bit mscorlib, which will produce a warning if /platform:x86 is
            // specified. A reference to the default mscorlib should always succeed without
            // warning so we ignore it here.
            if ((object)assembly != (object)assembly.CorLibrary &&
                !(refMachine == Machine.I386 && !assembly.Bit32Required))
            {
                var machine = SourceModule.Machine;

                if (!(machine == Machine.I386 && !SourceModule.Bit32Required) &&
                    machine != refMachine)
                {
                    // Different machine types, and neither is agnostic
                    diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_ConflictingMachineAssembly, assembly), NoLocation.Singleton);
                }
            }

            if (_embeddedTypesManagerOpt != null && _embeddedTypesManagerOpt.IsFrozen)
            {
                _embeddedTypesManagerOpt.ReportIndirectReferencesToLinkedAssemblies(assembly, diagnostics);
            }
        }

        internal sealed override IEnumerable<Cci.INestedTypeDefinition> GetSynthesizedNestedTypes(NamedTypeSymbol container)
        {
            return null;
        }

        public sealed override MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> GetSymbolToLocationMap()
        {
            var result = new MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation>();

            var namespacesAndTypesToProcess = new Stack<NamespaceOrTypeSymbol>();
            namespacesAndTypesToProcess.Push(SourceModule.GlobalNamespace);

            Location location = null;

            while (namespacesAndTypesToProcess.Count > 0)
            {
                NamespaceOrTypeSymbol symbol = namespacesAndTypesToProcess.Pop();
                switch (symbol.Kind)
                {
                    case SymbolKind.Namespace:
                        location = GetSmallestSourceLocationOrNull(symbol);

                        // filtering out synthesized symbols not having real source
                        // locations such as anonymous types, etc...
                        if (location != null)
                        {
                            foreach (var member in symbol.GetMembers())
                            {
                                switch (member.Kind)
                                {
                                    case SymbolKind.Namespace:
                                    case SymbolKind.NamedType:
                                        namespacesAndTypesToProcess.Push((NamespaceOrTypeSymbol)member);
                                        break;

                                    default:
                                        throw ExceptionUtilities.UnexpectedValue(member.Kind);
                                }
                            }
                        }
                        break;

                    case SymbolKind.NamedType:
                        location = GetSmallestSourceLocationOrNull(symbol);
                        if (location != null)
                        {
                            //  add this named type location
                            AddSymbolLocation(result, location, (Cci.IDefinition)symbol);

                            foreach (var member in symbol.GetMembers())
                            {
                                switch (member.Kind)
                                {
                                    case SymbolKind.NamedType:
                                        namespacesAndTypesToProcess.Push((NamespaceOrTypeSymbol)member);
                                        break;

                                    case SymbolKind.Method:
                                        // NOTE: Dev11 does not add synthesized static constructors to this map,
                                        //       but adds synthesized instance constructors, Roslyn adds both
                                        var method = (MethodSymbol)member;
                                        if (method.IsDefaultValueTypeConstructor() ||
                                            method.IsPartialMethod() && (object)method.PartialImplementationPart == null)
                                        {
                                            break;
                                        }

                                        AddSymbolLocation(result, member);
                                        break;

                                    case SymbolKind.Property:
                                    case SymbolKind.Field:
                                        // NOTE: Dev11 does not add synthesized backing fields for properties,
                                        //       but adds backing fields for events, Roslyn adds both
                                        AddSymbolLocation(result, member);
                                        break;

                                    case SymbolKind.Event:
                                        AddSymbolLocation(result, member);
                                        //  event backing fields do not show up in GetMembers
                                        FieldSymbol field = ((EventSymbol)member).AssociatedField;
                                        if ((object)field != null)
                                        {
                                            AddSymbolLocation(result, field);
                                        }
                                        break;

                                    default:
                                        throw ExceptionUtilities.UnexpectedValue(member.Kind);
                                }
                            }
                        }
                        break;

                    default:
                        throw ExceptionUtilities.UnexpectedValue(symbol.Kind);
                }
            }

            return result;
        }

        private void AddSymbolLocation(MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> result, Symbol symbol)
        {
            var location = GetSmallestSourceLocationOrNull(symbol);
            if (location != null)
            {
                AddSymbolLocation(result, location, (Cci.IDefinition)symbol);
            }
        }

        private void AddSymbolLocation(MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> result, Location location, Cci.IDefinition definition)
        {
            FileLinePositionSpan span = location.GetLineSpan();

            Cci.DebugSourceDocument doc = DebugDocumentsBuilder.TryGetDebugDocument(span.Path, basePath: location.SourceTree.FilePath);

            if (doc != null)
            {
                result.Add(doc,
                           new Cci.DefinitionWithLocation(
                               definition,
                               span.StartLinePosition.Line,
                               span.StartLinePosition.Character,
                               span.EndLinePosition.Line,
                               span.EndLinePosition.Character));
            }
        }

        private Location GetSmallestSourceLocationOrNull(Symbol symbol)
        {
            CSharpCompilation compilation = symbol.DeclaringCompilation;
            Debug.Assert(Compilation == compilation, "How did we get symbol from different compilation?");

            Location result = null;
            foreach (var loc in symbol.Locations)
            {
                if (loc.IsInSource && (result == null || compilation.CompareSourceLocations(result, loc) > 0))
                {
                    result = loc;
                }
            }

            return result;
        }

        /// <summary>
        /// Ignore accessibility when resolving well-known type
        /// members, in particular for generic type arguments
        /// (e.g.: binding to internal types in the EE).
        /// </summary>
        internal virtual bool IgnoreAccessibility => false;

        /// <summary>
        /// Override the dynamic operation context type for all dynamic calls in the module.
        /// </summary>
        internal virtual NamedTypeSymbol GetDynamicOperationContextType(NamedTypeSymbol contextType)
        {
            return contextType;
        }

        internal virtual VariableSlotAllocator TryCreateVariableSlotAllocator(MethodSymbol method, MethodSymbol topLevelMethod, DiagnosticBag diagnostics)
        {
            return null;
        }

        internal virtual ImmutableArray<AnonymousTypeKey> GetPreviousAnonymousTypes()
        {
            return ImmutableArray<AnonymousTypeKey>.Empty;
        }

        internal virtual int GetNextAnonymousTypeIndex()
        {
            return 0;
        }

        internal virtual bool TryGetAnonymousTypeName(NamedTypeSymbol template, out string name, out int index)
        {
            Debug.Assert(Compilation == template.DeclaringCompilation);

            name = null;
            index = -1;
            return false;
        }

        internal sealed override ImmutableArray<Cci.INamespaceTypeDefinition> GetAnonymousTypes(EmitContext context)
        {
            if (context.MetadataOnly)
            {
                return ImmutableArray<Cci.INamespaceTypeDefinition>.Empty;
            }

            return StaticCast<Cci.INamespaceTypeDefinition>.From(Compilation.AnonymousTypeManager.GetAllCreatedTemplates());
        }

        /// <summary>
        /// True if this module is an ENC update.
        /// </summary>
        internal virtual bool IsEncDelta
        {
            get { return false; }
        }

        internal override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypesCore(EmitContext context)
        {
            foreach (var type in GetAdditionalTopLevelTypes(context.Diagnostics))
            {
                yield return type;
            }

            foreach (var type in GetEmbeddedTypes(context.Diagnostics))
            {
                yield return type;
            }

            var namespacesToProcess = new Stack<NamespaceSymbol>();
            namespacesToProcess.Push(SourceModule.GlobalNamespace);

            while (namespacesToProcess.Count > 0)
            {
                var ns = namespacesToProcess.Pop();
                foreach (var member in ns.GetMembers())
                {
                    var memberNamespace = member as NamespaceSymbol;
                    if ((object)memberNamespace != null)
                    {
                        namespacesToProcess.Push(memberNamespace);
                    }
                    else
                    {
                        var type = (NamedTypeSymbol)member;
                        yield return type;
                    }
                }
            }
        }

        internal virtual ImmutableArray<NamedTypeSymbol> GetAdditionalTopLevelTypes(DiagnosticBag diagnostics)
        {
            return ImmutableArray<NamedTypeSymbol>.Empty;
        }

        internal virtual ImmutableArray<NamedTypeSymbol> GetEmbeddedTypes(DiagnosticBag diagnostics)
        {
            return ImmutableArray<NamedTypeSymbol>.Empty;
        }

        private static void GetExportedTypes(NamespaceOrTypeSymbol symbol, int parentIndex, ArrayBuilder<Cci.ExportedType> builder)
        {
            int index;
            if (symbol.Kind == SymbolKind.NamedType)
            {
                if (symbol.DeclaredAccessibility != Accessibility.Public)
                {
                    return;
                }

                Debug.Assert(symbol.IsDefinition);
                index = builder.Count;
                builder.Add(new Cci.ExportedType((Cci.ITypeReference)symbol, parentIndex, isForwarder: false));
            }
            else
            {
                index = -1;
            }

            foreach (var member in symbol.GetMembers())
            {
                var namespaceOrType = member as NamespaceOrTypeSymbol;
                if ((object)namespaceOrType != null)
                {
                    GetExportedTypes(namespaceOrType, index, builder);
                }
            }
        }

        public sealed override ImmutableArray<Cci.ExportedType> GetExportedTypes(DiagnosticBag diagnostics)
        {
            Debug.Assert(HaveDeterminedTopLevelTypes);

            if (_lazyExportedTypes.IsDefault)
            {
                _lazyExportedTypes = CalculateExportedTypes();

                if (_lazyExportedTypes.Length > 0)
                {
                    ReportExportedTypeNameCollisions(_lazyExportedTypes, diagnostics);
                }
            }

            return _lazyExportedTypes;
        }

        /// <summary>
        /// Builds an array of public type symbols defined in netmodules included in the compilation
        /// and type forwarders defined in this compilation or any included netmodule (in this order).
        /// </summary>
        private ImmutableArray<Cci.ExportedType> CalculateExportedTypes()
        {
            SourceAssemblySymbol sourceAssembly = SourceModule.ContainingSourceAssembly;
            var builder = ArrayBuilder<Cci.ExportedType>.GetInstance();

            if (!OutputKind.IsNetModule())
            {
                var modules = sourceAssembly.Modules;
                for (int i = 1; i < modules.Length; i++) //NOTE: skipping modules[0]
                {
                    GetExportedTypes(modules[i].GlobalNamespace, -1, builder);
                }
            }

            var seenTopLevelForwardedTypes = new HashSet<NamedTypeSymbol>();
            GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetSourceDecodedWellKnownAttributeData(), builder);

            if (!OutputKind.IsNetModule())
            {
                GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetNetModuleDecodedWellKnownAttributeData(), builder);
            }

            return builder.ToImmutableAndFree();
        }

        private void ReportExportedTypeNameCollisions(ImmutableArray<Cci.ExportedType> exportedTypes, DiagnosticBag diagnostics)
        {
            var sourceAssembly = SourceModule.ContainingSourceAssembly;
            var exportedNamesMap = new Dictionary<string, NamedTypeSymbol>(StringOrdinalComparer.Instance);

            foreach (var exportedType in exportedTypes)
            {
                var type = (NamedTypeSymbol)exportedType.Type;

                Debug.Assert(type.IsDefinition);

                if (!type.IsTopLevelType())
                {
                    continue;
                }

                string fullEmittedName = MetadataHelpers.BuildQualifiedName(
                    ((Cci.INamespaceTypeReference)type).NamespaceName,
                    Cci.MetadataWriter.GetMangledName(type));

                // First check against types declared in the primary module
                if (ContainsTopLevelType(fullEmittedName))
                {
                    if ((object)type.ContainingAssembly == sourceAssembly)
                    {
                        diagnostics.Add(ErrorCode.ERR_ExportedTypeConflictsWithDeclaration, NoLocation.Singleton, type, type.ContainingModule);
                    }
                    else
                    {
                        diagnostics.Add(ErrorCode.ERR_ForwardedTypeConflictsWithDeclaration, NoLocation.Singleton, type);
                    }

                    continue;
                }

                NamedTypeSymbol contender;

                // Now check against other exported types
                if (exportedNamesMap.TryGetValue(fullEmittedName, out contender))
                {
                    if ((object)type.ContainingAssembly == sourceAssembly)
                    {
                        // all exported types precede forwarded types, therefore contender cannot be a forwarded type.
                        Debug.Assert(contender.ContainingAssembly == sourceAssembly);

                        diagnostics.Add(ErrorCode.ERR_ExportedTypesConflict, NoLocation.Singleton, type, type.ContainingModule, contender, contender.ContainingModule);
                    }
                    else if ((object)contender.ContainingAssembly == sourceAssembly)
                    {
                        // Forwarded type conflicts with exported type
                        diagnostics.Add(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType, NoLocation.Singleton, type, type.ContainingAssembly, contender, contender.ContainingModule);
                    }
                    else
                    {
                        // Forwarded type conflicts with another forwarded type
                        diagnostics.Add(ErrorCode.ERR_ForwardedTypesConflict, NoLocation.Singleton, type, type.ContainingAssembly, contender, contender.ContainingAssembly);
                    }

                    continue;
                }

                exportedNamesMap.Add(fullEmittedName, type);
            }
        }

        private static void GetForwardedTypes(
            HashSet<NamedTypeSymbol> seenTopLevelTypes,
            CommonAssemblyWellKnownAttributeData<NamedTypeSymbol> wellKnownAttributeData,
            ArrayBuilder<Cci.ExportedType> builder)
        {
            if (wellKnownAttributeData?.ForwardedTypes?.Count > 0)
            {
                // (type, index of the parent exported type in builder, or -1 if the type is a top-level type)
                var stack = ArrayBuilder<(NamedTypeSymbol type, int parentIndex)>.GetInstance();

                // Hashset enumeration is not guaranteed to be deterministic. Emitting in the order of fully qualified names.
                var orderedForwardedTypes = wellKnownAttributeData.ForwardedTypes.OrderBy(t => t.OriginalDefinition.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat));

                foreach (NamedTypeSymbol forwardedType in orderedForwardedTypes)
                {
                    NamedTypeSymbol originalDefinition = forwardedType.OriginalDefinition;
                    Debug.Assert((object)originalDefinition.ContainingType == null, "How did a nested type get forwarded?");

                    // Since we need to allow multiple constructions of the same generic type at the source
                    // level, we need to de-dup the original definitions before emitting.
                    if (!seenTopLevelTypes.Add(originalDefinition)) continue;

                    // Return all nested types.
                    // Note the order: depth first, children in reverse order (to match dev10, not a requirement).
                    Debug.Assert(stack.Count == 0);
                    stack.Push((originalDefinition, -1));

                    while (stack.Count > 0)
                    {
                        var (type, parentIndex) = stack.Pop();

                        // In general, we don't want private types to appear in the ExportedTypes table.
                        // BREAK: dev11 emits these types.  The problem was discovered in dev10, but failed
                        // to meet the bar Bug: Dev10/258038 and was left as-is.
                        if (type.DeclaredAccessibility == Accessibility.Private)
                        {
                            // NOTE: this will also exclude nested types of type
                            continue;
                        }

                        // NOTE: not bothering to put nested types in seenTypes - the top-level type is adequate protection.

                        int index = builder.Count;
                        builder.Add(new Cci.ExportedType(type, parentIndex, isForwarder: true));

                        // Iterate backwards so they get popped in forward order.
                        ImmutableArray<NamedTypeSymbol> nested = type.GetTypeMembers(); // Ordered.
                        for (int i = nested.Length - 1; i >= 0; i--)
                        {
                            stack.Push((nested[i], index));
                        }
                    }
                }

                stack.Free();
            }
        }

        internal IEnumerable<AssemblySymbol> GetReferencedAssembliesUsedSoFar()
        {
            foreach (AssemblySymbol a in SourceModule.GetReferencedAssemblySymbols())
            {
                if (!a.IsLinked && !a.IsMissing && AssemblyOrModuleSymbolToModuleRefMap.ContainsKey(a))
                {
                    yield return a;
                }
            }
        }

        private NamedTypeSymbol GetUntranslatedSpecialType(SpecialType specialType, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
        {
            Debug.Assert(diagnostics != null);

            var typeSymbol = SourceModule.ContainingAssembly.GetSpecialType(specialType);

            DiagnosticInfo info = typeSymbol.GetUseSiteDiagnostic();
            if (info != null)
            {
                Symbol.ReportUseSiteDiagnostic(info,
                                               diagnostics,
                                               syntaxNodeOpt != null ? syntaxNodeOpt.Location : NoLocation.Singleton);
            }

            return typeSymbol;
        }

        internal sealed override Cci.INamedTypeReference GetSpecialType(SpecialType specialType, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
        {
            return Translate(GetUntranslatedSpecialType(specialType, syntaxNodeOpt, diagnostics),
                             diagnostics: diagnostics,
                             syntaxNodeOpt: syntaxNodeOpt,
                             needDeclaration: true);
        }

        internal sealed override Cci.INamedTypeReference GetSystemType(SyntaxNode syntaxOpt, DiagnosticBag diagnostics)
        {
            NamedTypeSymbol systemTypeSymbol = Compilation.GetWellKnownType(WellKnownType.System_Type);

            DiagnosticInfo info = systemTypeSymbol.GetUseSiteDiagnostic();
            if (info != null)
            {
                Symbol.ReportUseSiteDiagnostic(info,
                                               diagnostics,
                                               syntaxOpt != null ? syntaxOpt.Location : NoLocation.Singleton);
            }

            return Translate(systemTypeSymbol, syntaxOpt, diagnostics, needDeclaration: true);
        }

        public sealed override Cci.IMethodReference GetInitArrayHelper()
        {
            return (MethodSymbol)Compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle);
        }

        public sealed override bool IsPlatformType(Cci.ITypeReference typeRef, Cci.PlatformType platformType)
        {
            var namedType = typeRef as NamedTypeSymbol;
            if ((object)namedType != null)
            {
                if (platformType == Cci.PlatformType.SystemType)
                {
                    return (object)namedType == (object)Compilation.GetWellKnownType(WellKnownType.System_Type);
                }

                return namedType.SpecialType == (SpecialType)platformType;
            }

            return false;
        }

        protected sealed override Cci.IAssemblyReference GetCorLibraryReferenceToEmit(CodeAnalysis.Emit.EmitContext context)
        {
            AssemblySymbol corLibrary = CorLibrary;

            if (!corLibrary.IsMissing &&
                !corLibrary.IsLinked &&
                !ReferenceEquals(corLibrary, SourceModule.ContainingAssembly))
            {
                return Translate(corLibrary, context.Diagnostics);
            }

            return null;
        }

        internal sealed override Cci.IAssemblyReference Translate(AssemblySymbol assembly, DiagnosticBag diagnostics)
        {
            if (ReferenceEquals(SourceModule.ContainingAssembly, assembly))
            {
                return (Cci.IAssemblyReference)this;
            }

            Cci.IModuleReference reference;

            if (AssemblyOrModuleSymbolToModuleRefMap.TryGetValue(assembly, out reference))
            {
                return (Cci.IAssemblyReference)reference;
            }

            AssemblyReference asmRef = new AssemblyReference(assembly);

            AssemblyReference cachedAsmRef = (AssemblyReference)AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(assembly, asmRef);

            if (cachedAsmRef == asmRef)
            {
                ValidateReferencedAssembly(assembly, cachedAsmRef, diagnostics);
            }

            // TryAdd because whatever is associated with assembly should be associated with Modules[0]
            AssemblyOrModuleSymbolToModuleRefMap.TryAdd(assembly.Modules[0], cachedAsmRef);

            return cachedAsmRef;
        }

        internal Cci.IModuleReference Translate(ModuleSymbol module, DiagnosticBag diagnostics)
        {
            if (ReferenceEquals(SourceModule, module))
            {
                return this;
            }

            if ((object)module == null)
            {
                return null;
            }

            Cci.IModuleReference moduleRef;

            if (AssemblyOrModuleSymbolToModuleRefMap.TryGetValue(module, out moduleRef))
            {
                return moduleRef;
            }

            moduleRef = TranslateModule(module, diagnostics);
            moduleRef = AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(module, moduleRef);

            return moduleRef;
        }

        protected virtual Cci.IModuleReference TranslateModule(ModuleSymbol module, DiagnosticBag diagnostics)
        {
            AssemblySymbol container = module.ContainingAssembly;

            if ((object)container != null && ReferenceEquals(container.Modules[0], module))
            {
                Cci.IModuleReference moduleRef = new AssemblyReference(container);
                Cci.IModuleReference cachedModuleRef = AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(container, moduleRef);

                if (cachedModuleRef == moduleRef)
                {
                    ValidateReferencedAssembly(container, (AssemblyReference)moduleRef, diagnostics);
                }
                else
                {
                    moduleRef = cachedModuleRef;
                }

                return moduleRef;
            }
            else
            {
                return new ModuleReference(this, module);
            }
        }

        internal Cci.INamedTypeReference Translate(
            NamedTypeSymbol namedTypeSymbol,
            SyntaxNode syntaxNodeOpt,
            DiagnosticBag diagnostics,
            bool fromImplements = false,
            bool needDeclaration = false)
        {
            Debug.Assert(namedTypeSymbol.IsDefinitionOrDistinct());
            Debug.Assert(diagnostics != null);

            // Anonymous type being translated
            if (namedTypeSymbol.IsAnonymousType)
            {
                Debug.Assert(!needDeclaration);
                namedTypeSymbol = AnonymousTypeManager.TranslateAnonymousTypeSymbol(namedTypeSymbol);
            }
            else if (namedTypeSymbol.IsTupleType)
            {
                Debug.Assert(!needDeclaration);
                namedTypeSymbol = namedTypeSymbol.TupleUnderlyingType;
                CheckTupleUnderlyingType(namedTypeSymbol, syntaxNodeOpt, diagnostics);
            }

            // Substitute error types with a special singleton object.
            // Unreported bad types can come through NoPia embedding, for example.
            if (namedTypeSymbol.OriginalDefinition.Kind == SymbolKind.ErrorType)
            {
                ErrorTypeSymbol errorType = (ErrorTypeSymbol)namedTypeSymbol.OriginalDefinition;
                DiagnosticInfo diagInfo = errorType.GetUseSiteDiagnostic() ?? errorType.ErrorInfo;

                if (diagInfo == null && namedTypeSymbol.Kind == SymbolKind.ErrorType)
                {
                    errorType = (ErrorTypeSymbol)namedTypeSymbol;
                    diagInfo = errorType.GetUseSiteDiagnostic() ?? errorType.ErrorInfo;
                }

                // Try to decrease noise by not complaining about the same type over and over again.
                if (_reportedErrorTypesMap.Add(errorType))
                {
                    diagnostics.Add(new CSDiagnostic(diagInfo ?? new CSDiagnosticInfo(ErrorCode.ERR_BogusType, string.Empty), syntaxNodeOpt == null ? NoLocation.Singleton : syntaxNodeOpt.Location));
                }

                return CodeAnalysis.Emit.ErrorType.Singleton;
            }

            if (!namedTypeSymbol.IsDefinition)
            {
                // generic instantiation for sure
                Debug.Assert(!needDeclaration);

                if (namedTypeSymbol.IsUnboundGenericType)
                {
                    namedTypeSymbol = namedTypeSymbol.OriginalDefinition;
                }
                else
                {
                    return namedTypeSymbol;
                }
            }
            else if (!needDeclaration)
            {
                object reference;
                Cci.INamedTypeReference typeRef;

                NamedTypeSymbol container = namedTypeSymbol.ContainingType;

                if (namedTypeSymbol.Arity > 0)
                {
                    if (_genericInstanceMap.TryGetValue(namedTypeSymbol, out reference))
                    {
                        return (Cci.INamedTypeReference)reference;
                    }

                    if ((object)container != null)
                    {
                        if (IsGenericType(container))
                        {
                            // Container is a generic instance too.
                            typeRef = new SpecializedGenericNestedTypeInstanceReference(namedTypeSymbol);
                        }
                        else
                        {
                            typeRef = new GenericNestedTypeInstanceReference(namedTypeSymbol);
                        }
                    }
                    else
                    {
                        typeRef = new GenericNamespaceTypeInstanceReference(namedTypeSymbol);
                    }

                    typeRef = (Cci.INamedTypeReference)_genericInstanceMap.GetOrAdd(namedTypeSymbol, typeRef);

                    return typeRef;
                }
                else if (IsGenericType(container))
                {
                    Debug.Assert((object)container != null);

                    if (_genericInstanceMap.TryGetValue(namedTypeSymbol, out reference))
                    {
                        return (Cci.INamedTypeReference)reference;
                    }

                    typeRef = new SpecializedNestedTypeReference(namedTypeSymbol);
                    typeRef = (Cci.INamedTypeReference)_genericInstanceMap.GetOrAdd(namedTypeSymbol, typeRef);

                    return typeRef;
                }
            }

            // NoPia: See if this is a type, which definition we should copy into our assembly.
            Debug.Assert(namedTypeSymbol.IsDefinition);

            if (_embeddedTypesManagerOpt != null)
            {
                return _embeddedTypesManagerOpt.EmbedTypeIfNeedTo(namedTypeSymbol, fromImplements, syntaxNodeOpt, diagnostics);
            }

            return namedTypeSymbol;
        }

        private void CheckTupleUnderlyingType(NamedTypeSymbol namedTypeSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
        {
            // check that underlying type of a ValueTuple is indeed a value type (or error)
            // this should never happen, in theory,
            // but if it does happen we should make it a failure.
            // NOTE: declaredBase could be null for interfaces
            var declaredBase = namedTypeSymbol.BaseTypeNoUseSiteDiagnostics;
            if ((object)declaredBase != null && declaredBase.SpecialType == SpecialType.System_ValueType)
            {
                return;
            }

            // Try to decrease noise by not complaining about the same type over and over again.
            if (!_reportedErrorTypesMap.Add(namedTypeSymbol))
            {
                return;
            }

            var location = syntaxNodeOpt == null ? NoLocation.Singleton : syntaxNodeOpt.Location;
            if ((object)declaredBase != null)
            {
                var diagnosticInfo = declaredBase.GetUseSiteDiagnostic();
                if (diagnosticInfo != null && diagnosticInfo.Severity == DiagnosticSeverity.Error)
                {
                    diagnostics.Add(diagnosticInfo, location);
                    return;
                }
            }

            diagnostics.Add(
                new CSDiagnostic(
                    new CSDiagnosticInfo(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, namedTypeSymbol.MetadataName),
                    location));
        }

        public static bool IsGenericType(NamedTypeSymbol toCheck)
        {
            while ((object)toCheck != null)
            {
                if (toCheck.Arity > 0)
                {
                    return true;
                }

                toCheck = toCheck.ContainingType;
            }

            return false;
        }

        internal static Cci.IGenericParameterReference Translate(TypeParameterSymbol param)
        {
            if (!param.IsDefinition)
                throw new InvalidOperationException(string.Format(CSharpResources.GenericParameterDefinition, param.Name));

            return param;
        }

        internal sealed override Cci.ITypeReference Translate(
            TypeSymbol typeSymbol,
            SyntaxNode syntaxNodeOpt,
            DiagnosticBag diagnostics)
        {
            Debug.Assert(diagnostics != null);

            switch (typeSymbol.Kind)
            {
                case SymbolKind.DynamicType:
                    return Translate((DynamicTypeSymbol)typeSymbol, syntaxNodeOpt, diagnostics);

                case SymbolKind.ArrayType:
                    return Translate((ArrayTypeSymbol)typeSymbol);

                case SymbolKind.ErrorType:
                case SymbolKind.NamedType:
                    return Translate((NamedTypeSymbol)typeSymbol, syntaxNodeOpt, diagnostics);

                case SymbolKind.PointerType:
                    return Translate((PointerTypeSymbol)typeSymbol);

                case SymbolKind.TypeParameter:
                    return Translate((TypeParameterSymbol)typeSymbol);
            }

            throw ExceptionUtilities.UnexpectedValue(typeSymbol.Kind);
        }

        internal Cci.IFieldReference Translate(
            FieldSymbol fieldSymbol,
            SyntaxNode syntaxNodeOpt,
            DiagnosticBag diagnostics,
            bool needDeclaration = false)
        {
            Debug.Assert(fieldSymbol.IsDefinitionOrDistinct());
            Debug.Assert(!fieldSymbol.IsTupleField, "tuple fields should be rewritten to underlying by now");

            if (!fieldSymbol.IsDefinition)
            {
                Debug.Assert(!needDeclaration);

                return fieldSymbol;
            }
            else if (!needDeclaration && IsGenericType(fieldSymbol.ContainingType))
            {
                object reference;
                Cci.IFieldReference fieldRef;

                if (_genericInstanceMap.TryGetValue(fieldSymbol, out reference))
                {
                    return (Cci.IFieldReference)reference;
                }

                fieldRef = new SpecializedFieldReference(fieldSymbol);
                fieldRef = (Cci.IFieldReference)_genericInstanceMap.GetOrAdd(fieldSymbol, fieldRef);

                return fieldRef;
            }

            if (_embeddedTypesManagerOpt != null)
            {
                return _embeddedTypesManagerOpt.EmbedFieldIfNeedTo(fieldSymbol, syntaxNodeOpt, diagnostics);
            }

            return fieldSymbol;
        }

        public static Cci.TypeMemberVisibility MemberVisibility(Symbol symbol)
        {
            //
            // We need to relax visibility of members in interactive submissions since they might be emitted into multiple assemblies.
            //
            // Top-level:
            //   private                       -> public
            //   protected                     -> public (compiles with a warning)
            //   public
            //   internal                      -> public
            //
            // In a nested class:
            //
            //   private
            //   protected
            //   public
            //   internal                      -> public
            //
            switch (symbol.DeclaredAccessibility)
            {
                case Accessibility.Public:
                    return Cci.TypeMemberVisibility.Public;

                case Accessibility.Private:
                    if (symbol.ContainingType?.TypeKind == TypeKind.Submission)
                    {
                        // top-level private member:
                        return Cci.TypeMemberVisibility.Public;
                    }
                    else
                    {
                        return Cci.TypeMemberVisibility.Private;
                    }

                case Accessibility.Internal:
                    if (symbol.ContainingAssembly.IsInteractive)
                    {
                        // top-level or nested internal member:
                        return Cci.TypeMemberVisibility.Public;
                    }
                    else
                    {
                        return Cci.TypeMemberVisibility.Assembly;
                    }

                case Accessibility.Protected:
                    if (symbol.ContainingType.TypeKind == TypeKind.Submission)
                    {
                        // top-level protected member:
                        return Cci.TypeMemberVisibility.Public;
                    }
                    else
                    {
                        return Cci.TypeMemberVisibility.Family;
                    }

                case Accessibility.ProtectedAndInternal:
                    Debug.Assert(symbol.ContainingType.TypeKind != TypeKind.Submission);
                    return Cci.TypeMemberVisibility.FamilyAndAssembly;

                case Accessibility.ProtectedOrInternal:
                    if (symbol.ContainingAssembly.IsInteractive)
                    {
                        // top-level or nested protected internal member:
                        return Cci.TypeMemberVisibility.Public;
                    }
                    else
                    {
                        return Cci.TypeMemberVisibility.FamilyOrAssembly;
                    }

                default:
                    throw ExceptionUtilities.UnexpectedValue(symbol.DeclaredAccessibility);
            }
        }

        internal sealed override Cci.IMethodReference Translate(MethodSymbol symbol, DiagnosticBag diagnostics, bool needDeclaration)
        {
            return Translate(symbol, null, diagnostics, null, needDeclaration);
        }

        internal Cci.IMethodReference Translate(
            MethodSymbol methodSymbol,
            SyntaxNode syntaxNodeOpt,
            DiagnosticBag diagnostics,
            BoundArgListOperator optArgList = null,
            bool needDeclaration = false)
        {
            Debug.Assert(!methodSymbol.IsDefaultValueTypeConstructor());
            Debug.Assert(optArgList == null || (methodSymbol.IsVararg && !needDeclaration));

            Cci.IMethodReference unexpandedMethodRef = Translate(methodSymbol, syntaxNodeOpt, diagnostics, needDeclaration);

            if (optArgList != null && optArgList.Arguments.Length > 0)
            {
                Cci.IParameterTypeInformation[] @params = new Cci.IParameterTypeInformation[optArgList.Arguments.Length];
                int ordinal = methodSymbol.ParameterCount;

                for (int i = 0; i < @params.Length; i++)
                {
                    @params[i] = new ArgListParameterTypeInformation(ordinal,
                                                                    !optArgList.ArgumentRefKindsOpt.IsDefaultOrEmpty && optArgList.ArgumentRefKindsOpt[i] != RefKind.None,
                                                                    Translate(optArgList.Arguments[i].Type, syntaxNodeOpt, diagnostics));
                    ordinal++;
                }

                return new ExpandedVarargsMethodReference(unexpandedMethodRef, @params.AsImmutableOrNull());
            }
            else
            {
                return unexpandedMethodRef;
            }
        }

        private Cci.IMethodReference Translate(
            MethodSymbol methodSymbol,
            SyntaxNode syntaxNodeOpt,
            DiagnosticBag diagnostics,
            bool needDeclaration)
        {
            object reference;
            Cci.IMethodReference methodRef;
            NamedTypeSymbol container = methodSymbol.ContainingType;

            // Method of anonymous type being translated
            if (container.IsAnonymousType)
            {
                Debug.Assert(!needDeclaration);
                methodSymbol = AnonymousTypeManager.TranslateAnonymousTypeMethodSymbol(methodSymbol);
            }
            else if (methodSymbol.IsTupleMethod)
            {
                Debug.Assert(!needDeclaration);
                Debug.Assert(container.IsTupleType);
                container = container.TupleUnderlyingType;
                methodSymbol = methodSymbol.TupleUnderlyingMethod;
            }

            Debug.Assert(!container.IsTupleType);
            Debug.Assert(methodSymbol.IsDefinitionOrDistinct());

            if (!methodSymbol.IsDefinition)
            {
                Debug.Assert(!needDeclaration);

                return methodSymbol;
            }
            else if (!needDeclaration)
            {
                bool methodIsGeneric = methodSymbol.IsGenericMethod;
                bool typeIsGeneric = IsGenericType(container);

                if (methodIsGeneric || typeIsGeneric)
                {
                    if (_genericInstanceMap.TryGetValue(methodSymbol, out reference))
                    {
                        return (Cci.IMethodReference)reference;
                    }

                    if (methodIsGeneric)
                    {
                        if (typeIsGeneric)
                        {
                            // Specialized and generic instance at the same time.
                            methodRef = new SpecializedGenericMethodInstanceReference(methodSymbol);
                        }
                        else
                        {
                            methodRef = new GenericMethodInstanceReference(methodSymbol);
                        }
                    }
                    else
                    {
                        Debug.Assert(typeIsGeneric);
                        methodRef = new SpecializedMethodReference(methodSymbol);
                    }

                    methodRef = (Cci.IMethodReference)_genericInstanceMap.GetOrAdd(methodSymbol, methodRef);

                    return methodRef;
                }
            }

            if (_embeddedTypesManagerOpt != null)
            {
                return _embeddedTypesManagerOpt.EmbedMethodIfNeedTo(methodSymbol, syntaxNodeOpt, diagnostics);
            }

            return methodSymbol;
        }

        internal Cci.IMethodReference TranslateOverriddenMethodReference(
            MethodSymbol methodSymbol,
            CSharpSyntaxNode syntaxNodeOpt,
            DiagnosticBag diagnostics)
        {
            Cci.IMethodReference methodRef;
            NamedTypeSymbol container = methodSymbol.ContainingType;

            if (IsGenericType(container))
            {
                if (methodSymbol.IsDefinition)
                {
                    object reference;

                    if (_genericInstanceMap.TryGetValue(methodSymbol, out reference))
                    {
                        methodRef = (Cci.IMethodReference)reference;
                    }
                    else
                    {
                        methodRef = new SpecializedMethodReference(methodSymbol);
                        methodRef = (Cci.IMethodReference)_genericInstanceMap.GetOrAdd(methodSymbol, methodRef);
                    }
                }
                else
                {
                    methodRef = new SpecializedMethodReference(methodSymbol);
                }
            }
            else
            {
                Debug.Assert(methodSymbol.IsDefinition);

                if (_embeddedTypesManagerOpt != null)
                {
                    methodRef = _embeddedTypesManagerOpt.EmbedMethodIfNeedTo(methodSymbol, syntaxNodeOpt, diagnostics);
                }
                else
                {
                    methodRef = methodSymbol;
                }
            }

            return methodRef;
        }

        internal ImmutableArray<Cci.IParameterTypeInformation> Translate(ImmutableArray<ParameterSymbol> @params)
        {
            Debug.Assert(@params.All(p => p.IsDefinitionOrDistinct()));

            bool mustBeTranslated = @params.Any() && MustBeWrapped(@params.First());
            Debug.Assert(@params.All(p => mustBeTranslated == MustBeWrapped(p)), "either all or no parameters need translating");

            if (!mustBeTranslated)
            {
                return StaticCast<Cci.IParameterTypeInformation>.From(@params);
            }

            return TranslateAll(@params);
        }

        private static bool MustBeWrapped(ParameterSymbol param)
        {
            // we represent parameters of generic methods as definitions
            // CCI wants them represented as IParameterTypeInformation
            // so we need to create a wrapper of parameters iff
            // 1) parameters are definitions and
            // 2) container is generic
            // NOTE: all parameters must always agree on whether they need wrapping
            if (param.IsDefinition)
            {
                var container = param.ContainingSymbol;
                if (ContainerIsGeneric(container))
                {
                    return true;
                }
            }

            return false;
        }

        private ImmutableArray<Cci.IParameterTypeInformation> TranslateAll(ImmutableArray<ParameterSymbol> @params)
        {
            var builder = ArrayBuilder<Cci.IParameterTypeInformation>.GetInstance();
            foreach (var param in @params)
            {
                builder.Add(CreateParameterTypeInformationWrapper(param));
            }
            return builder.ToImmutableAndFree();
        }

        private Cci.IParameterTypeInformation CreateParameterTypeInformationWrapper(ParameterSymbol param)
        {
            object reference;
            Cci.IParameterTypeInformation paramRef;

            if (_genericInstanceMap.TryGetValue(param, out reference))
            {
                return (Cci.IParameterTypeInformation)reference;
            }

            paramRef = new ParameterTypeInformation(param);
            paramRef = (Cci.IParameterTypeInformation)_genericInstanceMap.GetOrAdd(param, paramRef);

            return paramRef;
        }

        private static bool ContainerIsGeneric(Symbol container)
        {
            return container.Kind == SymbolKind.Method && ((MethodSymbol)container).IsGenericMethod ||
                IsGenericType(container.ContainingType);
        }

        internal Cci.ITypeReference Translate(
            DynamicTypeSymbol symbol,
            SyntaxNode syntaxNodeOpt,
            DiagnosticBag diagnostics)
        {
            // Translate the dynamic type to System.Object special type to avoid duplicate entries in TypeRef table.
            // We don't need to recursively replace the dynamic type with Object since the DynamicTypeSymbol adapter
            // masquerades the TypeRef as System.Object when used to encode signatures.
            return GetSpecialType(SpecialType.System_Object, syntaxNodeOpt, diagnostics);
        }

        internal static Cci.IArrayTypeReference Translate(ArrayTypeSymbol symbol)
        {
            return symbol;
        }

        internal static Cci.IPointerTypeReference Translate(PointerTypeSymbol symbol)
        {
            return symbol;
        }

        /// <summary>
        /// Set the underlying implementation type for a given fixed-size buffer field.
        /// </summary>
        public NamedTypeSymbol SetFixedImplementationType(SourceMemberFieldSymbol field)
        {
            if (_fixedImplementationTypes == null)
            {
                Interlocked.CompareExchange(ref _fixedImplementationTypes, new Dictionary<FieldSymbol, NamedTypeSymbol>(), null);
            }

            lock (_fixedImplementationTypes)
            {
                NamedTypeSymbol result;
                if (_fixedImplementationTypes.TryGetValue(field, out result))
                {
                    return result;
                }

                result = new FixedFieldImplementationType(field);
                _fixedImplementationTypes.Add(field, result);
                AddSynthesizedDefinition(result.ContainingType, result);
                return result;
            }
        }

        internal NamedTypeSymbol GetFixedImplementationType(FieldSymbol field)
        {
            // Note that this method is called only after ALL fixed buffer types have been placed in the map.
            // At that point the map is all filled in and will not change further.  Therefore it is safe to
            // pull values from the map without locking.
            NamedTypeSymbol result;
            var found = _fixedImplementationTypes.TryGetValue(field, out result);
            Debug.Assert(found);
            return result;
        }

        protected override Cci.IMethodDefinition CreatePrivateImplementationDetailsStaticConstructor(PrivateImplementationDetails details, SyntaxNode syntaxOpt, DiagnosticBag diagnostics)
        {
            return new SynthesizedPrivateImplementationDetailsStaticConstructor(SourceModule, details, GetUntranslatedSpecialType(SpecialType.System_Void, syntaxOpt, diagnostics));
        }

        internal abstract SynthesizedAttributeData SynthesizeEmbeddedAttribute();

        internal SynthesizedAttributeData SynthesizeIsReadOnlyAttribute(Symbol symbol)
        {
            if ((object)Compilation.SourceModule != symbol.ContainingModule)
            {
                // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute.
                return null;
            }

            return TrySynthesizeIsReadOnlyAttribute();
        }

        internal SynthesizedAttributeData SynthesizeIsUnmanagedAttribute(Symbol symbol)
        {
            if ((object)Compilation.SourceModule != symbol.ContainingModule)
            {
                // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute.
                return null;
            }

            return TrySynthesizeIsUnmanagedAttribute();
        }

        internal SynthesizedAttributeData SynthesizeIsByRefLikeAttribute(Symbol symbol)
        {
            if ((object)Compilation.SourceModule != symbol.ContainingModule)
            {
                // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute.
                return null;
            }

            return TrySynthesizeIsByRefLikeAttribute();
        }

        /// <summary>
        /// Given a type <paramref name="type"/>, which is either a nullable reference type OR
        /// is a constructed type with a nullable reference type present in its type argument tree,
        /// returns a synthesized NullableAttribute with encoded nullable transforms array.
        /// </summary>
        internal SynthesizedAttributeData SynthesizeNullableAttribute(Symbol symbol, TypeWithAnnotations type)
        {
            if ((object)Compilation.SourceModule != symbol.ContainingModule)
            {
                // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute.
                return null;
            }

            var flagsBuilder = ArrayBuilder<byte>.GetInstance();
            type.AddNullableTransforms(flagsBuilder);

            Debug.Assert(flagsBuilder.Any());
            Debug.Assert(flagsBuilder.Contains((byte)NullableAnnotation.NotAnnotated) || flagsBuilder.Contains((byte)NullableAnnotation.Annotated));

            WellKnownMember constructor;
            ImmutableArray<TypedConstant> arguments;
            NamedTypeSymbol byteType = Compilation.GetSpecialType(SpecialType.System_Byte);
            Debug.Assert((object)byteType != null);

            if (flagsBuilder.All(flag => flag == (byte)NullableAnnotation.NotAnnotated) || flagsBuilder.All(flag => flag == (byte)NullableAnnotation.Annotated))
            {
                constructor = WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorByte;
                arguments = ImmutableArray.Create(new TypedConstant(byteType, TypedConstantKind.Primitive, flagsBuilder[0]));
            }
            else
            {
                var constantsBuilder = ArrayBuilder<TypedConstant>.GetInstance(flagsBuilder.Count);

                foreach (byte flag in flagsBuilder)
                {
                    Debug.Assert(flag == (byte)NullableAnnotation.Oblivious || flag == (byte)NullableAnnotation.NotAnnotated || flag == (byte)NullableAnnotation.Annotated);
                    constantsBuilder.Add(new TypedConstant(byteType, TypedConstantKind.Primitive, flag));
                }

                var byteArray = ArrayTypeSymbol.CreateSZArray(byteType.ContainingAssembly, TypeWithAnnotations.Create(byteType));
                constructor = WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags;
                arguments = ImmutableArray.Create(new TypedConstant(byteArray, constantsBuilder.ToImmutableAndFree()));
            }

            flagsBuilder.Free();
            return SynthesizeNullableAttribute(constructor, arguments);
        }

        internal virtual SynthesizedAttributeData SynthesizeNullableAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments)
        {
            // For modules, this attribute should be present. Only assemblies generate and embed this type.
            // https://github.com/dotnet/roslyn/issues/30062 Should not be optional.
            return Compilation.TrySynthesizeAttribute(member, arguments, isOptionalUse: true);
        }

        protected virtual SynthesizedAttributeData TrySynthesizeIsReadOnlyAttribute()
        {
            // For modules, this attribute should be present. Only assemblies generate and embed this type.
            return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor);
        }

        protected virtual SynthesizedAttributeData TrySynthesizeIsUnmanagedAttribute()
        {
            // For modules, this attribute should be present. Only assemblies generate and embed this type.
            return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor);
        }

        protected virtual SynthesizedAttributeData TrySynthesizeIsByRefLikeAttribute()
        {
            // For modules, this attribute should be present. Only assemblies generate and embed this type.
            return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor);
        }

        internal void EnsureIsReadOnlyAttributeExists()
        {
            Debug.Assert(!_needsGeneratedAttributes_IsFrozen);

            if (_needsGeneratedIsReadOnlyAttribute_Value || Compilation.NeedsGeneratedIsReadOnlyAttribute)
            {
                return;
            }

            // Don't report any errors. They should be reported during binding.
            if (Compilation.CheckIfIsReadOnlyAttributeShouldBeEmbedded(diagnosticsOpt: null, locationOpt: null))
            {
                _needsGeneratedIsReadOnlyAttribute_Value = true;
            }
        }

        internal void EnsureIsUnmanagedAttributeExists()
        {
            Debug.Assert(!_needsGeneratedAttributes_IsFrozen);

            if (_needsGeneratedIsUnmanagedAttribute_Value || Compilation.NeedsGeneratedIsUnmanagedAttribute)
            {
                return;
            }

            // Don't report any errors. They should be reported during binding.
            if (Compilation.CheckIfIsUnmanagedAttributeShouldBeEmbedded(diagnosticsOpt: null, locationOpt: null))
            {
                _needsGeneratedIsUnmanagedAttribute_Value = true;
            }
        }

        internal void EnsureNullableAttributeExists()
        {
            Debug.Assert(!_needsGeneratedAttributes_IsFrozen);

            if (_needsGeneratedNullableAttribute_Value || Compilation.NeedsGeneratedNullableAttribute)
            {
                return;
            }

            // Don't report any errors. They should be reported during binding.
            if (Compilation.CheckIfNullableAttributeShouldBeEmbedded(diagnosticsOpt: null, locationOpt: null))
            {
                _needsGeneratedNullableAttribute_Value = true;
            }
        }
    }
}


text:
package org.scaladebugger.api.pipelines

import org.scaladebugger.test.helpers.ParallelMockFunSpec

class FilterOperationSpec extends ParallelMockFunSpec {
  describe("FilterOperation") {
    describe("#process") {
      it("should filter data to include only predicates resolving to true") {
        val expected = Seq(2, 4)

        val data = Seq(1, 2, 3, 4, 5)
        val operation = new FilterOperation[Int](_ % 2 == 0)
        val actual = operation.process(data)

        actual should be (expected)
      }
    }
  }
}


text:
package org.apache.ignite.internal.processors.cache;

import java.util.HashMap;
import java.util.Map;
import javax.cache.processor.EntryProcessor;
import javax.cache.processor.MutableEntry;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.cache.CacheEntryProcessor;
import org.apache.ignite.cluster.ClusterState;
import org.junit.Test;

/**
 * Tests that {@link IgniteCache#invoke(Object, EntryProcessor, Object...)}, {@link IgniteCache#invokeAll(Map, Object...)}
 * overloaded and async methods works fine when cluster in a {@link ClusterState#ACTIVE_READ_ONLY} mode.
 */
public class IgniteCacheInvokeClusterReadOnlyModeSelfTest extends IgniteCacheClusterReadOnlyModeAbstractTest {
    /** Cache entry processor. */
    private static final CacheEntryProcessor<Integer, Integer, Object> CACHE_ENTRY_PROCESSOR =
        (entry, args) -> updateValue(entry);

    /** Entry processor. */
    private static final EntryProcessor<Integer, Integer, Object> ENTRY_PROCESSOR = (entry, args) -> updateValue(entry);

    /** */
    @Test
    public void testInvokeCacheEntryProcessorDenied() {
        performActionReadOnlyExceptionExpected(cache -> cache.invoke(Integer.valueOf(KEY), CACHE_ENTRY_PROCESSOR));
        performActionReadOnlyExceptionExpected(cache -> cache.invoke(Integer.valueOf(UNKNOWN_KEY), CACHE_ENTRY_PROCESSOR));
    }

    /** */
    @Test
    public void testInvokeEntryProcessorDenied() {
        performActionReadOnlyExceptionExpected(cache -> cache.invoke(Integer.valueOf(KEY), ENTRY_PROCESSOR));
        performActionReadOnlyExceptionExpected(cache -> cache.invoke(Integer.valueOf(UNKNOWN_KEY), ENTRY_PROCESSOR));
    }

    /** */
    @Test
    public void testInvokeAsyncCacheEntryProcessorDenied() {
        performActionReadOnlyExceptionExpected(cache -> cache.invokeAsync(KEY, CACHE_ENTRY_PROCESSOR).get());
        performActionReadOnlyExceptionExpected(cache -> cache.invokeAsync(UNKNOWN_KEY, CACHE_ENTRY_PROCESSOR).get());
    }

    /** */
    @Test
    public void testInvokeAsyncEntryProcessorDenied() {
        performActionReadOnlyExceptionExpected(cache -> cache.invokeAsync(KEY, ENTRY_PROCESSOR).get());
        performActionReadOnlyExceptionExpected(cache -> cache.invokeAsync(UNKNOWN_KEY, ENTRY_PROCESSOR).get());
    }

    /** */
    @Test
    public void testInvokeAllCacheEntryProcessorDenied() {
        performActionReadOnlyExceptionExpected(cache -> cache.invokeAll(kvMap.keySet(), CACHE_ENTRY_PROCESSOR));
    }

    /** */
    @Test
    public void testInvokeAllEntryProcessorDenied() {
        performActionReadOnlyExceptionExpected(cache -> cache.invokeAll(kvMap.keySet(), ENTRY_PROCESSOR));
    }

    /** */
    @Test
    public void testInvokeAllCacheEntryProcessorAsyncDenied() {
        performActionReadOnlyExceptionExpected(cache -> cache.invokeAllAsync(kvMap.keySet(), CACHE_ENTRY_PROCESSOR).get());
    }

    /** */
    @Test
    public void testInvokeAllEntryProcessorAsyncDenied() {
        performActionReadOnlyExceptionExpected(cache -> cache.invokeAllAsync(kvMap.keySet(), ENTRY_PROCESSOR).get());
    }

    /** */
    @Test
    public void testInvokeAllCacheEntryProcessorsDenied() {
        Map<Integer, CacheEntryProcessor<Integer, Integer, Object>> map = new HashMap<>();

        kvMap.keySet().forEach(k -> map.put(k, CACHE_ENTRY_PROCESSOR));

        performActionReadOnlyExceptionExpected(cache -> cache.invokeAll(map));
    }

    /** */
    @Test
    public void testInvokeAllEntryProcessorsDenied() {
        Map<Integer, EntryProcessor<Integer, Integer, Object>> map = new HashMap<>();

        kvMap.keySet().forEach(k -> map.put(k, ENTRY_PROCESSOR));

        performActionReadOnlyExceptionExpected(cache -> cache.invokeAll(map));
    }

    /** */
    @Test
    public void testInvokeAllAsyncCacheEntryProcessorsDenied() {
        Map<Integer, CacheEntryProcessor<Integer, Integer, Object>> map = new HashMap<>();

        kvMap.keySet().forEach(k -> map.put(k, CACHE_ENTRY_PROCESSOR));

        performActionReadOnlyExceptionExpected(cache -> cache.invokeAllAsync(map).get());
    }

    /** */
    @Test
    public void testInvokeAllAsyncEntryProcessorsDenied() {
        Map<Integer, EntryProcessor<Integer, Integer, Object>> map = new HashMap<>();

        kvMap.keySet().forEach(k -> map.put(k, ENTRY_PROCESSOR));

        performActionReadOnlyExceptionExpected(cache -> cache.invokeAllAsync(map).get());
    }

    /** */
    private static Object updateValue(MutableEntry<Integer, Integer> entry) {
        assertEquals(kvMap.get(entry.getKey()), entry.getValue());

        entry.setValue(entry.getValue() == null ? 0 : entry.getValue() + 1);

        return null;
    }
}


text:
export import Client = require('./lib/client');
export import ConnectionString = require('./lib/connection_string');
export { Message } from 'azure-iot-common';


text:
var http = require('http');

var posts = [{
    id: '1',
    title: 'test one two three',
    author: { name: 'Hank' },
    date: new Date() - 60 * 60 * 2 * 1000,
    excerpt: "# Lorem ipsum dolor sit amet \n consectetur adipisicing elit. Quasi earum possimus quidem animi perferendis esse eaque reprehenderit quis soluta suscipit. Ipsum, fugiat, laboriosam dolores nobis nihil iste perspiciatis suscipit quibusdam.",
    body: "## Lorem ipsum dolor sit amet \n consectetur adipisicing elit. Nam, facilis, dolores, et cupiditate illum quasi deleniti consequatur maiores minima possimus porro repellendus voluptatibus quam. Nihil, voluptates consequatur aut odit consequuntur!"
}, {
    id: '2',
    title: 'This is test 2',
    author: { name: 'Hank' },
    date: new Date() - 60 * 60 * 4 * 1000,
    excerpt: "# Lorem ipsum dolor sit amet \n consectetur adipisicing elit. Quasi earum possimus quidem animi perferendis esse eaque reprehenderit quis soluta suscipit. Ipsum, fugiat, laboriosam dolores nobis nihil iste perspiciatis suscipit quibusdam.",
    body: "## Lorem ipsum dolor sit amet \n consectetur adipisicing elit. Nam, facilis, dolores, et cupiditate illum quasi deleniti consequatur maiores minima possimus porro repellendus voluptatibus quam. Nihil, voluptates consequatur aut odit consequuntur!"
}];

http.createServer(function(req, res) {
    res.writeHead(200, {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin" : "*"
    });

    res.end(JSON.stringify({
        'posts': posts
    }));
}).listen(5000);
console.log('Server listening on port 5000');


text:
package org.apache.cassandra.db.filter;

import java.io.IOException;
import java.util.*;

import org.apache.cassandra.io.SSTableReader;
import org.apache.cassandra.utils.ReducingIterator;
import org.apache.cassandra.db.*;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.config.DatabaseDescriptor;

public class NamesQueryFilter extends QueryFilter
{
    public final SortedSet<byte[]> columns;

    public NamesQueryFilter(String key, QueryPath columnParent, SortedSet<byte[]> columns)
    {
        super(key, columnParent);
        this.columns = columns;
    }

    public NamesQueryFilter(String key, QueryPath columnParent, byte[] column)
    {
        this(key, columnParent, getSingleColumnSet(column));
    }

    private static TreeSet<byte[]> getSingleColumnSet(byte[] column)
    {
        Comparator<byte[]> singleColumnComparator = new Comparator<byte[]>()
        {
            public int compare(byte[] o1, byte[] o2)
            {
                return Arrays.equals(o1, o2) ? 0 : -1;
            }
        };
        TreeSet<byte[]> set = new TreeSet<byte[]>(singleColumnComparator);
        set.add(column);
        return set;
    }

    public ColumnIterator getMemColumnIterator(Memtable memtable, AbstractType comparator)
    {
        return memtable.getNamesIterator(this);
    }

    public ColumnIterator getSSTableColumnIterator(SSTableReader sstable) throws IOException
    {
        return new SSTableNamesIterator(sstable, key, columns);
    }

    public SuperColumn filterSuperColumn(SuperColumn superColumn, int gcBefore)
    {
        for (IColumn column : superColumn.getSubColumns())
        {
            if (!columns.contains(column.name()))
            {
                superColumn.remove(column.name());
            }
        }
        return superColumn;
    }

    public void collectReducedColumns(IColumnContainer container, Iterator<IColumn> reducedColumns, int gcBefore)
    {
        while (reducedColumns.hasNext())
        {
            IColumn column = reducedColumns.next();
            if (!column.isMarkedForDelete() || column.getLocalDeletionTime() > gcBefore)
                container.addColumn(column);
        }
    }
}