diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index 3dc367af54..78eac8cab7 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -3,7 +3,7 @@ "isRoot": true, "tools": { "fantomas-tool": { - "version": "4.3.0-alpha-001", + "version": "4.4.0", "commands": [ "fantomas" ] diff --git a/.editorconfig b/.editorconfig index 060f21b491..5533ec32a9 100644 --- a/.editorconfig +++ b/.editorconfig @@ -54,6 +54,7 @@ indent_size = 4 fsharp_max_array_or_list_width = 80 fsharp_max_dot_get_expression_width = 100 +fsharp_max_if_then_else_short_width = 100 fsharp_max_infix_operator_expression = 100 fsharp_max_record_number_of_items = 2 fsharp_max_value_binding_width = 100 diff --git a/src/QsCompiler/Core/ConstructorExtensions.fs b/src/QsCompiler/Core/ConstructorExtensions.fs index bf359608db..8038a35f43 100644 --- a/src/QsCompiler/Core/ConstructorExtensions.fs +++ b/src/QsCompiler/Core/ConstructorExtensions.fs @@ -169,10 +169,11 @@ type ResolvedSignature with } type QsSpecialization with - static member New kind - (source, location) - (parent, attributes, typeArgs, signature, implementation, documentation, comments) - = + static member New + kind + (source, location) + (parent, attributes, typeArgs, signature, implementation, documentation, comments) + = { Kind = kind Parent = parent @@ -192,17 +193,11 @@ type QsSpecialization with static member NewControlledAdjoint = QsSpecialization.New QsControlledAdjoint type QsCallable with - static member New kind - (source, location) - (name, - attributes, - access, - argTuple, - signature, - specializations: IEnumerable<_>, - documentation, - comments) - = + static member New + kind + (source, location) + (name, attributes, access, argTuple, signature, specializations: IEnumerable<_>, documentation, comments) + = { Kind = kind FullName = name @@ -251,7 +246,9 @@ type QsNamespaceElement with static member NewOperation loc = QsCallable.NewOperation loc >> QsCallable - static member NewFunction loc = QsCallable.NewFunction loc >> QsCallable + static member NewFunction loc = + QsCallable.NewFunction loc >> QsCallable + static member NewType loc = QsCustomType.New loc >> QsCustomType type QsNamespace with diff --git a/src/QsCompiler/Core/DeclarationHeaders.fs b/src/QsCompiler/Core/DeclarationHeaders.fs index d88ab79874..0c9a98c3a1 100644 --- a/src/QsCompiler/Core/DeclarationHeaders.fs +++ b/src/QsCompiler/Core/DeclarationHeaders.fs @@ -49,11 +49,14 @@ module DeclarationHeader = type private NullableOffsetConverter() = inherit JsonConverter() - override this.ReadJson(reader: JsonReader, - objectType: Type, - existingValue: Offset, - hasExistingValue: bool, - serializer: JsonSerializer) = + override this.ReadJson + ( + reader: JsonReader, + objectType: Type, + existingValue: Offset, + hasExistingValue: bool, + serializer: JsonSerializer + ) = if reader.ValueType <> typeof || (string) reader.Value <> "Undefined" then let offset = serializer.Deserialize(reader) if Object.ReferenceEquals(offset, null) then Offset.Undefined else Offset.Defined offset @@ -68,11 +71,14 @@ module DeclarationHeader = type private NullableRangeConverter() = inherit JsonConverter() - override this.ReadJson(reader: JsonReader, - objectType: Type, - existingValue: Range, - hasExistingValue: bool, - serializer: JsonSerializer) = + override this.ReadJson + ( + reader: JsonReader, + objectType: Type, + existingValue: Range, + hasExistingValue: bool, + serializer: JsonSerializer + ) = if reader.ValueType <> typeof || (string) reader.Value <> "Undefined" then let range = serializer.Deserialize(reader) if Object.ReferenceEquals(range, null) then Range.Undefined else Range.Defined range @@ -202,10 +208,7 @@ type TypeDeclarationHeader = let header = TypeDeclarationHeader.OfSchema schema let attributesAreNullOrDefault = Object.ReferenceEquals(header.Attributes, null) || header.Attributes.IsDefault - let header = - if attributesAreNullOrDefault - then { header with Attributes = ImmutableArray.Empty } - else header // no reason to raise an error + let header = if attributesAreNullOrDefault then { header with Attributes = ImmutableArray.Empty } else header // no reason to raise an error if not (Object.ReferenceEquals(header.TypeItems, null)) then success, header @@ -336,15 +339,18 @@ type CallableDeclarationHeader = let header = CallableDeclarationHeader.OfSchema schema let attributesAreNullOrDefault = Object.ReferenceEquals(header.Attributes, null) || header.Attributes.IsDefault - let header = - if attributesAreNullOrDefault - then { header with Attributes = ImmutableArray.Empty } - else header // no reason to raise an error + let header = if attributesAreNullOrDefault then { header with Attributes = ImmutableArray.Empty } else header // no reason to raise an error let header = { header with ArgumentTuple = header.ArgumentTuple |> setInferredInfo } - if Object.ReferenceEquals(header.Signature.Information, null) - || Object.ReferenceEquals(header.Signature.Information.Characteristics, null) then + if + Object.ReferenceEquals(header.Signature.Information, null) + || Object.ReferenceEquals + ( + header.Signature.Information.Characteristics, + null + ) + then false, { header with Signature = { header.Signature with Information = CallableInformation.Invalid } } else success, header @@ -457,10 +463,7 @@ type SpecializationDeclarationHeader = let typeArgsAreNull = Object.ReferenceEquals(header.TypeArguments, null) let attributesAreNullOrDefault = Object.ReferenceEquals(header.Attributes, null) || header.Attributes.IsDefault - let header = - if attributesAreNullOrDefault - then { header with Attributes = ImmutableArray.Empty } - else header // no reason to raise an error + let header = if attributesAreNullOrDefault then { header with Attributes = ImmutableArray.Empty } else header // no reason to raise an error if not (infoIsNull || typeArgsAreNull) then success, header diff --git a/src/QsCompiler/Core/SymbolResolution.fs b/src/QsCompiler/Core/SymbolResolution.fs index 5626faa17c..f5771a8d83 100644 --- a/src/QsCompiler/Core/SymbolResolution.fs +++ b/src/QsCompiler/Core/SymbolResolution.fs @@ -63,31 +63,32 @@ type SpecializationBundleProperties = DefinedGenerators: ImmutableDictionary } - /// Given the type- and set-arguments associated with a certain specialization, - /// determines the corresponding unique identifier for all specializations with the same type- and set-arguments. - static member public BundleId(typeArgs: QsNullable>) = - typeArgs - |> QsNullable<_>.Map(fun args -> (args |> Seq.map (fun t -> t.WithoutRangeInfo)).ToImmutableArray()) - - /// - /// Returns an identifier for the bundle to which the given specialization declaration belongs to. - /// - /// No (partial) resolution is defined for the given specialization. - static member internal BundleId(spec: Resolution<_, _>) = - match spec.Resolved with - | Null -> InvalidOperationException "cannot determine id for unresolved specialization" |> raise - | Value (gen: ResolvedGenerator) -> SpecializationBundleProperties.BundleId gen.TypeArguments - - /// Given a function that associates an item of the given array with a particular set of type- and set-arguments, - /// as well as a function that associates it with a certain specialization kind, - /// returns a dictionary that contains a dictionary mapping the specialization kind to the corresponding item for each set of type arguments. - /// The keys for the returned dictionary are the BundleIds for particular sets of type- and characteristics-arguments. - static member public Bundle (getTypeArgs: Func<_, _>, getKind: Func<_, QsSpecializationKind>) - (specs: IEnumerable<'T>) - = - specs - .ToLookup(new Func<_, _>(getTypeArgs.Invoke >> SpecializationBundleProperties.BundleId)) - .ToDictionary((fun group -> group.Key), (fun group -> group.ToImmutableDictionary(getKind))) + /// Given the type- and set-arguments associated with a certain specialization, + /// determines the corresponding unique identifier for all specializations with the same type- and set-arguments. + static member public BundleId(typeArgs: QsNullable>) = + typeArgs + |> QsNullable<_>.Map (fun args -> (args |> Seq.map (fun t -> t.WithoutRangeInfo)).ToImmutableArray()) + + /// + /// Returns an identifier for the bundle to which the given specialization declaration belongs to. + /// + /// No (partial) resolution is defined for the given specialization. + static member internal BundleId(spec: Resolution<_, _>) = + match spec.Resolved with + | Null -> InvalidOperationException "cannot determine id for unresolved specialization" |> raise + | Value (gen: ResolvedGenerator) -> SpecializationBundleProperties.BundleId gen.TypeArguments + + /// Given a function that associates an item of the given array with a particular set of type- and set-arguments, + /// as well as a function that associates it with a certain specialization kind, + /// returns a dictionary that contains a dictionary mapping the specialization kind to the corresponding item for each set of type arguments. + /// The keys for the returned dictionary are the BundleIds for particular sets of type- and characteristics-arguments. + static member public Bundle + (getTypeArgs: Func<_, _>, getKind: Func<_, QsSpecializationKind>) + (specs: IEnumerable<'T>) + = + specs + .ToLookup(new Func<_, _>(getTypeArgs.Invoke >> SpecializationBundleProperties.BundleId)) + .ToDictionary((fun group -> group.Key), (fun group -> group.ToImmutableDictionary(getKind))) /// Represents the outcome of resolving a symbol. @@ -156,16 +157,18 @@ module internal ResolutionResult = /// Returns a Found result if there is only one in the sequence. If there is more than one, returns an Ambiguous /// result containing the namespaces of all Found results given by applying nsGetter to each value. Otherwise, /// returns the same value as TryFirstBest. - let internal TryAtMostOne<'T> (nsGetter: 'T -> string) (results: seq>): ResolutionResult<'T> = + let internal TryAtMostOne<'T> (nsGetter: 'T -> string) (results: seq>) : ResolutionResult<'T> = let found = results - |> Seq.filter (function + |> Seq.filter + (function | Found _ -> true | _ -> false) - if Seq.length found > 1 - then found |> Seq.map (Map nsGetter >> ToList) |> Seq.concat |> Ambiguous - else found |> Seq.tryExactlyOne |> Option.defaultWith (fun () -> TryFirstBest results) + if Seq.length found > 1 then + found |> Seq.map (Map nsGetter >> ToList) |> Seq.concat |> Ambiguous + else + found |> Seq.tryExactlyOne |> Option.defaultWith (fun () -> TryFirstBest results) /// Returns a Found result if there is only one in the sequence. If there is more than one, raises an exception. /// Otherwise, returns the same value as ResolutionResult.TryFirstBest. @@ -243,11 +246,9 @@ module SymbolResolution = /// If several attributes indicate deprecation, a redirection is suggested based on the first deprecation attribute. let internal TryFindRedirectInUnresolved checkQualification attributes = let getRedirect (att: AttributeAnnotation) = - if att |> IndicatesDeprecation checkQualification - then Some att.Argument - else None + if att |> IndicatesDeprecation checkQualification then Some att.Argument else None - StringArgument (getRedirect, (fun ex -> ex.Expression)) attributes + StringArgument(getRedirect, (fun ex -> ex.Expression)) attributes |> Seq.tryHead |> QsNullable.ofOption @@ -259,7 +260,7 @@ module SymbolResolution = let getRedirect (att: QsDeclarationAttribute) = if att |> BuiltIn.MarksDeprecation then Some att.Argument else None - StringArgument (getRedirect, (fun ex -> ex.Expression)) attributes + StringArgument(getRedirect, (fun ex -> ex.Expression)) attributes |> Seq.tryHead |> QsNullable.ofOption @@ -272,9 +273,7 @@ module SymbolResolution = let pieces = str.Split '.' { Namespace = String.Join('.', pieces.Take(pieces.Length - 1)); Name = pieces.Last() } - if matchQualifiedName.Success - then Some(matchQualifiedName.Value |> asQualifiedName) - else None + if matchQualifiedName.Success then Some(matchQualifiedName.Value |> asQualifiedName) else None /// Checks whether the given attributes define an alternative name that may be used when loading a type or callable for testing purposes. /// Returns the qualified name to use as Value if such a name is defined, or Null otherwise. @@ -283,7 +282,7 @@ module SymbolResolution = let getTestName (att: QsDeclarationAttribute) = if att |> BuiltIn.DefinesNameForTesting then Some att.Argument else None - StringArgument (getTestName, (fun ex -> ex.Expression)) attributes + StringArgument(getTestName, (fun ex -> ex.Expression)) attributes |> Seq.tryHead |> Option.bind TryAsQualifiedName |> QsNullable.ofOption @@ -293,11 +292,9 @@ module SymbolResolution = /// The returned Value is based on the first attribute that indicates the original name. let TryGetOriginalName attributes = let loadedViaTestName (att: QsDeclarationAttribute) = - if att |> BuiltIn.DefinesLoadedViaTestNameInsteadOf - then Some att.Argument - else None + if att |> BuiltIn.DefinesLoadedViaTestNameInsteadOf then Some att.Argument else None - StringArgument (loadedViaTestName, (fun ex -> ex.Expression)) attributes + StringArgument(loadedViaTestName, (fun ex -> ex.Expression)) attributes |> Seq.tryHead |> Option.bind TryAsQualifiedName |> QsNullable.ofOption @@ -321,7 +318,7 @@ module SymbolResolution = | true, valid -> valid | false, _ -> null - StringArgument (getTarget, (fun ex -> ex.Expression)) attributes + StringArgument(getTarget, (fun ex -> ex.Expression)) attributes |> Seq.map targetName |> ImmutableHashSet.CreateRange @@ -337,13 +334,14 @@ module SymbolResolution = None let capabilities = - StringArgument (getCapability, (fun ex -> ex.Expression)) attributes + StringArgument(getCapability, (fun ex -> ex.Expression)) attributes |> QsNullable<_>.Choose RuntimeCapability.TryParse |> ImmutableHashSet.CreateRange - if Seq.isEmpty capabilities - then Null - else capabilities |> Seq.reduce RuntimeCapability.Combine |> Value + if Seq.isEmpty capabilities then + Null + else + capabilities |> Seq.reduce RuntimeCapability.Combine |> Value /// Checks whether the given attributes defines a code for an instruction within the quantum instruction set that matches this callable. /// Returns the string code as Value if this is the case, and Null otherwise. @@ -352,7 +350,7 @@ module SymbolResolution = let loadedViaTestName (att: QsDeclarationAttribute) = if att |> BuiltIn.DefinesTargetInstruction then Some att.Argument else None - StringArgument (loadedViaTestName, (fun ex -> ex.Expression)) attributes + StringArgument(loadedViaTestName, (fun ex -> ex.Expression)) attributes |> Seq.tryHead |> QsNullable.ofOption @@ -388,8 +386,8 @@ module SymbolResolution = let isNamedParam = isTypeParam name [ - if argType.Exists isNamedParam |> not && returnType.Exists isNamedParam |> not - then QsCompilerDiagnostic.Warning (WarningCode.UnusedTypeParam, [ "'" + name ]) range + if argType.Exists isNamedParam |> not && returnType.Exists isNamedParam |> not then + QsCompilerDiagnostic.Warning(WarningCode.UnusedTypeParam, [ "'" + name ]) range ] | InvalidName -> [] @@ -440,29 +438,31 @@ module SymbolResolution = /// Returns the resolved signature and argument tuple, as well as an array with the diagnostics created during resolution. /// /// is empty. - let internal ResolveCallableSignature (resolveType, specBundleInfos: CallableInformation list) - (signature: CallableSignature) - = + let internal ResolveCallableSignature + (resolveType, specBundleInfos: CallableInformation list) + (signature: CallableSignature) + = let orDefault (range: QsNullable<_>) = range.ValueOr Range.Zero let typeParams, tpErrs = signature.TypeParameters - |> Seq.fold (fun (tps, errs) qsSym -> - let range = qsSym.Range |> orDefault - let invalidTp = InvalidName, range - - match qsSym.Symbol with - | QsSymbolKind.InvalidSymbol -> invalidTp :: tps, errs - | QsSymbolKind.Symbol sym -> - if not (tps |> List.exists (fst >> (=) (ValidName sym))) then - (ValidName sym, range) :: tps, errs - else + |> Seq.fold + (fun (tps, errs) qsSym -> + let range = qsSym.Range |> orDefault + let invalidTp = InvalidName, range + + match qsSym.Symbol with + | QsSymbolKind.InvalidSymbol -> invalidTp :: tps, errs + | QsSymbolKind.Symbol sym -> + if not (tps |> List.exists (fst >> (=) (ValidName sym))) then + (ValidName sym, range) :: tps, errs + else + invalidTp :: tps, + (range |> QsCompilerDiagnostic.Error(ErrorCode.TypeParameterRedeclaration, [ sym ])) :: errs + | _ -> invalidTp :: tps, - (range |> QsCompilerDiagnostic.Error(ErrorCode.TypeParameterRedeclaration, [ sym ])) :: errs - | _ -> - invalidTp :: tps, - (range |> QsCompilerDiagnostic.Error(ErrorCode.InvalidTypeParameterDeclaration, [])) :: errs) - ([], []) + (range |> QsCompilerDiagnostic.Error(ErrorCode.InvalidTypeParameterDeclaration, [])) :: errs) + ([], []) |> (fun (tps, errs) -> tps |> List.rev, errs |> List.rev |> List.toArray) let resolveArg (sym, range) t = @@ -478,11 +478,12 @@ module SymbolResolution = let resolveType = let validTpNames = typeParams - |> List.choose - (fst - >> function - | ValidName name -> Some name - | InvalidName -> None) + |> List.choose ( + fst + >> function + | ValidName name -> Some name + | InvalidName -> None + ) resolveType (validTpNames.ToImmutableArray()) @@ -549,7 +550,8 @@ module SymbolResolution = ImmutableArray.Create udtTuple |> QsTuple |> ResolveArgumentTuple(resolveItem, resolveType) let underlyingType = - argTuple.ResolveWith(function + argTuple.ResolveWith + (function | Anonymous t -> t.WithoutRangeInfo | Named x -> x.Type.WithoutRangeInfo) @@ -663,13 +665,14 @@ module SymbolResolution = | ResultLiteral r -> (ResultLiteral r, Result) |> asTypedExpression ex.Range, [||] | PauliLiteral p -> (PauliLiteral p, Pauli) |> asTypedExpression ex.Range, [||] | StringLiteral (s, exs) -> - if exs.Length <> 0 - then invalidExpr ex.Range, [| ex.Range |> diagnostic ErrorCode.InterpolatedStringInAttribute |] - else (StringLiteral(s, ImmutableArray.Empty), String) |> asTypedExpression ex.Range, [||] + if exs.Length <> 0 then + invalidExpr ex.Range, [| ex.Range |> diagnostic ErrorCode.InterpolatedStringInAttribute |] + else + (StringLiteral(s, ImmutableArray.Empty), String) |> asTypedExpression ex.Range, [||] | ValueTuple vs when vs.Length = 1 -> argExpression (vs.First()) | ValueTuple vs -> - if vs.Length = 0 - then ArgumentException "tuple valued attribute argument requires at least one tuple item" |> raise + if vs.Length = 0 then + ArgumentException "tuple valued attribute argument requires at least one tuple item" |> raise let innerExs, errs = aggregateInner vs let types = (innerExs |> Seq.map (fun ex -> ex.ResolvedType)).ToImmutableArray() @@ -706,7 +709,7 @@ module SymbolResolution = let onTypeParam (_, tpRange) = InvalidType, [| tpRange |> diagnostic ErrorCode.TypeParameterizedArgumentInAttribute |] - let resBaseType, typeErrs = ResolveType (onUdt, onTypeParam) bt + let resBaseType, typeErrs = ResolveType(onUdt, onTypeParam) bt let resIdx, idxErrs = argExpression idx (NewArray(resBaseType, resIdx), ArrayType resBaseType) |> asTypedExpression ex.Range, @@ -904,7 +907,10 @@ module SymbolResolution = /// Otherwise resolves any valid directive to a "distribute" directive. /// Does *not* generate diagnostics for things that do not require semantic information to detect /// (these should be detected and raised upon context verification). - let private ResolveControlledGeneratorDirective (info: InferredCallableInformation) (gen: QsSpecializationGenerator) = + let private ResolveControlledGeneratorDirective + (info: InferredCallableInformation) + (gen: QsSpecializationGenerator) + = if info.IsIntrinsic then NeedsToBeIntrinsic(gen, false) else @@ -931,10 +937,11 @@ module SymbolResolution = /// b) to a "distribute" directive to be applied to the adjoint version otherwise. /// Does *not* generate diagnostics for things that do not require semantic information to detect /// (these should be detected and raised upon context verification). - let private ResolveControlledAdjointGeneratorDirective (adjGenKind, ctlGenKind) - (info: InferredCallableInformation) - (gen: QsSpecializationGenerator) - = + let private ResolveControlledAdjointGeneratorDirective + (adjGenKind, ctlGenKind) + (info: InferredCallableInformation) + (gen: QsSpecializationGenerator) + = if info.IsSelfAdjoint then NeedsToBeSelfInverse gen elif info.IsIntrinsic then @@ -988,10 +995,11 @@ module SymbolResolution = /// determines the resolved characteristics of the specializations for these type- and set-arguments. /// Calls generateSpecialization for each missing specialization kind that can be inferred. /// Returns the resolved characteristics as well as an array of diagnostics. - let private InferCharacteristicsAndMetadata generateSpecialization - (specKinds: ImmutableDictionary<_, _>) - (characteristics: Characteristics, declLocation: QsLocation) - = + let private InferCharacteristicsAndMetadata + generateSpecialization + (specKinds: ImmutableDictionary<_, _>) + (characteristics: Characteristics, declLocation: QsLocation) + = let adjExists, ctlExists = specKinds.ContainsKey QsAdjoint, specKinds.ContainsKey QsControlled let bodyExists, ctlAdjExists = specKinds.ContainsKey QsBody, specKinds.ContainsKey QsControlledAdjoint @@ -1006,14 +1014,13 @@ module SymbolResolution = let adjSup, ctlSup = supported.Contains Adjointable, supported.Contains Controllable let additional = - ResolvedCharacteristics.FromProperties - (seq { - if (adjExists || ctlAdjExists) && not adjSup - then yield Adjointable + ResolvedCharacteristics.FromProperties( + seq { + if (adjExists || ctlAdjExists) && not adjSup then yield Adjointable - if (ctlExists || ctlAdjExists) && not ctlSup - then yield Controllable - }) + if (ctlExists || ctlAdjExists) && not ctlSup then yield Controllable + } + ) let adj, ctl = (adjExists || ctlAdjExists || adjSup, annotRange adjSup), @@ -1039,12 +1046,12 @@ module SymbolResolution = let ctlAdjRange = annotRange (adjRange <> Null && ctlRange <> Null) let errs = - Array.concat [ if supportsAdj && not adjExists - then yield generateSpecialization QsAdjoint (declLocation, adjRange) - if supportsCtl && not ctlExists - then yield generateSpecialization QsControlled (declLocation, ctlRange) - if supportsAdj && supportsCtl && not ctlAdjExists - then yield generateSpecialization QsControlledAdjoint (declLocation, ctlAdjRange) + Array.concat [ if supportsAdj && not adjExists then + yield generateSpecialization QsAdjoint (declLocation, adjRange) + if supportsCtl && not ctlExists then + yield generateSpecialization QsControlled (declLocation, ctlRange) + if supportsAdj && supportsCtl && not ctlAdjExists then + yield generateSpecialization QsControlledAdjoint (declLocation, ctlAdjRange) if not bodyExists then yield generateSpecialization QsBody (declLocation, Null) @@ -1059,9 +1066,10 @@ module SymbolResolution = | Error _ -> true | _ -> false - if errs |> Array.exists isError - then InvalidSetExpr |> ResolvedCharacteristics.New, metadata, errs - else resolved, metadata, errs + if errs |> Array.exists isError then + InvalidSetExpr |> ResolvedCharacteristics.New, metadata, errs + else + resolved, metadata, errs /// /// Given the signature and source file of a callable as well as all specializations defined for it, constructs @@ -1072,10 +1080,11 @@ module SymbolResolution = /// Returns the constructed dictionary as well as an array of diagnostics. /// /// No (partial) resolution is defined for any one of the given specializations. - let internal GetBundleProperties generateSpecialization - (parentSignature: Resolution, source) - (definedSpecs: IEnumerable<_>) - = + let internal GetBundleProperties + generateSpecialization + (parentSignature: Resolution, source) + (definedSpecs: IEnumerable<_>) + = let declCharacteristics = parentSignature.Defined.Characteristics // if we allow to specialize for certain set parameters, then these need to be resolved in parent let declLocation = { Offset = parentSignature.Position; Range = parentSignature.Range } @@ -1093,14 +1102,17 @@ module SymbolResolution = let errs = (relevantSpecs.[QsBody].Skip(1) |> Seq.map (positionedErr ErrorCode.RedefinitionOfBody)) - |> Seq.append - (relevantSpecs.[QsAdjoint].Skip(1) |> Seq.map (positionedErr ErrorCode.RedefinitionOfAdjoint)) - |> Seq.append - (relevantSpecs.[QsControlled].Skip(1) - |> Seq.map (positionedErr ErrorCode.RedefinitionOfControlled)) - |> Seq.append - (relevantSpecs.[QsControlledAdjoint].Skip(1) - |> Seq.map (positionedErr ErrorCode.RedefinitionOfControlledAdjoint)) + |> Seq.append ( + relevantSpecs.[QsAdjoint].Skip(1) |> Seq.map (positionedErr ErrorCode.RedefinitionOfAdjoint) + ) + |> Seq.append ( + relevantSpecs.[QsControlled].Skip(1) + |> Seq.map (positionedErr ErrorCode.RedefinitionOfControlled) + ) + |> Seq.append ( + relevantSpecs.[QsControlledAdjoint].Skip(1) + |> Seq.map (positionedErr ErrorCode.RedefinitionOfControlledAdjoint) + ) relevantSpecs.ToImmutableDictionary((fun g -> g.Key), (fun g -> (g.First() |> snd).Defined)), errs.ToArray() @@ -1134,10 +1146,11 @@ module SymbolResolution = /// /// No (partial) resolution is defined for the given specialization. /// The given specialization is not part of a specialization bundle in the given properties dictionary. - let internal ResolveGenerator (properties: ImmutableDictionary<_, _>) - (kind, spec: Resolution) - = - let bundle: SpecializationBundleProperties = properties.[SpecializationBundleProperties.BundleId spec] + let internal ResolveGenerator + (properties: ImmutableDictionary<_, _>) + (kind, spec: Resolution) + = + let bundle : SpecializationBundleProperties = properties.[SpecializationBundleProperties.BundleId spec] let impl, err = match kind with @@ -1164,7 +1177,7 @@ module SymbolResolution = let resolvedGen = spec.Resolved - |> QsNullable<_> - .Map(fun resolution -> { resolution with Information = bundle.BundleInfo; Directive = dir }) + |> QsNullable<_>.Map + (fun resolution -> { resolution with Information = bundle.BundleInfo; Directive = dir }) resolvedGen, err |> Array.map (fun msg -> spec.Position, msg) diff --git a/src/QsCompiler/Core/SymbolTable/Namespace.fs b/src/QsCompiler/Core/SymbolTable/Namespace.fs index e93893f271..2cc67710c7 100644 --- a/src/QsCompiler/Core/SymbolTable/Namespace.fs +++ b/src/QsCompiler/Core/SymbolTable/Namespace.fs @@ -23,11 +23,15 @@ open Microsoft.Quantum.QsCompiler.Utils /// /// Symbol accessibility is considered when resolving symbols. Some methods bypass this (e.g., when returning a list of /// all declarations). Individual methods will mention if they follow accessibility or not. -type Namespace private (name, - parts: IEnumerable>, - CallablesInReferences: ILookup, - SpecializationsInReferences: ILookup, - TypesInReferences: ILookup) = +type Namespace + private + ( + name, + parts: IEnumerable>, + CallablesInReferences: ILookup, + SpecializationsInReferences: ILookup, + TypesInReferences: ILookup + ) = /// dictionary containing a PartialNamespaces for each source file which implements a part of this namespace - /// the key is the source file where each part of the namespace is defined @@ -44,10 +48,13 @@ type Namespace private (name, isAvailableWith (fun name -> CallablesInReferences.[name]) (fun c -> c.Access) OtherAssembly && isAvailableWith (fun name -> TypesInReferences.[name]) (fun t -> t.Access) OtherAssembly - && Parts.Values.All(fun partial -> - isAvailableWith (partial.TryGetCallable >> tryOption >> Option.toList) (fun c -> (snd c).Access) - SameAssembly - && isAvailableWith (partial.TryGetType >> tryOption >> Option.toList) (fun t -> t.Access) SameAssembly) + && Parts.Values.All + (fun partial -> + isAvailableWith + (partial.TryGetCallable >> tryOption >> Option.toList) + (fun c -> (snd c).Access) + SameAssembly + && isAvailableWith (partial.TryGetType >> tryOption >> Option.toList) (fun t -> t.Access) SameAssembly) /// Returns whether a declaration is accessible from the calling location, given whether the calling location is in /// the same assembly as the declaration, and the declaration's access modifier. @@ -90,17 +97,18 @@ type Namespace private (name, callablesInRefs.Where(fun (header: CallableDeclarationHeader) -> header.QualifiedName.Namespace = name) let specializationsInRefs = - specializationsInRefs.Where(fun (header: SpecializationDeclarationHeader, _) -> - header.Parent.Namespace = name) + specializationsInRefs.Where + (fun (header: SpecializationDeclarationHeader, _) -> header.Parent.Namespace = name) let discardConflicts getAccess (_, nameGroup) = // Only one externally accessible declaration with the same name is allowed. let isAccessible header = getAccess header |> Access.isAccessibleFrom OtherAssembly - if nameGroup |> Seq.filter isAccessible |> Seq.length > 1 - then nameGroup |> Seq.filter (isAccessible >> not) - else nameGroup + if nameGroup |> Seq.filter isAccessible |> Seq.length > 1 then + nameGroup |> Seq.filter (isAccessible >> not) + else + nameGroup let createLookup getName getAccess headers = headers @@ -121,11 +129,12 @@ type Namespace private (name, /// returns true if the namespace currently contains no source files or referenced content member this.IsEmpty = - not - (this.Sources.Any() - || this.TypesInReferencedAssemblies.Any() - || this.CallablesInReferencedAssemblies.Any() - || this.SpecializationsInReferencedAssemblies.Any()) + not ( + this.Sources.Any() + || this.TypesInReferencedAssemblies.Any() + || this.CallablesInReferencedAssemblies.Any() + || this.SpecializationsInReferencedAssemblies.Any() + ) /// returns a new Namespace that is an exact (deep) copy of this one /// -> any modification of the returned Namespace is not reflected in this one @@ -200,10 +209,7 @@ type Namespace private (name, |> Seq.tryExactlyOne match referenceType with - | Some qsType -> - if Seq.exists marksAttribute qsType.Attributes - then Some qsType.Type - else None + | Some qsType -> if Seq.exists marksAttribute qsType.Attributes then Some qsType.Type else None | None -> SymbolNotFoundException "The source file does not contain this namespace." |> raise /// @@ -218,8 +224,9 @@ type Namespace private (name, | true, partial -> partial.TryGetType tName |> tryOption - |> Option.defaultWith (fun () -> - SymbolNotFoundException "A type with the given name was not found in the source file." |> raise) + |> Option.defaultWith + (fun () -> + SymbolNotFoundException "A type with the given name was not found in the source file." |> raise) | false, _ -> SymbolNotFoundException "The source file does not contain this namespace." |> raise /// @@ -256,8 +263,9 @@ type Namespace private (name, | true, partial -> partial.TryGetCallable cName |> tryOption - |> Option.defaultWith (fun () -> - SymbolNotFoundException "A callable with the given name was not found in the source file." |> raise) + |> Option.defaultWith + (fun () -> + SymbolNotFoundException "A callable with the given name was not found in the source file." |> raise) | false, _ -> SymbolNotFoundException "The source file does not contain this namespace." |> raise /// @@ -294,9 +302,10 @@ type Namespace private (name, let getSpecializationInPartial (partial: PartialNamespace) = partial.GetSpecializations cName |> Seq.map (fun (kind, decl) -> kind, (partial.Source, decl)) - if this.TryFindCallable cName |> ResolutionResult.Exists - then (Parts.Values.SelectMany getSpecializationInPartial).ToImmutableArray() - else SymbolNotFoundException "A callable with the given name was not found in a source file." |> raise + if this.TryFindCallable cName |> ResolutionResult.Exists then + (Parts.Values.SelectMany getSpecializationInPartial).ToImmutableArray() + else + SymbolNotFoundException "A callable with the given name was not found in a source file." |> raise /// Returns a resolution result for the type with the given name containing the name of the source file or /// referenced assembly in which it is declared, a string indicating the redirection if it has been deprecated, and @@ -309,22 +318,25 @@ type Namespace private (name, /// source file. member this.TryFindType(tName, ?checkDeprecation: (string -> bool)) = let checkDeprecation = - defaultArg checkDeprecation (fun qual -> - String.IsNullOrWhiteSpace qual || qual = BuiltIn.Deprecated.FullName.Namespace) + defaultArg + checkDeprecation + (fun qual -> String.IsNullOrWhiteSpace qual || qual = BuiltIn.Deprecated.FullName.Namespace) let resolveReferenceType (typeHeader: TypeDeclarationHeader) = - if typeHeader.Access |> Access.isAccessibleFrom OtherAssembly - then Found(typeHeader.Source, SymbolResolution.TryFindRedirect typeHeader.Attributes, typeHeader.Access) - else Inaccessible + if typeHeader.Access |> Access.isAccessibleFrom OtherAssembly then + Found(typeHeader.Source, SymbolResolution.TryFindRedirect typeHeader.Attributes, typeHeader.Access) + else + Inaccessible let findInPartial (partial: PartialNamespace) = match partial.TryGetType tName with | true, qsType -> if qsType.Access |> Access.isAccessibleFrom SameAssembly then - Found - ({ CodeFile = partial.Source; AssemblyFile = Null }, - SymbolResolution.TryFindRedirectInUnresolved checkDeprecation qsType.DefinedAttributes, - qsType.Access) + Found( + { CodeFile = partial.Source; AssemblyFile = Null }, + SymbolResolution.TryFindRedirectInUnresolved checkDeprecation qsType.DefinedAttributes, + qsType.Access + ) else Inaccessible | false, _ -> NotFound @@ -349,21 +361,24 @@ type Namespace private (name, /// and source file. member this.TryFindCallable(cName, ?checkDeprecation: (string -> bool)) = let checkDeprecation = - defaultArg checkDeprecation (fun qual -> - String.IsNullOrWhiteSpace qual || qual = BuiltIn.Deprecated.FullName.Namespace) + defaultArg + checkDeprecation + (fun qual -> String.IsNullOrWhiteSpace qual || qual = BuiltIn.Deprecated.FullName.Namespace) let resolveReferenceCallable (callable: CallableDeclarationHeader) = - if callable.Access |> Access.isAccessibleFrom OtherAssembly - then Found(callable.Source, SymbolResolution.TryFindRedirect callable.Attributes) - else Inaccessible + if callable.Access |> Access.isAccessibleFrom OtherAssembly then + Found(callable.Source, SymbolResolution.TryFindRedirect callable.Attributes) + else + Inaccessible let findInPartial (partial: PartialNamespace) = match partial.TryGetCallable cName with | true, (_, callable) -> if callable.Access |> Access.isAccessibleFrom SameAssembly then - Found - ({ CodeFile = partial.Source; AssemblyFile = Null }, - SymbolResolution.TryFindRedirectInUnresolved checkDeprecation callable.DefinedAttributes) + Found( + { CodeFile = partial.Source; AssemblyFile = Null }, + SymbolResolution.TryFindRedirectInUnresolved checkDeprecation callable.DefinedAttributes + ) else Inaccessible | false, _ -> NotFound @@ -500,8 +515,10 @@ type Namespace private (name, /// If a type or callable with that name already exists, returns an array of suitable diagnostics. /// /// The source file does not contain this namespace. - member this.TryAddType (source, location) ((tName, tRange), typeTuple, attributes, access, documentation) - : QsCompilerDiagnostic [] = + member this.TryAddType + (source, location) + ((tName, tRange), typeTuple, attributes, access, documentation) + : QsCompilerDiagnostic [] = match Parts.TryGetValue source with | true, partial when isNameAvailable tName -> TypesDefinedInAllSourcesCache <- null @@ -529,9 +546,10 @@ type Namespace private (name, /// If a callable with that name already exists, returns an array of suitable diagnostics. /// /// The source file does not contain this namespace. - member this.TryAddCallableDeclaration (source, location) - ((cName, cRange), (kind, signature), attributes, access, documentation) - = + member this.TryAddCallableDeclaration + (source, location) + ((cName, cRange), (kind, signature), attributes, access, documentation) + = match Parts.TryGetValue source with | true, partial when isNameAvailable cName -> CallablesDefinedInAllSourcesCache <- null @@ -564,13 +582,11 @@ type Namespace private (name, /// IMPORTANT: The verification of whether the given specialization kind (body, adjoint, controlled, or controlled adjoint) may exist /// for the given callable is up to the calling routine. /// - member this.TryAddCallableSpecialization kind - (source, location: QsLocation) - ((cName, cRange), - generator: QsSpecializationGenerator, - attributes, - documentation) - = + member this.TryAddCallableSpecialization + kind + (source, location: QsLocation) + ((cName, cRange), generator: QsSpecializationGenerator, attributes, documentation) + = let getRelevantDeclInfo declSource = let unitOrInvalid fct = function @@ -653,10 +669,11 @@ type Namespace private (name, /// Return the diagnostics generated upon adding the specialization. /// /// The source file does not contain this namespace. - member internal this.InsertSpecialization (kind, typeArgs) - (parentName, source) - (declLocation: QsLocation, msgRange: QsNullable) - = + member internal this.InsertSpecialization + (kind, typeArgs) + (parentName, source) + (declLocation: QsLocation, msgRange: QsNullable) + = let location = { Offset = declLocation.Offset; Range = msgRange.ValueOr declLocation.Range } let generator = @@ -667,8 +684,9 @@ type Namespace private (name, } let doc = - ImmutableArray.Create - (sprintf "automatically generated %A specialization for %s.%s" kind this.Name parentName) + ImmutableArray.Create( + sprintf "automatically generated %A specialization for %s.%s" kind this.Name parentName + ) this.TryAddCallableSpecialization kind diff --git a/src/QsCompiler/Core/SymbolTable/NamespaceManager.fs b/src/QsCompiler/Core/SymbolTable/NamespaceManager.fs index 4871663465..2df8093522 100644 --- a/src/QsCompiler/Core/SymbolTable/NamespaceManager.fs +++ b/src/QsCompiler/Core/SymbolTable/NamespaceManager.fs @@ -28,12 +28,15 @@ open Newtonsoft.Json /// The namespace manager takes access modifiers into consideration when resolving symbols. Some methods bypass this /// (e.g., when returning a list of all declarations). Individual methods document whether they follow or ignore access /// modifiers. -type NamespaceManager(syncRoot: IReaderWriterLock, - callablesInRefs: IEnumerable, - specializationsInRefs: IEnumerable, - typesInRefs: IEnumerable, - runtimeCapability, - isExecutable) = +type NamespaceManager + ( + syncRoot: IReaderWriterLock, + callablesInRefs: IEnumerable, + specializationsInRefs: IEnumerable, + typesInRefs: IEnumerable, + runtimeCapability, + isExecutable + ) = // This class itself does not use any concurrency, // so anything that is accessible within the class only does not apply any locks. // IMPORTANT: the syncRoot is intentionally not exposed externally, since with this class supporting mutation @@ -58,8 +61,10 @@ type NamespaceManager(syncRoot: IReaderWriterLock, let namespacesInRefs = (getKeys callables).Concat(getKeys specializations).Concat(getKeys types) |> Seq.distinct for nsName in namespacesInRefs do - namespaces.Add - (nsName, new Namespace(nsName, [], callables.[nsName], specializations.[nsName], types.[nsName])) + namespaces.Add( + nsName, + new Namespace(nsName, [], callables.[nsName], specializations.[nsName], types.[nsName]) + ) namespaces @@ -67,14 +72,17 @@ type NamespaceManager(syncRoot: IReaderWriterLock, let GetEntryPoints () = let entryPoints = Namespaces.Values - |> Seq.collect (fun ns -> - ns.CallablesDefinedInAllSources() - |> Seq.choose (fun kvPair -> - let cName, (source, (_, decl)) = kvPair.Key, kvPair.Value + |> Seq.collect + (fun ns -> + ns.CallablesDefinedInAllSources() + |> Seq.choose + (fun kvPair -> + let cName, (source, (_, decl)) = kvPair.Key, kvPair.Value - if decl.ResolvedAttributes |> Seq.exists BuiltIn.MarksEntryPoint - then Some({ Namespace = ns.Name; Name = cName }, source) - else None)) + if decl.ResolvedAttributes |> Seq.exists BuiltIn.MarksEntryPoint then + Some({ Namespace = ns.Name; Name = cName }, source) + else + None)) entryPoints.ToImmutableArray() @@ -125,20 +133,22 @@ type NamespaceManager(syncRoot: IReaderWriterLock, let parentNs () = Namespaces.TryGetValue nsName |> tryOption - |> Option.defaultWith (fun () -> - SymbolNotFoundException "The namespace with the given name was not found." |> raise) + |> Option.defaultWith + (fun () -> SymbolNotFoundException "The namespace with the given name was not found." |> raise) let nsAlias = Namespaces.TryGetValue >> tryOption - >> Option.orElseWith (fun () -> - QsCompilerError.Raise "The corresponding namespace for a namespace short name could not be found." - None) + >> Option.orElseWith + (fun () -> + QsCompilerError.Raise "The corresponding namespace for a namespace short name could not be found." + None) Namespaces.TryGetValue qualifier |> tryOption - |> Option.orElseWith (fun () -> - (parentNs().NamespaceShortNames source).TryGetValue qualifier |> tryOption |> Option.bind nsAlias) + |> Option.orElseWith + (fun () -> + (parentNs().NamespaceShortNames source).TryGetValue qualifier |> tryOption |> Option.bind nsAlias) /// /// Returns the possible qualifications for the built-in type or callable used in the given namespace and source. @@ -151,8 +161,9 @@ type NamespaceManager(syncRoot: IReaderWriterLock, match Namespaces.TryGetValue nsName with | true, ns when ns.Sources.Contains source -> match (ns.ImportedNamespaces source).TryGetValue builtIn.FullName.Namespace with - | true, null when not (ns.TryFindType builtIn.FullName.Name |> ResolutionResult.IsAccessible) - || nsName = builtIn.FullName.Namespace -> [ ""; builtIn.FullName.Namespace ] + | true, null when + not (ns.TryFindType builtIn.FullName.Name |> ResolutionResult.IsAccessible) + || nsName = builtIn.FullName.Namespace -> [ ""; builtIn.FullName.Namespace ] | true, null -> [ builtIn.FullName.Namespace ] // the built-in type or callable is shadowed | true, alias -> [ alias; builtIn.FullName.Namespace ] | false, _ -> [ builtIn.FullName.Namespace ] @@ -181,21 +192,23 @@ type NamespaceManager(syncRoot: IReaderWriterLock, ({ Namespace = ns; Name = symName }, symRange.ValueOr Range.Zero) deprecation - Some - ({ - Namespace = ns - Name = symName - Range = symRange - }, - declSource, - access), + Some( + { + Namespace = ns + Name = symName + Range = symRange + }, + declSource, + access + ), Array.append errs warnings let error code args = - None, [| QsCompilerDiagnostic.Error (code, args) (symRange.ValueOr Range.Zero) |] + None, [| QsCompilerDiagnostic.Error(code, args) (symRange.ValueOr Range.Zero) |] let findUnqualified () = - match resolveInOpenNamespaces (fun ns -> ns.TryFindType(symName, checkQualificationForDeprecation)) + match resolveInOpenNamespaces + (fun ns -> ns.TryFindType(symName, checkQualificationForDeprecation)) (parentNS, source) with | Found (nsName, (declSource, deprecation, access)) -> success nsName declSource deprecation access [||] | Ambiguous namespaces -> @@ -266,7 +279,7 @@ type NamespaceManager(syncRoot: IReaderWriterLock, syncRoot.EnterReadLock() try - SymbolResolution.ResolveType (processUDT, processTP) qsType + SymbolResolution.ResolveType(processUDT, processTP) qsType finally syncRoot.ExitReadLock() @@ -277,8 +290,8 @@ type NamespaceManager(syncRoot: IReaderWriterLock, let udtRange = udtRange |> QsNullable.defaultValue Range.Zero [| - if udtAccess < parentAccess - then yield QsCompilerDiagnostic.Error (code, [ udt.Name; parent ]) udtRange + if udtAccess < parentAccess then + yield QsCompilerDiagnostic.Error(code, [ udt.Name; parent ]) udtRange |] /// @@ -310,10 +323,11 @@ type NamespaceManager(syncRoot: IReaderWriterLock, let specializations = ns.SpecializationsDefinedInAllSources parent.Name if hasCharacteristics || specializations.Any(fst >> (<>) QsBody) then - errs.Add - (decl.Position, - signature.Characteristics.Range.ValueOr decl.Range - |> QsCompilerDiagnostic.Error(ErrorCode.InvalidEntryPointSpecialization, [])) + errs.Add( + decl.Position, + signature.Characteristics.Range.ValueOr decl.Range + |> QsCompilerDiagnostic.Error(ErrorCode.InvalidEntryPointSpecialization, []) + ) // validate entry point argument and return type let rec validateArgAndReturnTypes (isArg, inArray) (t: QsType) = @@ -348,7 +362,9 @@ type NamespaceManager(syncRoot: IReaderWriterLock, | ArrayType bt -> validateArgAndReturnTypes (isArg, true) bt | _ -> Seq.empty - let validateArgAndReturnTypes isArg = validateArgAndReturnTypes (isArg, false) + let validateArgAndReturnTypes isArg = + validateArgAndReturnTypes (isArg, false) + let inErrs = signature.Argument.Items.Select snd |> Seq.collect (validateArgAndReturnTypes true) let outErrs = signature.ReturnType |> validateArgAndReturnTypes false let signatureErrs = inErrs.Concat outErrs @@ -357,20 +373,22 @@ type NamespaceManager(syncRoot: IReaderWriterLock, // currently, only return values of type Result, Result[], and tuples thereof are supported on quantum processors if runtimeCapability <> FullComputation then let invalid = - signature.ReturnType.ExtractAll(fun t -> - match t.Type with - | Result - | ArrayType _ - | TupleType _ - | InvalidType -> Seq.empty - | _ -> Seq.singleton t) + signature.ReturnType.ExtractAll + (fun t -> + match t.Type with + | Result + | ArrayType _ + | TupleType _ + | InvalidType -> Seq.empty + | _ -> Seq.singleton t) if invalid.Any() then - errs.Add - (decl.Position, - signature.ReturnType.Range - |> orDefault - |> QsCompilerDiagnostic.Warning(WarningCode.NonResultTypeReturnedInEntryPoint, [])) + errs.Add( + decl.Position, + signature.ReturnType.Range + |> orDefault + |> QsCompilerDiagnostic.Warning(WarningCode.NonResultTypeReturnedInEntryPoint, []) + ) // validate entry point argument names let asCommandLineArg (str: string) = @@ -390,15 +408,17 @@ type NamespaceManager(syncRoot: IReaderWriterLock, let verifyArgument i (arg, range: QsNullable<_>) = if i > 0 && simplifiedArgNames.[..i - 1] |> Seq.map fst |> Seq.contains arg then - errs.Add - (decl.Position, - range.ValueOr decl.Range - |> QsCompilerDiagnostic.Error(ErrorCode.DuplicateEntryPointArgumentName, [])) + errs.Add( + decl.Position, + range.ValueOr decl.Range + |> QsCompilerDiagnostic.Error(ErrorCode.DuplicateEntryPointArgumentName, []) + ) elif reservedCommandLineArgs.Contains arg then - errs.Add - (decl.Position, - range.ValueOr decl.Range - |> QsCompilerDiagnostic.Warning(WarningCode.ReservedEntryPointArgumentName, [])) + errs.Add( + decl.Position, + range.ValueOr decl.Range + |> QsCompilerDiagnostic.Warning(WarningCode.ReservedEntryPointArgumentName, []) + ) simplifiedArgNames |> List.iteri verifyArgument @@ -406,8 +426,10 @@ type NamespaceManager(syncRoot: IReaderWriterLock, if signatureErrs.Any() then false, errs elif not isExecutable then - errs.Add - (offset, range |> orDefault |> QsCompilerDiagnostic.Warning(WarningCode.EntryPointInLibrary, [])) + errs.Add( + offset, + range |> orDefault |> QsCompilerDiagnostic.Warning(WarningCode.EntryPointInLibrary, []) + ) false, errs else @@ -490,10 +512,8 @@ type NamespaceManager(syncRoot: IReaderWriterLock, // known attribute | Value tId -> let attributeHash = - if tId |> isBuiltIn BuiltIn.Deprecated - then hash (tId.Namespace, tId.Name) - elif tId |> isBuiltIn BuiltIn.EnableTestingViaName - then hash (tId.Namespace, tId.Name) + if tId |> isBuiltIn BuiltIn.Deprecated then hash (tId.Namespace, tId.Name) + elif tId |> isBuiltIn BuiltIn.EnableTestingViaName then hash (tId.Namespace, tId.Name) else hash (tId.Namespace, tId.Name, NamespaceManager.ExpressionHash att.Argument) // the attribute is a duplication of another attribute on this declaration @@ -510,9 +530,10 @@ type NamespaceManager(syncRoot: IReaderWriterLock, let register, msgs = validateEntryPoint parent (att.Offset, att.TypeIdRange) decl errs.AddRange msgs - if register - then attributeHash :: alreadyDefined, att :: resAttr - else alreadyDefined, { att with TypeId = Null } :: resAttr + if register then + attributeHash :: alreadyDefined, att :: resAttr + else + alreadyDefined, { att with TypeId = Null } :: resAttr // the attribute marks a unit test elif tId |> isBuiltIn BuiltIn.Test then @@ -530,8 +551,8 @@ type NamespaceManager(syncRoot: IReaderWriterLock, | _ -> false match box decl.Defined with - | :? CallableSignature as signature when signature |> isUnitToUnit - && not (signature.TypeParameters.Any()) -> + | :? CallableSignature as signature when + signature |> isUnitToUnit && not (signature.TypeParameters.Any()) -> let arg = att.Argument |> AttributeAnnotation.NonInterpolatedStringArgument(fun ex -> ex.Expression) @@ -682,34 +703,38 @@ type NamespaceManager(syncRoot: IReaderWriterLock, /// May throw an exception if the given parent and/or source file is inconsistent with the defined callables. /// /// is empty. - member private this.ResolveCallableSignature (parentKind, parentName: QsQualifiedName, source, access) - (signature, specBundleCharacteristics) - = + member private this.ResolveCallableSignature + (parentKind, parentName: QsQualifiedName, source, access) + (signature, specBundleCharacteristics) + = let checkAccess = checkUdtAccess ErrorCode.TypeLessAccessibleThanParentCallable (parentName.Name, access) let resolveType tpNames qsType = let res, errs = resolveType (parentName, tpNames, source) qsType checkAccess if parentKind <> TypeConstructor then res, errs else res.WithoutRangeInfo, errs // strip positional info for auto-generated type constructors - SymbolResolution.ResolveCallableSignature (resolveType, specBundleCharacteristics) signature + SymbolResolution.ResolveCallableSignature(resolveType, specBundleCharacteristics) signature /// Sets the Resolved property for all type and callable declarations to Null, and the ResolvedAttributes to an empty array. /// Unless the clearing is forced, does nothing if the symbols are not currently resolved. - member private this.ClearResolutions ?force = + member private this.ClearResolutions?force = let force = defaultArg force false if this.ContainsResolutions || force then for ns in Namespaces.Values do for kvPair in ns.TypesDefinedInAllSources() do - ns.SetTypeResolution (fst kvPair.Value) (kvPair.Key, Null, ImmutableArray.Empty) + ns.SetTypeResolution(fst kvPair.Value) (kvPair.Key, Null, ImmutableArray.Empty) for kvPair in ns.CallablesDefinedInAllSources() do - ns.SetSpecializationResolutions - (kvPair.Key, (fun _ _ -> Null, [||]), (fun _ _ -> ImmutableArray.Empty, [||])) + ns.SetSpecializationResolutions( + kvPair.Key, + (fun _ _ -> Null, [||]), + (fun _ _ -> ImmutableArray.Empty, [||]) + ) |> ignore - ns.SetCallableResolution (fst kvPair.Value) (kvPair.Key, Null, ImmutableArray.Empty) + ns.SetCallableResolution(fst kvPair.Value) (kvPair.Key, Null, ImmutableArray.Empty) this.ContainsResolutions <- false @@ -720,38 +745,44 @@ type NamespaceManager(syncRoot: IReaderWriterLock, // Since attributes are declared as types, we first need to resolve all types ... let resolutionDiagnostics = sortedNamespaces - |> Seq.collect (fun ns -> - ns.TypesDefinedInAllSources() - |> Seq.collect (fun kvPair -> - let tName, (source, qsType) = kvPair.Key, kvPair.Value - let fullName = { Namespace = ns.Name; Name = tName } - - let resolved, resErrs = - qsType.Defined |> this.ResolveTypeDeclaration(fullName, source, qsType.Access) - - ns.SetTypeResolution source (tName, resolved |> Value, ImmutableArray.Empty) - - if fullName.ToString() |> (not << nsNames.Contains) then - resErrs - else - [| - qsType.Range - |> QsCompilerDiagnostic.New - (Error ErrorCode.FullNameConflictsWithNamespace, [ fullName.ToString() ]) - |] - |> Array.append resErrs - |> Array.map (fun msg -> source, (qsType.Position, msg)))) + |> Seq.collect + (fun ns -> + ns.TypesDefinedInAllSources() + |> Seq.collect + (fun kvPair -> + let tName, (source, qsType) = kvPair.Key, kvPair.Value + let fullName = { Namespace = ns.Name; Name = tName } + + let resolved, resErrs = + qsType.Defined |> this.ResolveTypeDeclaration(fullName, source, qsType.Access) + + ns.SetTypeResolution source (tName, resolved |> Value, ImmutableArray.Empty) + + (if fullName.ToString() |> (not << nsNames.Contains) then + resErrs + else + [| + qsType.Range + |> QsCompilerDiagnostic.New( + Error ErrorCode.FullNameConflictsWithNamespace, + [ fullName.ToString() ] + ) + |] + |> Array.append resErrs) + |> Array.map (fun msg -> source, (qsType.Position, msg)))) // ... before we can resolve the corresponding attributes. let attributeDiagnostics = sortedNamespaces - |> Seq.collect (fun ns -> - ns.TypesDefinedInAllSources() - |> Seq.collect (fun kvPair -> - let tName, (source, qsType) = kvPair.Key, kvPair.Value - let parentName = { Namespace = ns.Name; Name = tName } - let resolvedAttributes, msgs = this.ResolveAttributes (parentName, source) qsType - ns.SetTypeResolution source (tName, qsType.Resolved, resolvedAttributes) - msgs |> Array.map (fun msg -> source, msg))) + |> Seq.collect + (fun ns -> + ns.TypesDefinedInAllSources() + |> Seq.collect + (fun kvPair -> + let tName, (source, qsType) = kvPair.Key, kvPair.Value + let parentName = { Namespace = ns.Name; Name = tName } + let resolvedAttributes, msgs = this.ResolveAttributes(parentName, source) qsType + ns.SetTypeResolution source (tName, qsType.Resolved, resolvedAttributes) + msgs |> Array.map (fun msg -> source, msg))) resolutionDiagnostics.Concat(attributeDiagnostics).ToArray() @@ -768,89 +799,109 @@ type NamespaceManager(syncRoot: IReaderWriterLock, let diagnostics = Namespaces.Values |> Seq.sortBy (fun ns -> ns.Name) - |> Seq.collect (fun ns -> - ns.CallablesDefinedInAllSources() - |> Seq.sortBy (fun kv -> kv.Key) - |> Seq.collect (fun kvPair -> - let source, (kind, signature) = kvPair.Value - let parent = { Namespace = ns.Name; Name = kvPair.Key } - - // we first need to resolve the type arguments to determine the right sets of specializations to consider - let typeArgsResolution specSource = - let typeResolution = this.ResolveType(parent, ImmutableArray.Empty, specSource) // do not allow using type parameters within type specializations! - SymbolResolution.ResolveTypeArgument typeResolution - - let mutable errs = - ns.SetSpecializationResolutions - (parent.Name, typeArgsResolution, (fun _ _ -> ImmutableArray.Empty, [||])) - - // we then build the specialization bundles (one for each set of type and set arguments) and insert missing specializations - let definedSpecs = ns.SpecializationsDefinedInAllSources parent.Name - - let insertSpecialization typeArgs kind = - ns.InsertSpecialization (kind, typeArgs) (parent.Name, source) - - let props, bundleErrs = - SymbolResolution.GetBundleProperties insertSpecialization (signature, source) definedSpecs - - let bundleErrs = bundleErrs |> Array.concat - errs <- bundleErrs :: errs - - // we remove the specializations which could not be bundled and resolve the newly inserted ones - for (specSource, (errPos, d)) in bundleErrs do - match d.Diagnostic with - | Information _ - | Warning _ -> () - | Error errCode -> - let removed = - ns.RemoveSpecialization (specSource, { Offset = errPos; Range = d.Range }) parent.Name - - QsCompilerError.Verify - ((removed <= 1), - sprintf - "removed %i specializations based on error code %s" - removed - (errCode.ToString())) - - let autoResErrs = - ns.SetSpecializationResolutions - (parent.Name, typeArgsResolution, (fun _ _ -> ImmutableArray.Empty, [||])) - - // only then can we resolve the generators themselves, as well as the callable and specialization attributes - let callableAttributes, attrErrs = this.ResolveAttributes (parent, source) signature - let resolution _ = SymbolResolution.ResolveGenerator props - - let specErrs = - ns.SetSpecializationResolutions - (parent.Name, resolution, (fun attSource -> this.ResolveAttributes(parent, attSource))) - - // and finally we resolve the overall signature (whose characteristics are the intersection of the one of all bundles) - let characteristics = props.Values |> Seq.map (fun bundle -> bundle.BundleInfo) |> Seq.toList - - let resolved, msgs = - (signature.Defined, characteristics) - |> this.ResolveCallableSignature(kind, parent, source, signature.Access) // no positional info for type constructors - - ns.SetCallableResolution source (parent.Name, resolved |> Value, callableAttributes) - - errs <- - (attrErrs |> Array.map (fun m -> source, m)) - :: (msgs |> Array.map (fun m -> source, (signature.Position, m))) :: errs - - let errs = specErrs.Concat autoResErrs |> errs.Concat |> Array.concat - - if kind = QsCallableKind.TypeConstructor then - // don't return diagnostics for type constructors - everything will be captured upon type resolution - Array.empty - elif parent.ToString() |> (not << nsNames.Contains) then - errs - else - signature.Range - |> QsCompilerDiagnostic.New - (Error ErrorCode.FullNameConflictsWithNamespace, [ parent.ToString() ]) - |> (fun msg -> source, (signature.Position, msg)) - |> Array.singleton - |> Array.append errs)) + |> Seq.collect + (fun ns -> + ns.CallablesDefinedInAllSources() + |> Seq.sortBy (fun kv -> kv.Key) + |> Seq.collect + (fun kvPair -> + let source, (kind, signature) = kvPair.Value + let parent = { Namespace = ns.Name; Name = kvPair.Key } + + // we first need to resolve the type arguments to determine the right sets of specializations to consider + let typeArgsResolution specSource = + let typeResolution = this.ResolveType(parent, ImmutableArray.Empty, specSource) // do not allow using type parameters within type specializations! + SymbolResolution.ResolveTypeArgument typeResolution + + let mutable errs = + ns.SetSpecializationResolutions( + parent.Name, + typeArgsResolution, + (fun _ _ -> ImmutableArray.Empty, [||]) + ) + + // we then build the specialization bundles (one for each set of type and set arguments) and insert missing specializations + let definedSpecs = ns.SpecializationsDefinedInAllSources parent.Name + + let insertSpecialization typeArgs kind = + ns.InsertSpecialization(kind, typeArgs) (parent.Name, source) + + let props, bundleErrs = + SymbolResolution.GetBundleProperties + insertSpecialization + (signature, source) + definedSpecs + + let bundleErrs = bundleErrs |> Array.concat + errs <- bundleErrs :: errs + + // we remove the specializations which could not be bundled and resolve the newly inserted ones + for (specSource, (errPos, d)) in bundleErrs do + match d.Diagnostic with + | Information _ + | Warning _ -> () + | Error errCode -> + let removed = + ns.RemoveSpecialization + (specSource, { Offset = errPos; Range = d.Range }) + parent.Name + + QsCompilerError.Verify( + (removed <= 1), + sprintf + "removed %i specializations based on error code %s" + removed + (errCode.ToString()) + ) + + let autoResErrs = + ns.SetSpecializationResolutions( + parent.Name, + typeArgsResolution, + (fun _ _ -> ImmutableArray.Empty, [||]) + ) + + // only then can we resolve the generators themselves, as well as the callable and specialization attributes + let callableAttributes, attrErrs = this.ResolveAttributes(parent, source) signature + let resolution _ = SymbolResolution.ResolveGenerator props + + let specErrs = + ns.SetSpecializationResolutions( + parent.Name, + resolution, + (fun attSource -> this.ResolveAttributes(parent, attSource)) + ) + + // and finally we resolve the overall signature (whose characteristics are the intersection of the one of all bundles) + let characteristics = + props.Values |> Seq.map (fun bundle -> bundle.BundleInfo) |> Seq.toList + + let resolved, msgs = + (signature.Defined, characteristics) + |> this.ResolveCallableSignature(kind, parent, source, signature.Access) // no positional info for type constructors + + ns.SetCallableResolution source (parent.Name, resolved |> Value, callableAttributes) + + errs <- + (attrErrs |> Array.map (fun m -> source, m)) + :: (msgs |> Array.map (fun m -> source, (signature.Position, m))) :: errs + + let errs = specErrs.Concat autoResErrs |> errs.Concat |> Array.concat + + if kind = QsCallableKind.TypeConstructor then + // don't return diagnostics for type constructors - everything will be captured upon type resolution + Array.empty + elif parent.ToString() |> (not << nsNames.Contains) then + errs + else + signature.Range + |> QsCompilerDiagnostic.New( + Error ErrorCode.FullNameConflictsWithNamespace, + [ parent.ToString() ] + ) + |> (fun msg -> source, (signature.Position, msg)) + |> Array.singleton + |> Array.append errs)) diagnostics.ToArray() @@ -883,7 +934,7 @@ type NamespaceManager(syncRoot: IReaderWriterLock, for opened in nsToAutoOpen do for ns in Namespaces.Values do for source in ns.Sources do - this.AddOpenDirective (opened, Range.Zero) (null, Value Range.Zero) (ns.Name, source) |> ignore + this.AddOpenDirective(opened, Range.Zero) (null, Value Range.Zero) (ns.Name, source) |> ignore // We need to resolve types before we resolve callables, // since the attribute resolution for callables relies on the corresponding types having been resolved. let typeDiagnostics = this.CacheTypeResolution nsNames @@ -892,9 +943,11 @@ type NamespaceManager(syncRoot: IReaderWriterLock, callableDiagnostics .Concat(typeDiagnostics) - .ToLookup(fst, - (fun (_, (position, diagnostic)) -> - { diagnostic with QsCompilerDiagnostic.Range = position + diagnostic.Range })) + .ToLookup( + fst, + (fun (_, (position, diagnostic)) -> + { diagnostic with QsCompilerDiagnostic.Range = position + diagnostic.Range }) + ) finally syncRoot.ExitWriteLock() @@ -921,12 +974,15 @@ type NamespaceManager(syncRoot: IReaderWriterLock, | true, ns -> let imported = ns.Sources - |> Seq.collect (fun source -> - ns.ImportedNamespaces source - |> Seq.choose (fun imported -> - if imported.Key <> ns.Name - then Some(source, new ValueTuple<_, _>(imported.Key, imported.Value)) - else None)) + |> Seq.collect + (fun source -> + ns.ImportedNamespaces source + |> Seq.choose + (fun imported -> + if imported.Key <> ns.Name then + Some(source, new ValueTuple<_, _>(imported.Key, imported.Value)) + else + None)) imported.ToLookup(fst, snd) | false, _ -> SymbolNotFoundException "The namespace with the given name was not found." |> raise @@ -968,25 +1024,27 @@ type NamespaceManager(syncRoot: IReaderWriterLock, | false, _ -> SymbolNotFoundException "The namespace with the given name was not found." |> raise | true, ns -> ns.SpecializationsDefinedInAllSources parent.Name - |> Seq.choose (fun (kind, (source, resolution)) -> - match resolution.Resolved with - | Null -> - QsCompilerError.Raise "everything should be resolved but isn't" - None - | Value gen -> - Some - (gen.Directive, - { - Kind = kind - TypeArguments = gen.TypeArguments - Information = gen.Information - Parent = parent - Attributes = resolution.ResolvedAttributes - Source = { CodeFile = source; AssemblyFile = Null } - Position = DeclarationHeader.Offset.Defined resolution.Position - HeaderRange = DeclarationHeader.Range.Defined resolution.Range - Documentation = resolution.Documentation - })) + |> Seq.choose + (fun (kind, (source, resolution)) -> + match resolution.Resolved with + | Null -> + QsCompilerError.Raise "everything should be resolved but isn't" + None + | Value gen -> + Some( + gen.Directive, + { + Kind = kind + TypeArguments = gen.TypeArguments + Information = gen.Information + Parent = parent + Attributes = resolution.ResolvedAttributes + Source = { CodeFile = source; AssemblyFile = Null } + Position = DeclarationHeader.Offset.Defined resolution.Position + HeaderRange = DeclarationHeader.Range.Defined resolution.Range + Documentation = resolution.Documentation + } + )) defined.ToImmutableArray() finally @@ -1018,29 +1076,31 @@ type NamespaceManager(syncRoot: IReaderWriterLock, let defined = Namespaces.Values - |> Seq.collect (fun ns -> - ns.CallablesDefinedInAllSources() - |> Seq.choose (fun kvPair -> - let cName, (source, (kind, declaration)) = kvPair.Key, kvPair.Value - - match declaration.Resolved with - | Null -> - QsCompilerError.Raise "everything should be resolved but isn't" - None - | Value (signature, argTuple) -> - Some - { - Kind = kind - QualifiedName = { Namespace = ns.Name; Name = cName } - Attributes = declaration.ResolvedAttributes - Access = declaration.Access - Source = { CodeFile = source; AssemblyFile = Null } - Position = DeclarationHeader.Offset.Defined declaration.Position - SymbolRange = DeclarationHeader.Range.Defined declaration.Range - Signature = signature - ArgumentTuple = argTuple - Documentation = declaration.Documentation - })) + |> Seq.collect + (fun ns -> + ns.CallablesDefinedInAllSources() + |> Seq.choose + (fun kvPair -> + let cName, (source, (kind, declaration)) = kvPair.Key, kvPair.Value + + match declaration.Resolved with + | Null -> + QsCompilerError.Raise "everything should be resolved but isn't" + None + | Value (signature, argTuple) -> + Some + { + Kind = kind + QualifiedName = { Namespace = ns.Name; Name = cName } + Attributes = declaration.ResolvedAttributes + Access = declaration.Access + Source = { CodeFile = source; AssemblyFile = Null } + Position = DeclarationHeader.Offset.Defined declaration.Position + SymbolRange = DeclarationHeader.Range.Defined declaration.Range + Signature = signature + ArgumentTuple = argTuple + Documentation = declaration.Documentation + })) defined.ToImmutableArray() finally @@ -1083,28 +1143,30 @@ type NamespaceManager(syncRoot: IReaderWriterLock, let defined = Namespaces.Values - |> Seq.collect (fun ns -> - ns.TypesDefinedInAllSources() - |> Seq.choose (fun kvPair -> - let tName, (source, qsType) = kvPair.Key, kvPair.Value - - match qsType.Resolved with - | Null -> - QsCompilerError.Raise "everything should be resolved but isn't" - None - | Value (underlyingType, items) -> - Some - { - QualifiedName = { Namespace = ns.Name; Name = tName } - Attributes = qsType.ResolvedAttributes - Access = qsType.Access - Source = { CodeFile = source; AssemblyFile = Null } - Position = DeclarationHeader.Offset.Defined qsType.Position - SymbolRange = DeclarationHeader.Range.Defined qsType.Range - Type = underlyingType - TypeItems = items - Documentation = qsType.Documentation - })) + |> Seq.collect + (fun ns -> + ns.TypesDefinedInAllSources() + |> Seq.choose + (fun kvPair -> + let tName, (source, qsType) = kvPair.Key, kvPair.Value + + match qsType.Resolved with + | Null -> + QsCompilerError.Raise "everything should be resolved but isn't" + None + | Value (underlyingType, items) -> + Some + { + QualifiedName = { Namespace = ns.Name; Name = tName } + Attributes = qsType.ResolvedAttributes + Access = qsType.Access + Source = { CodeFile = source; AssemblyFile = Null } + Position = DeclarationHeader.Offset.Defined qsType.Position + SymbolRange = DeclarationHeader.Range.Defined qsType.Range + Type = underlyingType + TypeItems = items + Documentation = qsType.Documentation + })) defined.ToImmutableArray() finally @@ -1177,9 +1239,10 @@ type NamespaceManager(syncRoot: IReaderWriterLock, | true, NS -> let copy = NS.Copy() - if copy.TryAddSource source - then copy - else ArgumentException "partial namespace already exists" |> raise + if copy.TryAddSource source then + copy + else + ArgumentException "partial namespace already exists" |> raise | false, _ -> new Namespace(nsName, [ source ], ImmutableArray.Empty, ImmutableArray.Empty, ImmutableArray.Empty) finally @@ -1270,10 +1333,9 @@ type NamespaceManager(syncRoot: IReaderWriterLock, let findInReferences (ns: Namespace) = ns.CallablesInReferencedAssemblies.[callableName.Name] - |> Seq.map (fun callable -> - if callable.Access |> Access.isAccessibleFrom OtherAssembly - then Found callable - else Inaccessible) + |> Seq.map + (fun callable -> + if callable.Access |> Access.isAccessibleFrom OtherAssembly then Found callable else Inaccessible) |> ResolutionResult.AtMostOne let findInSources (ns: Namespace) = @@ -1282,15 +1344,17 @@ type NamespaceManager(syncRoot: IReaderWriterLock, // OK to use CallableInSource because this is only evaluated if the callable is not in a reference. let kind, declaration = ns.CallableInSource source callableName.Name - if declaration.Access |> Access.isAccessibleFrom SameAssembly - then Found(buildHeader { callableName with Namespace = ns.Name } (source, kind, declaration)) - else Inaccessible + if declaration.Access |> Access.isAccessibleFrom SameAssembly then + Found(buildHeader { callableName with Namespace = ns.Name } (source, kind, declaration)) + else + Inaccessible | None -> match ns.CallablesDefinedInAllSources().TryGetValue callableName.Name with | true, (source, (kind, declaration)) -> - if declaration.Access |> Access.isAccessibleFrom SameAssembly - then Found(buildHeader { callableName with Namespace = ns.Name } (source, kind, declaration)) - else Inaccessible + if declaration.Access |> Access.isAccessibleFrom SameAssembly then + Found(buildHeader { callableName with Namespace = ns.Name } (source, kind, declaration)) + else + Inaccessible | false, _ -> NotFound syncRoot.EnterReadLock() @@ -1316,7 +1380,7 @@ type NamespaceManager(syncRoot: IReaderWriterLock, /// contain the parent namespace. /// member this.TryGetCallable (callableName: QsQualifiedName) (nsName, source) = - this.TryGetCallableHeader (callableName, None) (nsName, source) + this.TryGetCallableHeader(callableName, None) (nsName, source) /// Given an unqualified callable name, returns the corresponding CallableDeclarationHeader in a ResolutionResult if /// the qualifier can be uniquely resolved within the given parent namespace and source file, and the callable is @@ -1374,10 +1438,12 @@ type NamespaceManager(syncRoot: IReaderWriterLock, let findInReferences (ns: Namespace) = ns.TypesInReferencedAssemblies.[typeName.Name] - |> Seq.map (fun typeHeader -> - if typeHeader.Access |> Access.isAccessibleFrom OtherAssembly - then Found typeHeader - else Inaccessible) + |> Seq.map + (fun typeHeader -> + if typeHeader.Access |> Access.isAccessibleFrom OtherAssembly then + Found typeHeader + else + Inaccessible) |> ResolutionResult.AtMostOne let findInSources (ns: Namespace) = @@ -1386,15 +1452,17 @@ type NamespaceManager(syncRoot: IReaderWriterLock, // OK to use TypeInSource because this is only evaluated if the type is not in a reference. let declaration = ns.TypeInSource source typeName.Name - if declaration.Access |> Access.isAccessibleFrom SameAssembly - then Found(buildHeader { typeName with Namespace = ns.Name } (source, declaration)) - else Inaccessible + if declaration.Access |> Access.isAccessibleFrom SameAssembly then + Found(buildHeader { typeName with Namespace = ns.Name } (source, declaration)) + else + Inaccessible | None -> match ns.TypesDefinedInAllSources().TryGetValue typeName.Name with | true, (source, declaration) -> - if declaration.Access |> Access.isAccessibleFrom SameAssembly - then Found(buildHeader { typeName with Namespace = ns.Name } (source, declaration)) - else Inaccessible + if declaration.Access |> Access.isAccessibleFrom SameAssembly then + Found(buildHeader { typeName with Namespace = ns.Name } (source, declaration)) + else + Inaccessible | false, _ -> NotFound syncRoot.EnterReadLock() @@ -1420,7 +1488,7 @@ type NamespaceManager(syncRoot: IReaderWriterLock, /// contain the parent namespace. /// member this.TryGetType (typeName: QsQualifiedName) (nsName, source) = - this.TryGetTypeHeader (typeName, None) (nsName, source) + this.TryGetTypeHeader(typeName, None) (nsName, source) /// Given an unqualified type name, returns the corresponding TypeDeclarationHeader in a ResolutionResult if the /// qualifier can be uniquely resolved within the given parent namespace and source file, and the type is @@ -1430,7 +1498,7 @@ type NamespaceManager(syncRoot: IReaderWriterLock, /// uniquely resolved. member this.TryResolveAndGetType tName (nsName, source) = let toHeader (declaredNs, (declaredSource, _, _)) = - match this.TryGetTypeHeader ({ Namespace = declaredNs; Name = tName }, Some declaredSource) (nsName, source) with + match this.TryGetTypeHeader({ Namespace = declaredNs; Name = tName }, Some declaredSource) (nsName, source) with | Found value -> value | _ -> QsCompilerError.Raise "Expected to find the header corresponding to a possible resolution" @@ -1469,8 +1537,8 @@ type NamespaceManager(syncRoot: IReaderWriterLock, try Namespaces.Values - |> Seq.choose (fun ns -> - ns.TryFindCallable cName |> ResolutionResult.ToOption |> Option.map (fun _ -> ns.Name)) + |> Seq.choose + (fun ns -> ns.TryFindCallable cName |> ResolutionResult.ToOption |> Option.map (fun _ -> ns.Name)) |> fun namespaces -> namespaces.ToImmutableArray() finally syncRoot.ExitReadLock() @@ -1509,11 +1577,12 @@ type NamespaceManager(syncRoot: IReaderWriterLock, | QsTypeKind.UserDefinedType udt -> hash (2, udt.Namespace, udt.Name) | QsTypeKind.TypeParameter tp -> hash (3, tp.Origin.Namespace, tp.Origin.Name, tp.TypeName) | QsTypeKind.Operation ((inT, outT), fList) -> - hash - (4, - (inT |> NamespaceManager.TypeHash), - (outT |> NamespaceManager.TypeHash), - (fList |> JsonConvert.SerializeObject)) + hash ( + 4, + (inT |> NamespaceManager.TypeHash), + (outT |> NamespaceManager.TypeHash), + (fList |> JsonConvert.SerializeObject) + ) | QsTypeKind.Function (inT, outT) -> hash (5, (inT |> NamespaceManager.TypeHash), (outT |> NamespaceManager.TypeHash)) | kind -> JsonConvert.SerializeObject kind |> hash @@ -1552,7 +1621,7 @@ type NamespaceManager(syncRoot: IReaderWriterLock, hash (id.Namespace, id.Name, NamespaceManager.ExpressionHash arg) attributes - |> QsNullable<_>.Choose(fun att -> att.TypeId |> QsNullable<_>.Map(getHash att.Argument)) + |> QsNullable<_>.Choose (fun att -> att.TypeId |> QsNullable<_>.Map (getHash att.Argument)) |> Seq.toList let callableHash (kind, (signature, _), specs, attributes: QsDeclarationAttribute seq) = @@ -1572,7 +1641,7 @@ type NamespaceManager(syncRoot: IReaderWriterLock, let genHash (gen: ResolvedGenerator) = let tArgs = gen.TypeArguments - |> QsNullable<_>.Map(fun tArgs -> tArgs |> Seq.map NamespaceManager.TypeHash |> Seq.toList) + |> QsNullable<_>.Map (fun tArgs -> tArgs |> Seq.map NamespaceManager.TypeHash |> Seq.toList) hash (gen.Directive, hash tArgs) @@ -1587,7 +1656,8 @@ type NamespaceManager(syncRoot: IReaderWriterLock, let namedItems = typeItems.Items - |> Seq.choose (function + |> Seq.choose + (function | Named item -> Some item | _ -> None) @@ -1605,35 +1675,41 @@ type NamespaceManager(syncRoot: IReaderWriterLock, let callables = relevantNamespaces - |> Seq.collect (fun ns -> - let inSource = ns.CallablesDefinedInSource source |> Seq.sortBy fst - - inSource - |> Seq.map (fun (cName, (kind, signature)) -> - let specs = - ns.SpecializationsDefinedInAllSources cName - |> Seq.map (fun (kind, (_, resolution)) -> - kind, resolution.Resolved.ValueOrApply inconsistentStateException) - - let resolved = signature.Resolved.ValueOrApply inconsistentStateException - ns.Name, cName, (kind, resolved, specs, signature.ResolvedAttributes))) + |> Seq.collect + (fun ns -> + let inSource = ns.CallablesDefinedInSource source |> Seq.sortBy fst + + inSource + |> Seq.map + (fun (cName, (kind, signature)) -> + let specs = + ns.SpecializationsDefinedInAllSources cName + |> Seq.map + (fun (kind, (_, resolution)) -> + kind, resolution.Resolved.ValueOrApply inconsistentStateException) + + let resolved = signature.Resolved.ValueOrApply inconsistentStateException + ns.Name, cName, (kind, resolved, specs, signature.ResolvedAttributes))) let types = relevantNamespaces - |> Seq.collect (fun ns -> - let inSources = ns.TypesDefinedInSource source |> Seq.sortBy fst + |> Seq.collect + (fun ns -> + let inSources = ns.TypesDefinedInSource source |> Seq.sortBy fst - inSources - |> Seq.map (fun (tName, qsType) -> - let resolved, resItems = qsType.Resolved.ValueOrApply inconsistentStateException - ns.Name, tName, (resolved, resItems, qsType.ResolvedAttributes))) + inSources + |> Seq.map + (fun (tName, qsType) -> + let resolved, resItems = qsType.Resolved.ValueOrApply inconsistentStateException + ns.Name, tName, (resolved, resItems, qsType.ResolvedAttributes))) let imports = relevantNamespaces - |> Seq.collect (fun ns -> - ns.ImportedNamespaces source - |> Seq.sortBy (fun x -> x.Value) - |> Seq.map (fun opened -> ns.Name, opened.Value)) + |> Seq.collect + (fun ns -> + ns.ImportedNamespaces source + |> Seq.sortBy (fun x -> x.Value) + |> Seq.map (fun opened -> ns.Name, opened.Value)) let callablesHash = callables |> Seq.map (fun (ns, name, c) -> (ns, name, callableHash c)) |> Seq.toList |> hash diff --git a/src/QsCompiler/Core/SymbolTable/PartialNamespace.fs b/src/QsCompiler/Core/SymbolTable/PartialNamespace.fs index 0d102d8587..6dea3d5158 100644 --- a/src/QsCompiler/Core/SymbolTable/PartialNamespace.fs +++ b/src/QsCompiler/Core/SymbolTable/PartialNamespace.fs @@ -17,13 +17,17 @@ open Microsoft.Quantum.QsCompiler.Utils /// Represents the partial declaration of a namespace in a single file. /// /// Note that this class is *not* thread-safe, and access modifiers are always ignored when looking up declarations. -type private PartialNamespace private (name: string, - source: string, - documentation: IEnumerable>, - openNS: IEnumerable>, - typeDecl: IEnumerable, ResolvedType * QsTuple>>>, - callableDecl: IEnumerable>>>>, - specializations: IEnumerable>>>) = +type private PartialNamespace + private + ( + name: string, + source: string, + documentation: IEnumerable>, + openNS: IEnumerable>, + typeDecl: IEnumerable, ResolvedType * QsTuple>>>, + callableDecl: IEnumerable>>>>, + specializations: IEnumerable>>> + ) = let keySelector (item: KeyValuePair<'k, 'v>) = item.Key let valueSelector (item: KeyValuePair<'k, 'v>) = item.Value @@ -112,8 +116,8 @@ type private PartialNamespace private (name: string, member internal this.GetCallable cName = CallableDeclarations.TryGetValue cName |> tryOption - |> Option.defaultWith (fun () -> - SymbolNotFoundException "A callable with the given name was not found." |> raise) + |> Option.defaultWith + (fun () -> SymbolNotFoundException "A callable with the given name was not found." |> raise) member internal this.ContainsCallable = CallableDeclarations.ContainsKey @@ -189,9 +193,10 @@ type private PartialNamespace private (name: string, let validDeprecatedQualification qual = String.IsNullOrWhiteSpace qual || qual = BuiltIn.Deprecated.FullName.Namespace - if attributes |> Seq.exists (SymbolResolution.IndicatesDeprecation validDeprecatedQualification) - then ImmutableArray.Create deprecationWithoutRedirect - else ImmutableArray.Empty + if attributes |> Seq.exists (SymbolResolution.IndicatesDeprecation validDeprecatedQualification) then + ImmutableArray.Create deprecationWithoutRedirect + else + ImmutableArray.Empty TypeDeclarations.Add(tName, (typeTuple, attributes, access, documentation) |> unresolved location) @@ -216,8 +221,10 @@ type private PartialNamespace private (name: string, /// The given location is associated with the callable declaration and accessible via the record properties Position and SymbolRange. /// -> Note that this routine will fail with the standard dictionary.Add error if a callable with that name already exists. member this.AddCallableDeclaration location (cName, (kind, signature), attributes, modifiers, documentation) = - CallableDeclarations.Add - (cName, (kind, (signature, attributes, modifiers, documentation) |> unresolved location)) + CallableDeclarations.Add( + cName, + (kind, (signature, attributes, modifiers, documentation) |> unresolved location) + ) /// Adds the callable specialization defined by the given kind and generator for the callable of the given name to the dictionary of declared specializations. /// The given location is associated with the given specialization and accessible via the record properties Position and HeaderRange. @@ -225,14 +232,11 @@ type private PartialNamespace private (name: string, /// *IMPORTANT*: both the verification of whether the length of the given array of type specialization /// matches the number of type parameters in the callable declaration, and whether a specialization that clashes with this one /// already exists is up to the calling routine! - member this.AddCallableSpecialization location - kind - (cName, - generator: QsSpecializationGenerator, - attributes, - access, - documentation) - = + member this.AddCallableSpecialization + location + kind + (cName, generator: QsSpecializationGenerator, attributes, access, documentation) + = // NOTE: all types that are not specialized need to be resolved according to the file in which the callable is declared, // but all specialized types need to be resolved according to *this* file let spec = kind, (generator, attributes, access, documentation) |> unresolved location @@ -287,10 +291,11 @@ type private PartialNamespace private (name: string, match CallableSpecializations.TryGetValue cName with | true, specs -> [| 0 .. specs.Count - 1 |] - |> Array.collect (fun index -> - let kind, spec = specs.[index] - let resAttr, attErrs = getResAttributes this.Source spec - let res, errs = computeResolution this.Source (kind, spec) - specs.[index] <- (kind, { spec with Resolved = res; ResolvedAttributes = resAttr }) - errs |> Array.append attErrs) + |> Array.collect + (fun index -> + let kind, spec = specs.[index] + let resAttr, attErrs = getResAttributes this.Source spec + let res, errs = computeResolution this.Source (kind, spec) + specs.[index] <- (kind, { spec with Resolved = res; ResolvedAttributes = resAttr }) + errs |> Array.append attErrs) | false, _ -> [||] diff --git a/src/QsCompiler/Core/SyntaxGenerator.fs b/src/QsCompiler/Core/SyntaxGenerator.fs index 838ef4bb22..08796727ef 100644 --- a/src/QsCompiler/Core/SyntaxGenerator.fs +++ b/src/QsCompiler/Core/SyntaxGenerator.fs @@ -54,7 +54,9 @@ and public StripPositionInfo private (_internal_) = defaultInstance.Expressions.OnTypedExpression e static member public Apply s = defaultInstance.Statements.OnScope s - static member public Apply a = defaultInstance.Namespaces.OnNamespace a + + static member public Apply a = + defaultInstance.Namespaces.OnNamespace a module SyntaxGenerator = @@ -83,33 +85,33 @@ module SyntaxGenerator = /// Creates a typed expression that corresponds to a Bool literal with the given value. /// Sets the range information for the built expression to Null. let BoolLiteral value = - AutoGeneratedExpression (BoolLiteral value) QsTypeKind.Bool false + AutoGeneratedExpression(BoolLiteral value) QsTypeKind.Bool false /// Creates a typed expression that corresponds to an Int literal with the given value. /// Sets the range information for the built expression to Null. let IntLiteral v = - AutoGeneratedExpression (IntLiteral v) QsTypeKind.Int false + AutoGeneratedExpression(IntLiteral v) QsTypeKind.Int false /// Creates a typed expression that corresponds to a BigInt literal with the given value. /// Sets the range information for the built expression to Null. let BigIntLiteral (v: int) = - AutoGeneratedExpression (BigIntLiteral(bigint v)) QsTypeKind.BigInt false + AutoGeneratedExpression(BigIntLiteral(bigint v)) QsTypeKind.BigInt false /// Creates a typed expression that corresponds to a Double literal with the given value. /// Sets the range information for the built expression to Null. let DoubleLiteral v = - AutoGeneratedExpression (DoubleLiteral v) QsTypeKind.Double false + AutoGeneratedExpression(DoubleLiteral v) QsTypeKind.Double false /// Creates a typed expression that corresponds to a String literal with the given value and interpolation arguments. /// Sets the range information for the built expression to Null. let StringLiteral (s, interpolArgs) = - AutoGeneratedExpression (StringLiteral(s, interpolArgs)) QsTypeKind.String false + AutoGeneratedExpression(StringLiteral(s, interpolArgs)) QsTypeKind.String false /// Creates a typed expression that corresponds to a Range literal with the given left hand side and right hand side. /// Sets the range information for the built expression to Null. /// Does *not* verify the given left and right hand side. let RangeLiteral (lhs, rhs) = - AutoGeneratedExpression (RangeLiteral(lhs, rhs)) QsTypeKind.Range false + AutoGeneratedExpression(RangeLiteral(lhs, rhs)) QsTypeKind.Range false /// Creates a typed expression that corresponds to a value tuple with the given items. /// Sets the range information for the built expression to Null. @@ -117,13 +119,13 @@ module SyntaxGenerator = let TupleLiteral (items: TypedExpression seq) = let qdep = items |> Seq.exists (fun item -> item.InferredInformation.HasLocalQuantumDependency) let tupleType = items |> Seq.map (fun item -> item.ResolvedType) |> ImmutableArray.CreateRange |> TupleType - AutoGeneratedExpression (ValueTuple(items.ToImmutableArray())) tupleType qdep + AutoGeneratedExpression(ValueTuple(items.ToImmutableArray())) tupleType qdep // utils for assignments /// Given a typed expression that consists only of local variables, missing or invalid expressions, and tuples thereof, /// returns the corresponding symbol tuple. Throws an ArgumentException if the expression contains anything else. - let rec ExpressionAsSymbolTuple (ex: TypedExpression): SymbolTuple = + let rec ExpressionAsSymbolTuple (ex: TypedExpression) : SymbolTuple = match ex.Expression with | ValueTuple items -> items |> Seq.map ExpressionAsSymbolTuple |> ImmutableArray.CreateRange |> VariableNameTuple @@ -137,7 +139,7 @@ module SyntaxGenerator = /// Given the argument tuple of a callable or a provided specialization declaration, returns the corresponding symbol tuple. /// Throws an ArgumentExecption if the outermost tuple is empty or if it is not a QsTuple, or if an inner tuple is empty. - let ArgumentTupleAsSymbolTuple (argTuple: QsTuple>): SymbolTuple = + let ArgumentTupleAsSymbolTuple (argTuple: QsTuple>) : SymbolTuple = let rec resolveArgTupleItem = function | QsTupleItem (decl: LocalVariableDeclaration) -> @@ -182,7 +184,7 @@ module SyntaxGenerator = and buildTuple elements = let items = elements |> Seq.map resolveArgTupleItem |> ImmutableArray.CreateRange let exType = items |> Seq.map (fun ex -> ex.ResolvedType) |> ImmutableArray.CreateRange |> TupleType - AutoGeneratedExpression (ValueTuple items) exType false + AutoGeneratedExpression(ValueTuple items) exType false match argTuple with | QsTuple elements when elements.Length = 0 -> UnitValue @@ -222,7 +224,7 @@ module SyntaxGenerator = let exTypeKind = QsTypeKind.Function(QsTypeKind.Range |> ResolvedType.New, QsTypeKind.Range |> ResolvedType.New) - let reverse = AutoGeneratedExpression (QsExpressionKind.Identifier(kind, Null)) exTypeKind false + let reverse = AutoGeneratedExpression(QsExpressionKind.Identifier(kind, Null)) exTypeKind false CallNonGeneric(reverse, ex) match ex.ResolvedType.Resolution with @@ -261,7 +263,7 @@ module SyntaxGenerator = QsTypeKind.ArrayType(QsTypeKind.TypeParameter typeParameter |> ResolvedType.New) |> ResolvedType.New let exTypeKind = QsTypeKind.Function(genArrayType, QsTypeKind.Int |> ResolvedType.New) - let length = AutoGeneratedExpression (QsExpressionKind.Identifier(kind, Null)) exTypeKind false + let length = AutoGeneratedExpression(QsExpressionKind.Identifier(kind, Null)) exTypeKind false let callToLength tpRes = let resolutions = (seq { yield (typeParameter.Origin, typeParameter.TypeName, tpRes) }).ToImmutableArray() @@ -418,8 +420,8 @@ module SyntaxGenerator = | Missing -> false | _ -> true - if ctlQs.ResolvedType.Resolution <> QubitArrayType.Resolution && not (ctlQs.ResolvedType |> isInvalid) - then new ArgumentException "expression for the control qubits is valid but not of type Qubit[]" |> raise + if ctlQs.ResolvedType.Resolution <> QubitArrayType.Resolution && not (ctlQs.ResolvedType |> isInvalid) then + new ArgumentException "expression for the control qubits is valid but not of type Qubit[]" |> raise TupleLiteral [ ctlQs; arg ] diff --git a/src/QsCompiler/Core/SyntaxTreeExtensions.fs b/src/QsCompiler/Core/SyntaxTreeExtensions.fs index 2045b09c48..1c1548c132 100644 --- a/src/QsCompiler/Core/SyntaxTreeExtensions.fs +++ b/src/QsCompiler/Core/SyntaxTreeExtensions.fs @@ -18,10 +18,8 @@ open System.Linq let private OnTupleItems onSingle tupleName (items: ImmutableArray<'a>) = - if items.Length = 0 - then failwith (sprintf "empty tuple in %s instance" tupleName) - elif items.Length = 1 - then items.[0] |> onSingle + if items.Length = 0 then failwith (sprintf "empty tuple in %s instance" tupleName) + elif items.Length = 1 then items.[0] |> onSingle else Some(items |> Seq.toList) @@ -29,7 +27,7 @@ type QsInitializer with // utils for tuple matching - static member private OnTupleItems = OnTupleItems (fun (single: QsInitializer) -> single.TupleItems) "QsInitializer" + static member private OnTupleItems = OnTupleItems(fun (single: QsInitializer) -> single.TupleItems) "QsInitializer" member internal this.TupleItems = match this.Initializer with @@ -43,7 +41,7 @@ type ResolvedInitializer with // utils for tuple matching static member private OnTupleItems = - OnTupleItems (fun (single: ResolvedInitializer) -> single.TupleItems) "ResolvedInitializer" + OnTupleItems(fun (single: ResolvedInitializer) -> single.TupleItems) "ResolvedInitializer" member internal this.TupleItems = match this.Resolution with @@ -56,7 +54,7 @@ type QsSymbol with // utils for tuple matching - static member private OnTupleItems = OnTupleItems (fun (single: QsSymbol) -> single.TupleItems) "QsSymbol" + static member private OnTupleItems = OnTupleItems(fun (single: QsSymbol) -> single.TupleItems) "QsSymbol" member internal this.TupleItems = match this.Symbol with @@ -70,7 +68,7 @@ type SymbolTuple with // utils for tuple matching - static member private OnTupleItems = OnTupleItems (fun (single: SymbolTuple) -> single.TupleItems) "SymbolTuple" + static member private OnTupleItems = OnTupleItems(fun (single: SymbolTuple) -> single.TupleItems) "SymbolTuple" member internal this.TupleItems = match this with @@ -99,7 +97,7 @@ type ResolvedType with // utils for tuple matching - static member private OnTupleItems = OnTupleItems (fun (single: ResolvedType) -> single.TupleItems) "ResolvedType" + static member private OnTupleItems = OnTupleItems(fun (single: ResolvedType) -> single.TupleItems) "ResolvedType" member internal this.TupleItems = match this.Resolution with @@ -129,8 +127,10 @@ type ResolvedType with /// Recursively applies the given function inner to the given item and /// applies the given extraction function to each contained subitem of the returned type kind. /// Returns an enumerable of all extracted items. - static member private ExtractAll (inner: _ -> QsTypeKind<_, _, _, _>, extract: _ -> IEnumerable<_>) this - : IEnumerable<_> = + static member private ExtractAll + (inner: _ -> QsTypeKind<_, _, _, _>, extract: _ -> IEnumerable<_>) + this + : IEnumerable<_> = let recur = ResolvedType.ExtractAll(inner, extract) match inner this with @@ -145,16 +145,16 @@ type ResolvedType with /// and applies the given extraction function to each contained type, /// including array base types, tuple item types, and argument and result types of functions and operations. /// Returns an enumerable of all extracted return values. - member this.ExtractAll(extract: _ -> IEnumerable<_>): IEnumerable<_> = + member this.ExtractAll(extract: _ -> IEnumerable<_>) : IEnumerable<_> = let inner (t: ResolvedType) = t.Resolution - ResolvedType.ExtractAll (inner, extract) this + ResolvedType.ExtractAll(inner, extract) this type QsType with // utils for tuple matching - static member private OnTupleItems = OnTupleItems (fun (single: QsType) -> single.TupleItems) "QsType" + static member private OnTupleItems = OnTupleItems(fun (single: QsType) -> single.TupleItems) "QsType" member internal this.TupleItems = match this.Type with @@ -170,7 +170,7 @@ type QsType with /// Returns an enumerable of all extracted types. member public this.ExtractAll(extract: _ -> IEnumerable<_>) = let inner (t: QsType) = t.Type - ResolvedType.ExtractAll (inner, extract) this + ResolvedType.ExtractAll(inner, extract) this type TypedExpression with @@ -178,7 +178,7 @@ type TypedExpression with // utils for tuple matching static member private OnTupleItems = - OnTupleItems (fun (single: TypedExpression) -> single.TupleItems) "TypedExpression" + OnTupleItems(fun (single: TypedExpression) -> single.TupleItems) "TypedExpression" member internal this.TupleItems = match this.Expression with @@ -192,8 +192,10 @@ type TypedExpression with /// Recursively traverses an expression by first applying the given mapper to the expression, /// then finding all sub-expressions recurring on each one, and finally calling the given folder /// with the original expression as well as the returned results. - static member private MapAndFold (mapper: 'E -> QsExpressionKind<'E, _, _>, folder: 'E -> 'A seq -> 'A) (expr: 'E) - : 'A = + static member private MapAndFold + (mapper: 'E -> QsExpressionKind<'E, _, _>, folder: 'E -> 'A seq -> 'A) + (expr: 'E) + : 'A = let recur = TypedExpression.MapAndFold(mapper, folder) match mapper expr with @@ -272,8 +274,10 @@ type TypedExpression with /// Recursively applies the given function inner to the given item and /// applies the given extraction function to each contained subitem of the returned expression kind. /// Returns an enumerable of all extracted items. - static member private ExtractAll (inner: 'E -> QsExpressionKind<'E, _, _>, extract: _ -> seq<_>) (this: 'E) - : seq<_> = + static member private ExtractAll + (inner: 'E -> QsExpressionKind<'E, _, _>, extract: _ -> seq<_>) + (this: 'E) + : seq<_> = let fold ex sub = Seq.concat sub |> Seq.append (extract ex) @@ -284,7 +288,7 @@ type TypedExpression with /// Returns an enumerable of all extracted expressions. member public this.ExtractAll(extract: _ -> IEnumerable<_>) = let inner (ex: TypedExpression) = ex.Expression - TypedExpression.ExtractAll (inner, extract) this + TypedExpression.ExtractAll(inner, extract) this /// Applies the given function to the expression kind, /// and then recurs into each subexpression of the returned expression kind. @@ -302,7 +306,7 @@ type QsExpression with // utils for tuple matching - static member private OnTupleItems = OnTupleItems (fun (single: QsExpression) -> single.TupleItems) "QsExpression" + static member private OnTupleItems = OnTupleItems(fun (single: QsExpression) -> single.TupleItems) "QsExpression" member internal this.TupleItems = match this.Expression with @@ -318,7 +322,7 @@ type QsExpression with /// Returns an enumerable of all extracted expressions. member public this.ExtractAll(extract: _ -> IEnumerable<_>) = let inner (ex: QsExpression) = ex.Expression - TypedExpression.ExtractAll (inner, extract) this + TypedExpression.ExtractAll(inner, extract) this type QsStatement with @@ -342,9 +346,9 @@ type QsStatement with | QsConditionalStatement s -> (Seq.append (s.ConditionalBlocks |> Seq.collect (fun (_, b) -> b.Body.Statements)) - (match s.Default with - | Null -> Seq.empty - | Value v -> upcast v.Body.Statements)) + (match s.Default with + | Null -> Seq.empty + | Value v -> upcast v.Body.Statements)) | QsForStatement s -> upcast s.Body.Statements | QsWhileStatement s -> upcast s.Body.Statements | QsConjugation s -> Seq.append s.OuterTransformation.Body.Statements s.InnerTransformation.Body.Statements @@ -390,7 +394,7 @@ type QsTuple<'I> with // not the nicest solution, but unfortunatly type extensions cannot be used to satisfy member constraints... // the box >> unbox below is used to cast the value to the inferred type of 'T -let private TupleItems<'T when 'T :> ITuple> (arg: 'T): 'T list option = +let private TupleItems<'T when 'T :> ITuple> (arg: 'T) : 'T list option = let cast a = box >> unbox |> List.map |> Option.map <| a @@ -455,7 +459,7 @@ let TryAsGlobalCallable (this: TypedExpression) = | _ -> Null [] -let GetResolvedType (argTuple: QsTuple>): ResolvedType = +let GetResolvedType (argTuple: QsTuple>) : ResolvedType = let rec resolveArgTupleItem = function | QsTupleItem (decl: LocalVariableDeclaration) -> decl.Type @@ -480,20 +484,24 @@ let GetResolvedType (argTuple: QsTuple>) [] let Types (syntaxTree: IEnumerable) = syntaxTree - |> Seq.collect (fun ns -> - ns.Elements - |> Seq.choose (function - | QsCustomType t -> Some t - | _ -> None)) + |> Seq.collect + (fun ns -> + ns.Elements + |> Seq.choose + (function + | QsCustomType t -> Some t + | _ -> None)) [] let Callables (syntaxTree: IEnumerable) = syntaxTree - |> Seq.collect (fun ns -> - ns.Elements - |> Seq.choose (function - | QsCallable c -> Some c - | _ -> None)) + |> Seq.collect + (fun ns -> + ns.Elements + |> Seq.choose + (function + | QsCallable c -> Some c + | _ -> None)) [] let Attributes (syntaxTree: IEnumerable) = @@ -504,30 +512,36 @@ let Attributes (syntaxTree: IEnumerable) = | Null -> false syntaxTree - |> Seq.collect (fun ns -> - ns.Elements - |> Seq.choose (function - | QsCustomType t when t.Attributes |> Seq.exists marksAttribute -> Some t - | _ -> None)) + |> Seq.collect + (fun ns -> + ns.Elements + |> Seq.choose + (function + | QsCustomType t when t.Attributes |> Seq.exists marksAttribute -> Some t + | _ -> None)) [] let Specializations (syntaxTree: IEnumerable) = syntaxTree - |> Seq.collect (fun ns -> - ns.Elements - |> Seq.collect (function - | QsCallable c -> c.Specializations - | _ -> ImmutableArray.Empty)) + |> Seq.collect + (fun ns -> + ns.Elements + |> Seq.collect + (function + | QsCallable c -> c.Specializations + | _ -> ImmutableArray.Empty)) [] let GlobalTypeResolutions (syntaxTree: IEnumerable) = let types = syntaxTree - |> Seq.collect (fun ns -> - ns.Elements - |> Seq.choose (function - | QsCustomType t -> Some(t.FullName, t) - | _ -> None)) + |> Seq.collect + (fun ns -> + ns.Elements + |> Seq.choose + (function + | QsCustomType t -> Some(t.FullName, t) + | _ -> None)) types.ToImmutableDictionary(fst, snd) @@ -535,11 +549,13 @@ let GlobalTypeResolutions (syntaxTree: IEnumerable) = let GlobalCallableResolutions (syntaxTree: IEnumerable) = let callables = syntaxTree - |> Seq.collect (fun ns -> - ns.Elements - |> Seq.choose (function - | QsCallable c -> Some(c.FullName, c) - | _ -> None)) + |> Seq.collect + (fun ns -> + ns.Elements + |> Seq.choose + (function + | QsCallable c -> Some(c.FullName, c) + | _ -> None)) callables.ToImmutableDictionary(fst, snd) diff --git a/src/QsCompiler/Core/Transformations/ExpressionTransformation.fs b/src/QsCompiler/Core/Transformations/ExpressionTransformation.fs index ab5371915e..fac9f00751 100644 --- a/src/QsCompiler/Core/Transformations/ExpressionTransformation.fs +++ b/src/QsCompiler/Core/Transformations/ExpressionTransformation.fs @@ -50,38 +50,42 @@ type ExpressionKindTransformationBase internal (options: TransformationOptions, new(expressionTransformation: unit -> ExpressionTransformationBase, typeTransformation: unit -> TypeTransformationBase) = - new ExpressionKindTransformationBase(expressionTransformation, typeTransformation, TransformationOptions.Default) + new ExpressionKindTransformationBase( + expressionTransformation, + typeTransformation, + TransformationOptions.Default + ) new() = new ExpressionKindTransformationBase(TransformationOptions.Default) // nodes containing subexpressions or subtypes - abstract OnIdentifier: Identifier * QsNullable> -> ExpressionKind + abstract OnIdentifier : Identifier * QsNullable> -> ExpressionKind default this.OnIdentifier(sym, tArgs) = - let tArgs = tArgs |> QsNullable<_>.Map(fun ts -> ts |> Seq.map this.Types.OnType |> ImmutableArray.CreateRange) + let tArgs = tArgs |> QsNullable<_>.Map (fun ts -> ts |> Seq.map this.Types.OnType |> ImmutableArray.CreateRange) Identifier |> Node.BuildOr InvalidExpr (sym, tArgs) - abstract OnOperationCall: TypedExpression * TypedExpression -> ExpressionKind + abstract OnOperationCall : TypedExpression * TypedExpression -> ExpressionKind default this.OnOperationCall(method, arg) = let method, arg = this.Expressions.OnTypedExpression method, this.Expressions.OnTypedExpression arg CallLikeExpression |> Node.BuildOr InvalidExpr (method, arg) - abstract OnFunctionCall: TypedExpression * TypedExpression -> ExpressionKind + abstract OnFunctionCall : TypedExpression * TypedExpression -> ExpressionKind default this.OnFunctionCall(method, arg) = let method, arg = this.Expressions.OnTypedExpression method, this.Expressions.OnTypedExpression arg CallLikeExpression |> Node.BuildOr InvalidExpr (method, arg) - abstract OnPartialApplication: TypedExpression * TypedExpression -> ExpressionKind + abstract OnPartialApplication : TypedExpression * TypedExpression -> ExpressionKind default this.OnPartialApplication(method, arg) = let method, arg = this.Expressions.OnTypedExpression method, this.Expressions.OnTypedExpression arg CallLikeExpression |> Node.BuildOr InvalidExpr (method, arg) - abstract OnCallLikeExpression: TypedExpression * TypedExpression -> ExpressionKind + abstract OnCallLikeExpression : TypedExpression * TypedExpression -> ExpressionKind default this.OnCallLikeExpression(method, arg) = match method.ResolvedType.Resolution with @@ -90,74 +94,74 @@ type ExpressionKindTransformationBase internal (options: TransformationOptions, | ExpressionType.Operation _ -> this.OnOperationCall(method, arg) | _ -> this.OnFunctionCall(method, arg) - abstract OnAdjointApplication: TypedExpression -> ExpressionKind + abstract OnAdjointApplication : TypedExpression -> ExpressionKind default this.OnAdjointApplication ex = let ex = this.Expressions.OnTypedExpression ex AdjointApplication |> Node.BuildOr InvalidExpr ex - abstract OnControlledApplication: TypedExpression -> ExpressionKind + abstract OnControlledApplication : TypedExpression -> ExpressionKind default this.OnControlledApplication ex = let ex = this.Expressions.OnTypedExpression ex ControlledApplication |> Node.BuildOr InvalidExpr ex - abstract OnUnwrapApplication: TypedExpression -> ExpressionKind + abstract OnUnwrapApplication : TypedExpression -> ExpressionKind default this.OnUnwrapApplication ex = let ex = this.Expressions.OnTypedExpression ex UnwrapApplication |> Node.BuildOr InvalidExpr ex - abstract OnValueTuple: ImmutableArray -> ExpressionKind + abstract OnValueTuple : ImmutableArray -> ExpressionKind default this.OnValueTuple vs = let values = vs |> Seq.map this.Expressions.OnTypedExpression |> ImmutableArray.CreateRange ValueTuple |> Node.BuildOr InvalidExpr values - abstract OnArrayItem: TypedExpression * TypedExpression -> ExpressionKind + abstract OnArrayItem : TypedExpression * TypedExpression -> ExpressionKind default this.OnArrayItem(arr, idx) = let arr, idx = this.Expressions.OnTypedExpression arr, this.Expressions.OnTypedExpression idx ArrayItem |> Node.BuildOr InvalidExpr (arr, idx) - abstract OnNamedItem: TypedExpression * Identifier -> ExpressionKind + abstract OnNamedItem : TypedExpression * Identifier -> ExpressionKind default this.OnNamedItem(ex, acc) = let ex = this.Expressions.OnTypedExpression ex NamedItem |> Node.BuildOr InvalidExpr (ex, acc) - abstract OnValueArray: ImmutableArray -> ExpressionKind + abstract OnValueArray : ImmutableArray -> ExpressionKind default this.OnValueArray vs = let values = vs |> Seq.map this.Expressions.OnTypedExpression |> ImmutableArray.CreateRange ValueArray |> Node.BuildOr InvalidExpr values - abstract OnNewArray: ResolvedType * TypedExpression -> ExpressionKind + abstract OnNewArray : ResolvedType * TypedExpression -> ExpressionKind default this.OnNewArray(bt, idx) = let bt, idx = this.Types.OnType bt, this.Expressions.OnTypedExpression idx NewArray |> Node.BuildOr InvalidExpr (bt, idx) - abstract OnSizedArray: value:TypedExpression * size:TypedExpression -> ExpressionKind + abstract OnSizedArray : value: TypedExpression * size: TypedExpression -> ExpressionKind default this.OnSizedArray(value, size) = let value = this.Expressions.OnTypedExpression value let size = this.Expressions.OnTypedExpression size SizedArray |> Node.BuildOr InvalidExpr (value, size) - abstract OnStringLiteral: string * ImmutableArray -> ExpressionKind + abstract OnStringLiteral : string * ImmutableArray -> ExpressionKind default this.OnStringLiteral(s, exs) = let exs = exs |> Seq.map this.Expressions.OnTypedExpression |> ImmutableArray.CreateRange StringLiteral |> Node.BuildOr InvalidExpr (s, exs) - abstract OnRangeLiteral: TypedExpression * TypedExpression -> ExpressionKind + abstract OnRangeLiteral : TypedExpression * TypedExpression -> ExpressionKind default this.OnRangeLiteral(lhs, rhs) = let lhs, rhs = this.Expressions.OnTypedExpression lhs, this.Expressions.OnTypedExpression rhs RangeLiteral |> Node.BuildOr InvalidExpr (lhs, rhs) - abstract OnCopyAndUpdateExpression: TypedExpression * TypedExpression * TypedExpression -> ExpressionKind + abstract OnCopyAndUpdateExpression : TypedExpression * TypedExpression * TypedExpression -> ExpressionKind default this.OnCopyAndUpdateExpression(lhs, accEx, rhs) = let lhs, accEx, rhs = @@ -167,7 +171,7 @@ type ExpressionKindTransformationBase internal (options: TransformationOptions, CopyAndUpdate |> Node.BuildOr InvalidExpr (lhs, accEx, rhs) - abstract OnConditionalExpression: TypedExpression * TypedExpression * TypedExpression -> ExpressionKind + abstract OnConditionalExpression : TypedExpression * TypedExpression * TypedExpression -> ExpressionKind default this.OnConditionalExpression(cond, ifTrue, ifFalse) = let cond, ifTrue, ifFalse = @@ -177,133 +181,133 @@ type ExpressionKindTransformationBase internal (options: TransformationOptions, CONDITIONAL |> Node.BuildOr InvalidExpr (cond, ifTrue, ifFalse) - abstract OnEquality: TypedExpression * TypedExpression -> ExpressionKind + abstract OnEquality : TypedExpression * TypedExpression -> ExpressionKind default this.OnEquality(lhs, rhs) = let lhs, rhs = this.Expressions.OnTypedExpression lhs, this.Expressions.OnTypedExpression rhs EQ |> Node.BuildOr InvalidExpr (lhs, rhs) - abstract OnInequality: TypedExpression * TypedExpression -> ExpressionKind + abstract OnInequality : TypedExpression * TypedExpression -> ExpressionKind default this.OnInequality(lhs, rhs) = let lhs, rhs = this.Expressions.OnTypedExpression lhs, this.Expressions.OnTypedExpression rhs NEQ |> Node.BuildOr InvalidExpr (lhs, rhs) - abstract OnLessThan: TypedExpression * TypedExpression -> ExpressionKind + abstract OnLessThan : TypedExpression * TypedExpression -> ExpressionKind default this.OnLessThan(lhs, rhs) = let lhs, rhs = this.Expressions.OnTypedExpression lhs, this.Expressions.OnTypedExpression rhs LT |> Node.BuildOr InvalidExpr (lhs, rhs) - abstract OnLessThanOrEqual: TypedExpression * TypedExpression -> ExpressionKind + abstract OnLessThanOrEqual : TypedExpression * TypedExpression -> ExpressionKind default this.OnLessThanOrEqual(lhs, rhs) = let lhs, rhs = this.Expressions.OnTypedExpression lhs, this.Expressions.OnTypedExpression rhs LTE |> Node.BuildOr InvalidExpr (lhs, rhs) - abstract OnGreaterThan: TypedExpression * TypedExpression -> ExpressionKind + abstract OnGreaterThan : TypedExpression * TypedExpression -> ExpressionKind default this.OnGreaterThan(lhs, rhs) = let lhs, rhs = this.Expressions.OnTypedExpression lhs, this.Expressions.OnTypedExpression rhs GT |> Node.BuildOr InvalidExpr (lhs, rhs) - abstract OnGreaterThanOrEqual: TypedExpression * TypedExpression -> ExpressionKind + abstract OnGreaterThanOrEqual : TypedExpression * TypedExpression -> ExpressionKind default this.OnGreaterThanOrEqual(lhs, rhs) = let lhs, rhs = this.Expressions.OnTypedExpression lhs, this.Expressions.OnTypedExpression rhs GTE |> Node.BuildOr InvalidExpr (lhs, rhs) - abstract OnLogicalAnd: TypedExpression * TypedExpression -> ExpressionKind + abstract OnLogicalAnd : TypedExpression * TypedExpression -> ExpressionKind default this.OnLogicalAnd(lhs, rhs) = let lhs, rhs = this.Expressions.OnTypedExpression lhs, this.Expressions.OnTypedExpression rhs AND |> Node.BuildOr InvalidExpr (lhs, rhs) - abstract OnLogicalOr: TypedExpression * TypedExpression -> ExpressionKind + abstract OnLogicalOr : TypedExpression * TypedExpression -> ExpressionKind default this.OnLogicalOr(lhs, rhs) = let lhs, rhs = this.Expressions.OnTypedExpression lhs, this.Expressions.OnTypedExpression rhs OR |> Node.BuildOr InvalidExpr (lhs, rhs) - abstract OnAddition: TypedExpression * TypedExpression -> ExpressionKind + abstract OnAddition : TypedExpression * TypedExpression -> ExpressionKind default this.OnAddition(lhs, rhs) = let lhs, rhs = this.Expressions.OnTypedExpression lhs, this.Expressions.OnTypedExpression rhs ADD |> Node.BuildOr InvalidExpr (lhs, rhs) - abstract OnSubtraction: TypedExpression * TypedExpression -> ExpressionKind + abstract OnSubtraction : TypedExpression * TypedExpression -> ExpressionKind default this.OnSubtraction(lhs, rhs) = let lhs, rhs = this.Expressions.OnTypedExpression lhs, this.Expressions.OnTypedExpression rhs SUB |> Node.BuildOr InvalidExpr (lhs, rhs) - abstract OnMultiplication: TypedExpression * TypedExpression -> ExpressionKind + abstract OnMultiplication : TypedExpression * TypedExpression -> ExpressionKind default this.OnMultiplication(lhs, rhs) = let lhs, rhs = this.Expressions.OnTypedExpression lhs, this.Expressions.OnTypedExpression rhs MUL |> Node.BuildOr InvalidExpr (lhs, rhs) - abstract OnDivision: TypedExpression * TypedExpression -> ExpressionKind + abstract OnDivision : TypedExpression * TypedExpression -> ExpressionKind default this.OnDivision(lhs, rhs) = let lhs, rhs = this.Expressions.OnTypedExpression lhs, this.Expressions.OnTypedExpression rhs DIV |> Node.BuildOr InvalidExpr (lhs, rhs) - abstract OnExponentiate: TypedExpression * TypedExpression -> ExpressionKind + abstract OnExponentiate : TypedExpression * TypedExpression -> ExpressionKind default this.OnExponentiate(lhs, rhs) = let lhs, rhs = this.Expressions.OnTypedExpression lhs, this.Expressions.OnTypedExpression rhs POW |> Node.BuildOr InvalidExpr (lhs, rhs) - abstract OnModulo: TypedExpression * TypedExpression -> ExpressionKind + abstract OnModulo : TypedExpression * TypedExpression -> ExpressionKind default this.OnModulo(lhs, rhs) = let lhs, rhs = this.Expressions.OnTypedExpression lhs, this.Expressions.OnTypedExpression rhs MOD |> Node.BuildOr InvalidExpr (lhs, rhs) - abstract OnLeftShift: TypedExpression * TypedExpression -> ExpressionKind + abstract OnLeftShift : TypedExpression * TypedExpression -> ExpressionKind default this.OnLeftShift(lhs, rhs) = let lhs, rhs = this.Expressions.OnTypedExpression lhs, this.Expressions.OnTypedExpression rhs LSHIFT |> Node.BuildOr InvalidExpr (lhs, rhs) - abstract OnRightShift: TypedExpression * TypedExpression -> ExpressionKind + abstract OnRightShift : TypedExpression * TypedExpression -> ExpressionKind default this.OnRightShift(lhs, rhs) = let lhs, rhs = this.Expressions.OnTypedExpression lhs, this.Expressions.OnTypedExpression rhs RSHIFT |> Node.BuildOr InvalidExpr (lhs, rhs) - abstract OnBitwiseExclusiveOr: TypedExpression * TypedExpression -> ExpressionKind + abstract OnBitwiseExclusiveOr : TypedExpression * TypedExpression -> ExpressionKind default this.OnBitwiseExclusiveOr(lhs, rhs) = let lhs, rhs = this.Expressions.OnTypedExpression lhs, this.Expressions.OnTypedExpression rhs BXOR |> Node.BuildOr InvalidExpr (lhs, rhs) - abstract OnBitwiseOr: TypedExpression * TypedExpression -> ExpressionKind + abstract OnBitwiseOr : TypedExpression * TypedExpression -> ExpressionKind default this.OnBitwiseOr(lhs, rhs) = let lhs, rhs = this.Expressions.OnTypedExpression lhs, this.Expressions.OnTypedExpression rhs BOR |> Node.BuildOr InvalidExpr (lhs, rhs) - abstract OnBitwiseAnd: TypedExpression * TypedExpression -> ExpressionKind + abstract OnBitwiseAnd : TypedExpression * TypedExpression -> ExpressionKind default this.OnBitwiseAnd(lhs, rhs) = let lhs, rhs = this.Expressions.OnTypedExpression lhs, this.Expressions.OnTypedExpression rhs BAND |> Node.BuildOr InvalidExpr (lhs, rhs) - abstract OnLogicalNot: TypedExpression -> ExpressionKind + abstract OnLogicalNot : TypedExpression -> ExpressionKind default this.OnLogicalNot ex = let ex = this.Expressions.OnTypedExpression ex NOT |> Node.BuildOr InvalidExpr ex - abstract OnNegative: TypedExpression -> ExpressionKind + abstract OnNegative : TypedExpression -> ExpressionKind default this.OnNegative ex = let ex = this.Expressions.OnTypedExpression ex NEG |> Node.BuildOr InvalidExpr ex - abstract OnBitwiseNot: TypedExpression -> ExpressionKind + abstract OnBitwiseNot : TypedExpression -> ExpressionKind default this.OnBitwiseNot ex = let ex = this.Expressions.OnTypedExpression ex @@ -312,37 +316,37 @@ type ExpressionKindTransformationBase internal (options: TransformationOptions, // leaf nodes - abstract OnUnitValue: unit -> ExpressionKind + abstract OnUnitValue : unit -> ExpressionKind default this.OnUnitValue() = ExpressionKind.UnitValue - abstract OnMissingExpression: unit -> ExpressionKind + abstract OnMissingExpression : unit -> ExpressionKind default this.OnMissingExpression() = MissingExpr - abstract OnInvalidExpression: unit -> ExpressionKind + abstract OnInvalidExpression : unit -> ExpressionKind default this.OnInvalidExpression() = InvalidExpr - abstract OnIntLiteral: int64 -> ExpressionKind + abstract OnIntLiteral : int64 -> ExpressionKind default this.OnIntLiteral i = IntLiteral i - abstract OnBigIntLiteral: BigInteger -> ExpressionKind + abstract OnBigIntLiteral : BigInteger -> ExpressionKind default this.OnBigIntLiteral b = BigIntLiteral b - abstract OnDoubleLiteral: double -> ExpressionKind + abstract OnDoubleLiteral : double -> ExpressionKind default this.OnDoubleLiteral d = DoubleLiteral d - abstract OnBoolLiteral: bool -> ExpressionKind + abstract OnBoolLiteral : bool -> ExpressionKind default this.OnBoolLiteral b = BoolLiteral b - abstract OnResultLiteral: QsResult -> ExpressionKind + abstract OnResultLiteral : QsResult -> ExpressionKind default this.OnResultLiteral r = ResultLiteral r - abstract OnPauliLiteral: QsPauli -> ExpressionKind + abstract OnPauliLiteral : QsPauli -> ExpressionKind default this.OnPauliLiteral p = PauliLiteral p // transformation root called on each node - abstract OnExpressionKind: ExpressionKind -> ExpressionKind + abstract OnExpressionKind : ExpressionKind -> ExpressionKind default this.OnExpressionKind kind = if not options.Enable then @@ -441,23 +445,25 @@ and ExpressionTransformationBase internal (options: TransformationOptions, _inte // supplementary expression information - abstract OnRangeInformation: QsNullable -> QsNullable + abstract OnRangeInformation : QsNullable -> QsNullable default this.OnRangeInformation range = range - abstract OnExpressionInformation: InferredExpressionInformation -> InferredExpressionInformation + abstract OnExpressionInformation : InferredExpressionInformation -> InferredExpressionInformation default this.OnExpressionInformation info = info // nodes containing subexpressions or subtypes - abstract OnTypeParamResolutions: ImmutableDictionary<(QsQualifiedName * string), ResolvedType> - -> ImmutableDictionary<(QsQualifiedName * string), ResolvedType> + abstract OnTypeParamResolutions : + ImmutableDictionary<(QsQualifiedName * string), ResolvedType> -> + ImmutableDictionary<(QsQualifiedName * string), ResolvedType> default this.OnTypeParamResolutions typeParams = let filteredTypeParams = typeParams |> Seq.map (fun kv -> QsTypeParameter.New(fst kv.Key, snd kv.Key) |> this.Types.OnTypeParameter, kv.Value) - |> Seq.choose (function + |> Seq.choose + (function | TypeParameter tp, value -> Some((tp.Origin, tp.TypeName), this.Types.OnType value) | _ -> None) |> Seq.map (fun (key, value) -> new KeyValuePair<_, _>(key, value)) @@ -470,7 +476,7 @@ and ExpressionTransformationBase internal (options: TransformationOptions, _inte // transformation root called on each node - abstract OnTypedExpression: TypedExpression -> TypedExpression + abstract OnTypedExpression : TypedExpression -> TypedExpression default this.OnTypedExpression(ex: TypedExpression) = if not options.Enable then diff --git a/src/QsCompiler/Core/Transformations/NamespaceTransformation.fs b/src/QsCompiler/Core/Transformations/NamespaceTransformation.fs index fccd3f860e..f3eb22a62c 100644 --- a/src/QsCompiler/Core/Transformations/NamespaceTransformation.fs +++ b/src/QsCompiler/Core/Transformations/NamespaceTransformation.fs @@ -45,34 +45,35 @@ type NamespaceTransformationBase internal (options: TransformationOptions, _inte // subconstructs used within declarations - abstract OnLocation: QsNullable -> QsNullable + abstract OnLocation : QsNullable -> QsNullable default this.OnLocation l = l - abstract OnDocumentation: ImmutableArray -> ImmutableArray + abstract OnDocumentation : ImmutableArray -> ImmutableArray default this.OnDocumentation doc = doc // TODO: RELEASE 2021-07: Remove NamespaceTransformationBase.OnSourceFile. [] - abstract OnSourceFile: string -> string + abstract OnSourceFile : string -> string default this.OnSourceFile file = file - abstract OnSource: Source -> Source + abstract OnSource : Source -> Source default this.OnSource source = let file = Source.assemblyOrCodeFile source |> this.OnSourceFile - if file.EndsWith ".qs" - then { source with CodeFile = file } - else { source with AssemblyFile = Value file } + if file.EndsWith ".qs" then + { source with CodeFile = file } + else + { source with AssemblyFile = Value file } - abstract OnAttribute: QsDeclarationAttribute -> QsDeclarationAttribute + abstract OnAttribute : QsDeclarationAttribute -> QsDeclarationAttribute default this.OnAttribute att = att - abstract OnItemName: string -> string + abstract OnItemName : string -> string default this.OnItemName name = name - abstract OnTypeItems: QsTuple -> QsTuple + abstract OnTypeItems : QsTuple -> QsTuple default this.OnTypeItems tItem = match tItem with @@ -91,14 +92,14 @@ type NamespaceTransformationBase internal (options: TransformationOptions, _inte QsTupleItem << Named << LocalVariableDeclaration<_>.New info.IsMutable |> Node.BuildOr original (loc, name, t, info.HasLocalQuantumDependency) - abstract OnArgumentName: QsLocalSymbol -> QsLocalSymbol + abstract OnArgumentName : QsLocalSymbol -> QsLocalSymbol default this.OnArgumentName arg = match arg with | ValidName name -> ValidName |> Node.BuildOr arg (this.Statements.OnVariableName name) | InvalidName -> arg - abstract OnArgumentTuple: QsArgumentTuple -> QsArgumentTuple + abstract OnArgumentTuple : QsArgumentTuple -> QsArgumentTuple default this.OnArgumentTuple arg = match arg with @@ -114,7 +115,7 @@ type NamespaceTransformationBase internal (options: TransformationOptions, _inte QsTupleItem << LocalVariableDeclaration<_>.New info.IsMutable |> Node.BuildOr original (loc, name, t, info.HasLocalQuantumDependency) - abstract OnSignature: ResolvedSignature -> ResolvedSignature + abstract OnSignature : ResolvedSignature -> ResolvedSignature default this.OnSignature(s: ResolvedSignature) = let typeParams = s.TypeParameters @@ -126,32 +127,32 @@ type NamespaceTransformationBase internal (options: TransformationOptions, _inte // specialization declarations and implementations - abstract OnProvidedImplementation: QsArgumentTuple * QsScope -> QsArgumentTuple * QsScope + abstract OnProvidedImplementation : QsArgumentTuple * QsScope -> QsArgumentTuple * QsScope default this.OnProvidedImplementation(argTuple, body) = let argTuple = this.OnArgumentTuple argTuple let body = this.Statements.OnScope body argTuple, body - abstract OnSelfInverseDirective: unit -> unit + abstract OnSelfInverseDirective : unit -> unit default this.OnSelfInverseDirective() = () - abstract OnInvertDirective: unit -> unit + abstract OnInvertDirective : unit -> unit default this.OnInvertDirective() = () - abstract OnDistributeDirective: unit -> unit + abstract OnDistributeDirective : unit -> unit default this.OnDistributeDirective() = () - abstract OnInvalidGeneratorDirective: unit -> unit + abstract OnInvalidGeneratorDirective : unit -> unit default this.OnInvalidGeneratorDirective() = () - abstract OnExternalImplementation: unit -> unit + abstract OnExternalImplementation : unit -> unit default this.OnExternalImplementation() = () - abstract OnIntrinsicImplementation: unit -> unit + abstract OnIntrinsicImplementation : unit -> unit default this.OnIntrinsicImplementation() = () - abstract OnGeneratedImplementation: QsGeneratorDirective -> QsGeneratorDirective + abstract OnGeneratedImplementation : QsGeneratorDirective -> QsGeneratorDirective default this.OnGeneratedImplementation(directive: QsGeneratorDirective) = match directive with @@ -168,7 +169,7 @@ type NamespaceTransformationBase internal (options: TransformationOptions, _inte this.OnInvalidGeneratorDirective() InvalidGenerator - abstract OnSpecializationImplementation: SpecializationImplementation -> SpecializationImplementation + abstract OnSpecializationImplementation : SpecializationImplementation -> SpecializationImplementation default this.OnSpecializationImplementation(implementation: SpecializationImplementation) = let Build kind transformed = @@ -193,8 +194,8 @@ type NamespaceTransformationBase internal (options: TransformationOptions, _inte let typeArgs = spec.TypeArguments - |> QsNullable<_> - .Map(fun args -> args |> Seq.map this.Statements.Expressions.Types.OnType |> ImmutableArray.CreateRange) + |> QsNullable<_>.Map + (fun args -> args |> Seq.map this.Statements.Expressions.Types.OnType |> ImmutableArray.CreateRange) let signature = this.OnSignature spec.Signature let impl = this.OnSpecializationImplementation spec.Implementation @@ -204,19 +205,19 @@ type NamespaceTransformationBase internal (options: TransformationOptions, _inte QsSpecialization.New spec.Kind (source, loc) |> Node.BuildOr spec (spec.Parent, attributes, typeArgs, signature, impl, doc, comments) - abstract OnBodySpecialization: QsSpecialization -> QsSpecialization + abstract OnBodySpecialization : QsSpecialization -> QsSpecialization default this.OnBodySpecialization spec = this.OnSpecializationKind spec - abstract OnAdjointSpecialization: QsSpecialization -> QsSpecialization + abstract OnAdjointSpecialization : QsSpecialization -> QsSpecialization default this.OnAdjointSpecialization spec = this.OnSpecializationKind spec - abstract OnControlledSpecialization: QsSpecialization -> QsSpecialization + abstract OnControlledSpecialization : QsSpecialization -> QsSpecialization default this.OnControlledSpecialization spec = this.OnSpecializationKind spec - abstract OnControlledAdjointSpecialization: QsSpecialization -> QsSpecialization + abstract OnControlledAdjointSpecialization : QsSpecialization -> QsSpecialization default this.OnControlledAdjointSpecialization spec = this.OnSpecializationKind spec - abstract OnSpecializationDeclaration: QsSpecialization -> QsSpecialization + abstract OnSpecializationDeclaration : QsSpecialization -> QsSpecialization default this.OnSpecializationDeclaration(spec: QsSpecialization) = match spec.Kind with @@ -249,16 +250,16 @@ type NamespaceTransformationBase internal (options: TransformationOptions, _inte QsCallable.New c.Kind (source, loc) |> Node.BuildOr c (c.FullName, attributes, c.Access, argTuple, signature, specializations, doc, comments) - abstract OnOperation: QsCallable -> QsCallable + abstract OnOperation : QsCallable -> QsCallable default this.OnOperation c = this.OnCallableKind c - abstract OnFunction: QsCallable -> QsCallable + abstract OnFunction : QsCallable -> QsCallable default this.OnFunction c = this.OnCallableKind c - abstract OnTypeConstructor: QsCallable -> QsCallable + abstract OnTypeConstructor : QsCallable -> QsCallable default this.OnTypeConstructor c = this.OnCallableKind c - abstract OnCallableDeclaration: QsCallable -> QsCallable + abstract OnCallableDeclaration : QsCallable -> QsCallable default this.OnCallableDeclaration(c: QsCallable) = match c.Kind with @@ -266,7 +267,7 @@ type NamespaceTransformationBase internal (options: TransformationOptions, _inte | QsCallableKind.Operation -> this.OnOperation c | QsCallableKind.TypeConstructor -> this.OnTypeConstructor c - abstract OnTypeDeclaration: QsCustomType -> QsCustomType + abstract OnTypeDeclaration : QsCustomType -> QsCustomType default this.OnTypeDeclaration t = let source = this.OnSource t.Source @@ -283,7 +284,7 @@ type NamespaceTransformationBase internal (options: TransformationOptions, _inte // transformation roots called on each namespace or namespace element - abstract OnNamespaceElement: QsNamespaceElement -> QsNamespaceElement + abstract OnNamespaceElement : QsNamespaceElement -> QsNamespaceElement default this.OnNamespaceElement element = if not options.Enable then @@ -293,7 +294,7 @@ type NamespaceTransformationBase internal (options: TransformationOptions, _inte | QsCustomType t -> t |> this.OnTypeDeclaration |> QsCustomType | QsCallable c -> c |> this.OnCallableDeclaration |> QsCallable - abstract OnNamespace: QsNamespace -> QsNamespace + abstract OnNamespace : QsNamespace -> QsNamespace default this.OnNamespace ns = if not options.Enable then diff --git a/src/QsCompiler/Core/Transformations/StatementTransformation.fs b/src/QsCompiler/Core/Transformations/StatementTransformation.fs index 6db9ff4527..848a77f4ee 100644 --- a/src/QsCompiler/Core/Transformations/StatementTransformation.fs +++ b/src/QsCompiler/Core/Transformations/StatementTransformation.fs @@ -46,19 +46,21 @@ type StatementKindTransformationBase internal (options: TransformationOptions, _ new(statementTransformation: unit -> StatementTransformationBase, expressionTransformation: unit -> ExpressionTransformationBase) = - new StatementKindTransformationBase(statementTransformation, - expressionTransformation, - TransformationOptions.Default) + new StatementKindTransformationBase( + statementTransformation, + expressionTransformation, + TransformationOptions.Default + ) new() = new StatementKindTransformationBase(TransformationOptions.Default) // subconstructs used within statements - abstract OnSymbolTuple: SymbolTuple -> SymbolTuple + abstract OnSymbolTuple : SymbolTuple -> SymbolTuple default this.OnSymbolTuple syms = syms - abstract OnQubitInitializer: ResolvedInitializer -> ResolvedInitializer + abstract OnQubitInitializer : ResolvedInitializer -> ResolvedInitializer default this.OnQubitInitializer init = let transformed = @@ -73,9 +75,9 @@ type StatementKindTransformationBase internal (options: TransformationOptions, _ ResolvedInitializer.New |> Node.BuildOr init transformed - abstract OnPositionedBlock: QsNullable - * QsPositionedBlock - -> QsNullable * QsPositionedBlock + abstract OnPositionedBlock : + QsNullable * QsPositionedBlock -> + QsNullable * QsPositionedBlock default this.OnPositionedBlock(intro: QsNullable, block: QsPositionedBlock) = let location = this.Statements.OnLocation block.Location @@ -86,12 +88,12 @@ type StatementKindTransformationBase internal (options: TransformationOptions, _ let PositionedBlock (expr, body, location, comments) = expr, QsPositionedBlock.New comments location body - PositionedBlock |> Node.BuildOr (intro, block) (expr, body, location, comments) + PositionedBlock |> Node.BuildOr(intro, block) (expr, body, location, comments) // statements containing subconstructs or expressions - abstract OnVariableDeclaration: QsBinding -> QsStatementKind + abstract OnVariableDeclaration : QsBinding -> QsStatementKind default this.OnVariableDeclaration stm = let rhs = this.Expressions.OnTypedExpression stm.Rhs @@ -100,33 +102,34 @@ type StatementKindTransformationBase internal (options: TransformationOptions, _ QsVariableDeclaration << QsBinding.New stm.Kind |> Node.BuildOr EmptyStatement (lhs, rhs) - abstract OnValueUpdate: QsValueUpdate -> QsStatementKind + abstract OnValueUpdate : QsValueUpdate -> QsStatementKind default this.OnValueUpdate stm = let rhs = this.Expressions.OnTypedExpression stm.Rhs let lhs = this.Expressions.OnTypedExpression stm.Lhs QsValueUpdate << QsValueUpdate.New |> Node.BuildOr EmptyStatement (lhs, rhs) - abstract OnConditionalStatement: QsConditionalStatement -> QsStatementKind + abstract OnConditionalStatement : QsConditionalStatement -> QsStatementKind default this.OnConditionalStatement stm = let cases = stm.ConditionalBlocks - |> Seq.map (fun (c, b) -> - let cond, block = this.OnPositionedBlock(Value c, b) + |> Seq.map + (fun (c, b) -> + let cond, block = this.OnPositionedBlock(Value c, b) - let invalidCondition () = - failwith "missing condition in if-statement" + let invalidCondition () = + failwith "missing condition in if-statement" - cond.ValueOrApply invalidCondition, block) + cond.ValueOrApply invalidCondition, block) |> ImmutableArray.CreateRange - let defaultCase = stm.Default |> QsNullable<_>.Map(fun b -> this.OnPositionedBlock(Null, b) |> snd) + let defaultCase = stm.Default |> QsNullable<_>.Map (fun b -> this.OnPositionedBlock(Null, b) |> snd) QsConditionalStatement << QsConditionalStatement.New |> Node.BuildOr EmptyStatement (cases, defaultCase) - abstract OnForStatement: QsForStatement -> QsStatementKind + abstract OnForStatement : QsForStatement -> QsStatementKind default this.OnForStatement stm = let iterVals = this.Expressions.OnTypedExpression stm.IterationValues @@ -137,14 +140,14 @@ type StatementKindTransformationBase internal (options: TransformationOptions, _ QsForStatement << QsForStatement.New |> Node.BuildOr EmptyStatement ((loopVar, loopVarType), iterVals, body) - abstract OnWhileStatement: QsWhileStatement -> QsStatementKind + abstract OnWhileStatement : QsWhileStatement -> QsStatementKind default this.OnWhileStatement stm = let condition = this.Expressions.OnTypedExpression stm.Condition let body = this.Statements.OnScope stm.Body QsWhileStatement << QsWhileStatement.New |> Node.BuildOr EmptyStatement (condition, body) - abstract OnRepeatStatement: QsRepeatStatement -> QsStatementKind + abstract OnRepeatStatement : QsRepeatStatement -> QsStatementKind default this.OnRepeatStatement stm = let repeatBlock = this.OnPositionedBlock(Null, stm.RepeatBlock) |> snd @@ -156,26 +159,26 @@ type StatementKindTransformationBase internal (options: TransformationOptions, _ QsRepeatStatement << QsRepeatStatement.New |> Node.BuildOr EmptyStatement (repeatBlock, successCondition.ValueOrApply invalidCondition, fixupBlock) - abstract OnConjugation: QsConjugation -> QsStatementKind + abstract OnConjugation : QsConjugation -> QsStatementKind default this.OnConjugation stm = let outer = this.OnPositionedBlock(Null, stm.OuterTransformation) |> snd let inner = this.OnPositionedBlock(Null, stm.InnerTransformation) |> snd QsConjugation << QsConjugation.New |> Node.BuildOr EmptyStatement (outer, inner) - abstract OnExpressionStatement: TypedExpression -> QsStatementKind + abstract OnExpressionStatement : TypedExpression -> QsStatementKind default this.OnExpressionStatement ex = let transformed = this.Expressions.OnTypedExpression ex QsExpressionStatement |> Node.BuildOr EmptyStatement transformed - abstract OnReturnStatement: TypedExpression -> QsStatementKind + abstract OnReturnStatement : TypedExpression -> QsStatementKind default this.OnReturnStatement ex = let transformed = this.Expressions.OnTypedExpression ex QsReturnStatement |> Node.BuildOr EmptyStatement transformed - abstract OnFailStatement: TypedExpression -> QsStatementKind + abstract OnFailStatement : TypedExpression -> QsStatementKind default this.OnFailStatement ex = let transformed = this.Expressions.OnTypedExpression ex @@ -190,13 +193,13 @@ type StatementKindTransformationBase internal (options: TransformationOptions, _ let body = this.Statements.OnScope stm.Body QsQubitScope << QsQubitScope.New kind |> Node.BuildOr EmptyStatement ((lhs, rhs), body) - abstract OnAllocateQubits: QsQubitScope -> QsStatementKind + abstract OnAllocateQubits : QsQubitScope -> QsStatementKind default this.OnAllocateQubits stm = this.OnQubitScopeKind stm - abstract OnBorrowQubits: QsQubitScope -> QsStatementKind + abstract OnBorrowQubits : QsQubitScope -> QsStatementKind default this.OnBorrowQubits stm = this.OnQubitScopeKind stm - abstract OnQubitScope: QsQubitScope -> QsStatementKind + abstract OnQubitScope : QsQubitScope -> QsStatementKind default this.OnQubitScope(stm: QsQubitScope) = match stm.Kind with @@ -206,13 +209,13 @@ type StatementKindTransformationBase internal (options: TransformationOptions, _ // leaf nodes - abstract OnEmptyStatement: unit -> QsStatementKind + abstract OnEmptyStatement : unit -> QsStatementKind default this.OnEmptyStatement() = EmptyStatement // transformation root called on each statement - abstract OnStatementKind: QsStatementKind -> QsStatementKind + abstract OnStatementKind : QsStatementKind -> QsStatementKind default this.OnStatementKind kind = if not options.Enable then @@ -270,22 +273,24 @@ and StatementTransformationBase internal (options: TransformationOptions, _inter new(statementKindTransformation: unit -> StatementKindTransformationBase, expressionTransformation: unit -> ExpressionTransformationBase) = - new StatementTransformationBase(statementKindTransformation, - expressionTransformation, - TransformationOptions.Default) + new StatementTransformationBase( + statementKindTransformation, + expressionTransformation, + TransformationOptions.Default + ) new() = new StatementTransformationBase(TransformationOptions.Default) // supplementary statement information - abstract OnLocation: QsNullable -> QsNullable + abstract OnLocation : QsNullable -> QsNullable default this.OnLocation loc = loc - abstract OnVariableName: string -> string + abstract OnVariableName : string -> string default this.OnVariableName name = name - abstract OnLocalDeclarations: LocalDeclarations -> LocalDeclarations + abstract OnLocalDeclarations : LocalDeclarations -> LocalDeclarations default this.OnLocalDeclarations decl = let onLocalVariableDeclaration (local: LocalVariableDeclaration) = @@ -305,7 +310,7 @@ and StatementTransformationBase internal (options: TransformationOptions, _inter // transformation roots called on each statement or statement block - abstract OnStatement: QsStatement -> QsStatement + abstract OnStatement : QsStatement -> QsStatement default this.OnStatement stm = if not options.Enable then @@ -317,7 +322,7 @@ and StatementTransformationBase internal (options: TransformationOptions, _inter let varDecl = this.OnLocalDeclarations stm.SymbolDeclarations QsStatement.New comments location |> Node.BuildOr stm (kind, varDecl) - abstract OnScope: QsScope -> QsScope + abstract OnScope : QsScope -> QsScope default this.OnScope scope = if not options.Enable then diff --git a/src/QsCompiler/Core/Transformations/SyntaxTreeTransformation.fs b/src/QsCompiler/Core/Transformations/SyntaxTreeTransformation.fs index 6c7d74f939..1ac9a06c6f 100644 --- a/src/QsCompiler/Core/Transformations/SyntaxTreeTransformation.fs +++ b/src/QsCompiler/Core/Transformations/SyntaxTreeTransformation.fs @@ -76,7 +76,7 @@ type SyntaxTreeTransformation<'T> private (state: 'T, options: TransformationOpt and TypeTransformation<'T> internal (options, _internal_) = inherit TypeTransformationBase(options) - let mutable _Transformation: SyntaxTreeTransformation<'T> option = None // will be set to a suitable Some value once construction is complete + let mutable _Transformation : SyntaxTreeTransformation<'T> option = None // will be set to a suitable Some value once construction is complete /// Handle to the parent SyntaxTreeTransformation. /// This handle is always safe to access and will be set to a suitable value @@ -105,7 +105,7 @@ and TypeTransformation<'T> internal (options, _internal_) = and ExpressionKindTransformation<'T> internal (options, _internal_) = inherit ExpressionKindTransformationBase(options, _internal_) - let mutable _Transformation: SyntaxTreeTransformation<'T> option = None // will be set to a suitable Some value once construction is complete + let mutable _Transformation : SyntaxTreeTransformation<'T> option = None // will be set to a suitable Some value once construction is complete /// Handle to the parent SyntaxTreeTransformation. /// This handle is always safe to access and will be set to a suitable value @@ -138,7 +138,7 @@ and ExpressionKindTransformation<'T> internal (options, _internal_) = and ExpressionTransformation<'T> internal (options, _internal_) = inherit ExpressionTransformationBase(options, _internal_) - let mutable _Transformation: SyntaxTreeTransformation<'T> option = None // will be set to a suitable Some value once construction is complete + let mutable _Transformation : SyntaxTreeTransformation<'T> option = None // will be set to a suitable Some value once construction is complete /// Handle to the parent SyntaxTreeTransformation. /// This handle is always safe to access and will be set to a suitable value @@ -174,7 +174,7 @@ and ExpressionTransformation<'T> internal (options, _internal_) = and StatementKindTransformation<'T> internal (options, _internal_) = inherit StatementKindTransformationBase(options, _internal_) - let mutable _Transformation: SyntaxTreeTransformation<'T> option = None // will be set to a suitable Some value once construction is complete + let mutable _Transformation : SyntaxTreeTransformation<'T> option = None // will be set to a suitable Some value once construction is complete /// Handle to the parent SyntaxTreeTransformation. /// This handle is always safe to access and will be set to a suitable value @@ -211,7 +211,7 @@ and StatementKindTransformation<'T> internal (options, _internal_) = and StatementTransformation<'T> internal (options, _internal_) = inherit StatementTransformationBase(options, _internal_) - let mutable _Transformation: SyntaxTreeTransformation<'T> option = None // will be set to a suitable Some value once construction is complete + let mutable _Transformation : SyntaxTreeTransformation<'T> option = None // will be set to a suitable Some value once construction is complete /// Handle to the parent SyntaxTreeTransformation. /// This handle is always safe to access and will be set to a suitable value @@ -248,7 +248,7 @@ and StatementTransformation<'T> internal (options, _internal_) = and NamespaceTransformation<'T> internal (options, _internal_: string) = inherit NamespaceTransformationBase(options, _internal_) - let mutable _Transformation: SyntaxTreeTransformation<'T> option = None // will be set to a suitable Some value once construction is complete + let mutable _Transformation : SyntaxTreeTransformation<'T> option = None // will be set to a suitable Some value once construction is complete /// Handle to the parent SyntaxTreeTransformation. /// This handle is always safe to access and will be set to a suitable value @@ -350,7 +350,7 @@ type SyntaxTreeTransformation private (options: TransformationOptions, _internal and TypeTransformation internal (options, _internal_) = inherit TypeTransformationBase(options) - let mutable _Transformation: SyntaxTreeTransformation option = None // will be set to a suitable Some value once construction is complete + let mutable _Transformation : SyntaxTreeTransformation option = None // will be set to a suitable Some value once construction is complete /// Handle to the parent SyntaxTreeTransformation. /// This handle is always safe to access and will be set to a suitable value @@ -377,7 +377,7 @@ and TypeTransformation internal (options, _internal_) = and ExpressionKindTransformation internal (options, _internal_) = inherit ExpressionKindTransformationBase(options, _internal_) - let mutable _Transformation: SyntaxTreeTransformation option = None // will be set to a suitable Some value once construction is complete + let mutable _Transformation : SyntaxTreeTransformation option = None // will be set to a suitable Some value once construction is complete /// Handle to the parent SyntaxTreeTransformation. /// This handle is always safe to access and will be set to a suitable value @@ -408,7 +408,7 @@ and ExpressionKindTransformation internal (options, _internal_) = and ExpressionTransformation internal (options, _internal_) = inherit ExpressionTransformationBase(options, _internal_) - let mutable _Transformation: SyntaxTreeTransformation option = None // will be set to a suitable Some value once construction is complete + let mutable _Transformation : SyntaxTreeTransformation option = None // will be set to a suitable Some value once construction is complete /// Handle to the parent SyntaxTreeTransformation. /// This handle is always safe to access and will be set to a suitable value @@ -442,7 +442,7 @@ and ExpressionTransformation internal (options, _internal_) = and StatementKindTransformation internal (options, _internal_) = inherit StatementKindTransformationBase(options, _internal_) - let mutable _Transformation: SyntaxTreeTransformation option = None // will be set to a suitable Some value once construction is complete + let mutable _Transformation : SyntaxTreeTransformation option = None // will be set to a suitable Some value once construction is complete /// Handle to the parent SyntaxTreeTransformation. /// This handle is always safe to access and will be set to a suitable value @@ -477,7 +477,7 @@ and StatementKindTransformation internal (options, _internal_) = and StatementTransformation internal (options, _internal_) = inherit StatementTransformationBase(options, _internal_) - let mutable _Transformation: SyntaxTreeTransformation option = None // will be set to a suitable Some value once construction is complete + let mutable _Transformation : SyntaxTreeTransformation option = None // will be set to a suitable Some value once construction is complete /// Handle to the parent SyntaxTreeTransformation. /// This handle is always safe to access and will be set to a suitable value @@ -512,7 +512,7 @@ and StatementTransformation internal (options, _internal_) = and NamespaceTransformation internal (options, _internal_: string) = inherit NamespaceTransformationBase(options, _internal_) - let mutable _Transformation: SyntaxTreeTransformation option = None // will be set to a suitable Some value once construction is complete + let mutable _Transformation : SyntaxTreeTransformation option = None // will be set to a suitable Some value once construction is complete /// Handle to the parent SyntaxTreeTransformation. /// This handle is always safe to access and will be set to a suitable value diff --git a/src/QsCompiler/Core/Transformations/TransformationOptions.fs b/src/QsCompiler/Core/Transformations/TransformationOptions.fs index e1e5b63f27..5ef0a4b60d 100644 --- a/src/QsCompiler/Core/Transformations/TransformationOptions.fs +++ b/src/QsCompiler/Core/Transformations/TransformationOptions.fs @@ -17,19 +17,19 @@ type TransformationOptions = Rebuild: bool } - /// Default transformation setting. - /// The transformation will recur into leaf and subnodes, - /// and all nodes will be rebuilt upon transformation. - static member Default = { Enable = true; Rebuild = true } - - /// Disables the transformation at the transformation root, - /// meaning the transformation won't recur into leaf nodes or subnodes. - static member Disabled = { Enable = false; Rebuild = true } - - /// Indicates that the transformation is used to walk the syntax tree, but does not modify any of the nodes. - /// All nodes will be traversed recursively, but the nodes will not be rebuilt. - /// Setting this option constitutes a promise that the return value of all methods will be ignored. - static member NoRebuild = { Enable = true; Rebuild = false } + /// Default transformation setting. + /// The transformation will recur into leaf and subnodes, + /// and all nodes will be rebuilt upon transformation. + static member Default = { Enable = true; Rebuild = true } + + /// Disables the transformation at the transformation root, + /// meaning the transformation won't recur into leaf nodes or subnodes. + static member Disabled = { Enable = false; Rebuild = true } + + /// Indicates that the transformation is used to walk the syntax tree, but does not modify any of the nodes. + /// All nodes will be traversed recursively, but the nodes will not be rebuilt. + /// Setting this option constitutes a promise that the return value of all methods will be ignored. + static member NoRebuild = { Enable = true; Rebuild = false } /// Tools for adapting the default implementations for transformations diff --git a/src/QsCompiler/Core/Transformations/TypeTransformation.fs b/src/QsCompiler/Core/Transformations/TypeTransformation.fs index dca60e2d3b..78ae64600b 100644 --- a/src/QsCompiler/Core/Transformations/TypeTransformation.fs +++ b/src/QsCompiler/Core/Transformations/TypeTransformation.fs @@ -27,16 +27,17 @@ type TypeTransformationBase(options: TransformationOptions) = // TODO: RELEASE 2021-10: Remove obsolete method. [] - abstract OnRangeInformation: QsNullable -> QsNullable + abstract OnRangeInformation : QsNullable -> QsNullable + default this.OnRangeInformation range = range - abstract OnTypeRange: TypeRange -> TypeRange + abstract OnTypeRange : TypeRange -> TypeRange default this.OnTypeRange range = range - abstract OnCharacteristicsExpression: ResolvedCharacteristics -> ResolvedCharacteristics + abstract OnCharacteristicsExpression : ResolvedCharacteristics -> ResolvedCharacteristics default this.OnCharacteristicsExpression fs = fs - abstract OnCallableInformation: CallableInformation -> CallableInformation + abstract OnCallableInformation : CallableInformation -> CallableInformation default this.OnCallableInformation opInfo = let characteristics = this.OnCharacteristicsExpression opInfo.Characteristics @@ -46,14 +47,14 @@ type TypeTransformationBase(options: TransformationOptions) = // nodes containing subtypes - abstract OnUserDefinedType: UserDefinedType -> ExpressionType + abstract OnUserDefinedType : UserDefinedType -> ExpressionType default this.OnUserDefinedType udt = let ns, name = udt.Namespace, udt.Name let range = this.OnRangeInformation udt.Range Node.BuildOr InvalidType (ns, name, range) (UserDefinedType.New >> UserDefinedType) - abstract OnTypeParameter: QsTypeParameter -> ExpressionType + abstract OnTypeParameter : QsTypeParameter -> ExpressionType default this.OnTypeParameter tp = let origin = tp.Origin @@ -61,25 +62,25 @@ type TypeTransformationBase(options: TransformationOptions) = let range = this.OnRangeInformation tp.Range Node.BuildOr InvalidType (origin, name, range) (QsTypeParameter.New >> TypeParameter) - abstract OnOperation: (ResolvedType * ResolvedType) * CallableInformation -> ExpressionType + abstract OnOperation : (ResolvedType * ResolvedType) * CallableInformation -> ExpressionType default this.OnOperation((it, ot), info) = let transformed = (this.OnType it, this.OnType ot), this.OnCallableInformation info ExpressionType.Operation |> Node.BuildOr InvalidType transformed - abstract OnFunction: ResolvedType * ResolvedType -> ExpressionType + abstract OnFunction : ResolvedType * ResolvedType -> ExpressionType default this.OnFunction(it, ot) = let transformed = this.OnType it, this.OnType ot ExpressionType.Function |> Node.BuildOr InvalidType transformed - abstract OnTupleType: ImmutableArray -> ExpressionType + abstract OnTupleType : ImmutableArray -> ExpressionType default this.OnTupleType ts = let transformed = ts |> Seq.map this.OnType |> ImmutableArray.CreateRange ExpressionType.TupleType |> Node.BuildOr InvalidType transformed - abstract OnArrayType: ResolvedType -> ExpressionType + abstract OnArrayType : ResolvedType -> ExpressionType default this.OnArrayType b = ExpressionType.ArrayType |> Node.BuildOr InvalidType (this.OnType b) @@ -87,46 +88,47 @@ type TypeTransformationBase(options: TransformationOptions) = // leaf nodes - abstract OnUnitType: unit -> ExpressionType + abstract OnUnitType : unit -> ExpressionType default this.OnUnitType() = ExpressionType.UnitType - abstract OnQubit: unit -> ExpressionType + abstract OnQubit : unit -> ExpressionType default this.OnQubit() = ExpressionType.Qubit - abstract OnMissingType: unit -> ExpressionType + abstract OnMissingType : unit -> ExpressionType default this.OnMissingType() = ExpressionType.MissingType - abstract OnInvalidType: unit -> ExpressionType + abstract OnInvalidType : unit -> ExpressionType default this.OnInvalidType() = ExpressionType.InvalidType - abstract OnInt: unit -> ExpressionType + abstract OnInt : unit -> ExpressionType default this.OnInt() = ExpressionType.Int - abstract OnBigInt: unit -> ExpressionType + abstract OnBigInt : unit -> ExpressionType default this.OnBigInt() = ExpressionType.BigInt - abstract OnDouble: unit -> ExpressionType + abstract OnDouble : unit -> ExpressionType default this.OnDouble() = ExpressionType.Double - abstract OnBool: unit -> ExpressionType + abstract OnBool : unit -> ExpressionType default this.OnBool() = ExpressionType.Bool - abstract OnString: unit -> ExpressionType + abstract OnString : unit -> ExpressionType default this.OnString() = ExpressionType.String - abstract OnResult: unit -> ExpressionType + abstract OnResult : unit -> ExpressionType default this.OnResult() = ExpressionType.Result - abstract OnPauli: unit -> ExpressionType + abstract OnPauli : unit -> ExpressionType default this.OnPauli() = ExpressionType.Pauli - abstract OnRange: unit -> ExpressionType + abstract OnRange : unit -> ExpressionType default this.OnRange() = ExpressionType.Range // transformation root called on each node - abstract OnType: ResolvedType -> ResolvedType + abstract OnType : ResolvedType -> ResolvedType + default this.OnType(t: ResolvedType) = if not options.Enable then t diff --git a/src/QsCompiler/DataStructures/DataTypes.fs b/src/QsCompiler/DataStructures/DataTypes.fs index b69d674f0b..e32827a8f0 100644 --- a/src/QsCompiler/DataStructures/DataTypes.fs +++ b/src/QsCompiler/DataStructures/DataTypes.fs @@ -23,7 +23,7 @@ type QsNullable<'T> = /// If the given nullable has a value, applies the given function to it and returns the result as Value, /// and returns Null otherwise. - static member Map fct = QsNullable<_>.Bind(fct >> Value) + static member Map fct = QsNullable<_>.Bind (fct >> Value) /// If the given nullable has a value, applies the given function to it. static member Iter fct = @@ -51,11 +51,12 @@ type QsNullable<'T> = /// Returns the sequence comprised of the results x for each element where the function returns Value x static member Choose fct (seq: _ seq) = seq - |> Seq.choose - (fct - >> function - | Null -> None - | Value v -> Some v) + |> Seq.choose ( + fct + >> function + | Null -> None + | Value v -> Some v + ) /// Converts the given F# option to a QsNullable. // TODO: RELEASE 2021-08: Remove QsNullable.FromOption. @@ -187,8 +188,8 @@ type Position = /// /// Thrown if the line or column is negative. static member Create line column = - if line < 0 || column < 0 - then ArgumentOutOfRangeException "Line and column cannot be negative." |> raise + if line < 0 || column < 0 then + ArgumentOutOfRangeException "Line and column cannot be negative." |> raise Position(line, column) @@ -236,8 +237,7 @@ type Range = /// Thrown if occurs after . /// static member Create start ``end`` = - if start > ``end`` - then ArgumentException "Range start cannot occur after range end." |> raise + if start > ``end`` then ArgumentException "Range start cannot occur after range end." |> raise Range(start, ``end``) @@ -270,15 +270,15 @@ type QsCompilerDiagnostic = /// builds a new diagnostics error with the give code and range static member Error (code, args) range = - QsCompilerDiagnostic.New (Error code, args) range + QsCompilerDiagnostic.New(Error code, args) range /// builds a new diagnostics warning with the give code and range static member Warning (code, args) range = - QsCompilerDiagnostic.New (Warning code, args) range + QsCompilerDiagnostic.New(Warning code, args) range /// builds a new diagnostics information with the give code and range static member Info (code, args) range = - QsCompilerDiagnostic.New (Information code, args) range + QsCompilerDiagnostic.New(Information code, args) range member this.Code = match this.Diagnostic with @@ -295,7 +295,7 @@ type QsCompilerDiagnostic = /// interface used to pass anything lock-like to the symbol table (could not find an existing one??) type IReaderWriterLock = - abstract EnterReadLock: unit -> unit - abstract ExitReadLock: unit -> unit - abstract EnterWriteLock: unit -> unit - abstract ExitWriteLock: unit -> unit + abstract EnterReadLock : unit -> unit + abstract ExitReadLock : unit -> unit + abstract EnterWriteLock : unit -> unit + abstract ExitWriteLock : unit -> unit diff --git a/src/QsCompiler/DataStructures/Diagnostics.fs b/src/QsCompiler/DataStructures/Diagnostics.fs index bd8f59bca1..53916a9e85 100644 --- a/src/QsCompiler/DataStructures/Diagnostics.fs +++ b/src/QsCompiler/DataStructures/Diagnostics.fs @@ -446,7 +446,7 @@ type DiagnosticItem = | Information of InformationCode static member private ApplyArguments (args: IEnumerable) str = - let args: obj [] = + let args : obj [] = if args = null then [||] else @@ -773,9 +773,7 @@ type DiagnosticItem = | ErrorCode.UnexpectedTupleArgument -> "Unexpected argument tuple. Expecting an argument of type {0}." | ErrorCode.AmbiguousTypeParameterResolution -> "The type parameter {0} is ambiguous. More type annotations or usage context may be necessary." - + if Seq.item 1 args |> String.IsNullOrWhiteSpace - then "" - else " Note: {0} has constraints {1}." + + if Seq.item 1 args |> String.IsNullOrWhiteSpace then "" else " Note: {0} has constraints {1}." | ErrorCode.ConstrainsTypeParameter -> "The given expression constrains the type parameter(s) {0}." | ErrorCode.GlobalTypeAlreadyExists -> "A type with the name \"{0}\" already exists." | ErrorCode.GlobalCallableAlreadyExists -> "A callable with the name \"{0}\" already exists." diff --git a/src/QsCompiler/DataStructures/Documentation.fs b/src/QsCompiler/DataStructures/Documentation.fs index 304728b06f..12fa9b1c12 100644 --- a/src/QsCompiler/DataStructures/Documentation.fs +++ b/src/QsCompiler/DataStructures/Documentation.fs @@ -18,7 +18,7 @@ type QsType with | None -> InvalidSetExpr |> ResolvedCharacteristics.New | Some props -> ResolvedCharacteristics.FromProperties props - member public this.Documentation: ImmutableArray = + member public this.Documentation : ImmutableArray = let doc = match this.Type with | QsTypeKind.UnitType -> [ "# Summary"; "Represents a singleton type whose only value is \"()\"." ] diff --git a/src/QsCompiler/DataStructures/ErrorHandling.fs b/src/QsCompiler/DataStructures/ErrorHandling.fs index 3c211f07c9..9daf6387c6 100644 --- a/src/QsCompiler/DataStructures/ErrorHandling.fs +++ b/src/QsCompiler/DataStructures/ErrorHandling.fs @@ -22,10 +22,11 @@ type QsCompilerError = QsCompilerError /// Method that wraps all handling of inner errors (i.e. a failure of the Q# compiler) /// that allows to easily modify the behavior for such errors. [] - static member Raise(message, innerException: Exception): unit = - if innerException = null - then new QsCompilerException(message) |> raise - else new QsCompilerException(message, innerException) |> raise + static member Raise(message, innerException: Exception) : unit = + if innerException = null then + new QsCompilerException(message) |> raise + else + new QsCompilerException(message, innerException) |> raise /// Method that wraps all handling of inner errors (i.e. a failure of the Q# compiler) /// that allows to easily modify the behavior for such errors. @@ -44,9 +45,10 @@ type QsCompilerError = QsCompilerError let outer = sprintf "%s: %s\n" (ex.GetType().Name) ex.Message let inner = - if ex.InnerException = null - then "" - else sprintf "Inner Exception: %s - %s\n" (ex.InnerException.GetType().Name) ex.InnerException.Message + if ex.InnerException = null then + "" + else + sprintf "Inner Exception: %s - %s\n" (ex.InnerException.GetType().Name) ex.InnerException.Message let stackTrace = sprintf "Stack trace: \n%s\n" ex.StackTrace sprintf "%s\n%s%s%s" header outer inner stackTrace diff --git a/src/QsCompiler/DataStructures/Serialization.fs b/src/QsCompiler/DataStructures/Serialization.fs index f2b513290f..c61d16e62d 100644 --- a/src/QsCompiler/DataStructures/Serialization.fs +++ b/src/QsCompiler/DataStructures/Serialization.fs @@ -44,8 +44,8 @@ type RangeConverter() = let start, end' = serializer.Deserialize reader // For backwards compatibility, convert the serialized one-based positions to zero-based positions. Range.Create - (Position.Create (start.Line - 1) (start.Column - 1)) - (Position.Create (end'.Line - 1) (end'.Column - 1)) + (Position.Create(start.Line - 1) (start.Column - 1)) + (Position.Create(end'.Line - 1) (end'.Column - 1)) override this.WriteJson(writer: JsonWriter, range: Range, serializer: JsonSerializer) = // For backwards compatibility, convert the zero-based positions to one-based serialized positions. @@ -58,11 +58,14 @@ type QsNullableLocationConverter(?ignoreSerializationException) = inherit JsonConverter>() let ignoreSerializationException = defaultArg ignoreSerializationException false - override this.ReadJson(reader: JsonReader, - objectType: Type, - existingValue: QsNullable, - hasExistingValue: bool, - serializer: JsonSerializer) = + override this.ReadJson + ( + reader: JsonReader, + objectType: Type, + existingValue: QsNullable, + hasExistingValue: bool, + serializer: JsonSerializer + ) = try if reader.ValueType <> typeof || (string) reader.Value <> "Null" then let token = JObject.Load(reader) @@ -109,18 +112,19 @@ type ResolvedCharacteristicsConverter(?ignoreSerializationException) = let ignoreSerializationException = defaultArg ignoreSerializationException false /// Returns an invalid expression if the deserialization fails and ignoreSerializationException was set to true upon initialization - override this.ReadJson(reader: JsonReader, - objectType: Type, - existingValue: ResolvedCharacteristics, - hasExistingValue: bool, - serializer: JsonSerializer) = + override this.ReadJson + ( + reader: JsonReader, + objectType: Type, + existingValue: ResolvedCharacteristics, + hasExistingValue: bool, + serializer: JsonSerializer + ) = try serializer.Deserialize>(reader) |> ResolvedCharacteristics.New with :? JsonSerializationException as ex -> - if ignoreSerializationException - then ResolvedCharacteristics.New InvalidSetExpr - else raise ex + if ignoreSerializationException then ResolvedCharacteristics.New InvalidSetExpr else raise ex override this.WriteJson(writer: JsonWriter, value: ResolvedCharacteristics, serializer: JsonSerializer) = serializer.Serialize(writer, value.Expression) @@ -129,11 +133,14 @@ type ResolvedCharacteristicsConverter(?ignoreSerializationException) = type ResolvedInitializerConverter() = inherit JsonConverter() - override this.ReadJson(reader: JsonReader, - objectType: Type, - existingValue: ResolvedInitializer, - hasExistingValue: bool, - serializer: JsonSerializer) = + override this.ReadJson + ( + reader: JsonReader, + objectType: Type, + existingValue: ResolvedInitializer, + hasExistingValue: bool, + serializer: JsonSerializer + ) = serializer.Deserialize>(reader) |> ResolvedInitializer.New @@ -144,11 +151,14 @@ type ResolvedInitializerConverter() = type TypedExpressionConverter() = inherit JsonConverter() - override this.ReadJson(reader: JsonReader, - objectType: Type, - existingValue: TypedExpression, - hasExistingValue: bool, - serializer: JsonSerializer) = + override this.ReadJson + ( + reader: JsonReader, + objectType: Type, + existingValue: TypedExpression, + hasExistingValue: bool, + serializer: JsonSerializer + ) = let (ex, paramRes, t, info, range) = serializer.Deserialize * IEnumerable * ResolvedType * InferredExpressionInformation * QsNullable> reader @@ -162,8 +172,10 @@ type TypedExpressionConverter() = } override this.WriteJson(writer: JsonWriter, value: TypedExpression, serializer: JsonSerializer) = - serializer.Serialize - (writer, (value.Expression, value.TypeArguments, value.ResolvedType, value.InferredInformation, value.Range)) + serializer.Serialize( + writer, + (value.Expression, value.TypeArguments, value.ResolvedType, value.InferredInformation, value.Range) + ) /// @@ -366,11 +378,14 @@ type private QsCustomTypeConverter() = type QsNamespaceConverter() = inherit JsonConverter() - override this.ReadJson(reader: JsonReader, - objectType: Type, - existingValue: QsNamespace, - hasExistingValue: bool, - serializer: JsonSerializer) = + override this.ReadJson + ( + reader: JsonReader, + objectType: Type, + existingValue: QsNamespace, + hasExistingValue: bool, + serializer: JsonSerializer + ) = let (nsName, elements) = serializer.Deserialize>(reader) { @@ -390,16 +405,17 @@ type DictionaryAsArrayResolver() = let isDictionary (t: Type) = t = typedefof> || (t.IsGenericType - && t.GetGenericTypeDefinition() = typeof>.GetGenericTypeDefinition()) + && t.GetGenericTypeDefinition() = typeof>.GetGenericTypeDefinition ()) - if objectType.GetInterfaces().Any(new Func<_, _>(isDictionary)) - then base.CreateArrayContract(objectType) :> JsonContract - else base.CreateContract(objectType) + if objectType.GetInterfaces().Any(new Func<_, _>(isDictionary)) then + base.CreateArrayContract(objectType) :> JsonContract + else + base.CreateContract(objectType) module Json = - let Converters ignoreSerializationException: JsonConverter [] = + let Converters ignoreSerializationException : JsonConverter [] = [| PositionConverter() RangeConverter() diff --git a/src/QsCompiler/DataStructures/SyntaxTokens.fs b/src/QsCompiler/DataStructures/SyntaxTokens.fs index 50d68145dc..8d93f293d4 100644 --- a/src/QsCompiler/DataStructures/SyntaxTokens.fs +++ b/src/QsCompiler/DataStructures/SyntaxTokens.fs @@ -289,21 +289,21 @@ type CallableDeclaration = signature: CallableSignature } - static member Create(name, access, signature) = - { - name = name - access = access - signature = signature - } + static member Create(name, access, signature) = + { + name = name + access = access + signature = signature + } - /// The name of the callable. - member callable.Name = callable.name + /// The name of the callable. + member callable.Name = callable.name - /// The accessibility of the callable, or Null if the callable has the default accessibility. - member callable.Access = callable.access + /// The accessibility of the callable, or Null if the callable has the default accessibility. + member callable.Access = callable.access - /// The signature of the callable. - member callable.Signature = callable.signature + /// The signature of the callable. + member callable.Signature = callable.signature /// A type definition. type TypeDefinition = @@ -314,21 +314,21 @@ type TypeDefinition = underlyingType: (QsSymbol * QsType) QsTuple } - static member Create(name, access, underlyingType) = - { - name = name - access = access - underlyingType = underlyingType - } + static member Create(name, access, underlyingType) = + { + name = name + access = access + underlyingType = underlyingType + } - /// The name of the type. - member typeDef.Name = typeDef.name + /// The name of the type. + member typeDef.Name = typeDef.name - /// The accessibility of the type, or Null if the type has the default accessibility. - member typeDef.Access = typeDef.access + /// The accessibility of the type, or Null if the type has the default accessibility. + member typeDef.Access = typeDef.access - /// The type's underlying type. - member typeDef.UnderlyingType = typeDef.underlyingType + /// The type's underlying type. + member typeDef.UnderlyingType = typeDef.underlyingType type QsFragmentKind = | ExpressionStatement of QsExpression diff --git a/src/QsCompiler/DataStructures/SyntaxTree.fs b/src/QsCompiler/DataStructures/SyntaxTree.fs index 91d356a6ae..87cf45767e 100644 --- a/src/QsCompiler/DataStructures/SyntaxTree.fs +++ b/src/QsCompiler/DataStructures/SyntaxTree.fs @@ -71,7 +71,8 @@ type QsQualifiedName = /// the declared name of the namespace element Name: string } - override this.ToString() = sprintf "%s.%s" this.Namespace this.Name + override this.ToString() = + sprintf "%s.%s" this.Namespace this.Name type SymbolTuple = @@ -153,9 +154,12 @@ type QsTypeParameter = /// /// Returns a copy of this with updated fields. /// - member param.With([] ?origin, - [] ?typeName, - [] ?range) = + member param.With + ( + [] ?origin, + [] ?typeName, + [] ?range + ) = { param with Origin = defaultArg origin param.Origin TypeName = defaultArg typeName param.TypeName @@ -209,9 +213,12 @@ type UserDefinedType = /// /// Returns a copy of this with updated fields. /// - member udt.With([] ?ns, - [] ?name, - [] ?range) = + member udt.With + ( + [] ?ns, + [] ?name, + [] ?range + ) = { udt with Namespace = defaultArg ns udt.Namespace Name = defaultArg name udt.Name @@ -239,132 +246,132 @@ type ResolvedCharacteristics = _Characteristics: CharacteristicsKind } - static member Empty = EmptySet |> ResolvedCharacteristics.New + static member Empty = EmptySet |> ResolvedCharacteristics.New - member this.AreInvalid = - match this._Characteristics with - | InvalidSetExpr -> true + member this.AreInvalid = + match this._Characteristics with + | InvalidSetExpr -> true + | _ -> false + + /// Contains the fully resolved characteristics used to describe the properties of a Q# callable. + /// By construction never contains an empty or invalid set as inner expressions, + /// and necessarily contains the property "Adjointable" if it contains the property "SelfAdjoint". + member this.Expression = this._Characteristics + + /// Extracts all properties of a callable with the given characteristics using the given function to access the characteristics kind. + /// Returns the extracted properties as Some if the extraction succeeds. + /// Returns None if the properties cannot be determined either because the characteristics expression contains unresolved parameters or the expression is invalid. + static member internal ExtractProperties(getKind: _ -> CharacteristicsKind<_>) = + let rec yieldProperties ex = + match getKind ex with + | EmptySet -> Seq.empty |> Some + | SimpleSet property -> seq { yield property } |> Some + | Union (s1, s2) -> + Option.map2 (fun (x: _ seq) y -> x.Concat y) (s1 |> yieldProperties) (s2 |> yieldProperties) + | Intersection (s1, s2) -> + Option.map2 (fun (x: _ seq) y -> x.Intersect y) (s1 |> yieldProperties) (s2 |> yieldProperties) + | InvalidSetExpr -> None + + yieldProperties + + /// Returns a new characteristics expression that is the union of all properties, if the properties of the given characteristics can be determined. + /// Returns the given characteristics expression unchanged otherwise. + static member private Simplify(ex: ResolvedCharacteristics) = + let uniqueProps = + ex + |> ResolvedCharacteristics.ExtractProperties(fun a -> a._Characteristics) + |> Option.map (Seq.distinct >> Seq.toList) + // it is fine (and necessary) to directly reassemble the unions, + // since all property dependencies will already be satisfied (having been extracted from a ResolvedCharacteristics) + let rec addProperties (current: ResolvedCharacteristics) = + function + | head :: tail -> + tail |> addProperties { _Characteristics = Union(current, { _Characteristics = SimpleSet head }) } + | _ -> current + + match uniqueProps with + | Some (head :: tail) -> tail |> addProperties { _Characteristics = SimpleSet head } + | _ -> ex + + /// Builds a ResolvedCharacteristics based on a compatible characteristics kind, and replaces the (inaccessible) record constructor. + /// Returns an invalid expression if the properties for the built characteristics cannot be determined even after all parameters are known. + /// Incorporates all empty sets such that they do not ever occur as part of an encompassing expression. + static member New kind = + let isEmpty (ex: ResolvedCharacteristics) = + match ex._Characteristics with + | EmptySet -> true | _ -> false - /// Contains the fully resolved characteristics used to describe the properties of a Q# callable. - /// By construction never contains an empty or invalid set as inner expressions, - /// and necessarily contains the property "Adjointable" if it contains the property "SelfAdjoint". - member this.Expression = this._Characteristics - - /// Extracts all properties of a callable with the given characteristics using the given function to access the characteristics kind. - /// Returns the extracted properties as Some if the extraction succeeds. - /// Returns None if the properties cannot be determined either because the characteristics expression contains unresolved parameters or the expression is invalid. - static member internal ExtractProperties(getKind: _ -> CharacteristicsKind<_>) = - let rec yieldProperties ex = - match getKind ex with - | EmptySet -> Seq.empty |> Some - | SimpleSet property -> seq { yield property } |> Some - | Union (s1, s2) -> - Option.map2 (fun (x: _ seq) y -> x.Concat y) (s1 |> yieldProperties) (s2 |> yieldProperties) - | Intersection (s1, s2) -> - Option.map2 (fun (x: _ seq) y -> x.Intersect y) (s1 |> yieldProperties) (s2 |> yieldProperties) - | InvalidSetExpr -> None - - yieldProperties - - /// Returns a new characteristics expression that is the union of all properties, if the properties of the given characteristics can be determined. - /// Returns the given characteristics expression unchanged otherwise. - static member private Simplify(ex: ResolvedCharacteristics) = - let uniqueProps = - ex - |> ResolvedCharacteristics.ExtractProperties(fun a -> a._Characteristics) - |> Option.map (Seq.distinct >> Seq.toList) - // it is fine (and necessary) to directly reassemble the unions, - // since all property dependencies will already be satisfied (having been extracted from a ResolvedCharacteristics) - let rec addProperties (current: ResolvedCharacteristics) = - function - | head :: tail -> - tail |> addProperties { _Characteristics = Union(current, { _Characteristics = SimpleSet head }) } - | _ -> current - - match uniqueProps with - | Some (head :: tail) -> tail |> addProperties { _Characteristics = SimpleSet head } - | _ -> ex - - /// Builds a ResolvedCharacteristics based on a compatible characteristics kind, and replaces the (inaccessible) record constructor. - /// Returns an invalid expression if the properties for the built characteristics cannot be determined even after all parameters are known. - /// Incorporates all empty sets such that they do not ever occur as part of an encompassing expression. - static member New kind = - let isEmpty (ex: ResolvedCharacteristics) = - match ex._Characteristics with - | EmptySet -> true - | _ -> false - - match kind with - | EmptySet -> { _Characteristics = EmptySet } - | SimpleSet property -> { _Characteristics = SimpleSet property } - | Union (s1, s2) when s1 |> isEmpty -> s2 - | Union (s1, s2) when s2 |> isEmpty -> s1 - | Union (s1, s2) when s1.AreInvalid || s2.AreInvalid -> { _Characteristics = InvalidSetExpr } - | Union (s1, s2) -> { _Characteristics = Union(s1, s2) } |> ResolvedCharacteristics.Simplify - | Intersection (s1, s2) when s1 |> isEmpty || s2 |> isEmpty -> { _Characteristics = EmptySet } - | Intersection (s1, s2) when s1.AreInvalid || s2.AreInvalid -> { _Characteristics = InvalidSetExpr } - | Intersection (s1, s2) -> { _Characteristics = Intersection(s1, s2) } |> ResolvedCharacteristics.Simplify - | InvalidSetExpr -> { _Characteristics = InvalidSetExpr } + match kind with + | EmptySet -> { _Characteristics = EmptySet } + | SimpleSet property -> { _Characteristics = SimpleSet property } + | Union (s1, s2) when s1 |> isEmpty -> s2 + | Union (s1, s2) when s2 |> isEmpty -> s1 + | Union (s1, s2) when s1.AreInvalid || s2.AreInvalid -> { _Characteristics = InvalidSetExpr } + | Union (s1, s2) -> { _Characteristics = Union(s1, s2) } |> ResolvedCharacteristics.Simplify + | Intersection (s1, s2) when s1 |> isEmpty || s2 |> isEmpty -> { _Characteristics = EmptySet } + | Intersection (s1, s2) when s1.AreInvalid || s2.AreInvalid -> { _Characteristics = InvalidSetExpr } + | Intersection (s1, s2) -> { _Characteristics = Intersection(s1, s2) } |> ResolvedCharacteristics.Simplify + | InvalidSetExpr -> { _Characteristics = InvalidSetExpr } - /// - /// Given the resolved characteristics of a set of specializations, - /// determines and returns the minimal characteristics of any one of the specializations. - /// - /// is empty. - static member internal Common(characteristics: ResolvedCharacteristics list) = - let rec common current = - function - | [] -> current - | head :: tail -> - // todo: if we support parameterizing over characteristics, we need to replace them in head by their worst-case value - tail |> common { _Characteristics = Intersection(current, head) } - - if characteristics |> List.exists (fun a -> a._Characteristics = EmptySet) then - { _Characteristics = EmptySet } - elif characteristics |> List.exists (fun a -> a.AreInvalid) then - { _Characteristics = InvalidSetExpr } - else - match characteristics with - | [] -> ArgumentException "cannot determine common information for an empty sequence" |> raise - | head :: tail -> common head tail |> ResolvedCharacteristics.Simplify - - /// Builds a ResolvedCharacteristics that represents the given transformation properties. - static member FromProperties props = - let addProperty prop a = - { _Characteristics = Union(a, SimpleSet prop |> ResolvedCharacteristics.New) } - - let rec addProperties (current: ResolvedCharacteristics) = - function - | head :: tail -> addProperties (current |> addProperty head) tail - | _ -> current - - match props |> Seq.distinct |> Seq.toList with - | [] -> EmptySet |> ResolvedCharacteristics.New - | head :: tail -> tail |> addProperties (SimpleSet head |> ResolvedCharacteristics.New) + /// + /// Given the resolved characteristics of a set of specializations, + /// determines and returns the minimal characteristics of any one of the specializations. + /// + /// is empty. + static member internal Common(characteristics: ResolvedCharacteristics list) = + let rec common current = + function + | [] -> current + | head :: tail -> + // todo: if we support parameterizing over characteristics, we need to replace them in head by their worst-case value + tail |> common { _Characteristics = Intersection(current, head) } + + if characteristics |> List.exists (fun a -> a._Characteristics = EmptySet) then + { _Characteristics = EmptySet } + elif characteristics |> List.exists (fun a -> a.AreInvalid) then + { _Characteristics = InvalidSetExpr } + else + match characteristics with + | [] -> ArgumentException "cannot determine common information for an empty sequence" |> raise + | head :: tail -> common head tail |> ResolvedCharacteristics.Simplify + + /// Builds a ResolvedCharacteristics that represents the given transformation properties. + static member FromProperties props = + let addProperty prop a = + { _Characteristics = Union(a, SimpleSet prop |> ResolvedCharacteristics.New) } + + let rec addProperties (current: ResolvedCharacteristics) = + function + | head :: tail -> addProperties (current |> addProperty head) tail + | _ -> current + + match props |> Seq.distinct |> Seq.toList with + | [] -> EmptySet |> ResolvedCharacteristics.New + | head :: tail -> tail |> addProperties (SimpleSet head |> ResolvedCharacteristics.New) - /// - /// Determines which properties are supported by a callable with the given characteristics and returns them. - /// - /// - /// The properties cannot be determined either because the characteristics expression contains unresolved parameters or is invalid. - /// - member this.GetProperties() = - match ResolvedCharacteristics.ExtractProperties (fun ex -> ex._Characteristics) this with - | Some props -> props.ToImmutableHashSet() - | None -> InvalidOperationException "properties cannot be determined" |> raise - - /// Determines which functors are supported by a callable with the given characteristics and returns them as a Value. - /// Returns Null if the supported functors cannot be determined either because the characteristics expression contains unresolved parameters or is invalid. - member this.SupportedFunctors = - let getFunctor = - function - | Adjointable -> Some Adjoint - | Controllable -> Some Controlled - - match ResolvedCharacteristics.ExtractProperties (fun ex -> ex._Characteristics) this with - | Some props -> (props |> Seq.choose getFunctor).ToImmutableHashSet() |> Value - | None -> Null + /// + /// Determines which properties are supported by a callable with the given characteristics and returns them. + /// + /// + /// The properties cannot be determined either because the characteristics expression contains unresolved parameters or is invalid. + /// + member this.GetProperties() = + match ResolvedCharacteristics.ExtractProperties(fun ex -> ex._Characteristics) this with + | Some props -> props.ToImmutableHashSet() + | None -> InvalidOperationException "properties cannot be determined" |> raise + + /// Determines which functors are supported by a callable with the given characteristics and returns them as a Value. + /// Returns Null if the supported functors cannot be determined either because the characteristics expression contains unresolved parameters or is invalid. + member this.SupportedFunctors = + let getFunctor = + function + | Adjointable -> Some Adjoint + | Controllable -> Some Controlled + + match ResolvedCharacteristics.ExtractProperties(fun ex -> ex._Characteristics) this with + | Some props -> (props |> Seq.choose getFunctor).ToImmutableHashSet() |> Value + | None -> Null /// used to represent information on Q# operations and expressions thereof generated and/or tracked during compilation @@ -477,29 +484,29 @@ type ResolvedType = range: TypeRange } - interface ITuple - - interface IComparable with - member this.CompareTo that = - match that with - | :? ResolvedType as that -> compare this.kind that.kind - | _ -> ArgumentException "Types are different." |> raise + interface ITuple - override this.Equals that = + interface IComparable with + member this.CompareTo that = match that with - | :? ResolvedType as that -> this.kind = that.kind - | _ -> false + | :? ResolvedType as that -> compare this.kind that.kind + | _ -> ArgumentException "Types are different." |> raise - override this.GetHashCode() = hash this.kind + override this.Equals that = + match that with + | :? ResolvedType as that -> this.kind = that.kind + | _ -> false - /// Contains the fully resolved Q# type, - /// where type parameters are represented as QsTypeParameters containing their origin (the namespace and the callable they belong to) and their name, - /// and user defined types are resolved to their fully qualified name. - /// By construction never contains any arity-0 or arity-1 tuple types. - member this.Resolution = this.kind + override this.GetHashCode() = hash this.kind - /// The source code range where this type originated. Range is ignored when comparing resolved types. - member this.Range = this.range + /// Contains the fully resolved Q# type, + /// where type parameters are represented as QsTypeParameters containing their origin (the namespace and the callable they belong to) and their name, + /// and user defined types are resolved to their fully qualified name. + /// By construction never contains any arity-0 or arity-1 tuple types. + member this.Resolution = this.kind + + /// The source code range where this type originated. Range is ignored when comparing resolved types. + member this.Range = this.range module ResolvedType = /// @@ -643,14 +650,14 @@ type ResolvedInitializer = resolvedType: ResolvedType } - interface ITuple + interface ITuple - /// Contains the fully resolved Q# initializer. - /// By construction never contains any arity-0 or arity-1 tuple types. - member this.Resolution = this.kind + /// Contains the fully resolved Q# initializer. + /// By construction never contains any arity-0 or arity-1 tuple types. + member this.Resolution = this.kind - /// the fully resolved Q# type of the initializer. - member this.Type = this.resolvedType + /// the fully resolved Q# type of the initializer. + member this.Type = this.resolvedType module ResolvedInitializer = let create range kind = @@ -897,8 +904,11 @@ type Source with /// Returns a copy of this source with the given or if /// provided. /// - member source.With([] ?codeFile, - [] ?assemblyFile) = + member source.With + ( + [] ?codeFile, + [] ?assemblyFile + ) = { source with CodeFile = codeFile |> Option.defaultValue source.CodeFile AssemblyFile = assemblyFile |> QsNullable.ofOption |> QsNullable.orElse source.AssemblyFile diff --git a/src/QsCompiler/Optimizations/OptimizingTransformations/CallableInlining.fs b/src/QsCompiler/Optimizations/OptimizingTransformations/CallableInlining.fs index 74fe131924..f6e2a94db0 100644 --- a/src/QsCompiler/Optimizations/OptimizingTransformations/CallableInlining.fs +++ b/src/QsCompiler/Optimizations/OptimizingTransformations/CallableInlining.fs @@ -147,13 +147,15 @@ and private CallableInliningStatements(parent: CallableInlining, callables: Immu /// then findAllCalls f will include both g and h (and possibly other callables). /// Mutates the given HashSet by adding all the found callables to the set. /// Is used to prevent inlining recursive functions into themselves forever. - let rec findAllCalls (callables: ImmutableDictionary) - (scope: QsScope) - (found: HashSet) - : unit = + let rec findAllCalls + (callables: ImmutableDictionary) + (scope: QsScope) + (found: HashSet) + : unit = scope |> findAllSubStatements - |> Seq.iter (function + |> Seq.iter + (function | QsExpressionStatement ex -> match InliningInfo.TryGetInfo callables ex with | Some ii -> diff --git a/src/QsCompiler/Optimizations/OptimizingTransformations/ConstantPropagation.fs b/src/QsCompiler/Optimizations/OptimizingTransformations/ConstantPropagation.fs index 4f3d74a4ec..3884eaef21 100644 --- a/src/QsCompiler/Optimizations/OptimizingTransformations/ConstantPropagation.fs +++ b/src/QsCompiler/Optimizations/OptimizingTransformations/ConstantPropagation.fs @@ -57,8 +57,8 @@ and private ConstantPropagationStatementKinds(parent: ConstantPropagation, calla | RangeLiteral _ | SizedArray _ | NewArray _ -> true - | CallLikeExpression ({ Expression = Identifier (GlobalCallable name, _) }, _) when callables.[name] - .Kind = TypeConstructor -> true + | CallLikeExpression ({ Expression = Identifier (GlobalCallable name, _) }, _) when + callables.[name].Kind = TypeConstructor -> true | _ when TypedExpression.IsPartialApplication ex.Expression -> true | UnitValue | IntLiteral _ @@ -105,21 +105,23 @@ and private ConstantPropagationStatementKinds(parent: ConstantPropagation, calla let lhs = so.OnSymbolTuple stm.Lhs let rhs = so.Expressions.OnTypedExpression stm.Rhs - if stm.Kind = ImmutableBinding - then defineVarTuple (shouldPropagate callables) parent.Constants (lhs, rhs) + if stm.Kind = ImmutableBinding then + defineVarTuple (shouldPropagate callables) parent.Constants (lhs, rhs) QsBinding.New stm.Kind (lhs, rhs) |> QsVariableDeclaration override this.OnConditionalStatement stm = let cbList, cbListEnd = stm.ConditionalBlocks - |> Seq.fold (fun s (cond, block) -> - let newCond = this.Expressions.OnTypedExpression cond - - match newCond.Expression with - | BoolLiteral true -> s @ [ Null, block ] - | BoolLiteral false -> s - | _ -> s @ [ Value cond, block ]) [] + |> Seq.fold + (fun s (cond, block) -> + let newCond = this.Expressions.OnTypedExpression cond + + match newCond.Expression with + | BoolLiteral true -> s @ [ Null, block ] + | BoolLiteral false -> s + | _ -> s @ [ Value cond, block ]) + [] |> List.ofSeq |> takeWhilePlus1 (fun (c, _) -> c <> Null) @@ -146,20 +148,21 @@ and private ConstantPropagationStatementKinds(parent: ConstantPropagation, calla let rhs = this.OnQubitInitializer stm.Binding.Rhs jointFlatten (lhs, rhs) - |> Seq.iter (fun (l, r) -> - match l, r.Resolution with - | VariableName name, QubitRegisterAllocation { Expression = IntLiteral num } -> - let arrayIden = Identifier(LocalVariable name, Null) |> wrapExpr (ArrayType(ResolvedType.New Qubit)) - let elemI = fun i -> ArrayItem(arrayIden, IntLiteral(int64 i) |> wrapExpr Int) - - let expr = - Seq.init (safeCastInt64 num) (elemI >> wrapExpr Qubit) - |> ImmutableArray.CreateRange - |> ValueArray - |> wrapExpr (ArrayType(ResolvedType.New Qubit)) - - defineVar (fun _ -> true) parent.Constants (name, expr) - | _ -> ()) + |> Seq.iter + (fun (l, r) -> + match l, r.Resolution with + | VariableName name, QubitRegisterAllocation { Expression = IntLiteral num } -> + let arrayIden = Identifier(LocalVariable name, Null) |> wrapExpr (ArrayType(ResolvedType.New Qubit)) + let elemI = fun i -> ArrayItem(arrayIden, IntLiteral(int64 i) |> wrapExpr Int) + + let expr = + Seq.init (safeCastInt64 num) (elemI >> wrapExpr Qubit) + |> ImmutableArray.CreateRange + |> ValueArray + |> wrapExpr (ArrayType(ResolvedType.New Qubit)) + + defineVar (fun _ -> true) parent.Constants (name, expr) + | _ -> ()) let body = this.Statements.OnScope stm.Body QsQubitScope.New kind ((lhs, rhs), body) |> QsQubitScope diff --git a/src/QsCompiler/Optimizations/OptimizingTransformations/LoopUnrolling.fs b/src/QsCompiler/Optimizations/OptimizingTransformations/LoopUnrolling.fs index bb8d69fb69..c6cc54c3ff 100644 --- a/src/QsCompiler/Optimizations/OptimizingTransformations/LoopUnrolling.fs +++ b/src/QsCompiler/Optimizations/OptimizingTransformations/LoopUnrolling.fs @@ -52,10 +52,13 @@ and private LoopUnrollingStatementKinds(parent: LoopUnrolling, callables, maxSiz let iterRange = iterValsList - |> List.map (fun x -> - let variableDecl = QsBinding.New ImmutableBinding (loopVar, x) |> QsVariableDeclaration |> wrapStmt - let innerScope = { stm.Body with Statements = stm.Body.Statements.Insert(0, variableDecl) } - innerScope |> newScopeStatement |> wrapStmt) + |> List.map + (fun x -> + let variableDecl = + QsBinding.New ImmutableBinding (loopVar, x) |> QsVariableDeclaration |> wrapStmt + + let innerScope = { stm.Body with Statements = stm.Body.Statements.Insert(0, variableDecl) } + innerScope |> newScopeStatement |> wrapStmt) let outerScope = QsScope.New(iterRange, stm.Body.KnownSymbols) return outerScope |> newScopeStatement |> this.OnStatementKind diff --git a/src/QsCompiler/Optimizations/OptimizingTransformations/StatementRemoving.fs b/src/QsCompiler/Optimizations/OptimizingTransformations/StatementRemoving.fs index 8a63a703a5..fab6fc1fd4 100644 --- a/src/QsCompiler/Optimizations/OptimizingTransformations/StatementRemoving.fs +++ b/src/QsCompiler/Optimizations/OptimizingTransformations/StatementRemoving.fs @@ -53,25 +53,28 @@ and private VariableRemovalStatements(parent: StatementRemoval, removeFunctions) let myList = jointFlatten (s.Binding.Lhs, s.Binding.Rhs) - |> Seq.collect (fun (l, r) -> - match l, r.Resolution with - | VariableName name, QubitRegisterAllocation { Expression = IntLiteral num } -> - let elemI = fun i -> Identifier(LocalVariable(sprintf "__qsItem%d__%s__" i name), Null) - - let expr = - Seq.init (safeCastInt64 num) (elemI >> wrapExpr Qubit) - |> ImmutableArray.CreateRange - |> ValueArray - |> wrapExpr (ArrayType(ResolvedType.New Qubit)) - - let newStmt = QsVariableDeclaration(QsBinding.New QsBindingKind.ImmutableBinding (l, expr)) - newStatements <- wrapStmt newStmt :: newStatements - - Seq.init (safeCastInt64 num) (fun i -> - VariableName(sprintf "__qsItem%d__%s__" i name), - ResolvedInitializer.New SingleQubitAllocation) - | DiscardedItem, _ -> Seq.empty - | _ -> Seq.singleton (l, r)) + |> Seq.collect + (fun (l, r) -> + match l, r.Resolution with + | VariableName name, QubitRegisterAllocation { Expression = IntLiteral num } -> + let elemI = fun i -> Identifier(LocalVariable(sprintf "__qsItem%d__%s__" i name), Null) + + let expr = + Seq.init (safeCastInt64 num) (elemI >> wrapExpr Qubit) + |> ImmutableArray.CreateRange + |> ValueArray + |> wrapExpr (ArrayType(ResolvedType.New Qubit)) + + let newStmt = QsVariableDeclaration(QsBinding.New QsBindingKind.ImmutableBinding (l, expr)) + newStatements <- wrapStmt newStmt :: newStatements + + Seq.init + (safeCastInt64 num) + (fun i -> + VariableName(sprintf "__qsItem%d__%s__" i name), + ResolvedInitializer.New SingleQubitAllocation) + | DiscardedItem, _ -> Seq.empty + | _ -> Seq.singleton (l, r)) |> List.ofSeq match myList with @@ -88,8 +91,9 @@ and private VariableRemovalStatements(parent: StatementRemoval, removeFunctions) let newBody = QsScope.New(s.Body.Statements.InsertRange(0, newStatements), s.Body.KnownSymbols) QsQubitScope.New s.Kind ((lhs, rhs), newBody) |> QsQubitScope |> Seq.singleton | ScopeStatement s -> s.Body.Statements |> Seq.map (fun x -> x.Statement) - | _ when not c.HasQuantum - && c2.ExternalMutations.IsEmpty - && not c.HasInterrupts - && (not c.HasOutput || removeFunctions) -> Seq.empty + | _ when + not c.HasQuantum + && c2.ExternalMutations.IsEmpty + && not c.HasInterrupts + && (not c.HasOutput || removeFunctions) -> Seq.empty | a -> Seq.singleton a diff --git a/src/QsCompiler/Optimizations/OptimizingTransformations/TransformationBase.fs b/src/QsCompiler/Optimizations/OptimizingTransformations/TransformationBase.fs index e334f96e12..dcd52826b2 100644 --- a/src/QsCompiler/Optimizations/OptimizingTransformations/TransformationBase.fs +++ b/src/QsCompiler/Optimizations/OptimizingTransformations/TransformationBase.fs @@ -34,7 +34,6 @@ and private NamespaceTransformationBase(parent: TransformationBase) = override this.OnNamespace x = let newX = base.OnNamespace x - if (x.Elements, x.Name) <> (newX.Elements, newX.Name) - then parent.Changed <- true + if (x.Elements, x.Name) <> (newX.Elements, newX.Name) then parent.Changed <- true newX diff --git a/src/QsCompiler/Optimizations/PreEvaluation.fs b/src/QsCompiler/Optimizations/PreEvaluation.fs index 60c9b17abf..3959801e3d 100644 --- a/src/QsCompiler/Optimizations/PreEvaluation.fs +++ b/src/QsCompiler/Optimizations/PreEvaluation.fs @@ -22,9 +22,10 @@ type PreEvaluation = /// function that takes as input such a dictionary of callables. /// /// Disclaimer: This is an experimental feature. - static member WithScript (script: Func, TransformationBase seq>) - (arg: QsCompilation) - = + static member WithScript + (script: Func, TransformationBase seq>) + (arg: QsCompilation) + = // TODO: this should actually only evaluate everything for each entry point let rec evaluate (tree: _ list) = @@ -38,27 +39,25 @@ type PreEvaluation = for opt in optimizers do tree <- List.map opt.Namespaces.OnNamespace tree - if optimizers |> List.exists (fun opt -> opt.CheckChanged()) - then evaluate tree - else tree + if optimizers |> List.exists (fun opt -> opt.CheckChanged()) then evaluate tree else tree let namespaces = arg.Namespaces |> Seq.map StripPositionInfo.Apply |> List.ofSeq |> evaluate QsCompilation.New(namespaces.ToImmutableArray(), arg.EntryPoints) /// Default sequence of optimizing transformations - static member DefaultScript removeFunctions maxSize: Func<_, TransformationBase seq> = + static member DefaultScript removeFunctions maxSize : Func<_, TransformationBase seq> = new Func<_, _>(fun callables -> - seq { - VariableRemoval() - StatementRemoval(removeFunctions) - ConstantPropagation(callables) - LoopUnrolling(callables, maxSize) - CallableInlining(callables) - StatementGrouping() - PureCircuitFinder(callables) - }) + seq { + VariableRemoval() + StatementRemoval(removeFunctions) + ConstantPropagation(callables) + LoopUnrolling(callables, maxSize) + CallableInlining(callables) + StatementGrouping() + PureCircuitFinder(callables) + }) /// Attempts to pre-evaluate the given sequence of namespaces /// as much as possible with a default optimization script static member All(arg: QsCompilation) = - PreEvaluation.WithScript (PreEvaluation.DefaultScript false 40) arg + PreEvaluation.WithScript(PreEvaluation.DefaultScript false 40) arg diff --git a/src/QsCompiler/Optimizations/PureCircuitAPI.fs b/src/QsCompiler/Optimizations/PureCircuitAPI.fs index 5870ee7a69..9305aa7d27 100644 --- a/src/QsCompiler/Optimizations/PureCircuitAPI.fs +++ b/src/QsCompiler/Optimizations/PureCircuitAPI.fs @@ -57,7 +57,7 @@ type private CircuitContext = /// Converts a TypedExpression to an Expression -let rec private toExpression (cc: CircuitContext, expr: TypedExpression): (CircuitContext * Expression) option = +let rec private toExpression (cc: CircuitContext, expr: TypedExpression) : (CircuitContext * Expression) option = let someLiteral a = Some(cc, Literal a) let typeIsArray k = @@ -67,8 +67,7 @@ let rec private toExpression (cc: CircuitContext, expr: TypedExpression): (Circu let existing = Seq.indexed l |> Seq.tryPick (fun (i, ex) -> if expr = ex then Some(l, i) else None) let newList, index = existing |? (l.Add expr, l.Length) - if index > (1 <<< 29) - then ArgumentException "Trying to create too large of a circuit" |> raise + if index > (1 <<< 29) then ArgumentException "Trying to create too large of a circuit" |> raise newList, index @@ -102,15 +101,23 @@ let rec private toExpression (cc: CircuitContext, expr: TypedExpression): (Circu | ExprKind.PauliLiteral x -> PauliLiteral x |> someLiteral | ExprKind.ValueTuple x -> recurse cc x Some Tuple | ExprKind.ValueArray x when typeIsArray TypeKind.Pauli -> - recurse cc x (function + recurse + cc + x + (function | Literal (PauliLiteral p) -> Some p - | _ -> None) (PauliArray >> Literal) + | _ -> None) + (PauliArray >> Literal) | ExprKind.ValueArray x when typeIsArray TypeKind.Qubit -> - recurse cc x (function + recurse + cc + x + (function | Qubit i -> Some i - | _ -> None) QubitArray - | ExprKind.Identifier (LocalVariable name, _) when expr.ResolvedType.Resolution = TypeKind.Qubit - && cc.distinctNames.Contains name -> + | _ -> None) + QubitArray + | ExprKind.Identifier (LocalVariable name, _) when + expr.ResolvedType.Resolution = TypeKind.Qubit && cc.distinctNames.Contains name -> let newQubits, i = ensureMatchingIndex cc.qubits Some({ cc with qubits = newQubits }, Qubit i) | _ when mightContainQubit expr.ResolvedType.Resolution -> None @@ -119,8 +126,8 @@ let rec private toExpression (cc: CircuitContext, expr: TypedExpression): (Circu Some({ cc with unknownValues = newUnknownValues }, UnknownValue i) /// Converts a TypedExpression to a GateCall -let private toGateCall (cc: CircuitContext, expr: TypedExpression): (CircuitContext * GateCall) option = - let rec helper cc method arg: (CircuitContext * GateCall) option = +let private toGateCall (cc: CircuitContext, expr: TypedExpression) : (CircuitContext * GateCall) option = + let rec helper cc method arg : (CircuitContext * GateCall) option = maybe { match method.Expression with | AdjointApplication x -> @@ -162,7 +169,7 @@ let private toGateCall (cc: CircuitContext, expr: TypedExpression): (CircuitCont /// Converts a list of TypedExpressions to a Circuit, CircuitContext pair. /// Returns None if the given expression list cannot be converted to a pure circuit. -let private toCircuit callables distinctNames exprList: (Circuit * CircuitContext) option = +let private toCircuit callables distinctNames exprList : (Circuit * CircuitContext) option = maybe { let ccRef = ref @@ -192,7 +199,7 @@ let private toCircuit callables distinctNames exprList: (Circuit * CircuitContex /// Returns the Q# expression corresponding to the given Expression -let rec private fromExpression (cc: CircuitContext) (expr: Expression): TypedExpression = +let rec private fromExpression (cc: CircuitContext) (expr: Expression) : TypedExpression = let buildArray t x = x |> ImmutableArray.CreateRange |> ExprKind.ValueArray |> wrapExpr (ArrayType(ResolvedType.New t)) @@ -223,7 +230,7 @@ let rec private fromExpression (cc: CircuitContext) (expr: Expression): TypedExp | UnknownValue i -> cc.unknownValues.[i] /// Returns the Q# expression correponding to the given gate call -let private fromGateCall (cc: CircuitContext) (gc: GateCall): TypedExpression = +let private fromGateCall (cc: CircuitContext) (gc: GateCall) : TypedExpression = let mutable arg = fromExpression cc gc.arg let methodType = @@ -231,13 +238,13 @@ let private fromGateCall (cc: CircuitContext) (gc: GateCall): TypedExpression = let mutable method = wrapExpr methodType (Identifier(GlobalCallable gc.gate, Null)) - if gc.adjoint - then method <- wrapExpr methodType (AdjointApplication method) + if gc.adjoint then method <- wrapExpr methodType (AdjointApplication method) if not gc.controls.IsEmpty then let argType = - TupleType - (ImmutableArray.Create(ResolvedType.New(ArrayType(ResolvedType.New TypeKind.Qubit)), arg.ResolvedType)) + TupleType( + ImmutableArray.Create(ResolvedType.New(ArrayType(ResolvedType.New TypeKind.Qubit)), arg.ResolvedType) + ) arg <- wrapExpr argType (ValueTuple(ImmutableArray.Create(fromExpression cc (QubitArray gc.controls), arg))) @@ -254,7 +261,7 @@ let private fromCircuit (cc: CircuitContext) (circuit: Circuit) = /// Given a pure circuit, performs basic optimizations and returns the new circuit -let private optimizeCircuit (circuit: Circuit): Circuit option = +let private optimizeCircuit (circuit: Circuit) : Circuit option = let mutable circuit = circuit let mutable i = 0 diff --git a/src/QsCompiler/Optimizations/Utils/ComputationExpressions.fs b/src/QsCompiler/Optimizations/Utils/ComputationExpressions.fs index 1d139e7a1d..f77e4c46e6 100644 --- a/src/QsCompiler/Optimizations/Utils/ComputationExpressions.fs +++ b/src/QsCompiler/Optimizations/Utils/ComputationExpressions.fs @@ -35,21 +35,22 @@ type internal MaybeBuilder() = compensation () member this.Using(res: #IDisposable, body) = - this.TryFinally - (body res, - (fun () -> - match res with - | null -> () - | disp -> disp.Dispose())) + this.TryFinally( + body res, + (fun () -> + match res with + | null -> () + | disp -> disp.Dispose()) + ) member this.While(guard, f) = - if not (guard ()) - then this.Zero() - else this.Bind(f (), (fun () -> this.While(guard, f))) + if not (guard ()) then this.Zero() else this.Bind(f (), (fun () -> this.While(guard, f))) member this.For(sequence: seq<_>, body) = - this.Using - (sequence.GetEnumerator(), (fun enum -> this.While(enum.MoveNext, this.Delay(fun () -> body enum.Current)))) + this.Using( + sequence.GetEnumerator(), + (fun enum -> this.While(enum.MoveNext, this.Delay(fun () -> body enum.Current))) + ) /// Represents the result of an imperative computation. @@ -73,11 +74,11 @@ type Imperative<'a, 'b, 'c> = ('a -> ImperativeResult<'a, 'b, 'c>) /// A computation expression used to evaluate imperative, stateful code. type internal ImperativeBuilder() = - member this.Return(x: 'b): Imperative<'a, 'b, 'c> = (fun s -> Normal(x, s)) - member this.ReturnFrom(m: Imperative<'a, 'b, 'c>): Imperative<'a, 'b, 'c> = m + member this.Return(x: 'b) : Imperative<'a, 'b, 'c> = (fun s -> Normal(x, s)) + member this.ReturnFrom(m: Imperative<'a, 'b, 'c>) : Imperative<'a, 'b, 'c> = m - member this.Yield(x: 'c): Imperative<'a, 'b, 'c> = (fun _ -> Interrupt x) - member this.YieldFrom(m: Imperative<'a, 'b, 'c>): Imperative<'a, 'b, 'c> = m + member this.Yield(x: 'c) : Imperative<'a, 'b, 'c> = (fun _ -> Interrupt x) + member this.YieldFrom(m: Imperative<'a, 'b, 'c>) : Imperative<'a, 'b, 'c> = m member this.Bind(m: Imperative<'a, 'b, 'c>, f: 'b -> Imperative<'a, 'b2, 'c>) = fun s1 -> @@ -86,7 +87,7 @@ type internal ImperativeBuilder() = | Break s2 -> Break s2 | Interrupt x -> Interrupt x - member this.Zero(): Imperative<'a, Unit, 'c> = (fun s -> Normal((), s)) + member this.Zero() : Imperative<'a, Unit, 'c> = (fun s -> Normal((), s)) member this.Combine(m1: Imperative<'a, Unit, 'c>, m2: Imperative<'a, 'b, 'c>) = fun s1 -> @@ -102,12 +103,12 @@ type internal ImperativeBuilder() = | Break s2 -> Normal((), s2) | Interrupt x -> Interrupt x - member this.Delay(f: Unit -> Imperative<'a, 'b, 'c>): Imperative<'a, 'b, 'c> = f () + member this.Delay(f: Unit -> Imperative<'a, 'b, 'c>) : Imperative<'a, 'b, 'c> = f () member this.While(guard: Unit -> Imperative<'a, bool, 'c>, f: Imperative<'a, Unit, 'c>) = fun s1 -> match guard () s1 with - | Normal (true, s2) -> this.CombineLoopIters (f, this.While(guard, f)) s2 + | Normal (true, s2) -> this.CombineLoopIters(f, this.While(guard, f)) s2 | Normal (false, s2) -> Normal((), s2) | Break _ -> Exception "Cannot break in condition of while loop" |> raise | Interrupt x -> Interrupt x @@ -118,7 +119,7 @@ type internal ImperativeBuilder() = fun s1 -> match sequence with | [] -> Normal((), s1) - | head :: tail -> this.CombineLoopIters (body head, this.For(tail, body)) s1 + | head :: tail -> this.CombineLoopIters(body head, this.For(tail, body)) s1 member this.For(sequence: seq<'d>, body: 'd -> Imperative<'a, Unit, 'c>) = this.For(List.ofSeq sequence, body) @@ -126,11 +127,11 @@ type internal ImperativeBuilder() = let internal imperative = ImperativeBuilder() /// Returns the current state of an imperative computation -let internal getState: Imperative<'a, 'a, 'c> = fun s -> Normal(s, s) +let internal getState : Imperative<'a, 'a, 'c> = fun s -> Normal(s, s) /// Sets the current state of an imperative computation to the given value -let internal putState s: Imperative<'a, Unit, 'c> = fun _ -> Normal((), s) +let internal putState s : Imperative<'a, Unit, 'c> = fun _ -> Normal((), s) /// Updates the current state of an imperative computation using the given function -let internal updateState f: Imperative<'a, Unit, 'c> = fun s -> Normal((), f s) +let internal updateState f : Imperative<'a, Unit, 'c> = fun s -> Normal((), f s) /// The monadic Bind() function as an infix operator let inline internal (>>=) m f = imperative.Bind(m, f) diff --git a/src/QsCompiler/Optimizations/Utils/Evaluation.fs b/src/QsCompiler/Optimizations/Utils/Evaluation.fs index 7d211985d0..284401bd1b 100644 --- a/src/QsCompiler/Optimizations/Utils/Evaluation.fs +++ b/src/QsCompiler/Optimizations/Utils/Evaluation.fs @@ -42,7 +42,7 @@ type internal FunctionEvaluator(callables: IDictionary = + let incrementState : Imp = imperative { let! vars, counter = getState if counter < 1 then yield TooManyStatements @@ -50,7 +50,7 @@ type internal FunctionEvaluator(callables: IDictionary = + let setVars callables entry : Imp = imperative { let! vars, counter = getState defineVarTuple (isLiteral callables) vars entry @@ -58,20 +58,21 @@ type internal FunctionEvaluator(callables: IDictionary b | _ -> ArgumentException("Not a BoolLiteral: " + x.Expression.ToString()) |> raise /// Evaluates and simplifies a single Q# expression - member private this.EvaluateExpression expr: Imp = + member private this.EvaluateExpression expr : Imp = imperative { let! vars, counter = getState let result = ExpressionEvaluator(callables, vars, counter / 2).Expressions.OnTypedExpression expr - if isLiteral callables result - then return result - else yield CouldNotEvaluate("Not a literal: " + result.Expression.ToString()) + if isLiteral callables result then + return result + else + yield CouldNotEvaluate("Not a literal: " + result.Expression.ToString()) } /// Evaluates a single Q# statement @@ -125,8 +126,9 @@ type internal FunctionEvaluator(callables: IDictionary return va :> seq<_> | _ -> yield - CouldNotEvaluate - ("Unknown IterationValue in for loop: " + iterExpr.Expression.ToString()) + CouldNotEvaluate( + "Unknown IterationValue in for loop: " + iterExpr.Expression.ToString() + ) } for loopValue in iterSeq do @@ -162,11 +164,10 @@ type internal FunctionEvaluator(callables: IDictionary raise + if callable.Kind = Operation then ArgumentException "Input is not a function" |> raise - if callable.Specializations.Length <> 1 - then ArgumentException "Functions must have exactly one specialization" |> raise + if callable.Specializations.Length <> 1 then + ArgumentException "Functions must have exactly one specialization" |> raise let impl = (Seq.exactlyOne callable.Specializations).Implementation @@ -199,10 +200,13 @@ and internal ExpressionEvaluator private (_private_) = /// The ExpressionKindTransformation used to evaluate constant expressions -and private ExpressionKindEvaluator(parent, - callables: IDictionary, - constants: IDictionary, - stmtsLeft: int) = +and private ExpressionKindEvaluator + ( + parent, + callables: IDictionary, + constants: IDictionary, + stmtsLeft: int + ) = inherit ExpressionKindTransformation(parent) member private this.simplify e1 = this.Expressions.OnTypedExpression e1 @@ -291,18 +295,20 @@ and private ExpressionKindEvaluator(parent, let ex = this.simplify ex match ex.Expression with - | CallLikeExpression ({ Expression = Identifier (GlobalCallable qualName, types) }, arg) when (callables.[qualName]) - .Kind = TypeConstructor -> - // TODO - must be adapted if we want to support user-defined type constructors - QsCompilerError.Verify - ((callables.[qualName]).Specializations.Length = 1, - "Type constructors should have exactly one specialization") - - QsCompilerError.Verify - ((callables.[qualName]).Specializations.[0].Implementation = Intrinsic, - "Type constructors should be implicit") - - arg.Expression + | CallLikeExpression ({ Expression = Identifier (GlobalCallable qualName, types) }, arg) when + (callables.[qualName]).Kind = TypeConstructor -> + // TODO - must be adapted if we want to support user-defined type constructors + QsCompilerError.Verify( + (callables.[qualName]).Specializations.Length = 1, + "Type constructors should have exactly one specialization" + ) + + QsCompilerError.Verify( + (callables.[qualName]).Specializations.[0].Implementation = Intrinsic, + "Type constructors should be implicit" + ) + + arg.Expression | _ -> UnwrapApplication ex override this.OnArrayItem(arr, idx) = @@ -493,7 +499,8 @@ and private ExpressionKindEvaluator(parent, override this.OnBitwiseExclusiveOr(lhs, rhs) = this.intBinaryOp BXOR (^^^) (^^^) lhs rhs - override this.OnBitwiseOr(lhs, rhs) = this.intBinaryOp BOR (|||) (|||) lhs rhs + override this.OnBitwiseOr(lhs, rhs) = + this.intBinaryOp BOR (|||) (|||) lhs rhs override this.OnBitwiseAnd(lhs, rhs) = this.intBinaryOp BAND (&&&) (&&&) lhs rhs diff --git a/src/QsCompiler/Optimizations/Utils/HelperFunctions.fs b/src/QsCompiler/Optimizations/Utils/HelperFunctions.fs index b7a5249d0d..dd9ade901b 100644 --- a/src/QsCompiler/Optimizations/Utils/HelperFunctions.fs +++ b/src/QsCompiler/Optimizations/Utils/HelperFunctions.fs @@ -32,7 +32,7 @@ let internal check x = if x then Some() else None /// Returns whether a given expression is a literal (and thus a constant) -let rec internal isLiteral (callables: IDictionary) (expr: TypedExpression): bool = +let rec internal isLiteral (callables: IDictionary) (expr: TypedExpression) : bool = let folder ex sub = match ex.Expression with | IntLiteral _ @@ -51,8 +51,8 @@ let rec internal isLiteral (callables: IDictionary) | RangeLiteral _ | NewArray _ -> true | Identifier _ when ex.ResolvedType.Resolution = Qubit -> true - | CallLikeExpression ({ Expression = Identifier (GlobalCallable name, _) }, _) when callables.[name].Kind = TypeConstructor -> - true + | CallLikeExpression ({ Expression = Identifier (GlobalCallable name, _) }, _) when + callables.[name].Kind = TypeConstructor -> true | _ when TypedExpression.IsPartialApplication ex.Expression -> true | Identifier _ | ArrayItem _ @@ -102,12 +102,12 @@ let internal defineVar check (constants: IDictionary<_, _>) (name, value) = if check value then constants.[name] <- value /// Applies the given function op on a SymbolTuple, ValueTuple pair -let rec private onTuple op constants (names, values): unit = +let rec private onTuple op constants (names, values) : unit = match names, values with | VariableName name, _ -> op constants (name, values) | VariableNameTuple namesTuple, Tuple valuesTuple -> - if namesTuple.Length <> valuesTuple.Length - then ArgumentException "names and values have different lengths" |> raise + if namesTuple.Length <> valuesTuple.Length then + ArgumentException "names and values have different lengths" |> raise for sym, value in Seq.zip namesTuple valuesTuple do onTuple op constants (sym, value) @@ -136,8 +136,8 @@ let rec internal flatten = let rec internal jointFlatten = function | Tuple t1, Tuple t2 -> - if t1.Length <> t2.Length - then ArgumentException "The lengths of the given tuples do not match" |> raise + if t1.Length <> t2.Length then + ArgumentException "The lengths of the given tuples do not match" |> raise Seq.zip t1 t2 |> Seq.collect jointFlatten | v1, v2 -> Seq.singleton (v1, v2) @@ -147,7 +147,7 @@ let rec internal jointFlatten = /// Converts a range literal to a sequence of integers. /// /// The input isn't a valid range literal. -let internal rangeLiteralToSeq (r: ExprKind): seq = +let internal rangeLiteralToSeq (r: ExprKind) : seq = match r with | RangeLiteral (a, b) -> match a.Expression, b.Expression with @@ -173,7 +173,7 @@ let rec internal removeIndices idx l = /// Converts a QsTuple to a SymbolTuple -let rec internal toSymbolTuple (x: QsTuple>): SymbolTuple = +let rec internal toSymbolTuple (x: QsTuple>) : SymbolTuple = match x with | QsTupleItem item -> match item.VariableName with @@ -192,7 +192,8 @@ let rec internal (|LocalVarTuple|_|) (expr: TypedExpression) = | InvalidExpr -> InvalidItem |> Some | ValueTuple va -> va - |> Seq.map (function + |> Seq.map + (function | LocalVarTuple t -> Some t | _ -> None) |> List.ofSeq @@ -204,12 +205,12 @@ let rec internal (|LocalVarTuple|_|) (expr: TypedExpression) = /// Wraps a QsExpressionType in a basic TypedExpression /// The returned TypedExpression has no type param / inferred info / range information, /// and it should not be used for any code step that requires this information. -let internal wrapExpr (bt: TypeKind) (expr: ExprKind): TypedExpression = +let internal wrapExpr (bt: TypeKind) (expr: ExprKind) : TypedExpression = let ii = { IsMutable = false; HasLocalQuantumDependency = false } TypedExpression.New(expr, ImmutableDictionary.Empty, ResolvedType.New bt, ii, Null) /// Wraps a QsStatementKind in a basic QsStatement -let internal wrapStmt (stmt: QsStatementKind): QsStatement = +let internal wrapStmt (stmt: QsStatementKind) : QsStatement = let symbolDecl = match stmt with | QsVariableDeclaration x -> @@ -262,7 +263,7 @@ let rec private containsMissing (ex: TypedExpression) = | _ -> false /// Fills a partial argument by replacing MissingExprs with the corresponding values of a tuple -let rec internal fillPartialArg (partialArg: TypedExpression, arg: TypedExpression): TypedExpression = +let rec internal fillPartialArg (partialArg: TypedExpression, arg: TypedExpression) : TypedExpression = match partialArg with | Missing -> arg | Tuple items -> @@ -273,13 +274,15 @@ let rec internal fillPartialArg (partialArg: TypedExpression, arg: TypedExpressi | _ -> failwithf "args must be a tuple" items - |> List.mapFold (fun args t1 -> - if containsMissing t1 then - match args with - | [] -> failwithf "ran out of args" - | head :: tail -> fillPartialArg (t1, head), tail - else - t1, args) argsList + |> List.mapFold + (fun args t1 -> + if containsMissing t1 then + match args with + | [] -> failwithf "ran out of args" + | head :: tail -> fillPartialArg (t1, head), tail + else + t1, args) + argsList |> fst |> ImmutableArray.CreateRange |> ValueTuple @@ -288,9 +291,8 @@ let rec internal fillPartialArg (partialArg: TypedExpression, arg: TypedExpressi /// Computes exponentiation for 64-bit integers -let internal longPow (a: int64) (b: int64): int64 = - if b < 0L - then failwithf "Negative power %d not supported for integer exponentiation." b +let internal longPow (a: int64) (b: int64) : int64 = + if b < 0L then failwithf "Negative power %d not supported for integer exponentiation." b let mutable x = a let mutable power = b @@ -323,15 +325,16 @@ let internal findAllSubStatements (scope: QsScope) = scope.Statements |> Seq.collect (fun stm -> stm.ExtractAll(statementKind >> Seq.singleton)) /// Returns the number of return statements in this scope -let internal countReturnStatements (scope: QsScope): int = +let internal countReturnStatements (scope: QsScope) : int = scope |> findAllSubStatements - |> Seq.sumBy (function + |> Seq.sumBy + (function | QsReturnStatement _ -> 1 | _ -> 0) /// Returns the number of statements in this scope -let internal scopeLength (scope: QsScope): int = +let internal scopeLength (scope: QsScope) : int = scope |> findAllSubStatements |> Seq.length @@ -347,23 +350,25 @@ let rec internal isAllDiscarded = /// Casts an to an . /// /// is outside the allowed range. -let internal safeCastInt64 (i: int64): int = - if i > int64 (1 <<< 30) || i < -int64 (1 <<< 30) - then ArgumentException "Integer is too large for 32 bits" |> raise - else int i +let internal safeCastInt64 (i: int64) : int = + if i > int64 (1 <<< 30) || i < -int64 (1 <<< 30) then + ArgumentException "Integer is too large for 32 bits" |> raise + else + int i /// /// Casts a to an . /// /// is outside the allowed range. -let internal safeCastBigInt (i: BigInteger): int = - if BigInteger.Abs(i) > BigInteger(1 <<< 30) - then ArgumentException "Integer is too large for 32 bits" |> raise - else int i +let internal safeCastBigInt (i: BigInteger) : int = + if BigInteger.Abs(i) > BigInteger(1 <<< 30) then + ArgumentException "Integer is too large for 32 bits" |> raise + else + int i /// Creates a new scope statement wrapping the given block -let internal newScopeStatement (block: QsScope): QsStatementKind = +let internal newScopeStatement (block: QsScope) : QsStatementKind = let posBlock = QsPositionedBlock.New QsComments.Empty Null block QsConditionalStatement.New(Seq.singleton (wrapExpr Bool (BoolLiteral true), posBlock), Null) diff --git a/src/QsCompiler/Optimizations/Utils/OptimizationTools.fs b/src/QsCompiler/Optimizations/Utils/OptimizationTools.fs index 374e9085e1..ea0db95971 100644 --- a/src/QsCompiler/Optimizations/Utils/OptimizationTools.fs +++ b/src/QsCompiler/Optimizations/Utils/OptimizationTools.fs @@ -33,7 +33,8 @@ and private DistinctQubitsNamespaces(parent: FindDistinctQubits) = argTuple |> toSymbolTuple |> flatten - |> Seq.iter (function + |> Seq.iter + (function | VariableName name -> parent.DistinctNames <- parent.DistinctNames.Add name | _ -> ()) @@ -46,7 +47,8 @@ and private DistinctQubitsStatementKinds(parent: FindDistinctQubits) = override this.OnQubitScope stm = stm.Binding.Lhs |> flatten - |> Seq.iter (function + |> Seq.iter + (function | VariableName name -> parent.DistinctNames <- parent.DistinctNames.Add name | _ -> ()) @@ -77,7 +79,8 @@ and private MutationCheckerStatementKinds(parent: MutationChecker) = override this.OnVariableDeclaration stm = flatten stm.Lhs - |> Seq.iter (function + |> Seq.iter + (function | VariableName name -> parent.DeclaredVariables <- parent.DeclaredVariables.Add name | _ -> ()) @@ -87,7 +90,8 @@ and private MutationCheckerStatementKinds(parent: MutationChecker) = match stm.Lhs with | LocalVarTuple v -> flatten v - |> Seq.iter (function + |> Seq.iter + (function | VariableName name -> parent.MutatedVariables <- parent.MutatedVariables.Add name | _ -> ()) | _ -> () @@ -205,7 +209,7 @@ and internal SideEffectChecker private (_private_) = type internal StatementCollectorTransformation(parent: Core.SyntaxTreeTransformation) = inherit Core.StatementTransformation(parent) - abstract CollectStatements: QsStatementKind -> QsStatementKind seq + abstract CollectStatements : QsStatementKind -> QsStatementKind seq override this.OnScope scope = let parentSymbols = scope.KnownSymbols diff --git a/src/QsCompiler/SyntaxProcessor/CapabilityInference.fs b/src/QsCompiler/SyntaxProcessor/CapabilityInference.fs index 2beb6db9c5..75213468d4 100644 --- a/src/QsCompiler/SyntaxProcessor/CapabilityInference.fs +++ b/src/QsCompiler/SyntaxProcessor/CapabilityInference.fs @@ -33,7 +33,7 @@ type private Pattern = | ResultEqualityNotInCondition of Range QsNullable /// Returns the offset of a nullable location. -let private locationOffset = QsNullable<_>.Map(fun (location: QsLocation) -> location.Offset) +let private locationOffset = QsNullable<_>.Map (fun (location: QsLocation) -> location.Offset) /// Tracks the most recently seen statement location. type private StatementLocationTracker(parent, options) = @@ -63,30 +63,34 @@ let private joinCapabilities = Seq.fold RuntimeCapability.Combine RuntimeCapabil /// level. let private patternDiagnostic context pattern = let error code args (range: _ QsNullable) = - if patternCapability context.IsInOperation pattern |> context.Capability.Implies - then None - else range.ValueOr Range.Zero |> QsCompilerDiagnostic.Error(code, args) |> Some + if patternCapability context.IsInOperation pattern |> context.Capability.Implies then + None + else + range.ValueOr Range.Zero |> QsCompilerDiagnostic.Error(code, args) |> Some let unsupported = - if context.Capability = BasicMeasurementFeedback - then ErrorCode.ResultComparisonNotInOperationIf - else ErrorCode.UnsupportedResultComparison + if context.Capability = BasicMeasurementFeedback then + ErrorCode.ResultComparisonNotInOperationIf + else + ErrorCode.UnsupportedResultComparison match pattern with | ReturnInResultConditionedBlock range -> - if context.Capability = BasicMeasurementFeedback - then error ErrorCode.ReturnInResultConditionedBlock [ context.ProcessorArchitecture ] range - else None + if context.Capability = BasicMeasurementFeedback then + error ErrorCode.ReturnInResultConditionedBlock [ context.ProcessorArchitecture ] range + else + None | SetInResultConditionedBlock (name, range) -> - if context.Capability = BasicMeasurementFeedback - then error ErrorCode.SetInResultConditionedBlock [ name; context.ProcessorArchitecture ] range - else None + if context.Capability = BasicMeasurementFeedback then + error ErrorCode.SetInResultConditionedBlock [ name; context.ProcessorArchitecture ] range + else + None | ResultEqualityInCondition range -> error unsupported [ context.ProcessorArchitecture ] range | ResultEqualityNotInCondition range -> error unsupported [ context.ProcessorArchitecture ] range /// Adds a position offset to the range in the pattern. let private addOffset offset = - let add = QsNullable.Map2 (+) offset + let add = QsNullable.Map2(+) offset function | ReturnInResultConditionedBlock range -> add range |> ReturnInResultConditionedBlock @@ -141,7 +145,7 @@ let private nonLocalUpdates scope = /// equivalent to "elif (true) { ... }". let private conditionBlocks condBlocks elseBlock = elseBlock - |> QsNullable<_>.Map(fun block -> SyntaxGenerator.BoolLiteral true, block) + |> QsNullable<_>.Map (fun block -> SyntaxGenerator.BoolLiteral true, block) |> QsNullable<_>.Fold (fun acc x -> x :: acc) [] |> Seq.append condBlocks @@ -158,9 +162,10 @@ let private conditionalStatementPatterns { ConditionalBlocks = condBlocks; Defau let returnPatterns (block: QsPositionedBlock) = block.Body.Statements |> Seq.collect returnStatements - |> Seq.map (fun statement -> - let range = statement.Location |> QsNullable<_>.Map(fun location -> location.Offset + location.Range) - ReturnInResultConditionedBlock range) + |> Seq.map + (fun statement -> + let range = statement.Location |> QsNullable<_>.Map (fun location -> location.Offset + location.Range) + ReturnInResultConditionedBlock range) let setPatterns (block: QsPositionedBlock) = nonLocalUpdates block.Body @@ -224,7 +229,7 @@ let private globalReferences scope = override this.OnTypedExpression expression = match expression.Expression with | Identifier (GlobalCallable name, _) -> - let range = QsNullable.Map2 (+) location.Offset expression.Range + let range = QsNullable.Map2(+) location.Offset expression.Range references <- (name, range) :: references | _ -> () @@ -235,11 +240,12 @@ let private globalReferences scope = references /// Returns diagnostic reasons for why a global callable reference is not supported. -let rec private referenceReasons context - (name: QsQualifiedName) - (range: _ QsNullable) - (header: SpecializationDeclarationHeader, impl) - = +let rec private referenceReasons + context + (name: QsQualifiedName) + (range: _ QsNullable) + (header: SpecializationDeclarationHeader, impl) + = let reason (header: SpecializationDeclarationHeader) diagnostic = match diagnostic.Diagnostic with | Error ErrorCode.UnsupportedResultComparison -> Some WarningCode.UnsupportedResultComparison @@ -248,26 +254,28 @@ let rec private referenceReasons context | Error ErrorCode.SetInResultConditionedBlock -> Some WarningCode.SetInResultConditionedBlock | Error ErrorCode.UnsupportedCallableCapability -> Some WarningCode.UnsupportedCallableCapability | _ -> None - |> Option.map (fun code -> - let args = - Seq.append - [ - name.Name - header.Source.CodeFile - string (diagnostic.Range.Start.Line + 1) - string (diagnostic.Range.Start.Column + 1) - ] - diagnostic.Arguments - - range.ValueOr Range.Zero |> QsCompilerDiagnostic.Warning(code, args)) + |> Option.map + (fun code -> + let args = + Seq.append + [ + name.Name + header.Source.CodeFile + string (diagnostic.Range.Start.Line + 1) + string (diagnostic.Range.Start.Column + 1) + ] + diagnostic.Arguments + + range.ValueOr Range.Zero |> QsCompilerDiagnostic.Warning(code, args)) match impl with | Provided (_, scope) -> scopeDiagnosticsImpl false context scope - |> Seq.map (fun diagnostic -> - locationOffset header.Location - |> QsNullable<_>.Map(fun offset -> { diagnostic with Range = offset + diagnostic.Range }) - |> QsNullable.defaultValue diagnostic) + |> Seq.map + (fun diagnostic -> + locationOffset header.Location + |> QsNullable<_>.Map (fun offset -> { diagnostic with Range = offset + diagnostic.Range }) + |> QsNullable.defaultValue diagnostic) |> Seq.choose (reason header) | _ -> Seq.empty @@ -283,9 +291,10 @@ and private referenceDiagnostics includeReasons context (name: QsQualifiedName, Seq.empty else let reasons = - if includeReasons - then context.Globals.ImportedSpecializations name |> Seq.collect (referenceReasons context name range) - else Seq.empty + if includeReasons then + context.Globals.ImportedSpecializations name |> Seq.collect (referenceReasons context name range) + else + Seq.empty let error = ErrorCode.UnsupportedCallableCapability, [ name.Name; string capability; context.ProcessorArchitecture ] @@ -295,7 +304,7 @@ and private referenceDiagnostics includeReasons context (name: QsQualifiedName, | _ -> Seq.empty /// Returns all capability diagnostics for the scope. Ranges are relative to the start of the specialization. -and private scopeDiagnosticsImpl includeReasons context scope: QsCompilerDiagnostic seq = +and private scopeDiagnosticsImpl includeReasons context scope : QsCompilerDiagnostic seq = [ globalReferences scope |> Seq.collect (referenceDiagnostics includeReasons context) scopePatterns scope |> Seq.choose (patternDiagnostic context) @@ -321,7 +330,7 @@ let private isDeclaredInSourceFile (callable: QsCallable) = let private specSourceCapability inOperation spec = match spec.Implementation with | Provided (_, scope) -> - let offset = spec.Location |> QsNullable<_>.Map(fun location -> location.Offset) + let offset = spec.Location |> QsNullable<_>.Map (fun location -> location.Offset) scopePatterns scope |> Seq.map (addOffset offset >> patternCapability inOperation) @@ -344,9 +353,10 @@ let private sourceCycleCapabilities (callables: ImmutableDictionary<_, _>) (grap let sourceCycles = graph.GetCallCycles() - |> Seq.filter - (Seq.exists - <| fun node -> callables.TryGetValue node.CallableName |> tryOption |> Option.exists isDeclaredInSourceFile) + |> Seq.filter ( + Seq.exists + <| fun node -> callables.TryGetValue node.CallableName |> tryOption |> Option.exists isDeclaredInSourceFile + ) for cycle in sourceCycles do let cycleCapability = @@ -356,8 +366,9 @@ let private sourceCycleCapabilities (callables: ImmutableDictionary<_, _>) (grap |> joinCapabilities for node in cycle do - initialCapabilities.[node.CallableName] <- joinCapabilities [ initialCapabilities.[node.CallableName] - cycleCapability ] + initialCapabilities.[node.CallableName] <- + joinCapabilities [ initialCapabilities.[node.CallableName] + cycleCapability ] initialCapabilities @@ -408,10 +419,11 @@ let private callableDependentCapability (callables: ImmutableDictionary<_, _>) ( and cachedCapability visited (callable: QsCallable) = cache.TryGetValue callable.FullName |> tryOption - |> Option.defaultWith (fun () -> - let capability = callableCapability visited callable - cache.[callable.FullName] <- capability - capability) + |> Option.defaultWith + (fun () -> + let capability = callableCapability visited callable + cache.[callable.FullName] <- capability + capability) cachedCapability Set.empty @@ -434,9 +446,10 @@ let InferCapabilities compilation = let isMissingCapability = SymbolResolution.TryGetRequiredCapability callable.Attributes |> QsNullable.isNull - if isMissingCapability && isDeclaredInSourceFile callable - then callableCapability callable |> toAttribute |> callable.AddAttribute - else callable + if isMissingCapability && isDeclaredInSourceFile callable then + callableCapability callable |> toAttribute |> callable.AddAttribute + else + callable } transformation.OnCompilation compilation diff --git a/src/QsCompiler/SyntaxProcessor/ContextVerification.fs b/src/QsCompiler/SyntaxProcessor/ContextVerification.fs index f4a4df77e6..c3ae7512d9 100644 --- a/src/QsCompiler/SyntaxProcessor/ContextVerification.fs +++ b/src/QsCompiler/SyntaxProcessor/ContextVerification.fs @@ -28,9 +28,10 @@ let private ApplyOrDefaultTo fallback nullable apply = /// Verifies that the number of parents in the given context is 0. /// Returns an array with suitable diagnostics. let private verifyNamespace (context: SyntaxTokenContext) = - if context.Parents.Length = 0 - then true, [||] - else false, [| (ErrorCode.NotWithinGlobalScope |> Error, context.Range) |] + if context.Parents.Length = 0 then + true, [||] + else + false, [| (ErrorCode.NotWithinGlobalScope |> Error, context.Range) |] /// Verifies that the direct parent in the given context is a namespace declaration. /// Indicates that the fragment is to be excluded from compilation if the direct parent is not a namespace declaration. @@ -130,7 +131,7 @@ let private verifySpecialization (context: SyntaxTokenContext) = false, [| (ErrorCode.ControlledAdjointDeclInFunction |> Error, context.Range) |] | decl -> checkGenerator decl - let NullOr = ApplyOrDefaultTo (false, [||]) context.Self // empty fragments can be excluded from the compilation + let NullOr = ApplyOrDefaultTo(false, [||]) context.Self // empty fragments can be excluded from the compilation let errMsg = false, [| (ErrorCode.NotWithinCallable |> Error, context.Range) |] @@ -178,7 +179,7 @@ let private verifyStatement (context: SyntaxTokenContext) = | ReturnStatement _ -> false, [| (ErrorCode.ReturnFromWithinApplyBlock |> Error, context.Range) |] | _ -> true, [||] - let NullOr = ApplyOrDefaultTo (false, [||]) context.Self // empty fragments can be excluded from the compilation + let NullOr = ApplyOrDefaultTo(false, [||]) context.Self // empty fragments can be excluded from the compilation let notWithinSpecialization = false, [| (ErrorCode.NotWithinSpecialization |> Error, context.Range) |] @@ -264,36 +265,36 @@ type ContextVerification = delegate of SyntaxTokenContext -> (bool * QsCompilerD /// Marked as excluded, on the other hand, are invalid or empty fragments. let VerifySyntaxTokenContext = new ContextVerification(fun context -> - match context.Self with - | Null -> false, [||] - | Value kind -> - match kind with - | ExpressionStatement _ -> verifyStatement context - | ReturnStatement _ -> verifyStatement context - | FailStatement _ -> verifyStatement context - | ImmutableBinding _ -> verifyStatement context - | MutableBinding _ -> verifyStatement context - | ValueUpdate _ -> verifyStatement context - | IfClause _ -> verifyStatement context - | ElifClause _ -> precededByIfOrElif context - | ElseClause _ -> precededByIfOrElif context - | ForLoopIntro _ -> verifyStatement context - | WhileLoopIntro _ -> verifyStatement context - | RepeatIntro _ -> followedByUntil context - | UntilSuccess _ -> precededByRepeat context - | WithinBlockIntro _ -> followedByApply context - | ApplyBlockIntro _ -> precededByWithin context - | UsingBlockIntro _ -> verifyStatement context - | BorrowingBlockIntro _ -> verifyStatement context - | BodyDeclaration _ -> verifySpecialization context - | AdjointDeclaration _ -> verifySpecialization context - | ControlledDeclaration _ -> verifySpecialization context - | ControlledAdjointDeclaration _ -> verifySpecialization context - | OperationDeclaration _ -> verifyDeclaration context - | FunctionDeclaration _ -> verifyDeclaration context - | TypeDefinition _ -> verifyDeclaration context - | OpenDirective _ -> verifyOpenDirective context - | DeclarationAttribute _ -> verifyDeclarationAttribute context - | NamespaceDeclaration _ -> verifyNamespace context - | InvalidFragment _ -> false, [||] - |> fun (kind, tuple) -> kind, tuple |> Array.map (fun (x, y) -> QsCompilerDiagnostic.New (x, []) y)) + match context.Self with + | Null -> false, [||] + | Value kind -> + match kind with + | ExpressionStatement _ -> verifyStatement context + | ReturnStatement _ -> verifyStatement context + | FailStatement _ -> verifyStatement context + | ImmutableBinding _ -> verifyStatement context + | MutableBinding _ -> verifyStatement context + | ValueUpdate _ -> verifyStatement context + | IfClause _ -> verifyStatement context + | ElifClause _ -> precededByIfOrElif context + | ElseClause _ -> precededByIfOrElif context + | ForLoopIntro _ -> verifyStatement context + | WhileLoopIntro _ -> verifyStatement context + | RepeatIntro _ -> followedByUntil context + | UntilSuccess _ -> precededByRepeat context + | WithinBlockIntro _ -> followedByApply context + | ApplyBlockIntro _ -> precededByWithin context + | UsingBlockIntro _ -> verifyStatement context + | BorrowingBlockIntro _ -> verifyStatement context + | BodyDeclaration _ -> verifySpecialization context + | AdjointDeclaration _ -> verifySpecialization context + | ControlledDeclaration _ -> verifySpecialization context + | ControlledAdjointDeclaration _ -> verifySpecialization context + | OperationDeclaration _ -> verifyDeclaration context + | FunctionDeclaration _ -> verifyDeclaration context + | TypeDefinition _ -> verifyDeclaration context + | OpenDirective _ -> verifyOpenDirective context + | DeclarationAttribute _ -> verifyDeclarationAttribute context + | NamespaceDeclaration _ -> verifyNamespace context + | InvalidFragment _ -> false, [||] + |> fun (kind, tuple) -> kind, tuple |> Array.map (fun (x, y) -> QsCompilerDiagnostic.New(x, []) y)) diff --git a/src/QsCompiler/SyntaxProcessor/DeclarationVerification.fs b/src/QsCompiler/SyntaxProcessor/DeclarationVerification.fs index 4b8e6e29c3..c1f49221e8 100644 --- a/src/QsCompiler/SyntaxProcessor/DeclarationVerification.fs +++ b/src/QsCompiler/SyntaxProcessor/DeclarationVerification.fs @@ -30,13 +30,13 @@ let public AsDeclarationName sym onInvalid = | _ -> null let private NameOnly onInvalid arg = - (arg |> QsNullable<_>.Map(fun (sym, _) -> AsDeclarationName sym.Symbol onInvalid)).ValueOr null + (arg |> QsNullable<_>.Map (fun (sym, _) -> AsDeclarationName sym.Symbol onInvalid)).ValueOr null /// If the given fragment kind is a namespace declaration, /// returns a tuple with the namespace symbol and null (to make the signature of this routine compatible with the remaining ones) as Value. /// Returns Null otherwise. [] -let public DeclaredNamespace this: QsNullable = +let public DeclaredNamespace this : QsNullable = match this with | NamespaceDeclaration sym -> (sym, null) |> Value | _ -> Null @@ -53,7 +53,7 @@ let public DeclaredNamespaceName this onInvalid = /// returns a tuple with the symbol of the opened namespace and the defined short name (if any) as Value. /// Returns Null otherwise. [] -let public OpenedNamespace this: QsNullable> = +let public OpenedNamespace this : QsNullable> = match this with | OpenDirective (nsName, alias) -> (nsName, alias) |> Value | _ -> Null @@ -107,8 +107,9 @@ let public DeclaredCallableName this onInvalid = /// The type specializations are given as either an Value containing an immutable array of Q# types, /// or as Null, if no type specializations have been declared. [] -let public DeclaredSpecialization this - : QsNullable<(QsSpecializationKind * QsSpecializationGenerator) * QsNullable>> = +let public DeclaredSpecialization + this + : QsNullable<(QsSpecializationKind * QsSpecializationGenerator) * QsNullable>> = match this with | BodyDeclaration gen -> ((QsBody, gen), Null) |> Value | AdjointDeclaration gen -> ((QsAdjoint, gen), Null) |> Value @@ -211,7 +212,10 @@ let public BuildArgumentControlled (this: QsTuple] -let public BuildArgumentControlledAdjoint (this: QsTuple>) (arg: QsSymbol, pos) = +let public BuildArgumentControlledAdjoint + (this: QsTuple>) + (arg: QsSymbol, pos) + = let ctrlQs, diagnostics = arg |> singleAdditionalArg (ErrorCode.ControlledAdjointGenArgMismatch, []) SyntaxGenerator.WithControlQubits this pos ctrlQs |> StripRangeInfo, diagnostics @@ -228,9 +232,11 @@ let public ValidDeclarations (this: ImmutableArray] let public WithAbsolutePosition (this: LocalDeclarations) (updatePosition: Func, Position>) = - LocalDeclarations.New - (this + LocalDeclarations.New( + this .Variables - .Select(Func<_, _>(fun (d: LocalVariableDeclaration<_>) -> - { d with Position = updatePosition.Invoke d.Position |> Value })) - .ToImmutableArray()) + .Select(Func<_, _> + (fun (d: LocalVariableDeclaration<_>) -> + { d with Position = updatePosition.Invoke d.Position |> Value })) + .ToImmutableArray() + ) diff --git a/src/QsCompiler/SyntaxProcessor/ExpressionVerification.fs b/src/QsCompiler/SyntaxProcessor/ExpressionVerification.fs index 989f4d21a4..d151f35737 100644 --- a/src/QsCompiler/SyntaxProcessor/ExpressionVerification.fs +++ b/src/QsCompiler/SyntaxProcessor/ExpressionVerification.fs @@ -19,7 +19,7 @@ open System.Collections.Immutable // utils for verifying types in expressions /// Returns the string representation of a type. -let private showType: ResolvedType -> _ = SyntaxTreeToQsharp.Default.ToCode +let private showType : ResolvedType -> _ = SyntaxTreeToQsharp.Default.ToCode /// Returns true if the type is a function type. let private isFunction (resolvedType: ResolvedType) = @@ -53,9 +53,10 @@ let rec private partialArgType (inference: InferenceContext) (argType: ResolvedT ||> Seq.foldBack (fun (item, params1) (items, params2) -> item :: items, Option.toList params1 @ params2) let missing = - if List.isEmpty missing - then None - else ImmutableArray.CreateRange missing |> TupleType |> ResolvedType.New |> Some + if List.isEmpty missing then + None + else + ImmutableArray.CreateRange missing |> TupleType |> ResolvedType.New |> Some argType |> ResolvedType.withKind (ImmutableArray.CreateRange items |> TupleType), missing | _ -> argType, None @@ -94,8 +95,8 @@ let private verifyConditionalExecution (expr: TypedExpression) = | _ -> false [ - if expr.Exists isOperationCall - then QsCompilerDiagnostic.Warning (WarningCode.ConditionalEvaluationOfOperationCall, []) (rangeOrDefault expr) + if expr.Exists isOperationCall then + QsCompilerDiagnostic.Warning(WarningCode.ConditionalEvaluationOfOperationCall, []) (rangeOrDefault expr) ] /// @@ -116,7 +117,7 @@ let private verifyUdtWith processUdt (resolvedType: ResolvedType) range = | _ -> ResolvedType.New InvalidType, [ - QsCompilerDiagnostic.Error (ErrorCode.ExpectingUserDefinedType, [ showType resolvedType ]) range + QsCompilerDiagnostic.Error(ErrorCode.ExpectingUserDefinedType, [ showType resolvedType ]) range ] /// @@ -209,10 +210,11 @@ let private verifyValueArray (inference: InferenceContext) range exprs = let diagnostics = ResizeArray() types - |> Seq.reduce (fun left right -> - let intersectionType, intersectionDiagnostics = inference.Intersect(left, right) - intersectionDiagnostics |> List.iter diagnostics.Add - intersectionType |> ResolvedType.withAllRanges right.Range) + |> Seq.reduce + (fun left right -> + let intersectionType, intersectionDiagnostics = inference.Intersect(left, right) + intersectionDiagnostics |> List.iter diagnostics.Add + intersectionType |> ResolvedType.withAllRanges right.Range) |> ResolvedType.withAllRanges (Inferred range) |> ArrayType |> ResolvedType.create (Inferred range), @@ -255,14 +257,15 @@ let private verifyIdentifier (inference: InferenceContext) (symbols: SymbolTrack let resolvedTargs = typeArgs - |> QsNullable<_> - .Map(fun (args: ImmutableArray) -> + |> QsNullable<_>.Map + (fun (args: ImmutableArray) -> args - |> Seq.map (fun tArg -> - match tArg.Type with - | MissingType -> ResolvedType.New MissingType - | _ -> symbols.ResolveType diagnostics.Add tArg)) - |> QsNullable<_>.Map(fun args -> args.ToImmutableArray()) + |> Seq.map + (fun tArg -> + match tArg.Type with + | MissingType -> ResolvedType.New MissingType + | _ -> symbols.ResolveType diagnostics.Add tArg)) + |> QsNullable<_>.Map (fun args -> args.ToImmutableArray()) let resId, typeParams = symbols.ResolveIdentifier diagnostics.Add symbol let identifier, info = Identifier(resId.VariableName, resolvedTargs), resId.InferredInformation @@ -279,7 +282,7 @@ let private verifyIdentifier (inference: InferenceContext) (symbols: SymbolTrack | LocalVariable _, Null -> (identifier, resId.Type) |> exprWithoutTypeArgs symbol.Range info, Seq.toList diagnostics | LocalVariable _, Value _ -> invalidWithoutTargs false, - QsCompilerDiagnostic.Error (ErrorCode.IdentifierCannotHaveTypeArguments, []) symbol.RangeOrDefault + QsCompilerDiagnostic.Error(ErrorCode.IdentifierCannotHaveTypeArguments, []) symbol.RangeOrDefault :: Seq.toList diagnostics | GlobalCallable _, Value res when res.Length <> typeParams.Length -> invalidWithoutTargs false, @@ -290,7 +293,8 @@ let private verifyIdentifier (inference: InferenceContext) (symbols: SymbolTrack | GlobalCallable name, _ -> let typeParams = typeParams - |> Seq.choose (function + |> Seq.choose + (function | ValidName param -> Some(name, param) | InvalidName -> None) @@ -298,16 +302,19 @@ let private verifyIdentifier (inference: InferenceContext) (symbols: SymbolTrack let resolutions = typeParams - |> Seq.mapi (fun i param -> - if i < typeArgs.Length && typeArgs.[i].Resolution <> MissingType - then KeyValuePair(param, typeArgs.[i]) - else KeyValuePair(param, inference.Fresh symbol.RangeOrDefault)) + |> Seq.mapi + (fun i param -> + if i < typeArgs.Length && typeArgs.[i].Resolution <> MissingType then + KeyValuePair(param, typeArgs.[i]) + else + KeyValuePair(param, inference.Fresh symbol.RangeOrDefault)) |> ImmutableDictionary.CreateRange let identifier = - if resolutions.IsEmpty - then identifier - else Identifier(GlobalCallable name, ImmutableArray.CreateRange resolutions.Values |> Value) + if resolutions.IsEmpty then + identifier + else + Identifier(GlobalCallable name, ImmutableArray.CreateRange resolutions.Values |> Value) let exInfo = InferredExpressionInformation.New(isMutable = false, quantumDep = info.HasLocalQuantumDependency) TypedExpression.New(identifier, resolutions, resId.Type, exInfo, symbol.Range), Seq.toList diagnostics @@ -504,7 +511,7 @@ type QsExpression with | InvalidSymbol -> InvalidIdentifier | Symbol name -> LocalVariable name | _ -> - QsCompilerDiagnostic.Error (ErrorCode.ExpectingItemName, []) sym.RangeOrDefault |> diagnose + QsCompilerDiagnostic.Error(ErrorCode.ExpectingItemName, []) sym.RangeOrDefault |> diagnose InvalidIdentifier /// Resolves and verifies the given expression and item name of a named item access expression, @@ -698,8 +705,7 @@ type QsExpression with let rhs = resolve rhs verify lhs rhs |> List.iter diagnose - if shortCircuits - then verifyConditionalExecution rhs |> List.iter diagnose + if shortCircuits then verifyConditionalExecution rhs |> List.iter diagnose let localQdependency = lhs.InferredInformation.HasLocalQuantumDependency @@ -748,8 +754,10 @@ type QsExpression with let argType, partialType = partialArgType inference arg.ResolvedType if Option.isNone partialType then - inference.Constrain - (callable.ResolvedType, Set.ofSeq symbols.RequiredFunctorSupport |> CanGenerateFunctors) + inference.Constrain( + callable.ResolvedType, + Set.ofSeq symbols.RequiredFunctorSupport |> CanGenerateFunctors + ) |> List.iter diagnose let output = inference.Fresh this.RangeOrDefault @@ -761,7 +769,7 @@ type QsExpression with inference.Unify(QsTypeKind.Function(argType, output) |> ResolvedType.New, callable.ResolvedType) if inference.Resolve callable.ResolvedType |> isOperation then - QsCompilerDiagnostic.Error (ErrorCode.OperationCallOutsideOfOperation, []) this.RangeOrDefault + QsCompilerDiagnostic.Error(ErrorCode.OperationCallOutsideOfOperation, []) this.RangeOrDefault |> diagnose else List.iter diagnose diagnostics @@ -836,16 +844,28 @@ type QsExpression with | MUL (lhs, rhs) -> buildArithmeticOp MUL (lhs, rhs) | DIV (lhs, rhs) -> buildArithmeticOp DIV (lhs, rhs) | LT (lhs, rhs) -> - buildBooleanOpWith (fun lhs rhs -> verifyArithmeticOp inference this.Range lhs rhs |> snd) false LT + buildBooleanOpWith + (fun lhs rhs -> verifyArithmeticOp inference this.Range lhs rhs |> snd) + false + LT (lhs, rhs) | LTE (lhs, rhs) -> - buildBooleanOpWith (fun lhs rhs -> verifyArithmeticOp inference this.Range lhs rhs |> snd) false LTE + buildBooleanOpWith + (fun lhs rhs -> verifyArithmeticOp inference this.Range lhs rhs |> snd) + false + LTE (lhs, rhs) | GT (lhs, rhs) -> - buildBooleanOpWith (fun lhs rhs -> verifyArithmeticOp inference this.Range lhs rhs |> snd) false GT + buildBooleanOpWith + (fun lhs rhs -> verifyArithmeticOp inference this.Range lhs rhs |> snd) + false + GT (lhs, rhs) | GTE (lhs, rhs) -> - buildBooleanOpWith (fun lhs rhs -> verifyArithmeticOp inference this.Range lhs rhs |> snd) false GTE + buildBooleanOpWith + (fun lhs rhs -> verifyArithmeticOp inference this.Range lhs rhs |> snd) + false + GTE (lhs, rhs) | POW (lhs, rhs) -> buildPower (lhs, rhs) // power takes a special role because you can raise integers and doubles to integer and double powers, but bigint only to integer powers | MOD (lhs, rhs) -> buildIntegralOp MOD (lhs, rhs) @@ -862,6 +882,8 @@ type QsExpression with | BNOT ex -> verifyAndBuildWith BNOT (verifyIsIntegral inference) ex | NOT ex -> ex - |> verifyAndBuildWith NOT (fun expr -> - Bool |> ResolvedType.create (TypeRange.inferred this.Range), - inference.Unify(ResolvedType.New Bool, expr.ResolvedType)) + |> verifyAndBuildWith + NOT + (fun expr -> + Bool |> ResolvedType.create (TypeRange.inferred this.Range), + inference.Unify(ResolvedType.New Bool, expr.ResolvedType)) diff --git a/src/QsCompiler/SyntaxProcessor/ScopeContext.fs b/src/QsCompiler/SyntaxProcessor/ScopeContext.fs index 58b46e7485..bb8aa868c8 100644 --- a/src/QsCompiler/SyntaxProcessor/ScopeContext.fs +++ b/src/QsCompiler/SyntaxProcessor/ScopeContext.fs @@ -45,11 +45,12 @@ type ScopeContext = /// Thrown if the given namespace manager does not contain all resolutions or if the specialization's parent does /// not exist in the given namespace manager. /// - static member Create (nsManager: NamespaceManager) - capability - processorArchitecture - (spec: SpecializationDeclarationHeader) - = + static member Create + (nsManager: NamespaceManager) + capability + processorArchitecture + (spec: SpecializationDeclarationHeader) + = match nsManager.TryGetCallable spec.Parent (spec.Parent.Namespace, Source.assemblyOrCodeFile spec.Source) with | Found declaration -> let symbolTracker = SymbolTracker(nsManager, Source.assemblyOrCodeFile spec.Source, spec.Parent) diff --git a/src/QsCompiler/SyntaxProcessor/StatementVerification.fs b/src/QsCompiler/SyntaxProcessor/StatementVerification.fs index 4a5694f0a9..390a471ef3 100644 --- a/src/QsCompiler/SyntaxProcessor/StatementVerification.fs +++ b/src/QsCompiler/SyntaxProcessor/StatementVerification.fs @@ -32,16 +32,17 @@ let private onAutoInvertCheckQuantumDependency (symbols: SymbolTracker) (expr: T [| if symbols.RequiredFunctorSupport.Contains Adjoint && expr.InferredInformation.HasLocalQuantumDependency then - QsCompilerDiagnostic.Error (ErrorCode.QuantumDependencyOutsideExprStatement, []) (rangeOrDefault expr) + QsCompilerDiagnostic.Error(ErrorCode.QuantumDependencyOutsideExprStatement, []) (rangeOrDefault expr) |] /// If the given SymbolTracker specifies that an auto-inversion of the routine is requested, /// returns an array with containing a diagnostic for the given range with the given error code. /// Returns an empty array otherwise. let private onAutoInvertGenerateError (errCode, range) (symbols: SymbolTracker) = - if symbols.RequiredFunctorSupport.Contains Adjoint - then [| range |> QsCompilerDiagnostic.Error errCode |] - else [||] + if symbols.RequiredFunctorSupport.Contains Adjoint then + [| range |> QsCompilerDiagnostic.Error errCode |] + else + [||] // utils for building QsStatements from QsFragmentKinds @@ -107,12 +108,12 @@ let rec private VerifyBinding (inference: InferenceContext) tryBuildDeclaration match symbol.Symbol with | InvalidSymbol -> InvalidItem, [||], [||] | MissingSymbol when warnOnDiscard -> - let warning = QsCompilerDiagnostic.Warning (WarningCode.DiscardingItemInAssignment, []) symbol.RangeOrDefault + let warning = QsCompilerDiagnostic.Warning(WarningCode.DiscardingItemInAssignment, []) symbol.RangeOrDefault DiscardedItem, [||], [| warning |] | MissingSymbol -> DiscardedItem, [||], [||] | OmittedSymbols | QualifiedSymbol _ -> - let error = QsCompilerDiagnostic.Error (ErrorCode.ExpectingUnqualifiedSymbol, []) symbol.RangeOrDefault + let error = QsCompilerDiagnostic.Error(ErrorCode.ExpectingUnqualifiedSymbol, []) symbol.RangeOrDefault InvalidItem, [||], [| error |] | Symbol name -> match tryBuildDeclaration (name, symbol.RangeOrDefault) (rhsType) with @@ -153,7 +154,7 @@ let NewValueUpdate comments (location: QsLocation) context (lhs, rhs) = verifyAssignment context.Inference lhs.ResolvedType ErrorCode.TypeMismatchInValueUpdate rhs |> diagnostics.AddRange - let rec verifyMutability: TypedExpression -> _ = + let rec verifyMutability : TypedExpression -> _ = function | Tuple exs -> exs |> Seq.iter verifyMutability | Item ex when ex.InferredInformation.IsMutable -> @@ -161,7 +162,7 @@ let NewValueUpdate comments (location: QsLocation) context (lhs, rhs) = | Identifier (LocalVariable id, Null) -> context.Symbols.UpdateQuantumDependency id localQdep | _ -> () | Item ex -> - QsCompilerDiagnostic.Error (ErrorCode.UpdateOfImmutableIdentifier, []) (ex.Range.ValueOr Range.Zero) + QsCompilerDiagnostic.Error(ErrorCode.UpdateOfImmutableIdentifier, []) (ex.Range.ValueOr Range.Zero) |> diagnostics.Add | _ -> () // both missing and invalid expressions on the lhs are fine @@ -342,8 +343,9 @@ let NewConjugation (outer: QsPositionedBlock, inner: QsPositionedBlock) = updatedInInner |> Seq.filter (fun updated -> usedInOuter.Contains updated.Key) |> Seq.collect id - |> Seq.map (fun loc -> - loc.Offset + loc.Range |> QsCompilerDiagnostic.Error(ErrorCode.InvalidReassignmentInApplyBlock, [])) + |> Seq.map + (fun loc -> + loc.Offset + loc.Range |> QsCompilerDiagnostic.Error(ErrorCode.InvalidReassignmentInApplyBlock, [])) |> Seq.toArray QsConjugation.New(outer, inner) diff --git a/src/QsCompiler/SyntaxProcessor/SymbolTracker.fs b/src/QsCompiler/SyntaxProcessor/SymbolTracker.fs index c4c67bd262..f8b4bfd384 100644 --- a/src/QsCompiler/SyntaxProcessor/SymbolTracker.fs +++ b/src/QsCompiler/SyntaxProcessor/SymbolTracker.fs @@ -27,28 +27,29 @@ type private TrackedScope = RequiredFunctorSupport: ImmutableHashSet } - /// Given all functors that need to be applied to a particular operation call, - /// combines them into the set of functors that that operation needs to support. - static member internal CombinedFunctorSupport functors = - let rec requiredSupport current = - function - | [] -> current - | Adjoint :: tail -> - if not (current |> List.contains Adjoint) then - requiredSupport (Adjoint :: current) tail - else - requiredSupport - [ - for f in current do - if f <> Adjoint then yield f - ] - tail - | Controlled :: tail -> - if current |> List.contains Controlled - then requiredSupport current tail - else requiredSupport (Controlled :: current) tail - - requiredSupport [] functors + /// Given all functors that need to be applied to a particular operation call, + /// combines them into the set of functors that that operation needs to support. + static member internal CombinedFunctorSupport functors = + let rec requiredSupport current = + function + | [] -> current + | Adjoint :: tail -> + if not (current |> List.contains Adjoint) then + requiredSupport (Adjoint :: current) tail + else + requiredSupport + [ + for f in current do + if f <> Adjoint then yield f + ] + tail + | Controlled :: tail -> + if current |> List.contains Controlled then + requiredSupport current tail + else + requiredSupport (Controlled :: current) tail + + requiredSupport [] functors /// /// The class does *not* make a copy of the given , @@ -62,13 +63,13 @@ type SymbolTracker(globals: NamespaceManager, sourceFile, parent: QsQualifiedNam // TODO: once we support type specialiations, the parent needs to be the specialization name rather than the callable name do - if not globals.ContainsResolutions - then ArgumentException "the content of the given namespace manager needs to be resolved" |> raise + if not globals.ContainsResolutions then + ArgumentException "the content of the given namespace manager needs to be resolved" |> raise /// Contains all properties that need to be tracked for verifying the built syntax tree, but are not needed after. /// In particular, contains a "stack" of all local declarations up to this point in each scope, /// as well as which functors need to be supported by the operations called within each scope. - let mutable pushedScopes: TrackedScope list = [] + let mutable pushedScopes : TrackedScope list = [] /// contains the version number of the global symbols manager upon initialization let expectedVersionGlobals = globals.VersionNumber @@ -90,7 +91,8 @@ type SymbolTracker(globals: NamespaceManager, sourceFile, parent: QsQualifiedNam match GlobalSymbols().TryGetCallable parent (parent.Namespace, sourceFile) with | Found decl -> decl.Signature.TypeParameters - |> Seq.choose (function + |> Seq.choose + (function | ValidName name -> Some name | InvalidName -> None) |> fun valid -> valid.ToImmutableArray() @@ -117,7 +119,7 @@ type SymbolTracker(globals: NamespaceManager, sourceFile, parent: QsQualifiedNam let globalTypeWithName (ns, name) = match ns with | None -> GlobalSymbols().TryResolveAndGetType name (parent.Namespace, sourceFile) - | Some nsName -> GlobalSymbols().TryGetType (QsQualifiedName.New(nsName, name)) (parent.Namespace, sourceFile) + | Some nsName -> GlobalSymbols().TryGetType(QsQualifiedName.New(nsName, name)) (parent.Namespace, sourceFile) /// If a callable declaration (including type constructors!) for a callable with the given name exists in GlobalSymbols, /// returns a its header information as Value. Returns Null otherwise. @@ -127,7 +129,7 @@ type SymbolTracker(globals: NamespaceManager, sourceFile, parent: QsQualifiedNam match ns with | None -> GlobalSymbols().TryResolveAndGetCallable name (parent.Namespace, sourceFile) | Some nsName -> - GlobalSymbols().TryGetCallable (QsQualifiedName.New(nsName, name)) (parent.Namespace, sourceFile) + GlobalSymbols().TryGetCallable(QsQualifiedName.New(nsName, name)) (parent.Namespace, sourceFile) /// the namespace and callable declaration within which the symbols tracked by this SymbolTracker instance are used member this.Parent = parent @@ -168,8 +170,7 @@ type SymbolTracker(globals: NamespaceManager, sourceFile, parent: QsQualifiedNam /// pops the most recent scope from the stack, thus closing it member this.EndScope() = - if pushedScopes.Length = 0 - then InvalidOperationException "no scope is currently open" |> raise + if pushedScopes.Length = 0 then InvalidOperationException "no scope is currently open" |> raise pushedScopes <- pushedScopes.Tail @@ -184,8 +185,7 @@ type SymbolTracker(globals: NamespaceManager, sourceFile, parent: QsQualifiedNam /// /// No scope is currently open. member this.TryAddVariableDeclartion(decl: LocalVariableDeclaration) = - if pushedScopes.Length = 0 - then InvalidOperationException "no scope is currently open" |> raise + if pushedScopes.Length = 0 then InvalidOperationException "no scope is currently open" |> raise if (globalTypeWithName (None, decl.VariableName)) <> NotFound then false, @@ -220,8 +220,7 @@ type SymbolTracker(globals: NamespaceManager, sourceFile, parent: QsQualifiedNam /// /// No scope is currently open. member this.TryAddVariableDeclartion(decl: LocalVariableDeclaration) = - if pushedScopes.Length = 0 - then InvalidOperationException "no scope is currently open" |> raise + if pushedScopes.Length = 0 then InvalidOperationException "no scope is currently open" |> raise match decl.VariableName with | InvalidName -> false, [||] @@ -238,8 +237,7 @@ type SymbolTracker(globals: NamespaceManager, sourceFile, parent: QsQualifiedNam /// No scope is currently open. /// is immutable. member internal this.UpdateQuantumDependency varName localQdep = - if pushedScopes.Length = 0 - then InvalidOperationException "no scope is currently open" |> raise + if pushedScopes.Length = 0 then InvalidOperationException "no scope is currently open" |> raise match localVariableWithName varName with | Value dict -> @@ -248,10 +246,11 @@ type SymbolTracker(globals: NamespaceManager, sourceFile, parent: QsQualifiedNam if not existing.InferredInformation.IsMutable then InvalidOperationException "cannot update information for immutable variable" |> raise else - dict.[varName] <- { existing with - InferredInformation = - { existing.InferredInformation with HasLocalQuantumDependency = localQdep } - } + dict.[varName] <- + { existing with + InferredInformation = + { existing.InferredInformation with HasLocalQuantumDependency = localQdep } + } | Null -> ArgumentException "no local variable with the given name exists on the current scope" |> raise /// returns all *local* declarations on the current scope *and* all parent scopes up to this point @@ -349,7 +348,7 @@ type SymbolTracker(globals: NamespaceManager, sourceFile, parent: QsQualifiedNam /// For each diagnostic generated during the resolution, calls the given addDiagnostics function on it. /// Returns the resolved type, *including* its range information if applicable. member internal this.ResolveType addDiagnostic (qsType: QsType) = - let resolved, errs = GlobalSymbols().ResolveType (parent, typeParameters, sourceFile) qsType + let resolved, errs = GlobalSymbols().ResolveType(parent, typeParameters, sourceFile) qsType for err in errs do addDiagnostic err diff --git a/src/QsCompiler/SyntaxProcessor/SyntaxExtensions.fs b/src/QsCompiler/SyntaxProcessor/SyntaxExtensions.fs index cfa58b4597..6e75b2e58e 100644 --- a/src/QsCompiler/SyntaxProcessor/SyntaxExtensions.fs +++ b/src/QsCompiler/SyntaxProcessor/SyntaxExtensions.fs @@ -21,7 +21,7 @@ open Microsoft.Quantum.QsCompiler.Transformations.QsCodeOutput // utils for providing information for editor commands based on syntax tokens -let rec private collectWith collector (exs: 'a seq, ts: QsType seq): QsSymbol list * QsType list * QsExpression list = +let rec private collectWith collector (exs: 'a seq, ts: QsType seq) : QsSymbol list * QsType list * QsExpression list = let (varFromExs, tsFromExs, bsFromExs) = [ for item in exs do @@ -60,7 +60,7 @@ and private VariablesInInitializer item = | QsInitializerKind.QubitTupleAllocation items -> collectWith VariablesInInitializer (items, []) | QsInitializerKind.InvalidInitializer -> [], [], [] -and private SymbolsFromExpr item: QsSymbol list * QsType list * QsExpression list = +and private SymbolsFromExpr item : QsSymbol list * QsType list * QsExpression list = match item.Expression with | QsExpressionKind.UnitValue -> [], [], [ item ] | QsExpressionKind.Identifier (id, typeArgs) -> @@ -135,7 +135,7 @@ let private SymbolsInGenerator (gen: QsSpecializationGenerator) = let private SymbolsInArgumentTuple (declName, argTuple) = let recur extract items = - let extracted: (QsSymbol list * QsType list) list = items |> List.map extract + let extracted : (QsSymbol list * QsType list) list = items |> List.map extract let getSeq select = [ @@ -463,12 +463,13 @@ let public PrintSignature (header: CallableDeclarationHeader) = sprintf "%s%s" signature annotation [] -let public VariableInfo (symbolTable: NamespaceManager) - (locals: LocalDeclarations) - (currentNS, source) - (qsSym: QsSymbol) - markdown - = +let public VariableInfo + (symbolTable: NamespaceManager) + (locals: LocalDeclarations) + (currentNS, source) + (qsSym: QsSymbol) + markdown + = match qsSym |> globalCallableResolution symbolTable (currentNS, source) with | Some decl, _ -> let kind = showAccess (printCallableKind decl.Kind) decl.Access |> toUpperFirst @@ -581,16 +582,17 @@ let public LocalVariable (locals: LocalDeclarations) (qsSym: QsSymbol) = | _ -> Null [] -let public VariableDeclaration (symbolTable: NamespaceManager) - (locals: LocalDeclarations) - (currentNS, source) - (qsSym: QsSymbol) - = +let public VariableDeclaration + (symbolTable: NamespaceManager) + (locals: LocalDeclarations) + (currentNS, source) + (qsSym: QsSymbol) + = match qsSym |> globalCallableResolution symbolTable (currentNS, source) with | Some decl, Some _ -> decl.Location - |> QsNullable<_>.Map(fun loc -> Source.assemblyOrCodeFile decl.Source, loc.Offset, loc.Range) - | _ -> LocalVariable locals qsSym |> QsNullable<_>.Map(fun (_, pos, range) -> source, pos, range) + |> QsNullable<_>.Map (fun loc -> Source.assemblyOrCodeFile decl.Source, loc.Offset, loc.Range) + | _ -> LocalVariable locals qsSym |> QsNullable<_>.Map (fun (_, pos, range) -> source, pos, range) [] let public TypeDeclaration (symbolTable: NamespaceManager) (currentNS, source) (qsType: QsType) = @@ -599,26 +601,27 @@ let public TypeDeclaration (symbolTable: NamespaceManager) (currentNS, source) ( match udt |> globalTypeResolution symbolTable (currentNS, source) with | Some decl, _ -> decl.Location - |> QsNullable<_>.Map(fun loc -> Source.assemblyOrCodeFile decl.Source, loc.Offset, loc.Range) + |> QsNullable<_>.Map (fun loc -> Source.assemblyOrCodeFile decl.Source, loc.Offset, loc.Range) | _ -> Null | _ -> Null [] -let public SymbolDeclaration (symbolTable: NamespaceManager) - (locals: LocalDeclarations) - (currentNS, source) - (qsSym: QsSymbol) - = +let public SymbolDeclaration + (symbolTable: NamespaceManager) + (locals: LocalDeclarations) + (currentNS, source) + (qsSym: QsSymbol) + = match qsSym.Symbol with // needs to be first | QsSymbolKind.Symbol _ -> match qsSym |> globalTypeResolution symbolTable (currentNS, source) with // needs to be first | Some decl, _ -> decl.Location - |> QsNullable<_>.Map(fun loc -> Source.assemblyOrCodeFile decl.Source, loc.Offset, loc.Range) + |> QsNullable<_>.Map (fun loc -> Source.assemblyOrCodeFile decl.Source, loc.Offset, loc.Range) | None, _ -> match qsSym |> globalCallableResolution symbolTable (currentNS, source) with | Some decl, _ -> decl.Location - |> QsNullable<_>.Map(fun loc -> Source.assemblyOrCodeFile decl.Source, loc.Offset, loc.Range) - | _ -> LocalVariable locals qsSym |> QsNullable<_>.Map(fun (_, pos, range) -> source, pos, range) + |> QsNullable<_>.Map (fun loc -> Source.assemblyOrCodeFile decl.Source, loc.Offset, loc.Range) + | _ -> LocalVariable locals qsSym |> QsNullable<_>.Map (fun (_, pos, range) -> source, pos, range) | _ -> Null diff --git a/src/QsCompiler/SyntaxProcessor/TreeVerification.fs b/src/QsCompiler/SyntaxProcessor/TreeVerification.fs index ff3bf2c85a..d35cce2774 100644 --- a/src/QsCompiler/SyntaxProcessor/TreeVerification.fs +++ b/src/QsCompiler/SyntaxProcessor/TreeVerification.fs @@ -149,8 +149,8 @@ let CheckDefinedTypesForCycles (definitions: ImmutableArray() let getLocation (header: TypeDeclarationHeader) = - header.Location.ValueOrApply(fun _ -> - ArgumentException "The given type header contains no location information." |> raise) + header.Location.ValueOrApply + (fun _ -> ArgumentException "The given type header contains no location information." |> raise) // for each defined type build a list of all user defined types it contains, and one with all types it is contained in (convenient for sorting later) let containedTypes = List.init definitions.Length (fun _ -> List()) @@ -166,15 +166,14 @@ let CheckDefinedTypesForCycles (definitions: ImmutableArray [ header |> (fun header -> header.Type) ] | Some parent -> if typeIndex <> parent then - if not (containedTypes.[parent].Contains typeIndex) - then containedTypes.[parent].Add typeIndex + if not (containedTypes.[parent].Contains typeIndex) then containedTypes.[parent].Add typeIndex - if not (containedIn.[typeIndex].Contains parent) - then containedIn.[typeIndex].Add parent + if not (containedIn.[typeIndex].Contains parent) then containedIn.[typeIndex].Add parent else (source, (getLocation header).Range |> QsCompilerDiagnostic.Error(ErrorCode.TypeCannotContainItself, [])) |> diagnostics.Add + [] let getTypes location (vtype: ResolvedType) (rootIndex: int option) = @@ -189,31 +188,32 @@ let CheckDefinedTypesForCycles (definitions: ImmutableArray Seq.iteri (fun typeIndex header -> - let queue = Queue() + |> Seq.iteri + (fun typeIndex header -> + let queue = Queue() - let parent = - UserDefinedType.New(header.QualifiedName.Namespace, header.QualifiedName.Name) - |> UserDefinedType - |> ResolvedType.New + let parent = + UserDefinedType.New(header.QualifiedName.Namespace, header.QualifiedName.Name) + |> UserDefinedType + |> ResolvedType.New - for entry in getTypes ((getLocation header).Offset, Source.assemblyOrCodeFile header.Source) parent None do - queue.Enqueue entry + for entry in getTypes ((getLocation header).Offset, Source.assemblyOrCodeFile header.Source) parent None do + queue.Enqueue entry - let rec search () = - if queue.Count <> 0 then - let ctypes = - getTypes - ((getLocation header).Offset, Source.assemblyOrCodeFile header.Source) - (queue.Dequeue()) - (Some typeIndex) + let rec search () = + if queue.Count <> 0 then + let ctypes = + getTypes + ((getLocation header).Offset, Source.assemblyOrCodeFile header.Source) + (queue.Dequeue()) + (Some typeIndex) - for entry in ctypes do - queue.Enqueue entry + for entry in ctypes do + queue.Enqueue entry - search () + search () - search ()) + search ()) walk_udts () @@ -245,7 +245,8 @@ let CheckDefinedTypesForCycles (definitions: ImmutableArray QsCompilerDiagnostic.Error(ErrorCode.TypeIsPartOfCyclicDeclaration, [])) |> diagnostics.Add - diagnostics.ToLookup - (fst >> snd, - (fun ((position, _), diagnostic) -> - { diagnostic with QsCompilerDiagnostic.Range = position + diagnostic.Range })) + diagnostics.ToLookup( + fst >> snd, + (fun ((position, _), diagnostic) -> + { diagnostic with QsCompilerDiagnostic.Range = position + diagnostic.Range }) + ) diff --git a/src/QsCompiler/SyntaxProcessor/TypeInference/Constraint.fs b/src/QsCompiler/SyntaxProcessor/TypeInference/Constraint.fs index 97220bb9b6..991b5291e6 100644 --- a/src/QsCompiler/SyntaxProcessor/TypeInference/Constraint.fs +++ b/src/QsCompiler/SyntaxProcessor/TypeInference/Constraint.fs @@ -23,7 +23,7 @@ type internal Constraint = module internal Constraint = /// Pretty prints a type. - let private prettyType: ResolvedType -> _ = SyntaxTreeToQsharp.Default.ToCode + let private prettyType : ResolvedType -> _ = SyntaxTreeToQsharp.Default.ToCode let types = function diff --git a/src/QsCompiler/SyntaxProcessor/TypeInference/InferenceContext.fs b/src/QsCompiler/SyntaxProcessor/TypeInference/InferenceContext.fs index 0a4a1d29a1..5f455eefa9 100644 --- a/src/QsCompiler/SyntaxProcessor/TypeInference/InferenceContext.fs +++ b/src/QsCompiler/SyntaxProcessor/TypeInference/InferenceContext.fs @@ -90,16 +90,18 @@ module private TypeContext = /// Descends into the respective children of each type, preserving the original types if the range of both the left /// and the right types do not change. let into (leftChild: ResolvedType) (rightChild: ResolvedType) context = - if leftChild.Range = context.Left.Range || rightChild.Range = context.Right.Range - then { context with Left = leftChild; Right = rightChild } - else create leftChild rightChild + if leftChild.Range = context.Left.Range || rightChild.Range = context.Right.Range then + { context with Left = leftChild; Right = rightChild } + else + create leftChild rightChild /// Descends into the respective children of each type, preserving the original types if the range of the right type /// does not change. let intoRight leftChild (rightChild: ResolvedType) context = - if rightChild.Range = context.Right.Range - then { context with Left = leftChild; Right = rightChild } - else create leftChild rightChild + if rightChild.Range = context.Right.Range then + { context with Left = leftChild; Right = rightChild } + else + create leftChild rightChild /// Swaps the left and right types. let swap context = @@ -136,7 +138,7 @@ module private Inference = |> fun functors -> functors.Contains functor /// Shows the type as a string. - let showType: ResolvedType -> _ = SyntaxTreeToQsharp.Default.ToCode + let showType : ResolvedType -> _ = SyntaxTreeToQsharp.Default.ToCode /// /// Describes a type with additional information. @@ -227,8 +229,10 @@ module private Inference = match combineCallableInfo ordering info1 info2 with | Some info -> info, [] | None -> - CallableInformation.New - (ResolvedCharacteristics.New InvalidSetExpr, InferredCallableInformation.NoInformation), + CallableInformation.New( + ResolvedCharacteristics.New InvalidSetExpr, + InferredCallableInformation.NoInformation + ), [ error ] QsTypeKind.Operation((input, output), info) |> ResolvedType.New, @@ -251,11 +255,12 @@ module private Inference = /// An infinite sequence of alphabetic strings of increasing length in alphabetical order. let letters = Seq.initInfinite ((+) 1) - |> Seq.collect (fun length -> - seq { 'a' .. 'z' } - |> Seq.map string - |> Seq.replicate length - |> Seq.reduce (fun strings -> Seq.allPairs strings >> Seq.map String.Concat)) + |> Seq.collect + (fun length -> + seq { 'a' .. 'z' } + |> Seq.map string + |> Seq.replicate length + |> Seq.reduce (fun strings -> Seq.allPairs strings >> Seq.map String.Concat)) /// /// The set of type parameters contained in the given . @@ -267,7 +272,8 @@ module private Inference = member this.OnTypeParameter param = parameters <- parameters |> Set.add param TypeParameter param - }.OnType resolvedType + } + .OnType resolvedType |> ignore parameters @@ -283,8 +289,7 @@ type InferenceContext(symbolTracker: SymbolTracker) = if occursCheck param substitution |> not then failwith "Occurs check failed." let variable = variables.[param] - if Option.isSome variable.Substitution - then failwith "Type parameter is already bound." + if Option.isSome variable.Substitution then failwith "Type parameter is already bound." variables.[param] <- { variable with Substitution = Some substitution } let rememberErrors types diagnostics = @@ -304,7 +309,7 @@ type InferenceContext(symbolTracker: SymbolTracker) = variable.Constraints |> List.map Constraint.pretty |> String.concat ", " ] - QsCompilerDiagnostic.Error (ErrorCode.AmbiguousTypeParameterResolution, args) variable.Source + QsCompilerDiagnostic.Error(ErrorCode.AmbiguousTypeParameterResolution, args) variable.Source variables |> Seq.filter (fun item -> not item.Value.HasError && Option.isNone item.Value.Substitution) @@ -319,8 +324,9 @@ type InferenceContext(symbolTracker: SymbolTracker) = let param = Seq.initInfinite (fun i -> if i = 0 then name else name + string (i - 1)) |> Seq.map (fun name -> QsTypeParameter.New(symbolTracker.Parent, name)) - |> Seq.skipWhile (fun param -> - variables.ContainsKey param || symbolTracker.DefinedTypeParameters.Contains param.TypeName) + |> Seq.skipWhile + (fun param -> + variables.ContainsKey param || symbolTracker.DefinedTypeParameters.Contains param.TypeName) |> Seq.head let variable = @@ -419,19 +425,25 @@ type InferenceContext(symbolTracker: SymbolTracker) = [] context.UnifyByOrdering(ordering, types |> TypeContext.swap |> TypeContext.intoRight in2 in1) - @ context.UnifyByOrdering - (ordering, types |> TypeContext.intoRight (context.Resolve out1) (context.Resolve out2)) + @ context.UnifyByOrdering( + ordering, + types |> TypeContext.intoRight (context.Resolve out1) (context.Resolve out2) + ) @ errors | QsTypeKind.Function (in1, out1), QsTypeKind.Function (in2, out2) -> context.UnifyByOrdering(ordering, types |> TypeContext.swap |> TypeContext.intoRight in2 in1) - @ context.UnifyByOrdering - (ordering, types |> TypeContext.intoRight (context.Resolve out1) (context.Resolve out2)) + @ context.UnifyByOrdering( + ordering, + types |> TypeContext.intoRight (context.Resolve out1) (context.Resolve out2) + ) | QsTypeKind.Operation ((in1, out1), _), QsTypeKind.Function (in2, out2) | QsTypeKind.Function (in1, out1), QsTypeKind.Operation ((in2, out2), _) -> error :: context.UnifyByOrdering(ordering, types |> TypeContext.swap |> TypeContext.intoRight in2 in1) - @ context.UnifyByOrdering - (ordering, types |> TypeContext.intoRight (context.Resolve out1) (context.Resolve out2)) + @ context.UnifyByOrdering( + ordering, + types |> TypeContext.intoRight (context.Resolve out1) (context.Resolve out2) + ) | InvalidType, _ | MissingType, _ | _, InvalidType @@ -449,7 +461,7 @@ type InferenceContext(symbolTracker: SymbolTracker) = | Constraint.Adjointable -> match resolvedType.Resolution with | QsTypeKind.Operation (_, info) when hasFunctor Adjoint info -> [] - | _ -> [ QsCompilerDiagnostic.Error (ErrorCode.InvalidAdjointApplication, []) range ] + | _ -> [ QsCompilerDiagnostic.Error(ErrorCode.InvalidAdjointApplication, []) range ] | Callable (input, output) -> match resolvedType.Resolution with | QsTypeKind.Operation _ -> @@ -459,7 +471,7 @@ type InferenceContext(symbolTracker: SymbolTracker) = context.Unify(QsTypeKind.Function(input, output) |> ResolvedType.New, resolvedType) | _ -> [ - QsCompilerDiagnostic.Error (ErrorCode.ExpectingCallableExpr, [ showType resolvedType ]) range + QsCompilerDiagnostic.Error(ErrorCode.ExpectingCallableExpr, [ showType resolvedType ]) range ] | CanGenerateFunctors functors -> match resolvedType.Resolution with @@ -471,12 +483,12 @@ type InferenceContext(symbolTracker: SymbolTracker) = ErrorCode.MissingFunctorForAutoGeneration, [ missing |> Seq.map string |> String.concat "," ] [ - if not info.Characteristics.AreInvalid && Set.isEmpty missing |> not - then QsCompilerDiagnostic.Error error range + if not info.Characteristics.AreInvalid && Set.isEmpty missing |> not then + QsCompilerDiagnostic.Error error range ] | _ -> [] | Constraint.Controllable controlled -> - let error = QsCompilerDiagnostic.Error (ErrorCode.InvalidControlledApplication, []) range + let error = QsCompilerDiagnostic.Error(ErrorCode.InvalidControlledApplication, []) range match resolvedType.Resolution with | QsTypeKind.Operation ((input, output), info) -> @@ -496,10 +508,10 @@ type InferenceContext(symbolTracker: SymbolTracker) = | _ -> [ error ] | Equatable -> [ - if Option.isNone resolvedType.supportsEqualityComparison - then QsCompilerDiagnostic.Error - (ErrorCode.InvalidTypeInEqualityComparison, [ showType resolvedType ]) - range + if Option.isNone resolvedType.supportsEqualityComparison then + QsCompilerDiagnostic.Error + (ErrorCode.InvalidTypeInEqualityComparison, [ showType resolvedType ]) + range ] | HasPartialApplication (missing, result) -> match resolvedType.Resolution with @@ -509,7 +521,7 @@ type InferenceContext(symbolTracker: SymbolTracker) = context.Unify(result, QsTypeKind.Operation((missing, output), info) |> ResolvedType.New) | _ -> [ - QsCompilerDiagnostic.Error (ErrorCode.ExpectingCallableExpr, [ showType resolvedType ]) range + QsCompilerDiagnostic.Error(ErrorCode.ExpectingCallableExpr, [ showType resolvedType ]) range ] | Indexed (index, item) -> let index = context.Resolve index @@ -525,38 +537,38 @@ type InferenceContext(symbolTracker: SymbolTracker) = ] | _ -> [ - QsCompilerDiagnostic.Error (ErrorCode.ItemAccessForNonArray, [ showType resolvedType ]) range + QsCompilerDiagnostic.Error(ErrorCode.ItemAccessForNonArray, [ showType resolvedType ]) range ] | Integral -> [ - if resolvedType.Resolution <> Int && resolvedType.Resolution <> BigInt - then QsCompilerDiagnostic.Error (ErrorCode.ExpectingIntegralExpr, [ showType resolvedType ]) range + if resolvedType.Resolution <> Int && resolvedType.Resolution <> BigInt then + QsCompilerDiagnostic.Error(ErrorCode.ExpectingIntegralExpr, [ showType resolvedType ]) range ] | Iterable item -> match resolvedType.supportsIteration with | Some actualItem -> context.Unify(item, actualItem) | None -> [ - QsCompilerDiagnostic.Error (ErrorCode.ExpectingIterableExpr, [ showType resolvedType ]) range + QsCompilerDiagnostic.Error(ErrorCode.ExpectingIterableExpr, [ showType resolvedType ]) range ] | Numeric -> [ - if Option.isNone resolvedType.supportsArithmetic - then QsCompilerDiagnostic.Error (ErrorCode.InvalidTypeInArithmeticExpr, [ showType resolvedType ]) range + if Option.isNone resolvedType.supportsArithmetic then + QsCompilerDiagnostic.Error(ErrorCode.InvalidTypeInArithmeticExpr, [ showType resolvedType ]) range ] | Semigroup -> [ - if Option.isNone resolvedType.supportsConcatenation && Option.isNone resolvedType.supportsArithmetic - then QsCompilerDiagnostic.Error (ErrorCode.InvalidTypeForConcatenation, [ showType resolvedType ]) range + if Option.isNone resolvedType.supportsConcatenation && Option.isNone resolvedType.supportsArithmetic then + QsCompilerDiagnostic.Error(ErrorCode.InvalidTypeForConcatenation, [ showType resolvedType ]) range ] | Wrapped item -> match resolvedType.Resolution with | UserDefinedType udt -> - let actualItem = symbolTracker.GetUnderlyingType (fun _ -> ()) udt + let actualItem = symbolTracker.GetUnderlyingType(fun _ -> ()) udt context.Unify(item, actualItem) | _ -> [ - QsCompilerDiagnostic.Error (ErrorCode.ExpectingUserDefinedType, [ showType resolvedType ]) range + QsCompilerDiagnostic.Error(ErrorCode.ExpectingUserDefinedType, [ showType resolvedType ]) range ] /// diff --git a/src/QsCompiler/Tests.Compiler/AccessModifierTests.fs b/src/QsCompiler/Tests.Compiler/AccessModifierTests.fs index e5553e4079..0463c0c96e 100644 --- a/src/QsCompiler/Tests.Compiler/AccessModifierTests.fs +++ b/src/QsCompiler/Tests.Compiler/AccessModifierTests.fs @@ -3,18 +3,18 @@ namespace Microsoft.Quantum.QsCompiler.Testing -open System.Collections.Generic -open System.IO -open Microsoft.Quantum.QsCompiler.DataTypes open Microsoft.Quantum.QsCompiler.Diagnostics open Microsoft.Quantum.QsCompiler.SyntaxExtensions open Microsoft.Quantum.QsCompiler.SyntaxTree +open System.Collections.Generic +open System.IO open Xunit - type AccessModifierTests() = - inherit CompilerTests(CompilerTests.Compile - ("TestCases", [ "AccessModifiers.qs" ], [ File.ReadAllLines("ReferenceTargets.txt").[1] ])) + inherit CompilerTests(AccessModifierTests.Compile()) + + static member private Compile() = + CompilerTests.Compile("TestCases", [ "AccessModifiers.qs" ], [ File.ReadAllLines("ReferenceTargets.txt").[1] ]) member private this.Expect name (diagnostics: IEnumerable) = let ns = "Microsoft.Quantum.Testing.AccessModifiers" diff --git a/src/QsCompiler/Tests.Compiler/CallGraphTests.fs b/src/QsCompiler/Tests.Compiler/CallGraphTests.fs index 32616ebf09..fc1dbdecd5 100644 --- a/src/QsCompiler/Tests.Compiler/CallGraphTests.fs +++ b/src/QsCompiler/Tests.Compiler/CallGraphTests.fs @@ -24,18 +24,24 @@ type CallGraphTests(output: ITestOutputHelper) = let compilationManager = new CompilationUnitManager(new Action(fun ex -> failwith ex.Message)) let compilationManagerExe = - new CompilationUnitManager(Action<_>(fun ex -> failwith ex.Message), - null, - false, - FullComputation, - isExecutable = true) + new CompilationUnitManager( + Action<_>(fun ex -> failwith ex.Message), + null, + false, + FullComputation, + isExecutable = true + ) let getTempFile () = new Uri(Path.GetFullPath(Path.GetRandomFileName())) let getManager uri content = - CompilationUnitManager.InitializeFileManager - (uri, content, compilationManager.PublishDiagnostics, compilationManager.LogException) + CompilationUnitManager.InitializeFileManager( + uri, + content, + compilationManager.PublishDiagnostics, + compilationManager.LogException + ) // Adds Core to the compilation do @@ -54,8 +60,10 @@ type CallGraphTests(output: ITestOutputHelper) = let qualifiedName = { Namespace = Signatures.PopulateCallGraphNS; Name = name } let res = - paramRes.ToImmutableDictionary - ((fun kvp -> (qualifiedName, fst kvp)), (fun kvp -> ResolvedType.New(snd kvp))) + paramRes.ToImmutableDictionary( + (fun kvp -> (qualifiedName, fst kvp)), + (fun kvp -> ResolvedType.New(snd kvp)) + ) ConcreteCallGraphNode(qualifiedName, specKind, res) @@ -94,20 +102,25 @@ type CallGraphTests(output: ITestOutputHelper) = let got = compilationDataStructures.Diagnostics() |> Seq.filter (fun d -> d.Severity = Nullable DiagnosticSeverity.Error) - |> Seq.choose (fun d -> - match Diagnostics.TryGetCode d.Code with - | true, code -> Some code - | false, _ -> None) + |> Seq.choose + (fun d -> + match Diagnostics.TryGetCode d.Code with + | true, code -> Some code + | false, _ -> None) let codeMismatch = expected.ToImmutableHashSet().SymmetricExcept got let gotLookup = got.ToLookup(new Func<_, _>(id)) let expectedLookup = expected.ToLookup(new Func<_, _>(id)) let nrMismatch = gotLookup.Where(fun g -> g.Count() <> expectedLookup.[g.Key].Count()) - Assert.False - (codeMismatch.Any() || nrMismatch.Any(), - sprintf "%A code mismatch\nexpected: %s\ngot: %s" DiagnosticSeverity.Error (String.Join(", ", expected)) - (String.Join(", ", got))) + Assert.False( + codeMismatch.Any() || nrMismatch.Any(), + sprintf + "%A code mismatch\nexpected: %s\ngot: %s" + DiagnosticSeverity.Error + (String.Join(", ", expected)) + (String.Join(", ", got)) + ) let CompileTest testNumber fileName = let srcChunks = ReadAndChunkSourceFile fileName @@ -133,7 +146,8 @@ type CallGraphTests(output: ITestOutputHelper) = let CompileInvalidCycleTest testNumber expected = let errors = expected - |> Seq.choose (function + |> Seq.choose + (function | Error error -> Some error | _ -> None) @@ -172,17 +186,19 @@ type CallGraphTests(output: ITestOutputHelper) = let expected = expectedCycles |> DecorateWithNamespace Signatures.CycleDetectionNS let actual = actualCycles |> (Seq.map ((Seq.map (fun x -> x.CallableName)) >> Seq.toList) >> Seq.toList) - Assert.True - (actual.Length = expected.Length, - sprintf "Expected call graph to have %i cycle(s), but found %i cycle(s)" expected.Length actual.Length) + Assert.True( + actual.Length = expected.Length, + sprintf "Expected call graph to have %i cycle(s), but found %i cycle(s)" expected.Length actual.Length + ) let cycleToString (cycle: QsQualifiedName list) = String.Join(" -> ", List.map (fun node -> node.ToString()) cycle) for cycle in expected do - Assert.True - (List.exists (CyclicEquivalence cycle) actual, - sprintf "Did not find expected cycle: %s" (cycleToString cycle)) + Assert.True( + List.exists (CyclicEquivalence cycle) actual, + sprintf "Did not find expected cycle: %s" (cycleToString cycle) + ) let AssertExpectedDirectDependencies nameFrom nameToList (givenGraph: CallGraph) = let strToNode name = @@ -194,8 +210,10 @@ type CallGraphTests(output: ITestOutputHelper) = for nameTo in nameToList do let expectedNode = strToNode nameTo - Assert.True - (dependencies.Contains(expectedNode), sprintf "Expected %s to take dependency on %s." nameFrom nameTo) + Assert.True( + dependencies.Contains(expectedNode), + sprintf "Expected %s to take dependency on %s." nameFrom nameTo + ) let AssertInGraph (givenGraph: CallGraph) name = let nodeName = { Namespace = Signatures.PopulateCallGraphNS; Name = name } @@ -208,16 +226,24 @@ type CallGraphTests(output: ITestOutputHelper) = Assert.False(found, sprintf "Expected %s to not be in the call graph." name) let AssertInConcreteGraph (givenGraph: ConcreteCallGraph) node = - Assert.True - (givenGraph.Nodes.Contains(node), - sprintf "Expected %A (%A) to be in the call graph with the following type parameter resolutions:\n%A" - node.CallableName node.Kind node.ParamResolutions) + Assert.True( + givenGraph.Nodes.Contains(node), + sprintf + "Expected %A (%A) to be in the call graph with the following type parameter resolutions:\n%A" + node.CallableName + node.Kind + node.ParamResolutions + ) let AssertNotInConcreteGraph (givenGraph: ConcreteCallGraph) node = - Assert.False - (givenGraph.Nodes.Contains(node), - sprintf "Expected %A (%A) to not be in the call graph with the following type parameter resolutions:\n%A" - node.CallableName node.Kind node.ParamResolutions) + Assert.False( + givenGraph.Nodes.Contains(node), + sprintf + "Expected %A (%A) to not be in the call graph with the following type parameter resolutions:\n%A" + node.CallableName + node.Kind + node.ParamResolutions + ) // ToDo: Add tests for cycle validation once that is implemented. @@ -227,7 +253,7 @@ type CallGraphTests(output: ITestOutputHelper) = let graph = PopulateCallGraphWithExe 1 |> BuildTrimmedGraph [ "Main", [ "Foo"; "Bar" ]; "Foo", []; "Bar", [ "Baz" ]; "Baz", [] ] - |> List.map (fun x -> AssertExpectedDirectDependencies (fst x) (snd x) graph) + |> List.map (fun x -> AssertExpectedDirectDependencies(fst x) (snd x) graph) |> ignore [] @@ -236,7 +262,7 @@ type CallGraphTests(output: ITestOutputHelper) = let graph = PopulateCallGraphWithExe 2 |> BuildTrimmedGraph [ "Main", [ "Foo" ]; "Foo", [] ] - |> List.map (fun x -> AssertExpectedDirectDependencies (fst x) (snd x) graph) + |> List.map (fun x -> AssertExpectedDirectDependencies(fst x) (snd x) graph) |> ignore [ "Bar"; "Baz" ] |> List.map (AssertNotInGraph graph) |> ignore @@ -247,7 +273,7 @@ type CallGraphTests(output: ITestOutputHelper) = let graph = PopulateCallGraphWithExe 3 |> BuildTrimmedGraph [ "Main", [ "Foo" ]; "Foo", [] ] - |> List.map (fun x -> AssertExpectedDirectDependencies (fst x) (snd x) graph) + |> List.map (fun x -> AssertExpectedDirectDependencies(fst x) (snd x) graph) |> ignore AssertNotInGraph graph "NotCalled" @@ -258,7 +284,7 @@ type CallGraphTests(output: ITestOutputHelper) = let graph = PopulateCallGraph 4 |> CallGraph [ "Main", [ "Foo" ]; "Foo", [] ] - |> List.map (fun x -> AssertExpectedDirectDependencies (fst x) (snd x) graph) + |> List.map (fun x -> AssertExpectedDirectDependencies(fst x) (snd x) graph) |> ignore AssertInGraph graph "NotCalled" @@ -269,7 +295,7 @@ type CallGraphTests(output: ITestOutputHelper) = let graph = PopulateCallGraph 5 |> CallGraph [ "Main", [ "Foo" ]; "Foo", []; "Bar", [ "Baz" ]; "Baz", [] ] - |> List.map (fun x -> AssertExpectedDirectDependencies (fst x) (snd x) graph) + |> List.map (fun x -> AssertExpectedDirectDependencies(fst x) (snd x) graph) |> ignore [] @@ -284,7 +310,7 @@ type CallGraphTests(output: ITestOutputHelper) = let graph = PopulateCallGraphWithExe 7 |> BuildTrimmedGraph [ "Main", [ "Foo" ]; "Foo", [ "Main" ] ] - |> List.map (fun x -> AssertExpectedDirectDependencies (fst x) (snd x) graph) + |> List.map (fun x -> AssertExpectedDirectDependencies(fst x) (snd x) graph) |> ignore [] @@ -293,7 +319,7 @@ type CallGraphTests(output: ITestOutputHelper) = let graph = PopulateCallGraphWithExe 8 |> BuildTrimmedGraph [ "Main", [ "Foo" ]; "Foo", [] ] - |> List.map (fun x -> AssertExpectedDirectDependencies (fst x) (snd x) graph) + |> List.map (fun x -> AssertExpectedDirectDependencies(fst x) (snd x) graph) |> ignore AssertNotInGraph graph "Bar" @@ -304,7 +330,7 @@ type CallGraphTests(output: ITestOutputHelper) = let graph = PopulateCallGraphWithExe 9 |> BuildTrimmedGraph [ "Main1", [ "Foo" ]; "Main2", [ "Bar" ]; "Foo", []; "Bar", [] ] - |> List.map (fun x -> AssertExpectedDirectDependencies (fst x) (snd x) graph) + |> List.map (fun x -> AssertExpectedDirectDependencies(fst x) (snd x) graph) |> ignore [] @@ -313,7 +339,7 @@ type CallGraphTests(output: ITestOutputHelper) = let graph = PopulateCallGraphWithExe 10 |> BuildTrimmedGraph [ "Test", [ "Foo" ]; "Foo", [] ] - |> List.map (fun x -> AssertExpectedDirectDependencies (fst x) (snd x) graph) + |> List.map (fun x -> AssertExpectedDirectDependencies(fst x) (snd x) graph) |> ignore AssertNotInGraph graph "Bar" @@ -329,7 +355,7 @@ type CallGraphTests(output: ITestOutputHelper) = "Test1", [ "Zip" ] "Test2", [ "Zap" ] ] - |> List.map (fun x -> AssertExpectedDirectDependencies (fst x) (snd x) graph) + |> List.map (fun x -> AssertExpectedDirectDependencies(fst x) (snd x) graph) |> ignore AssertNotInGraph graph "Unused" @@ -470,14 +496,17 @@ type CallGraphTests(output: ITestOutputHelper) = let dependencies = graph.GetDirectDependencies FooAdj - Assert.True - (dependencies.Contains(Foo), "Expected adjoint specialization to take dependency on body specialization.") + Assert.True( + dependencies.Contains(Foo), + "Expected adjoint specialization to take dependency on body specialization." + ) let dependencies = graph.GetDirectDependencies FooCtlAdj - Assert.True - (dependencies.Contains(FooCtl), - "Expected controlled-adjoint specialization to take dependency on controlled specialization.") + Assert.True( + dependencies.Contains(FooCtl), + "Expected controlled-adjoint specialization to take dependency on controlled specialization." + ) [] [] @@ -490,10 +519,11 @@ type CallGraphTests(output: ITestOutputHelper) = for node in graph.Nodes do let unresolvedTypeParameters = node.ParamResolutions - |> Seq.choose (fun res -> - match res.Value.Resolution with - | TypeParameter _ -> Some(res.Key) - | _ -> None) + |> Seq.choose + (fun res -> + match res.Value.Resolution with + | TypeParameter _ -> Some(res.Key) + | _ -> None) Assert.Empty unresolvedTypeParameters diff --git a/src/QsCompiler/Tests.Compiler/CapabilityInferenceTests.fs b/src/QsCompiler/Tests.Compiler/CapabilityInferenceTests.fs index 571200f5c4..8cd2f128ac 100644 --- a/src/QsCompiler/Tests.Compiler/CapabilityInferenceTests.fs +++ b/src/QsCompiler/Tests.Compiler/CapabilityInferenceTests.fs @@ -9,10 +9,11 @@ open Xunit /// A mapping of all callables in the capability verification tests, after inferring capabilities. let private callables = - CompilerTests.Compile - ("TestCases", - [ "CapabilityTests/Verification.qs"; "CapabilityTests/Inference.qs" ], - references = [ (File.ReadAllLines "ReferenceTargets.txt").[1] ]) + CompilerTests.Compile( + "TestCases", + [ "CapabilityTests/Verification.qs"; "CapabilityTests/Inference.qs" ], + references = [ (File.ReadAllLines "ReferenceTargets.txt").[1] ] + ) |> fun compilation -> compilation.BuiltCompilation |> CapabilityInference.InferCapabilities |> fun compilation -> compilation.Namespaces diff --git a/src/QsCompiler/Tests.Compiler/CapabilityVerificationTests.fs b/src/QsCompiler/Tests.Compiler/CapabilityVerificationTests.fs index e13ff6dd64..9204d8652b 100644 --- a/src/QsCompiler/Tests.Compiler/CapabilityVerificationTests.fs +++ b/src/QsCompiler/Tests.Compiler/CapabilityVerificationTests.fs @@ -11,11 +11,12 @@ open Xunit /// Compiles the capability verification test cases using the given capability. let private compile capability = - CompilerTests.Compile - ("TestCases", - [ "CapabilityTests/Verification.qs"; "CapabilityTests/Inference.qs" ], - references = [ File.ReadAllLines("ReferenceTargets.txt").[1] ], - capability = capability) + CompilerTests.Compile( + "TestCases", + [ "CapabilityTests/Verification.qs"; "CapabilityTests/Inference.qs" ], + references = [ File.ReadAllLines("ReferenceTargets.txt").[1] ], + capability = capability + ) /// The FullComputation capability tester. let private fullComputation = compile FullComputation |> CompilerTests @@ -85,10 +86,10 @@ let ``BasicQuantumFunctionality restricts all Result comparison`` () = "SetReusedName" |> expect basicQuantumFunctionality - [ - Error ErrorCode.LocalVariableAlreadyExists - Error ErrorCode.UnsupportedResultComparison - ] + [ + Error ErrorCode.LocalVariableAlreadyExists + Error ErrorCode.UnsupportedResultComparison + ] [ "ResultTuple"; "ResultArray" ] |> List.iter (expect fullComputation [ Error ErrorCode.InvalidTypeInEqualityComparison ]) @@ -128,11 +129,11 @@ let ``BasicMeasurementFeedback restricts non-local mutable set from Result if`` "SetReusedName" |> expect basicMeasurementFeedback - [ - Error ErrorCode.LocalVariableAlreadyExists - Error ErrorCode.SetInResultConditionedBlock - Error ErrorCode.SetInResultConditionedBlock - ] + [ + Error ErrorCode.LocalVariableAlreadyExists + Error ErrorCode.SetInResultConditionedBlock + Error ErrorCode.SetInResultConditionedBlock + ] [] let ``BasicMeasurementFeedback restricts non-local mutable set from Result elif`` () = @@ -178,53 +179,56 @@ let ``BasicMeasurementFeedback restricts library calls and references`` () = |> List.iter (expect basicMeasurementFeedback []) [ "CallLibraryFull"; "ReferenceLibraryFull" ] - |> List.iter - (expect + |> List.iter ( + expect basicMeasurementFeedback - [ - Error ErrorCode.UnsupportedCallableCapability - Warning WarningCode.ResultComparisonNotInOperationIf - Warning WarningCode.ReturnInResultConditionedBlock - Warning WarningCode.SetInResultConditionedBlock - ]) + [ + Error ErrorCode.UnsupportedCallableCapability + Warning WarningCode.ResultComparisonNotInOperationIf + Warning WarningCode.ReturnInResultConditionedBlock + Warning WarningCode.SetInResultConditionedBlock + ] + ) "CallLibraryFullWithNestedCall" |> expect basicMeasurementFeedback - [ - Error ErrorCode.UnsupportedCallableCapability - Warning WarningCode.ResultComparisonNotInOperationIf - Warning WarningCode.UnsupportedCallableCapability - ] + [ + Error ErrorCode.UnsupportedCallableCapability + Warning WarningCode.ResultComparisonNotInOperationIf + Warning WarningCode.UnsupportedCallableCapability + ] [] let ``BasicQuantumFunctionality restricts library calls and references`` () = [ "CallLibraryBqf"; "ReferenceLibraryBqf" ] |> List.iter (expect basicQuantumFunctionality []) [ "CallLibraryBmf"; "ReferenceLibraryBmf" ] - |> List.iter - (expect + |> List.iter ( + expect basicQuantumFunctionality - [ - Error ErrorCode.UnsupportedCallableCapability - Warning WarningCode.UnsupportedResultComparison - ]) + [ + Error ErrorCode.UnsupportedCallableCapability + Warning WarningCode.UnsupportedResultComparison + ] + ) [ "CallLibraryFull"; "ReferenceLibraryFull" ] - |> List.iter - (expect + |> List.iter ( + expect basicQuantumFunctionality - [ - Error ErrorCode.UnsupportedCallableCapability - Warning WarningCode.UnsupportedResultComparison - Warning WarningCode.UnsupportedResultComparison - ]) + [ + Error ErrorCode.UnsupportedCallableCapability + Warning WarningCode.UnsupportedResultComparison + Warning WarningCode.UnsupportedResultComparison + ] + ) "CallLibraryBmfWithNestedCall" |> expect basicQuantumFunctionality - [ - Error ErrorCode.UnsupportedCallableCapability - Warning WarningCode.UnsupportedResultComparison - Warning WarningCode.UnsupportedCallableCapability - ] + [ + Error ErrorCode.UnsupportedCallableCapability + Warning WarningCode.UnsupportedResultComparison + Warning WarningCode.UnsupportedCallableCapability + ] diff --git a/src/QsCompiler/Tests.Compiler/ClassicalControlTests.fs b/src/QsCompiler/Tests.Compiler/ClassicalControlTests.fs index 087c4e7857..16c34d81ed 100644 --- a/src/QsCompiler/Tests.Compiler/ClassicalControlTests.fs +++ b/src/QsCompiler/Tests.Compiler/ClassicalControlTests.fs @@ -24,8 +24,12 @@ type ClassicalControlTests() = new Uri(Path.GetFullPath(Path.GetRandomFileName())) let getManager uri content = - CompilationUnitManager.InitializeFileManager - (uri, content, compilationManager.PublishDiagnostics, compilationManager.LogException) + CompilationUnitManager.InitializeFileManager( + uri, + content, + compilationManager.PublishDiagnostics, + compilationManager.LogException + ) let ReadAndChunkSourceFile fileName = let sourceInput = Path.Combine("TestCases", fileName) |> File.ReadAllText @@ -96,9 +100,10 @@ type ClassicalControlTests() = let regexMatch = Regex.Match(input, regex) - if regexMatch.Success - then (true, regexMatch.Groups.[3].Value, regexMatch.Groups.[4].Value) - else (false, "", "") + if regexMatch.Success then + (true, regexMatch.Groups.[3].Value, regexMatch.Groups.[4].Value) + else + (false, "", "") let MakeApplicationRegex (opName: QsQualifiedName) = let call = sprintf @"(%s\.)?%s" <| Regex.Escape opName.Namespace <| Regex.Escape opName.Name @@ -110,9 +115,10 @@ type ClassicalControlTests() = let regexMatch = Regex.Match(input, sprintf @"^\s*%s,\s*%s$" <| Regex.Escape resultVar <| MakeApplicationRegex opName) - if regexMatch.Success - then (true, regexMatch.Groups.[3].Value, regexMatch.Groups.[4].Value) - else (false, "", "") + if regexMatch.Success then + (true, regexMatch.Groups.[3].Value, regexMatch.Groups.[4].Value) + else + (false, "", "") let IsApplyIfElseArgsMatch input resultVar (opName1: QsQualifiedName) (opName2: QsQualifiedName) = let ApplyIfElseRegex = @@ -140,9 +146,10 @@ type ClassicalControlTests() = Seq.forall (fun (i, ns, name) -> CheckIfLineIsCall ns name lines.[i] |> (fun (x, _, _) -> x)) calls let AssertSpecializationHasCalls specialization calls = - Assert.True - (CheckIfSpecializationHasCalls specialization calls, - sprintf "Callable %O(%A) did not have expected content" specialization.Parent specialization.Kind) + Assert.True( + CheckIfSpecializationHasCalls specialization calls, + sprintf "Callable %O(%A) did not have expected content" specialization.Parent specialization.Kind + ) let ExpandBuiltInQualifiedSymbol (i, (builtin: BuiltIn)) = (i, builtin.FullName.Namespace, builtin.FullName.Name) @@ -190,9 +197,10 @@ type ClassicalControlTests() = let original = GetCallableWithName compilation Signatures.ClassicalControlNS "Foo" |> GetBodyFromCallable let lines = original |> GetLinesFromSpecialization - Assert.True - (2 = Seq.length lines, - sprintf "Callable %O(%A) did not have the expected number of statements" original.Parent original.Kind) + Assert.True( + 2 = Seq.length lines, + sprintf "Callable %O(%A) did not have the expected number of statements" original.Parent original.Kind + ) let (success, targs, args) = CheckIfLineIsCall BuiltIn.ApplyIfElseR.FullName.Namespace BuiltIn.ApplyIfElseR.FullName.Name lines.[1] @@ -216,36 +224,37 @@ type ClassicalControlTests() = let adjMatch = lazy (if hasAdjoint then - match call.Specializations |> Seq.tryFind (fun x -> x.Kind = QsSpecializationKind.QsAdjoint) with - | None -> false - | Some x -> - match x.Implementation with - | SpecializationImplementation.Generated gen -> - gen = QsGeneratorDirective.Invert || gen = QsGeneratorDirective.SelfInverse - | SpecializationImplementation.Provided _ -> true - | _ -> false + match call.Specializations |> Seq.tryFind (fun x -> x.Kind = QsSpecializationKind.QsAdjoint) with + | None -> false + | Some x -> + match x.Implementation with + | SpecializationImplementation.Generated gen -> + gen = QsGeneratorDirective.Invert || gen = QsGeneratorDirective.SelfInverse + | SpecializationImplementation.Provided _ -> true + | _ -> false else true) let ctlMatch = lazy (if hasControlled then - match call.Specializations |> Seq.tryFind (fun x -> x.Kind = QsSpecializationKind.QsControlled) with - | None -> false - | Some x -> - match x.Implementation with - | SpecializationImplementation.Generated gen -> gen = QsGeneratorDirective.Distribute - | SpecializationImplementation.Provided _ -> true - | _ -> false + match call.Specializations |> Seq.tryFind (fun x -> x.Kind = QsSpecializationKind.QsControlled) with + | None -> false + | Some x -> + match x.Implementation with + | SpecializationImplementation.Generated gen -> gen = QsGeneratorDirective.Distribute + | SpecializationImplementation.Provided _ -> true + | _ -> false else true) charMatch.Value && adjMatch.Value && ctlMatch.Value let AssertCallSupportsFunctors expectedFunctors call = - Assert.True - (DoesCallSupportFunctors expectedFunctors call, - sprintf "Callable %O did not support the expected functors" call.FullName) + Assert.True( + DoesCallSupportFunctors expectedFunctors call, + sprintf "Callable %O did not support the expected functors" call.FullName + ) [] [] @@ -339,9 +348,10 @@ type ClassicalControlTests() = let lines = original |> GetLinesFromSpecialization - Assert.True - (2 = Seq.length lines, - sprintf "Callable %O(%A) did not have the expected number of statements" original.Parent original.Kind) + Assert.True( + 2 = Seq.length lines, + sprintf "Callable %O(%A) did not have the expected number of statements" original.Parent original.Kind + ) let (success, _, args) = CheckIfLineIsCall BuiltIn.ApplyIfElseR.FullName.Namespace BuiltIn.ApplyIfElseR.FullName.Name lines.[1] @@ -355,9 +365,10 @@ type ClassicalControlTests() = let lines = generated |> GetLinesFromSpecialization - Assert.True - (1 = Seq.length lines, - sprintf "Callable %O(%A) did not have the expected number of statements" generated.Parent generated.Kind) + Assert.True( + 1 = Seq.length lines, + sprintf "Callable %O(%A) did not have the expected number of statements" generated.Parent generated.Kind + ) let (success, _, args) = CheckIfLineIsCall BuiltIn.ApplyIfElseR.FullName.Namespace BuiltIn.ApplyIfElseR.FullName.Name lines.[0] @@ -383,9 +394,10 @@ type ClassicalControlTests() = let lines = original |> GetLinesFromSpecialization - Assert.True - (2 = Seq.length lines, - sprintf "Callable %O(%A) did not have the expected number of statements" original.Parent original.Kind) + Assert.True( + 2 = Seq.length lines, + sprintf "Callable %O(%A) did not have the expected number of statements" original.Parent original.Kind + ) let (success, _, args) = CheckIfLineIsCall BuiltIn.ApplyIfElseR.FullName.Namespace BuiltIn.ApplyIfElseR.FullName.Name lines.[1] @@ -399,9 +411,10 @@ type ClassicalControlTests() = let lines = generated |> GetLinesFromSpecialization - Assert.True - (1 = Seq.length lines, - sprintf "Callable %O(%A) did not have the expected number of statements" generated.Parent generated.Kind) + Assert.True( + 1 = Seq.length lines, + sprintf "Callable %O(%A) did not have the expected number of statements" generated.Parent generated.Kind + ) let (success, _, args) = CheckIfLineIsCall BuiltIn.ApplyIfElseR.FullName.Namespace BuiltIn.ApplyIfElseR.FullName.Name lines.[0] @@ -427,9 +440,10 @@ type ClassicalControlTests() = let lines = original |> GetLinesFromSpecialization - Assert.True - (2 = Seq.length lines, - sprintf "Callable %O(%A) did not have the expected number of statements" original.Parent original.Kind) + Assert.True( + 2 = Seq.length lines, + sprintf "Callable %O(%A) did not have the expected number of statements" original.Parent original.Kind + ) let (success, _, args) = CheckIfLineIsCall BuiltIn.ApplyIfElseR.FullName.Namespace BuiltIn.ApplyIfElseR.FullName.Name lines.[1] @@ -443,9 +457,10 @@ type ClassicalControlTests() = let lines = generated |> GetLinesFromSpecialization - Assert.True - (1 = Seq.length lines, - sprintf "Callable %O(%A) did not have the expected number of statements" generated.Parent generated.Kind) + Assert.True( + 1 = Seq.length lines, + sprintf "Callable %O(%A) did not have the expected number of statements" generated.Parent generated.Kind + ) let (success, _, args) = CheckIfLineIsCall BuiltIn.ApplyIfElseR.FullName.Namespace BuiltIn.ApplyIfElseR.FullName.Name lines.[0] @@ -457,15 +472,18 @@ type ClassicalControlTests() = [] [] - member this.``Don't Lift Functions``() = CompileClassicalControlTest 13 |> ignore + member this.``Don't Lift Functions``() = + CompileClassicalControlTest 13 |> ignore [] [] - member this.``Lift Self-Contained Mutable``() = CompileClassicalControlTest 14 |> ignore + member this.``Lift Self-Contained Mutable``() = + CompileClassicalControlTest 14 |> ignore [] [] - member this.``Don't Lift General Mutable``() = CompileClassicalControlTest 15 |> ignore + member this.``Don't Lift General Mutable``() = + CompileClassicalControlTest 15 |> ignore [] [] @@ -482,7 +500,8 @@ type ClassicalControlTests() = let GetTypeParams call = call.Signature.TypeParameters - |> Seq.choose (function + |> Seq.choose + (function | ValidName str -> Some str | InvalidName -> None) @@ -504,9 +523,10 @@ type ClassicalControlTests() = let (success, _, args) = CheckIfLineIsCall BuiltIn.ApplyIfZero.FullName.Namespace BuiltIn.ApplyIfZero.FullName.Name lines.[1] - Assert.True - (success, - sprintf "Callable %O(%A) did not have expected content" original.FullName QsSpecializationKind.QsBody) + Assert.True( + success, + sprintf "Callable %O(%A) did not have expected content" original.FullName QsSpecializationKind.QsBody + ) let (success, typeArgs, _) = IsApplyIfArgMatch args "r" generated.FullName Assert.True(success, sprintf "ApplyIfZero did not have the correct arguments") @@ -779,7 +799,7 @@ type ClassicalControlTests() = let bodyContent = [ (0, "SubOps", "SubOpCA1"); (1, "SubOps", "SubOpCA2") ] let bodyGen = (Seq.item 0 generated) - AssertSpecializationHasCalls (GetBodyFromCallable bodyGen) bodyContent + AssertSpecializationHasCalls(GetBodyFromCallable bodyGen) bodyContent AssertCallSupportsFunctors [ QsFunctor.Controlled; QsFunctor.Adjoint ] original AssertCallSupportsFunctors [ QsFunctor.Controlled; QsFunctor.Adjoint ] bodyGen @@ -907,7 +927,7 @@ type ClassicalControlTests() = let bodyContent = [ (0, "SubOps", "SubOpCA1"); (1, "SubOps", "SubOpCA2") ] let bodyGen = (Seq.item 0 generated) - AssertSpecializationHasCalls (GetBodyFromCallable bodyGen) bodyContent + AssertSpecializationHasCalls(GetBodyFromCallable bodyGen) bodyContent AssertCallSupportsFunctors [ QsFunctor.Controlled; QsFunctor.Adjoint ] original AssertCallSupportsFunctors [ QsFunctor.Controlled; QsFunctor.Adjoint ] bodyGen @@ -1033,7 +1053,7 @@ type ClassicalControlTests() = let bodyContent = [ (0, "SubOps", "SubOpCA1"); (1, "SubOps", "SubOpCA2") ] let bodyGen = (Seq.item 0 generated) - AssertSpecializationHasCalls (GetBodyFromCallable bodyGen) bodyContent + AssertSpecializationHasCalls(GetBodyFromCallable bodyGen) bodyContent AssertCallSupportsFunctors [ QsFunctor.Controlled; QsFunctor.Adjoint ] original AssertCallSupportsFunctors [ QsFunctor.Controlled ] bodyGen @@ -1096,9 +1116,10 @@ type ClassicalControlTests() = let (success, _, args) = CheckIfLineIsCall BuiltIn.ApplyIfZeroA.FullName.Namespace BuiltIn.ApplyIfZeroA.FullName.Name lines.[2] - Assert.True - (success, - sprintf "Callable %O(%A) did not have expected content" original.Parent QsSpecializationKind.QsBody) + Assert.True( + success, + sprintf "Callable %O(%A) did not have expected content" original.Parent QsSpecializationKind.QsBody + ) let (success, _, _) = IsApplyIfArgMatch args "r" outerOp.FullName Assert.True(success, "ApplyIfZeroA did not have the correct arguments") @@ -1113,9 +1134,10 @@ type ClassicalControlTests() = let (success, _, args) = CheckIfLineIsCall BuiltIn.ApplyIfZero.FullName.Namespace BuiltIn.ApplyIfZero.FullName.Name lines.[1] - Assert.True - (success, - sprintf "Callable %O(%A) did not have expected content" original.Parent QsSpecializationKind.QsBody) + Assert.True( + success, + sprintf "Callable %O(%A) did not have expected content" original.Parent QsSpecializationKind.QsBody + ) let (success, typeArgs, _) = IsApplyIfArgMatch args "r" { Namespace = Signatures.ClassicalControlNS; Name = "Bar" } @@ -1126,15 +1148,18 @@ type ClassicalControlTests() = [] [] - member this.``Lift Functor Application``() = CompileClassicalControlTest 25 |> ignore + member this.``Lift Functor Application``() = + CompileClassicalControlTest 25 |> ignore [] [] - member this.``Lift Partial Application``() = CompileClassicalControlTest 26 |> ignore + member this.``Lift Partial Application``() = + CompileClassicalControlTest 26 |> ignore [] [] - member this.``Lift Array Item Call``() = CompileClassicalControlTest 27 |> ignore + member this.``Lift Array Item Call``() = + CompileClassicalControlTest 27 |> ignore [] [] @@ -1152,9 +1177,10 @@ type ClassicalControlTests() = let original = GetCallableWithName result Signatures.ClassicalControlNS "Foo" |> GetBodyFromCallable let lines = original |> GetLinesFromSpecialization - Assert.True - (3 = Seq.length lines, - sprintf "Callable %O(%A) did not have the expected number of statements" original.Parent original.Kind) + Assert.True( + 3 = Seq.length lines, + sprintf "Callable %O(%A) did not have the expected number of statements" original.Parent original.Kind + ) let (success, targs, args) = CheckIfLineIsCall @@ -1179,9 +1205,10 @@ type ClassicalControlTests() = let original = GetCallableWithName result Signatures.ClassicalControlNS "Foo" |> GetBodyFromCallable let lines = original |> GetLinesFromSpecialization - Assert.True - (3 = Seq.length lines, - sprintf "Callable %O(%A) did not have the expected number of statements" original.Parent original.Kind) + Assert.True( + 3 = Seq.length lines, + sprintf "Callable %O(%A) did not have the expected number of statements" original.Parent original.Kind + ) let (success, targs, args) = CheckIfLineIsCall @@ -1206,9 +1233,10 @@ type ClassicalControlTests() = let original = GetCallableWithName result Signatures.ClassicalControlNS "Foo" |> GetBodyFromCallable let lines = original |> GetLinesFromSpecialization - Assert.True - (3 = Seq.length lines, - sprintf "Callable %O(%A) did not have the expected number of statements" original.Parent original.Kind) + Assert.True( + 3 = Seq.length lines, + sprintf "Callable %O(%A) did not have the expected number of statements" original.Parent original.Kind + ) let (success, targs, args) = CheckIfLineIsCall @@ -1309,9 +1337,10 @@ type ClassicalControlTests() = let lines = original |> GetLinesFromSpecialization - Assert.True - (2 = Seq.length lines, - sprintf "Callable %O(%A) did not have the expected number of statements" original.Parent original.Kind) + Assert.True( + 2 = Seq.length lines, + sprintf "Callable %O(%A) did not have the expected number of statements" original.Parent original.Kind + ) let (success, _, args) = CheckIfLineIsCall BuiltIn.ApplyIfElseR.FullName.Namespace BuiltIn.ApplyIfElseR.FullName.Name lines.[1] @@ -1325,9 +1354,10 @@ type ClassicalControlTests() = let lines = generated |> GetLinesFromSpecialization - Assert.True - (1 = Seq.length lines, - sprintf "Callable %O(%A) did not have the expected number of statements" generated.Parent generated.Kind) + Assert.True( + 1 = Seq.length lines, + sprintf "Callable %O(%A) did not have the expected number of statements" generated.Parent generated.Kind + ) let (success, _, args) = CheckIfLineIsCall BuiltIn.ApplyIfElseR.FullName.Namespace BuiltIn.ApplyIfElseR.FullName.Name lines.[0] @@ -1352,9 +1382,10 @@ type ClassicalControlTests() = let lines = original |> GetLinesFromSpecialization - Assert.True - (2 = Seq.length lines, - sprintf "Callable %O(%A) did not have the expected number of statements" original.Parent original.Kind) + Assert.True( + 2 = Seq.length lines, + sprintf "Callable %O(%A) did not have the expected number of statements" original.Parent original.Kind + ) let (success, _, args) = CheckIfLineIsCall BuiltIn.ApplyIfElseR.FullName.Namespace BuiltIn.ApplyIfElseR.FullName.Name lines.[1] @@ -1368,9 +1399,10 @@ type ClassicalControlTests() = let lines = generated |> GetLinesFromSpecialization - Assert.True - (1 = Seq.length lines, - sprintf "Callable %O(%A) did not have the expected number of statements" generated.Parent generated.Kind) + Assert.True( + 1 = Seq.length lines, + sprintf "Callable %O(%A) did not have the expected number of statements" generated.Parent generated.Kind + ) let (success, _, args) = CheckIfLineIsCall BuiltIn.ApplyIfElseR.FullName.Namespace BuiltIn.ApplyIfElseR.FullName.Name lines.[0] diff --git a/src/QsCompiler/Tests.Compiler/CommandLineTests.fs b/src/QsCompiler/Tests.Compiler/CommandLineTests.fs index 48fc1125db..65e173eb75 100644 --- a/src/QsCompiler/Tests.Compiler/CommandLineTests.fs +++ b/src/QsCompiler/Tests.Compiler/CommandLineTests.fs @@ -146,8 +146,11 @@ let ``execute rewrite steps only if validation passes`` () = let source2 = ("TestCases", "AttributeGeneration.qs") |> Path.Combine let config = - CompilationLoader.Configuration - (GenerateFunctorSupport = true, BuildOutputFolder = null, RuntimeCapability = BasicQuantumFunctionality) + CompilationLoader.Configuration( + GenerateFunctorSupport = true, + BuildOutputFolder = null, + RuntimeCapability = BasicQuantumFunctionality + ) let loadSources (loader: Func<_ seq, _>) = loader.Invoke([ source1; source2 ]) diff --git a/src/QsCompiler/Tests.Compiler/CompilationLoaderTests.fs b/src/QsCompiler/Tests.Compiler/CompilationLoaderTests.fs index 09c4ec8124..c4daf53cb3 100644 --- a/src/QsCompiler/Tests.Compiler/CompilationLoaderTests.fs +++ b/src/QsCompiler/Tests.Compiler/CompilationLoaderTests.fs @@ -26,9 +26,10 @@ type CompilationLoaderTests(output: ITestOutputHelper) = let testCases = File.ReadAllText testFile |> fun text -> Environment.NewLine + "// ---" |> text.Split - |> Seq.map (fun case -> - let parts = case.Split(Environment.NewLine, 2) - parts.[0].Trim(), parts.[1]) + |> Seq.map + (fun case -> + let parts = case.Split(Environment.NewLine, 2) + parts.[0].Trim(), parts.[1]) |> Map.ofSeq /// diff --git a/src/QsCompiler/Tests.Compiler/CompilationTrackerTests.fs b/src/QsCompiler/Tests.Compiler/CompilationTrackerTests.fs index e2b9ec51ce..83a5fb73d6 100644 --- a/src/QsCompiler/Tests.Compiler/CompilationTrackerTests.fs +++ b/src/QsCompiler/Tests.Compiler/CompilationTrackerTests.fs @@ -120,10 +120,11 @@ type CompilationTrackerTests(output: ITestOutputHelper) = [] [] [] - member this.``Measure Task Intervals With Pause`` (firstIntervalDurationInMs: int) - (pauseDurationInMs: int) - (secondIntervalDurationInMs: int) - = + member this.``Measure Task Intervals With Pause`` + (firstIntervalDurationInMs: int) + (pauseDurationInMs: int) + (secondIntervalDurationInMs: int) + = CompilationTracker.ClearData() let taskName = "TestTask" @@ -218,9 +219,10 @@ type CompilationTrackerTests(output: ITestOutputHelper) = Assert.InRange(measuredTaskDurationInMs, nestedTaskDurationInMs, Int32.MaxValue) [)>] - member this.``Measure Double Nested Tasks`` (firstNestedTasksDurationInMs: int []) - (secondNestedTasksDurationInMs: int []) - = + member this.``Measure Double Nested Tasks`` + (firstNestedTasksDurationInMs: int []) + (secondNestedTasksDurationInMs: int []) + = CompilationTracker.ClearData() let parentTaskName = "ParentTask" let firstNestedTaskName = "FirstNestedTask" @@ -298,8 +300,8 @@ type CompilationTrackerTests(output: ITestOutputHelper) = // Start measuring a task but attempt to publish when it is still in progress. CompilationTracker.OnCompilationTaskEvent(CompilationTaskEventType.Start, null, taskName) - Assert.Throws(fun () -> - MethodBase.GetCurrentMethod().Name |> getResultsDictionary |> ignore) + Assert.Throws + (fun () -> MethodBase.GetCurrentMethod().Name |> getResultsDictionary |> ignore) |> ignore @@ -311,8 +313,8 @@ type CompilationTrackerTests(output: ITestOutputHelper) = // Start measuring a task when it is already in progress. CompilationTracker.OnCompilationTaskEvent(CompilationTaskEventType.Start, null, taskName) - Assert.Throws(fun () -> - CompilationTracker.OnCompilationTaskEvent(CompilationTaskEventType.Start, null, taskName)) + Assert.Throws + (fun () -> CompilationTracker.OnCompilationTaskEvent(CompilationTaskEventType.Start, null, taskName)) |> ignore [] @@ -321,8 +323,8 @@ type CompilationTrackerTests(output: ITestOutputHelper) = let taskName = "TestTask" // Stop measuring a task when it was never started. - Assert.Throws(fun () -> - CompilationTracker.OnCompilationTaskEvent(CompilationTaskEventType.End, null, taskName)) + Assert.Throws + (fun () -> CompilationTracker.OnCompilationTaskEvent(CompilationTaskEventType.End, null, taskName)) |> ignore [] @@ -334,6 +336,6 @@ type CompilationTrackerTests(output: ITestOutputHelper) = CompilationTracker.OnCompilationTaskEvent(CompilationTaskEventType.Start, null, taskName) CompilationTracker.OnCompilationTaskEvent(CompilationTaskEventType.End, null, taskName) - Assert.Throws(fun () -> - CompilationTracker.OnCompilationTaskEvent(CompilationTaskEventType.End, null, taskName)) + Assert.Throws + (fun () -> CompilationTracker.OnCompilationTaskEvent(CompilationTaskEventType.End, null, taskName)) |> ignore diff --git a/src/QsCompiler/Tests.Compiler/CompletionParsingTests.fs b/src/QsCompiler/Tests.Compiler/CompletionParsingTests.fs index 7a6cdacffa..02c1d850f6 100644 --- a/src/QsCompiler/Tests.Compiler/CompletionParsingTests.fs +++ b/src/QsCompiler/Tests.Compiler/CompletionParsingTests.fs @@ -13,9 +13,10 @@ open Microsoft.Quantum.QsCompiler.TextProcessing.CodeCompletion.FragmentParsing let private matches scope previous (text, expected) = match GetCompletionKinds scope previous text with | Success actual -> - Assert.True - (Set.ofList expected = Set.ofSeq actual, - String.Format("Input: {0}\n" + "Expected: {1}\n" + "Actual: {2}", text, Set.ofList expected, actual)) + Assert.True( + Set.ofList expected = Set.ofSeq actual, + String.Format("Input: {0}\n" + "Expected: {1}\n" + "Actual: {2}", text, Set.ofList expected, actual) + ) | Failure message -> raise (Exception message) let private fails scope previous text = diff --git a/src/QsCompiler/Tests.Compiler/EntryPointSchemaTests.fs b/src/QsCompiler/Tests.Compiler/EntryPointSchemaTests.fs index 387c6c9cf9..73f4b28a7d 100644 --- a/src/QsCompiler/Tests.Compiler/EntryPointSchemaTests.fs +++ b/src/QsCompiler/Tests.Compiler/EntryPointSchemaTests.fs @@ -60,11 +60,14 @@ type EntryPointSchemaTests(output: ITestOutputHelper) = List.iter (fun v -> argument.Values.Add v) valuesList argument - let createArrayArgument (name: string, - argType: DataType, - position: int32, - arrayType: System.Nullable, - valuesList: ArgumentValue list) = + let createArrayArgument + ( + name: string, + argType: DataType, + position: int32, + arrayType: System.Nullable, + valuesList: ArgumentValue list + ) = let argument = new Argument(Name = name, Type = argType, Position = position, ArrayType = arrayType) List.iter (fun v -> argument.Values.Add v) valuesList argument @@ -78,278 +81,411 @@ type EntryPointSchemaTests(output: ITestOutputHelper) = Map .empty .Add("UseNoArgs", (new EntryPointOperation(Name = "UseNoArgs"), "{\"Name\":\"UseNoArgs\"}")) - .Add("UseBoolArg", - (createEntryPointOperation ("UseBoolArg", [ createArgument ("BoolArg", DataType.BoolType, 0, []) ]), - "{\"Name\":\"UseBoolArg\",\"Arguments\":[{\"Name\":\"BoolArg\"}]}")) - .Add("UseBoolArgWithValues", - (createEntryPointOperation - ("UseBoolArgWithValues", - [ - createArgument - ("BoolArg", - DataType.BoolType, - 0, - [ - new ArgumentValue(Bool = System.Nullable(true)) - new ArgumentValue(Bool = System.Nullable(false)) - ]) - ]), - "{\"Name\":\"UseBoolArgWithValues\",\"Arguments\":[{\"Name\":\"BoolArg\",\"Values\":[{\"Bool\":[true]},{\"Bool\":[false]}]}]}")) - .Add("UseIntegerArg", - (createEntryPointOperation - ("UseIntegerArg", [ createArgument ("IntegerArg", DataType.IntegerType, 0, []) ]), - "{\"Name\":\"UseIntegerArg\",\"Arguments\":[{\"Type\":1,\"Name\":\"IntegerArg\"}]}")) - .Add("UseIntegerArgWithValues", - (createEntryPointOperation - ("UseIntegerArgWithValues", - [ - createArgument - ("IntegerArg", - DataType.IntegerType, - 0, - [ - new ArgumentValue(Integer = System.Nullable(int64 (11))) - new ArgumentValue(Integer = System.Nullable(int64 (999))) - ]) - ]), - "{\"Name\":\"UseIntegerArgWithValues\",\"Arguments\":[{\"Type\":1,\"Name\":\"IntegerArg\",\"Values\":[{\"Integer\":[11]},{\"Integer\":[999]}]}]}")) - .Add("UseDoubleArg", - (createEntryPointOperation - ("UseDoubleArg", [ createArgument ("DoubleArg", DataType.DoubleType, 0, []) ]), - "{\"Name\":\"UseDoubleArg\",\"Arguments\":[{\"Type\":2,\"Name\":\"DoubleArg\"}]}")) - .Add("UseDoubleArgWithValues", - (createEntryPointOperation - ("UseDoubleArgWithValues", - [ - createArgument - ("DoubleArg", - DataType.DoubleType, - 0, - [ - new ArgumentValue(Double = System.Nullable(0.1)) - new ArgumentValue(Double = System.Nullable(0.2)) - ]) - ]), - "{\"Name\":\"UseDoubleArgWithValues\",\"Arguments\":[{\"Type\":2,\"Name\":\"DoubleArg\",\"Values\":[{\"Double\":[0.1]},{\"Double\":[0.2]}]}]}")) - .Add("UsePauliArg", - (createEntryPointOperation ("UsePauliArg", [ createArgument ("PauliArg", DataType.PauliType, 0, []) ]), - "{\"Name\":\"UsePauliArg\",\"Arguments\":[{\"Type\":3,\"Name\":\"PauliArg\"}]}")) - .Add("UsePauliArgWithValues", - (createEntryPointOperation - ("UsePauliArgWithValues", - [ - createArgument - ("PauliArg", - DataType.PauliType, - 0, - [ - new ArgumentValue(Pauli = System.Nullable(PauliValue.PauliX)) - new ArgumentValue(Pauli = System.Nullable(PauliValue.PauliY)) - new ArgumentValue(Pauli = System.Nullable(PauliValue.PauliZ)) - ]) - ]), - "{\"Name\":\"UsePauliArgWithValues\",\"Arguments\":[{\"Type\":3,\"Name\":\"PauliArg\",\"Values\":[{\"Pauli\":[1]},{\"Pauli\":[2]},{\"Pauli\":[3]}]}]}")) - .Add("UseRangeArg", - (createEntryPointOperation ("UseRangeArg", [ createArgument ("RangeArg", DataType.RangeType, 0, []) ]), - "{\"Name\":\"UseRangeArg\",\"Arguments\":[{\"Type\":4,\"Name\":\"RangeArg\"}]}")) - .Add("UseRangeArgWithValues", - (createEntryPointOperation - ("UseRangeArgWithValues", - [ - createArgument - ("RangeArg", - DataType.RangeType, - 0, - [ - createRangeArgumentValue (int64 (1), int64 (1), int64 (10)) - createRangeArgumentValue (int64 (10), int64 (5), int64 (100)) - ]) - ]), - "{\"Name\":\"UseRangeArgWithValues\",\"Arguments\":[{\"Type\":4,\"Name\":\"RangeArg\",\"Values\":[{\"Range\":[{\"Start\":1,\"Step\":1,\"End\":10}]},{\"Range\":[{\"Start\":10,\"Step\":5,\"End\":100}]}]}]}")) - .Add("UseResultArg", - (createEntryPointOperation - ("UseResultArg", [ createArgument ("ResultArg", DataType.ResultType, 0, []) ]), - "{\"Name\":\"UseResultArg\",\"Arguments\":[{\"Type\":5,\"Name\":\"ResultArg\"}]}")) - .Add("UseResultArgWithValues", - (createEntryPointOperation - ("UseResultArgWithValues", - [ - createArgument - ("ResultArg", - DataType.ResultType, - 0, - [ - new ArgumentValue(Result = System.Nullable(ResultValue.Zero)) - new ArgumentValue(Result = System.Nullable(ResultValue.One)) - ]) - ]), - "{\"Name\":\"UseResultArgWithValues\",\"Arguments\":[{\"Type\":5,\"Name\":\"ResultArg\",\"Values\":[{\"Result\":[0]},{\"Result\":[1]}]}]}")) - .Add("UseStringArg", - (createEntryPointOperation - ("UseStringArg", [ createArgument ("StringArg", DataType.StringType, 0, []) ]), - "{\"Name\":\"UseStringArg\",\"Arguments\":[{\"Type\":6,\"Name\":\"StringArg\"}]}")) - .Add("UseStringArgWithValues", - (createEntryPointOperation - ("UseStringArgWithValues", - [ - createArgument - ("StringArg", - DataType.StringType, - 0, - [ new ArgumentValue(String = "StringA"); new ArgumentValue(String = "StringB") ]) - ]), - "{\"Name\":\"UseStringArgWithValues\",\"Arguments\":[{\"Type\":6,\"Name\":\"StringArg\",\"Values\":[{\"String\":[\"StringA\"]},{\"String\":[\"StringB\"]}]}]}")) - .Add("UseBoolArrayArg", - (createEntryPointOperation - ("UseBoolArrayArg", - [ - createArrayArgument - ("BoolArrayArg", DataType.ArrayType, 0, System.Nullable(DataType.BoolType), []) - ]), - "{\"Name\":\"UseBoolArrayArg\",\"Arguments\":[{\"Type\":7,\"Name\":\"BoolArrayArg\",\"ArrayType\":[0]}]}")) - .Add("UseBoolArrayArgWithValues", - (createEntryPointOperation - ("UseBoolArrayArgWithValues", - [ - createArrayArgument - ("BoolArrayArg", - DataType.ArrayType, - 0, - System.Nullable(DataType.BoolType), - [ - createBoolArrayArgumentValue ([ true; false; true ]) - createBoolArrayArgumentValue ([ false; true; false ]) - ]) - ]), - "{\"Name\":\"UseBoolArrayArgWithValues\",\"Arguments\":[{\"Type\":7,\"Name\":\"BoolArrayArg\",\"ArrayType\":[0],\"Values\":[{\"Array\":[{\"Bool\":[[true,false,true]]}]},{\"Array\":[{\"Bool\":[[false,true,false]]}]}]}]}")) - .Add("UseIntegerArrayArg", - (createEntryPointOperation - ("UseIntegerArrayArg", - [ - createArrayArgument - ("IntegerArrayArg", DataType.ArrayType, 0, System.Nullable(DataType.IntegerType), []) - ]), - "{\"Name\":\"UseIntegerArrayArg\",\"Arguments\":[{\"Type\":7,\"Name\":\"IntegerArrayArg\",\"ArrayType\":[1]}]}")) - .Add("UseIntegerArrayArgWithValues", - (createEntryPointOperation - ("UseIntegerArrayArgWithValues", - [ - createArrayArgument - ("IntegerArrayArg", - DataType.ArrayType, - 0, - System.Nullable(DataType.IntegerType), - [ - createIntegerArrayArgumentValue ([ int64 (999); int64 (-1); int64 (11) ]) - createIntegerArrayArgumentValue - ([ int64 (2048); int64 (-1024); int64 (4096); int64 (-8192) ]) - ]) - ]), - "{\"Name\":\"UseIntegerArrayArgWithValues\",\"Arguments\":[{\"Type\":7,\"Name\":\"IntegerArrayArg\",\"ArrayType\":[1],\"Values\":[{\"Array\":[{\"Integer\":[[999,-1,11]]}]},{\"Array\":[{\"Integer\":[[2048,-1024,4096,-8192]]}]}]}]}")) - .Add("UseDoubleArrayArg", - (createEntryPointOperation - ("UseDoubleArrayArg", - [ - createArrayArgument - ("DoubleArrayArg", DataType.ArrayType, 0, System.Nullable(DataType.DoubleType), []) - ]), - "{\"Name\":\"UseDoubleArrayArg\",\"Arguments\":[{\"Type\":7,\"Name\":\"DoubleArrayArg\",\"ArrayType\":[2]}]}")) - .Add("UseDoubleArrayArgWithValues", - (createEntryPointOperation - ("UseDoubleArrayArgWithValues", - [ - createArrayArgument - ("DoubleArrayArg", - DataType.ArrayType, - 0, - System.Nullable(DataType.DoubleType), - [ - createDoubleArrayArgumentValue ([ 3.14159; 0.55; 1024.333; -8192.667 ]) - createDoubleArrayArgumentValue ([ 999.999; -101010.10; 0.0001 ]) - ]) - ]), - "{\"Name\":\"UseDoubleArrayArgWithValues\",\"Arguments\":[{\"Type\":7,\"Name\":\"DoubleArrayArg\",\"ArrayType\":[2],\"Values\":[{\"Array\":[{\"Double\":[[3.14159,0.55,1024.333,-8192.667]]}]},{\"Array\":[{\"Double\":[[999.999,-101010.1,0.0001]]}]}]}]}")) - .Add("UsePauliArrayArg", - (createEntryPointOperation - ("UsePauliArrayArg", - [ - createArrayArgument - ("PauliArrayArg", DataType.ArrayType, 0, System.Nullable(DataType.PauliType), []) - ]), - "{\"Name\":\"UsePauliArrayArg\",\"Arguments\":[{\"Type\":7,\"Name\":\"PauliArrayArg\",\"ArrayType\":[3]}]}")) - .Add("UsePauliArrayArgWithValues", - (createEntryPointOperation - ("UsePauliArrayArgWithValues", - [ - createArrayArgument - ("PauliArrayArg", - DataType.ArrayType, - 0, - System.Nullable(DataType.PauliType), - [ - createPauliArrayArgumentValue - ([ PauliValue.PauliX; PauliValue.PauliY; PauliValue.PauliZ ]) - createPauliArrayArgumentValue ([ PauliValue.PauliI; PauliValue.PauliZ ]) - ]) - ]), - "{\"Name\":\"UsePauliArrayArgWithValues\",\"Arguments\":[{\"Type\":7,\"Name\":\"PauliArrayArg\",\"ArrayType\":[3],\"Values\":[{\"Array\":[{\"Pauli\":[[1,2,3]]}]},{\"Array\":[{\"Pauli\":[[0,3]]}]}]}]}")) - .Add("UseRangeArrayArg", - (createEntryPointOperation - ("UseRangeArrayArg", - [ - createArrayArgument - ("RangeArrayArg", DataType.ArrayType, 0, System.Nullable(DataType.RangeType), []) - ]), - "{\"Name\":\"UseRangeArrayArg\",\"Arguments\":[{\"Type\":7,\"Name\":\"RangeArrayArg\",\"ArrayType\":[4]}]}")) - .Add("UseRangeArrayArgWithValues", - (createEntryPointOperation - ("UseRangeArrayArgWithValues", - [ - createArrayArgument - ("RangeArrayArg", - DataType.ArrayType, - 0, - System.Nullable(DataType.RangeType), - [ - createRangeArrayArgumentValue - ([ (int64 (1), int64 (1), int64 (10)); (int64 (10), int64 (5), int64 (100)) ]) - createRangeArrayArgumentValue ([ (int64 (1), int64 (2), int64 (10)) ]) - ]) - ]), - "{\"Name\":\"UseRangeArrayArgWithValues\",\"Arguments\":[{\"Type\":7,\"Name\":\"RangeArrayArg\",\"ArrayType\":[4],\"Values\":[{\"Array\":[{\"Range\":[[{\"Start\":1,\"Step\":1,\"End\":10},{\"Start\":10,\"Step\":5,\"End\":100}]]}]},{\"Array\":[{\"Range\":[[{\"Start\":1,\"Step\":2,\"End\":10}]]}]}]}]}")) - .Add("UseResultArrayArg", - (createEntryPointOperation - ("UseResultArrayArg", - [ - createArrayArgument - ("ResultArrayArg", DataType.ArrayType, 0, System.Nullable(DataType.ResultType), []) - ]), - "{\"Name\":\"UseResultArrayArg\",\"Arguments\":[{\"Type\":7,\"Name\":\"ResultArrayArg\",\"ArrayType\":[5]}]}")) - .Add("UseResultArrayArgWithValues", - (createEntryPointOperation - ("UseResultArrayArgWithValues", - [ - createArrayArgument - ("ResultArrayArg", - DataType.ArrayType, - 0, - System.Nullable(DataType.ResultType), - [ - createResultArrayArgumentValue ([ ResultValue.Zero; ResultValue.One ]) - createResultArrayArgumentValue ([ ResultValue.One; ResultValue.Zero ]) - ]) - ]), - "{\"Name\":\"UseResultArrayArgWithValues\",\"Arguments\":[{\"Type\":7,\"Name\":\"ResultArrayArg\",\"ArrayType\":[5],\"Values\":[{\"Array\":[{\"Result\":[[0,1]]}]},{\"Array\":[{\"Result\":[[1,0]]}]}]}]}")) - .Add("UseMiscArgs", - (createEntryPointOperation - ("UseMiscArgs", - [ - createArgument ("IntegerArg", DataType.BoolType, 0, []) - createArgument ("PauliArg", DataType.PauliType, 1, []) - createArrayArgument - ("ResultArrayArg", DataType.ArrayType, 2, System.Nullable(DataType.ResultType), []) - ]), - "{\"Name\":\"UseMiscArgs\",\"Arguments\":[{\"Name\":\"IntegerArg\"},{\"Type\":3,\"Name\":\"PauliArg\",\"Position\":1},{\"Type\":7,\"Name\":\"ResultArrayArg\",\"Position\":2,\"ArrayType\":[5]}]}")) + .Add( + "UseBoolArg", + (createEntryPointOperation ("UseBoolArg", [ createArgument ("BoolArg", DataType.BoolType, 0, []) ]), + "{\"Name\":\"UseBoolArg\",\"Arguments\":[{\"Name\":\"BoolArg\"}]}") + ) + .Add( + "UseBoolArgWithValues", + (createEntryPointOperation ( + "UseBoolArgWithValues", + [ + createArgument ( + "BoolArg", + DataType.BoolType, + 0, + [ + new ArgumentValue(Bool = System.Nullable(true)) + new ArgumentValue(Bool = System.Nullable(false)) + ] + ) + ] + ), + "{\"Name\":\"UseBoolArgWithValues\",\"Arguments\":[{\"Name\":\"BoolArg\",\"Values\":[{\"Bool\":[true]},{\"Bool\":[false]}]}]}") + ) + .Add( + "UseIntegerArg", + (createEntryPointOperation ( + "UseIntegerArg", + [ createArgument ("IntegerArg", DataType.IntegerType, 0, []) ] + ), + "{\"Name\":\"UseIntegerArg\",\"Arguments\":[{\"Type\":1,\"Name\":\"IntegerArg\"}]}") + ) + .Add( + "UseIntegerArgWithValues", + (createEntryPointOperation ( + "UseIntegerArgWithValues", + [ + createArgument ( + "IntegerArg", + DataType.IntegerType, + 0, + [ + new ArgumentValue(Integer = System.Nullable(int64 (11))) + new ArgumentValue(Integer = System.Nullable(int64 (999))) + ] + ) + ] + ), + "{\"Name\":\"UseIntegerArgWithValues\",\"Arguments\":[{\"Type\":1,\"Name\":\"IntegerArg\",\"Values\":[{\"Integer\":[11]},{\"Integer\":[999]}]}]}") + ) + .Add( + "UseDoubleArg", + (createEntryPointOperation ( + "UseDoubleArg", + [ createArgument ("DoubleArg", DataType.DoubleType, 0, []) ] + ), + "{\"Name\":\"UseDoubleArg\",\"Arguments\":[{\"Type\":2,\"Name\":\"DoubleArg\"}]}") + ) + .Add( + "UseDoubleArgWithValues", + (createEntryPointOperation ( + "UseDoubleArgWithValues", + [ + createArgument ( + "DoubleArg", + DataType.DoubleType, + 0, + [ + new ArgumentValue(Double = System.Nullable(0.1)) + new ArgumentValue(Double = System.Nullable(0.2)) + ] + ) + ] + ), + "{\"Name\":\"UseDoubleArgWithValues\",\"Arguments\":[{\"Type\":2,\"Name\":\"DoubleArg\",\"Values\":[{\"Double\":[0.1]},{\"Double\":[0.2]}]}]}") + ) + .Add( + "UsePauliArg", + (createEntryPointOperation ("UsePauliArg", [ createArgument ("PauliArg", DataType.PauliType, 0, []) ]), + "{\"Name\":\"UsePauliArg\",\"Arguments\":[{\"Type\":3,\"Name\":\"PauliArg\"}]}") + ) + .Add( + "UsePauliArgWithValues", + (createEntryPointOperation ( + "UsePauliArgWithValues", + [ + createArgument ( + "PauliArg", + DataType.PauliType, + 0, + [ + new ArgumentValue(Pauli = System.Nullable(PauliValue.PauliX)) + new ArgumentValue(Pauli = System.Nullable(PauliValue.PauliY)) + new ArgumentValue(Pauli = System.Nullable(PauliValue.PauliZ)) + ] + ) + ] + ), + "{\"Name\":\"UsePauliArgWithValues\",\"Arguments\":[{\"Type\":3,\"Name\":\"PauliArg\",\"Values\":[{\"Pauli\":[1]},{\"Pauli\":[2]},{\"Pauli\":[3]}]}]}") + ) + .Add( + "UseRangeArg", + (createEntryPointOperation ("UseRangeArg", [ createArgument ("RangeArg", DataType.RangeType, 0, []) ]), + "{\"Name\":\"UseRangeArg\",\"Arguments\":[{\"Type\":4,\"Name\":\"RangeArg\"}]}") + ) + .Add( + "UseRangeArgWithValues", + (createEntryPointOperation ( + "UseRangeArgWithValues", + [ + createArgument ( + "RangeArg", + DataType.RangeType, + 0, + [ + createRangeArgumentValue (int64 (1), int64 (1), int64 (10)) + createRangeArgumentValue (int64 (10), int64 (5), int64 (100)) + ] + ) + ] + ), + "{\"Name\":\"UseRangeArgWithValues\",\"Arguments\":[{\"Type\":4,\"Name\":\"RangeArg\",\"Values\":[{\"Range\":[{\"Start\":1,\"Step\":1,\"End\":10}]},{\"Range\":[{\"Start\":10,\"Step\":5,\"End\":100}]}]}]}") + ) + .Add( + "UseResultArg", + (createEntryPointOperation ( + "UseResultArg", + [ createArgument ("ResultArg", DataType.ResultType, 0, []) ] + ), + "{\"Name\":\"UseResultArg\",\"Arguments\":[{\"Type\":5,\"Name\":\"ResultArg\"}]}") + ) + .Add( + "UseResultArgWithValues", + (createEntryPointOperation ( + "UseResultArgWithValues", + [ + createArgument ( + "ResultArg", + DataType.ResultType, + 0, + [ + new ArgumentValue(Result = System.Nullable(ResultValue.Zero)) + new ArgumentValue(Result = System.Nullable(ResultValue.One)) + ] + ) + ] + ), + "{\"Name\":\"UseResultArgWithValues\",\"Arguments\":[{\"Type\":5,\"Name\":\"ResultArg\",\"Values\":[{\"Result\":[0]},{\"Result\":[1]}]}]}") + ) + .Add( + "UseStringArg", + (createEntryPointOperation ( + "UseStringArg", + [ createArgument ("StringArg", DataType.StringType, 0, []) ] + ), + "{\"Name\":\"UseStringArg\",\"Arguments\":[{\"Type\":6,\"Name\":\"StringArg\"}]}") + ) + .Add( + "UseStringArgWithValues", + (createEntryPointOperation ( + "UseStringArgWithValues", + [ + createArgument ( + "StringArg", + DataType.StringType, + 0, + [ new ArgumentValue(String = "StringA"); new ArgumentValue(String = "StringB") ] + ) + ] + ), + "{\"Name\":\"UseStringArgWithValues\",\"Arguments\":[{\"Type\":6,\"Name\":\"StringArg\",\"Values\":[{\"String\":[\"StringA\"]},{\"String\":[\"StringB\"]}]}]}") + ) + .Add( + "UseBoolArrayArg", + (createEntryPointOperation ( + "UseBoolArrayArg", + [ + createArrayArgument ( + "BoolArrayArg", + DataType.ArrayType, + 0, + System.Nullable(DataType.BoolType), + [] + ) + ] + ), + "{\"Name\":\"UseBoolArrayArg\",\"Arguments\":[{\"Type\":7,\"Name\":\"BoolArrayArg\",\"ArrayType\":[0]}]}") + ) + .Add( + "UseBoolArrayArgWithValues", + (createEntryPointOperation ( + "UseBoolArrayArgWithValues", + [ + createArrayArgument ( + "BoolArrayArg", + DataType.ArrayType, + 0, + System.Nullable(DataType.BoolType), + [ + createBoolArrayArgumentValue ([ true; false; true ]) + createBoolArrayArgumentValue ([ false; true; false ]) + ] + ) + ] + ), + "{\"Name\":\"UseBoolArrayArgWithValues\",\"Arguments\":[{\"Type\":7,\"Name\":\"BoolArrayArg\",\"ArrayType\":[0],\"Values\":[{\"Array\":[{\"Bool\":[[true,false,true]]}]},{\"Array\":[{\"Bool\":[[false,true,false]]}]}]}]}") + ) + .Add( + "UseIntegerArrayArg", + (createEntryPointOperation ( + "UseIntegerArrayArg", + [ + createArrayArgument ( + "IntegerArrayArg", + DataType.ArrayType, + 0, + System.Nullable(DataType.IntegerType), + [] + ) + ] + ), + "{\"Name\":\"UseIntegerArrayArg\",\"Arguments\":[{\"Type\":7,\"Name\":\"IntegerArrayArg\",\"ArrayType\":[1]}]}") + ) + .Add( + "UseIntegerArrayArgWithValues", + (createEntryPointOperation ( + "UseIntegerArrayArgWithValues", + [ + createArrayArgument ( + "IntegerArrayArg", + DataType.ArrayType, + 0, + System.Nullable(DataType.IntegerType), + [ + createIntegerArrayArgumentValue ([ int64 (999); int64 (-1); int64 (11) ]) + createIntegerArrayArgumentValue ( + [ int64 (2048); int64 (-1024); int64 (4096); int64 (-8192) ] + ) + ] + ) + ] + ), + "{\"Name\":\"UseIntegerArrayArgWithValues\",\"Arguments\":[{\"Type\":7,\"Name\":\"IntegerArrayArg\",\"ArrayType\":[1],\"Values\":[{\"Array\":[{\"Integer\":[[999,-1,11]]}]},{\"Array\":[{\"Integer\":[[2048,-1024,4096,-8192]]}]}]}]}") + ) + .Add( + "UseDoubleArrayArg", + (createEntryPointOperation ( + "UseDoubleArrayArg", + [ + createArrayArgument ( + "DoubleArrayArg", + DataType.ArrayType, + 0, + System.Nullable(DataType.DoubleType), + [] + ) + ] + ), + "{\"Name\":\"UseDoubleArrayArg\",\"Arguments\":[{\"Type\":7,\"Name\":\"DoubleArrayArg\",\"ArrayType\":[2]}]}") + ) + .Add( + "UseDoubleArrayArgWithValues", + (createEntryPointOperation ( + "UseDoubleArrayArgWithValues", + [ + createArrayArgument ( + "DoubleArrayArg", + DataType.ArrayType, + 0, + System.Nullable(DataType.DoubleType), + [ + createDoubleArrayArgumentValue ([ 3.14159; 0.55; 1024.333; -8192.667 ]) + createDoubleArrayArgumentValue ([ 999.999; -101010.10; 0.0001 ]) + ] + ) + ] + ), + "{\"Name\":\"UseDoubleArrayArgWithValues\",\"Arguments\":[{\"Type\":7,\"Name\":\"DoubleArrayArg\",\"ArrayType\":[2],\"Values\":[{\"Array\":[{\"Double\":[[3.14159,0.55,1024.333,-8192.667]]}]},{\"Array\":[{\"Double\":[[999.999,-101010.1,0.0001]]}]}]}]}") + ) + .Add( + "UsePauliArrayArg", + (createEntryPointOperation ( + "UsePauliArrayArg", + [ + createArrayArgument ( + "PauliArrayArg", + DataType.ArrayType, + 0, + System.Nullable(DataType.PauliType), + [] + ) + ] + ), + "{\"Name\":\"UsePauliArrayArg\",\"Arguments\":[{\"Type\":7,\"Name\":\"PauliArrayArg\",\"ArrayType\":[3]}]}") + ) + .Add( + "UsePauliArrayArgWithValues", + (createEntryPointOperation ( + "UsePauliArrayArgWithValues", + [ + createArrayArgument ( + "PauliArrayArg", + DataType.ArrayType, + 0, + System.Nullable(DataType.PauliType), + [ + createPauliArrayArgumentValue ( + [ PauliValue.PauliX; PauliValue.PauliY; PauliValue.PauliZ ] + ) + createPauliArrayArgumentValue ([ PauliValue.PauliI; PauliValue.PauliZ ]) + ] + ) + ] + ), + "{\"Name\":\"UsePauliArrayArgWithValues\",\"Arguments\":[{\"Type\":7,\"Name\":\"PauliArrayArg\",\"ArrayType\":[3],\"Values\":[{\"Array\":[{\"Pauli\":[[1,2,3]]}]},{\"Array\":[{\"Pauli\":[[0,3]]}]}]}]}") + ) + .Add( + "UseRangeArrayArg", + (createEntryPointOperation ( + "UseRangeArrayArg", + [ + createArrayArgument ( + "RangeArrayArg", + DataType.ArrayType, + 0, + System.Nullable(DataType.RangeType), + [] + ) + ] + ), + "{\"Name\":\"UseRangeArrayArg\",\"Arguments\":[{\"Type\":7,\"Name\":\"RangeArrayArg\",\"ArrayType\":[4]}]}") + ) + .Add( + "UseRangeArrayArgWithValues", + (createEntryPointOperation ( + "UseRangeArrayArgWithValues", + [ + createArrayArgument ( + "RangeArrayArg", + DataType.ArrayType, + 0, + System.Nullable(DataType.RangeType), + [ + createRangeArrayArgumentValue ( + [ (int64 (1), int64 (1), int64 (10)); (int64 (10), int64 (5), int64 (100)) ] + ) + createRangeArrayArgumentValue ([ (int64 (1), int64 (2), int64 (10)) ]) + ] + ) + ] + ), + "{\"Name\":\"UseRangeArrayArgWithValues\",\"Arguments\":[{\"Type\":7,\"Name\":\"RangeArrayArg\",\"ArrayType\":[4],\"Values\":[{\"Array\":[{\"Range\":[[{\"Start\":1,\"Step\":1,\"End\":10},{\"Start\":10,\"Step\":5,\"End\":100}]]}]},{\"Array\":[{\"Range\":[[{\"Start\":1,\"Step\":2,\"End\":10}]]}]}]}]}") + ) + .Add( + "UseResultArrayArg", + (createEntryPointOperation ( + "UseResultArrayArg", + [ + createArrayArgument ( + "ResultArrayArg", + DataType.ArrayType, + 0, + System.Nullable(DataType.ResultType), + [] + ) + ] + ), + "{\"Name\":\"UseResultArrayArg\",\"Arguments\":[{\"Type\":7,\"Name\":\"ResultArrayArg\",\"ArrayType\":[5]}]}") + ) + .Add( + "UseResultArrayArgWithValues", + (createEntryPointOperation ( + "UseResultArrayArgWithValues", + [ + createArrayArgument ( + "ResultArrayArg", + DataType.ArrayType, + 0, + System.Nullable(DataType.ResultType), + [ + createResultArrayArgumentValue ([ ResultValue.Zero; ResultValue.One ]) + createResultArrayArgumentValue ([ ResultValue.One; ResultValue.Zero ]) + ] + ) + ] + ), + "{\"Name\":\"UseResultArrayArgWithValues\",\"Arguments\":[{\"Type\":7,\"Name\":\"ResultArrayArg\",\"ArrayType\":[5],\"Values\":[{\"Array\":[{\"Result\":[[0,1]]}]},{\"Array\":[{\"Result\":[[1,0]]}]}]}]}") + ) + .Add( + "UseMiscArgs", + (createEntryPointOperation ( + "UseMiscArgs", + [ + createArgument ("IntegerArg", DataType.BoolType, 0, []) + createArgument ("PauliArg", DataType.PauliType, 1, []) + createArrayArgument ( + "ResultArrayArg", + DataType.ArrayType, + 2, + System.Nullable(DataType.ResultType), + [] + ) + ] + ), + "{\"Name\":\"UseMiscArgs\",\"Arguments\":[{\"Name\":\"IntegerArg\"},{\"Type\":3,\"Name\":\"PauliArg\",\"Position\":1},{\"Type\":7,\"Name\":\"ResultArrayArg\",\"Position\":2,\"ArrayType\":[5]}]}") + ) [] [] diff --git a/src/QsCompiler/Tests.Compiler/ExecutionTests.fs b/src/QsCompiler/Tests.Compiler/ExecutionTests.fs index 3e15ca724b..77c928f115 100644 --- a/src/QsCompiler/Tests.Compiler/ExecutionTests.fs +++ b/src/QsCompiler/Tests.Compiler/ExecutionTests.fs @@ -46,7 +46,9 @@ type ExecutionTests(output: ITestOutputHelper) = [] member this.``Specialization Generation for Conjugations``() = - ExecuteAndCompareOutput "ConjugationsInBody" " + ExecuteAndCompareOutput + "ConjugationsInBody" + " U1 V1 U3 @@ -69,7 +71,9 @@ type ExecutionTests(output: ITestOutputHelper) = Adjoint U1 " - ExecuteAndCompareOutput "ConjugationsInAdjoint" " + ExecuteAndCompareOutput + "ConjugationsInAdjoint" + " U1 V1 U3 @@ -92,7 +96,9 @@ type ExecutionTests(output: ITestOutputHelper) = Adjoint U1 " - ExecuteAndCompareOutput "ConjugationsInControlled" " + ExecuteAndCompareOutput + "ConjugationsInControlled" + " U1 V1 U3 @@ -115,7 +121,9 @@ type ExecutionTests(output: ITestOutputHelper) = Adjoint U1 " - ExecuteAndCompareOutput "ConjugationsInControlledAdjoint" " + ExecuteAndCompareOutput + "ConjugationsInControlledAdjoint" + " U1 V1 U3 @@ -141,18 +149,24 @@ type ExecutionTests(output: ITestOutputHelper) = [] member this.``Referencing Projects and Packages``() = - ExecuteAndCompareOutput "PackageAndProjectReference" " + ExecuteAndCompareOutput + "PackageAndProjectReference" + " Welcome to Q#! Info: Go check out https://docs.microsoft.com/azure/quantum. " - ExecuteAndCompareOutput "TypeInReferencedProject" " + ExecuteAndCompareOutput + "TypeInReferencedProject" + " [Complex((1, 0))] " [] member this.``Adjoint generation from expressions should be reversed``() = - ExecuteAndCompareOutput "AdjointExpressions" " + ExecuteAndCompareOutput + "AdjointExpressions" + " 1 2 3 diff --git a/src/QsCompiler/Tests.Compiler/ExternalRewriteStepsManagerTests.fs b/src/QsCompiler/Tests.Compiler/ExternalRewriteStepsManagerTests.fs index fcea0ca767..f85f15d286 100644 --- a/src/QsCompiler/Tests.Compiler/ExternalRewriteStepsManagerTests.fs +++ b/src/QsCompiler/Tests.Compiler/ExternalRewriteStepsManagerTests.fs @@ -12,20 +12,23 @@ open System.Collections.Immutable type TestRewriteStep(priority: int) = interface IRewriteStep with - member this.AssemblyConstants: IDictionary = + member this.AssemblyConstants : IDictionary = new Dictionary() :> IDictionary - member this.GeneratedDiagnostics: IEnumerable = Seq.empty - member this.ImplementsPostconditionVerification: bool = false - member this.ImplementsPreconditionVerification: bool = false - member this.ImplementsTransformation: bool = false - member this.Name: string = "Test Rewrite Step" - member this.PostconditionVerification(compilation: SyntaxTree.QsCompilation): bool = false - member this.PreconditionVerification(compilation: SyntaxTree.QsCompilation): bool = false - member this.Priority: int = priority - - member this.Transformation(compilation: SyntaxTree.QsCompilation, transformed: byref) - : bool = + member this.GeneratedDiagnostics : IEnumerable = Seq.empty + member this.ImplementsPostconditionVerification : bool = false + member this.ImplementsPreconditionVerification : bool = false + member this.ImplementsTransformation : bool = false + member this.Name : string = "Test Rewrite Step" + member this.PostconditionVerification(compilation: SyntaxTree.QsCompilation) : bool = false + member this.PreconditionVerification(compilation: SyntaxTree.QsCompilation) : bool = false + member this.Priority : int = priority + + member this.Transformation + ( + compilation: SyntaxTree.QsCompilation, + transformed: byref + ) : bool = true new() = TestRewriteStep(0) @@ -83,9 +86,11 @@ type ExternalRewriteStepsManagerTests() = let stepInstance = new TestRewriteStep() let config = - new CompilationLoader.Configuration(RewriteStepAssemblies = [ (this.GetType().Assembly.Location, "") ], - RewriteStepTypes = [ (typedefof, "") ], - RewriteStepInstances = [ (stepInstance :> IRewriteStep, "") ]) + new CompilationLoader.Configuration( + RewriteStepAssemblies = [ (this.GetType().Assembly.Location, "") ], + RewriteStepTypes = [ (typedefof, "") ], + RewriteStepInstances = [ (stepInstance :> IRewriteStep, "") ] + ) let loadedSteps = GetSteps config @@ -98,12 +103,10 @@ type ExternalRewriteStepsManagerTests() = let stepInstance2 = new TestRewriteStep 20 let config = - new CompilationLoader.Configuration(RewriteStepTypes = [ (typedefof, "") ], - RewriteStepInstances = - [ - (stepInstance1 :> IRewriteStep, "") - (stepInstance2 :> IRewriteStep, "") - ]) + new CompilationLoader.Configuration( + RewriteStepTypes = [ (typedefof, "") ], + RewriteStepInstances = [ (stepInstance1 :> IRewriteStep, ""); (stepInstance2 :> IRewriteStep, "") ] + ) let loadedSteps = GetSteps config diff --git a/src/QsCompiler/Tests.Compiler/GlobalVerificationTests.fs b/src/QsCompiler/Tests.Compiler/GlobalVerificationTests.fs index bd677926c6..585d659e1e 100644 --- a/src/QsCompiler/Tests.Compiler/GlobalVerificationTests.fs +++ b/src/QsCompiler/Tests.Compiler/GlobalVerificationTests.fs @@ -3,23 +3,26 @@ namespace Microsoft.Quantum.QsCompiler.Testing -open System.Collections.Generic -open Microsoft.Quantum.QsCompiler.DataTypes open Microsoft.Quantum.QsCompiler.Diagnostics open Microsoft.Quantum.QsCompiler.SyntaxExtensions open Microsoft.Quantum.QsCompiler.SyntaxTree +open System.Collections.Generic +open System.IO open Xunit - type GlobalVerificationTests() = - inherit CompilerTests(CompilerTests.Compile - ("TestCases", - [ - "General.qs" - "GlobalVerification.qs" - "Types.qs" - System.IO.Path.Join("LinkingTests", "Core.qs") - ])) + inherit CompilerTests(GlobalVerificationTests.Compile()) + + static member private Compile() = + CompilerTests.Compile( + "TestCases", + [ + "General.qs" + "GlobalVerification.qs" + "Types.qs" + Path.Join("LinkingTests", "Core.qs") + ] + ) member private this.Expect name (diag: IEnumerable) = let ns = "Microsoft.Quantum.Testing.GlobalVerification" diff --git a/src/QsCompiler/Tests.Compiler/LinkingTests.fs b/src/QsCompiler/Tests.Compiler/LinkingTests.fs index 1490b5e349..a63feea6c4 100644 --- a/src/QsCompiler/Tests.Compiler/LinkingTests.fs +++ b/src/QsCompiler/Tests.Compiler/LinkingTests.fs @@ -3,18 +3,13 @@ namespace Microsoft.Quantum.QsCompiler.Testing -open System -open System.Collections.Generic -open System.Collections.Immutable -open System.IO open Microsoft.Quantum.QsCompiler open Microsoft.Quantum.QsCompiler.CompilationBuilder open Microsoft.Quantum.QsCompiler.DataTypes open Microsoft.Quantum.QsCompiler.Diagnostics -open Microsoft.Quantum.QsCompiler.ReservedKeywords.AssemblyConstants open Microsoft.Quantum.QsCompiler.SyntaxExtensions -open Microsoft.Quantum.QsCompiler.SyntaxTree open Microsoft.Quantum.QsCompiler.SyntaxTokens +open Microsoft.Quantum.QsCompiler.SyntaxTree open Microsoft.Quantum.QsCompiler.Transformations.BasicTransformations open Microsoft.Quantum.QsCompiler.Transformations.Monomorphization open Microsoft.Quantum.QsCompiler.Transformations.Monomorphization.Validation @@ -22,13 +17,14 @@ open Microsoft.Quantum.QsCompiler.Transformations.SearchAndReplace open Microsoft.Quantum.QsCompiler.Transformations.SyntaxTreeTrimming open Microsoft.Quantum.QsCompiler.Transformations.Targeting open Microsoft.VisualStudio.LanguageServer.Protocol +open System +open System.Collections.Generic +open System.Collections.Immutable +open System.IO open Xunit -open Xunit.Abstractions - -type LinkingTests(output: ITestOutputHelper) = - inherit CompilerTests(CompilerTests.Compile - (Path.Combine("TestCases", "LinkingTests"), [ "Core.qs"; "InvalidEntryPoints.qs" ])) +type LinkingTests() = + inherit CompilerTests(LinkingTests.Compile()) let compilationManager = new CompilationUnitManager(new Action(fun ex -> failwith ex.Message), isExecutable = true) @@ -38,14 +34,18 @@ type LinkingTests(output: ITestOutputHelper) = Path.GetRandomFileName() + ".qs" |> Path.GetFullPath |> Uri let getManager uri content = - CompilationUnitManager.InitializeFileManager - (uri, content, compilationManager.PublishDiagnostics, compilationManager.LogException) + CompilationUnitManager.InitializeFileManager( + uri, + content, + compilationManager.PublishDiagnostics, + compilationManager.LogException + ) let defaultOffset = { Offset = Position.Zero; Range = Range.Zero } let qualifiedName ns name = { Namespace = ns; Name = name } - let createReferences: seq> -> References = + let createReferences : seq> -> References = Seq.map (fun (source, namespaces) -> KeyValuePair.Create(source, References.Headers(source, namespaces))) >> ImmutableDictionary.CreateRange >> References @@ -55,10 +55,7 @@ type LinkingTests(output: ITestOutputHelper) = let references = IdentifierReferences(name, defaultOffset) Seq.iter (references.Namespaces.OnNamespace >> ignore) namespaces - let declaration = - if obj.ReferenceEquals(references.SharedState.DeclarationLocation, null) - then 0 - else 1 + let declaration = if obj.ReferenceEquals(references.SharedState.DeclarationLocation, null) then 0 else 1 references.SharedState.Locations.Count + declaration @@ -77,6 +74,9 @@ type LinkingTests(output: ITestOutputHelper) = Path.Combine("TestCases", "LinkingTests", "Core.qs") |> Path.GetFullPath |> addOrUpdateSourceFile + static member private Compile() = + CompilerTests.Compile(Path.Combine("TestCases", "LinkingTests"), [ "Core.qs"; "InvalidEntryPoints.qs" ]) + static member private ReadAndChunkSourceFile fileName = let sourceInput = Path.Combine("TestCases", "LinkingTests", fileName) |> File.ReadAllText sourceInput.Split([| "===" |], StringSplitOptions.RemoveEmptyEntries) @@ -159,11 +159,12 @@ type LinkingTests(output: ITestOutputHelper) = targetCallable.Specializations.Length > 0 |> Assert.True targetCallable.Specializations - |> Seq.map (fun spec -> - match spec.Implementation with - | Provided _ -> true - | _ -> false - |> Assert.True) + |> Seq.map + (fun spec -> + match spec.Implementation with + | Provided _ -> true + | _ -> false + |> Assert.True) |> ignore /// Runs the nth internal renaming test, asserting that declarations with the given name and references to them have @@ -234,8 +235,10 @@ type LinkingTests(output: ITestOutputHelper) = Assert.True(1 = Seq.length x) Seq.item 0 x) - Assert.True - (generated.Access = Public, "Callables originally public should remain public if all arguments are public.") + Assert.True( + generated.Access = Public, + "Callables originally public should remain public if all arguments are public." + ) member private this.RunSyntaxTreeTrimTest testNumber keepIntrinsics = let source = (LinkingTests.ReadAndChunkSourceFile "SyntaxTreeTrim.qs").[testNumber - 1] @@ -244,7 +247,7 @@ type LinkingTests(output: ITestOutputHelper) = TrimSyntaxTree.Apply(compilationDataStructures.BuiltCompilation, keepIntrinsics) |> Signatures.SignatureCheck [ Signatures.SyntaxTreeTrimmingNS ] - Signatures.SyntaxTreeTrimmingSignatures.[testNumber - 1] + Signatures.SyntaxTreeTrimmingSignatures.[testNumber - 1] [] [] @@ -462,9 +465,11 @@ type LinkingTests(output: ITestOutputHelper) = let tests = LinkingTests.ReadAndChunkSourceFile "EntryPointDiagnostics.qs" let compilationManager = - new CompilationUnitManager(Action<_>(fun ex -> failwith ex.Message), - isExecutable = true, - capability = BasicQuantumFunctionality) + new CompilationUnitManager( + Action<_>(fun ex -> failwith ex.Message), + isExecutable = true, + capability = BasicQuantumFunctionality + ) let addOrUpdateSourceFile filePath = getManager (new Uri(filePath)) (File.ReadAllText filePath) @@ -622,6 +627,7 @@ type LinkingTests(output: ITestOutputHelper) = let callables = GlobalCallableResolutions referenceCompilation.BuiltCompilation.Namespaces let decorator = new NameDecorator("QsRef") + for idx = 0 to references.Declarations.Count - 1 do let name = decorator.Decorate(qualifiedName Signatures.InternalRenamingNS "Foo", idx) let specializations = callables.[name].Specializations @@ -726,38 +732,47 @@ type LinkingTests(output: ITestOutputHelper) = let buildDict (args: _ seq) = args.ToImmutableDictionary(fst, snd) let declInSource1 = - new Set<_>([ - ("Microsoft.Quantum.Testing.Linking", "BigEndian") |> fullName - ("Microsoft.Quantum.Testing.Linking", "Foo") |> fullName - ("Microsoft.Quantum.Testing.Linking", "Bar") |> fullName - ]) - - checkValidCombination - (buildDict [ (source 1, (chunks.[0], declInSource1)) - (source 2, (chunks.[1], declInSource1)) ]) - - checkValidCombination - (buildDict [ (source 1, (chunks.[1], declInSource1)) - (source 2, (chunks.[1], declInSource1)) ]) - - checkValidCombination - (buildDict [ (source 1, (chunks.[2], declInSource1)) - (source 2, (chunks.[4], declInSource1)) ]) - - checkValidCombination - (buildDict [ (source 1, (chunks.[3], declInSource1)) - (source 2, (chunks.[4], declInSource1)) ]) + new Set<_>( + [ + ("Microsoft.Quantum.Testing.Linking", "BigEndian") |> fullName + ("Microsoft.Quantum.Testing.Linking", "Foo") |> fullName + ("Microsoft.Quantum.Testing.Linking", "Bar") |> fullName + ] + ) + + checkValidCombination ( + buildDict [ (source 1, (chunks.[0], declInSource1)) + (source 2, (chunks.[1], declInSource1)) ] + ) + + checkValidCombination ( + buildDict [ (source 1, (chunks.[1], declInSource1)) + (source 2, (chunks.[1], declInSource1)) ] + ) + + checkValidCombination ( + buildDict [ (source 1, (chunks.[2], declInSource1)) + (source 2, (chunks.[4], declInSource1)) ] + ) + + checkValidCombination ( + buildDict [ (source 1, (chunks.[3], declInSource1)) + (source 2, (chunks.[4], declInSource1)) ] + ) let declInSource2 = - new Set<_>([ - ("Microsoft.Quantum.Testing.Linking.Core", "BigEndian") |> fullName - ("Microsoft.Quantum.Testing.Linking.Core", "Foo") |> fullName - ("Microsoft.Quantum.Testing.Linking.Core", "Bar") |> fullName - ]) - - checkValidCombination - (buildDict [ (source 1, (chunks.[0], declInSource1)) - (source 2, (chunks.[6], declInSource2)) ]) + new Set<_>( + [ + ("Microsoft.Quantum.Testing.Linking.Core", "BigEndian") |> fullName + ("Microsoft.Quantum.Testing.Linking.Core", "Foo") |> fullName + ("Microsoft.Quantum.Testing.Linking.Core", "Bar") |> fullName + ] + ) + + checkValidCombination ( + buildDict [ (source 1, (chunks.[0], declInSource1)) + (source 2, (chunks.[6], declInSource2)) ] + ) [] member this.``Trimmer Removes Unused Callables``() = this.RunSyntaxTreeTrimTest 1 false diff --git a/src/QsCompiler/Tests.Compiler/LocalVerificationTests.fs b/src/QsCompiler/Tests.Compiler/LocalVerificationTests.fs index d5a0803b77..58a0245e11 100644 --- a/src/QsCompiler/Tests.Compiler/LocalVerificationTests.fs +++ b/src/QsCompiler/Tests.Compiler/LocalVerificationTests.fs @@ -3,25 +3,28 @@ namespace Microsoft.Quantum.QsCompiler.Testing -open System.Collections.Generic -open System.IO open Microsoft.Quantum.QsCompiler.Diagnostics open Microsoft.Quantum.QsCompiler.SyntaxExtensions open Microsoft.Quantum.QsCompiler.SyntaxTree +open System.Collections.Generic +open System.IO open Xunit - type LocalVerificationTests() = - inherit CompilerTests(CompilerTests.Compile - ("TestCases", - [ - "General.qs" - "LocalVerification.qs" - "Types.qs" - Path.Combine("LinkingTests", "Core.qs") - Path.Combine("StringParsingTests", "StringParsing.qs") - Path.Combine("StringParsingTests", "StringInterpolation.qs") - ])) + inherit CompilerTests(LocalVerificationTests.Compile()) + + static member private Compile() = + CompilerTests.Compile( + "TestCases", + [ + "General.qs" + "LocalVerification.qs" + "Types.qs" + Path.Combine("LinkingTests", "Core.qs") + Path.Combine("StringParsingTests", "StringParsing.qs") + Path.Combine("StringParsingTests", "StringInterpolation.qs") + ] + ) member private this.Expect name (diag: IEnumerable) = let ns = "Microsoft.Quantum.Testing.LocalVerification" diff --git a/src/QsCompiler/Tests.Compiler/QirTests.fs b/src/QsCompiler/Tests.Compiler/QirTests.fs index 4609e193a1..4e48d5fda4 100644 --- a/src/QsCompiler/Tests.Compiler/QirTests.fs +++ b/src/QsCompiler/Tests.Compiler/QirTests.fs @@ -35,22 +35,21 @@ let private compilerArgs target (name: string) = ("TestCases", "QirTests", name + ".qs") |> Path.Combine ("TestCases", "QirTests", "QirCore.qs") |> Path.Combine - (if target - then ("TestCases", "QirTests", "QirTarget.qs") |> Path.Combine - else "") + (if target then ("TestCases", "QirTests", "QirTarget.qs") |> Path.Combine else "") "--load" - Path.Combine - (Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Microsoft.Quantum.QirGeneration.dll") + Path.Combine( + Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), + "Microsoft.Quantum.QirGeneration.dll" + ) "--verbosity" "Diagnostic" } let private customTest name compilerArgs snippets = - if not <| Directory.Exists "qir" - then Directory.CreateDirectory "qir" |> ignore + if not <| Directory.Exists "qir" then Directory.CreateDirectory "qir" |> ignore let fileName = Path.Combine("qir", name + ".ll") clearOutput fileName diff --git a/src/QsCompiler/Tests.Compiler/SerializationTests.fs b/src/QsCompiler/Tests.Compiler/SerializationTests.fs index 30fd48e2fa..24df04304e 100644 --- a/src/QsCompiler/Tests.Compiler/SerializationTests.fs +++ b/src/QsCompiler/Tests.Compiler/SerializationTests.fs @@ -57,8 +57,10 @@ module SerializationTests = ArgumentType = argType |> ResolvedType.New ReturnType = rType |> ResolvedType.New Information = - CallableInformation.New - (ResolvedCharacteristics.FromProperties props, InferredCallableInformation.NoInformation) + CallableInformation.New( + ResolvedCharacteristics.FromProperties props, + InferredCallableInformation.NoInformation + ) } let varDecl name t (s, e) = @@ -67,7 +69,7 @@ module SerializationTests = Type = t |> ResolvedType.New InferredInformation = InferredExpressionInformation.New(false, false) Position = Null - Range = Range.Create (Position.Create 0 s) (Position.Create 0 e) + Range = Range.Create(Position.Create 0 s) (Position.Create 0 e) } let tupleIntIntType = TupleType([ Int |> ResolvedType.New; Int |> ResolvedType.New ].ToImmutableArray()) @@ -103,7 +105,7 @@ module SerializationTests = Attributes = ImmutableArray.Empty Source = { CodeFile = "Test.qs"; AssemblyFile = Null } Position = Position.Create 4 43 |> DeclarationHeader.Offset.Defined - HeaderRange = Range.Create (Position.Create 0 0) (Position.Create 0 4) |> DeclarationHeader.Range.Defined + HeaderRange = Range.Create(Position.Create 0 0) (Position.Create 0 4) |> DeclarationHeader.Range.Defined Documentation = ImmutableArray.Empty } |> testOne @@ -112,15 +114,16 @@ module SerializationTests = Kind = QsSpecializationKind.QsBody TypeArguments = Null Information = - CallableInformation.New - (ResolvedCharacteristics.FromProperties [ Adjointable - Controllable ], - InferredCallableInformation.NoInformation) + CallableInformation.New( + ResolvedCharacteristics.FromProperties [ Adjointable + Controllable ], + InferredCallableInformation.NoInformation + ) Parent = qualifiedName "Microsoft.Quantum" "emptyOperation" Attributes = ImmutableArray.Empty Source = { CodeFile = "Test.qs"; AssemblyFile = Null } Position = Position.Create 5 39 |> DeclarationHeader.Offset.Defined - HeaderRange = Range.Create (Position.Create 0 0) (Position.Create 0 4) |> DeclarationHeader.Range.Defined + HeaderRange = Range.Create(Position.Create 0 0) (Position.Create 0 4) |> DeclarationHeader.Range.Defined Documentation = [ "Line one"; "Line two" ] |> ImmutableArray.CreateRange } |> testOne @@ -129,13 +132,15 @@ module SerializationTests = Kind = QsSpecializationKind.QsBody TypeArguments = Null Information = - CallableInformation.New - (ResolvedCharacteristics.Empty, InferredCallableInformation.New(intrinsic = true)) + CallableInformation.New( + ResolvedCharacteristics.Empty, + InferredCallableInformation.New(intrinsic = true) + ) Parent = qualifiedName "Microsoft.Quantum" "Pair" Attributes = ImmutableArray.Empty Source = { CodeFile = "Test.qs"; AssemblyFile = Null } Position = Position.Create 5 4 |> DeclarationHeader.Offset.Defined - HeaderRange = Range.Create (Position.Create 0 8) (Position.Create 0 12) |> DeclarationHeader.Range.Defined + HeaderRange = Range.Create(Position.Create 0 8) (Position.Create 0 12) |> DeclarationHeader.Range.Defined Documentation = ImmutableArray.Empty } |> testOne @@ -144,13 +149,15 @@ module SerializationTests = Kind = QsSpecializationKind.QsBody TypeArguments = Null Information = - CallableInformation.New - (ResolvedCharacteristics.Empty, InferredCallableInformation.New(intrinsic = true)) + CallableInformation.New( + ResolvedCharacteristics.Empty, + InferredCallableInformation.New(intrinsic = true) + ) Parent = qualifiedName "Microsoft.Quantum" "Unused" Attributes = ImmutableArray.Empty Source = { CodeFile = "Test.qs"; AssemblyFile = Null } Position = Position.Create 6 4 |> DeclarationHeader.Offset.Defined - HeaderRange = Range.Create (Position.Create 0 8) (Position.Create 0 14) |> DeclarationHeader.Range.Defined + HeaderRange = Range.Create(Position.Create 0 8) (Position.Create 0 14) |> DeclarationHeader.Range.Defined Documentation = ImmutableArray.Empty } |> testOne @@ -171,7 +178,7 @@ module SerializationTests = Access = Public Source = { CodeFile = "Test.qs"; AssemblyFile = Null } Position = Position.Create 2 4 |> DeclarationHeader.Offset.Defined - SymbolRange = Range.Create (Position.Create 0 8) (Position.Create 0 12) |> DeclarationHeader.Range.Defined + SymbolRange = Range.Create(Position.Create 0 8) (Position.Create 0 12) |> DeclarationHeader.Range.Defined ArgumentTuple = [ varDecl "__Item1__" Int (1, 1) |> QsTupleItem @@ -191,7 +198,7 @@ module SerializationTests = Access = Public Source = { CodeFile = "Test.qs"; AssemblyFile = Null } Position = Position.Create 4 4 |> DeclarationHeader.Offset.Defined - SymbolRange = Range.Create (Position.Create 0 9) (Position.Create 0 22) |> DeclarationHeader.Range.Defined + SymbolRange = Range.Create(Position.Create 0 9) (Position.Create 0 22) |> DeclarationHeader.Range.Defined ArgumentTuple = [ varDecl "p" udtPair (25, 26) |> QsTupleItem ].ToImmutableArray() |> QsTuple Signature = simpleSignature udtPair UnitType [] Documentation = ImmutableArray.Empty @@ -205,7 +212,7 @@ module SerializationTests = Access = Public Source = { CodeFile = "Test.qs"; AssemblyFile = Null } Position = Position.Create 5 4 |> DeclarationHeader.Offset.Defined - SymbolRange = Range.Create (Position.Create 0 10) (Position.Create 0 24) |> DeclarationHeader.Range.Defined + SymbolRange = Range.Create(Position.Create 0 10) (Position.Create 0 24) |> DeclarationHeader.Range.Defined ArgumentTuple = [].ToImmutableArray() |> QsTuple Signature = simpleSignature UnitType UnitType [ Adjointable; Controllable ] Documentation = ImmutableArray.Empty @@ -219,7 +226,7 @@ module SerializationTests = Access = Public Source = { CodeFile = "Test.qs"; AssemblyFile = Null } Position = Position.Create 3 4 |> DeclarationHeader.Offset.Defined - SymbolRange = Range.Create (Position.Create 0 8) (Position.Create 0 14) |> DeclarationHeader.Range.Defined + SymbolRange = Range.Create(Position.Create 0 8) (Position.Create 0 14) |> DeclarationHeader.Range.Defined ArgumentTuple = [ varDecl "__Item1__" Int (1, 1) |> QsTupleItem @@ -247,7 +254,7 @@ module SerializationTests = Access = Public Source = { CodeFile = "Test.qs"; AssemblyFile = Null } Position = Position.Create 2 4 |> DeclarationHeader.Offset.Defined - SymbolRange = Range.Create (Position.Create 0 8) (Position.Create 0 12) |> DeclarationHeader.Range.Defined + SymbolRange = Range.Create(Position.Create 0 8) (Position.Create 0 12) |> DeclarationHeader.Range.Defined Type = tupleIntIntType |> ResolvedType.New TypeItems = intIntTypeItems Documentation = ImmutableArray.Empty @@ -260,7 +267,7 @@ module SerializationTests = Access = Public Source = { CodeFile = "Test.qs"; AssemblyFile = Null } Position = Position.Create 3 4 |> DeclarationHeader.Offset.Defined - SymbolRange = Range.Create (Position.Create 0 8) (Position.Create 0 14) |> DeclarationHeader.Range.Defined + SymbolRange = Range.Create(Position.Create 0 8) (Position.Create 0 14) |> DeclarationHeader.Range.Defined Type = tupleIntIntType |> ResolvedType.New TypeItems = intIntTypeItems Documentation = ImmutableArray.Empty @@ -298,9 +305,10 @@ module SerializationTests = let mutable attrs = null let loadedFromResource = AssemblyLoader.LoadReferencedAssembly(dllUri, &attrs, false) - Assert.False - (loadedFromResource, - "loading should indicate failure when headers are loaded based on attributes rather than resources") + Assert.False( + loadedFromResource, + "loading should indicate failure when headers are loaded based on attributes rather than resources" + ) let callables = attrs.Callables |> Seq.map (fun c -> c.ToJson()) |> Seq.toList let types = attrs.Types |> Seq.map (fun t -> t.ToJson()) |> Seq.toList diff --git a/src/QsCompiler/Tests.Compiler/SymbolManagementTests.fs b/src/QsCompiler/Tests.Compiler/SymbolManagementTests.fs index eb640f71ca..412644b58f 100644 --- a/src/QsCompiler/Tests.Compiler/SymbolManagementTests.fs +++ b/src/QsCompiler/Tests.Compiler/SymbolManagementTests.fs @@ -15,11 +15,11 @@ open Xunit let private random = System.Random 1 let private randomPosition () = - Position.Create (random.Next()) (random.Next()) + Position.Create(random.Next()) (random.Next()) let private randomRange () = let a, b = randomPosition (), randomPosition () - Range.Create (min a b) (max a b) + Range.Create(min a b) (max a b) let toQualName (ns: string, name: string) = { Namespace = ns; Name = name } @@ -62,6 +62,7 @@ let ``type hash tests`` () = (toTuple [ Int; Bool ], toTuple [ Bool; String ], false) (toTuple [ Int; Bool ], toTuple [ Int; Bool ], true) ] - |> Seq.iter (fun (left, right, expected) -> - let ok = (expected = ((thash left) = (thash right))) - Assert.True ok) + |> Seq.iter + (fun (left, right, expected) -> + let ok = (expected = ((thash left) = (thash right))) + Assert.True ok) diff --git a/src/QsCompiler/Tests.Compiler/SyntaxTests.fs b/src/QsCompiler/Tests.Compiler/SyntaxTests.fs index bf7467c744..06c1907db5 100644 --- a/src/QsCompiler/Tests.Compiler/SyntaxTests.fs +++ b/src/QsCompiler/Tests.Compiler/SyntaxTests.fs @@ -324,7 +324,7 @@ let ``Expression literal tests`` () = ("\"\\\"hello\\\"\"", true, toExpr (StringLiteral("\"hello\"", noExprs)), []) ("\"hello\\n\"", true, toExpr (StringLiteral("hello\n", noExprs)), []) ("\"hello\\r\\n\"", true, toExpr (StringLiteral("hello\r\n", noExprs)), []) - ("\"hello\\t\"", true, toExpr (StringLiteral("hello\t", noExprs)), []) + ("\"hello\\t\"", true, toExpr (StringLiteral("hello ", noExprs)), []) ("One", true, toExpr (ResultLiteral One), []) ("Zero", true, toExpr (ResultLiteral Zero), []) ("PauliI", true, toExpr (PauliLiteral PauliI), []) @@ -570,10 +570,11 @@ let ``Call tests`` () = "(x(1,(2, _)))(2)", true, ([ - CallLikeExpression - (toIdentifier "x", - toTuple [ toInt 1 - toTuple [ toInt 2; toExpr MissingExpr ] ]) + CallLikeExpression( + toIdentifier "x", + toTuple [ toInt 1 + toTuple [ toInt 2; toExpr MissingExpr ] ] + ) |> toExpr ] |> toTuple, @@ -583,10 +584,11 @@ let ``Call tests`` () = [] "x(1,(2, _))(2)", true, - (CallLikeExpression - (toIdentifier "x", - toTuple [ toInt 1 - toTuple [ toInt 2; toExpr MissingExpr ] ]) + (CallLikeExpression( + toIdentifier "x", + toTuple [ toInt 1 + toTuple [ toInt 2; toExpr MissingExpr ] ] + ) |> toExpr, toTuple [ toInt 2 ]) |> CallLikeExpression @@ -642,9 +644,12 @@ let ``Modifier tests`` () = // modifiers can only be applied to identifiers, ari []) ("ab!! ()", true, - toExpr - (CallLikeExpression - (UnwrapApplication(UnwrapApplication(toIdentifier "ab") |> toExpr) |> toExpr, UnitValue |> toExpr)), + toExpr ( + CallLikeExpression( + UnwrapApplication(UnwrapApplication(toIdentifier "ab") |> toExpr) |> toExpr, + UnitValue |> toExpr + ) + ), []) ("Adjoint x()", true, @@ -652,80 +657,106 @@ let ``Modifier tests`` () = // modifiers can only be applied to identifiers, ari []) ("Adjoint Controlled x()", true, - toExpr - (CallLikeExpression - (AdjointApplication(ControlledApplication(toIdentifier "x") |> toExpr) |> toExpr, UnitValue |> toExpr)), + toExpr ( + CallLikeExpression( + AdjointApplication(ControlledApplication(toIdentifier "x") |> toExpr) |> toExpr, + UnitValue |> toExpr + ) + ), []) ("Adjoint x! ()", true, - toExpr - (CallLikeExpression - (AdjointApplication(UnwrapApplication(toIdentifier "x") |> toExpr) |> toExpr, UnitValue |> toExpr)), + toExpr ( + CallLikeExpression( + AdjointApplication(UnwrapApplication(toIdentifier "x") |> toExpr) |> toExpr, + UnitValue |> toExpr + ) + ), []) // modifiers on arity-1 tuples: ("(udt(x))!", true, - toExpr - (UnwrapApplication - (toTuple [ (CallLikeExpression(toIdentifier "udt", toTuple [ toIdentifier "x" ]) |> toExpr) ])), + toExpr ( + UnwrapApplication( + toTuple [ (CallLikeExpression(toIdentifier "udt", toTuple [ toIdentifier "x" ]) |> toExpr) ] + ) + ), []) ("(udt(x))! ()", true, - toExpr - (CallLikeExpression - ((UnwrapApplication - (toTuple [ CallLikeExpression(toIdentifier "udt", toTuple [ toIdentifier "x" ]) |> toExpr ])) - |> toExpr, - UnitValue |> toExpr)), + toExpr ( + CallLikeExpression( + (UnwrapApplication( + toTuple [ CallLikeExpression(toIdentifier "udt", toTuple [ toIdentifier "x" ]) |> toExpr ] + )) + |> toExpr, + UnitValue |> toExpr + ) + ), []) ("Controlled (udt(x))! ()", true, - toExpr - (CallLikeExpression - (ControlledApplication - ((UnwrapApplication - (toTuple [ CallLikeExpression(toIdentifier "udt", toTuple [ toIdentifier "x" ]) |> toExpr ])) - |> toExpr) - |> toExpr, - UnitValue |> toExpr)), + toExpr ( + CallLikeExpression( + ControlledApplication( + (UnwrapApplication( + toTuple [ CallLikeExpression(toIdentifier "udt", toTuple [ toIdentifier "x" ]) |> toExpr ] + )) + |> toExpr + ) + |> toExpr, + UnitValue |> toExpr + ) + ), []) ("(Controlled (udt(x))!)()", true, - toExpr - (CallLikeExpression - (toTuple [ ControlledApplication - ((UnwrapApplication - (toTuple [ CallLikeExpression(toIdentifier "udt", toTuple [ toIdentifier "x" ]) - |> toExpr ])) - |> toExpr) - |> toExpr ], - UnitValue |> toExpr)), + toExpr ( + CallLikeExpression( + toTuple [ ControlledApplication( + (UnwrapApplication( + toTuple [ CallLikeExpression(toIdentifier "udt", toTuple [ toIdentifier "x" ]) + |> toExpr ] + )) + |> toExpr + ) + |> toExpr ], + UnitValue |> toExpr + ) + ), []) // modifiers on array item expressions ("x[i]!", true, toExpr (UnwrapApplication(ArrayItem(toIdentifier "x", toIdentifier "i") |> toExpr)), []) ("Adjoint x[i]", true, toExpr (AdjointApplication(ArrayItem(toIdentifier "x", toIdentifier "i") |> toExpr)), []) ("x[i]! ()", true, - toExpr - (CallLikeExpression - (UnwrapApplication(ArrayItem(toIdentifier "x", toIdentifier "i") |> toExpr) |> toExpr, - UnitValue |> toExpr)), + toExpr ( + CallLikeExpression( + UnwrapApplication(ArrayItem(toIdentifier "x", toIdentifier "i") |> toExpr) |> toExpr, + UnitValue |> toExpr + ) + ), []) ("Adjoint x[i] ()", true, - toExpr - (CallLikeExpression - (AdjointApplication(ArrayItem(toIdentifier "x", toIdentifier "i") |> toExpr) |> toExpr, - UnitValue |> toExpr)), + toExpr ( + CallLikeExpression( + AdjointApplication(ArrayItem(toIdentifier "x", toIdentifier "i") |> toExpr) |> toExpr, + UnitValue |> toExpr + ) + ), []) ("Controlled x[i]! ()", true, - toExpr - (CallLikeExpression - (ControlledApplication - (UnwrapApplication(ArrayItem(toIdentifier "x", toIdentifier "i") |> toExpr) |> toExpr) - |> toExpr, - UnitValue |> toExpr)), + toExpr ( + CallLikeExpression( + ControlledApplication( + UnwrapApplication(ArrayItem(toIdentifier "x", toIdentifier "i") |> toExpr) |> toExpr + ) + |> toExpr, + UnitValue |> toExpr + ) + ), []) // modifiers combined with named and array item access ("x[i]::Re", @@ -734,41 +765,54 @@ let ``Modifier tests`` () = // modifiers can only be applied to identifiers, ari []) ("x[i]!::Re", true, - toExpr - (NamedItem - (UnwrapApplication(ArrayItem(toIdentifier "x", toIdentifier "i") |> toExpr) |> toExpr, toSymbol "Re")), + toExpr ( + NamedItem( + UnwrapApplication(ArrayItem(toIdentifier "x", toIdentifier "i") |> toExpr) |> toExpr, + toSymbol "Re" + ) + ), []) ("x[i]::Re!", true, - toExpr - (UnwrapApplication - (NamedItem(ArrayItem(toIdentifier "x", toIdentifier "i") |> toExpr, toSymbol "Re") |> toExpr)), + toExpr ( + UnwrapApplication( + NamedItem(ArrayItem(toIdentifier "x", toIdentifier "i") |> toExpr, toSymbol "Re") |> toExpr + ) + ), []) ("x[i]![j]", true, - toExpr - (ArrayItem - (UnwrapApplication(ArrayItem(toIdentifier "x", toIdentifier "i") |> toExpr) |> toExpr, toIdentifier "j")), + toExpr ( + ArrayItem( + UnwrapApplication(ArrayItem(toIdentifier "x", toIdentifier "i") |> toExpr) |> toExpr, + toIdentifier "j" + ) + ), []) ("x::Re![j]", true, - toExpr - (ArrayItem - (UnwrapApplication(NamedItem(toIdentifier "x", toSymbol "Re") |> toExpr) |> toExpr, toIdentifier "j")), + toExpr ( + ArrayItem( + UnwrapApplication(NamedItem(toIdentifier "x", toSymbol "Re") |> toExpr) |> toExpr, + toIdentifier "j" + ) + ), []) ("x::Re!::Im", true, - toExpr - (NamedItem - (UnwrapApplication(NamedItem(toIdentifier "x", toSymbol "Re") |> toExpr) |> toExpr, toSymbol "Im")), + toExpr ( + NamedItem(UnwrapApplication(NamedItem(toIdentifier "x", toSymbol "Re") |> toExpr) |> toExpr, toSymbol "Im") + ), []) ("x::Re!!::Im", true, - toExpr - (NamedItem - (UnwrapApplication(UnwrapApplication(NamedItem(toIdentifier "x", toSymbol "Re") |> toExpr) |> toExpr) - |> toExpr, - toSymbol "Im")), + toExpr ( + NamedItem( + UnwrapApplication(UnwrapApplication(NamedItem(toIdentifier "x", toSymbol "Re") |> toExpr) |> toExpr) + |> toExpr, + toSymbol "Im" + ) + ), []) ] |> List.iter testExpr @@ -813,26 +857,29 @@ let ``Function type tests`` () = [] "('T => Unit)[] -> Unit", - Function - (ArrayType(toTupleType [ toOpType (TypeParameter(toSymbol "T") |> toType) unitType emptySet ]) - |> toType, - unitType) + Function( + ArrayType(toTupleType [ toOpType (TypeParameter(toSymbol "T") |> toType) unitType emptySet ]) + |> toType, + unitType + ) |> toType, [] "('T => Unit is Adj)[] -> Unit", - Function - (ArrayType(toTupleType [ toOpType (TypeParameter(toSymbol "T") |> toType) unitType adjSet ]) - |> toType, - unitType) + Function( + ArrayType(toTupleType [ toOpType (TypeParameter(toSymbol "T") |> toType) unitType adjSet ]) + |> toType, + unitType + ) |> toType, [] "(('T => Unit)[] -> Unit)", - toTupleType [ Function - (ArrayType(toTupleType [ toOpType (TypeParameter(toSymbol "T") |> toType) unitType emptySet ]) - |> toType, - unitType) + toTupleType [ Function( + ArrayType(toTupleType [ toOpType (TypeParameter(toSymbol "T") |> toType) unitType emptySet ]) + |> toType, + unitType + ) |> toType ], [] ] @@ -1085,21 +1132,30 @@ let ``Other expression tests`` () = ("a[0... ]", true, toExpr (ArrayItem(toIdentifier "a", RangeLiteral(toInt 0, toExpr MissingExpr) |> toExpr)), []) ("a[0..2...]", true, - toExpr - (ArrayItem - (toIdentifier "a", RangeLiteral(RangeLiteral(toInt 0, toInt 2) |> toExpr, toExpr MissingExpr) |> toExpr)), + toExpr ( + ArrayItem( + toIdentifier "a", + RangeLiteral(RangeLiteral(toInt 0, toInt 2) |> toExpr, toExpr MissingExpr) |> toExpr + ) + ), []) ("a[0 .. 2 ... ]", true, - toExpr - (ArrayItem - (toIdentifier "a", RangeLiteral(RangeLiteral(toInt 0, toInt 2) |> toExpr, toExpr MissingExpr) |> toExpr)), + toExpr ( + ArrayItem( + toIdentifier "a", + RangeLiteral(RangeLiteral(toInt 0, toInt 2) |> toExpr, toExpr MissingExpr) |> toExpr + ) + ), []) ("a[0..2 ...]", true, - toExpr - (ArrayItem - (toIdentifier "a", RangeLiteral(RangeLiteral(toInt 0, toInt 2) |> toExpr, toExpr MissingExpr) |> toExpr)), + toExpr ( + ArrayItem( + toIdentifier "a", + RangeLiteral(RangeLiteral(toInt 0, toInt 2) |> toExpr, toExpr MissingExpr) |> toExpr + ) + ), []) ("a[...0]", true, toExpr (ArrayItem(toIdentifier "a", RangeLiteral(toExpr MissingExpr, toInt 0) |> toExpr)), []) ("a[ ...0]", true, toExpr (ArrayItem(toIdentifier "a", RangeLiteral(toExpr MissingExpr, toInt 0) |> toExpr)), []) @@ -1109,37 +1165,50 @@ let ``Other expression tests`` () = []) ("a[...2..0]", true, - toExpr - (ArrayItem - (toIdentifier "a", RangeLiteral(RangeLiteral(toExpr MissingExpr, toInt 2) |> toExpr, toInt 0) |> toExpr)), + toExpr ( + ArrayItem( + toIdentifier "a", + RangeLiteral(RangeLiteral(toExpr MissingExpr, toInt 2) |> toExpr, toInt 0) |> toExpr + ) + ), []) ("a[ ...2 .. 0]", true, - toExpr - (ArrayItem - (toIdentifier "a", RangeLiteral(RangeLiteral(toExpr MissingExpr, toInt 2) |> toExpr, toInt 0) |> toExpr)), + toExpr ( + ArrayItem( + toIdentifier "a", + RangeLiteral(RangeLiteral(toExpr MissingExpr, toInt 2) |> toExpr, toInt 0) |> toExpr + ) + ), []) ("a[ ... 2 ..0]", true, - toExpr - (ArrayItem - (toIdentifier "a", RangeLiteral(RangeLiteral(toExpr MissingExpr, toInt 2) |> toExpr, toInt 0) |> toExpr)), + toExpr ( + ArrayItem( + toIdentifier "a", + RangeLiteral(RangeLiteral(toExpr MissingExpr, toInt 2) |> toExpr, toInt 0) |> toExpr + ) + ), []) ("a[...-1...]", true, - toExpr - (ArrayItem - (toIdentifier "a", - RangeLiteral(RangeLiteral(toExpr MissingExpr, NEG(toInt 1) |> toExpr) |> toExpr, toExpr MissingExpr) - |> toExpr)), + toExpr ( + ArrayItem( + toIdentifier "a", + RangeLiteral(RangeLiteral(toExpr MissingExpr, NEG(toInt 1) |> toExpr) |> toExpr, toExpr MissingExpr) + |> toExpr + ) + ), []) ("a[ ... -1 ... ]", true, - toExpr - (ArrayItem - (toIdentifier "a", - RangeLiteral(RangeLiteral(toExpr MissingExpr, NEG(toInt 1) |> toExpr) |> toExpr, toExpr MissingExpr) - |> toExpr)), + toExpr ( + ArrayItem( + toIdentifier "a", + RangeLiteral(RangeLiteral(toExpr MissingExpr, NEG(toInt 1) |> toExpr) |> toExpr, toExpr MissingExpr) + |> toExpr + ) + ), []) ("a[...]", true, @@ -1165,11 +1234,13 @@ let ``Operator precendence tests`` () = ("1+2>2*3", true, toExpr (GT(ADD(toInt 1, toInt 2) |> toExpr, (MUL(toInt 2, toInt 3) |> toExpr))), []) ("A(5+7)?2^3|B(3)/2", true, - toExpr - (CONDITIONAL - (CallLikeExpression(toIdentifier "A", [ ADD(toInt 5, toInt 7) |> toExpr ] |> toTuple) |> toExpr, - POW(toInt 2, toInt 3) |> toExpr, - DIV(CallLikeExpression(toIdentifier "B", [ toInt 3 ] |> toTuple) |> toExpr, toInt 2) |> toExpr)), + toExpr ( + CONDITIONAL( + CallLikeExpression(toIdentifier "A", [ ADD(toInt 5, toInt 7) |> toExpr ] |> toTuple) |> toExpr, + POW(toInt 2, toInt 3) |> toExpr, + DIV(CallLikeExpression(toIdentifier "B", [ toInt 3 ] |> toTuple) |> toExpr, toInt 2) |> toExpr + ) + ), []) ] |> List.iter testExpr diff --git a/src/QsCompiler/Tests.Compiler/TestUtils/SetupVerificationTests.fs b/src/QsCompiler/Tests.Compiler/TestUtils/SetupVerificationTests.fs index b1e62c98c6..c21eb671dc 100644 --- a/src/QsCompiler/Tests.Compiler/TestUtils/SetupVerificationTests.fs +++ b/src/QsCompiler/Tests.Compiler/TestUtils/SetupVerificationTests.fs @@ -34,15 +34,16 @@ type CompilerTests(compilation: CompilationUnitManager.Compilation) = | TypeConstructor -> types.[c.FullName].Attributes | _ -> c.Attributes - if attributes.Length = 0 - then (c.Location.ValueOrApply(fun _ -> failwith "missing position information")).Offset - else attributes |> Seq.map (fun att -> att.Offset) |> Seq.sort |> Seq.head + if attributes.Length = 0 then + (c.Location.ValueOrApply(fun _ -> failwith "missing position information")).Offset + else + attributes |> Seq.map (fun att -> att.Offset) |> Seq.sort |> Seq.head [ for file in compilation.SourceFiles do let containedCallables = - callables.Where(fun kv -> - Source.assemblyOrCodeFile kv.Value.Source = file && kv.Value.Location <> Null) + callables.Where + (fun kv -> Source.assemblyOrCodeFile kv.Value.Source = file && kv.Value.Location <> Null) let locations = containedCallables.Select(fun kv -> kv.Key, kv.Value |> getCallableStart) @@ -72,50 +73,60 @@ type CompilerTests(compilation: CompilationUnitManager.Compilation) = let got = diag.Where(fun d -> d.Severity = severity) - |> Seq.choose (fun d -> - match Diagnostics.TryGetCode d.Code with - | true, code -> Some code - | false, _ -> None) + |> Seq.choose + (fun d -> + match Diagnostics.TryGetCode d.Code with + | true, code -> Some code + | false, _ -> None) let codeMismatch = expected.ToImmutableHashSet().SymmetricExcept got let gotLookup = got.ToLookup(new Func<_, _>(id)) let expectedLookup = expected.ToLookup(new Func<_, _>(id)) let nrMismatch = gotLookup.Where(fun g -> g.Count() <> expectedLookup.[g.Key].Count()) - Assert.False - (codeMismatch.Any() || nrMismatch.Any(), - sprintf "%A code mismatch for %s.%s \nexpected: %s\ngot: %s" severity name.Namespace name.Name - (String.Join(", ", expected)) (String.Join(", ", got))) + Assert.False( + codeMismatch.Any() || nrMismatch.Any(), + sprintf + "%A code mismatch for %s.%s \nexpected: %s\ngot: %s" + severity + name.Namespace + name.Name + (String.Join(", ", expected)) + (String.Join(", ", got)) + ) member this.Verify(name, expected: IEnumerable) = let expected = expected.Select(fun code -> int code) - VerifyDiagnosticsOfSeverity (Nullable DiagnosticSeverity.Error) name expected + VerifyDiagnosticsOfSeverity(Nullable DiagnosticSeverity.Error) name expected member this.Verify(name, expected: IEnumerable) = let expected = expected.Select(fun code -> int code) - VerifyDiagnosticsOfSeverity (Nullable DiagnosticSeverity.Warning) name expected + VerifyDiagnosticsOfSeverity(Nullable DiagnosticSeverity.Warning) name expected member this.Verify(name, expected: IEnumerable) = let expected = expected.Select(fun code -> int code) - VerifyDiagnosticsOfSeverity (Nullable DiagnosticSeverity.Information) name expected + VerifyDiagnosticsOfSeverity(Nullable DiagnosticSeverity.Information) name expected member this.VerifyDiagnostics(name, expected: IEnumerable) = let errs = expected - |> Seq.choose (function + |> Seq.choose + (function | Error err -> Some err | _ -> None) let wrns = expected - |> Seq.choose (function + |> Seq.choose + (function | Warning wrn -> Some wrn | _ -> None) let infs = expected - |> Seq.choose (function + |> Seq.choose + (function | Information inf -> Some inf | _ -> None) @@ -125,13 +136,13 @@ type CompilerTests(compilation: CompilationUnitManager.Compilation) = let other = expected - |> Seq.choose (function + |> Seq.choose + (function | Warning _ | Error _ -> None | item -> Some item) - if other.Any() - then NotImplementedException "unknown diagnostics item to verify" |> raise + if other.Any() then NotImplementedException "unknown diagnostics item to verify" |> raise static member Compile(srcFolder, fileNames, ?references, ?capability) = @@ -154,7 +165,6 @@ type CompilerTests(compilation: CompilationUnitManager.Compilation) = let compilation = manager.Build() - if not <| List.isEmpty exceptions - then exceptions |> List.rev |> AggregateException |> raise + if not <| List.isEmpty exceptions then exceptions |> List.rev |> AggregateException |> raise compilation diff --git a/src/QsCompiler/Tests.Compiler/TestUtils/Signatures.fs b/src/QsCompiler/Tests.Compiler/TestUtils/Signatures.fs index 719a4e9375..4b1d747d9d 100644 --- a/src/QsCompiler/Tests.Compiler/TestUtils/Signatures.fs +++ b/src/QsCompiler/Tests.Compiler/TestUtils/Signatures.fs @@ -65,10 +65,11 @@ let public SignatureCheck checkedNamespaces targetSignatures compilation = checkedNamespaces |> Seq.map (fun checkedNs -> getNs checkedNs) |> SyntaxTreeExtensions.Callables - |> Seq.map (fun call -> - (call.FullName, - StripPositionInfo.Apply call.Signature.ArgumentType, - StripPositionInfo.Apply call.Signature.ReturnType)) + |> Seq.map + (fun call -> + (call.FullName, + StripPositionInfo.Apply call.Signature.ArgumentType, + StripPositionInfo.Apply call.Signature.ReturnType)) let doesCallMatchSig call signature = let (call_fullName: QsQualifiedName), call_argType, call_rtrnType = call @@ -94,14 +95,15 @@ let public SignatureCheck checkedNamespaces targetSignatures compilation = callableSigs |> Seq.tryFindIndex (fun callSig -> doesCallMatchSig callSig targetSig) |> (fun x -> - Assert.True - (x <> None, - sprintf - "Expected but did not find: %s.*%s %s : %A" - sig_fullName.Namespace - sig_fullName.Name - (makeArgsString sig_argType) - sig_rtrnType.Resolution) + Assert.True( + x <> None, + sprintf + "Expected but did not find: %s.*%s %s : %A" + sig_fullName.Namespace + sig_fullName.Name + (makeArgsString sig_argType) + sig_rtrnType.Resolution + ) callableSigs <- removeAt x.Value callableSigs) @@ -109,12 +111,13 @@ let public SignatureCheck checkedNamespaces targetSignatures compilation = for callSig in callableSigs do let sig_fullName, sig_argType, sig_rtrnType = callSig - failwith - (sprintf + failwith ( + sprintf "Found unexpected callable: %O %s : %A" - sig_fullName - (makeArgsString sig_argType) - sig_rtrnType.Resolution) + sig_fullName + (makeArgsString sig_argType) + sig_rtrnType.Resolution + ) /// Names of several testing namespaces let public MonomorphizationNS = "Microsoft.Quantum.Testing.Monomorphization" diff --git a/src/QsCompiler/Tests.Compiler/TestUtils/TestUtils.fs b/src/QsCompiler/Tests.Compiler/TestUtils/TestUtils.fs index ba109e09df..4ba1492ff6 100644 --- a/src/QsCompiler/Tests.Compiler/TestUtils/TestUtils.fs +++ b/src/QsCompiler/Tests.Compiler/TestUtils/TestUtils.fs @@ -48,21 +48,21 @@ let simpleParseString parser string = | Failure (_) -> false let parse_string parser str = - let diags: QsCompilerDiagnostic list = [] + let diags : QsCompilerDiagnostic list = [] match CharParsers.runParserOnString parser diags "" str with | Success (_) -> true | Failure (_) -> false let parse_string_diags parser str = - let diags: QsCompilerDiagnostic list = [] + let diags : QsCompilerDiagnostic list = [] match CharParsers.runParserOnString parser diags "" str with | Success (_, ustate, _) -> true, ustate | Failure (_) -> false, [] let parse_string_diags_res parser str = - let diags: QsCompilerDiagnostic list = [] + let diags : QsCompilerDiagnostic list = [] match CharParsers.runParserOnString parser diags "" str with | Success (res, ustate, _) -> true, ustate, Some res @@ -79,7 +79,8 @@ let toBigInt b = let toSymbol s = { Symbol = Symbol s; Range = Null } -let toIdentifier s = (Identifier(toSymbol s, Null)) |> toExpr +let toIdentifier s = + (Identifier(toSymbol s, Null)) |> toExpr let toTuple (es: QsExpression seq) = ValueTuple(es.ToImmutableArray()) |> toExpr @@ -174,11 +175,12 @@ let rec matchExpression e1 e2 = a1.Length = a2.Length && Seq.forall2 matchExpression a1 a2 let matchTypeArray (t1: QsNullable>) (t2: QsNullable>) = - if t1 <> Null && t2 <> Null - then Seq.forall2 matchType (t1.ValueOr ImmutableArray.Empty) (t2.ValueOr ImmutableArray.Empty) - elif t1 = Null && t2 = Null - then true - else false + if t1 <> Null && t2 <> Null then + Seq.forall2 matchType (t1.ValueOr ImmutableArray.Empty) (t2.ValueOr ImmutableArray.Empty) + elif t1 = Null && t2 = Null then + true + else + false let ex1 = e1.Expression let ex2 = e2.Expression @@ -353,28 +355,29 @@ let testOne parser (str, succExp, resExp, diagsExp) = let resOk = (not succ) || (res |> Option.contains resExp) let errsOk = (not succ) || (matchDiagnostics diagsExp diags) - Assert.True - (succOk && resOk && errsOk, - sprintf - "String %s: %s" - str - (if not succOk - then sprintf "%s unexpectedly" (if succExp then "failed" else "passed") - elif not resOk - then sprintf "expected result %A but received %A" resExp res.Value - else sprintf "expected errors %A but received %A" diagsExp diags)) + Assert.True( + succOk && resOk && errsOk, + sprintf + "String %s: %s" + str + (if not succOk then sprintf "%s unexpectedly" (if succExp then "failed" else "passed") + elif not resOk then sprintf "expected result %A but received %A" resExp res.Value + else sprintf "expected errors %A but received %A" diagsExp diags) + ) let internal testType (str, result, diagnostics) = let success, diagnostics', result' = parse_string_diags_res TypeParsing.qsType str Assert.True(success, sprintf "Failed to parse: %s" str) - Assert.True - (result' |> Option.exists (matchType result), - sprintf "Type: %s\n\nExpected result:\n%A\n\nActual result:\n%A" str result result') + Assert.True( + result' |> Option.exists (matchType result), + sprintf "Type: %s\n\nExpected result:\n%A\n\nActual result:\n%A" str result result' + ) - Assert.True - (matchDiagnostics diagnostics diagnostics', - sprintf "Type: %s\n\nExpected diagnostics:\n%A\n\nActual diagnostics:\n%A" str diagnostics diagnostics') + Assert.True( + matchDiagnostics diagnostics diagnostics', + sprintf "Type: %s\n\nExpected diagnostics:\n%A\n\nActual diagnostics:\n%A" str diagnostics diagnostics' + ) let testExpr (str, succExp, resExp, diagsExp) = let succ, diags, res = parse_string_diags_res ExpressionParsing.expr str @@ -382,13 +385,12 @@ let testExpr (str, succExp, resExp, diagsExp) = let resOk = (not succ) || (res |> Option.exists (matchExpression resExp)) let errsOk = (not succ) || (matchDiagnostics diagsExp diags) - Assert.True - (succOk && resOk && errsOk, - sprintf - "Expression %s: %s" - str - (if not succOk - then sprintf "%s unexpectedly" (if succExp then "failed" else "passed") - elif not resOk - then sprintf "expected result %A but received %A" resExp res.Value - else sprintf "expected errors %A but received %A" diagsExp diags)) + Assert.True( + succOk && resOk && errsOk, + sprintf + "Expression %s: %s" + str + (if not succOk then sprintf "%s unexpectedly" (if succExp then "failed" else "passed") + elif not resOk then sprintf "expected result %A but received %A" resExp res.Value + else sprintf "expected errors %A but received %A" diagsExp diags) + ) diff --git a/src/QsCompiler/Tests.Compiler/TestUtils/Transformations.fs b/src/QsCompiler/Tests.Compiler/TestUtils/Transformations.fs index e32e86158a..d85e6d51aa 100644 --- a/src/QsCompiler/Tests.Compiler/TestUtils/Transformations.fs +++ b/src/QsCompiler/Tests.Compiler/TestUtils/Transformations.fs @@ -23,8 +23,12 @@ and private CheckDeclarations private (_internal_, onTypeDecl, onCallableDecl, o member internal this.CheckSpecializationDeclaration = onSpecDecl new(?onTypeDecl, ?onCallableDecl, ?onSpecDecl) as this = - CheckDeclarations - ("_internal_", defaultArg onTypeDecl id, defaultArg onCallableDecl id, defaultArg onSpecDecl id) + CheckDeclarations( + "_internal_", + defaultArg onTypeDecl id, + defaultArg onCallableDecl id, + defaultArg onSpecDecl id + ) then this.Types <- new TypeTransformation(this, TransformationOptions.Disabled) this.Expressions <- new ExpressionTransformation(this, TransformationOptions.Disabled) diff --git a/src/QsCompiler/Tests.Compiler/TextTests.fs b/src/QsCompiler/Tests.Compiler/TextTests.fs index 29918297f9..b9e43818a0 100644 --- a/src/QsCompiler/Tests.Compiler/TextTests.fs +++ b/src/QsCompiler/Tests.Compiler/TextTests.fs @@ -31,10 +31,13 @@ let ``Simple punctuation tests`` () = Assert.True(simpleParseString unitValue "()", "Unit value positive") Assert.True(simpleParseString unitValue "( )", "Unit value positive 2") - Assert.True - (simpleParseString unitValue @"( + Assert.True( + simpleParseString + unitValue + @"( )", - "Unit value positive 3") + "Unit value positive 3" + ) Assert.False(simpleParseString unitValue "unit", "Unit value negative") diff --git a/src/QsCompiler/Tests.Compiler/TransformationTests.fs b/src/QsCompiler/Tests.Compiler/TransformationTests.fs index 24a650f718..b23145aa35 100644 --- a/src/QsCompiler/Tests.Compiler/TransformationTests.fs +++ b/src/QsCompiler/Tests.Compiler/TransformationTests.fs @@ -146,8 +146,7 @@ let ``attaching attributes to callables`` () = spec let checkType (customType: QsCustomType) = - if customType |> QsCustomType |> WithinNamespace attGenNs - then Assert.Empty customType.Attributes + if customType |> QsCustomType |> WithinNamespace attGenNs then Assert.Empty customType.Attributes customType @@ -175,10 +174,11 @@ let ``attaching attributes to callables`` () = checker.OnCompilation transformed |> ignore let transformed = - AttributeUtils.AddToCallables - (compilation, - struct (testAttribute, new Func<_, _>(predicate)), - struct (testAttribute, new Func<_, _>(predicate))) + AttributeUtils.AddToCallables( + compilation, + struct (testAttribute, new Func<_, _>(predicate)), + struct (testAttribute, new Func<_, _>(predicate)) + ) let checker = new CheckDeclarations(checkType, checkCallable attGenNs 2, checkSpec) checker.OnCompilation transformed |> ignore @@ -191,12 +191,14 @@ let ``attaching attributes to callables`` () = [] let ``generation of open statements`` () = let compilation = - buildSyntaxTree @" + buildSyntaxTree + @" namespace Microsoft.Quantum.Testing { operation emptyOperation () : Unit {} }" let ns = compilation.Namespaces |> Seq.head + let source = match ns.Elements.Single() with | QsCallable callable -> Source.assemblyOrCodeFile callable.Source diff --git a/src/QsCompiler/Tests.Compiler/TypeParameterTests.fs b/src/QsCompiler/Tests.Compiler/TypeParameterTests.fs index 16452ee6d6..5af12f13de 100644 --- a/src/QsCompiler/Tests.Compiler/TypeParameterTests.fs +++ b/src/QsCompiler/Tests.Compiler/TypeParameterTests.fs @@ -51,7 +51,10 @@ type TypeParameterTests() = let AssertExpectedResolution expected given = Assert.True(CheckResolutionMatch expected given, "Given resolutions did not match the expected resolutions.") - let CheckCombinedResolution expected (resolutions: ImmutableDictionary<(QsQualifiedName * string), ResolvedType> []) = + let CheckCombinedResolution + expected + (resolutions: ImmutableDictionary<(QsQualifiedName * string), ResolvedType> []) + = let combination = TypeResolutionCombination(resolutions) AssertExpectedResolution expected combination.CombinedResolutionDictionary combination.IsValid @@ -70,8 +73,12 @@ type TypeParameterTests() = new Uri(Path.GetFullPath(Path.GetRandomFileName())) let getManager uri content = - CompilationUnitManager.InitializeFileManager - (uri, content, compilationManager.PublishDiagnostics, compilationManager.LogException) + CompilationUnitManager.InitializeFileManager( + uri, + content, + compilationManager.PublishDiagnostics, + compilationManager.LogException + ) let ReadAndChunkSourceFile fileName = let sourceInput = Path.Combine("TestCases", fileName) |> File.ReadAllText diff --git a/src/QsCompiler/TextProcessor/CodeCompletion/ParsingPrimitives.fs b/src/QsCompiler/TextProcessor/CodeCompletion/ParsingPrimitives.fs index e500babe9c..7e21400b0e 100644 --- a/src/QsCompiler/TextProcessor/CodeCompletion/ParsingPrimitives.fs +++ b/src/QsCompiler/TextProcessor/CodeCompletion/ParsingPrimitives.fs @@ -140,8 +140,8 @@ let manyR p shouldBacktrack stream = let consumedEot = (previousCharSatisfies ((<>) '\u0004') stream).Status = Ok stream.BacktrackTo(fst last.Result) - if ((notFollowedBy shouldBacktrack >>. notFollowedBy eot) stream).Status = Ok || consumedEot - then stream.BacktrackTo after + if ((notFollowedBy shouldBacktrack >>. notFollowedBy eot) stream).Status = Ok || consumedEot then + stream.BacktrackTo after Reply(snd last.Result) @@ -179,7 +179,7 @@ let tuple1 p = let omittedSymbols = { parse = keyword "..."; id = "..." } /// Parses the unit value. The right bracket is optional if EOT occurs first. -let unitValue: Parser = term (pchar '(' >>. emptySpace >>. expected (pchar ')')) |>> fst +let unitValue : Parser = term (pchar '(' >>. emptySpace >>. expected (pchar ')')) |>> fst /// Creates an expression parser using the given prefix operator, infix operator, postfix operator, and term parsers. let createExpressionParser prefixOp infixOp postfixOp expTerm = diff --git a/src/QsCompiler/TextProcessor/ParsingPrimitives.fs b/src/QsCompiler/TextProcessor/ParsingPrimitives.fs index c15024b58c..9402b7fa8a 100644 --- a/src/QsCompiler/TextProcessor/ParsingPrimitives.fs +++ b/src/QsCompiler/TextProcessor/ParsingPrimitives.fs @@ -23,7 +23,7 @@ let internal emptySpace = manySatisfy Text.IsWhitespace // whitespace management -let private rws p: Parser<_, QsCompilerDiagnostic list> = attempt p .>> emptySpace // making all parsers non-generic here for the sake of performance! +let private rws p : Parser<_, QsCompilerDiagnostic list> = attempt p .>> emptySpace // making all parsers non-generic here for the sake of performance! let private rwstr s = pstring s |> rws // symbols and names @@ -45,17 +45,17 @@ let internal isSymbolContinuation c = System.Char.IsLetter(c) // Covers Lu, Ll, Lt, Lm, Lo || List.contains (System.Char.GetUnicodeCategory c) - [ - System.Globalization.UnicodeCategory.LetterNumber // Nl - System.Globalization.UnicodeCategory.DecimalDigitNumber // Nd - System.Globalization.UnicodeCategory.ConnectorPunctuation // Pc (includes underscore) - System.Globalization.UnicodeCategory.NonSpacingMark // Mn - System.Globalization.UnicodeCategory.SpacingCombiningMark // Mc - System.Globalization.UnicodeCategory.Format // Cf - ] + [ + System.Globalization.UnicodeCategory.LetterNumber // Nl + System.Globalization.UnicodeCategory.DecimalDigitNumber // Nd + System.Globalization.UnicodeCategory.ConnectorPunctuation // Pc (includes underscore) + System.Globalization.UnicodeCategory.NonSpacingMark // Mn + System.Globalization.UnicodeCategory.SpacingCombiningMark // Mc + System.Globalization.UnicodeCategory.Format // Cf + ] /// Returns the current position in the input stream. -let internal getPosition = CharParsers.getPosition |>> fun p -> Position.Create (int p.Line - 1) (int p.Column - 1) +let internal getPosition = CharParsers.getPosition |>> fun p -> Position.Create(int p.Line - 1) (int p.Column - 1) /// Returns the result of 'p' and the character range that 'p' consumed. let internal getRange p = diff --git a/src/QsCompiler/TextProcessor/QsExpressionParsing.fs b/src/QsCompiler/TextProcessor/QsExpressionParsing.fs index a804aff80d..de77ac2544 100644 --- a/src/QsCompiler/TextProcessor/QsExpressionParsing.fs +++ b/src/QsCompiler/TextProcessor/QsExpressionParsing.fs @@ -59,124 +59,165 @@ let private deprecatedOp warning (parsedOp: string) = buildWarning (getPosition |>> precedingRange) warning -qsExpression.AddOperator - (TernaryOperator - (qsCopyAndUpdateOp.op, - emptySpace, - qsCopyAndUpdateOp.cont, - emptySpace, - qsCopyAndUpdateOp.prec, - qsCopyAndUpdateOp.Associativity, - applyTerinary CopyAndUpdate)) - -qsExpression.AddOperator - (TernaryOperator - (qsConditionalOp.op, - emptySpace, - qsConditionalOp.cont, - emptySpace, - qsConditionalOp.prec, - qsConditionalOp.Associativity, - applyTerinary CONDITIONAL)) - -qsExpression.AddOperator - (InfixOperator(qsRangeOp.op, emptySpace, qsRangeOp.prec, qsRangeOp.Associativity, (), applyBinary RangeLiteral)) +qsExpression.AddOperator( + TernaryOperator( + qsCopyAndUpdateOp.op, + emptySpace, + qsCopyAndUpdateOp.cont, + emptySpace, + qsCopyAndUpdateOp.prec, + qsCopyAndUpdateOp.Associativity, + applyTerinary CopyAndUpdate + ) +) + +qsExpression.AddOperator( + TernaryOperator( + qsConditionalOp.op, + emptySpace, + qsConditionalOp.cont, + emptySpace, + qsConditionalOp.prec, + qsConditionalOp.Associativity, + applyTerinary CONDITIONAL + ) +) + +qsExpression.AddOperator( + InfixOperator(qsRangeOp.op, emptySpace, qsRangeOp.prec, qsRangeOp.Associativity, (), applyBinary RangeLiteral) +) qsExpression.AddOperator(InfixOperator(qsORop.op, emptySpace, qsORop.prec, qsORop.Associativity, (), applyBinary OR)) -qsExpression.AddOperator - (InfixOperator(qsANDop.op, emptySpace, qsANDop.prec, qsANDop.Associativity, (), applyBinary AND)) +qsExpression.AddOperator( + InfixOperator(qsANDop.op, emptySpace, qsANDop.prec, qsANDop.Associativity, (), applyBinary AND) +) -qsExpression.AddOperator - (InfixOperator(qsBORop.op, emptySpace, qsBORop.prec, qsBORop.Associativity, (), applyBinary BOR)) +qsExpression.AddOperator( + InfixOperator(qsBORop.op, emptySpace, qsBORop.prec, qsBORop.Associativity, (), applyBinary BOR) +) -qsExpression.AddOperator - (InfixOperator(qsBXORop.op, emptySpace, qsBXORop.prec, qsBXORop.Associativity, (), applyBinary BXOR)) +qsExpression.AddOperator( + InfixOperator(qsBXORop.op, emptySpace, qsBXORop.prec, qsBXORop.Associativity, (), applyBinary BXOR) +) -qsExpression.AddOperator - (InfixOperator(qsBANDop.op, emptySpace, qsBANDop.prec, qsBANDop.Associativity, (), applyBinary BAND)) +qsExpression.AddOperator( + InfixOperator(qsBANDop.op, emptySpace, qsBANDop.prec, qsBANDop.Associativity, (), applyBinary BAND) +) qsExpression.AddOperator(InfixOperator(qsEQop.op, emptySpace, qsEQop.prec, qsEQop.Associativity, (), applyBinary EQ)) -qsExpression.AddOperator - (InfixOperator(qsNEQop.op, emptySpace, qsNEQop.prec, qsNEQop.Associativity, (), applyBinary NEQ)) - -qsExpression.AddOperator - (InfixOperator(qsLTEop.op, emptySpace, qsLTEop.prec, qsLTEop.Associativity, (), applyBinary LTE)) - -qsExpression.AddOperator - (InfixOperator(qsGTEop.op, emptySpace, qsGTEop.prec, qsGTEop.Associativity, (), applyBinary GTE)) - -qsExpression.AddOperator - (InfixOperator - (qsLTop.op, notFollowedBy (pchar '-') >>. emptySpace, qsLTop.prec, qsLTop.Associativity, (), applyBinary LT)) +qsExpression.AddOperator( + InfixOperator(qsNEQop.op, emptySpace, qsNEQop.prec, qsNEQop.Associativity, (), applyBinary NEQ) +) + +qsExpression.AddOperator( + InfixOperator(qsLTEop.op, emptySpace, qsLTEop.prec, qsLTEop.Associativity, (), applyBinary LTE) +) + +qsExpression.AddOperator( + InfixOperator(qsGTEop.op, emptySpace, qsGTEop.prec, qsGTEop.Associativity, (), applyBinary GTE) +) + +qsExpression.AddOperator( + InfixOperator( + qsLTop.op, + notFollowedBy (pchar '-') >>. emptySpace, + qsLTop.prec, + qsLTop.Associativity, + (), + applyBinary LT + ) +) qsExpression.AddOperator(InfixOperator(qsGTop.op, emptySpace, qsGTop.prec, qsGTop.Associativity, (), applyBinary GT)) -qsExpression.AddOperator - (InfixOperator(qsRSHIFTop.op, emptySpace, qsRSHIFTop.prec, qsRSHIFTop.Associativity, (), applyBinary RSHIFT)) - -qsExpression.AddOperator - (InfixOperator(qsLSHIFTop.op, emptySpace, qsLSHIFTop.prec, qsLSHIFTop.Associativity, (), applyBinary LSHIFT)) - -qsExpression.AddOperator - (InfixOperator(qsADDop.op, emptySpace, qsADDop.prec, qsADDop.Associativity, (), applyBinary ADD)) - -qsExpression.AddOperator - (InfixOperator(qsSUBop.op, emptySpace, qsSUBop.prec, qsSUBop.Associativity, (), applyBinary SUB)) - -qsExpression.AddOperator - (InfixOperator(qsMULop.op, emptySpace, qsMULop.prec, qsMULop.Associativity, (), applyBinary MUL)) - -qsExpression.AddOperator - (InfixOperator(qsMODop.op, emptySpace, qsMODop.prec, qsMODop.Associativity, (), applyBinary MOD)) - -qsExpression.AddOperator - (InfixOperator - (qsDIVop.op, notFollowedBy (pchar '/') >>. emptySpace, qsDIVop.prec, qsDIVop.Associativity, (), applyBinary DIV)) - -qsExpression.AddOperator - (InfixOperator(qsPOWop.op, emptySpace, qsPOWop.prec, qsPOWop.Associativity, (), applyBinary POW)) +qsExpression.AddOperator( + InfixOperator(qsRSHIFTop.op, emptySpace, qsRSHIFTop.prec, qsRSHIFTop.Associativity, (), applyBinary RSHIFT) +) + +qsExpression.AddOperator( + InfixOperator(qsLSHIFTop.op, emptySpace, qsLSHIFTop.prec, qsLSHIFTop.Associativity, (), applyBinary LSHIFT) +) + +qsExpression.AddOperator( + InfixOperator(qsADDop.op, emptySpace, qsADDop.prec, qsADDop.Associativity, (), applyBinary ADD) +) + +qsExpression.AddOperator( + InfixOperator(qsSUBop.op, emptySpace, qsSUBop.prec, qsSUBop.Associativity, (), applyBinary SUB) +) + +qsExpression.AddOperator( + InfixOperator(qsMULop.op, emptySpace, qsMULop.prec, qsMULop.Associativity, (), applyBinary MUL) +) + +qsExpression.AddOperator( + InfixOperator(qsMODop.op, emptySpace, qsMODop.prec, qsMODop.Associativity, (), applyBinary MOD) +) + +qsExpression.AddOperator( + InfixOperator( + qsDIVop.op, + notFollowedBy (pchar '/') >>. emptySpace, + qsDIVop.prec, + qsDIVop.Associativity, + (), + applyBinary DIV + ) +) + +qsExpression.AddOperator( + InfixOperator(qsPOWop.op, emptySpace, qsPOWop.prec, qsPOWop.Associativity, (), applyBinary POW) +) qsExpression.AddOperator(PrefixOperator(qsBNOTop.op, emptySpace, qsBNOTop.prec, true, (), applyUnary BNOT)) -qsExpression.AddOperator - (PrefixOperator - (qsNOTop.op, - notFollowedBy (many1Satisfy isSymbolContinuation) >>. emptySpace, - qsNOTop.prec, - true, - (), - applyUnary NOT)) +qsExpression.AddOperator( + PrefixOperator( + qsNOTop.op, + notFollowedBy (many1Satisfy isSymbolContinuation) >>. emptySpace, + qsNOTop.prec, + true, + (), + applyUnary NOT + ) +) qsExpression.AddOperator(PrefixOperator(qsNEGop.op, emptySpace, qsNEGop.prec, true, (), applyUnary NEG)) -qsExpression.AddOperator - (PrefixOperator - ("!", - "!" |> deprecatedOp WarningCode.DeprecatedNOToperator >>. emptySpace, - qsNOTop.prec, - true, - (), - applyUnary NOT)) - -qsExpression.AddOperator - (InfixOperator - ("||", - "||" |> deprecatedOp WarningCode.DeprecatedORoperator >>. emptySpace, - qsORop.prec, - qsORop.Associativity, - (), - applyBinary OR)) - -qsExpression.AddOperator - (InfixOperator - ("&&", - "&&" |> deprecatedOp WarningCode.DeprecatedANDoperator >>. emptySpace, - qsANDop.prec, - qsANDop.Associativity, - (), - applyBinary AND)) +qsExpression.AddOperator( + PrefixOperator( + "!", + "!" |> deprecatedOp WarningCode.DeprecatedNOToperator >>. emptySpace, + qsNOTop.prec, + true, + (), + applyUnary NOT + ) +) + +qsExpression.AddOperator( + InfixOperator( + "||", + "||" |> deprecatedOp WarningCode.DeprecatedORoperator >>. emptySpace, + qsORop.prec, + qsORop.Associativity, + (), + applyBinary OR + ) +) + +qsExpression.AddOperator( + InfixOperator( + "&&", + "&&" |> deprecatedOp WarningCode.DeprecatedANDoperator >>. emptySpace, + qsANDop.prec, + qsANDop.Associativity, + (), + applyBinary AND + ) +) for op in qsExpression.Operators do qsArgument.AddOperator op @@ -313,8 +354,11 @@ let internal numericLiteral = |> BigIntLiteral |> returnWithRange elif format = 2 || format = 8 then - BigInteger.Parse - (baseToHex (format, str), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture) + BigInteger.Parse( + baseToHex (format, str), + NumberStyles.AllowHexSpecifier, + CultureInfo.InvariantCulture + ) |> BigIntLiteral |> returnWithRange else @@ -351,14 +395,13 @@ let internal numericLiteral = // re-parse making sure to not process fractions ... let number omitFraction = numberLiteral - (if omitFraction - then format - NumberLiteralOptions.AllowFraction - else format) + (if omitFraction then format - NumberLiteralOptions.AllowFraction else format) "number literal" >>= fun nl -> - if nl.String.Chars(nl.String.Length - 1) <> '.' - then preturn nl - else notFollowedBy (pchar '.') >>. preturn nl + if nl.String.Chars(nl.String.Length - 1) <> '.' then + preturn nl + else + notFollowedBy (pchar '.') >>. preturn nl // note that on a first pass, all options *need* to be parsed together -> don't split into double and int!! attempt (number false) <|> attempt (number true) diff --git a/src/QsCompiler/TextProcessor/QsFragmentParsing.fs b/src/QsCompiler/TextProcessor/QsFragmentParsing.fs index 99e863dd00..25c1d78f0b 100644 --- a/src/QsCompiler/TextProcessor/QsFragmentParsing.fs +++ b/src/QsCompiler/TextProcessor/QsFragmentParsing.fs @@ -359,7 +359,11 @@ let private controlledDeclaration = let private controlledAdjointDeclaration = let invalid = ControlledAdjointDeclaration unknownGenerator - buildFragment (attempt ctrlAdjDeclHeader.parse) functorGenDirective invalid (fun _ -> ControlledAdjointDeclaration) + buildFragment + (attempt ctrlAdjDeclHeader.parse) + functorGenDirective + invalid + (fun _ -> ControlledAdjointDeclaration) eof /// Uses buildFragment to parse a Q# OperationDeclaration as QsFragment. @@ -442,15 +446,23 @@ let private failStatement = let private letStatement = let invalid = ImmutableBinding(invalidSymbol, unknownExpr) - buildFragment qsImmutableBinding.parse (expectedExpr eof |> symbolBinding equal ErrorCode.ExpectingAssignment) - invalid (fun _ -> ImmutableBinding) eof + buildFragment + qsImmutableBinding.parse + (expectedExpr eof |> symbolBinding equal ErrorCode.ExpectingAssignment) + invalid + (fun _ -> ImmutableBinding) + eof /// Uses buildFragment to parse a Q# mutable binding (i.e. mutable-statement) as QsFragment. let private mutableStatement = let invalid = MutableBinding(invalidSymbol, unknownExpr) - buildFragment qsMutableBinding.parse (expectedExpr eof |> symbolBinding equal ErrorCode.ExpectingAssignment) invalid (fun _ -> - MutableBinding) eof + buildFragment + qsMutableBinding.parse + (expectedExpr eof |> symbolBinding equal ErrorCode.ExpectingAssignment) + invalid + (fun _ -> MutableBinding) + eof /// Uses buildFragment to parse a Q# value update (i.e. set-statement) as QsFragment. @@ -580,7 +592,11 @@ let private untilSuccess = let invalid = UntilSuccess(unknownExpr, false) let optionalFixup = qsRUSfixup.parse >>% true <|> preturn false - buildFragment qsUntil.parse (expectedCondition qsRUSfixup.parse .>>. optionalFixup) invalid (fun _ -> UntilSuccess) + buildFragment + qsUntil.parse + (expectedCondition qsRUSfixup.parse .>>. optionalFixup) + invalid + (fun _ -> UntilSuccess) eof @@ -652,13 +668,13 @@ let private fragments = (qsInternal, buildInvalidFragment qsInternal.parse) ] -// Make sure all of the fragment header keywords are listed above. -do let implementedHeaders = (List.map (fun (keyword, _) -> keyword.id) fragments).ToImmutableHashSet() - let existingHeaders = Keywords.FragmentHeaders.ToImmutableHashSet() +do + let implementedHeaders = (List.map (fun (keyword, _) -> keyword.id) fragments).ToImmutableHashSet() + let existingHeaders = Keywords.FragmentHeaders.ToImmutableHashSet() - if (implementedHeaders.SymmetricExcept existingHeaders).Count <> 0 then - System.NotImplementedException "mismatch between existing Q# fragments and implemented Q# fragments" - |> raise + if (implementedHeaders.SymmetricExcept existingHeaders).Count <> 0 then + System.NotImplementedException "mismatch between existing Q# fragments and implemented Q# fragments" + |> raise /// Uses buildFragment to parse a Q# expression statement as QsFragment. diff --git a/src/QsCompiler/TextProcessor/QsKeywords.fs b/src/QsCompiler/TextProcessor/QsKeywords.fs index 8f04117120..a17c884028 100644 --- a/src/QsCompiler/TextProcessor/QsKeywords.fs +++ b/src/QsCompiler/TextProcessor/QsKeywords.fs @@ -303,6 +303,7 @@ let qsSetIntersection = QsOperator.New("*", 20, true) // All modifiers bind stronger than the call combinator. // The array item combinator binds stronger than all modifiers. let qsCallCombinator = QsOperator.New("(", ")", 900, true) // Op()() is fine + let qsAdjointModifier = QsOperator.New(qsAdjointFunctor.id, 950, false) let qsControlledModifier = QsOperator.New(qsControlledFunctor.id, 951, false) let qsUnwrapModifier = QsOperator.New("!", 1000, true) diff --git a/src/QsCompiler/TextProcessor/QsTypeParsing.fs b/src/QsCompiler/TextProcessor/QsTypeParsing.fs index 15fe1c0671..e48fd05bc8 100644 --- a/src/QsCompiler/TextProcessor/QsTypeParsing.fs +++ b/src/QsCompiler/TextProcessor/QsTypeParsing.fs @@ -33,17 +33,20 @@ let private buildCombinedExpression kind (lRange, rRange) = let private applyBinary operator _ (left: Characteristics) (right: Characteristics) = buildCombinedExpression (operator (left, right)) (left.Range, right.Range) -characteristicsExpression.AddOperator - (InfixOperator(qsSetUnion.op, emptySpace, qsSetUnion.prec, qsSetUnion.Associativity, (), applyBinary Union)) - -characteristicsExpression.AddOperator - (InfixOperator - (qsSetIntersection.op, - emptySpace, - qsSetIntersection.prec, - qsSetIntersection.Associativity, - (), - applyBinary Intersection)) +characteristicsExpression.AddOperator( + InfixOperator(qsSetUnion.op, emptySpace, qsSetUnion.prec, qsSetUnion.Associativity, (), applyBinary Union) +) + +characteristicsExpression.AddOperator( + InfixOperator( + qsSetIntersection.op, + emptySpace, + qsSetIntersection.prec, + qsSetIntersection.Associativity, + (), + applyBinary Intersection + ) +) /// Parses for an arbitrary characteristics expression. /// Fails on all reserved keywords except the ones denoting predefined sets of operation characteristics. @@ -176,8 +179,8 @@ let internal validateTypeSyntax isArrayItem { Type = kind; Range = range } = // To avoid confusing syntax like "new Int -> Int[3]" or "Qubit => Unit is Adj[]", require that function and // operation types are tupled when used as an array item type. [ - QsCompilerDiagnostic.Error (ErrorCode.MissingLTupleBracket, []) (Range.Create start start) - QsCompilerDiagnostic.Error (ErrorCode.MissingRTupleBracket, []) (Range.Create end' end') + QsCompilerDiagnostic.Error(ErrorCode.MissingLTupleBracket, []) (Range.Create start start) + QsCompilerDiagnostic.Error(ErrorCode.MissingRTupleBracket, []) (Range.Create end' end') ] |> pushDiagnostics | _ -> preturn () diff --git a/src/QsCompiler/TextProcessor/SyntaxBuilder.fs b/src/QsCompiler/TextProcessor/SyntaxBuilder.fs index 6d48fe080a..b1a97f6a3b 100644 --- a/src/QsCompiler/TextProcessor/SyntaxBuilder.fs +++ b/src/QsCompiler/TextProcessor/SyntaxBuilder.fs @@ -28,7 +28,7 @@ let getSubstring (start: CharStreamState<_>) = /// between the given char stream state and the current stream position. /// NOTE: Anything run on the substream will be processed with the user state of the original stream, /// and any updates to the user state will be reflected in the original stream. -let runOnSubstream (start: CharStreamState<_>) (parser: Parser<'A, _>): Parser<'A, _> = +let runOnSubstream (start: CharStreamState<_>) (parser: Parser<'A, _>) : Parser<'A, _> = let parserAndState = parser .>>. getUserState let subparser (stream: CharStream<_>) = @@ -218,7 +218,7 @@ let internal getStringContent interpolArg = |>> function // Also supports escapting '{' | 'n' -> "\n" | 'r' -> "\r" - | 't' -> "\t" + | 't' -> " " | c -> string c) let nonInterpol = (stringsSepBy interpolCharSnippet escapedChar) @@ -240,7 +240,7 @@ let internal getStringContent interpolArg = |>> function | 'n' -> "\n" | 'r' -> "\r" - | 't' -> "\t" + | 't' -> " " | c -> string c) let content = (stringsSepBy normalCharSnippet escapedChar) @@ -279,9 +279,10 @@ let leftRecursionByInfix breakingDelimiter before after = // before and after br getCharStreamState >>= fun state -> - attempt - (advanceToInfix >>. (before .>> followedBy eof |> runOnSubstream state) .>> breakingDelimiter - .>>. after) + attempt ( + advanceToInfix >>. (before .>> followedBy eof |> runOnSubstream state) .>> breakingDelimiter + .>>. after + ) // routines that dictate how parsing is handled accross all fragments and expression @@ -404,11 +405,12 @@ let internal buildTupleItem validSingle bundle errCode missingCode fallback cont /// In order to guarantee correct whitespace management, the name needs to be parsed as a term. let internal symbolNameLike errCode = let ident = - IdentifierOptions - (isAsciiIdStart = isSymbolStart, - isAsciiIdContinue = isSymbolContinuation, - preCheckStart = isSymbolStart, - preCheckContinue = isSymbolContinuation) + IdentifierOptions( + isAsciiIdStart = isSymbolStart, + isAsciiIdContinue = isSymbolContinuation, + preCheckStart = isSymbolStart, + preCheckContinue = isSymbolContinuation + ) |> identifier |> getRange @@ -513,27 +515,29 @@ let private filterAndAdapt (diagnostics: QsCompilerDiagnostic list) endPos = // opting to only actually raise ExcessContinuation errors if no other errors overlap with them let excessCont, remainingDiagnostics = diagnostics - |> List.partition (fun x -> - match x.Diagnostic with - | Error (ErrorCode.ExcessContinuation) -> true - | _ -> false) + |> List.partition + (fun x -> + match x.Diagnostic with + | Error (ErrorCode.ExcessContinuation) -> true + | _ -> false) let remainingErrs = remainingDiagnostics - |> List.filter (fun x -> - match x.Diagnostic with - | Error _ -> true - | _ -> false) + |> List.filter + (fun x -> + match x.Diagnostic with + | Error _ -> true + | _ -> false) let hasOverlap (diagnostic: QsCompilerDiagnostic) = remainingErrs - |> List.exists (fun other -> - diagnostic.Range.Start <= other.Range.Start && diagnostic.Range.End >= other.Range.Start) + |> List.exists + (fun other -> diagnostic.Range.Start <= other.Range.Start && diagnostic.Range.End >= other.Range.Start) let filteredExcessCont = excessCont |> List.filter (not << hasOverlap) let rangeWithinFragment (range: Range) = - Range.Create (min endPos range.Start) (min endPos range.End) + Range.Create(min endPos range.Start) (min endPos range.End) filteredExcessCont @ remainingDiagnostics |> List.map (fun diagnostic -> { diagnostic with Range = rangeWithinFragment diagnostic.Range }) diff --git a/src/QsCompiler/TextProcessor/TextProcessing.fs b/src/QsCompiler/TextProcessor/TextProcessing.fs index aa356f8869..658c681f5f 100644 --- a/src/QsCompiler/TextProcessor/TextProcessing.fs +++ b/src/QsCompiler/TextProcessor/TextProcessing.fs @@ -40,11 +40,11 @@ let private BuildUnknown text = { Kind = InvalidFragment Range = range - Diagnostics = ImmutableArray.Create(QsCompilerDiagnostic.Error (InvalidFragment.ErrorCode, []) range) + Diagnostics = ImmutableArray.Create(QsCompilerDiagnostic.Error(InvalidFragment.ErrorCode, []) range) Text = text } - let range = GetDelimiters (getRange remainingText |>> snd) text + let range = GetDelimiters(getRange remainingText |>> snd) text let unknownStatement = unknownFragment text range unknownStatement, (unknownStatement.Range.End, "") @@ -110,9 +110,7 @@ let HeaderDelimiters nrHeaders = splitHeaders |>> fun (following, range) -> - if nrHeaders <= following.Length - then Range.Create range.Start following.[nrHeaders - 1] - else range + if nrHeaders <= following.Length then Range.Create range.Start following.[nrHeaders - 1] else range |> GetDelimiters /// Parse an illegal array item update set statement for use by the copy-and-update recommendation code action. diff --git a/src/QsFmt/App.Tests/Tests.fs b/src/QsFmt/App.Tests/Tests.fs index 9306904099..74a5e9e50c 100644 --- a/src/QsFmt/App.Tests/Tests.fs +++ b/src/QsFmt/App.Tests/Tests.fs @@ -52,11 +52,11 @@ let private run args input = [] let ``Shows help with no arguments`` () = - Assert.Equal - ({ - Code = 2 - Out = "" - Error = "ERROR: missing argument ''. + Assert.Equal( + { + Code = 2 + Out = "" + Error = "ERROR: missing argument ''. INPUT: @@ -66,8 +66,9 @@ OPTIONS: --help Display this list of options. " - }, - run [||] "") + }, + run [||] "" + ) [] [] let ``Formats file`` path output = - Assert.Equal - ({ - Code = 0 - Out = output - Error = "" - }, - run [| path |] "") + Assert.Equal( + { + Code = 0 + Out = output + Error = "" + }, + run [| path |] "" + ) [] [] let ``Formats standard input`` input output = - Assert.Equal - ({ - Code = 0 - Out = output - Error = "" - }, - run [| "-" |] input) + Assert.Equal( + { + Code = 0 + Out = output + Error = "" + }, + run [| "-" |] input + ) [] [] let ``Shows syntax errors`` input errors = - Assert.Equal - ({ - Code = 1 - Out = "" - Error = errors - }, - run [| "-" |] input) + Assert.Equal( + { + Code = 1 + Out = "" + Error = errors + }, + run [| "-" |] input + ) [] [] diff --git a/src/QsFmt/Formatter.Tests/Discoverer.fs b/src/QsFmt/Formatter.Tests/Discoverer.fs index c5b5e5482f..c532dfbc46 100644 --- a/src/QsFmt/Formatter.Tests/Discoverer.fs +++ b/src/QsFmt/Formatter.Tests/Discoverer.fs @@ -80,43 +80,46 @@ module Discoverer = let private properties<'a when 'a :> Attribute> () = Assembly.GetCallingAssembly().GetTypes() |> Seq.collect (fun typ -> typ.GetProperties()) - |> Seq.choose (fun property -> - property.GetCustomAttributes typeof<'a> - |> Seq.tryHead - |> Option.map (fun attribute' -> attribute' :?> 'a, property)) + |> Seq.choose + (fun property -> + property.GetCustomAttributes typeof<'a> + |> Seq.tryHead + |> Option.map (fun attribute' -> attribute' :?> 'a, property)) /// /// The auto-discovered test cases. /// let private examples = properties () - |> Seq.choose (fun (attribute, property) -> - match property.GetValue null with - | :? (string * string) as example -> - { - Name = property.Name - Skip = Option.ofObj attribute.Skip - Before = fst example - After = snd example - } - |> Some - | _ -> None) + |> Seq.choose + (fun (attribute, property) -> + match property.GetValue null with + | :? (string * string) as example -> + { + Name = property.Name + Skip = Option.ofObj attribute.Skip + Before = fst example + After = snd example + } + |> Some + | _ -> None) /// /// The auto-discovered test cases. /// let private fixedPoints = properties () - |> Seq.choose (fun (attribute, property) -> - match property.GetValue null with - | :? string as source -> - { - Name = property.Name - Skip = Option.ofObj attribute.Skip - Source = source - } - |> Some - | _ -> None) + |> Seq.choose + (fun (attribute, property) -> + match property.GetValue null with + | :? string as source -> + { + Name = property.Name + Skip = Option.ofObj attribute.Skip + Source = source + } + |> Some + | _ -> None) /// /// Provides auto-discovered test cases as theory data. diff --git a/src/QsFmt/Formatter/Formatter.fs b/src/QsFmt/Formatter/Formatter.fs index 1ca2f9c029..a85fe61220 100644 --- a/src/QsFmt/Formatter/Formatter.fs +++ b/src/QsFmt/Formatter/Formatter.fs @@ -34,12 +34,13 @@ let parse (source: string) = [] let format source = parse source - |> Result.map - (curry collapsedSpaces.Document () - >> curry operatorSpacing.Document () - >> curry newLines.Document () - >> curry indentation.Document 0 - >> printer.Document) + |> Result.map ( + curry collapsedSpaces.Document () + >> curry operatorSpacing.Document () + >> curry newLines.Document () + >> curry indentation.Document 0 + >> printer.Document + ) [] let identity source = diff --git a/src/QsFmt/Formatter/Rules.fs b/src/QsFmt/Formatter/Rules.fs index 7ac9553973..7b0e3a3702 100644 --- a/src/QsFmt/Formatter/Rules.fs +++ b/src/QsFmt/Formatter/Rules.fs @@ -57,7 +57,8 @@ let indentPrefix level = /// /// Indents the token to the given indentation . /// -let indentTerminal level = indentPrefix level |> Terminal.mapPrefix +let indentTerminal level = + indentPrefix level |> Terminal.mapPrefix let indentation = { new Rewriter<_>() with @@ -95,7 +96,8 @@ let newLines = override _.Block((), mapper, block) = let block = base.Block((), mapper, block) - if List.isEmpty block.Items - then block - else { block with CloseBrace = Terminal.mapPrefix ensureNewLine block.CloseBrace } + if List.isEmpty block.Items then + block + else + { block with CloseBrace = Terminal.mapPrefix ensureNewLine block.CloseBrace } } diff --git a/src/QsFmt/Formatter/SyntaxTree/Node.fs b/src/QsFmt/Formatter/SyntaxTree/Node.fs index 57d42a03d5..ba2e679e95 100644 --- a/src/QsFmt/Formatter/SyntaxTree/Node.fs +++ b/src/QsFmt/Formatter/SyntaxTree/Node.fs @@ -22,7 +22,8 @@ module Trivia = | NewLine -> NewLine | Comment comment -> Comment comment - let spaces count = String.replicate count " " |> Whitespace + let spaces count = + String.replicate count " " |> Whitespace let newLine = NewLine @@ -41,9 +42,7 @@ module Trivia = let (|Prefix|_|) (pattern: string) (input: string) = let result = Regex.Match(input, "^" + pattern) - if result.Success - then Some(result.Value, input.[result.Length..]) - else None + if result.Success then Some(result.Value, input.[result.Length..]) else None let rec ofString = function diff --git a/src/QsFmt/Formatter/SyntaxTree/Reducer.fs b/src/QsFmt/Formatter/SyntaxTree/Reducer.fs index 893b1cb81b..d59df79615 100644 --- a/src/QsFmt/Formatter/SyntaxTree/Reducer.fs +++ b/src/QsFmt/Formatter/SyntaxTree/Reducer.fs @@ -10,14 +10,14 @@ type internal 'result Reducer() as reducer = /// Reduces a list of results into a single result. let reduce = curry reducer.Combine |> List.reduce - abstract Combine: 'result * 'result -> 'result + abstract Combine : 'result * 'result -> 'result - abstract Document: document:Document -> 'result + abstract Document : document: Document -> 'result default _.Document document = (document.Namespaces |> List.map reducer.Namespace) @ [ reducer.Terminal document.Eof ] |> reduce - abstract Namespace: ns:Namespace -> 'result + abstract Namespace : ns: Namespace -> 'result default _.Namespace ns = [ @@ -27,14 +27,14 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract NamespaceItem: item:NamespaceItem -> 'result + abstract NamespaceItem : item: NamespaceItem -> 'result default _.NamespaceItem item = match item with | CallableDeclaration callable -> reducer.CallableDeclaration callable | Unknown terminal -> reducer.Terminal terminal - abstract CallableDeclaration: callable:CallableDeclaration -> 'result + abstract CallableDeclaration : callable: CallableDeclaration -> 'result default _.CallableDeclaration callable = [ @@ -46,7 +46,7 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract Type: typ:Type -> 'result + abstract Type : typ: Type -> 'result default _.Type typ = match typ with @@ -59,12 +59,12 @@ type internal 'result Reducer() as reducer = | Callable callable -> reducer.CallableType callable | Type.Unknown terminal -> reducer.Terminal terminal - abstract TypeAnnotation: annotation:TypeAnnotation -> 'result + abstract TypeAnnotation : annotation: TypeAnnotation -> 'result default _.TypeAnnotation annotation = [ reducer.Terminal annotation.Colon; reducer.Type annotation.Type ] |> reduce - abstract ArrayType: array:ArrayType -> 'result + abstract ArrayType : array: ArrayType -> 'result default _.ArrayType array = [ @@ -74,7 +74,7 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract CallableType: callable:CallableType -> 'result + abstract CallableType : callable: CallableType -> 'result default _.CallableType callable = [ @@ -85,7 +85,7 @@ type internal 'result Reducer() as reducer = @ (callable.Characteristics |> Option.map reducer.CharacteristicSection |> Option.toList) |> reduce - abstract CharacteristicSection: section:CharacteristicSection -> 'result + abstract CharacteristicSection : section: CharacteristicSection -> 'result default _.CharacteristicSection section = [ @@ -94,7 +94,7 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract CharacteristicGroup: group:CharacteristicGroup -> 'result + abstract CharacteristicGroup : group: CharacteristicGroup -> 'result default _.CharacteristicGroup group = [ @@ -104,7 +104,7 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract Characteristic: characteristic:Characteristic -> 'result + abstract Characteristic : characteristic: Characteristic -> 'result default _.Characteristic characteristic = match characteristic with @@ -113,7 +113,7 @@ type internal 'result Reducer() as reducer = | Group group -> reducer.CharacteristicGroup group | Characteristic.BinaryOperator operator -> reducer.BinaryOperator(reducer.Characteristic, operator) - abstract Statement: statement:Statement -> 'result + abstract Statement : statement: Statement -> 'result default _.Statement statement = match statement with @@ -123,7 +123,7 @@ type internal 'result Reducer() as reducer = | Else elses -> reducer.Else elses | Statement.Unknown terminal -> reducer.Terminal terminal - abstract Let: lets:Let -> 'result + abstract Let : lets: Let -> 'result default _.Let lets = [ @@ -135,7 +135,7 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract Return: returns:Return -> 'result + abstract Return : returns: Return -> 'result default _.Return returns = [ @@ -145,7 +145,7 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract If: ifs:If -> 'result + abstract If : ifs: If -> 'result default _.If ifs = [ @@ -155,7 +155,7 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract Else: elses:Else -> 'result + abstract Else : elses: Else -> 'result default _.Else elses = [ @@ -164,21 +164,21 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract SymbolBinding: binding:SymbolBinding -> 'result + abstract SymbolBinding : binding: SymbolBinding -> 'result default _.SymbolBinding binding = match binding with | SymbolDeclaration declaration -> reducer.SymbolDeclaration declaration | SymbolTuple tuple -> reducer.Tuple(reducer.SymbolBinding, tuple) - abstract SymbolDeclaration: declaration:SymbolDeclaration -> 'result + abstract SymbolDeclaration : declaration: SymbolDeclaration -> 'result default _.SymbolDeclaration declaration = reducer.Terminal declaration.Name :: (declaration.Type |> Option.map reducer.TypeAnnotation |> Option.toList) |> reduce - abstract Expression: expression:Expression -> 'result + abstract Expression : expression: Expression -> 'result default _.Expression expression = match expression with @@ -189,7 +189,7 @@ type internal 'result Reducer() as reducer = | Update update -> reducer.Update update | Expression.Unknown terminal -> reducer.Terminal terminal - abstract Update: update:Update -> 'result + abstract Update : update: Update -> 'result default _.Update update = [ @@ -201,28 +201,28 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract Block: mapper:('a -> 'result) * block:'a Block -> 'result + abstract Block : mapper: ('a -> 'result) * block: 'a Block -> 'result default _.Block(mapper, block) = reducer.Terminal block.OpenBrace :: (block.Items |> List.map mapper) @ [ reducer.Terminal block.CloseBrace ] |> reduce - abstract Tuple: mapper:('a -> 'result) * tuple:'a Tuple -> 'result + abstract Tuple : mapper: ('a -> 'result) * tuple: 'a Tuple -> 'result default _.Tuple(mapper, tuple) = reducer.Terminal tuple.OpenParen :: (tuple.Items |> List.map (curry reducer.SequenceItem mapper)) @ [ reducer.Terminal tuple.CloseParen ] |> reduce - abstract SequenceItem: mapper:('a -> 'result) * item:'a SequenceItem -> 'result + abstract SequenceItem : mapper: ('a -> 'result) * item: 'a SequenceItem -> 'result default _.SequenceItem(mapper, item) = (item.Item |> Option.map mapper |> Option.toList) @ (item.Comma |> Option.map reducer.Terminal |> Option.toList) |> reduce - abstract BinaryOperator: mapper:('a -> 'result) * operator:'a BinaryOperator -> 'result + abstract BinaryOperator : mapper: ('a -> 'result) * operator: 'a BinaryOperator -> 'result default _.BinaryOperator(mapper, operator) = [ @@ -232,4 +232,4 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract Terminal: terminal:Terminal -> 'result + abstract Terminal : terminal: Terminal -> 'result diff --git a/src/QsFmt/Formatter/SyntaxTree/Rewriter.fs b/src/QsFmt/Formatter/SyntaxTree/Rewriter.fs index ad6d6bb18a..833dff6fcc 100644 --- a/src/QsFmt/Formatter/SyntaxTree/Rewriter.fs +++ b/src/QsFmt/Formatter/SyntaxTree/Rewriter.fs @@ -6,7 +6,7 @@ namespace Microsoft.Quantum.QsFmt.Formatter.SyntaxTree open Microsoft.Quantum.QsFmt.Formatter.Utils type 'context Rewriter() = - abstract Document: context:'context * document:Document -> Document + abstract Document : context: 'context * document: Document -> Document default rewriter.Document(context, document) = { @@ -14,7 +14,7 @@ type 'context Rewriter() = Eof = rewriter.Terminal(context, document.Eof) } - abstract Namespace: context:'context * ns:Namespace -> Namespace + abstract Namespace : context: 'context * ns: Namespace -> Namespace default rewriter.Namespace(context, ns) = { @@ -23,14 +23,14 @@ type 'context Rewriter() = Block = rewriter.Block(context, rewriter.NamespaceItem, ns.Block) } - abstract NamespaceItem: context:'context * item:NamespaceItem -> NamespaceItem + abstract NamespaceItem : context: 'context * item: NamespaceItem -> NamespaceItem default rewriter.NamespaceItem(context, item) = match item with | CallableDeclaration callable -> rewriter.CallableDeclaration(context, callable) |> CallableDeclaration | Unknown terminal -> rewriter.Terminal(context, terminal) |> Unknown - abstract CallableDeclaration: context:'context * callable:CallableDeclaration -> CallableDeclaration + abstract CallableDeclaration : context: 'context * callable: CallableDeclaration -> CallableDeclaration default rewriter.CallableDeclaration(context, callable) = { @@ -41,7 +41,7 @@ type 'context Rewriter() = Block = rewriter.Block(context, rewriter.Statement, callable.Block) } - abstract Type: context:'context * typ:Type -> Type + abstract Type : context: 'context * typ: Type -> Type default rewriter.Type(context, typ) = match typ with @@ -54,12 +54,12 @@ type 'context Rewriter() = | Type.Callable callable -> rewriter.CallableType(context, callable) |> Type.Callable | Type.Unknown terminal -> rewriter.Terminal(context, terminal) |> Type.Unknown - abstract TypeAnnotation: context:'context * annotation:TypeAnnotation -> TypeAnnotation + abstract TypeAnnotation : context: 'context * annotation: TypeAnnotation -> TypeAnnotation default rewriter.TypeAnnotation(context, annotation) = { Colon = rewriter.Terminal(context, annotation.Colon); Type = rewriter.Type(context, annotation.Type) } - abstract ArrayType: context:'context * array:ArrayType -> ArrayType + abstract ArrayType : context: 'context * array: ArrayType -> ArrayType default rewriter.ArrayType(context, array) = { @@ -68,7 +68,7 @@ type 'context Rewriter() = CloseBracket = rewriter.Terminal(context, array.CloseBracket) } - abstract CallableType: context:'context * callable:CallableType -> CallableType + abstract CallableType : context: 'context * callable: CallableType -> CallableType default rewriter.CallableType(context, callable) = { @@ -78,7 +78,7 @@ type 'context Rewriter() = Characteristics = callable.Characteristics |> Option.map (curry rewriter.CharacteristicSection context) } - abstract CharacteristicSection: context:'context * section:CharacteristicSection -> CharacteristicSection + abstract CharacteristicSection : context: 'context * section: CharacteristicSection -> CharacteristicSection default rewriter.CharacteristicSection(context, section) = { @@ -86,7 +86,7 @@ type 'context Rewriter() = Characteristic = rewriter.Characteristic(context, section.Characteristic) } - abstract CharacteristicGroup: context:'context * group:CharacteristicGroup -> CharacteristicGroup + abstract CharacteristicGroup : context: 'context * group: CharacteristicGroup -> CharacteristicGroup default rewriter.CharacteristicGroup(context, group) = { @@ -95,7 +95,7 @@ type 'context Rewriter() = CloseParen = rewriter.Terminal(context, group.CloseParen) } - abstract Characteristic: context:'context * characteristic:Characteristic -> Characteristic + abstract Characteristic : context: 'context * characteristic: Characteristic -> Characteristic default rewriter.Characteristic(context, characteristic) = match characteristic with @@ -105,7 +105,7 @@ type 'context Rewriter() = | Characteristic.BinaryOperator operator -> rewriter.BinaryOperator(context, rewriter.Characteristic, operator) |> Characteristic.BinaryOperator - abstract Statement: context:'context * statement:Statement -> Statement + abstract Statement : context: 'context * statement: Statement -> Statement default rewriter.Statement(context, statement) = match statement with @@ -115,7 +115,7 @@ type 'context Rewriter() = | Else elses -> rewriter.Else(context, elses) |> Else | Statement.Unknown terminal -> rewriter.Terminal(context, terminal) |> Statement.Unknown - abstract Let: context:'context * lets:Let -> Let + abstract Let : context: 'context * lets: Let -> Let default rewriter.Let(context, lets) = { @@ -126,7 +126,7 @@ type 'context Rewriter() = Semicolon = rewriter.Terminal(context, lets.Semicolon) } - abstract Return: context:'context * returns:Return -> Return + abstract Return : context: 'context * returns: Return -> Return default rewriter.Return(context, returns) = { @@ -135,7 +135,7 @@ type 'context Rewriter() = Semicolon = rewriter.Terminal(context, returns.Semicolon) } - abstract If: context:'context * ifs:If -> If + abstract If : context: 'context * ifs: If -> If default rewriter.If(context, ifs) = { @@ -144,7 +144,7 @@ type 'context Rewriter() = Block = rewriter.Block(context, rewriter.Statement, ifs.Block) } - abstract Else: context:'context * elses:Else -> Else + abstract Else : context: 'context * elses: Else -> Else default rewriter.Else(context, elses) = { @@ -152,14 +152,14 @@ type 'context Rewriter() = Block = rewriter.Block(context, rewriter.Statement, elses.Block) } - abstract SymbolBinding: context:'context * binding:SymbolBinding -> SymbolBinding + abstract SymbolBinding : context: 'context * binding: SymbolBinding -> SymbolBinding default rewriter.SymbolBinding(context, binding) = match binding with | SymbolDeclaration declaration -> rewriter.SymbolDeclaration(context, declaration) |> SymbolDeclaration | SymbolTuple tuple -> rewriter.Tuple(context, rewriter.SymbolBinding, tuple) |> SymbolTuple - abstract SymbolDeclaration: context:'context * declaration:SymbolDeclaration -> SymbolDeclaration + abstract SymbolDeclaration : context: 'context * declaration: SymbolDeclaration -> SymbolDeclaration default rewriter.SymbolDeclaration(context, declaration) = { @@ -167,7 +167,7 @@ type 'context Rewriter() = Type = declaration.Type |> Option.map (curry rewriter.TypeAnnotation context) } - abstract Expression: context:'context * expression:Expression -> Expression + abstract Expression : context: 'context * expression: Expression -> Expression default rewriter.Expression(context, expression) = match expression with @@ -178,7 +178,7 @@ type 'context Rewriter() = | Update update -> rewriter.Update(context, update) |> Update | Expression.Unknown terminal -> rewriter.Terminal(context, terminal) |> Expression.Unknown - abstract Update: context:'context * update:Update -> Update + abstract Update : context: 'context * update: Update -> Update default rewriter.Update(context, update) = { @@ -189,7 +189,7 @@ type 'context Rewriter() = Value = rewriter.Expression(context, update.Value) } - abstract Block: context:'context * mapper:('context * 'a -> 'a) * block:'a Block -> 'a Block + abstract Block : context: 'context * mapper: ('context * 'a -> 'a) * block: 'a Block -> 'a Block default rewriter.Block(context, mapper, block) = { @@ -198,7 +198,7 @@ type 'context Rewriter() = CloseBrace = rewriter.Terminal(context, block.CloseBrace) } - abstract Tuple: context:'context * mapper:('context * 'a -> 'a) * tuple:'a Tuple -> 'a Tuple + abstract Tuple : context: 'context * mapper: ('context * 'a -> 'a) * tuple: 'a Tuple -> 'a Tuple default rewriter.Tuple(context, mapper, tuple) = { @@ -207,7 +207,7 @@ type 'context Rewriter() = CloseParen = rewriter.Terminal(context, tuple.CloseParen) } - abstract SequenceItem: context:'context * mapper:('context * 'a -> 'a) * item:'a SequenceItem -> 'a SequenceItem + abstract SequenceItem : context: 'context * mapper: ('context * 'a -> 'a) * item: 'a SequenceItem -> 'a SequenceItem default rewriter.SequenceItem(context, mapper, item) = { @@ -215,10 +215,9 @@ type 'context Rewriter() = Comma = item.Comma |> Option.map (curry rewriter.Terminal context) } - abstract BinaryOperator: context:'context - * mapper:('context * 'a -> 'a) - * operator:'a BinaryOperator - -> 'a BinaryOperator + abstract BinaryOperator : + context: 'context * mapper: ('context * 'a -> 'a) * operator: 'a BinaryOperator -> + 'a BinaryOperator default rewriter.BinaryOperator(context, mapper, operator) = { @@ -227,5 +226,5 @@ type 'context Rewriter() = Right = mapper (context, operator.Right) } - abstract Terminal: context:'context * terminal:Terminal -> Terminal + abstract Terminal : context: 'context * terminal: Terminal -> Terminal default _.Terminal(_, terminal) = terminal