コード例 #1
0
 public override Tuple <QsTuple <LocalVariableDeclaration <QsLocalSymbol> >, QsScope> onProvidedImplementation
     (QsTuple <LocalVariableDeclaration <QsLocalSymbol> > argTuple, QsScope body)
 {
     this._Scope.Reset();
     try { body = this._Scope.Transform(body); }
     catch (Exception ex)
     {
         this.OnException?.Invoke(ex);
         this.Success = false;
     }
     return(new Tuple <QsTuple <LocalVariableDeclaration <QsLocalSymbol> >, QsScope>(argTuple, body));
 }
コード例 #2
0
        /// <summary>
        /// Gets a list of names for each of the parameters in a method.
        /// </summary>
        /// <param name="MethodSignature">The signature of the method to process</param>
        /// <returns>A list of all of the method's parameter names.</returns>
        private List <string> GetParameterNames(CallableSignature MethodSignature)
        {
            List <string> parameterNames = new List <string>();

            // The method's parameters will all be encapsulated into one large tuple, so it can be
            // processed the same way as a nested tuple parameter.
            QsTuple <Tuple <QsSymbol, QsType> > .QsTuple parameterTuple =
                (QsTuple <Tuple <QsSymbol, QsType> > .QsTuple)MethodSignature.Argument;
            ProcessTupleParameter(parameterTuple, parameterNames);

            return(parameterNames);
        }
コード例 #3
0
            private (QsCallable, ResolvedType) GenerateOperation(QsScope contents)
            {
                var newName = UniqueVariableNames.PrependGuid(this.CurrentCallable.Callable.FullName);

                var knownVariables = contents.KnownSymbols.Variables;

                var parameters = QsTuple <LocalVariableDeclaration <QsLocalSymbol> > .NewQsTuple(knownVariables
                                                                                                 .Select(var => QsTuple <LocalVariableDeclaration <QsLocalSymbol> > .NewQsTupleItem(new LocalVariableDeclaration <QsLocalSymbol>(
                                                                                                                                                                                        QsLocalSymbol.NewValidName(var.VariableName),
                                                                                                                                                                                        var.Type,
                                                                                                                                                                                        new InferredExpressionInformation(false, false),
                                                                                                                                                                                        var.Position,
                                                                                                                                                                                        var.Range)))
                                                                                                 .ToImmutableArray());

                var paramTypes = ResolvedType.New(ResolvedTypeKind.UnitType);

                if (knownVariables.Length == 1)
                {
                    paramTypes = knownVariables.First().Type;
                }
                else if (knownVariables.Length > 1)
                {
                    paramTypes = ResolvedType.New(ResolvedTypeKind.NewTupleType(knownVariables
                                                                                .Select(var => var.Type)
                                                                                .ToImmutableArray()));
                }

                var(signature, specializations) = this.MakeSpecializations(newName, paramTypes, SpecializationImplementation.NewProvided(parameters, contents));

                var generatedCallable = new QsCallable(
                    QsCallableKind.Operation,
                    newName,
                    ImmutableArray <QsDeclarationAttribute> .Empty,
                    new Modifiers(AccessModifier.Internal),
                    this.CurrentCallable.Callable.SourceFile,
                    QsNullable <QsLocation> .Null,
                    signature,
                    parameters,
                    specializations.ToImmutableArray(),
                    ImmutableArray <string> .Empty,
                    QsComments.Empty);

                // Change the origin of all type parameter references to use the new name and make all variables immutable
                generatedCallable = UpdateGeneratedOp.Apply(generatedCallable, knownVariables, this.CurrentCallable.Callable.FullName, newName);

                return(generatedCallable, signature.ArgumentType);
            }
コード例 #4
0
        /// <summary>
        /// Parses a parameter that is represented as a tuple, and adds its constituents to the provided
        /// list of named parameters.
        /// </summary>
        /// <param name="TupleParameter">The tuple parameter to parse</param>
        /// <param name="ParameterNames">The collection of parameter names discovered so far</param>
        private void ProcessTupleParameter(QsTuple <Tuple <QsSymbol, QsType> > .QsTuple TupleParameter, List <string> ParameterNames)
        {
            // Go through the tuple and look at all of its elements
            foreach (QsTuple <Tuple <QsSymbol, QsType> > parameter in TupleParameter.Item)
            {
                // If this element is a basic parameter, record its name
                if (parameter is QsTuple <Tuple <QsSymbol, QsType> > .QsTupleItem basicParameter)
                {
                    string parameterName = GetSymbolName(basicParameter.Item.Item1);
                    ParameterNames.Add(parameterName);
                }

                // If this is a nested tuple, process it recursively
                else if (parameter is QsTuple <Tuple <QsSymbol, QsType> > .QsTuple tupleParameter)
                {
                    ProcessTupleParameter(tupleParameter, ParameterNames);
                }
            }
        }
コード例 #5
0
        public void ExcludeInaccessible()
        {
            var elements = new[] { Access.Public, Access.Internal }
            .SelectMany(access =>
            {
                var source = new Source("Tests.qs", QsNullable <string> .Null);
                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,
                    access,
                    source: 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,
                    access,
                    source: 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 => "");
            var ns          = new QsNamespace(CanonName, elements.ToImmutableArray(), emptyLookup);
            var docNs       = new DocNamespace(ns);
            var stream      = new MemoryStream();

#pragma warning disable 618 // WriteToStream is obsolete.
            docNs.WriteToStream(stream, null);
#pragma warning restore 618

            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.publicoperation
  summary: ''
newtypes:
- uid: microsoft.quantum.canon.publictype
  summary: ''
...
";
            var actual   = Encoding.UTF8.GetString(stream.ToArray());
            Assert.Equal(expected, actual);
        }
コード例 #6
0
 /// <summary>
 /// Given the argument tuple of a specialization, returns the argument tuple for its controlled version.
 /// Returns null if the given argument tuple is null.
 /// </summary>
 private static QsTuple <LocalVariableDeclaration <QsLocalSymbol> > ControlledArg(QsTuple <LocalVariableDeclaration <QsLocalSymbol> > arg) =>
 arg != null
     ? SyntaxGenerator.WithControlQubits(arg,
                                         QsNullable <Tuple <int, int> > .Null,
                                         QsLocalSymbol.NewValidName(NonNullable <string> .New(InternalUse.ControlQubitsName)),
                                         QsNullable <Tuple <QsPositionInfo, QsPositionInfo> > .Null)
     : null;
コード例 #7
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"),
                                                      ImmutableArray <QsDeclarationAttribute> .Empty,
                                                      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);
        }
コード例 #8
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"),
                                            ImmutableArray <QsDeclarationAttribute> .Empty,
                                            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);
        }
コード例 #9
0
 /// <summary>
 /// Given the argument tuple of a specialization, returns the argument tuple for its controlled version.
 /// Returns null if the given argument tuple is null.
 /// </summary>
 private static QsTuple <LocalVariableDeclaration <QsLocalSymbol> >?ControlledArg(QsTuple <LocalVariableDeclaration <QsLocalSymbol> > arg) =>
 arg != null
     ? SyntaxGenerator.WithControlQubits(
     arg,
     QsNullable <Position> .Null,
     QsLocalSymbol.NewValidName(InternalUse.ControlQubitsName),
     QsNullable <Range> .Null)
     : null;
コード例 #10
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
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);
        }