Exemplo n.º 1
0
 public void NonNullConstructionAndConversion()
 {
     string x = new string('x', 1);
     NonNullable<string> subject = new NonNullable<string>(x);
     Assert.AreSame(x, (string)subject);
     Assert.AreSame(x, subject.Value);
 }
Exemplo n.º 2
0
 public void DefaultConstructionAndImplicitConversion()
 {
     NonNullable<string> x = new NonNullable<string>();
     try
     {
         string y = x;
         Assert.Fail("Expected exception:" + y);
     }
     catch (NullReferenceException)
     {
         // Expected
     }
 }
Exemplo n.º 3
0
 public void DefaultConstructionAndValueProperty()
 {
     NonNullable<string> x = new NonNullable<string>();
     try
     {
         string y = x.Value;
         Assert.Fail("Expected exception:" + y);
     }
     catch (NullReferenceException)
     {
         // Expected
     }
 }
Exemplo n.º 4
0
 public static NonNullable <T> Create <T>(NonNullable <T> Value) => new NonNullable <T>(Value);
 NonNullable <string> SourceOr(NonNullable <string> origSource) => NonNullable <string> .New(source ?? origSource.Value);
Exemplo n.º 6
0
 private static void SampleMethod(NonNullable<string> text)
 {
     // Shouldn't get here with usual conversions, but could do
     // through default construction. The conversion to string
     // will throw an exception anyway, so we're guaranteed
     // that foo is non-null afterwards.
     string foo = text;
     Assert.IsNotNull(foo);
 }
Exemplo n.º 7
0
        // interface methods

        public bool Transformation(QsCompilation compilation, out QsCompilation transformed)
        {
            transformed = FilterSourceFiles.Apply(compilation);
            var manager = new CompilationUnitManager();

            // get source code from examples

            var fileManagers = ExamplesInDocs.Extract(transformed)
                               .Select(g => InitializeFileManager(g, compilation, g.Key))
                               .Where(m => m != null).ToImmutableHashSet();

            manager.AddOrUpdateSourceFilesAsync(fileManagers, suppressVerification: true);
            var sourceFiles = fileManagers.Select(m => m.FileName).ToImmutableHashSet();

            bool IsGeneratedSourceFile(NonNullable <string> source) => sourceFiles.Contains(source);

            // get everything contained in the compilation as references

            var refName = NonNullable <string> .New(Path.GetFullPath(ReferenceSource));

            var refHeaders = new References.Headers(refName, DllToQs.Rename(compilation).Namespaces);
            var refDict    = new Dictionary <NonNullable <string>, References.Headers> {
                { refName, refHeaders }
            };
            var references = new References(refDict.ToImmutableDictionary());

            manager.UpdateReferencesAsync(references);

            // compile the examples in the doc comments and add any diagnostics to the list of generated diagnostics

            var built       = manager.Build();
            var diagnostics = built.Diagnostics();

            this.Diagnostics.AddRange(diagnostics.Select(d => IRewriteStep.Diagnostic.Create(d, IRewriteStep.Stage.Transformation)));
            if (diagnostics.Any(d => d.Severity == VS.DiagnosticSeverity.Error))
            {
                return(false);
            }

            // add the extracted namespace elements from doc comments to the transformed compilation

            var toBeAdded = built.BuiltCompilation.Namespaces.ToImmutableDictionary(
                ns => ns.Name,
                ns => FilterBySourceFile.Apply(ns, IsGeneratedSourceFile));
            var namespaces = compilation.Namespaces.Select(ns =>
                                                           toBeAdded.TryGetValue(ns.Name, out var add)
                ? new QsNamespace(ns.Name, ns.Elements.AddRange(add.Elements), ns.Documentation)
                : ns);
            var addedNamespaces = toBeAdded.Values.Where(add => !compilation.Namespaces.Any(ns => ns.Name.Value == add.Name.Value));

            transformed = new QsCompilation(namespaces.Concat(addedNamespaces).ToImmutableArray(), compilation.EntryPoints);

            // mark all newly created callables that take unit as argument as unit tests to run on the QuantumSimulator and ResourcesEstimator

            bool IsSuitableForUnitTest(QsCallable c) => IsGeneratedSourceFile(c.SourceFile) && c.Signature.ArgumentType.Resolution.IsUnitType;

            var qsimAtt = AttributeUtils.BuildAttribute(BuiltIn.Test.FullName, AttributeUtils.StringArgument(Constants.QuantumSimulator));
            var restAtt = AttributeUtils.BuildAttribute(BuiltIn.Test.FullName, AttributeUtils.StringArgument(Constants.ResourcesEstimator));

            transformed = AttributeUtils.AddToCallables(transformed, (qsimAtt, IsSuitableForUnitTest), (restAtt, IsSuitableForUnitTest));
            return(true);
        }
        // utils for getting the necessary information for editor commands

        /// <summary>
        /// Throws an ArgumentNullException if the given offset or relative range is null.
        /// </summary>
        internal static Location AsLocation(NonNullable <string> source,
                                            Tuple <int, int> offset, Tuple <QsPositionInfo, QsPositionInfo> relRange) =>
Exemplo n.º 9
0
        /// <summary>
        /// Builds the corresponding .net core assembly from the Q# syntax tree.
        /// </summary>
        public static AssemblyInfo BuildAssembly(Uri[] fileNames, QsCompiler.SyntaxTree.QsNamespace[] syntaxTree, IEnumerable <MetadataReference> references, QSharpLogger logger, string targetDll)
        {
            if (logger.HasErrors)
            {
                return(null);
            }

            logger.LogDebug($"Compiling the following Q# files: {string.Join(",", fileNames.Select(f => f.LocalPath))}");

            try
            {
                // Generate C# simulation code from Q# syntax tree and convert it into C# syntax trees:
                var trees = new List <SyntaxTree>();
                NonNullable <string> GetFileId(Uri uri) => CompilationUnitManager.TryGetFileId(uri, out var id) ? id : NonNullable <string> .New(uri.AbsolutePath);

                foreach (var file in fileNames)
                {
                    var sourceFile = GetFileId(file);
                    var code       = SimulationCode.generate(sourceFile, syntaxTree);
                    var tree       = CSharpSyntaxTree.ParseText(code, encoding: UTF8Encoding.UTF8);
                    trees.Add(tree);
                    logger.LogDebug($"Generated the following C# code for {sourceFile.Value}:\n=============\n{code}\n=============\n");
                }

                // Compile the C# syntax trees:
                var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Debug);

                var compilation = CSharpCompilation.Create(
                    Path.GetFileNameWithoutExtension(targetDll),
                    trees,
                    references,
                    options);

                // Generate the assembly from the C# compilation:
                using (var ms = new MemoryStream())
                {
                    EmitResult result = compilation.Emit(ms);

                    if (!result.Success)
                    {
                        IEnumerable <Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
                                                                                     diagnostic.IsWarningAsError ||
                                                                                     diagnostic.Severity == DiagnosticSeverity.Error);

                        logger.LogError("IQS000", "Could not compile Roslyn dll from working folder.");

                        foreach (Diagnostic diagnostic in failures)
                        {
                            logger.LogError(diagnostic.Id, diagnostic.GetMessage());
                        }

                        return(null);
                    }
                    else
                    {
                        logger.LogDebug($"Assembly successfully generated. Caching at {targetDll}.");
                        var data = ms.ToArray();

                        try
                        {
                            File.WriteAllBytes(targetDll, data);
                        }
                        catch (Exception e)
                        {
                            logger.LogError("IQS001", $"Unable to save assembly cache: {e.Message}.");
                        }

                        return(new AssemblyInfo(Assembly.Load(data), targetDll, syntaxTree));
                    }
                }
            }
            catch (Exception e)
            {
                logger.LogError("IQS002", $"Unexpected error compiling assembly: {e.Message}.");
                return(null);
            }
        }
Exemplo n.º 10
0
 public static byte[] KeyFromPassword(NonNullable <byte[]> password, HashAlgorithmName algorithm, byte[] salt = null, int iterations = DefaultIterations, int keyLength = DefaultKeyLength)
 {
     salt ??= SaltBytes();
     using var keyGen = new Rfc2898DeriveBytes(password, salt, iterations, algorithm);
     return(keyGen.GetBytes(keyLength));
 }
Exemplo n.º 11
0
        /// <summary>
        /// Adds a key/value pair to the dictionary.
        /// </summary>
        /// <typeparam name="TK">key type</typeparam>
        /// <typeparam name="TV">value type</typeparam>
        /// <param name="dictionary"></param>
        /// <param name="key"></param>
        /// <param name="addFunc">add function</param>
        /// <param name="updateFunc">update function</param>
        /// <returns>The new value for the key.</returns>
        /// <remarks>
        /// Add or updates the key/value pair to the dictionary.
        /// </remarks>
        private static TV AddOrUpdateInternal <TK, TV>(IDictionary <TK, TV> dictionary, TK key, NonNullable <Func <TK, TV> > addFunc, NonNullable <Func <TK, TV, TV> > updateFunc)
        {
            dictionary[key] = !dictionary.ContainsKey(key)
                ? addFunc.Value.Invoke(key)
                : updateFunc.Value.Invoke(key, dictionary[key]);

            return(dictionary[key]);
        }
Exemplo n.º 12
0
		public void Constructor_ConstructViaConstructor_NonNullReference()
		{
			NonNullable<string> str = new NonNullable<string>("abc");

			Assert.AreEqual(str.Value, "abc");
		}
Exemplo n.º 13
0
        /// <summary>
        /// Builds the corresponding .net core assembly from the Q# syntax tree.
        /// </summary>
        private AssemblyInfo BuildAssembly(ImmutableDictionary <Uri, string> sources, CompilerMetadata metadata, QSharpLogger logger, string dllName)
        {
            logger.LogDebug($"Compiling the following Q# files: {string.Join(",", sources.Keys.Select(f => f.LocalPath))}");

            var qsCompilation = this.UpdateCompilation(sources, metadata.QsMetadatas, logger);

            if (logger.HasErrors)
            {
                return(null);
            }

            try
            {
                // Generate C# simulation code from Q# syntax tree and convert it into C# syntax trees:
                var trees = new List <SyntaxTree>();
                NonNullable <string> GetFileId(Uri uri) => CompilationUnitManager.TryGetFileId(uri, out var id) ? id : NonNullable <string> .New(uri.AbsolutePath);

                foreach (var file in sources.Keys)
                {
                    var sourceFile = GetFileId(file);
                    var code       = SimulationCode.generate(sourceFile, CodegenContext.Create(qsCompilation.Namespaces));
                    var tree       = CSharpSyntaxTree.ParseText(code, encoding: UTF8Encoding.UTF8);
                    trees.Add(tree);
                    logger.LogDebug($"Generated the following C# code for {sourceFile.Value}:\n=============\n{code}\n=============\n");
                }

                // Compile the C# syntax trees:
                var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Debug);

                var compilation = CSharpCompilation.Create(
                    Path.GetFileNameWithoutExtension(dllName),
                    trees,
                    metadata.RoslynMetadatas,
                    options);

                // Generate the assembly from the C# compilation:
                using (var ms = new MemoryStream())
                    using (var bsonStream = new MemoryStream())
                    {
                        using var writer = new BsonDataWriter(bsonStream)
                              {
                                  CloseOutput = false
                              };
                        var fromSources = qsCompilation.Namespaces.Select(ns => FilterBySourceFile.Apply(ns, s => s.Value.EndsWith(".qs")));
                        Json.Serializer.Serialize(writer, new QsCompilation(fromSources.ToImmutableArray(), qsCompilation.EntryPoints));

                        var resourceDescription = new ResourceDescription
                                                  (
                            resourceName: QsCompiler.ReservedKeywords.DotnetCoreDll.ResourceName,
                            dataProvider: () => new MemoryStream(bsonStream.ToArray()),
                            isPublic: true
                                                  );


                        var result = compilation.Emit(ms, manifestResources: new[] { resourceDescription });

                        if (!result.Success)
                        {
                            IEnumerable <Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
                                                                                         diagnostic.IsWarningAsError ||
                                                                                         diagnostic.Severity == DiagnosticSeverity.Error);

                            logger.LogError("IQS000", "Could not compile Roslyn dll from working folder.");

                            foreach (Diagnostic diagnostic in failures)
                            {
                                logger.LogError(diagnostic.Id, diagnostic.GetMessage());
                            }

                            return(null);
                        }
                        else
                        {
                            logger.LogDebug($"Assembly successfully generated. Caching at {dllName}.");
                            var data = ms.ToArray();

                            try
                            {
                                File.WriteAllBytes(dllName, data);
                            }
                            catch (Exception e)
                            {
                                logger.LogError("IQS001", $"Unable to save assembly cache: {e.Message}.");
                            }

                            return(new AssemblyInfo(Assembly.Load(data), dllName, fromSources.ToArray()));
                        }
                    }
            }
            catch (Exception e)
            {
                logger.LogError("IQS002", $"Unexpected error compiling assembly: {e.Message}.");
                return(null);
            }
        }
Exemplo n.º 14
0
 public BaseUrls(IConfiguration config)
 {
     _baseUrl      = new NonNullable <string>(value: config["BaseUrl"], paramName: "config.BaseUrl");
     _imageBaseUrl = new NonNullable <string>(value: config["ImageBaseUrl"], paramName: "config.ImageBaseUrl");
 }
Exemplo n.º 15
0
 internal static QsQualifiedName MakeFullName(string name)
 {
     return(new QsQualifiedName(CanonName, NonNullable <string> .New(name)));
 }
Exemplo n.º 16
0
 public override NonNullable <string> OnSourceFile(NonNullable <string> f)
 {
     this.SharedState.SourceFiles.Add(f);
     return(base.OnSourceFile(f));
 }
Exemplo n.º 17
0
        public void NonNullable_GetUnderlyingType_WithNullType_ThrowsError()
        {
            Type type = null;

            Assert.Throws <ArgumentNullException>(() => NonNullable.GetUnderlyingType(type), "Value cannot be null.\nParameter name: nonNullableType");
        }
Exemplo n.º 18
0
		public void ToString_ReturnsUnderlyingToString()
		{
			string str = "abc";
			NonNullable<string> str2 = new NonNullable<string>(str);

			Assert.AreEqual(str2.ToString(), str);
		}
Exemplo n.º 19
0
 public static NonNullable <T> Create <T>(T Value, NonNullable <T> Null) => new NonNullable <T>(Value, Null);
Exemplo n.º 20
0
		public void Constructor_DefaultConstructorCausesExceptionWhenCast()
		{
			NonNullable<string> str = new NonNullable<string>();
			string str2 = str;
		}
Exemplo n.º 21
0
 public override NonNullable <string> onSourceFile(NonNullable <string> f)
 {
     this._Scope.Source = f;
     return(base.onSourceFile(f));
 }
Exemplo n.º 22
0
 public static byte[] KeyFromPassword(NonNullable <byte[]> password, byte[] salt = null, int iterations = DefaultIterations, int keyLength = DefaultKeyLength)
 => KeyFromPassword(password, HashAlgorithmName.SHA512, salt, iterations, keyLength);
Exemplo n.º 23
0
        public void ExcludeInaccessible()
        {
            var elements =
                new[] { AccessModifier.DefaultAccess, AccessModifier.Internal }
            .SelectMany(access =>
            {
                var source = NonNullable <string> .New("Tests.qs");
                var unit   = ResolvedType.New(QsType.UnitType);

                var signature = new ResolvedSignature(Array.Empty <QsLocalSymbol>().ToImmutableArray(),
                                                      unit,
                                                      unit,
                                                      CallableInformation.NoInformation);
                var argumentTuple = QsTuple <ArgDeclType> .NewQsTuple(ImmutableArray.Create <QsTuple <ArgDeclType> >());
                var callable      = new QsCallable(kind: QsCallableKind.Operation,
                                                   fullName: MakeFullName(access + "Operation"),
                                                   attributes: ImmutableArray <QsDeclarationAttribute> .Empty,
                                                   modifiers: new Modifiers(access),
                                                   sourceFile: source,
                                                   location: ZeroLocation,
                                                   signature: signature,
                                                   argumentTuple: argumentTuple,
                                                   specializations: ImmutableArray.Create <QsSpecialization>(),
                                                   documentation: ImmutableArray.Create <string>(),
                                                   comments: QsComments.Empty);

                var typeItems = QsTuple <QsTypeItem> .NewQsTuple(
                    ImmutableArray.Create(QsTuple <QsTypeItem> .NewQsTupleItem(QsTypeItem.NewAnonymous(unit))));
                var type = new QsCustomType(fullName: MakeFullName(access + "Type"),
                                            attributes: ImmutableArray <QsDeclarationAttribute> .Empty,
                                            modifiers: new Modifiers(access),
                                            sourceFile: source,
                                            location: ZeroLocation,
                                            type: unit,
                                            typeItems: typeItems,
                                            documentation: ImmutableArray.Create <string>(),
                                            comments: QsComments.Empty);
                return(new[]
                {
                    QsNamespaceElement.NewQsCallable(callable),
                    QsNamespaceElement.NewQsCustomType(type)
                });
            });
            var emptyLookup = Array.Empty <ImmutableArray <string> >().ToLookup(x => NonNullable <string> .New(""));
            var ns          = new QsNamespace(CanonName, elements.ToImmutableArray(), emptyLookup);
            var docNs       = new DocNamespace(ns);
            var stream      = new MemoryStream();

            docNs.WriteToStream(stream, null);

            var expected = @"### YamlMime:QSharpNamespace
# This file is automatically generated.
# Please do not modify this file manually, or your changes may be lost when
# documentation is rebuilt.

uid: microsoft.quantum.canon
name: Microsoft.Quantum.Canon
operations:
- uid: microsoft.quantum.canon.defaultaccessoperation
  summary: ''
newtypes:
- uid: microsoft.quantum.canon.defaultaccesstype
  summary: ''
...
";
            var actual   = Encoding.UTF8.GetString(stream.ToArray());

            Assert.Equal(expected, actual);
        }
Exemplo n.º 24
0
 /// <summary>
 /// Helper function that returns true if the given file id is consistent with the one for a code snippet.
 /// </summary>
 public static bool IsCodeSnippet(NonNullable <string> fileId) =>
 fileId.Value == SNIPPET_FILE_ID.Value;
Exemplo n.º 25
0
 public LocationDef(NonNullable <Coordinate> Region, NonNullable <Coordinate> sector)
 {
     this.Region = Region;
     this.Sector = sector;
 }
Exemplo n.º 26
0
            private static Identifier GetConcreteIdentifier(
                Response currentResponse,
                Stack <Request> requests,
                List <Response> responses,
                Identifier.GlobalCallable globalCallable,
                ImmutableConcretion types)
            {
                QsQualifiedName concreteName = globalCallable.Item;

                var typesHashSet = ImmutableHashSet <KeyValuePair <Tuple <QsQualifiedName, NonNullable <string> >, ResolvedType> > .Empty;

                if (types != null && !types.IsEmpty)
                {
                    typesHashSet = types.ToImmutableHashSet();
                }

                string name = null;

                // Check for recursive call
                if (currentResponse.originalName.Equals(globalCallable.Item) &&
                    typesHashSet.SetEquals(currentResponse.typeResolutions))
                {
                    name = currentResponse.concreteCallable.FullName.Name.Value;
                }

                // Search requests for identifier
                if (name == null)
                {
                    name = requests
                           .Where(req =>
                                  req.originalName.Equals(globalCallable.Item) &&
                                  typesHashSet.SetEquals(req.typeResolutions))
                           .Select(req => req.concreteName.Name.Value)
                           .FirstOrDefault();
                }

                // Search responses for identifier
                if (name == null)
                {
                    name = responses
                           .Where(res =>
                                  res.originalName.Equals(globalCallable.Item) &&
                                  typesHashSet.SetEquals(res.typeResolutions))
                           .Select(res => res.concreteCallable.FullName.Name.Value)
                           .FirstOrDefault();
                }

                // If identifier can't be found, make a new request
                if (name == null)
                {
                    // If this is not a generic, do not change the name
                    if (!typesHashSet.IsEmpty)
                    {
                        // Create new name
                        name         = "_" + Guid.NewGuid().ToString("N") + "_" + globalCallable.Item.Name.Value;
                        concreteName = new QsQualifiedName(globalCallable.Item.Namespace, NonNullable <string> .New(name));
                    }

                    requests.Push(new Request()
                    {
                        originalName    = globalCallable.Item,
                        typeResolutions = types,
                        concreteName    = concreteName
                    });
                }
                else // If the identifier was found, update with the name
                {
                    concreteName = new QsQualifiedName(globalCallable.Item.Namespace, NonNullable <string> .New(name));
                }

                return(Identifier.NewGlobalCallable(concreteName));
            }
Exemplo n.º 27
0
 /// <summary>
 /// LogEventWriter constructor.
 /// </summary>
 /// <param name="category">log category</param>
 /// <param name="logEventListener">log event listener</param>
 public LogEventWriter(NonNullable <string> category, Action <LogEventMessage> logEventListener)
     : this(category, new LogEventReceiver(logEventListener))
 {
 }
Exemplo n.º 28
0
 internal bool IsRelevant(NonNullable <string> source) =>
 this.RelevantSourseFiles?.Contains(source) ?? true;
Exemplo n.º 29
0
        public void ParseOp()
        {
            ArgDeclType BuildArgument(string name, ResolvedType t)
            {
                var validName = QsLocalSymbol.NewValidName(NonNullable <string> .New(name));
                var info      = new InferredExpressionInformation(false, false);

                return(new ArgDeclType(validName, t, info, QsNullable <Tuple <int, int> > .Null, EmptyRange));
            }

            string[] comments =
            {
                "# Summary",
                "Convenience function that performs state preparation by applying a ",
                "`statePrepUnitary` on the input state, followed by adiabatic state ",
                "preparation using a `adiabaticUnitary`, and finally phase estimation ",
                "with respect to `qpeUnitary`on the resulting state using a ",
                "`phaseEstAlgorithm`.",
                "",
                "# Input",
                "## statePrepUnitary",
                "An oracle representing state preparation for the initial dynamical",
                "generator.",
                "## adiabaticUnitary",
                "An oracle representing the adiabatic evolution algorithm to be used",
                "to implement the sweeps to the final state of the algorithm.",
                "## qpeUnitary",
                "An oracle representing a unitary operator $U$ representing evolution",
                "for time $\\delta t$ under a dynamical generator with ground state",
                "$\\ket{\\phi}$ and ground state energy $E = \\phi\\\\,\\delta t$.",
                "## phaseEstAlgorithm",
                "An operation that performs phase estimation on a given unitary operation.",
                "See [iterative phase estimation](/quantum/libraries/characterization#iterative-phase-estimation)",
                "for more details.",
                "## qubits",
                "A register of qubits to be used to perform the simulation.",
                "",
                "# Output",
                "An estimate $\\hat{\\phi}$ of the ground state energy $\\phi$",
                "of the generator represented by $U$."
            };
            string expected = @"### YamlMime:QSharpType
uid: microsoft.quantum.canon.adiabaticstateenergyunitary
name: AdiabaticStateEnergyUnitary
type: operation
namespace: Microsoft.Quantum.Canon
summary: |-
  Convenience function that performs state preparation by applying a
  `statePrepUnitary` on the input state, followed by adiabatic state
  preparation using a `adiabaticUnitary`, and finally phase estimation
  with respect to `qpeUnitary`on the resulting state using a
  `phaseEstAlgorithm`.
syntax: 'operation AdiabaticStateEnergyUnitary (statePrepUnitary : (Qubit[] => Unit), adiabaticUnitary : (Qubit[] => Unit), qpeUnitary : (Qubit[] => Unit is Adj + Ctl), phaseEstAlgorithm : ((Microsoft.Quantum.Canon.DiscreteOracle, Qubit[]) => Double), qubits : Qubit[]) : Double'
input:
  content: '(statePrepUnitary : (Qubit[] => Unit), adiabaticUnitary : (Qubit[] => Unit), qpeUnitary : (Qubit[] => Unit is Adj + Ctl), phaseEstAlgorithm : ((Microsoft.Quantum.Canon.DiscreteOracle, Qubit[]) => Double), qubits : Qubit[])'
  types:
  - name: statePrepUnitary
    summary: |-
      An oracle representing state preparation for the initial dynamical
      generator.
    isOperation: true
    input:
      types:
      - isArray: true
        isPrimitive: true
        uid: Qubit
    output:
      types:
      - isPrimitive: true
        uid: Unit
  - name: adiabaticUnitary
    summary: |-
      An oracle representing the adiabatic evolution algorithm to be used
      to implement the sweeps to the final state of the algorithm.
    isOperation: true
    input:
      types:
      - isArray: true
        isPrimitive: true
        uid: Qubit
    output:
      types:
      - isPrimitive: true
        uid: Unit
  - name: qpeUnitary
    summary: |-
      An oracle representing a unitary operator $U$ representing evolution
      for time $\delta t$ under a dynamical generator with ground state
      $\ket{\phi}$ and ground state energy $E = \phi\\,\delta t$.
    isOperation: true
    input:
      types:
      - isArray: true
        isPrimitive: true
        uid: Qubit
    output:
      types:
      - isPrimitive: true
        uid: Unit
    functors:
    - Adjoint
    - Controlled
  - name: phaseEstAlgorithm
    summary: |-
      An operation that performs phase estimation on a given unitary operation.
      See [iterative phase estimation](/quantum/libraries/characterization#iterative-phase-estimation)
      for more details.
    isOperation: true
    input:
      types:
      - uid: microsoft.quantum.canon.discreteoracle
      - isArray: true
        isPrimitive: true
        uid: Qubit
    output:
      types:
      - isPrimitive: true
        uid: Double
  - name: qubits
    summary: A register of qubits to be used to perform the simulation.
    isArray: true
    isPrimitive: true
    uid: Qubit
output:
  content: Double
  types:
  - summary: |-
      An estimate $\hat{\phi}$ of the ground state energy $\phi$
      of the generator represented by $U$.
    isPrimitive: true
    uid: Double
...
";

            var qubitArrayType = ResolvedType.New(QsType.NewArrayType(ResolvedType.New(QsType.Qubit)));
            var unitType       = ResolvedType.New(QsType.UnitType);
            var doubleType     = ResolvedType.New(QsType.Double);
            var oracleType     = ResolvedType.New(QsType.NewUserDefinedType(new UserDefinedType(CanonName,
                                                                                                NonNullable <string> .New("DiscreteOracle"),
                                                                                                QsNullable <Tuple <QsPositionInfo, QsPositionInfo> > .Null)));
            var noInfo = CallableInformation.NoInformation;
            var acFunctors = ResolvedCharacteristics.FromProperties(new[] { OpProperty.Adjointable, OpProperty.Controllable });
            var acInfo = new CallableInformation(acFunctors, InferredCallableInformation.NoInformation);
            var qubitToUnitOp = ResolvedType.New(QsType.NewOperation(new SigTypeTuple(qubitArrayType, unitType), noInfo));
            var qubitToUnitOpAC = ResolvedType.New(QsType.NewOperation(new SigTypeTuple(qubitArrayType, unitType), acInfo));
            var phaseEstArgs = new ResolvedType[] { oracleType, qubitArrayType }.ToImmutableArray();
            var phaseEstArgTuple = ResolvedType.New(QsType.NewTupleType(phaseEstArgs));
            var phaseEstOp       = ResolvedType.New(QsType.NewOperation(new SigTypeTuple(phaseEstArgTuple, doubleType), noInfo));

            var typeParams = new QsLocalSymbol[] { }.ToImmutableArray();
            var argTypes = new ResolvedType[] { qubitToUnitOp, qubitToUnitOp, qubitToUnitOpAC, phaseEstOp, qubitArrayType }.ToImmutableArray();
            var argTupleType = ResolvedType.New(QsType.NewTupleType(argTypes));
            var signature    = new ResolvedSignature(typeParams, argTupleType, doubleType, noInfo);

            var args = new List <ArgDeclType> {
                BuildArgument("statePrepUnitary", qubitToUnitOp),
                BuildArgument("adiabaticUnitary", qubitToUnitOp),
                BuildArgument("qpeUnitary", qubitToUnitOpAC),
                BuildArgument("phaseEstAlgorithm", phaseEstOp),
                BuildArgument("qubits", qubitArrayType)
            }
            .ConvertAll(arg => QsTuple <ArgDeclType> .NewQsTupleItem(arg))
            .ToImmutableArray();
            var argTuple = QsTuple <ArgDeclType> .NewQsTuple(args);

            var specs = new QsSpecialization[] { }.ToImmutableArray();

            var qsCallable = new QsCallable(QsCallableKind.Operation,
                                            MakeFullName("AdiabaticStateEnergyUnitary"),
                                            NonNullable <string> .New("Techniques.qs"),
                                            ZeroLocation,
                                            signature,
                                            argTuple,
                                            specs,
                                            comments.ToImmutableArray(),
                                            QsComments.Empty);
            var callable = new DocCallable("Microsoft.Quantum.Canon", qsCallable);

            var stream = new StringWriter();

            callable.WriteToFile(stream);
            var s = stream.ToString();

            Assert.Equal(expected, s);
        }
Exemplo n.º 30
0
        public void EqualityMethod()
        {
            string x = new string('1', 10);
            string y = new string('1', 10);
            string z = new string('z', 10);

            NonNullable<string> xx = x;
            NonNullable<string> yy = y;
            NonNullable<string> zz = z;
            NonNullable<string> nn = new NonNullable<string>();

            Assert.IsTrue(xx.Equals(xx));
            Assert.IsTrue(xx.Equals(yy));
            Assert.IsFalse(xx.Equals(zz));
            Assert.IsFalse(xx.Equals(nn));
            Assert.IsFalse(nn.Equals(xx));
        }
Exemplo n.º 31
0
 private QsQualifiedName MakeFullName(string name)
 {
     return(new QsQualifiedName(CanonName, NonNullable <string> .New(name)));
 }
Exemplo n.º 32
0
        public void ParseUdt()
        {
            string[] comments =
            {
                "# Summary",
                "Represents a single primitive term in the set of all dynamical generators, e.g.",
                "Hermitian operators, for which there exists a map from that generator",
                "to time-evolution by that that generator, through \"EvolutionSet\".",
                "",
                "# Description",
                "The first element",
                "(Int[], Double[]) is indexes that single term -- For instance, the Pauli string",
                "XXY with coefficient 0.5 would be indexed by ([1,1,2], [0.5]). Alternatively,",
                "Hamiltonians parameterized by a continuous variable, such as X cos φ + Y sin φ,",
                "might for instance be represented by ([], [φ]). The second",
                "element indexes the subsystem on which the generator acts on.",
                "",
                "# Remarks",
                "> [!WARNING]",
                "> The interpretation of an `GeneratorIndex` is not defined except",
                "> with reference to a particular set of generators.",
                "",
                "# Example",
                "Using  <xref:microsoft.quantum.canon.paulievolutionset>, the operator",
                "$\\pi X_2 X_5 Y_9$ is represented as:",
                "```qsharp",
                "let index = GeneratorIndex(([1; 1; 2], [PI()]), [2; 5; 9]);",
                "```",
                "",
                "# See Also",
                "- @\"microsoft.quantum.canon.paulievolutionset\"",
                "- @\"microsoft.quantum.canon.evolutionset\""
            };
            string expected = @"### YamlMime:QSharpType
uid: microsoft.quantum.canon.generatorindex
name: GeneratorIndex
type: newtype
namespace: Microsoft.Quantum.Canon
summary: |-
  Represents a single primitive term in the set of all dynamical generators, e.g.
  Hermitian operators, for which there exists a map from that generator
  to time-evolution by that that generator, through ""EvolutionSet"".

  The first element
  (Int[], Double[]) is indexes that single term -- For instance, the Pauli string
  XXY with coefficient 0.5 would be indexed by ([1,1,2], [0.5]). Alternatively,
  Hamiltonians parameterized by a continuous variable, such as X cos φ + Y sin φ,
  might for instance be represented by ([], [φ]). The second
  element indexes the subsystem on which the generator acts on.
remarks: |-
  > [!WARNING]
  > The interpretation of an `GeneratorIndex` is not defined except
  > with reference to a particular set of generators.

  ### Examples
  Using  <xref:microsoft.quantum.canon.paulievolutionset>, the operator
  $\pi X_2 X_5 Y_9$ is represented as:

  ```qsharp
  let index = GeneratorIndex(([1; 1; 2], [PI()]), [2; 5; 9]);
  ```
syntax: newtype GeneratorIndex = ((Int[], Double[]), Int[]);
seeAlso:
- microsoft.quantum.canon.paulievolutionset
- microsoft.quantum.canon.evolutionset
...
";
            var    intArrayType = ResolvedType.New(QsType.NewArrayType(ResolvedType.New(QsType.Int)));
            var    doubleArrayType = ResolvedType.New(QsType.NewArrayType(ResolvedType.New(QsType.Double)));
            var    innerTuple = new ResolvedType[] { intArrayType, doubleArrayType }.ToImmutableArray();
            var    innerTupleType = ResolvedType.New(QsType.NewTupleType(innerTuple));
            var    baseTuple = new ResolvedType[] { innerTupleType, intArrayType }.ToImmutableArray();
            var    baseType      = ResolvedType.New(QsType.NewTupleType(baseTuple));
            var    anonymousItem = QsTuple <QsTypeItem> .NewQsTupleItem(QsTypeItem.NewAnonymous(baseType));

            var typeItems = QsTuple <QsTypeItem> .NewQsTuple(ImmutableArray.Create(anonymousItem));

            var generatorIndexType = new QsCustomType(MakeFullName("GeneratorIndex"),
                                                      NonNullable <string> .New("GeneratorRepresentation.qs"),
                                                      ZeroLocation,
                                                      baseType,
                                                      typeItems,
                                                      comments.ToImmutableArray(),
                                                      QsComments.Empty);
            var udt = new DocUdt("Microsoft.Quantum.Canon", generatorIndexType);

            var stream = new StringWriter();

            udt.WriteToFile(stream);
            var s = stream.ToString();

            Assert.Equal(expected, s);
        }
Exemplo n.º 33
0
 public static byte[] KeyFromPassword(NonNullable <string> password, byte[] salt = null, int iterations = DefaultIterations, int keyLength = DefaultKeyLength)
 => KeyFromPassword(Encoding.UTF8.GetBytes(password.Value), salt, iterations, keyLength);
Exemplo n.º 34
0
        public void EqualityOperator()
        {
            string x = new string('1', 10);
            string y = new string('1', 10);
            string z = new string('z', 10);

            NonNullable<string> xx = x;
            NonNullable<string> yy = y;
            NonNullable<string> zz = z;
            NonNullable<string> nn = new NonNullable<string>();

#pragma warning disable 1718
            Assert.IsTrue(xx == xx);
            Assert.IsTrue(yy == yy);
            Assert.IsTrue(zz == zz);
            Assert.IsTrue(nn == nn);
#pragma warning restore 1718

            Assert.IsFalse(xx == yy);
            Assert.IsFalse(yy == zz);
            Assert.IsFalse(zz == nn);
            Assert.IsFalse(nn == xx);
        }
Exemplo n.º 35
0
        public static IDisposable On <T1, T2, T3, T4, T5, T6, T7, T8>(this SignalRChannel channel, string methodName, Action <T1, T2, T3, T4, T5, T6, T7, T8> handler)
        {
            var connection = new NonNullable <HubConnection>(channel.Connection);

            return(connection.Value.On(methodName, handler));
        }
Exemplo n.º 36
0
		public void Value_ThrowExceptionIfValueNull()
		{
			//This is the only way to create a NonNullable that contains a null reference.
			//C# does not allow overriding the default constructor on structs.
			NonNullable<string> str = new NonNullable<string>();
			string s = str.Value;
		}
Exemplo n.º 37
0
        public static IDisposable On(this SignalRChannel channel, string methodName, Type[] parameterTypes, Func <object[], Task> handler)
        {
            var connection = new NonNullable <HubConnection>(channel.Connection);

            return(connection.Value.On(methodName, parameterTypes, handler));
        }
Exemplo n.º 38
0
		public void Constructor_ConstructViaConstructor_NullReference()
		{
			NonNullable<string> str = new NonNullable<string>(null);
		}
Exemplo n.º 39
0
 : new QsQualifiedName(NonNullable <string> .New(@namespace), NonNullable <string> .New(name));
Exemplo n.º 40
0
		public void Constructor_DefaultConstructorCausesExceptionWhenValueRetrieved()
		{
			NonNullable<string> str = new NonNullable<string>();
			string str2 = str.Value;
		}
Exemplo n.º 41
0
 public static byte[] KeyFromPassword(NonNullable <string> password, byte[] salt = null, int iterations = DefaultIterations, int keyLength = DefaultKeyLength)
 => KeyFromPassword(password.Value.Utf8ToBytes(), salt, iterations, keyLength);
Exemplo n.º 42
0
		private bool ImplicitCastMethod(NonNullable<string> str)
		{
			return true;
		}
Exemplo n.º 43
0
 /// <summary>
 /// Builds a string literal with the given content that can be used as argument to a Q# attribute.
 /// The value of the string literal is set to the empty string if the given content is null.
 /// </summary>
 public static TypedExpression StringArgument(string content) =>
 SyntaxGenerator.StringLiteral(NonNullable <string> .New(content ?? ""), ImmutableArray <TypedExpression> .Empty);