diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index b4744bbc5a..e6ed1dceee 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -3,7 +3,7 @@ "isRoot": true, "tools": { "fantomas-tool": { - "version": "4.5.0-beta-001", + "version": "4.6.5", "commands": [ "fantomas" ] diff --git a/.fantomasignore b/.fantomasignore deleted file mode 100644 index 7d336bfbee..0000000000 --- a/.fantomasignore +++ /dev/null @@ -1,8 +0,0 @@ -# Ignore signature files because of formatting bugs. -*.fsi - -# Disabling the check for the transformations due to formatting bugs. -# The issues are fixed with version 4.6.0, and these files can be reenabled -after updating fantomas. -*ExpressionTransformation.fs -*StatementTransformation.fs diff --git a/src/QsCompiler/CSharpGeneration/Context.fs b/src/QsCompiler/CSharpGeneration/Context.fs index a568f9e5a3..a07cce13b2 100644 --- a/src/QsCompiler/CSharpGeneration/Context.fs +++ b/src/QsCompiler/CSharpGeneration/Context.fs @@ -38,7 +38,7 @@ module internal DeclarationLocations = type internal SyntaxTreeTransformation private (_private_) = - inherit SyntaxTreeTransformation(new TransformationState(), TransformationOptions.NoRebuild) + inherit SyntaxTreeTransformation(TransformationState(), TransformationOptions.NoRebuild) new() as this = new SyntaxTreeTransformation("_private_") @@ -86,19 +86,16 @@ type CodegenContext = let result = new Dictionary() syntaxTree - |> Seq.collect - (fun ns -> - ns.Elements - |> Seq.choose - (function - | QsCallable c -> Some(ns, c) - | _ -> None)) - |> Seq.iter - (fun (ns: QsNamespace, c: QsCallable) -> - if result.ContainsKey c.FullName.Name then - result.[c.FullName.Name] <- (ns.Name, c) :: (result.[c.FullName.Name]) - else - result.[c.FullName.Name] <- [ ns.Name, c ]) + |> Seq.collect (fun ns -> + ns.Elements + |> Seq.choose (function + | QsCallable c -> Some(ns, c) + | _ -> None)) + |> Seq.iter (fun (ns, c) -> + if result.ContainsKey c.FullName.Name then + result.[c.FullName.Name] <- (ns.Name, c) :: result.[c.FullName.Name] + else + result.[c.FullName.Name] <- [ ns.Name, c ]) result.ToImmutableDictionary() diff --git a/src/QsCompiler/CSharpGeneration/EntryPoint.fs b/src/QsCompiler/CSharpGeneration/EntryPoint.fs index 62b42ddc1f..c79b3ed849 100644 --- a/src/QsCompiler/CSharpGeneration/EntryPoint.fs +++ b/src/QsCompiler/CSharpGeneration/EntryPoint.fs @@ -335,10 +335,13 @@ let private entryPointClass context (entryPoint: QsCallable) = ``property-arrow_get`` typeName name [ ``public`` ] get (``=>`` value) let nameProperty = string entryPoint.FullName |> literal |> property "Name" "string" - let summaryProperty = (PrintSummary entryPoint.Documentation false).Trim() |> literal |> property "Summary" "string" + + let summaryProperty = + (PrintSummary entryPoint.Documentation false).Trim() |> literal |> property "Summary" "string" + let parameters = parameters context entryPoint.Documentation entryPoint.ArgumentTuple - let members : MemberDeclarationSyntax list = + let members: MemberDeclarationSyntax list = [ nameProperty summaryProperty @@ -371,7 +374,8 @@ let private entryPointNamespace context name entryPoints = /// Returns the driver settings object. let private driverSettings context = - let newDriverSettings = driverNamespace + ".DriverSettings" |> ``type`` |> SyntaxFactory.ObjectCreationExpression + let newDriverSettings = + driverNamespace + ".DriverSettings" |> ``type`` |> SyntaxFactory.ObjectCreationExpression let namedArg (name: string) expr = SyntaxFactory.NameColon name |> (SyntaxFactory.Argument expr).WithNameColon diff --git a/src/QsCompiler/CSharpGeneration/SimulationCode.fs b/src/QsCompiler/CSharpGeneration/SimulationCode.fs index cc7ce89be0..e5ea982dea 100644 --- a/src/QsCompiler/CSharpGeneration/SimulationCode.fs +++ b/src/QsCompiler/CSharpGeneration/SimulationCode.fs @@ -3,6 +3,8 @@ namespace Microsoft.Quantum.QsCompiler.CsharpGeneration +#nowarn "46" // Backticks removed by Fantomas: https://github.com/fsprojects/fantomas/issues/2034 + open System open System.Collections.Generic open System.Collections.Immutable @@ -112,12 +114,10 @@ module SimulationCode = let getTypeParameters types = let findAll (t: ResolvedType) = - t.ExtractAll - (fun item -> - item.Resolution - |> function - | QsTypeKind.TypeParameter tp -> seq { yield tp } - | _ -> Enumerable.Empty()) + t.ExtractAll (fun item -> + match item.Resolution with + | QsTypeKind.TypeParameter tp -> seq { tp } + | _ -> Seq.empty) types |> Seq.collect findAll |> Seq.distinctBy (fun tp -> tp.Origin, tp.TypeName) |> Seq.toList @@ -460,6 +460,7 @@ module SimulationCode = | NewUdt (udt, args) -> buildNewUdt udt args // needs to be before CallLikeExpression! | CallLikeExpression (op, args) -> buildApply ex.ResolvedType op args | MissingExpr -> ident "_" :> ExpressionSyntax + and captureExpression (ex: TypedExpression) = match ex.Expression with | Identifier (s, _) when ex.InferredInformation.IsMutable -> @@ -467,6 +468,7 @@ module SimulationCode = | QsTypeKind.ArrayType _ -> invoke (buildId s <|?.|> (ident "Copy")) ``(`` [] ``)`` | _ -> buildExpression ex | _ -> buildExpression ex + and buildNamedItem ex acc = match acc with | LocalVariable name -> @@ -480,16 +482,19 @@ module SimulationCode = | _ -> // TODO: Diagnostics failwith "Invalid identifier for named item" + and buildAddExpr (exType: ResolvedType) lhs rhs = match exType.Resolution |> QArrayType with | Some arrType -> arrType <.> (ident "Add", [ buildExpression lhs; buildExpression rhs ]) | _ -> ``((`` ((buildExpression lhs) <+> (buildExpression rhs)) ``))`` + and buildInterpolatedString (s: string) (exs: ImmutableArray) = if exs.Length <> 0 then let exprs = exs |> Seq.map buildExpression |> Seq.toList invoke (ident "String.Format") ``(`` (literal s :: exprs) ``)`` else literal s + and buildId id : ExpressionSyntax = match id with | LocalVariable n -> n |> ident :> ExpressionSyntax @@ -497,6 +502,7 @@ module SimulationCode = | InvalidIdentifier -> // TODO: Diagnostics failwith "Received InvalidIdentifier" + and buildCopyAndUpdateExpression (lhsEx: TypedExpression, accEx: TypedExpression, rhsEx) = match lhsEx.ResolvedType.Resolution |> QArrayType with | Some arrayType -> @@ -554,8 +560,10 @@ module SimulationCode = | _ -> failwith "copy-and-update expressions are currently only supported for arrays and user defined types" + and buildTuple many : ExpressionSyntax = many |> Seq.map captureExpression |> Seq.toList |> tuple // captured since we rely on the native C# tuples + and buildPartial (partialType: ResolvedType) typeParamResolutions opEx args = let (pIn, pOut) = inAndOutputType partialType // The type of the operation constructed by partial application let (oIn, _) = inAndOutputType opEx.ResolvedType // The type of the operation accepting the partial tuples. @@ -607,10 +615,12 @@ module SimulationCode = // If it does, we can't create the PartialMapper at compile time // so we just build a partial-tuple and let it be resolved at runtime. let op = buildExpression opEx - let values = if hasTypeParameters [ pIn; pOut ] then args |> captureExpression else buildPartialMapper () + let values = if hasTypeParameters [ pIn; pOut ] then captureExpression args else buildPartialMapper () op <.> (ident "Partial", [ values ]) + and buildNewUdt n args = ``new`` (``type`` [ justTheName context n ]) ``(`` [ args |> captureExpression ] ``)`` + and buildApply returnType op args = // Checks if the expression points to a non-generic user-defined callable. // Because these have fully-resolved types in the runtime, @@ -645,11 +655,13 @@ module SimulationCode = (ident "Apply") buildExpression op <.> (apply, [ args |> captureExpression ]) // we need to capture to guarantee that the result accurately reflects any indirect binding of arguments + and buildConditional c t f = let cond = c |> buildExpression let whenTrue = t |> captureExpression let whenFalse = f |> captureExpression ``?`` cond (whenTrue, whenFalse) + and buildRange lhs rEnd = let args = lhs.Expression @@ -659,17 +671,21 @@ module SimulationCode = | _ -> [ (buildExpression lhs); (buildExpression rEnd) ] ``new`` (``type`` [ "QRange" ]) ``(`` args ``)`` + and buildValueArray at elems = match at.Resolution |> QArrayType with | Some arrayType -> ``new`` arrayType ``(`` (elems |> Seq.map captureExpression |> Seq.toList) ``)`` // TODO: diagnostics. | _ -> failwith "" + and buildSizedArray value size = let supplier = ``() =>`` [] (captureExpression value) :> ExpressionSyntax ident "QArray" <.> (ident "Filled", [ supplier; buildExpression size ]) + and buildNewArray b count = let arrayType = (ArrayType b |> QArrayType).Value arrayType <.> (ident "Create", [ count |> buildExpression ]) + and buildArrayItem a i = match i.ResolvedType.Resolution with | Range -> invoke ((buildExpression a) <|.|> (ident "Slice")) ``(`` [ (buildExpression i) ] ``)`` @@ -882,7 +898,7 @@ module SimulationCode = override this.OnRepeatStatement rs = let buildTest test fixup = let condition = buildExpression test - let thens = [ ``break`` ] + let thens = [ break ] let elses = buildBlock fixup ``if`` ``(`` condition ``)`` thens (Some(``else`` elses)) @@ -1091,8 +1107,8 @@ module SimulationCode = // Use the right accessibility for the property depending on the accessibility of the callable. // Note: In C#, "private protected" is the intersection of protected and internal. match getCallableAccess qualifiedName |> Option.defaultValue Public with - | Public -> [ ``protected`` ] - | Internal -> [ ``private``; ``protected`` ] + | Public -> [ protected ] + | Internal -> [ ``private``; protected ] let buildOne qualifiedName = /// eg: @@ -1462,7 +1478,7 @@ module SimulationCode = ``property-arrow_get`` "String" "ICallable.Name" [] get (``=>`` (literal name)) :> MemberDeclarationSyntax let buildImpl name = - propg "IOperationFactory" "Impl" [ ``private``; ``protected`` ] :> MemberDeclarationSyntax + propg "IOperationFactory" "Impl" [ ``private``; protected ] :> MemberDeclarationSyntax let buildFullName (name: QsQualifiedName) = let fqn = @@ -1752,8 +1768,7 @@ module SimulationCode = op.Attributes |> SymbolResolution.TryFindTestTargets |> Seq.filter (String.IsNullOrWhiteSpace >> not) - |> Seq.map - (function + |> Seq.map (function | x when x.Contains(".") -> let indexOfDot = x.LastIndexOf('.') { Namespace = x.Substring(0, indexOfDot); Name = x.Substring(indexOfDot + 1) } @@ -1970,9 +1985,8 @@ module SimulationCode = // Returns only those namespaces and their elements that are defined for the given file. let findLocalElements selector (fileName: string) syntaxTree = syntaxTree - |> Seq.map - (fun ns -> - (ns.Name, (FilterBySourceFile.Apply(ns, fileName)).Elements |> Seq.choose selector |> Seq.toList)) + |> Seq.map (fun ns -> + (ns.Name, (FilterBySourceFile.Apply(ns, fileName)).Elements |> Seq.choose selector |> Seq.toList)) |> Seq.sortBy fst |> Seq.filter (fun (_, elements) -> not elements.IsEmpty) |> Seq.toList diff --git a/src/QsCompiler/Core/DeclarationHeaders.fs b/src/QsCompiler/Core/DeclarationHeaders.fs index e61084677a..8c4c155902 100644 --- a/src/QsCompiler/Core/DeclarationHeaders.fs +++ b/src/QsCompiler/Core/DeclarationHeaders.fs @@ -97,7 +97,8 @@ module DeclarationHeader = new NullableRangeConverter() :> JsonConverter |] - let private Serializer = [ qsNullableConverters; Json.Converters false ] |> Array.concat |> Json.CreateSerializer + let private Serializer = + [ qsNullableConverters; Json.Converters false ] |> Array.concat |> Json.CreateSerializer let private PermissiveSerializer = [ qsNullableConverters; Json.Converters true ] |> Array.concat |> Json.CreateSerializer @@ -198,9 +199,12 @@ type TypeDeclarationHeader = static member FromJson json = let success, schema = DeclarationHeader.FromJson json 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 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 if not (Object.ReferenceEquals(header.TypeItems, null)) then success, header @@ -319,18 +323,17 @@ type CallableDeclarationHeader = // due to changes of fields over time are initialized to a proper value let success, schema = DeclarationHeader.FromJson json 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 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 = { header with ArgumentTuple = header.ArgumentTuple |> setInferredInfo } if - Object.ReferenceEquals - ( - header.Signature.Information, - null - ) + Object.ReferenceEquals(header.Signature.Information, null) || Object.ReferenceEquals(header.Signature.Information.Characteristics, null) then false, { header with Signature = { header.Signature with Information = CallableInformation.Invalid } } @@ -439,9 +442,12 @@ type SpecializationDeclarationHeader = let header = SpecializationDeclarationHeader.OfSchema schema let infoIsNull = Object.ReferenceEquals(header.Information, null) 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 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 if not (infoIsNull || typeArgsAreNull) then success, header diff --git a/src/QsCompiler/Core/Dependencies.fs b/src/QsCompiler/Core/Dependencies.fs index 41bd271469..960b4022f6 100644 --- a/src/QsCompiler/Core/Dependencies.fs +++ b/src/QsCompiler/Core/Dependencies.fs @@ -216,7 +216,8 @@ type BuiltIn = Kind = Function(TypeParameters = ImmutableArray.Empty) } - static member Attribute = { FullName = { Name = "Attribute"; Namespace = BuiltIn.CoreNamespace }; Kind = Attribute } + static member Attribute = + { FullName = { Name = "Attribute"; Namespace = BuiltIn.CoreNamespace }; Kind = Attribute } static member EntryPoint = { FullName = { Name = "EntryPoint"; Namespace = BuiltIn.CoreNamespace }; Kind = Attribute } diff --git a/src/QsCompiler/Core/SymbolResolution.fs b/src/QsCompiler/Core/SymbolResolution.fs index a15a678e1f..c3d2aabf1c 100644 --- a/src/QsCompiler/Core/SymbolResolution.fs +++ b/src/QsCompiler/Core/SymbolResolution.fs @@ -160,8 +160,7 @@ module internal ResolutionResult = let internal TryAtMostOne<'T> (nsGetter: 'T -> string) (results: seq>) : ResolutionResult<'T> = let found = results - |> Seq.filter - (function + |> Seq.filter (function | Found _ -> true | _ -> false) @@ -306,7 +305,8 @@ module SymbolResolution = let getTarget (att: QsDeclarationAttribute) = if att |> BuiltIn.MarksTestOperation then Some att.Argument else None - let validTargets = CommandLineArguments.BuiltInSimulators.ToImmutableDictionary(fun t -> t.ToLowerInvariant()) + let validTargets = + CommandLineArguments.BuiltInSimulators.ToImmutableDictionary(fun t -> t.ToLowerInvariant()) let targetName (target: string) = if target = null then @@ -548,8 +548,7 @@ 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) @@ -1148,7 +1147,7 @@ module SymbolResolution = (properties: ImmutableDictionary<_, _>) (kind, spec: Resolution) = - let bundle : SpecializationBundleProperties = properties.[SpecializationBundleProperties.BundleId spec] + let bundle = properties.[SpecializationBundleProperties.BundleId spec] let impl, err = match kind with diff --git a/src/QsCompiler/Core/SymbolTable/Namespace.fs b/src/QsCompiler/Core/SymbolTable/Namespace.fs index 5c74316c18..c6cfc22592 100644 --- a/src/QsCompiler/Core/SymbolTable/Namespace.fs +++ b/src/QsCompiler/Core/SymbolTable/Namespace.fs @@ -48,13 +48,12 @@ type Namespace 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) /// name of the namespace member this.Name = name @@ -88,8 +87,8 @@ type Namespace 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. @@ -215,9 +214,8 @@ type Namespace | 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 /// @@ -254,9 +252,8 @@ type Namespace | 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 /// @@ -309,9 +306,8 @@ type Namespace /// 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 @@ -352,9 +348,8 @@ type Namespace /// 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 diff --git a/src/QsCompiler/Core/SymbolTable/NamespaceManager.fs b/src/QsCompiler/Core/SymbolTable/NamespaceManager.fs index 7064d73b3e..db199880e0 100644 --- a/src/QsCompiler/Core/SymbolTable/NamespaceManager.fs +++ b/src/QsCompiler/Core/SymbolTable/NamespaceManager.fs @@ -58,7 +58,8 @@ type NamespaceManager let getKeys (lookup: ILookup<_, _>) = lookup |> Seq.map (fun group -> group.Key) - let namespacesInRefs = (getKeys callables).Concat(getKeys specializations).Concat(getKeys types) |> Seq.distinct + let namespacesInRefs = + (getKeys callables).Concat(getKeys specializations).Concat(getKeys types) |> Seq.distinct for nsName in namespacesInRefs do namespaces.Add( @@ -115,22 +116,20 @@ type NamespaceManager 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. @@ -191,9 +190,11 @@ type NamespaceManager None, [| QsCompilerDiagnostic.Error(code, args) (symRange.ValueOr Range.Zero) |] let findUnqualified () = - match resolveInOpenNamespaces - (fun ns -> ns.TryFindType(symName, checkQualificationForDeprecation)) - (parentNS, source) with + match + resolveInOpenNamespaces + (fun ns -> ns.TryFindType(symName, checkQualificationForDeprecation)) + (parentNS, source) + with | Found (nsName, (declSource, deprecation, access)) -> success nsName declSource deprecation access [||] | Ambiguous namespaces -> let names = String.Join(", ", namespaces) @@ -357,14 +358,13 @@ type NamespaceManager // 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( @@ -391,7 +391,7 @@ type NamespaceManager let simplifiedArgNames = signature.Argument.Items.Select fst |> Seq.choose nameAndRange |> Seq.toList let verifyArgument i (arg, range: QsNullable<_>) = - if i > 0 && simplifiedArgNames.[..i - 1] |> Seq.map fst |> Seq.contains arg then + if i > 0 && simplifiedArgNames.[.. i - 1] |> Seq.map fst |> Seq.contains arg then errs.Add( decl.Position, range.ValueOr decl.Range @@ -692,7 +692,8 @@ type NamespaceManager (parentKind, parentName: QsQualifiedName, source, access) (signature, specBundleCharacteristics) = - let checkAccess = checkUdtAccess ErrorCode.TypeLessAccessibleThanParentCallable (parentName.Name, access) + let checkAccess = + checkUdtAccess ErrorCode.TypeLessAccessibleThanParentCallable (parentName.Name, access) let resolveType tpNames qsType = let res, errs = resolveType (parentName, tpNames, source) qsType checkAccess @@ -730,44 +731,40 @@ type NamespaceManager // 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() @@ -784,109 +781,98 @@ type NamespaceManager 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() @@ -959,15 +945,13 @@ type NamespaceManager | 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 @@ -1009,27 +993,26 @@ type NamespaceManager | 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 @@ -1061,31 +1044,29 @@ type NamespaceManager 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 @@ -1128,30 +1109,28 @@ type NamespaceManager 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 @@ -1318,9 +1297,8 @@ type NamespaceManager 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) = @@ -1375,9 +1353,11 @@ type NamespaceManager /// uniquely resolved. member this.TryResolveAndGetCallable cName (nsName, source) = let toHeader (declaredNs, (declaredSource, _)) = - match this.TryGetCallableHeader - ({ Namespace = declaredNs; Name = cName }, Some declaredSource) - (nsName, source) with + match + this.TryGetCallableHeader + ({ Namespace = declaredNs; Name = cName }, Some declaredSource) + (nsName, source) + with | Found value -> value | _ -> QsCompilerError.Raise "Expected to find the header corresponding to a possible resolution" @@ -1423,12 +1403,11 @@ type NamespaceManager 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) = @@ -1483,7 +1462,8 @@ type NamespaceManager /// 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" @@ -1522,8 +1502,8 @@ type NamespaceManager 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() @@ -1641,8 +1621,7 @@ type NamespaceManager let namedItems = typeItems.Items - |> Seq.choose - (function + |> Seq.choose (function | Named item -> Some item | _ -> None) @@ -1660,41 +1639,35 @@ type NamespaceManager 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 6dea3d5158..b508204002 100644 --- a/src/QsCompiler/Core/SymbolTable/PartialNamespace.fs +++ b/src/QsCompiler/Core/SymbolTable/PartialNamespace.fs @@ -116,8 +116,8 @@ type private PartialNamespace 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 @@ -169,7 +169,8 @@ type private PartialNamespace | QsTupleItem (n, t) -> ImmutableArray.Create(replaceAnonymous (n, t)) |> QsTuple | QsTuple _ -> buildItem typeTuple - let returnType = { Type = UserDefinedType(QualifiedSymbol(this.Name, tName) |> withoutRange); Range = Null } + let returnType = + { Type = UserDefinedType(QualifiedSymbol(this.Name, tName) |> withoutRange); Range = Null } { TypeParameters = ImmutableArray.Empty @@ -291,11 +292,10 @@ type private PartialNamespace 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 4f8001234b..d52cb96a7d 100644 --- a/src/QsCompiler/Core/SyntaxGenerator.fs +++ b/src/QsCompiler/Core/SyntaxGenerator.fs @@ -118,7 +118,10 @@ module SyntaxGenerator = /// Does *not* strip positional information from the given items; the responsibility to do so is with the caller. 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 + + let tupleType = + items |> Seq.map (fun item -> item.ResolvedType) |> ImmutableArray.CreateRange |> TupleType + AutoGeneratedExpression(ValueTuple(items.ToImmutableArray())) tupleType qdep // utils for assignments @@ -266,7 +269,7 @@ module SyntaxGenerator = let length = AutoGeneratedExpression(QsExpressionKind.Identifier(kind, Null)) exTypeKind false let callToLength tpRes = - let resolutions = (seq { yield (typeParameter.Origin, typeParameter.TypeName, tpRes) }).ToImmutableArray() + let resolutions = ImmutableArray.Create((typeParameter.Origin, typeParameter.TypeName, tpRes)) { CallNonGeneric(length, ex) with TypeArguments = resolutions } match ex.ResolvedType.Resolution with diff --git a/src/QsCompiler/Core/SyntaxTreeExtensions.fs b/src/QsCompiler/Core/SyntaxTreeExtensions.fs index cedde89903..0480cf4b12 100644 --- a/src/QsCompiler/Core/SyntaxTreeExtensions.fs +++ b/src/QsCompiler/Core/SyntaxTreeExtensions.fs @@ -27,7 +27,8 @@ 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 @@ -495,24 +496,20 @@ 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) = @@ -523,36 +520,30 @@ 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) @@ -560,13 +551,11 @@ 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/CommonTransformationNodes.fs b/src/QsCompiler/Core/Transformations/CommonTransformationNodes.fs index dd60bae9bb..b87b390251 100644 --- a/src/QsCompiler/Core/Transformations/CommonTransformationNodes.fs +++ b/src/QsCompiler/Core/Transformations/CommonTransformationNodes.fs @@ -16,32 +16,32 @@ type QsArgumentTuple = QsTuple> /// type CommonTransformationNodes internal () = - abstract OnLocalNameDeclaration : string -> string + abstract OnLocalNameDeclaration: string -> string default this.OnLocalNameDeclaration name = name - abstract OnLocalName : string -> string + abstract OnLocalName: string -> string default this.OnLocalName name = name - abstract OnItemNameDeclaration : string -> string + abstract OnItemNameDeclaration: string -> string default this.OnItemNameDeclaration name = name - abstract OnItemName : UserDefinedType * string -> string + abstract OnItemName: UserDefinedType * string -> string default this.OnItemName(parentType, itemName) = itemName - abstract OnArgumentTuple : QsArgumentTuple -> QsArgumentTuple + abstract OnArgumentTuple: QsArgumentTuple -> QsArgumentTuple default this.OnArgumentTuple argTuple = argTuple - abstract OnAbsoluteLocation : QsNullable -> QsNullable + abstract OnAbsoluteLocation: QsNullable -> QsNullable default this.OnAbsoluteLocation loc = loc - abstract OnRelativeLocation : QsNullable -> QsNullable + abstract OnRelativeLocation: QsNullable -> QsNullable default this.OnRelativeLocation loc = loc - abstract OnSymbolLocation : QsNullable * Range -> QsNullable * Range + abstract OnSymbolLocation: QsNullable * Range -> QsNullable * Range default this.OnSymbolLocation(offset, range) = (offset, range) - abstract OnExpressionRange : QsNullable -> QsNullable + abstract OnExpressionRange: QsNullable -> QsNullable default this.OnExpressionRange range = range - abstract OnTypeRange : TypeRange -> TypeRange + abstract OnTypeRange: TypeRange -> TypeRange default this.OnTypeRange range = range diff --git a/src/QsCompiler/Core/Transformations/ExpressionTransformation.fs b/src/QsCompiler/Core/Transformations/ExpressionTransformation.fs index 95e43877a1..49db04028d 100644 --- a/src/QsCompiler/Core/Transformations/ExpressionTransformation.fs +++ b/src/QsCompiler/Core/Transformations/ExpressionTransformation.fs @@ -27,9 +27,9 @@ type ExpressionKindTransformationBase internal (options: TransformationOptions, member val internal ExpressionTransformationHandle = missingTransformation "expression" with get, set - member this.Expressions : ExpressionTransformationBase = this.ExpressionTransformationHandle() - member this.Types : TypeTransformationBase = this.ExpressionTransformationHandle().Types - member this.Common : CommonTransformationNodes = this.ExpressionTransformationHandle().Types.Common + member this.Expressions: ExpressionTransformationBase = this.ExpressionTransformationHandle() + member this.Types: TypeTransformationBase = this.ExpressionTransformationHandle().Types + member this.Common: CommonTransformationNodes = this.ExpressionTransformationHandle().Types.Common new(expressionTransformation: unit -> ExpressionTransformationBase, options: TransformationOptions) as this = new ExpressionKindTransformationBase(options, "_internal_") @@ -65,10 +65,11 @@ type ExpressionKindTransformationBase internal (options: TransformationOptions, // 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) let idName = match sym with @@ -78,25 +79,25 @@ type ExpressionKindTransformationBase internal (options: TransformationOptions, Identifier |> Node.BuildOr InvalidExpr (idName, 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 @@ -105,25 +106,25 @@ 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 @@ -131,24 +132,24 @@ type ExpressionKindTransformationBase internal (options: TransformationOptions, // TODO: RELEASE 2022-09: Remove member. [] - abstract OnArrayItem : TypedExpression * TypedExpression -> ExpressionKind + abstract OnArrayItem: TypedExpression * TypedExpression -> ExpressionKind // TODO: RELEASE 2022-09: Remove member. [] - default this.OnArrayItem(arr, idx) = + override this.OnArrayItem(arr, idx) = let arr, idx = this.Expressions.OnTypedExpression arr, this.Expressions.OnTypedExpression idx ArrayItem |> Node.BuildOr InvalidExpr (arr, idx) - abstract OnArrayItemAccess : TypedExpression * TypedExpression -> ExpressionKind + abstract OnArrayItemAccess: TypedExpression * TypedExpression -> ExpressionKind default this.OnArrayItemAccess(arr, idx) = this.OnArrayItem(arr, idx) // replace with the implementation once the deprecated member is removed // TODO: RELEASE 2022-09: Remove member. [] - abstract OnNamedItem : TypedExpression * Identifier -> ExpressionKind + abstract OnNamedItem: TypedExpression * Identifier -> ExpressionKind // TODO: RELEASE 2022-09: Remove member. [] - default this.OnNamedItem(ex, acc) = + override this.OnNamedItem(ex, acc) = let lhs = this.Expressions.OnTypedExpression ex let acc = @@ -158,41 +159,41 @@ type ExpressionKindTransformationBase internal (options: TransformationOptions, NamedItem |> Node.BuildOr InvalidExpr (lhs, acc) - abstract OnNamedItemAccess : TypedExpression * Identifier -> ExpressionKind + abstract OnNamedItemAccess: TypedExpression * Identifier -> ExpressionKind default this.OnNamedItemAccess(ex, acc) = this.OnNamedItem(ex, acc) // replace with the implementation once the deprecated member is removed - 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 updated = this.Expressions.OnTypedExpression lhs @@ -210,7 +211,7 @@ type ExpressionKindTransformationBase internal (options: TransformationOptions, let rhs = this.Expressions.OnTypedExpression rhs CopyAndUpdate |> Node.BuildOr InvalidExpr (updated, accEx, rhs) - abstract OnConditionalExpression : TypedExpression * TypedExpression * TypedExpression -> ExpressionKind + abstract OnConditionalExpression: TypedExpression * TypedExpression * TypedExpression -> ExpressionKind default this.OnConditionalExpression(cond, ifTrue, ifFalse) = let cond, ifTrue, ifFalse = @@ -220,180 +221,178 @@ 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 BNOT |> Node.BuildOr InvalidExpr ex - abstract OnLambda : lambda: Lambda -> ExpressionKind + abstract OnLambda: lambda: Lambda -> ExpressionKind - default this.OnLambda lambda = + default this.OnLambda lambda = let syms = this.Common.OnArgumentTuple lambda.ArgumentTuple let body = this.Expressions.OnTypedExpression lambda.Body - - Lambda.create lambda.Kind syms >> Lambda - |> Node.BuildOr InvalidExpr body + Lambda.create lambda.Kind syms >> Lambda |> Node.BuildOr InvalidExpr body // 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 @@ -462,9 +461,9 @@ and ExpressionTransformationBase internal (options: TransformationOptions, _inte member val internal TypeTransformationHandle = missingTransformation "type" with get, set member val internal ExpressionKindTransformationHandle = missingTransformation "expression kind" with get, set - member this.ExpressionKinds : ExpressionKindTransformationBase = this.ExpressionKindTransformationHandle() - member this.Types : TypeTransformationBase = this.TypeTransformationHandle() - member this.Common : CommonTransformationNodes = this.TypeTransformationHandle().Common + member this.ExpressionKinds: ExpressionKindTransformationBase = this.ExpressionKindTransformationHandle() + member this.Types: TypeTransformationBase = this.TypeTransformationHandle() + member this.Common: CommonTransformationNodes = this.TypeTransformationHandle().Common new(exkindTransformation: unit -> ExpressionKindTransformationBase, typeTransformation: unit -> TypeTransformationBase, @@ -493,28 +492,27 @@ and ExpressionTransformationBase internal (options: TransformationOptions, _inte // TODO: RELEASE 2022-09: Remove member. [] - abstract OnRangeInformation : QsNullable -> QsNullable + abstract OnRangeInformation: QsNullable -> QsNullable // TODO: RELEASE 2022-09: Remove member. [] - default this.OnRangeInformation range = range + override this.OnRangeInformation range = range - abstract OnExpressionInformation : InferredExpressionInformation -> InferredExpressionInformation + abstract OnExpressionInformation: InferredExpressionInformation -> InferredExpressionInformation default this.OnExpressionInformation info = info // nodes containing subexpressions or subtypes - abstract OnTypeParamResolutions : + abstract OnTypeParamResolutions: ImmutableDictionary<(QsQualifiedName * string), ResolvedType> -> - 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)) @@ -527,7 +525,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 906eeebc17..cd493c6166 100644 --- a/src/QsCompiler/Core/Transformations/NamespaceTransformation.fs +++ b/src/QsCompiler/Core/Transformations/NamespaceTransformation.fs @@ -24,10 +24,10 @@ type NamespaceTransformationBase internal (options: TransformationOptions, _inte member val internal StatementTransformationHandle = missingTransformation "statement" with get, set - member this.Statements : StatementTransformationBase = this.StatementTransformationHandle() - member this.Expressions : ExpressionTransformationBase = this.StatementTransformationHandle().Expressions - member this.Types : TypeTransformationBase = this.StatementTransformationHandle().Expressions.Types - member this.Common : CommonTransformationNodes = this.StatementTransformationHandle().Expressions.Types.Common + member this.Statements: StatementTransformationBase = this.StatementTransformationHandle() + member this.Expressions = this.StatementTransformationHandle().Expressions + member this.Types = this.StatementTransformationHandle().Expressions.Types + member this.Common = this.StatementTransformationHandle().Expressions.Types.Common new(statementTransformation: unit -> StatementTransformationBase, options: TransformationOptions) as this = new NamespaceTransformationBase(options, "_internal_") @@ -49,30 +49,30 @@ type NamespaceTransformationBase internal (options: TransformationOptions, _inte // TODO: RELEASE 2022-09: Remove member. [] - abstract OnLocation : QsNullable -> QsNullable + abstract OnLocation: QsNullable -> QsNullable // TODO: RELEASE 2022-09: Remove member. [] override this.OnLocation loc = loc - abstract OnDocumentation : ImmutableArray -> ImmutableArray + abstract OnDocumentation: ImmutableArray -> ImmutableArray default this.OnDocumentation doc = doc - abstract OnSource : Source -> Source + abstract OnSource: Source -> Source default this.OnSource source = source - abstract OnAttribute : QsDeclarationAttribute -> QsDeclarationAttribute + abstract OnAttribute: QsDeclarationAttribute -> QsDeclarationAttribute default this.OnAttribute att = att // TODO: RELEASE 2022-09: Remove member. [] - abstract OnItemName : string -> string + abstract OnItemName: string -> string // TODO: RELEASE 2022-09: Remove member. [] override this.OnItemName name = name - abstract OnTypeItems : QsTuple -> QsTuple + abstract OnTypeItems: QsTuple -> QsTuple default this.OnTypeItems tItem = match tItem with @@ -93,7 +93,7 @@ type NamespaceTransformationBase internal (options: TransformationOptions, _inte // TODO: RELEASE 2022-09: Remove. [] - abstract OnArgumentName : QsLocalSymbol -> QsLocalSymbol + abstract OnArgumentName: QsLocalSymbol -> QsLocalSymbol // TODO: RELEASE 2022-09: Remove. [] @@ -104,7 +104,7 @@ type NamespaceTransformationBase internal (options: TransformationOptions, _inte // TODO: RELEASE 2022-09: Remove member. [] - abstract OnArgumentTuple : QsArgumentTuple -> QsArgumentTuple + abstract OnArgumentTuple: QsArgumentTuple -> QsArgumentTuple // TODO: RELEASE 2022-09: Make this an internal member. Keep the following comment: // do not expose this - this handle is exposed as a virtual member in the SyntaxTreeTransformation itself @@ -122,7 +122,7 @@ type NamespaceTransformationBase internal (options: TransformationOptions, _inte let newDecl = LocalVariableDeclaration.New info.IsMutable (loc, name, t, info.HasLocalQuantumDependency) QsTupleItem |> Node.BuildOr original newDecl - abstract OnSignature : ResolvedSignature -> ResolvedSignature + abstract OnSignature: ResolvedSignature -> ResolvedSignature default this.OnSignature(s: ResolvedSignature) = let typeParams = s.TypeParameters // if this had a range is should be handled by the corresponding Common nodes @@ -134,32 +134,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.Common.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 @@ -176,7 +176,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 = @@ -211,19 +211,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 @@ -256,16 +256,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 @@ -273,7 +273,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 @@ -290,7 +290,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 @@ -300,7 +300,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 b4b0f35df1..8cb77f1d70 100644 --- a/src/QsCompiler/Core/Transformations/StatementTransformation.fs +++ b/src/QsCompiler/Core/Transformations/StatementTransformation.fs @@ -21,10 +21,10 @@ type StatementKindTransformationBase internal (options: TransformationOptions, _ member val internal StatementTransformationHandle = missingTransformation "statement" with get, set - member this.Statements : StatementTransformationBase = this.StatementTransformationHandle() - member this.Expressions : ExpressionTransformationBase = this.StatementTransformationHandle().Expressions - member this.Types : TypeTransformationBase = this.StatementTransformationHandle().Expressions.Types - member this.Common : CommonTransformationNodes = this.StatementTransformationHandle().Expressions.Types.Common + member this.Statements: StatementTransformationBase = this.StatementTransformationHandle() + member this.Expressions = this.StatementTransformationHandle().Expressions + member this.Types = this.StatementTransformationHandle().Expressions.Types + member this.Common = this.StatementTransformationHandle().Expressions.Types.Common new(statementTransformation: unit -> StatementTransformationBase, options: TransformationOptions) as this = new StatementKindTransformationBase(options, "_internal_") @@ -59,7 +59,7 @@ type StatementKindTransformationBase internal (options: TransformationOptions, _ // subconstructs used within statements - abstract OnSymbolTuple : SymbolTuple -> SymbolTuple + abstract OnSymbolTuple: SymbolTuple -> SymbolTuple default this.OnSymbolTuple syms = match syms with @@ -69,7 +69,7 @@ type StatementKindTransformationBase internal (options: TransformationOptions, _ | DiscardedItem | InvalidItem -> syms - abstract OnQubitInitializer : ResolvedInitializer -> ResolvedInitializer + abstract OnQubitInitializer: ResolvedInitializer -> ResolvedInitializer default this.OnQubitInitializer init = let transformed = @@ -84,7 +84,7 @@ type StatementKindTransformationBase internal (options: TransformationOptions, _ ResolvedInitializer.New |> Node.BuildOr init transformed - abstract OnPositionedBlock : + abstract OnPositionedBlock: QsNullable * QsPositionedBlock -> QsNullable * QsPositionedBlock default this.OnPositionedBlock(intro: QsNullable, block: QsPositionedBlock) = @@ -101,7 +101,7 @@ type StatementKindTransformationBase internal (options: TransformationOptions, _ // statements containing subconstructs or expressions - abstract OnVariableDeclaration : QsBinding -> QsStatementKind + abstract OnVariableDeclaration: QsBinding -> QsStatementKind default this.OnVariableDeclaration stm = let rhs = this.Expressions.OnTypedExpression stm.Rhs @@ -110,26 +110,25 @@ 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) @@ -137,7 +136,7 @@ type StatementKindTransformationBase internal (options: TransformationOptions, _ 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 @@ -148,14 +147,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 @@ -167,26 +166,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 @@ -201,13 +200,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 @@ -217,13 +216,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 @@ -257,10 +256,10 @@ and StatementTransformationBase internal (options: TransformationOptions, _inter member val internal ExpressionTransformationHandle = missingTransformation "expression" with get, set member val internal StatementKindTransformationHandle = missingTransformation "statement kind" with get, set - member this.StatementKinds : StatementKindTransformationBase = this.StatementKindTransformationHandle() - member this.Expressions : ExpressionTransformationBase = this.ExpressionTransformationHandle() - member this.Types : TypeTransformationBase = this.ExpressionTransformationHandle().Types - member this.Common : CommonTransformationNodes = this.ExpressionTransformationHandle().Types.Common + member this.StatementKinds: StatementKindTransformationBase = this.StatementKindTransformationHandle() + member this.Expressions: ExpressionTransformationBase = this.ExpressionTransformationHandle() + member this.Types: TypeTransformationBase = this.ExpressionTransformationHandle().Types + member this.Common: CommonTransformationNodes = this.ExpressionTransformationHandle().Types.Common new(statementKindTransformation: unit -> StatementKindTransformationBase, expressionTransformation: unit -> ExpressionTransformationBase, @@ -293,31 +292,32 @@ and StatementTransformationBase internal (options: TransformationOptions, _inter // TODO: RELEASE 2022-09: Remove member. [] - abstract OnLocation : QsNullable -> QsNullable + abstract OnLocation: QsNullable -> QsNullable // TODO: RELEASE 2022-09: Remove member. [] - default this.OnLocation loc = loc + override this.OnLocation loc = loc // TODO: RELEASE 2022-09: Remove member. [] - abstract OnVariableName : string -> string + abstract OnVariableName: string -> string // TODO: RELEASE 2022-09: Remove member. [] - default this.OnVariableName name = name + override this.OnVariableName name = name - abstract OnLocalDeclarations : LocalDeclarations -> LocalDeclarations + abstract OnLocalDeclarations: LocalDeclarations -> LocalDeclarations default this.OnLocalDeclarations decl = let onLocalVariableDeclaration (local: LocalVariableDeclaration) = - let loc = this.Common.OnSymbolLocation (local.Position, local.Range) + let loc = this.Common.OnSymbolLocation(local.Position, local.Range) let name = this.Common.OnLocalName local.VariableName let varType = this.Types.OnType local.Type let info = this.Expressions.OnExpressionInformation local.InferredInformation LocalVariableDeclaration.New info.IsMutable (loc, name, varType, info.HasLocalQuantumDependency) let variableDeclarations = decl.Variables |> Seq.map onLocalVariableDeclaration + if options.Rebuild then LocalDeclarations.New(variableDeclarations |> ImmutableArray.CreateRange) else @@ -326,7 +326,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 @@ -338,7 +338,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 1b3585bbe4..0fd4723428 100644 --- a/src/QsCompiler/Core/Transformations/SyntaxTreeTransformation.fs +++ b/src/QsCompiler/Core/Transformations/SyntaxTreeTransformation.fs @@ -38,7 +38,9 @@ type SyntaxTreeTransformation<'T> private (state: 'T, options: TransformationOpt /// Invokes the transformation for all namespaces in the given compilation. member this.OnCompilation compilation = if options.Rebuild then - let namespaces = compilation.Namespaces |> Seq.map this.Namespaces.OnNamespace |> ImmutableArray.CreateRange + let namespaces = + compilation.Namespaces |> Seq.map this.Namespaces.OnNamespace |> ImmutableArray.CreateRange + QsCompilation.New(namespaces, compilation.EntryPoints) else compilation.Namespaces |> Seq.iter (this.Namespaces.OnNamespace >> ignore) @@ -78,7 +80,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 @@ -109,7 +111,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 @@ -141,7 +143,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 @@ -177,7 +179,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 @@ -213,7 +215,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 @@ -250,7 +252,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 @@ -314,7 +316,9 @@ type SyntaxTreeTransformation private (options: TransformationOptions, _internal /// Invokes the transformation for all namespaces in the given compilation. member this.OnCompilation compilation = if options.Rebuild then - let namespaces = compilation.Namespaces |> Seq.map this.Namespaces.OnNamespace |> ImmutableArray.CreateRange + let namespaces = + compilation.Namespaces |> Seq.map this.Namespaces.OnNamespace |> ImmutableArray.CreateRange + QsCompilation.New(namespaces, compilation.EntryPoints) else compilation.Namespaces |> Seq.iter (this.Namespaces.OnNamespace >> ignore) @@ -352,7 +356,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 @@ -381,7 +385,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 @@ -411,7 +415,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 @@ -445,7 +449,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 @@ -479,7 +483,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 @@ -514,7 +518,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/TypeTransformation.fs b/src/QsCompiler/Core/Transformations/TypeTransformation.fs index ec84da3c22..dba4a34059 100644 --- a/src/QsCompiler/Core/Transformations/TypeTransformation.fs +++ b/src/QsCompiler/Core/Transformations/TypeTransformation.fs @@ -26,7 +26,7 @@ type TypeTransformationBase internal (options: TransformationOptions, _internal_ member val internal CommonTransformationItemsHandle = missingTransformation "common items" with get, set - member this.Common : CommonTransformationNodes = this.CommonTransformationItemsHandle() + member this.Common: CommonTransformationNodes = this.CommonTransformationItemsHandle() internal new(getCommonItems: unit -> CommonTransformationNodes, options: TransformationOptions) as this = new TypeTransformationBase(options, "_internal_") @@ -44,7 +44,7 @@ type TypeTransformationBase internal (options: TransformationOptions, _internal_ // TODO: RELEASE 2021-10: Remove obsolete method. [] - abstract OnRangeInformation : QsNullable -> QsNullable + abstract OnRangeInformation: QsNullable -> QsNullable // TODO: RELEASE 2021-10: Remove obsolete method. [] @@ -52,16 +52,16 @@ type TypeTransformationBase internal (options: TransformationOptions, _internal_ // TODO: RELEASE 2022-09: Remove obsolete method. [] - abstract OnTypeRange : TypeRange -> TypeRange + abstract OnTypeRange: TypeRange -> TypeRange // TODO: RELEASE 2022-09: Remove obsolete method. [] override 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 @@ -71,14 +71,14 @@ type TypeTransformationBase internal (options: TransformationOptions, _internal_ // 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 // udt.Range should be removed along with OnRangeInformation 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 @@ -86,25 +86,25 @@ type TypeTransformationBase internal (options: TransformationOptions, _internal_ let range = this.OnRangeInformation tp.Range // tp.Range should be removed along with OnRangeInformation 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) @@ -112,46 +112,46 @@ type TypeTransformationBase internal (options: TransformationOptions, _internal_ // 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 diff --git a/src/QsCompiler/DataStructures/DataTypes.fs b/src/QsCompiler/DataStructures/DataTypes.fs index efdd62b9b4..2eab3c804f 100644 --- a/src/QsCompiler/DataStructures/DataTypes.fs +++ b/src/QsCompiler/DataStructures/DataTypes.fs @@ -314,7 +314,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 819cd4d272..2ed1ac7bce 100644 --- a/src/QsCompiler/DataStructures/Diagnostics.fs +++ b/src/QsCompiler/DataStructures/Diagnostics.fs @@ -451,7 +451,7 @@ type DiagnosticItem = | Information of InformationCode static member private ApplyArguments (args: IEnumerable) str = - let args : obj [] = + let args: obj [] = if args = null then [||] else diff --git a/src/QsCompiler/DataStructures/Documentation.fs b/src/QsCompiler/DataStructures/Documentation.fs index 12fa9b1c12..304728b06f 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/Serialization.fs b/src/QsCompiler/DataStructures/Serialization.fs index f05ae40bfb..46731133e3 100644 --- a/src/QsCompiler/DataStructures/Serialization.fs +++ b/src/QsCompiler/DataStructures/Serialization.fs @@ -413,9 +413,9 @@ type DictionaryAsArrayResolver() = && t.GetGenericTypeDefinition() = typeof>.GetGenericTypeDefinition ()) if objectType.GetInterfaces().Any(new Func<_, _>(isDictionary)) then - base.CreateArrayContract(objectType) :> JsonContract + ``base``.CreateArrayContract(objectType) :> JsonContract else - base.CreateContract(objectType) + ``base``.CreateContract(objectType) module Json = diff --git a/src/QsCompiler/DataStructures/SyntaxTokens.fs b/src/QsCompiler/DataStructures/SyntaxTokens.fs index 26aa521fef..267fbb1112 100644 --- a/src/QsCompiler/DataStructures/SyntaxTokens.fs +++ b/src/QsCompiler/DataStructures/SyntaxTokens.fs @@ -149,7 +149,7 @@ type Lambda<'Expr, 'Type> = member lambda.Kind = lambda.kind /// The symbol tuple for the lambda's parameter. - member lambda.ArgumentTuple : QsTuple> = lambda.paramTuple + member lambda.ArgumentTuple = lambda.paramTuple /// The body of the lambda. member lambda.Body = lambda.body @@ -164,7 +164,7 @@ module Lambda = body = body } - let createUnchecked kind (paramTuple: QsSymbol) body = + let createUnchecked kind paramTuple body = let variableDeclaration = { VariableName = InvalidName @@ -174,7 +174,7 @@ module Lambda = Range = Range.Zero } - let rec mapSymbol (sym: QsSymbol) = + let rec mapSymbol sym = match sym.Symbol with | Symbol name -> let range = sym.Range.ValueOrApply(fun _ -> failwith "missing range information for valid symbol") diff --git a/src/QsCompiler/Optimizations/OptimizingTransformations/CallableInlining.fs b/src/QsCompiler/Optimizations/OptimizingTransformations/CallableInlining.fs index f6e2a94db0..0b44cae3b1 100644 --- a/src/QsCompiler/Optimizations/OptimizingTransformations/CallableInlining.fs +++ b/src/QsCompiler/Optimizations/OptimizingTransformations/CallableInlining.fs @@ -92,7 +92,9 @@ type private InliningInfo = let! functors, callable, arg = InliningInfo.TrySplitCall callables expr.Expression let! specArgs, body = InliningInfo.TryGetProvidedImpl callable functors let body = ReplaceTypeParams(expr.TypeParameterResolutions).Statements.OnScope body - let returnType = ReplaceTypeParams(expr.TypeParameterResolutions).Types.OnType callable.Signature.ReturnType + + let returnType = + ReplaceTypeParams(expr.TypeParameterResolutions).Types.OnType callable.Signature.ReturnType return { @@ -154,8 +156,7 @@ and private CallableInliningStatements(parent: CallableInlining, callables: Immu : 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 d1dd2b75cf..3b8d372b20 100644 --- a/src/QsCompiler/Optimizations/OptimizingTransformations/ConstantPropagation.fs +++ b/src/QsCompiler/Optimizations/OptimizingTransformations/ConstantPropagation.fs @@ -35,7 +35,7 @@ and private ConstantPropagationNamespaces(parent: ConstantPropagation) = override __.OnProvidedImplementation(argTuple, body) = parent.Constants.Clear() - base.OnProvidedImplementation(argTuple, body) + ``base``.OnProvidedImplementation(argTuple, body) /// private helper class for ConstantPropagation and private ConstantPropagationStatementKinds(parent: ConstantPropagation, callables) = @@ -151,21 +151,20 @@ 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 c6cc54c3ff..fab4597286 100644 --- a/src/QsCompiler/Optimizations/OptimizingTransformations/LoopUnrolling.fs +++ b/src/QsCompiler/Optimizations/OptimizingTransformations/LoopUnrolling.fs @@ -52,13 +52,11 @@ and private LoopUnrollingStatementKinds(parent: LoopUnrolling, callables, maxSiz let iterRange = iterValsList - |> List.map - (fun x -> - let variableDecl = - QsBinding.New ImmutableBinding (loopVar, x) |> QsVariableDeclaration |> 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 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 638a2bbf69..d6774aec0d 100644 --- a/src/QsCompiler/Optimizations/OptimizingTransformations/StatementRemoving.fs +++ b/src/QsCompiler/Optimizations/OptimizingTransformations/StatementRemoving.fs @@ -53,28 +53,25 @@ 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 diff --git a/src/QsCompiler/Optimizations/OptimizingTransformations/VariableRemoving.fs b/src/QsCompiler/Optimizations/OptimizingTransformations/VariableRemoving.fs index 4612ae84d2..5e17f50023 100644 --- a/src/QsCompiler/Optimizations/OptimizingTransformations/VariableRemoving.fs +++ b/src/QsCompiler/Optimizations/OptimizingTransformations/VariableRemoving.fs @@ -32,7 +32,7 @@ and private VariableRemovalNamespaces(parent: VariableRemoval) = let r = ReferenceCounter() r.Statements.OnScope body |> ignore parent.ReferenceCounter <- Some r - base.OnProvidedImplementation(argTuple, body) + ``base``.OnProvidedImplementation(argTuple, body) /// private helper class for VariableRemoval and private VariableRemovalStatementKinds(parent: VariableRemoval) = diff --git a/src/QsCompiler/Optimizations/Utils/ComputationExpressions.fs b/src/QsCompiler/Optimizations/Utils/ComputationExpressions.fs index a4f3d62814..83d45c73a0 100644 --- a/src/QsCompiler/Optimizations/Utils/ComputationExpressions.fs +++ b/src/QsCompiler/Optimizations/Utils/ComputationExpressions.fs @@ -128,7 +128,7 @@ 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) /// Updates the current state of an imperative computation using the given function diff --git a/src/QsCompiler/Optimizations/Utils/Evaluation.fs b/src/QsCompiler/Optimizations/Utils/Evaluation.fs index 8b0c62a045..df2cdcb18a 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 diff --git a/src/QsCompiler/Optimizations/Utils/HelperFunctions.fs b/src/QsCompiler/Optimizations/Utils/HelperFunctions.fs index 852a5ee2d0..e17cd5ea37 100644 --- a/src/QsCompiler/Optimizations/Utils/HelperFunctions.fs +++ b/src/QsCompiler/Optimizations/Utils/HelperFunctions.fs @@ -154,9 +154,9 @@ let internal rangeLiteralToSeq (r: ExprKind) : seq = match r with | RangeLiteral (a, b) -> match a.Expression, b.Expression with - | IntLiteral start, IntLiteral stop -> seq { start .. stop } + | IntLiteral start, IntLiteral stop -> seq { start..stop } | RangeLiteral ({ Expression = IntLiteral start }, { Expression = IntLiteral step }), IntLiteral stop -> - seq { start .. step .. stop } + seq { start..step..stop } | _ -> ArgumentException "Invalid range literal" |> raise | _ -> ArgumentException "Not a range literal" |> raise @@ -195,8 +195,7 @@ 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 @@ -331,8 +330,7 @@ let internal findAllSubStatements (scope: QsScope) = let internal countReturnStatements (scope: QsScope) : int = scope |> findAllSubStatements - |> Seq.sumBy - (function + |> Seq.sumBy (function | QsReturnStatement _ -> 1 | _ -> 0) diff --git a/src/QsCompiler/Optimizations/Utils/OptimizationTools.fs b/src/QsCompiler/Optimizations/Utils/OptimizationTools.fs index ea0db95971..9480b85fae 100644 --- a/src/QsCompiler/Optimizations/Utils/OptimizationTools.fs +++ b/src/QsCompiler/Optimizations/Utils/OptimizationTools.fs @@ -33,12 +33,11 @@ and private DistinctQubitsNamespaces(parent: FindDistinctQubits) = argTuple |> toSymbolTuple |> flatten - |> Seq.iter - (function + |> Seq.iter (function | VariableName name -> parent.DistinctNames <- parent.DistinctNames.Add name | _ -> ()) - base.OnProvidedImplementation(argTuple, body) + ``base``.OnProvidedImplementation(argTuple, body) /// private helper class for FindDistinctQubits and private DistinctQubitsStatementKinds(parent: FindDistinctQubits) = @@ -47,8 +46,7 @@ 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 | _ -> ()) @@ -79,8 +77,7 @@ 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 | _ -> ()) @@ -90,8 +87,7 @@ 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 | _ -> ()) | _ -> () @@ -124,7 +120,7 @@ and private ReferenceCounterExpressionKinds(parent: ReferenceCounter) = | LocalVariable name -> parent.UsedVariables <- parent.UsedVariables.Add(name, parent.NumberOfUses name + 1) | _ -> () - base.OnIdentifier(sym, tArgs) + ``base``.OnIdentifier(sym, tArgs) /// private helper class for ReplaceTypeParams @@ -155,12 +151,12 @@ type private SideEffectCheckerExpressionKinds(parent: SideEffectChecker) = override this.OnFunctionCall(method, arg) = parent.HasOutput <- true - base.OnFunctionCall(method, arg) + ``base``.OnFunctionCall(method, arg) override this.OnOperationCall(method, arg) = parent.HasQuantum <- true parent.HasOutput <- true - base.OnOperationCall(method, arg) + ``base``.OnOperationCall(method, arg) /// private helper class for SideEffectChecker and private SideEffectCheckerStatementKinds(parent: SideEffectChecker) = @@ -209,7 +205,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/Optimizations/Utils/VariableRenaming.fs b/src/QsCompiler/Optimizations/Utils/VariableRenaming.fs index 3322837047..ff76ea4382 100644 --- a/src/QsCompiler/Optimizations/Utils/VariableRenaming.fs +++ b/src/QsCompiler/Optimizations/Utils/VariableRenaming.fs @@ -102,7 +102,7 @@ and private VariableRenamingNamespaces(parent: VariableRenaming) = override __.OnProvidedImplementation(argTuple, body) = parent.Clear() do processArgTuple argTuple - base.OnProvidedImplementation(argTuple, body) + ``base``.OnProvidedImplementation(argTuple, body) /// private helper class for VariableRenaming and private VariableRenamingStatements(parent: VariableRenaming) = diff --git a/src/QsCompiler/RoslynWrapper/ExpressionStatement.fs b/src/QsCompiler/RoslynWrapper/ExpressionStatement.fs index 007b65dec0..76a0355bb9 100644 --- a/src/QsCompiler/RoslynWrapper/ExpressionStatement.fs +++ b/src/QsCompiler/RoslynWrapper/ExpressionStatement.fs @@ -1,5 +1,6 @@ namespace Microsoft.Quantum.RoslynWrapper +#nowarn "46" // Backticks removed by Fantomas: https://github.com/fsprojects/fantomas/issues/2034 #nowarn "1182" // Unused parameters [] @@ -281,7 +282,7 @@ module Statements = SyntaxFactory.YieldStatement(SyntaxKind.YieldReturnStatement, value) :> StatementSyntax // break; - let ``break`` = SyntaxFactory.BreakStatement() :> StatementSyntax + let break = SyntaxFactory.BreakStatement() :> StatementSyntax // { blocks } let ``}}`` = None diff --git a/src/QsCompiler/RoslynWrapper/WhiteNoise.fs b/src/QsCompiler/RoslynWrapper/WhiteNoise.fs index 7365cdef00..c9587e400d 100644 --- a/src/QsCompiler/RoslynWrapper/WhiteNoise.fs +++ b/src/QsCompiler/RoslynWrapper/WhiteNoise.fs @@ -1,5 +1,7 @@ namespace Microsoft.Quantum.RoslynWrapper +#nowarn "46" // Backticks removed by Fantomas: https://github.com/fsprojects/fantomas/issues/2034 + [] module WhiteNoise = open Microsoft.CodeAnalysis.CSharp @@ -19,13 +21,13 @@ module WhiteNoise = let ``in`` = None let ``private`` = SyntaxKind.PrivateKeyword - let ``protected`` = SyntaxKind.ProtectedKeyword + let protected = SyntaxKind.ProtectedKeyword let ``internal`` = SyntaxKind.InternalKeyword let ``public`` = SyntaxKind.PublicKeyword let partial = SyntaxKind.PartialKeyword let ``abstract`` = SyntaxKind.AbstractKeyword let async = SyntaxKind.AsyncKeyword - let ``virtual`` = SyntaxKind.VirtualKeyword + let virtual = SyntaxKind.VirtualKeyword let ``override`` = SyntaxKind.OverrideKeyword let ``static`` = SyntaxKind.StaticKeyword let readonly = SyntaxKind.ReadOnlyKeyword diff --git a/src/QsCompiler/SyntaxProcessor/CapabilityInference.fs b/src/QsCompiler/SyntaxProcessor/CapabilityInference.fs index bc16b80318..88f1fad9e5 100644 --- a/src/QsCompiler/SyntaxProcessor/CapabilityInference.fs +++ b/src/QsCompiler/SyntaxProcessor/CapabilityInference.fs @@ -162,10 +162,9 @@ 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 @@ -253,28 +252,26 @@ let rec private referenceReasons | 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 @@ -418,17 +415,16 @@ 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 /// Returns the attribute for the inferred runtime capability. let private toAttribute capability = - let args = AttributeUtils.StringArguments(capability.ToString(), "Inferred automatically by the compiler.") + let args = AttributeUtils.StringArguments(string capability, "Inferred automatically by the compiler.") AttributeUtils.BuildAttribute(BuiltIn.RequiresCapability.FullName, args) /// Infers the capability of all callables in the compilation, adding the built-in Capability attribute to each diff --git a/src/QsCompiler/SyntaxProcessor/DeclarationVerification.fs b/src/QsCompiler/SyntaxProcessor/DeclarationVerification.fs index 3e2a8a600d..bf0a5ec06a 100644 --- a/src/QsCompiler/SyntaxProcessor/DeclarationVerification.fs +++ b/src/QsCompiler/SyntaxProcessor/DeclarationVerification.fs @@ -236,9 +236,8 @@ let public WithAbsolutePosition (this: LocalDeclarations) (updatePosition: Func< this .Variables .Select( - Func<_, _> - (fun (d: LocalVariableDeclaration<_>) -> - { d with Position = updatePosition.Invoke d.Position |> Value }) + 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 78ae844c10..4ee4bc4dd0 100644 --- a/src/QsCompiler/SyntaxProcessor/ExpressionVerification.fs +++ b/src/QsCompiler/SyntaxProcessor/ExpressionVerification.fs @@ -21,7 +21,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) = @@ -114,7 +114,10 @@ let private verifyUdtWith processUdt (resolvedType: ResolvedType) range = match resolvedType.Resolution with | QsTypeKind.UserDefinedType udt -> let diagnostics = ResizeArray() - let resultType = udt |> processUdt (fun error -> QsCompilerDiagnostic.Error error range |> diagnostics.Add) + + let resultType = + udt |> processUdt (fun error -> QsCompilerDiagnostic.Error error range |> diagnostics.Add) + resultType, Seq.toList diagnostics | _ -> ResolvedType.New InvalidType, @@ -212,11 +215,10 @@ 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), @@ -262,11 +264,10 @@ let private verifyIdentifier (inference: InferenceContext) (symbols: SymbolTrack |> QsNullable<_>.Map (fun (args: ImmutableArray) -> args - |> Seq.map - (fun tArg -> - match tArg.Type with - | MissingType -> ResolvedType.New MissingType - | _ -> symbols.ResolveType diagnostics.Add tArg)) + |> 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 @@ -295,8 +296,7 @@ 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) @@ -304,12 +304,11 @@ 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 = @@ -318,7 +317,9 @@ let private verifyIdentifier (inference: InferenceContext) (symbols: SymbolTrack else Identifier(GlobalCallable name, ImmutableArray.CreateRange resolutions.Values |> Value) - let exInfo = InferredExpressionInformation.New(isMutable = false, quantumDep = info.HasLocalQuantumDependency) + let exInfo = + InferredExpressionInformation.New(isMutable = false, quantumDep = info.HasLocalQuantumDependency) + TypedExpression.New(identifier, resolutions, resId.Type, exInfo, symbol.Range), Seq.toList diagnostics /// Verifies that an expression of the given rhsType, used within the given parent (i.e. specialization declaration), @@ -353,7 +354,9 @@ let rec internal 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 @@ -379,7 +382,8 @@ let rec internal verifyBinding (inference: InferenceContext) tryBuildDeclaration let combine (item, declarations1, diagnostics1) (items, declarations2, diagnostics2) = item :: items, Array.append declarations1 declarations2, Array.append diagnostics1 diagnostics2 - let items, declarations, diagnostics = Seq.foldBack combine (Seq.map2 verify symbols types) ([], [||], [||]) + let items, declarations, diagnostics = + Seq.foldBack combine (Seq.map2 verify symbols types) ([], [||], [||]) let symbolTuple = match items with @@ -391,8 +395,7 @@ let rec internal verifyBinding (inference: InferenceContext) tryBuildDeclaration let private characteristicsSet info = info.Characteristics.SupportedFunctors |> QsNullable.defaultValue ImmutableHashSet.Empty - |> Seq.map - (function + |> Seq.map (function | Adjoint -> Adjointable | Controlled -> Controllable) |> Set.ofSeq @@ -420,7 +423,7 @@ let private lambdaCharacteristics (inference: InferenceContext) (body: TypedExpr { new ExpressionKindTransformation() with override _.OnCallLikeExpression(callable, arg) = onCall callable.ResolvedType - base.OnCallLikeExpression(callable, arg) + ``base``.OnCallLikeExpression(callable, arg) // Call expressions in nested lambdas don't affect our characteristics, so don't visit nested lambda bodies. override _.OnLambda lambda = Lambda lambda @@ -532,7 +535,9 @@ type QsExpression with /// Resolves and verifies the interpolated expressions, and returns the StringLiteral as typed expression. let buildStringLiteral (literal, interpolated) = let resInterpol = interpolated |> Seq.map (resolve context) |> ImmutableArray.CreateRange - let localQdependency = resInterpol |> Seq.exists (fun r -> r.InferredInformation.HasLocalQuantumDependency) + + let localQdependency = + resInterpol |> Seq.exists (fun r -> r.InferredInformation.HasLocalQuantumDependency) (StringLiteral(literal, resInterpol), String |> ResolvedType.create (TypeRange.inferred this.Range)) |> exprWithoutTypeArgs this.Range (inferred false localQdependency) @@ -545,7 +550,9 @@ type QsExpression with let buildTuple items = let items = items |> Seq.map (resolve context) |> ImmutableArray.CreateRange let types = items |> Seq.map (fun x -> x.ResolvedType) |> ImmutableArray.CreateRange - let localQdependency = items |> Seq.exists (fun item -> item.InferredInformation.HasLocalQuantumDependency) + + let localQdependency = + items |> Seq.exists (fun item -> item.InferredInformation.HasLocalQuantumDependency) if items.IsEmpty then failwith "tuple expression requires at least one tuple item" @@ -570,7 +577,9 @@ type QsExpression with let buildValueArray values = let values = values |> Seq.map (resolve context) |> ImmutableArray.CreateRange let resolvedType = values |> verifyValueArray inference this.RangeOrDefault |> takeDiagnostics - let localQdependency = values |> Seq.exists (fun item -> item.InferredInformation.HasLocalQuantumDependency) + + let localQdependency = + values |> Seq.exists (fun item -> item.InferredInformation.HasLocalQuantumDependency) (ValueArray values, resolvedType) |> exprWithoutTypeArgs this.Range (inferred false localQdependency) @@ -917,7 +926,7 @@ type QsExpression with let rec mapArgumentTuple = function | QsTupleItem (decl: LocalVariableDeclaration<_, _>) -> - let var : LocalVariableDeclaration = + let var: LocalVariableDeclaration = let resDecl = decl.WithPosition(inference.GetRelativeStatementPosition() |> Value) resDecl.WithType(inference.Fresh decl.Range) diff --git a/src/QsCompiler/SyntaxProcessor/StatementVerification.fs b/src/QsCompiler/SyntaxProcessor/StatementVerification.fs index 78dbd61422..b159e44243 100644 --- a/src/QsCompiler/SyntaxProcessor/StatementVerification.fs +++ b/src/QsCompiler/SyntaxProcessor/StatementVerification.fs @@ -108,7 +108,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 -> @@ -261,7 +261,8 @@ let NewRepeatStatement (symbols: SymbolTracker) (repeatBlock: QsPositionedBlock, | Null -> ArgumentException "no location is set for the given repeat-block" |> raise | Value loc -> loc - let autoGenErrs = symbols |> onAutoInvertGenerateError ((ErrorCode.RUSloopWithinAutoInversion, []), location.Range) + let autoGenErrs = + symbols |> onAutoInvertGenerateError ((ErrorCode.RUSloopWithinAutoInversion, []), location.Range) QsRepeatStatement.New(repeatBlock, successCondition, fixupBlock) |> QsRepeatStatement @@ -297,9 +298,8 @@ 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/SymbolOccurrence.fsi b/src/QsCompiler/SyntaxProcessor/SymbolOccurrence.fsi index f19b44faf1..38a55a0827 100644 --- a/src/QsCompiler/SyntaxProcessor/SymbolOccurrence.fsi +++ b/src/QsCompiler/SyntaxProcessor/SymbolOccurrence.fsi @@ -22,32 +22,32 @@ type SymbolOccurrence = /// Called when this occurrence is a used variable. /// Called when this occurrence is a used literal. /// The result of the called match function. - member Match : - declaration: Func - * usedType: Func - * usedVariable: Func - * usedLiteral: Func -> - 'a + member Match: + declaration: Func * + usedType: Func * + usedVariable: Func * + usedLiteral: Func -> + 'a /// /// Gets the occurring symbol if this occurrence is a declaration. /// - member TryGetDeclaration : symbol: QsSymbol outref -> bool + member TryGetDeclaration: symbol: QsSymbol outref -> bool /// /// Gets the occurring type if this occurrence is a used type. /// - member TryGetUsedType : ``type``: QsType outref -> bool + member TryGetUsedType: ``type``: QsType outref -> bool /// /// Gets the occurring symbol if this occurrence is a used variable. /// - member TryGetUsedVariable : symbol: QsSymbol outref -> bool + member TryGetUsedVariable: symbol: QsSymbol outref -> bool /// /// Gets the occurring expression if this occurrence is a used literal. /// - member TryGetUsedLiteral : expression: QsExpression outref -> bool + member TryGetUsedLiteral: expression: QsExpression outref -> bool module SymbolOccurrence = /// @@ -56,4 +56,4 @@ module SymbolOccurrence = /// The fragment to extract symbols from. /// The list of symbols. [] - val inFragment : fragment: QsFragmentKind -> SymbolOccurrence list + val inFragment: fragment: QsFragmentKind -> SymbolOccurrence list diff --git a/src/QsCompiler/SyntaxProcessor/SymbolTracker.fs b/src/QsCompiler/SyntaxProcessor/SymbolTracker.fs index 34eae769ef..765fa43665 100644 --- a/src/QsCompiler/SyntaxProcessor/SymbolTracker.fs +++ b/src/QsCompiler/SyntaxProcessor/SymbolTracker.fs @@ -69,7 +69,7 @@ type SymbolTracker(globals: NamespaceManager, sourceFile, parent: QsQualifiedNam /// 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 @@ -91,8 +91,7 @@ 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() diff --git a/src/QsCompiler/SyntaxProcessor/SyntaxExtensions.fs b/src/QsCompiler/SyntaxProcessor/SyntaxExtensions.fs index 827eff26a9..43b52714a2 100644 --- a/src/QsCompiler/SyntaxProcessor/SyntaxExtensions.fs +++ b/src/QsCompiler/SyntaxProcessor/SyntaxExtensions.fs @@ -294,7 +294,10 @@ let public PrintSignature (header: CallableDeclarationHeader) = QsComments.Empty) let signature = SyntaxTreeToQsharp.DeclarationSignature(callable, new Func<_, _>(TypeName)) - let annotation = CharacteristicsAnnotation(header.Signature.Information.Characteristics, sprintf "%s%s" newLine) + + let annotation = + CharacteristicsAnnotation(header.Signature.Information.Characteristics, sprintf "%s%s" newLine) + sprintf "%s%s" signature annotation [] diff --git a/src/QsCompiler/SyntaxProcessor/TreeVerification.fs b/src/QsCompiler/SyntaxProcessor/TreeVerification.fs index d35cce2774..44e7c0acd4 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()) @@ -188,32 +188,31 @@ 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 () @@ -234,7 +233,8 @@ let CheckDefinedTypesForCycles (definitions: ImmutableArray List.mapi (fun i x -> (i, x)) |> List.filter (fun x -> (snd x).Count <> 0) + let remaining = + containedIn |> List.mapi (fun i x -> (i, x)) |> List.filter (fun x -> (snd x).Count <> 0) if remaining.Length <> 0 then for (udtIndex, _) in remaining do diff --git a/src/QsCompiler/SyntaxProcessor/TypeInference/Constraint.fs b/src/QsCompiler/SyntaxProcessor/TypeInference/Constraint.fs index 991b5291e6..97220bb9b6 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 95f246a50e..57173703fe 100644 --- a/src/QsCompiler/SyntaxProcessor/TypeInference/InferenceContext.fs +++ b/src/QsCompiler/SyntaxProcessor/TypeInference/InferenceContext.fs @@ -285,12 +285,11 @@ module 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 . @@ -371,9 +370,8 @@ 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 = @@ -595,7 +593,9 @@ type InferenceContext(symbolTracker: SymbolTracker) = member private context.ApplyConstraints(param, resolvedType) = match variables.TryGetValue param |> tryOption with | Some variable -> - let diagnostics = variable.Constraints |> List.collect (fun c -> context.ApplyConstraint(c, resolvedType)) + let diagnostics = + variable.Constraints |> List.collect (fun c -> context.ApplyConstraint(c, resolvedType)) + variables.[param] <- { variable with Constraints = [] } diagnostics | None -> [] diff --git a/src/QsCompiler/SyntaxProcessor/TypeInference/InferenceContext.fsi b/src/QsCompiler/SyntaxProcessor/TypeInference/InferenceContext.fsi index d45a22b10c..7da8e3beb5 100644 --- a/src/QsCompiler/SyntaxProcessor/TypeInference/InferenceContext.fsi +++ b/src/QsCompiler/SyntaxProcessor/TypeInference/InferenceContext.fsi @@ -18,17 +18,17 @@ module internal RelationOps = /// /// is a subtype of . /// - val (<.): lhs:'a -> rhs:'a -> 'a Relation + val (<.): lhs: 'a -> rhs: 'a -> 'a Relation /// /// is equal to . /// - val (.=.): lhs:'a -> rhs:'a -> 'a Relation + val (.=.): lhs: 'a -> rhs: 'a -> 'a Relation /// /// is a supertype of . /// - val (.>): lhs:'a -> rhs:'a -> 'a Relation + val (.>): lhs: 'a -> rhs: 'a -> 'a Relation /// The inference context is an implementation of Hindley-Milner type inference. It is a source of fresh type parameters /// and can unify types containing them. @@ -36,16 +36,16 @@ type InferenceContext = /// /// Creates a new inference context using the given . /// - new: symbolTracker:SymbolTracker -> InferenceContext + new: symbolTracker: SymbolTracker -> InferenceContext /// Diagnostics for all type variables that are missing substitutions. member AmbiguousDiagnostics: QsCompilerDiagnostic list /// Updates the position of the statement in which types are currently being inferred. - member UseStatementPosition: position:Position -> unit + member UseStatementPosition: position: Position -> unit /// Updates the the root node position and the position of the statement in which types are currently being inferred relative to that. - member UseSyntaxTreeNodeLocation: rootNodePosition:Position * relativePosition:Position -> unit + member UseSyntaxTreeNodeLocation: rootNodePosition: Position * relativePosition: Position -> unit /// Gets the position of the statement relative to the root node in which types are currently being inferred. member internal GetRelativeStatementPosition: unit -> Position @@ -53,7 +53,7 @@ type InferenceContext = /// /// Creates a fresh type parameter originating from the given range. /// - member internal Fresh: source:Range -> ResolvedType + member internal Fresh: source: Range -> ResolvedType /// /// Matches the types in the according to its ordering. @@ -62,24 +62,24 @@ type InferenceContext = /// Diagnostics if the types did not match. For error reporting purposes, the left-hand type is considered the /// expected type. /// - member internal Match: relation:ResolvedType Relation -> QsCompilerDiagnostic list + member internal Match: relation: ResolvedType Relation -> QsCompilerDiagnostic list /// /// Returns a type that is a supertype of both types and , and that /// has a range. /// - member internal Intersect: type1:ResolvedType * type2:ResolvedType -> ResolvedType * QsCompilerDiagnostic list + member internal Intersect: type1: ResolvedType * type2: ResolvedType -> ResolvedType * QsCompilerDiagnostic list /// /// Constrains the given to satisfy the . /// - member internal Constrain: type_:ResolvedType * constraint_:Constraint -> QsCompilerDiagnostic list + member internal Constrain: type_: ResolvedType * constraint_: Constraint -> QsCompilerDiagnostic list /// /// Replaces each placeholder type parameter in the given with its substitution if /// one exists. /// - member internal Resolve: type_:ResolvedType -> ResolvedType + member internal Resolve: type_: ResolvedType -> ResolvedType /// /// Utility functions for . @@ -89,4 +89,4 @@ module InferenceContext = /// A syntax tree transformation that resolves types using the given inference . /// [] - val resolver: context:InferenceContext -> SyntaxTreeTransformation + val resolver: context: InferenceContext -> SyntaxTreeTransformation diff --git a/src/QsCompiler/Tests.CSharpGeneration/SimulationCodeTests.fs b/src/QsCompiler/Tests.CSharpGeneration/SimulationCodeTests.fs index 13ebe7154e..d99d505c12 100644 --- a/src/QsCompiler/Tests.CSharpGeneration/SimulationCodeTests.fs +++ b/src/QsCompiler/Tests.CSharpGeneration/SimulationCodeTests.fs @@ -101,7 +101,7 @@ namespace N1 |> List.iter testCulture let parse files = - let mutable errors : Diagnostic list = [] + let mutable errors: Diagnostic list = [] let addError (diag: Diagnostic) = if diag.Severity.HasValue then @@ -3134,7 +3134,10 @@ public class NamedTuple : UDTBase<((Int64,Double),Int64)>, IApplyData | QsCallable op -> op.FullName.Name let expected = [ "H"; "M"; "Qubits"; "Qubits"; "R"; "S"; "X"; "Z" ] // Qubits is two times: one for UDT and one for constructor. - let local = syntaxTree |> findLocalElements Some (Path.GetFullPath(Path.Combine("Circuits", "Intrinsic.qs"))) + + let local = + syntaxTree |> findLocalElements Some (Path.GetFullPath(Path.Combine("Circuits", "Intrinsic.qs"))) + Assert.Equal(1, local.Length) Assert.Equal("Microsoft.Quantum.Intrinsic", (fst local.[0])) let actual = (snd local.[0]) |> List.map oneName |> List.sort diff --git a/src/QsCompiler/Tests.Compiler/CallGraphTests.fs b/src/QsCompiler/Tests.Compiler/CallGraphTests.fs index 8d9152276c..673fdf1b51 100644 --- a/src/QsCompiler/Tests.Compiler/CallGraphTests.fs +++ b/src/QsCompiler/Tests.Compiler/CallGraphTests.fs @@ -20,7 +20,8 @@ open Xunit.Abstractions type CallGraphTests(output: ITestOutputHelper) = - let compilationManager = new CompilationUnitManager(ProjectProperties.Empty, (fun ex -> failwith ex.Message)) + let compilationManager = + new CompilationUnitManager(ProjectProperties.Empty, (fun ex -> failwith ex.Message)) let compilationManagerExe = let props = ImmutableDictionary.CreateBuilder() @@ -97,11 +98,10 @@ 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)) @@ -141,8 +141,7 @@ type CallGraphTests(output: ITestOutputHelper) = let CompileInvalidCycleTest testNumber expected = let errors = expected - |> Seq.choose - (function + |> Seq.choose (function | Error error -> Some error | _ -> None) @@ -514,11 +513,10 @@ 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/ClassicalControlTests.fs b/src/QsCompiler/Tests.Compiler/ClassicalControlTests.fs index c4b6d126bf..1f8bf3b390 100644 --- a/src/QsCompiler/Tests.Compiler/ClassicalControlTests.fs +++ b/src/QsCompiler/Tests.Compiler/ClassicalControlTests.fs @@ -384,8 +384,7 @@ type ClassicalControlTests() = let GetTypeParams call = call.Signature.TypeParameters - |> Seq.choose - (function + |> Seq.choose (function | ValidName str -> Some str | InvalidName -> None) @@ -475,7 +474,8 @@ type ClassicalControlTests() = [ (1, BuiltIn.ApplyIfZero.FullName) ] |> assertSpecializationHasCalls (TestUtils.getBodyFromCallable providedOp) - let _distributeOp = callables |> Seq.find (fun x -> x.Key.Name.EndsWith "_Distribute") |> fun x -> x.Value + let _distributeOp = + callables |> Seq.find (fun x -> x.Key.Name.EndsWith "_Distribute") |> fun x -> x.Value let _providedOps = callables |> Seq.filter (fun x -> x.Key.Name.EndsWith "_Provided") |> Seq.map (fun x -> x.Value) @@ -625,7 +625,8 @@ type ClassicalControlTests() = let adjContent = [ (0, SubOpCA2); (1, SubOpCA3) ] let ctlAdjContent = [ (2, SubOpCA3) ] - let orderedGens = identifyGeneratedByCalls generated [ bodyContent; ctlContent; adjContent; ctlAdjContent ] + let orderedGens = + identifyGeneratedByCalls generated [ bodyContent; ctlContent; adjContent; ctlAdjContent ] let bodyGen, ctlGen, adjGen, ctlAdjGen = (Seq.item 0 orderedGens), (Seq.item 1 orderedGens), (Seq.item 2 orderedGens), (Seq.item 3 orderedGens) @@ -752,7 +753,7 @@ type ClassicalControlTests() = let ctlContent = [ (0, SubOpCA3); (1, SubOpCA1) ] let adjContent = [ (0, SubOpCA2); (1, SubOpCA3) ] let orderedGens = identifyGeneratedByCalls generated [ bodyContent; ctlContent; adjContent ] - let bodyGen, ctlGen, adjGen = (Seq.item 0 orderedGens), (Seq.item 1 orderedGens), (Seq.item 2 orderedGens) + let bodyGen, ctlGen, adjGen = Seq.item 0 orderedGens, Seq.item 1 orderedGens, Seq.item 2 orderedGens TestUtils.assertCallSupportsFunctors [ QsFunctor.Controlled; QsFunctor.Adjoint ] original TestUtils.assertCallSupportsFunctors [] bodyGen TestUtils.assertCallSupportsFunctors [] ctlGen @@ -870,7 +871,7 @@ type ClassicalControlTests() = let ctlContent = [ (0, SubOpCA3); (1, SubOpCA1) ] let adjContent = [ (0, SubOpCA2); (1, SubOpCA3) ] let orderedGens = identifyGeneratedByCalls generated [ bodyContent; ctlContent; adjContent ] - let bodyGen, ctlGen, adjGen = (Seq.item 0 orderedGens), (Seq.item 1 orderedGens), (Seq.item 2 orderedGens) + let bodyGen, ctlGen, adjGen = Seq.item 0 orderedGens, Seq.item 1 orderedGens, Seq.item 2 orderedGens TestUtils.assertCallSupportsFunctors [ QsFunctor.Controlled; QsFunctor.Adjoint ] original TestUtils.assertCallSupportsFunctors [] bodyGen TestUtils.assertCallSupportsFunctors [ QsFunctor.Adjoint ] ctlGen @@ -1597,7 +1598,8 @@ type ClassicalControlTests() = TestUtils.getCallableWithName result Signatures.ClassicalControlNS "Foo" |> TestUtils.getBodyFromCallable - let generated = TestUtils.getCallablesWithSuffix result Signatures.ClassicalControlNS "_Foo" |> Seq.exactlyOne + let generated = + TestUtils.getCallablesWithSuffix result Signatures.ClassicalControlNS "_Foo" |> Seq.exactlyOne let lines = original |> TestUtils.getLinesFromSpecialization @@ -1618,11 +1620,10 @@ type ClassicalControlTests() = let parameters = generated.ArgumentTuple.Items - |> Seq.choose - (fun x -> - match x.VariableName with - | ValidName str -> Some str - | InvalidName -> None) + |> Seq.choose (fun x -> + match x.VariableName with + | ValidName str -> Some str + | InvalidName -> None) |> (fun s -> String.Join(", ", s)) Assert.True( diff --git a/src/QsCompiler/Tests.Compiler/CompilationLoaderTests.fs b/src/QsCompiler/Tests.Compiler/CompilationLoaderTests.fs index be72b66b70..f6f1b5d29c 100644 --- a/src/QsCompiler/Tests.Compiler/CompilationLoaderTests.fs +++ b/src/QsCompiler/Tests.Compiler/CompilationLoaderTests.fs @@ -26,10 +26,9 @@ 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 83a5fb73d6..9506cbb70e 100644 --- a/src/QsCompiler/Tests.Compiler/CompilationTrackerTests.fs +++ b/src/QsCompiler/Tests.Compiler/CompilationTrackerTests.fs @@ -97,7 +97,7 @@ type CompilationTrackerTests(output: ITestOutputHelper) = let taskName = "TestTask" // Measure time spent in a task. - for i in 1 .. intervalCount do + for i in 1..intervalCount do CompilationTracker.OnCompilationTaskEvent(CompilationTaskEventType.Start, null, taskName) Thread.Sleep intervalDurationInMs CompilationTracker.OnCompilationTaskEvent(CompilationTaskEventType.End, null, taskName) @@ -193,7 +193,7 @@ type CompilationTrackerTests(output: ITestOutputHelper) = CompilationTracker.OnCompilationTaskEvent(CompilationTaskEventType.Start, null, parentTaskName) Thread.Sleep initialPaddingInMs - for i in 0 .. nestedTaskCount do + for i in 0..nestedTaskCount do let taskName = sprintf "%s-%i" nestedTaskPrefix i CompilationTracker.OnCompilationTaskEvent(CompilationTaskEventType.Start, parentTaskName, taskName) Thread.Sleep nestedTaskDurationInMs @@ -212,7 +212,7 @@ type CompilationTrackerTests(output: ITestOutputHelper) = Assert.True(resultsDictionary.TryGetValue(parentTaskName, &measuredParentTaskDurationInMs)) Assert.InRange(measuredParentTaskDurationInMs, expectedParentTaskDurationInMs, Int32.MaxValue) - for i in 0 .. nestedTaskCount do + for i in 0..nestedTaskCount do let taskId = sprintf "%s.%s-%i" parentTaskName nestedTaskPrefix i let mutable measuredTaskDurationInMs = 0 Assert.True(resultsDictionary.TryGetValue(taskId, &measuredTaskDurationInMs)) @@ -258,7 +258,10 @@ type CompilationTrackerTests(output: ITestOutputHelper) = let resultsDictionary = MethodBase.GetCurrentMethod().Name |> getResultsDictionary let expectedFirstNestedTaskDurationInMs = Array.sum firstNestedTasksDurationInMs let expectedSecondNestedTaskDurationInMs = Array.sum secondNestedTasksDurationInMs - let expectedParentTaskDurationInMs = expectedFirstNestedTaskDurationInMs + expectedSecondNestedTaskDurationInMs + + let expectedParentTaskDurationInMs = + expectedFirstNestedTaskDurationInMs + expectedSecondNestedTaskDurationInMs + let mutable measuredParentTaskDurationInMs = 0 Assert.True(resultsDictionary.TryGetValue(parentTaskName, &measuredParentTaskDurationInMs)) Assert.InRange(measuredParentTaskDurationInMs, expectedParentTaskDurationInMs, Int32.MaxValue) @@ -300,8 +303,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 @@ -313,8 +316,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 [] @@ -323,8 +326,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 [] @@ -336,6 +339,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/ExternalRewriteStepsManagerTests.fs b/src/QsCompiler/Tests.Compiler/ExternalRewriteStepsManagerTests.fs index f85f15d286..a5fe97c7a3 100644 --- a/src/QsCompiler/Tests.Compiler/ExternalRewriteStepsManagerTests.fs +++ b/src/QsCompiler/Tests.Compiler/ExternalRewriteStepsManagerTests.fs @@ -12,17 +12,17 @@ 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.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.Priority: int = priority member this.Transformation ( @@ -56,7 +56,7 @@ type ExternalRewriteStepsManagerTests() = [] member this.``Loading Assembly based steps (legacy)``() = - let config = new CompilationLoader.Configuration(RewriteSteps = [ (this.GetType().Assembly.Location, "") ]) + let config = CompilationLoader.Configuration(RewriteSteps = [ (this.GetType().Assembly.Location, "") ]) let loadedSteps = GetSteps config VerifyStep loadedSteps @@ -70,14 +70,14 @@ type ExternalRewriteStepsManagerTests() = [] member this.``Loading Type based steps``() = - let config = new CompilationLoader.Configuration(RewriteStepTypes = [ (typedefof, "") ]) + let config = CompilationLoader.Configuration(RewriteStepTypes = [ (typedefof, "") ]) let loadedSteps = GetSteps config VerifyStep loadedSteps [] member this.``Loading instance based steps``() = - let stepInstance = new TestRewriteStep() - let config = new CompilationLoader.Configuration(RewriteStepInstances = [ (stepInstance :> IRewriteStep, "") ]) + let stepInstance = TestRewriteStep() + let config = CompilationLoader.Configuration(RewriteStepInstances = [ (upcast stepInstance, "") ]) let loadedSteps = GetSteps config VerifyStep loadedSteps diff --git a/src/QsCompiler/Tests.Compiler/LambdaLiftingTests.fs b/src/QsCompiler/Tests.Compiler/LambdaLiftingTests.fs index da8acefe29..ac093c57fc 100644 --- a/src/QsCompiler/Tests.Compiler/LambdaLiftingTests.fs +++ b/src/QsCompiler/Tests.Compiler/LambdaLiftingTests.fs @@ -329,7 +329,8 @@ type LambdaLiftingTests() = member this.``Function Lambda``() = let result = compileLambdaLiftingTest 10 - let generated = TestUtils.getCallablesWithSuffix result Signatures.LambdaLiftingNS "_Foo" |> Seq.exactlyOne + let generated = + TestUtils.getCallablesWithSuffix result Signatures.LambdaLiftingNS "_Foo" |> Seq.exactlyOne Assert.True(generated.Kind = QsCallableKind.Function, "The generated callable was expected to be a function.") @@ -344,7 +345,8 @@ type LambdaLiftingTests() = let result = LiftLambdaExpressions.Apply compilationDataStructures.BuiltCompilation Assert.NotNull result - let generated = TestUtils.getCallablesWithSuffix result Signatures.LambdaLiftingNS "_Foo" |> Seq.exactlyOne + let generated = + TestUtils.getCallablesWithSuffix result Signatures.LambdaLiftingNS "_Foo" |> Seq.exactlyOne let originalExpectedName = { Namespace = Signatures.LambdaLiftingNS; Name = "Foo" } let ``Foo.A`` = QsTypeParameter.New(originalExpectedName, "A") |> TypeParameter |> ResolvedType.New @@ -384,7 +386,7 @@ type LambdaLiftingTests() = (seq { originalSigExpected generatedSigExpected - }) + }) result [] diff --git a/src/QsCompiler/Tests.Compiler/LinkingTests.fs b/src/QsCompiler/Tests.Compiler/LinkingTests.fs index b77bbc9082..19fcde5efe 100644 --- a/src/QsCompiler/Tests.Compiler/LinkingTests.fs +++ b/src/QsCompiler/Tests.Compiler/LinkingTests.fs @@ -48,7 +48,7 @@ type LinkingTests() = 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 @@ -162,12 +162,11 @@ type LinkingTests() = 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 @@ -194,11 +193,15 @@ type LinkingTests() = let countAll namespaces names = names |> Seq.map (countReferences namespaces) |> Seq.sum - let beforeCount = countAll sourceCompilation.BuiltCompilation.Namespaces (Seq.concat [ renamed; notRenamed ]) + let beforeCount = + countAll sourceCompilation.BuiltCompilation.Namespaces (Seq.concat [ renamed; notRenamed ]) + let afterCountOriginal = countAll referenceCompilation.BuiltCompilation.Namespaces renamed let decorator = new NameDecorator("QsRef") let newNames = renamed |> Seq.map (fun name -> decorator.Decorate(name, 0)) - let afterCount = countAll referenceCompilation.BuiltCompilation.Namespaces (Seq.concat [ newNames; notRenamed ]) + + let afterCount = + countAll referenceCompilation.BuiltCompilation.Namespaces (Seq.concat [ newNames; notRenamed ]) Assert.NotEqual(0, beforeCount) Assert.Equal(0, afterCountOriginal) diff --git a/src/QsCompiler/Tests.Compiler/OptimizationTests.fs b/src/QsCompiler/Tests.Compiler/OptimizationTests.fs index 20c9aa7296..ebc521db71 100644 --- a/src/QsCompiler/Tests.Compiler/OptimizationTests.fs +++ b/src/QsCompiler/Tests.Compiler/OptimizationTests.fs @@ -15,7 +15,10 @@ open Xunit /// Given a string of valid Q# code, outputs the AST and the callables dictionary let private buildCompilation code = let fileId = new Uri(Path.GetFullPath "test-file.qs") - let compilationUnit = new CompilationUnitManager(ProjectProperties.Empty, (fun ex -> failwith ex.Message)) + + let compilationUnit = + new CompilationUnitManager(ProjectProperties.Empty, (fun ex -> failwith ex.Message)) + let file = CompilationUnitManager.InitializeFileManager(fileId, code) // spawns a task that modifies the current compilation compilationUnit.AddOrUpdateSourceFileAsync file |> ignore diff --git a/src/QsCompiler/Tests.Compiler/SymbolManagementTests.fs b/src/QsCompiler/Tests.Compiler/SymbolManagementTests.fs index 412644b58f..89b3866485 100644 --- a/src/QsCompiler/Tests.Compiler/SymbolManagementTests.fs +++ b/src/QsCompiler/Tests.Compiler/SymbolManagementTests.fs @@ -62,7 +62,6 @@ 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/TestUtils/SetupVerificationTests.fs b/src/QsCompiler/Tests.Compiler/TestUtils/SetupVerificationTests.fs index 571505b666..fe57b6ab28 100644 --- a/src/QsCompiler/Tests.Compiler/TestUtils/SetupVerificationTests.fs +++ b/src/QsCompiler/Tests.Compiler/TestUtils/SetupVerificationTests.fs @@ -43,8 +43,8 @@ type CompilerTests(compilation: CompilationUnitManager.Compilation) = [ 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) @@ -74,11 +74,10 @@ 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)) @@ -113,22 +112,19 @@ type CompilerTests(compilation: CompilationUnitManager.Compilation) = 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) @@ -138,8 +134,7 @@ type CompilerTests(compilation: CompilationUnitManager.Compilation) = let other = expected - |> Seq.choose - (function + |> Seq.choose (function | Warning _ | Error _ -> None | item -> Some item) @@ -154,7 +149,9 @@ type CompilerTests(compilation: CompilationUnitManager.Compilation) = let props = ImmutableDictionary.CreateBuilder() props.Add(MSBuildProperties.ResolvedRuntimeCapabilities, capability.Name) let mutable exceptions = [] - use manager = new CompilationUnitManager(new ProjectProperties(props), (fun e -> exceptions <- e :: exceptions)) + + use manager = + new CompilationUnitManager(new ProjectProperties(props), (fun e -> exceptions <- e :: exceptions)) paths.ToImmutableDictionary(Uri, File.ReadAllText) |> CompilationUnitManager.InitializeFileManagers diff --git a/src/QsCompiler/Tests.Compiler/TestUtils/Signatures.fs b/src/QsCompiler/Tests.Compiler/TestUtils/Signatures.fs index 5f869a2354..0ab528a1c5 100644 --- a/src/QsCompiler/Tests.Compiler/TestUtils/Signatures.fs +++ b/src/QsCompiler/Tests.Compiler/TestUtils/Signatures.fs @@ -73,11 +73,10 @@ 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 diff --git a/src/QsCompiler/Tests.Compiler/TestUtils/TestUtils.fs b/src/QsCompiler/Tests.Compiler/TestUtils/TestUtils.fs index 9856814be7..070c82c950 100644 --- a/src/QsCompiler/Tests.Compiler/TestUtils/TestUtils.fs +++ b/src/QsCompiler/Tests.Compiler/TestUtils/TestUtils.fs @@ -54,21 +54,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 @@ -298,7 +298,9 @@ let readAndChunkSourceFile fileName = sourceInput.Split([| "===" |], StringSplitOptions.RemoveEmptyEntries) let buildContent content = - let compilationManager = new CompilationUnitManager(ProjectProperties.Empty, (fun ex -> failwith ex.Message)) + let compilationManager = + new CompilationUnitManager(ProjectProperties.Empty, (fun ex -> failwith ex.Message)) + let fileId = new Uri(Path.GetFullPath(Path.GetRandomFileName())) let file = @@ -366,11 +368,10 @@ let getCallablesWithSuffix compilation ns (suffix: string) = let identifyCallablesBySignature generatedCallables signatures = let mutable callables = generatedCallables - |> Seq.map - (fun x -> - x, - (SyntaxTreeToQsharp.ArgumentTuple(x.ArgumentTuple, (fun x -> SyntaxTreeToQsharp.Default.ToCode(x))), - SyntaxTreeToQsharp.Default.ToCode(x.Signature.ReturnType))) + |> Seq.map (fun x -> + x, + (SyntaxTreeToQsharp.ArgumentTuple(x.ArgumentTuple, (fun x -> SyntaxTreeToQsharp.Default.ToCode(x))), + SyntaxTreeToQsharp.Default.ToCode(x.Signature.ReturnType))) Assert.True(Seq.length callables = Seq.length signatures) // This should be true if this method is called correctly diff --git a/src/QsCompiler/Tests.Compiler/TransformationTests.fs b/src/QsCompiler/Tests.Compiler/TransformationTests.fs index cec6cd5e2b..63e9d9442c 100644 --- a/src/QsCompiler/Tests.Compiler/TransformationTests.fs +++ b/src/QsCompiler/Tests.Compiler/TransformationTests.fs @@ -71,12 +71,15 @@ and private SyntaxCounterExpressionKinds(parent: SyntaxCounter) = override this.OnCallLikeExpression(op, args) = parent.Counter.callsCount <- parent.Counter.callsCount + 1 - base.OnCallLikeExpression(op, args) + ``base``.OnCallLikeExpression(op, args) let private buildSyntaxTree code = let fileId = new Uri(Path.GetFullPath "test-file.qs") - let compilationUnit = new CompilationUnitManager(ProjectProperties.Empty, (fun ex -> failwith ex.Message)) + + let compilationUnit = + new CompilationUnitManager(ProjectProperties.Empty, (fun ex -> failwith ex.Message)) + let file = CompilationUnitManager.InitializeFileManager(fileId, code) // spawns a task that modifies the current compilation compilationUnit.AddOrUpdateSourceFileAsync file |> ignore diff --git a/src/QsCompiler/Tests.Compiler/TypeParameterTests.fs b/src/QsCompiler/Tests.Compiler/TypeParameterTests.fs index 3f8160f318..aa9842446a 100644 --- a/src/QsCompiler/Tests.Compiler/TypeParameterTests.fs +++ b/src/QsCompiler/Tests.Compiler/TypeParameterTests.fs @@ -67,7 +67,8 @@ type TypeParameterTests() = let success = CheckCombinedResolution expected resolutions Assert.False(success, "Combining type resolutions should have failed.") - let compilationManager = new CompilationUnitManager(ProjectProperties.Empty, (fun ex -> failwith ex.Message)) + let compilationManager = + new CompilationUnitManager(ProjectProperties.Empty, (fun ex -> failwith ex.Message)) let getTempFile () = new Uri(Path.GetFullPath(Path.GetRandomFileName())) diff --git a/src/QsCompiler/Tests.RoslynWrapper/Common.fs b/src/QsCompiler/Tests.RoslynWrapper/Common.fs index 05ff0cde4b..8a8d12931d 100644 --- a/src/QsCompiler/Tests.RoslynWrapper/Common.fs +++ b/src/QsCompiler/Tests.RoslynWrapper/Common.fs @@ -1,5 +1,7 @@ namespace Microsoft.Quantum.RoslynWrapper.Testing +#nowarn "46" // Backticks removed by Fantomas: https://github.com/fsprojects/fantomas/issues/2034 + open Xunit open System.Text.RegularExpressions @@ -29,7 +31,7 @@ module internal Common = to_namespace_member_code c let host_in_method t ss = - method t "Host" ``<<`` [] ``>>`` ``(`` [] ``)`` [ ``protected``; ``internal`` ] ``{`` ss ``}`` + method t "Host" ``<<`` [] ``>>`` ``(`` [] ``)`` [ protected; ``internal`` ] ``{`` ss ``}`` let return_from_arrow_method t s = - arrow_method t "Host" ``<<`` [] ``>>`` ``(`` [] ``)`` [ ``protected``; ``internal`` ] (Some <| ``=>`` s) + arrow_method t "Host" ``<<`` [] ``>>`` ``(`` [] ``)`` [ protected; ``internal`` ] (Some <| ``=>`` s) diff --git a/src/QsCompiler/Tests.RoslynWrapper/MethodTests.fs b/src/QsCompiler/Tests.RoslynWrapper/MethodTests.fs index 246bb8d89e..ea2e3afac7 100644 --- a/src/QsCompiler/Tests.RoslynWrapper/MethodTests.fs +++ b/src/QsCompiler/Tests.RoslynWrapper/MethodTests.fs @@ -1,5 +1,7 @@ namespace Microsoft.Quantum.RoslynWrapper.Testing +#nowarn "46" // Backticks removed by Fantomas: https://github.com/fsprojects/fantomas/issues/2034 + open Xunit open Microsoft.Quantum.RoslynWrapper @@ -106,7 +108,7 @@ module MethodTests = ``(`` [ param "thing" ``of`` (``type`` "object") ] ``)`` - [ ``public``; ``virtual`` ] + [ ``public``; virtual ] (Some e) let actual = to_class_members_code [ m ] diff --git a/src/QsCompiler/Tests.RoslynWrapper/NamespaceTests.fs b/src/QsCompiler/Tests.RoslynWrapper/NamespaceTests.fs index b56a3b1127..5bf1c937ad 100644 --- a/src/QsCompiler/Tests.RoslynWrapper/NamespaceTests.fs +++ b/src/QsCompiler/Tests.RoslynWrapper/NamespaceTests.fs @@ -53,7 +53,9 @@ module NamespaceTests = [] let ``namespace: type aliases`` () = - let n = ``namespace`` "Foo" ``{`` [ using "System"; using "System.Collections"; alias "Foo" "Int" ] [] ``}`` + let n = + ``namespace`` "Foo" ``{`` [ using "System"; using "System.Collections"; alias "Foo" "Int" ] [] ``}`` + let actual = to_namespace_code n let expected = diff --git a/src/QsCompiler/Tests.RoslynWrapper/StatementTests.fs b/src/QsCompiler/Tests.RoslynWrapper/StatementTests.fs index 98df446da7..3ee1a7e524 100644 --- a/src/QsCompiler/Tests.RoslynWrapper/StatementTests.fs +++ b/src/QsCompiler/Tests.RoslynWrapper/StatementTests.fs @@ -1,5 +1,7 @@ namespace Microsoft.Quantum.RoslynWrapper.Testing +#nowarn "46" // Backticks removed by Fantomas: https://github.com/fsprojects/fantomas/issues/2034 + open Xunit open Microsoft.Quantum.RoslynWrapper @@ -664,7 +666,7 @@ module StatementTests = let s = await ma |> statement let m = - method "int" "Host" ``<<`` [] ``>>`` ``(`` [] ``)`` [ ``protected``; ``internal``; async ] ``{`` [ s ] ``}`` + method "int" "Host" ``<<`` [] ``>>`` ``(`` [] ``)`` [ protected; ``internal``; async ] ``{`` [ s ] ``}`` let actual = to_class_members_code [ m ] @@ -912,7 +914,8 @@ module StatementTests = let thens x = [ (ident "a") <-- ((literal 1) <+> (literal x)) ] |> List.map statement - let (condition, thens), elifs = (condition 1, thens 1), [ 2 .. 3 ] |> List.map (fun x -> condition x, thens x) + let (condition, thens), elifs = + (condition 1, thens 1), [ 2..3 ] |> List.map (fun x -> condition x, thens x) let elses = [ @@ -1081,7 +1084,7 @@ module StatementTests = [ (ident "x") <-- ((literal 1) <-> (literal 3)) |> statement (ident "y") <-- ((``-`` (literal 1)) <*> (literal 4)) |> statement - ``break`` + break ] let stmt = ``while`` ``(`` condition ``)`` body diff --git a/src/QsCompiler/TextProcessor/CodeCompletion/ExpressionParsing.fs b/src/QsCompiler/TextProcessor/CodeCompletion/ExpressionParsing.fs index 7266b13d13..24a8eb8b38 100644 --- a/src/QsCompiler/TextProcessor/CodeCompletion/ExpressionParsing.fs +++ b/src/QsCompiler/TextProcessor/CodeCompletion/ExpressionParsing.fs @@ -28,7 +28,8 @@ let private array expression = let private missingExpr = { parse = keyword "_"; id = "_" } /// Parses a prefix operator. -let private prefixOp = expectedKeyword notOperator <|> operator qsNEGop.op "" <|> operator qsBNOTop.op "" +let private prefixOp = + expectedKeyword notOperator <|> operator qsNEGop.op "" <|> operator qsBNOTop.op "" /// Parses an infix operator. let private infixOp = diff --git a/src/QsCompiler/TextProcessor/CodeCompletion/FragmentParsing.fs b/src/QsCompiler/TextProcessor/CodeCompletion/FragmentParsing.fs index e8f8d8ea44..e57aebee33 100644 --- a/src/QsCompiler/TextProcessor/CodeCompletion/FragmentParsing.fs +++ b/src/QsCompiler/TextProcessor/CodeCompletion/FragmentParsing.fs @@ -147,7 +147,9 @@ let private applyHeader = expectedKeyword qsApply /// Parses a qubit initializer tuple used to allocate qubits in using- and borrowing-blocks. let rec private qubitInitializerTuple = parse { - let item = expectedKeyword qsQubit ?>> (expected unitValue <|> expectedBrackets (lArray, rArray) expression) + let item = + expectedKeyword qsQubit ?>> (expected unitValue <|> expectedBrackets (lArray, rArray) expression) + return! item <|> (tuple1 item <|> qubitInitializerTuple) } @@ -196,7 +198,8 @@ let private callableStatement = let private functionStatement = whileHeader .>> eotEof <|>@ callableStatement /// Parses a statement in a function that follows an if or elif clause in the same scope. -let private functionStatementFollowingIf = pcollect [ elifClause; elseClause ] .>> eotEof <|>@ functionStatement +let private functionStatementFollowingIf = + pcollect [ elifClause; elseClause ] .>> eotEof <|>@ functionStatement /// Parses a statement in an operation. let private operationStatement = @@ -208,16 +211,19 @@ let private operationStatement = <|>@ callableStatement /// Parses a statement in an operation that follows an if or elif clause in the same scope. -let private operationStatementFollowingIf = pcollect [ elifClause; elseClause ] .>> eotEof <|>@ operationStatement +let private operationStatementFollowingIf = + pcollect [ elifClause; elseClause ] .>> eotEof <|>@ operationStatement /// Parses a statement in the top-level scope of an operation. let private operationTopLevel = specializationDeclaration .>> eotEof <|>@ operationStatement /// Parses a statement in the top-level scope of an operation that follows an if or elif clause. -let private operationTopLevelFollowingIf = pcollect [ elifClause; elseClause ] .>> eotEof <|>@ operationTopLevel +let private operationTopLevelFollowingIf = + pcollect [ elifClause; elseClause ] .>> eotEof <|>@ operationTopLevel /// Parses a namespace declaration. -let private namespaceDeclaration = expectedKeyword namespaceDeclHeader ?>> expectedQualifiedSymbol Namespace +let private namespaceDeclaration = + expectedKeyword namespaceDeclHeader ?>> expectedQualifiedSymbol Namespace /// Parses the fragment text assuming that it is in the given scope and follows the given previous fragment kind in the /// same scope (or null if it is the first statement in the scope). Returns the set of completion kinds that are valid diff --git a/src/QsCompiler/TextProcessor/CodeCompletion/ParsingPrimitives.fs b/src/QsCompiler/TextProcessor/CodeCompletion/ParsingPrimitives.fs index 7e21400b0e..0bac8c2a9d 100644 --- a/src/QsCompiler/TextProcessor/CodeCompletion/ParsingPrimitives.fs +++ b/src/QsCompiler/TextProcessor/CodeCompletion/ParsingPrimitives.fs @@ -69,7 +69,7 @@ let operator (op: string) notAfter = let charByChar p c = p ?>> ((eot >>% ()) <|> (pchar c >>% ())) - let p = Seq.fold charByChar (pstring op.[..numLetters] >>% ()) op.[numLetters + 1..] + let p = Seq.fold charByChar (pstring op.[..numLetters] >>% ()) op.[numLetters + 1 ..] attempt (p ?>> nextCharSatisfiesNot (fun c -> Seq.contains c notAfter)) >>. (emptySpace >>% ()) >>% [] @@ -179,7 +179,8 @@ 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 9402b7fa8a..fe7f0a1f50 100644 --- a/src/QsCompiler/TextProcessor/ParsingPrimitives.fs +++ b/src/QsCompiler/TextProcessor/ParsingPrimitives.fs @@ -55,7 +55,8 @@ let internal isSymbolContinuation c = ] /// 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 = @@ -93,7 +94,9 @@ let internal opArrow = rwstr "=>" let internal fctArrow = rwstr "->" /// parses a unit value as a term and returnes the corresponding Q# expression -let internal unitValue = term (pstring "(" >>. emptySpace .>> pstring ")") |>> snd |>> buildQsExpression UnitValue +let internal unitValue = + term (pstring "(" >>. emptySpace .>> pstring ")") |>> snd |>> buildQsExpression UnitValue + /// parses a missing type as term and returns the corresponding Q# type let internal missingType = keyword "_" |>> buildQsType MissingType /// parses a missing expression as a term and returnes the corresponding Q# expression diff --git a/src/QsCompiler/TextProcessor/QsExpressionParsing.fs b/src/QsCompiler/TextProcessor/QsExpressionParsing.fs index f85a7ef776..4ce47a2d71 100644 --- a/src/QsCompiler/TextProcessor/QsExpressionParsing.fs +++ b/src/QsCompiler/TextProcessor/QsExpressionParsing.fs @@ -498,7 +498,9 @@ let internal buildTupleExpr (items, range: Range) = /// Uses buildTuple to generate suitable errors for invalid or missing expressions within the tuple. let private valueTuple item = // allows something like (a,(),b) let invalid = buildError (skipInvalidUntil qsFragmentHeader) ErrorCode.InvalidValueTuple >>% unknownExpr // used for processing e.g. (,) - let validTuple = buildTuple item buildTupleExpr ErrorCode.InvalidExpression ErrorCode.MissingExpression unknownExpr + + let validTuple = + buildTuple item buildTupleExpr ErrorCode.InvalidExpression ErrorCode.MissingExpression unknownExpr tupledItem item <|> validTuple @@ -509,7 +511,9 @@ let private valueTuple item = // allows something like (a,(),b) /// Uses commaSep1 to generate suitable errors for invalid or missing expressions within the array. let private valueArray = let sized = expr .>>. (comma >>. size.parse >>. equal >>. expectedExpr rArray) |>> SizedArray - let items = commaSep expr ErrorCode.InvalidExpression ErrorCode.MissingExpression unknownExpr eof |>> ValueArray + + let items = + commaSep expr ErrorCode.InvalidExpression ErrorCode.MissingExpression unknownExpr eof |>> ValueArray arrayBrackets (attempt sized <|> items) |>> QsExpression.New <|> bracketDefinedCommaSepExpr (lArray, rArray) @@ -518,7 +522,9 @@ let private valueArray = /// Adds an InvalidConstructorExpression if the array declaration keyword is not followed by a valid array constructor, /// and advances to the next whitespace character or QsFragmentHeader. let private newArray = - let itemType = expectedQsType (lArray >>% ()) >>= fun itemType -> validateTypeSyntax true itemType >>% itemType + let itemType = + expectedQsType (lArray >>% ()) >>= fun itemType -> validateTypeSyntax true itemType >>% itemType + let body = itemType .>>. (arrayBrackets (expectedExpr eof) |>> fst) |>> NewArray let toExpr headRange (kind, bodyRange) = @@ -631,7 +637,9 @@ let private itemAccessExpr = /// If the parsed argument tuple is not a unit value, /// uses buildTuple to generate a MissingArgument error if a tuple item is missing, or an InvalidArgument error for invalid items. let private argumentTuple = - let tupleArg = buildTuple argument buildTupleExpr ErrorCode.InvalidArgument ErrorCode.MissingArgument unknownExpr + let tupleArg = + buildTuple argument buildTupleExpr ErrorCode.InvalidArgument ErrorCode.MissingArgument unknownExpr + unitValue <|> tupleArg /// Parses a Q# call-like expression as QsExpression. diff --git a/src/QsCompiler/TextProcessor/QsFragmentParsing.fs b/src/QsCompiler/TextProcessor/QsFragmentParsing.fs index 449eb7beae..a5630cc31c 100644 --- a/src/QsCompiler/TextProcessor/QsFragmentParsing.fs +++ b/src/QsCompiler/TextProcessor/QsFragmentParsing.fs @@ -32,7 +32,8 @@ let private invalidArgTupleItem = (invalidSymbol, invalidType) |> QsTupleItem let private invalidInitializer = (InvalidInitializer, Null) |> QsInitializer.New /// returns a QsFunctorGenerator representing an invalid functor generator (i.e. syntax error on parsing) -let private unknownGenerator = (FunctorGenerationDirective InvalidGenerator, Null) |> QsSpecializationGenerator.New +let private unknownGenerator = + (FunctorGenerationDirective InvalidGenerator, Null) |> QsSpecializationGenerator.New /// Given a continuation (parser), attempts to parse an unqualified QsSymbol /// using localItentifier to generate suitable errors for invalid symbol names, @@ -340,7 +341,8 @@ let private controlledAdjointDeclaration = /// Uses buildFragment to parse a Q# OperationDeclaration as QsFragment. let private operationDeclaration = - let invalid = CallableDeclaration.Create(invalidSymbol, Null, CallableSignature.Invalid) |> OperationDeclaration + let invalid = + CallableDeclaration.Create(invalidSymbol, Null, CallableSignature.Invalid) |> OperationDeclaration let valid visibility (symbol, signature) = CallableDeclaration.Create(symbol, QsNullable.ofOption visibility, signature) @@ -350,7 +352,8 @@ let private operationDeclaration = /// Uses buildFragment to parse a Q# FunctionDeclaration as QsFragment. let private functionDeclaration = - let invalid = CallableDeclaration.Create(invalidSymbol, Null, CallableSignature.Invalid) |> FunctionDeclaration + let invalid = + CallableDeclaration.Create(invalidSymbol, Null, CallableSignature.Invalid) |> FunctionDeclaration let valid visibility (symbol, signature) = CallableDeclaration.Create(symbol, QsNullable.ofOption visibility, signature) |> FunctionDeclaration @@ -512,12 +515,16 @@ let private setStatement = let symbolUpdate = let continuation = isTupleContinuation >>% "" <|> equal <|> lTuple // need lTuple here to make sure tuples are not parsed as expressions! - let invalidErr, missingErr = ErrorCode.InvalidIdentifierExprInUpdate, ErrorCode.MissingIdentifierExprInUpdate + + let invalidErr, missingErr = + ErrorCode.InvalidIdentifierExprInUpdate, ErrorCode.MissingIdentifierExprInUpdate let symbolTuple = buildTupleItem (identifierExpr continuation) buildTupleExpr invalidErr missingErr unknownExpr equal - let expectedEqual = expected equal ErrorCode.ExpectingAssignment ErrorCode.ExpectingAssignment "" (preturn ()) + let expectedEqual = + expected equal ErrorCode.ExpectingAssignment ErrorCode.ExpectingAssignment "" (preturn ()) + symbolTuple .>> expectedEqual .>>. expectedExpr eof let invalid = ValueUpdate(unknownExpr, unknownExpr) @@ -557,7 +564,8 @@ let private whileHeader = /// Uses buildFragment to parse a Q# repeat intro as QsFragment. -let private repeatHeader = buildFragment qsRepeat.parse (preturn "") RepeatIntro (fun _ _ -> RepeatIntro) eof +let private repeatHeader = + buildFragment qsRepeat.parse (preturn "") RepeatIntro (fun _ _ -> RepeatIntro) eof /// Uses buildFragment to parse a Q# until success clause as QsFragment. let private untilSuccess = @@ -573,10 +581,12 @@ let private untilSuccess = /// Uses buildFragment to parse a Q# within-block intro as QsFragment. -let private withinHeader = buildFragment qsWithin.parse (preturn "") WithinBlockIntro (fun _ _ -> WithinBlockIntro) eof +let private withinHeader = + buildFragment qsWithin.parse (preturn "") WithinBlockIntro (fun _ _ -> WithinBlockIntro) eof /// Uses buildFragment to parse a Q# apply block intro as QsFragment. -let private applyHeader = buildFragment qsApply.parse (preturn "") ApplyBlockIntro (fun _ _ -> ApplyBlockIntro) eof +let private applyHeader = + buildFragment qsApply.parse (preturn "") ApplyBlockIntro (fun _ _ -> ApplyBlockIntro) eof /// Parses a Q# qubit binding keyword or an equivalent deprecated keyword. If the deprecated keyword is parsed, a diff --git a/src/QsCompiler/TextProcessor/QsKeywords.fs b/src/QsCompiler/TextProcessor/QsKeywords.fs index df755b494d..ad6790b8ae 100644 --- a/src/QsCompiler/TextProcessor/QsKeywords.fs +++ b/src/QsCompiler/TextProcessor/QsKeywords.fs @@ -256,7 +256,8 @@ type QsOperator = prec: int isLeftAssociative: bool } - member internal this.Associativity = if this.isLeftAssociative then Associativity.Left else Associativity.Right + member internal this.Associativity = + if this.isLeftAssociative then Associativity.Left else Associativity.Right static member New(str, p, assoc) = { diff --git a/src/QsCompiler/TextProcessor/SyntaxBuilder.fs b/src/QsCompiler/TextProcessor/SyntaxBuilder.fs index 024f1495c9..a83e54f3e7 100644 --- a/src/QsCompiler/TextProcessor/SyntaxBuilder.fs +++ b/src/QsCompiler/TextProcessor/SyntaxBuilder.fs @@ -59,11 +59,16 @@ let private wordContainedIn (strings: ImmutableHashSet<_>) = term (keywordLike >>= inStrings) |>> snd /// parses any QsFragmentHeader and return unit -let internal qsFragmentHeader = previousCharSatisfiesNot isLetter >>. wordContainedIn Keywords.FragmentHeaders +let internal qsFragmentHeader = + previousCharSatisfiesNot isLetter >>. wordContainedIn Keywords.FragmentHeaders + /// parses any QsLanguageKeyword and return unit -let internal qsLanguageKeyword = previousCharSatisfiesNot isLetter >>. wordContainedIn Keywords.LanguageKeywords +let internal qsLanguageKeyword = + previousCharSatisfiesNot isLetter >>. wordContainedIn Keywords.LanguageKeywords + /// parses any QsReservedKeyword and return unit -let internal qsReservedKeyword = previousCharSatisfiesNot isLetter >>. wordContainedIn Keywords.ReservedKeywords +let internal qsReservedKeyword = + previousCharSatisfiesNot isLetter >>. wordContainedIn Keywords.ReservedKeywords /// adds the given diagnostic to the user state let internal pushDiagnostic newDiagnostic = @@ -151,8 +156,11 @@ let internal optTupleBrackets core = /// Fails without consuming input it the parsing fails. /// IMPORTANT: This parser does does *not* handle whitespace and needs to be wrapped into a term parser for proper processing of all whitespace. let private bracketDefinedContent core (lbracket, rbracket) = - let nextRbracket = attempt (skipPiecesUntil stringContent (lbracket <|> rbracket) .>> followedBy rbracket) - let nextLbracket = attempt (skipPiecesUntil stringContent (lbracket <|> rbracket) .>> followedBy lbracket) + let nextRbracket = + attempt (skipPiecesUntil stringContent (lbracket <|> rbracket) .>> followedBy rbracket) + + let nextLbracket = + attempt (skipPiecesUntil stringContent (lbracket <|> rbracket) .>> followedBy lbracket) let rec findMatching stream = let recur = nextLbracket >>. bracket lbracket >>. findMatching .>> bracket rbracket @@ -467,7 +475,7 @@ let internal asQualifiedSymbol ((path, sym), range: Range) = match names |> List.choose id with | [ sym ] -> (Symbol sym, range) |> QsSymbol.New | parts -> - let (ns, sym) = (String.concat "." parts.[0..parts.Length - 2]), parts.[parts.Length - 1] + let (ns, sym) = (String.concat "." parts.[0 .. parts.Length - 2]), parts.[parts.Length - 1] (QualifiedSymbol(ns, sym), range) |> QsSymbol.New /// Handles permissive parsing of a qualified symbol: @@ -515,24 +523,22 @@ 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) diff --git a/src/QsFmt/App.Tests/ProjectTests.fs b/src/QsFmt/App.Tests/ProjectTests.fs index d42d3678c4..59c9865b2e 100644 --- a/src/QsFmt/App.Tests/ProjectTests.fs +++ b/src/QsFmt/App.Tests/ProjectTests.fs @@ -37,7 +37,9 @@ let SimpleApplication () = let SimpleLibrary () = DesignTimeBuild.assemblyLoadContextSetup () - let files, version = DesignTimeBuild.getSourceFiles "Examples\TestProjects\SimpleLibrary\QSharpLibrary1.csproj" + let files, version = + DesignTimeBuild.getSourceFiles "Examples\TestProjects\SimpleLibrary\QSharpLibrary1.csproj" + let files = files |> List.map Path.GetFullPath let expectedFiles = diff --git a/src/QsFmt/App.Tests/Tests.fs b/src/QsFmt/App.Tests/Tests.fs index e1a78d0b71..ee9c916c54 100644 --- a/src/QsFmt/App.Tests/Tests.fs +++ b/src/QsFmt/App.Tests/Tests.fs @@ -73,7 +73,7 @@ let private updateAndFormatOutput files = + Environment.NewLine let private makeTestFile (path: string) = - let name = path.[(path.LastIndexOf "\\") + 1..(path.LastIndexOf ".qs") - 1] + let name = path.[(path.LastIndexOf "\\") + 1 .. (path.LastIndexOf ".qs") - 1] { Path = path diff --git a/src/QsFmt/App/CommandLineArguments.fs b/src/QsFmt/App/CommandLineArguments.fs index 3310e9ade0..3144dc7d14 100644 --- a/src/QsFmt/App/CommandLineArguments.fs +++ b/src/QsFmt/App/CommandLineArguments.fs @@ -46,12 +46,12 @@ type InputKind = | Project type internal IArguments = - abstract member Backup : bool - abstract member Recurse : bool - abstract member QdkVersion : string - abstract member InputFiles : seq - abstract member ProjectFile : string - abstract member CommandKind : CommandKind + abstract member Backup: bool + abstract member Recurse: bool + abstract member QdkVersion: string + abstract member InputFiles: seq + abstract member ProjectFile: string + abstract member CommandKind: CommandKind [ let getItemsByType (project: ProjectInstance) (itemType: string) = project.Items - |> Seq.where - (fun item -> - item.ItemType.Equals(itemType, StringComparison.OrdinalIgnoreCase) - && not (isNull item.EvaluatedInclude)) + |> Seq.where (fun item -> + item.ItemType.Equals(itemType, StringComparison.OrdinalIgnoreCase) + && not (isNull item.EvaluatedInclude)) |> Seq.map (fun item -> Path.Combine(project.Directory, item.EvaluatedInclude)) let getSourceFiles (projectFile: string) = diff --git a/src/QsFmt/App/DesignTimeBuild.fsi b/src/QsFmt/App/DesignTimeBuild.fsi index cbd80d4ddd..f96da5c487 100644 --- a/src/QsFmt/App/DesignTimeBuild.fsi +++ b/src/QsFmt/App/DesignTimeBuild.fsi @@ -6,7 +6,7 @@ module internal Microsoft.Quantum.QsFmt.App.DesignTimeBuild /// Given a path to a project file, returns the list of files associated /// to the project and the Quantum SDK version. /// Errors if given a file that is not a project file using Microsoft.Quantum.Sdk. -val getSourceFiles : string -> string list * string +val getSourceFiles: string -> string list * string /// Initializes the assembly load context needed for building project files. -val assemblyLoadContextSetup : Unit -> Unit +val assemblyLoadContextSetup: Unit -> Unit diff --git a/src/QsFmt/App/Program.fs b/src/QsFmt/App/Program.fs index c88caec328..f86d2541fc 100644 --- a/src/QsFmt/App/Program.fs +++ b/src/QsFmt/App/Program.fs @@ -49,14 +49,13 @@ let runCommand (commandWithOptions: CommandWithOptions) inputs = |> Result.map (fun isUpdated -> if isUpdated then filesUpdated <- filesUpdated.Add input) | Format -> Formatter.performFormat input commandWithOptions.QSharpVersion source - |> Result.map - (fun isFormatted -> if isFormatted then filesFormatted <- filesFormatted.Add input) + |> Result.map (fun isFormatted -> + if isFormatted then filesFormatted <- filesFormatted.Add input) | UpdateAndFormat -> Formatter.performUpdateAndFormat input commandWithOptions.QSharpVersion source - |> Result.map - (fun (isUpdated, isFormatted) -> - if isUpdated then filesUpdated <- filesUpdated.Add input - if isFormatted then filesFormatted <- filesFormatted.Add input) + |> Result.map (fun (isUpdated, isFormatted) -> + if isUpdated then filesUpdated <- filesUpdated.Add input + if isFormatted then filesFormatted <- filesFormatted.Add input) match result with | Ok _ -> { RunResult.Default with FilesProcessed = 1 } diff --git a/src/QsFmt/App/Program.fsi b/src/QsFmt/App/Program.fsi index ce2ce008e5..fa48486b9c 100644 --- a/src/QsFmt/App/Program.fsi +++ b/src/QsFmt/App/Program.fsi @@ -6,4 +6,4 @@ module Microsoft.Quantum.QsFmt.App.Program /// Runs the Q# formatter. [] -val main : string [] -> int +val main: string [] -> int diff --git a/src/QsFmt/App/Telemetry.fsi b/src/QsFmt/App/Telemetry.fsi index 15b6bf425a..d67209c29b 100644 --- a/src/QsFmt/App/Telemetry.fsi +++ b/src/QsFmt/App/Telemetry.fsi @@ -49,12 +49,12 @@ type ExecutionCompleted = ExitCode: ExitCode } /// Initializes the telemetry manager. This is required before logging telemetry. -val internal initializeTelemetry : string [] -> IDisposable +val internal initializeTelemetry: string [] -> IDisposable /// Logs the ExecutionCompleted telemetry event. -val internal logExecutionCompleted : +val internal logExecutionCompleted: Result, Exception> -> Result -> DateTime -> TimeSpan -> - unit + unit diff --git a/src/QsFmt/Formatter.Tests/Discoverer.fs b/src/QsFmt/Formatter.Tests/Discoverer.fs index dae6e9a016..ffb2cb4636 100644 --- a/src/QsFmt/Formatter.Tests/Discoverer.fs +++ b/src/QsFmt/Formatter.Tests/Discoverer.fs @@ -100,47 +100,44 @@ 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 : seq = + let private examples: seq = 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 - Kind = attribute.Kind - }: 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 + Kind = attribute.Kind + }: 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 for format examples as theory data. diff --git a/src/QsFmt/Formatter.Tests/Errors.fs b/src/QsFmt/Formatter.Tests/Errors.fs index 310ddc75c9..5ccaed0b28 100644 --- a/src/QsFmt/Formatter.Tests/Errors.fs +++ b/src/QsFmt/Formatter.Tests/Errors.fs @@ -9,7 +9,8 @@ open Xunit [] let ``Returns error result with syntax errors`` () = - let result = Formatter.format None "namespace Foo { invalid syntax; }" |> Result.mapError (List.map string) + let result = + Formatter.format None "namespace Foo { invalid syntax; }" |> Result.mapError (List.map string) let error = "Line 1, Character 16: mismatched input 'invalid' expecting {'function', 'internal', 'newtype', 'open', 'operation', '@', '}'}" diff --git a/src/QsFmt/Formatter/Formatter.fs b/src/QsFmt/Formatter/Formatter.fs index b1eb419825..9013864f3c 100644 --- a/src/QsFmt/Formatter/Formatter.fs +++ b/src/QsFmt/Formatter/Formatter.fs @@ -75,13 +75,12 @@ let internal formatDocument = versionToFormatRules let performFormat fileName qsharp_version source = parse source - |> Result.map - (fun ast -> - checkParsed source ast |> ignore - let formatted = formatDocument qsharp_version ast |> printer.Document - let isFormatted = formatted <> source - if isFormatted then File.WriteAllText(fileName, formatted) - isFormatted) + |> Result.map (fun ast -> + checkParsed source ast |> ignore + let formatted = formatDocument qsharp_version ast |> printer.Document + let isFormatted = formatted <> source + if isFormatted then File.WriteAllText(fileName, formatted) + isFormatted) let internal versionToUpdateRules (version: Version option) = let rules = @@ -117,26 +116,24 @@ let internal updateDocument fileName qsharp_version document = let performUpdate fileName qsharp_version source = parse source - |> Result.map - (fun ast -> - checkParsed source ast |> ignore - let updated = updateDocument fileName qsharp_version ast |> printer.Document - let isUpdated = updated <> source - if isUpdated then File.WriteAllText(fileName, updated) - isUpdated) + |> Result.map (fun ast -> + checkParsed source ast |> ignore + let updated = updateDocument fileName qsharp_version ast |> printer.Document + let isUpdated = updated <> source + if isUpdated then File.WriteAllText(fileName, updated) + isUpdated) let performUpdateAndFormat fileName qsharp_version source = parse source - |> Result.map - (fun ast -> - checkParsed source ast |> ignore - let updatedAST = updateDocument fileName qsharp_version ast - let updated = printer.Document updatedAST - let isUpdated = updated <> source - let formatted = formatDocument qsharp_version updatedAST |> printer.Document - let isFormatted = formatted <> updated - if isUpdated || isFormatted then File.WriteAllText(fileName, formatted) - (isUpdated, isFormatted)) + |> Result.map (fun ast -> + checkParsed source ast |> ignore + let updatedAST = updateDocument fileName qsharp_version ast + let updated = printer.Document updatedAST + let isUpdated = updated <> source + let formatted = formatDocument qsharp_version updatedAST |> printer.Document + let isFormatted = formatted <> updated + if isUpdated || isFormatted then File.WriteAllText(fileName, formatted) + (isUpdated, isFormatted)) [] let update fileName qsharp_version source = diff --git a/src/QsFmt/Formatter/ParseTree/Expression.fsi b/src/QsFmt/Formatter/ParseTree/Expression.fsi index 48a6262a86..f240bde307 100644 --- a/src/QsFmt/Formatter/ParseTree/Expression.fsi +++ b/src/QsFmt/Formatter/ParseTree/Expression.fsi @@ -15,7 +15,7 @@ type internal InterpStringContentVisitor = /// /// Creates a new with the list of . /// - new: tokens:IToken ImmutableArray -> InterpStringContentVisitor + new: tokens: IToken ImmutableArray -> InterpStringContentVisitor inherit InterpStringContent QSharpParserBaseVisitor @@ -26,6 +26,6 @@ type internal ExpressionVisitor = /// /// Creates a new with the list of . /// - new: tokens:IToken ImmutableArray -> ExpressionVisitor + new: tokens: IToken ImmutableArray -> ExpressionVisitor inherit Expression QSharpParserBaseVisitor diff --git a/src/QsFmt/Formatter/ParseTree/Namespace.fsi b/src/QsFmt/Formatter/ParseTree/Namespace.fsi index 545c1f6470..55ec030764 100644 --- a/src/QsFmt/Formatter/ParseTree/Namespace.fsi +++ b/src/QsFmt/Formatter/ParseTree/Namespace.fsi @@ -16,4 +16,4 @@ module internal Namespace = /// Creates a syntax tree node from the parse tree /// node and the list of . /// - val toDocument: tokens:IToken ImmutableArray -> context:QSharpParser.DocumentContext -> Document + val toDocument: tokens: IToken ImmutableArray -> context: QSharpParser.DocumentContext -> Document diff --git a/src/QsFmt/Formatter/ParseTree/Node.fsi b/src/QsFmt/Formatter/ParseTree/Node.fsi index 69b6ecdbd8..e23ddfd12a 100644 --- a/src/QsFmt/Formatter/ParseTree/Node.fsi +++ b/src/QsFmt/Formatter/ParseTree/Node.fsi @@ -13,21 +13,21 @@ open Microsoft.Quantum.QsFmt.Formatter.SyntaxTree /// The tokens that occur before the token with the given in /// . /// -val prefix: tokens:IToken ImmutableArray -> index:int -> Trivia list +val prefix: tokens: IToken ImmutableArray -> index: int -> Trivia list /// /// Creates a syntax tree node from the given parse tree . /// -val toTerminal: tokens:IToken ImmutableArray -> terminal:IToken -> Terminal +val toTerminal: tokens: IToken ImmutableArray -> terminal: IToken -> Terminal /// /// Creates a syntax tree node from the given parse tree that represents /// unknown or not yet supported syntax. /// -val toUnknown: tokens:IToken ImmutableArray -> node:IRuleNode -> Terminal +val toUnknown: tokens: IToken ImmutableArray -> node: IRuleNode -> Terminal /// /// Creates a list of sequence items by pairing each item in with its respective comma in /// . /// -val tupleItems: items:'a seq -> commas:Terminal seq -> 'a SequenceItem list +val tupleItems: items: 'a seq -> commas: Terminal seq -> 'a SequenceItem list diff --git a/src/QsFmt/Formatter/ParseTree/Statement.fsi b/src/QsFmt/Formatter/ParseTree/Statement.fsi index 66dbbb5ebf..958c02a219 100644 --- a/src/QsFmt/Formatter/ParseTree/Statement.fsi +++ b/src/QsFmt/Formatter/ParseTree/Statement.fsi @@ -15,6 +15,6 @@ type internal StatementVisitor = /// /// Creates a new with the list of . /// - new: tokens:IToken ImmutableArray -> StatementVisitor + new: tokens: IToken ImmutableArray -> StatementVisitor inherit Statement QSharpParserBaseVisitor diff --git a/src/QsFmt/Formatter/ParseTree/Type.fsi b/src/QsFmt/Formatter/ParseTree/Type.fsi index 574ac0688f..feafe9c175 100644 --- a/src/QsFmt/Formatter/ParseTree/Type.fsi +++ b/src/QsFmt/Formatter/ParseTree/Type.fsi @@ -15,7 +15,7 @@ type internal CharacteristicVisitor = /// /// Creates a new with the list of . /// - new: tokens:IToken ImmutableArray -> CharacteristicVisitor + new: tokens: IToken ImmutableArray -> CharacteristicVisitor inherit Characteristic QSharpParserBaseVisitor @@ -26,7 +26,7 @@ type internal TypeVisitor = /// /// Creates a new with the list of . /// - new: tokens:IToken ImmutableArray -> TypeVisitor + new: tokens: IToken ImmutableArray -> TypeVisitor inherit Type QSharpParserBaseVisitor @@ -38,4 +38,5 @@ module internal Type = /// Creates a syntax tree node from the parse tree /// node and the list of . /// - val toCharacteristicSection: tokens:IToken ImmutableArray -> context:QSharpParser.CharacteristicsContext -> CharacteristicSection + val toCharacteristicSection: + tokens: IToken ImmutableArray -> context: QSharpParser.CharacteristicsContext -> CharacteristicSection diff --git a/src/QsFmt/Formatter/Rules.fs b/src/QsFmt/Formatter/Rules.fs index 90e68b23dd..ad39339f50 100644 --- a/src/QsFmt/Formatter/Rules.fs +++ b/src/QsFmt/Formatter/Rules.fs @@ -63,16 +63,16 @@ let indentTerminal level = let indentation = { new Rewriter<_>() with override _.Namespace(level, ns) = - { base.Namespace(level, ns) with NamespaceKeyword = indentTerminal level ns.NamespaceKeyword } + { ``base``.Namespace(level, ns) with NamespaceKeyword = indentTerminal level ns.NamespaceKeyword } override _.NamespaceItem(level, item) = - base.NamespaceItem(level, item) |> NamespaceItem.mapPrefix (indentPrefix level) + ``base``.NamespaceItem(level, item) |> NamespaceItem.mapPrefix (indentPrefix level) override _.Statement(level, statement) = - base.Statement(level, statement) |> Statement.mapPrefix (indentPrefix level) + ``base``.Statement(level, statement) |> Statement.mapPrefix (indentPrefix level) override _.Block(level, mapper, block) = - { base.Block(level + 1, mapper, block) with CloseBrace = indentTerminal level block.CloseBrace } + { ``base``.Block(level + 1, mapper, block) with CloseBrace = indentTerminal level block.CloseBrace } } /// @@ -84,17 +84,17 @@ let ensureNewLine prefix = let newLines = { new Rewriter<_>() with override _.NamespaceItem((), item) = - base.NamespaceItem((), item) |> NamespaceItem.mapPrefix ensureNewLine + ``base``.NamespaceItem((), item) |> NamespaceItem.mapPrefix ensureNewLine override _.Statement((), statement) = - let statement = base.Statement((), statement) + let statement = ``base``.Statement((), statement) match statement with | ElseStatement _ -> statement | _ -> Statement.mapPrefix ensureNewLine statement override _.Block((), mapper, block) = - let block = base.Block((), mapper, block) + let block = ``base``.Block((), mapper, block) if List.isEmpty block.Items then block @@ -149,7 +149,7 @@ let unitUpdate = { Prefix = tuple.OpenParen.Prefix; Text = "Unit" } |> Type.BuiltIn | _ -> typ - base.Type((), updated) + ``base``.Type((), updated) } let forParensUpdate = @@ -244,30 +244,26 @@ let arraySyntaxUpdate = | Type.Tuple tuple -> let items = tuple.Items - |> List.mapi - (fun i item -> - match item.Item with - | Some t -> - // When Item has a value, map the Type to and Expression, if valid - match getDefaultValue t with - | Some value -> - // If the Type was mapped to an Expression successfully, create an Expression-SequenceItem - { - Item = - // For all items after the first, we need to inject a space before each item - // For example: (0,0) goes to (0, 0) - if i > 0 then - value |> Expression.mapPrefix ((@) space) |> Some - else - value |> Some - Comma = item.Comma - } - |> Some - | None -> None - | None -> - // A Type-SequenceItem object with Item=None becomes an Expression-SequenceItem with Item=None - // ToDo: Don't know what the use-case is for an Item of None - { Item = None; Comma = item.Comma } |> Some) + |> List.mapi (fun i item -> + match item.Item with + | Some t -> + // When Item has a value, map the Type to and Expression, if valid + match getDefaultValue t with + | Some value -> + // If the Type was mapped to an Expression successfully, create an Expression-SequenceItem + { + Item = + // For all items after the first, we need to inject a space before each item + // For example: (0,0) goes to (0, 0) + if i > 0 then value |> Expression.mapPrefix ((@) space) |> Some else value |> Some + Comma = item.Comma + } + |> Some + | None -> None + | None -> + // A Type-SequenceItem object with Item=None becomes an Expression-SequenceItem with Item=None + // ToDo: Don't know what the use-case is for an Item of None + { Item = None; Comma = item.Comma } |> Some) // If any of the items are None (which means invalid for update) return None if items |> List.forall Option.isSome then { @@ -282,18 +278,17 @@ let arraySyntaxUpdate = | Type.Array arrayType -> arrayType.ItemType |> getDefaultValue - |> Option.map - (fun value -> - { - OpenBracket = { Prefix = []; Text = arrayType.OpenBracket.Text } - Value = value - Comma = { Prefix = []; Text = "," } - Size = { Prefix = space; Text = "size" } - Equals = { Prefix = space; Text = "=" } - Length = { Prefix = space; Text = "0" } |> Literal - CloseBracket = { Prefix = []; Text = arrayType.CloseBracket.Text } - } - |> NewSizedArray) + |> Option.map (fun value -> + { + OpenBracket = { Prefix = []; Text = arrayType.OpenBracket.Text } + Value = value + Comma = { Prefix = []; Text = "," } + Size = { Prefix = space; Text = "size" } + Equals = { Prefix = space; Text = "=" } + Length = { Prefix = space; Text = "0" } |> Literal + CloseBracket = { Prefix = []; Text = arrayType.CloseBracket.Text } + } + |> NewSizedArray) | _ -> None { new Rewriter<_>() with @@ -319,7 +314,7 @@ let arraySyntaxUpdate = } |> NewSizedArray | None -> newArray |> NewArray // If the conversion is invalid, just leave the node as-is - | _ -> base.Expression((), expression) + | _ -> ``base``.Expression((), expression) } let checkArraySyntax fileName document = @@ -414,5 +409,5 @@ let booleanOperatorUpdate = |> InfixOperator | _ -> expression - base.Expression((), updated) + ``base``.Expression((), updated) } diff --git a/src/QsFmt/Formatter/Rules.fsi b/src/QsFmt/Formatter/Rules.fsi index c260c5b15b..f1dfab69b2 100644 --- a/src/QsFmt/Formatter/Rules.fsi +++ b/src/QsFmt/Formatter/Rules.fsi @@ -24,7 +24,7 @@ val qubitBindingUpdate: unit Rewriter /// Replaces `()` with `Unit` when referencing the Unit type. /// Will not replace `()` when referencing the Unit value literal. -val unitUpdate : unit Rewriter +val unitUpdate: unit Rewriter /// Updates for-loops to remove deprecated parentheses. val forParensUpdate: unit Rewriter @@ -40,4 +40,4 @@ val checkArraySyntax: string -> Document -> string list /// Replaces deprecated use of boolean operators `&&`, `||`, and `!` with their keyword /// equivalence `and`, `or`, and `not` respectively. -val booleanOperatorUpdate : unit Rewriter +val booleanOperatorUpdate: unit Rewriter diff --git a/src/QsFmt/Formatter/SyntaxTree/Expression.fsi b/src/QsFmt/Formatter/SyntaxTree/Expression.fsi index d6a07fbc32..b1b1bd67e6 100644 --- a/src/QsFmt/Formatter/SyntaxTree/Expression.fsi +++ b/src/QsFmt/Formatter/SyntaxTree/Expression.fsi @@ -8,29 +8,27 @@ namespace Microsoft.Quantum.QsFmt.Formatter.SyntaxTree /// to call the callable. type internal Identifier = { - /// The name of the identifier - Name: Terminal + /// The name of the identifier + Name: Terminal - /// Optional type arguments - TypeArgs: Type Tuple Option - } + /// Optional type arguments + TypeArgs: Type Tuple Option } /// An escaped expression in an interpolated string type internal InterpStringExpression = { - /// - /// The { symbol. - /// - OpenBrace: Terminal + /// + /// The { symbol. + /// + OpenBrace: Terminal - /// The escaped expression - Expression: Expression + /// The escaped expression + Expression: Expression - /// - /// The } symbol. - /// - CloseBrace: Terminal - } + /// + /// The } symbol. + /// + CloseBrace: Terminal } and internal InterpStringContent = /// A literal. @@ -42,166 +40,158 @@ and internal InterpStringContent = /// An interpolated string and internal InterpString = { - /// - /// The " symbol. - /// - OpenQuote: Terminal + /// + /// The " symbol. + /// + OpenQuote: Terminal - /// The content of the interpolated string - Content: InterpStringContent list + /// The content of the interpolated string + Content: InterpStringContent list - /// - /// The " symbol. - /// - CloseQuote: Terminal - } + /// + /// The " symbol. + /// + CloseQuote: Terminal } /// A new array expression. and internal NewArray = { - /// The `new` keyword. - New: Terminal + /// The `new` keyword. + New: Terminal - /// The type of the created array. - ItemType: Type + /// The type of the created array. + ItemType: Type - /// - /// The [ symbol. - /// - OpenBracket: Terminal + /// + /// The [ symbol. + /// + OpenBracket: Terminal - /// The length of the created array. - Length: Expression + /// The length of the created array. + Length: Expression - /// - /// The ] symbol. - /// - CloseBracket: Terminal - } + /// + /// The ] symbol. + /// + CloseBracket: Terminal } /// A new array expression with a size. and internal NewSizedArray = { - /// - /// The [ symbol. - /// - OpenBracket: Terminal - - // The value at each index of the array. - Value: Expression - - /// - /// The , symbol. - /// - Comma: Terminal - - /// - /// The size keyword. - /// - Size: Terminal - - /// - /// The = symbol. - /// - Equals: Terminal - - /// The length of the created array. - Length: Expression - - /// - /// The ] symbol. - /// - CloseBracket: Terminal - } + /// + /// The [ symbol. + /// + OpenBracket: Terminal + + // The value at each index of the array. + Value: Expression + + /// + /// The , symbol. + /// + Comma: Terminal + + /// + /// The size keyword. + /// + Size: Terminal + + /// + /// The = symbol. + /// + Equals: Terminal + + /// The length of the created array. + Length: Expression + + /// + /// The ] symbol. + /// + CloseBracket: Terminal } /// A named-item-access expression. and internal NamedItemAccess = { - /// The accessing object - Record: Expression + /// The accessing object + Record: Expression - /// - /// The :: symbol. - /// - DoubleColon: Terminal + /// + /// The :: symbol. + /// + DoubleColon: Terminal - /// The accessed item name - Name: Terminal - } + /// The accessed item name + Name: Terminal } /// An array-item-access expression. and internal ArrayAccess = { - /// The array - Array: Expression + /// The array + Array: Expression - /// - /// The [ symbol. - /// - OpenBracket: Terminal + /// + /// The [ symbol. + /// + OpenBracket: Terminal - /// The index of the accessed item. - Index: Expression + /// The index of the accessed item. + Index: Expression - /// - /// The ] symbol. - /// - CloseBracket: Terminal - } + /// + /// The ] symbol. + /// + CloseBracket: Terminal } /// A callable-call expression. and internal Call = { - /// The callable being called. - Callable: Expression + /// The callable being called. + Callable: Expression - /// The argument list of the callable call. - Arguments: Expression Tuple - } + /// The argument list of the callable call. + Arguments: Expression Tuple } /// A conditional expression. and internal Conditional = { - /// The condition. - Condition: Expression + /// The condition. + Condition: Expression - /// - /// The ? symbol. - /// - Question: Terminal + /// + /// The ? symbol. + /// + Question: Terminal - /// The expression value if the condition is true. - IfTrue: Expression + /// The expression value if the condition is true. + IfTrue: Expression - /// - /// The | symbol. - /// - Pipe: Terminal + /// + /// The | symbol. + /// + Pipe: Terminal - /// The expression value if the condition is false. - IfFalse: Expression - } + /// The expression value if the condition is false. + IfFalse: Expression } /// A copy-and-update expression. and internal Update = { - /// The record to update. - Record: Expression + /// The record to update. + Record: Expression - /// - /// The w/ symbol. - /// - With: Terminal + /// + /// The w/ symbol. + /// + With: Terminal - /// The item to update. - Item: Expression + /// The item to update. + Item: Expression - /// The left arrow symbol. - Arrow: Terminal + /// The left arrow symbol. + Arrow: Terminal - /// The value to assign to the item. - Value: Expression - } + /// The value to assign to the item. + Value: Expression } /// An expression. and internal Expression = @@ -260,4 +250,4 @@ module internal Expression = /// /// Maps an expression by applying to its leftmost terminal's trivia prefix. /// - val mapPrefix: mapper:(Trivia list -> Trivia list) -> Expression -> Expression + val mapPrefix: mapper: (Trivia list -> Trivia list) -> Expression -> Expression diff --git a/src/QsFmt/Formatter/SyntaxTree/Namespace.fsi b/src/QsFmt/Formatter/SyntaxTree/Namespace.fsi index 81c262231f..8a2e6e5eaf 100644 --- a/src/QsFmt/Formatter/SyntaxTree/Namespace.fsi +++ b/src/QsFmt/Formatter/SyntaxTree/Namespace.fsi @@ -6,25 +6,23 @@ namespace Microsoft.Quantum.QsFmt.Formatter.SyntaxTree /// An attribute. type internal Attribute = { - /// The at symbol prefix. - At: Terminal + /// The at symbol prefix. + At: Terminal - /// The attribute expression. - Expression: Expression - } + /// The attribute expression. + Expression: Expression } /// A type parameter binding sequence. type internal TypeParameterBinding = { - /// The opening angle bracket. - OpenBracket: Terminal + /// The opening angle bracket. + OpenBracket: Terminal - /// The type parameters. - Parameters: Terminal SequenceItem list + /// The type parameters. + Parameters: Terminal SequenceItem list - /// The closing angle bracket. - CloseBracket: Terminal - } + /// The closing angle bracket. + CloseBracket: Terminal } /// A specialization generator. type internal SpecializationGenerator = @@ -37,35 +35,33 @@ type internal SpecializationGenerator = /// A specialization. type internal Specialization = { - /// The names of the specialization. - Names: Terminal list + /// The names of the specialization. + Names: Terminal list - /// The specialization generator. - Generator: SpecializationGenerator - } + /// The specialization generator. + Generator: SpecializationGenerator } /// An open directive type internal OpenDirective = { - /// - /// The open keyword. - /// - OpenKeyword: Terminal + /// + /// The open keyword. + /// + OpenKeyword: Terminal - /// The name of the opened namespace. - OpenName: Terminal + /// The name of the opened namespace. + OpenName: Terminal - /// - /// The optional as keyword. - /// - AsKeyword: Terminal option + /// + /// The optional as keyword. + /// + AsKeyword: Terminal option - /// The alias name of the opened namespace. - AsName: Terminal option + /// The alias name of the opened namespace. + AsName: Terminal option - /// The semicolon. - Semicolon: Terminal - } + /// The semicolon. + Semicolon: Terminal } /// The underlying type of a newly defined type. type internal UnderlyingType = @@ -86,31 +82,30 @@ and internal TypeTupleItem = /// A type declaration type internal TypeDeclaration = { - /// The attributes attached to the type declaration. - Attributes: Attribute list + /// The attributes attached to the type declaration. + Attributes: Attribute list - /// The access modifier for the callable. - Access: Terminal option + /// The access modifier for the callable. + Access: Terminal option - /// - /// The newtype keyword. - /// - NewtypeKeyword: Terminal + /// + /// The newtype keyword. + /// + NewtypeKeyword: Terminal - /// The name of the declared type. - DeclaredType: Terminal + /// The name of the declared type. + DeclaredType: Terminal - /// - /// The = symbol. - /// - Equals: Terminal + /// + /// The = symbol. + /// + Equals: Terminal - /// The underlying type. - UnderlyingType: UnderlyingType + /// The underlying type. + UnderlyingType: UnderlyingType - /// The semicolon. - Semicolon: Terminal - } + /// The semicolon. + Semicolon: Terminal } /// The body of a callable declaration. type internal CallableBody = @@ -124,35 +119,34 @@ type internal CallableBody = // TODO: Add specialization generators. type internal CallableDeclaration = { - /// The attributes attached to the callable. - Attributes: Attribute list + /// The attributes attached to the callable. + Attributes: Attribute list - /// The access modifier for the callable. - Access: Terminal option + /// The access modifier for the callable. + Access: Terminal option - /// - /// The declaration keyword (either function or operation). - /// - CallableKeyword: Terminal + /// + /// The declaration keyword (either function or operation). + /// + CallableKeyword: Terminal - /// The name of the callable. - Name: Terminal + /// The name of the callable. + Name: Terminal - /// The type parameters of the callable. - TypeParameters: TypeParameterBinding option + /// The type parameters of the callable. + TypeParameters: TypeParameterBinding option - /// The parameters of the callable. - Parameters: ParameterBinding + /// The parameters of the callable. + Parameters: ParameterBinding - /// The return type of the callable. - ReturnType: TypeAnnotation + /// The return type of the callable. + ReturnType: TypeAnnotation - /// The characteristic section of the callable. - CharacteristicSection: CharacteristicSection option + /// The characteristic section of the callable. + CharacteristicSection: CharacteristicSection option - /// The body of the callable. - Body: CallableBody - } + /// The body of the callable. + Body: CallableBody } /// An item in a namespace. type internal NamespaceItem = @@ -172,29 +166,27 @@ module internal NamespaceItem = /// /// Maps a namespace item by applying to its leftmost terminal's trivia prefix. /// - val mapPrefix: mapper:(Trivia list -> Trivia list) -> NamespaceItem -> NamespaceItem + val mapPrefix: mapper: (Trivia list -> Trivia list) -> NamespaceItem -> NamespaceItem /// A namespace. type internal Namespace = { - /// - /// The namespace keyword. - /// - NamespaceKeyword: Terminal + /// + /// The namespace keyword. + /// + NamespaceKeyword: Terminal - /// The name of the namespace. - Name: Terminal + /// The name of the namespace. + Name: Terminal - /// The body of the namespace. - Block: NamespaceItem Block - } + /// The body of the namespace. + Block: NamespaceItem Block } /// A document representing a Q# file. type internal Document = { - /// The namespaces in the document. - Namespaces: Namespace list + /// The namespaces in the document. + Namespaces: Namespace list - /// The end-of-file symbol. - Eof: Terminal - } + /// The end-of-file symbol. + Eof: Terminal } diff --git a/src/QsFmt/Formatter/SyntaxTree/Node.fs b/src/QsFmt/Formatter/SyntaxTree/Node.fs index 2fbbfaff2e..d7ef79b476 100644 --- a/src/QsFmt/Formatter/SyntaxTree/Node.fs +++ b/src/QsFmt/Formatter/SyntaxTree/Node.fs @@ -48,7 +48,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/Node.fsi b/src/QsFmt/Formatter/SyntaxTree/Node.fsi index 44fb831225..67d4a1bffe 100644 --- a/src/QsFmt/Formatter/SyntaxTree/Node.fsi +++ b/src/QsFmt/Formatter/SyntaxTree/Node.fsi @@ -30,24 +30,24 @@ module internal Trivia = /// /// A node containing number of space characters. /// - val spaces : count: int -> Trivia + val spaces: count: int -> Trivia /// /// The new line node containing the default new line character for the current platform.. /// - val newLine : Trivia + val newLine: Trivia /// Determine whether a Trivia is a NewLine val isNewLine: Trivia -> bool /// Replaces each occurrence of more than one whitespace character in a row with a single space. - val collapseSpaces : (Trivia -> Trivia) + val collapseSpaces: (Trivia -> Trivia) /// /// Converts a string into a list of nodes. /// /// The string contains invalid trivia. - val ofString : string -> Trivia list + val ofString: string -> Trivia list /// A terminal symbol has no child nodes and represents a token in the source code. type internal Terminal = @@ -62,7 +62,7 @@ module internal Terminal = /// /// Maps by applying to its trivia prefix. /// - val mapPrefix : mapper: (Trivia list -> Trivia list) -> terminal: Terminal -> Terminal + val mapPrefix: mapper: (Trivia list -> Trivia list) -> terminal: Terminal -> Terminal /// An item in a comma-separated sequence. type internal 'a SequenceItem = @@ -89,7 +89,7 @@ module internal Tuple = /// /// Maps by applying to its leftmost terminal's trivia prefix. /// - val mapPrefix : mapper: (Trivia list -> Trivia list) -> tuple: 'a Tuple -> 'a Tuple + val mapPrefix: mapper: (Trivia list -> Trivia list) -> tuple: 'a Tuple -> 'a Tuple /// A prefix operator. The operator is in the front of the operand. type internal 'a PrefixOperator = @@ -137,4 +137,4 @@ module internal Block = /// /// Maps by applying to its leftmost terminal's trivia prefix. /// - val mapPrefix : mapper: (Trivia list -> Trivia list) -> block: 'a Block -> 'a Block + val mapPrefix: mapper: (Trivia list -> Trivia list) -> block: 'a Block -> 'a Block diff --git a/src/QsFmt/Formatter/SyntaxTree/Reducer.fs b/src/QsFmt/Formatter/SyntaxTree/Reducer.fs index 5c68438263..eb80442903 100644 --- a/src/QsFmt/Formatter/SyntaxTree/Reducer.fs +++ b/src/QsFmt/Formatter/SyntaxTree/Reducer.fs @@ -47,14 +47,14 @@ type internal 'result Reducer() as reducer = ] |> 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 = [ @@ -64,7 +64,7 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract NamespaceItem : item: NamespaceItem -> 'result + abstract NamespaceItem: item: NamespaceItem -> 'result default _.NamespaceItem item = match item with @@ -73,7 +73,7 @@ type internal 'result Reducer() as reducer = | CallableDeclaration callable -> reducer.CallableDeclaration callable | Unknown terminal -> reducer.Terminal terminal - abstract OpenDirective : directive: OpenDirective -> 'result + abstract OpenDirective: directive: OpenDirective -> 'result default _.OpenDirective directive = [ reducer.Terminal directive.OpenKeyword; reducer.Terminal directive.OpenName ] @@ -82,7 +82,7 @@ type internal 'result Reducer() as reducer = @ [ reducer.Terminal directive.Semicolon ] |> reduce - abstract TypeDeclaration : declaration: TypeDeclaration -> 'result + abstract TypeDeclaration: declaration: TypeDeclaration -> 'result default _.TypeDeclaration declaration = (declaration.Attributes |> List.map reducer.Attribute) @@ -96,26 +96,26 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract Attribute : attribute: Attribute -> 'result + abstract Attribute: attribute: Attribute -> 'result default _.Attribute attribute = [ reducer.Terminal attribute.At; reducer.Expression attribute.Expression ] |> reduce - abstract UnderlyingType : underlying: UnderlyingType -> 'result + abstract UnderlyingType: underlying: UnderlyingType -> 'result default _.UnderlyingType underlying = match underlying with | TypeDeclarationTuple tuple -> reducer.Tuple(reducer.TypeTupleItem, tuple) | Type _type -> reducer.Type _type - abstract TypeTupleItem : item: TypeTupleItem -> 'result + abstract TypeTupleItem: item: TypeTupleItem -> 'result default _.TypeTupleItem item = match item with | TypeBinding binding -> reducer.ParameterDeclaration binding | UnderlyingType underlying -> reducer.UnderlyingType underlying - abstract CallableDeclaration : callable: CallableDeclaration -> 'result + abstract CallableDeclaration: callable: CallableDeclaration -> 'result default _.CallableDeclaration callable = [ @@ -133,7 +133,7 @@ type internal 'result Reducer() as reducer = |> List.concat |> reduce - abstract TypeParameterBinding : binding: TypeParameterBinding -> 'result + abstract TypeParameterBinding: binding: TypeParameterBinding -> 'result default _.TypeParameterBinding binding = reducer.Terminal binding.OpenBracket @@ -141,7 +141,7 @@ type internal 'result Reducer() as reducer = @ [ reducer.Terminal binding.CloseBracket ] |> reduce - abstract Type : typ: Type -> 'result + abstract Type: typ: Type -> 'result default _.Type typ = match typ with @@ -154,12 +154,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 = [ @@ -169,7 +169,7 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract CallableType : callable: CallableType -> 'result + abstract CallableType: callable: CallableType -> 'result default _.CallableType callable = [ @@ -180,7 +180,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 = [ @@ -189,7 +189,7 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract CharacteristicGroup : group: CharacteristicGroup -> 'result + abstract CharacteristicGroup: group: CharacteristicGroup -> 'result default _.CharacteristicGroup group = [ @@ -199,7 +199,7 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract Characteristic : characteristic: Characteristic -> 'result + abstract Characteristic: characteristic: Characteristic -> 'result default _.Characteristic characteristic = match characteristic with @@ -208,21 +208,21 @@ type internal 'result Reducer() as reducer = | Group group -> reducer.CharacteristicGroup group | Characteristic.InfixOperator operator -> reducer.InfixOperator(reducer.Characteristic, operator) - abstract CallableBody : body: CallableBody -> 'result + abstract CallableBody: body: CallableBody -> 'result default _.CallableBody body = match body with | Statements statements -> reducer.Block(reducer.Statement, statements) | Specializations specializations -> reducer.Block(reducer.Specialization, specializations) - abstract Specialization : specialization: Specialization -> 'result + abstract Specialization: specialization: Specialization -> 'result default _.Specialization specialization = (specialization.Names |> List.map reducer.Terminal) @ [ reducer.SpecializationGenerator specialization.Generator ] |> reduce - abstract SpecializationGenerator : generator: SpecializationGenerator -> 'result + abstract SpecializationGenerator: generator: SpecializationGenerator -> 'result default _.SpecializationGenerator generator = match generator with @@ -232,7 +232,7 @@ type internal 'result Reducer() as reducer = @ [ reducer.Block(reducer.Statement, statements) ] |> reduce - abstract Statement : statement: Statement -> 'result + abstract Statement: statement: Statement -> 'result default _.Statement statement = match statement with @@ -256,32 +256,32 @@ type internal 'result Reducer() as reducer = | QubitDeclarationStatement decl -> reducer.QubitDeclarationStatement decl | Statement.Unknown terminal -> reducer.Terminal terminal - abstract ExpressionStatement : expr: ExpressionStatement -> 'result + abstract ExpressionStatement: expr: ExpressionStatement -> 'result default _.ExpressionStatement expr = [ reducer.Expression expr.Expression; reducer.Terminal expr.Semicolon ] |> reduce - abstract ReturnStatement : returns: SimpleStatement -> 'result + abstract ReturnStatement: returns: SimpleStatement -> 'result default _.ReturnStatement returns = defaultSimpleStatement returns - abstract FailStatement : fails: SimpleStatement -> 'result + abstract FailStatement: fails: SimpleStatement -> 'result default _.FailStatement fails = defaultSimpleStatement fails - abstract LetStatement : lets: BindingStatement -> 'result + abstract LetStatement: lets: BindingStatement -> 'result default _.LetStatement lets = defaultBindingStatement lets - abstract MutableStatement : mutables: BindingStatement -> 'result + abstract MutableStatement: mutables: BindingStatement -> 'result default _.MutableStatement mutables = defaultBindingStatement mutables - abstract SetStatement : sets: BindingStatement -> 'result + abstract SetStatement: sets: BindingStatement -> 'result default _.SetStatement sets = defaultBindingStatement sets - abstract UpdateStatement : updates: UpdateStatement -> 'result + abstract UpdateStatement: updates: UpdateStatement -> 'result default _.UpdateStatement updates = [ @@ -293,7 +293,7 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract UpdateWithStatement : withs: UpdateWithStatement -> 'result + abstract UpdateWithStatement: withs: UpdateWithStatement -> 'result default _.UpdateWithStatement withs = [ @@ -307,19 +307,19 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract IfStatement : ifs: ConditionalBlockStatement -> 'result + abstract IfStatement: ifs: ConditionalBlockStatement -> 'result default _.IfStatement ifs = defaultConditionalBlockStatement ifs - abstract ElifStatement : elifs: ConditionalBlockStatement -> 'result + abstract ElifStatement: elifs: ConditionalBlockStatement -> 'result default _.ElifStatement elifs = defaultConditionalBlockStatement elifs - abstract ElseStatement : elses: BlockStatement -> 'result + abstract ElseStatement: elses: BlockStatement -> 'result default _.ElseStatement elses = defaultBlockStatement elses - abstract ForStatement : loop: ForStatement -> 'result + abstract ForStatement: loop: ForStatement -> 'result default _.ForStatement loop = [ @@ -332,15 +332,15 @@ type internal 'result Reducer() as reducer = |> List.choose id |> reduce - abstract WhileStatement : whiles: ConditionalBlockStatement -> 'result + abstract WhileStatement: whiles: ConditionalBlockStatement -> 'result default _.WhileStatement whiles = defaultConditionalBlockStatement whiles - abstract RepeatStatement : repeats: BlockStatement -> 'result + abstract RepeatStatement: repeats: BlockStatement -> 'result default _.RepeatStatement repeats = defaultBlockStatement repeats - abstract UntilStatement : untils: UntilStatement -> 'result + abstract UntilStatement: untils: UntilStatement -> 'result default _.UntilStatement untils = [ @@ -352,19 +352,19 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract Fixup : fixup: BlockStatement -> 'result + abstract Fixup: fixup: BlockStatement -> 'result default _.Fixup fixup = defaultBlockStatement fixup - abstract WithinStatement : withins: BlockStatement -> 'result + abstract WithinStatement: withins: BlockStatement -> 'result default _.WithinStatement withins = defaultBlockStatement withins - abstract ApplyStatement : apply: BlockStatement -> 'result + abstract ApplyStatement: apply: BlockStatement -> 'result default _.ApplyStatement apply = defaultBlockStatement apply - abstract QubitDeclarationStatement : decl: QubitDeclarationStatement -> 'result + abstract QubitDeclarationStatement: decl: QubitDeclarationStatement -> 'result default _.QubitDeclarationStatement decl = [ @@ -379,26 +379,26 @@ type internal 'result Reducer() as reducer = |> List.choose id |> reduce - abstract ParameterBinding : binding: ParameterBinding -> 'result + abstract ParameterBinding: binding: ParameterBinding -> 'result default _.ParameterBinding binding = match binding with | ParameterDeclaration declaration -> reducer.ParameterDeclaration declaration | ParameterTuple tuple -> reducer.Tuple(reducer.ParameterBinding, tuple) - abstract ParameterDeclaration : declaration: ParameterDeclaration -> 'result + abstract ParameterDeclaration: declaration: ParameterDeclaration -> 'result default _.ParameterDeclaration declaration = [ reducer.Terminal declaration.Name; reducer.TypeAnnotation declaration.Type ] |> reduce - abstract SymbolBinding : symbol: SymbolBinding -> 'result + abstract SymbolBinding: symbol: SymbolBinding -> 'result default _.SymbolBinding symbol = match symbol with | SymbolDeclaration declaration -> reducer.Terminal declaration | SymbolTuple tuple -> reducer.Tuple(reducer.SymbolBinding, tuple) - abstract QubitBinding : binding: QubitBinding -> 'result + abstract QubitBinding: binding: QubitBinding -> 'result default _.QubitBinding binding = [ @@ -408,7 +408,7 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract ForBinding : binding: ForBinding -> 'result + abstract ForBinding: binding: ForBinding -> 'result default _.ForBinding binding = [ @@ -418,7 +418,7 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract QubitInitializer : initializer: QubitInitializer -> 'result + abstract QubitInitializer: initializer: QubitInitializer -> 'result default _.QubitInitializer initializer = match initializer with @@ -426,7 +426,7 @@ type internal 'result Reducer() as reducer = | QubitArray qubitArray -> reducer.QubitArray qubitArray | QubitTuple tuple -> reducer.Tuple(reducer.QubitInitializer, tuple) - abstract SingleQubit : newQubit: SingleQubit -> 'result + abstract SingleQubit: newQubit: SingleQubit -> 'result default _.SingleQubit newQubit = [ @@ -436,7 +436,7 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract QubitArray : newQubits: QubitArray -> 'result + abstract QubitArray: newQubits: QubitArray -> 'result default _.QubitArray newQubits = [ @@ -447,14 +447,14 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract InterpStringContent : interpStringContent: InterpStringContent -> 'result + abstract InterpStringContent: interpStringContent: InterpStringContent -> 'result default _.InterpStringContent interpStringContent = match interpStringContent with | Text text -> reducer.Terminal text | Expression interpStringExpression -> reducer.InterpStringExpression interpStringExpression - abstract InterpStringExpression : interpStringExpression: InterpStringExpression -> 'result + abstract InterpStringExpression: interpStringExpression: InterpStringExpression -> 'result default _.InterpStringExpression interpStringExpression = [ @@ -464,7 +464,7 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract Expression : expression: Expression -> 'result + abstract Expression: expression: Expression -> 'result default _.Expression expression = match expression with @@ -486,14 +486,14 @@ type internal 'result Reducer() as reducer = | Update update -> reducer.Update update | Expression.Unknown terminal -> reducer.Terminal terminal - abstract Identifier : identifier: Identifier -> 'result + abstract Identifier: identifier: Identifier -> 'result default _.Identifier identifier = reducer.Terminal identifier.Name :: (identifier.TypeArgs |> Option.map (curry reducer.Tuple reducer.Type) |> Option.toList) |> reduce - abstract InterpString : interpString: InterpString -> 'result + abstract InterpString: interpString: InterpString -> 'result default _.InterpString interpString = reducer.Terminal interpString.OpenQuote @@ -501,7 +501,7 @@ type internal 'result Reducer() as reducer = @ [ reducer.Terminal interpString.CloseQuote ] |> reduce - abstract NewArray : newArray: NewArray -> 'result + abstract NewArray: newArray: NewArray -> 'result default _.NewArray newArray = [ @@ -513,7 +513,7 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract NewSizedArray : newSizedArray: NewSizedArray -> 'result + abstract NewSizedArray: newSizedArray: NewSizedArray -> 'result default _.NewSizedArray newSizedArray = [ @@ -527,7 +527,7 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract NamedItemAccess : namedItemAccess: NamedItemAccess -> 'result + abstract NamedItemAccess: namedItemAccess: NamedItemAccess -> 'result default _.NamedItemAccess namedItemAccess = [ @@ -537,7 +537,7 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract ArrayAccess : arrayAccess: ArrayAccess -> 'result + abstract ArrayAccess: arrayAccess: ArrayAccess -> 'result default _.ArrayAccess arrayAccess = [ @@ -548,7 +548,7 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract Call : call: Call -> 'result + abstract Call: call: Call -> 'result default _.Call call = [ @@ -557,7 +557,7 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract Conditional : conditional: Conditional -> 'result + abstract Conditional: conditional: Conditional -> 'result default _.Conditional conditional = [ @@ -569,7 +569,7 @@ type internal 'result Reducer() as reducer = ] |> reduce - abstract Update : update: Update -> 'result + abstract Update: update: Update -> 'result default _.Update update = [ @@ -581,38 +581,38 @@ 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 PrefixOperator : mapper: ('a -> 'result) * operator: 'a PrefixOperator -> 'result + abstract PrefixOperator: mapper: ('a -> 'result) * operator: 'a PrefixOperator -> 'result default _.PrefixOperator(mapper, operator) = [ reducer.Terminal operator.PrefixOperator; mapper operator.Operand ] |> reduce - abstract PostfixOperator : mapper: ('a -> 'result) * operator: 'a PostfixOperator -> 'result + abstract PostfixOperator: mapper: ('a -> 'result) * operator: 'a PostfixOperator -> 'result default _.PostfixOperator(mapper, operator) = [ mapper operator.Operand; reducer.Terminal operator.PostfixOperator ] |> reduce - abstract InfixOperator : mapper: ('a -> 'result) * operator: 'a InfixOperator -> 'result + abstract InfixOperator: mapper: ('a -> 'result) * operator: 'a InfixOperator -> 'result default _.InfixOperator(mapper, operator) = [ @@ -622,4 +622,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/Reducer.fsi b/src/QsFmt/Formatter/SyntaxTree/Reducer.fsi index baba400698..4046367401 100644 --- a/src/QsFmt/Formatter/SyntaxTree/Reducer.fsi +++ b/src/QsFmt/Formatter/SyntaxTree/Reducer.fsi @@ -20,400 +20,400 @@ type internal 'result Reducer = /// /// Reduces a node. /// - abstract Document: document:Document -> 'result - default Document: document:Document -> 'result + abstract Document: document: Document -> 'result + default Document: document: Document -> 'result /// /// Reduces a node. /// - abstract Namespace: ns:Namespace -> 'result - default Namespace: ns:Namespace -> 'result + abstract Namespace: ns: Namespace -> 'result + default Namespace: ns: Namespace -> 'result /// /// Reduces a node. /// - abstract NamespaceItem: item:NamespaceItem -> 'result - default NamespaceItem: item:NamespaceItem -> 'result + abstract NamespaceItem: item: NamespaceItem -> 'result + default NamespaceItem: item: NamespaceItem -> 'result /// /// Reduces an node. /// - abstract OpenDirective: directive:OpenDirective -> 'result - default OpenDirective: directive:OpenDirective -> 'result + abstract OpenDirective: directive: OpenDirective -> 'result + default OpenDirective: directive: OpenDirective -> 'result /// /// Reduces a node. /// - abstract TypeDeclaration: declaration:TypeDeclaration -> 'result - default TypeDeclaration: declaration:TypeDeclaration -> 'result + abstract TypeDeclaration: declaration: TypeDeclaration -> 'result + default TypeDeclaration: declaration: TypeDeclaration -> 'result /// /// Reduces an node. /// - abstract Attribute: attribute:Attribute -> 'result - default Attribute: attribute:Attribute -> 'result + abstract Attribute: attribute: Attribute -> 'result + default Attribute: attribute: Attribute -> 'result /// /// Reduces an node. /// - abstract UnderlyingType: underlying:UnderlyingType -> 'result - default UnderlyingType: underlying:UnderlyingType -> 'result + abstract UnderlyingType: underlying: UnderlyingType -> 'result + default UnderlyingType: underlying: UnderlyingType -> 'result /// /// Reduces a node. /// - abstract TypeTupleItem: item:TypeTupleItem -> 'result - default TypeTupleItem: item:TypeTupleItem -> 'result + abstract TypeTupleItem: item: TypeTupleItem -> 'result + default TypeTupleItem: item: TypeTupleItem -> 'result /// /// Reduces a node. /// - abstract CallableDeclaration: callable:CallableDeclaration -> 'result - default CallableDeclaration: callable:CallableDeclaration -> 'result + abstract CallableDeclaration: callable: CallableDeclaration -> 'result + default CallableDeclaration: callable: CallableDeclaration -> 'result /// /// Reduces a node. /// - abstract TypeParameterBinding: binding:TypeParameterBinding -> 'result - default TypeParameterBinding: binding:TypeParameterBinding -> 'result + abstract TypeParameterBinding: binding: TypeParameterBinding -> 'result + default TypeParameterBinding: binding: TypeParameterBinding -> 'result /// /// Reduces a node. /// - abstract Type: typ:Type -> 'result - default Type: typ:Type -> 'result + abstract Type: typ: Type -> 'result + default Type: typ: Type -> 'result /// /// Reduces a node. /// - abstract TypeAnnotation: annotation:TypeAnnotation -> 'result - default TypeAnnotation: annotation:TypeAnnotation -> 'result + abstract TypeAnnotation: annotation: TypeAnnotation -> 'result + default TypeAnnotation: annotation: TypeAnnotation -> 'result /// /// Reduces an node. /// - abstract ArrayType: array:ArrayType -> 'result - default ArrayType: array:ArrayType -> 'result + abstract ArrayType: array: ArrayType -> 'result + default ArrayType: array: ArrayType -> 'result /// /// Reduces a node. /// - abstract CallableType: callable:CallableType -> 'result - default CallableType: callable:CallableType -> 'result + abstract CallableType: callable: CallableType -> 'result + default CallableType: callable: CallableType -> 'result /// /// Reduces a node. /// - abstract CharacteristicSection: section:CharacteristicSection -> 'result - default CharacteristicSection: section:CharacteristicSection -> 'result + abstract CharacteristicSection: section: CharacteristicSection -> 'result + default CharacteristicSection: section: CharacteristicSection -> 'result /// /// Reduces a node. /// - abstract CharacteristicGroup: group:CharacteristicGroup -> 'result - default CharacteristicGroup: group:CharacteristicGroup -> 'result + abstract CharacteristicGroup: group: CharacteristicGroup -> 'result + default CharacteristicGroup: group: CharacteristicGroup -> 'result /// /// Reduces a node. /// - abstract Characteristic: characteristic:Characteristic -> 'result - default Characteristic: characteristic:Characteristic -> 'result + abstract Characteristic: characteristic: Characteristic -> 'result + default Characteristic: characteristic: Characteristic -> 'result /// /// Reduces a node. /// - abstract CallableBody: body:CallableBody -> 'result - default CallableBody: body:CallableBody -> 'result + abstract CallableBody: body: CallableBody -> 'result + default CallableBody: body: CallableBody -> 'result /// /// Reduces a node. /// - abstract Specialization: specialization:Specialization -> 'result - default Specialization: specialization:Specialization -> 'result + abstract Specialization: specialization: Specialization -> 'result + default Specialization: specialization: Specialization -> 'result /// /// Reduces a node. /// - abstract SpecializationGenerator: generator:SpecializationGenerator -> 'result - default SpecializationGenerator: generator:SpecializationGenerator -> 'result + abstract SpecializationGenerator: generator: SpecializationGenerator -> 'result + default SpecializationGenerator: generator: SpecializationGenerator -> 'result /// /// Reduces a node. /// - abstract Statement: statement:Statement -> 'result - default Statement: statement:Statement -> 'result + abstract Statement: statement: Statement -> 'result + default Statement: statement: Statement -> 'result /// /// Reduces an statement node. /// - abstract ExpressionStatement: expr:ExpressionStatement -> 'result - default ExpressionStatement: expr:ExpressionStatement -> 'result + abstract ExpressionStatement: expr: ExpressionStatement -> 'result + default ExpressionStatement: expr: ExpressionStatement -> 'result /// /// Reduces a statement node. /// - abstract ReturnStatement: returns:SimpleStatement -> 'result - default ReturnStatement: returns:SimpleStatement -> 'result + abstract ReturnStatement: returns: SimpleStatement -> 'result + default ReturnStatement: returns: SimpleStatement -> 'result /// /// Reduces a statement node. /// - abstract FailStatement: fails:SimpleStatement -> 'result - default FailStatement: fails:SimpleStatement -> 'result + abstract FailStatement: fails: SimpleStatement -> 'result + default FailStatement: fails: SimpleStatement -> 'result /// /// Reduces a statement node. /// - abstract LetStatement: lets:BindingStatement -> 'result - default LetStatement: lets:BindingStatement -> 'result + abstract LetStatement: lets: BindingStatement -> 'result + default LetStatement: lets: BindingStatement -> 'result /// /// Reduces a declaration statement node. /// - abstract MutableStatement: mutables:BindingStatement -> 'result - default MutableStatement: mutables:BindingStatement -> 'result + abstract MutableStatement: mutables: BindingStatement -> 'result + default MutableStatement: mutables: BindingStatement -> 'result /// /// Reduces a statement node. /// - abstract SetStatement: sets:BindingStatement -> 'result - default SetStatement: sets:BindingStatement -> 'result + abstract SetStatement: sets: BindingStatement -> 'result + default SetStatement: sets: BindingStatement -> 'result /// /// Reduces an statement node. /// - abstract UpdateStatement: updates:UpdateStatement -> 'result - default UpdateStatement: updates:UpdateStatement -> 'result + abstract UpdateStatement: updates: UpdateStatement -> 'result + default UpdateStatement: updates: UpdateStatement -> 'result /// /// Reduces an statement node. /// - abstract UpdateWithStatement: withs:UpdateWithStatement -> 'result - default UpdateWithStatement: withs:UpdateWithStatement -> 'result + abstract UpdateWithStatement: withs: UpdateWithStatement -> 'result + default UpdateWithStatement: withs: UpdateWithStatement -> 'result /// /// Reduces an statement node. /// - abstract IfStatement: ifs:ConditionalBlockStatement -> 'result - default IfStatement: ifs:ConditionalBlockStatement -> 'result + abstract IfStatement: ifs: ConditionalBlockStatement -> 'result + default IfStatement: ifs: ConditionalBlockStatement -> 'result /// /// Reduces an statement node. /// - abstract ElifStatement: elifs:ConditionalBlockStatement -> 'result - default ElifStatement: elifs:ConditionalBlockStatement -> 'result + abstract ElifStatement: elifs: ConditionalBlockStatement -> 'result + default ElifStatement: elifs: ConditionalBlockStatement -> 'result /// /// Reduces an statement node. /// - abstract ElseStatement: elses:BlockStatement -> 'result - default ElseStatement: elses:BlockStatement -> 'result + abstract ElseStatement: elses: BlockStatement -> 'result + default ElseStatement: elses: BlockStatement -> 'result /// /// Reduces an statement node. /// - abstract ForStatement : loop: ForStatement -> 'result - default ForStatement : loop: ForStatement -> 'result + abstract ForStatement: loop: ForStatement -> 'result + default ForStatement: loop: ForStatement -> 'result /// /// Reduces an statement node. /// - abstract WhileStatement : whiles: ConditionalBlockStatement -> 'result - default WhileStatement : whiles: ConditionalBlockStatement -> 'result + abstract WhileStatement: whiles: ConditionalBlockStatement -> 'result + default WhileStatement: whiles: ConditionalBlockStatement -> 'result /// /// Reduces an statement node. /// - abstract RepeatStatement : repeats: BlockStatement -> 'result - default RepeatStatement : repeats: BlockStatement -> 'result + abstract RepeatStatement: repeats: BlockStatement -> 'result + default RepeatStatement: repeats: BlockStatement -> 'result /// /// Reduces an statement node. /// - abstract UntilStatement : untils: UntilStatement -> 'result - default UntilStatement : untils: UntilStatement -> 'result + abstract UntilStatement: untils: UntilStatement -> 'result + default UntilStatement: untils: UntilStatement -> 'result /// /// Reduces an node. /// - abstract Fixup : fixup: BlockStatement -> 'result - default Fixup : fixup: BlockStatement -> 'result + abstract Fixup: fixup: BlockStatement -> 'result + default Fixup: fixup: BlockStatement -> 'result /// /// Reduces an statement node. /// - abstract WithinStatement : withins: BlockStatement -> 'result - default WithinStatement : withins: BlockStatement -> 'result + abstract WithinStatement: withins: BlockStatement -> 'result + default WithinStatement: withins: BlockStatement -> 'result /// /// Reduces an statement node. /// - abstract ApplyStatement : apply: BlockStatement -> 'result - default ApplyStatement : apply: BlockStatement -> 'result + abstract ApplyStatement: apply: BlockStatement -> 'result + default ApplyStatement: apply: BlockStatement -> 'result /// /// Reduces a statement node. /// - abstract QubitDeclarationStatement : decl: QubitDeclarationStatement -> 'result - default QubitDeclarationStatement : decl: QubitDeclarationStatement -> 'result + abstract QubitDeclarationStatement: decl: QubitDeclarationStatement -> 'result + default QubitDeclarationStatement: decl: QubitDeclarationStatement -> 'result /// /// Reduces a node. /// - abstract ParameterBinding: binding:ParameterBinding -> 'result - default ParameterBinding: binding:ParameterBinding -> 'result + abstract ParameterBinding: binding: ParameterBinding -> 'result + default ParameterBinding: binding: ParameterBinding -> 'result /// /// Reduces a node. /// - abstract ParameterDeclaration: declaration:ParameterDeclaration -> 'result - default ParameterDeclaration: declaration:ParameterDeclaration -> 'result + abstract ParameterDeclaration: declaration: ParameterDeclaration -> 'result + default ParameterDeclaration: declaration: ParameterDeclaration -> 'result /// /// Reduces a node. /// - abstract SymbolBinding: symbol:SymbolBinding -> 'result - default SymbolBinding: symbol:SymbolBinding -> 'result + abstract SymbolBinding: symbol: SymbolBinding -> 'result + default SymbolBinding: symbol: SymbolBinding -> 'result /// /// Reduces a node. /// - abstract QubitBinding: binding:QubitBinding -> 'result - default QubitBinding: binding:QubitBinding -> 'result + abstract QubitBinding: binding: QubitBinding -> 'result + default QubitBinding: binding: QubitBinding -> 'result /// /// Reduces a node. /// - abstract ForBinding : binding: ForBinding -> 'result - default ForBinding : binding: ForBinding -> 'result + abstract ForBinding: binding: ForBinding -> 'result + default ForBinding: binding: ForBinding -> 'result /// /// Reduces a node. /// - abstract QubitInitializer: initializer:QubitInitializer -> 'result - default QubitInitializer: initializer:QubitInitializer -> 'result + abstract QubitInitializer: initializer: QubitInitializer -> 'result + default QubitInitializer: initializer: QubitInitializer -> 'result /// /// Reduces a node. /// - abstract SingleQubit: newQubit:SingleQubit -> 'result - default SingleQubit: newQubit:SingleQubit -> 'result + abstract SingleQubit: newQubit: SingleQubit -> 'result + default SingleQubit: newQubit: SingleQubit -> 'result /// /// Reduces a node. /// - abstract QubitArray: newQubits:QubitArray -> 'result - default QubitArray: newQubits:QubitArray -> 'result + abstract QubitArray: newQubits: QubitArray -> 'result + default QubitArray: newQubits: QubitArray -> 'result /// /// Reduces an node. /// - abstract InterpStringContent: interpStringContent:InterpStringContent -> 'result - default InterpStringContent: interpStringContent:InterpStringContent -> 'result + abstract InterpStringContent: interpStringContent: InterpStringContent -> 'result + default InterpStringContent: interpStringContent: InterpStringContent -> 'result /// /// Reduces an node. /// - abstract InterpStringExpression: interpStringExpression:InterpStringExpression -> 'result - default InterpStringExpression: interpStringExpression:InterpStringExpression -> 'result + abstract InterpStringExpression: interpStringExpression: InterpStringExpression -> 'result + default InterpStringExpression: interpStringExpression: InterpStringExpression -> 'result /// /// Reduces an node. /// - abstract Expression: expression:Expression -> 'result - default Expression: expression:Expression -> 'result + abstract Expression: expression: Expression -> 'result + default Expression: expression: Expression -> 'result /// /// Reduces an expression node. /// - abstract Identifier: identifier:Identifier -> 'result - default Identifier: identifier:Identifier -> 'result + abstract Identifier: identifier: Identifier -> 'result + default Identifier: identifier: Identifier -> 'result /// /// Reduces an expression node. /// - abstract InterpString: interpString:InterpString -> 'result - default InterpString: interpString:InterpString -> 'result + abstract InterpString: interpString: InterpString -> 'result + default InterpString: interpString: InterpString -> 'result /// /// Reduces a expression node. /// - abstract NewArray: newArray:NewArray -> 'result - default NewArray: newArray:NewArray -> 'result + abstract NewArray: newArray: NewArray -> 'result + default NewArray: newArray: NewArray -> 'result /// /// Reduces a expression node. /// - abstract NewSizedArray: newSizedArray:NewSizedArray -> 'result - default NewSizedArray: newSizedArray:NewSizedArray -> 'result + abstract NewSizedArray: newSizedArray: NewSizedArray -> 'result + default NewSizedArray: newSizedArray: NewSizedArray -> 'result /// /// Reduces a expression node. /// - abstract NamedItemAccess: namedItemAccess:NamedItemAccess -> 'result - default NamedItemAccess: namedItemAccess:NamedItemAccess -> 'result + abstract NamedItemAccess: namedItemAccess: NamedItemAccess -> 'result + default NamedItemAccess: namedItemAccess: NamedItemAccess -> 'result /// /// Reduces an expression node. /// - abstract ArrayAccess: arrayAccess:ArrayAccess -> 'result - default ArrayAccess: arrayAccess:ArrayAccess -> 'result + abstract ArrayAccess: arrayAccess: ArrayAccess -> 'result + default ArrayAccess: arrayAccess: ArrayAccess -> 'result /// /// Reduces a expression node. /// - abstract Call: call:Call -> 'result - default Call: call:Call -> 'result + abstract Call: call: Call -> 'result + default Call: call: Call -> 'result /// /// Reduces a expression node. /// - abstract Conditional: conditional:Conditional -> 'result - default Conditional: conditional:Conditional -> 'result + abstract Conditional: conditional: Conditional -> 'result + default Conditional: conditional: Conditional -> 'result /// /// Reduces an expression node. /// - abstract Update: update:Update -> 'result - default Update: update:Update -> 'result + abstract Update: update: Update -> 'result + default Update: update: Update -> 'result /// /// Reduces a node, given a reducer for the block contents. /// - abstract Block: mapper:('a -> 'result) * block:'a Block -> 'result - default Block: mapper:('a -> 'result) * block:'a Block -> 'result + abstract Block: mapper: ('a -> 'result) * block: 'a Block -> 'result + default Block: mapper: ('a -> 'result) * block: 'a Block -> 'result /// /// Reduces a node, given a reducer for the tuple contents. /// - abstract Tuple: mapper:('a -> 'result) * tuple:'a Tuple -> 'result - default Tuple: mapper:('a -> 'result) * tuple:'a Tuple -> 'result + abstract Tuple: mapper: ('a -> 'result) * tuple: 'a Tuple -> 'result + default Tuple: mapper: ('a -> 'result) * tuple: 'a Tuple -> 'result /// /// Reduces a node, given a reducer for the sequence items. /// - abstract SequenceItem: mapper:('a -> 'result) * item:'a SequenceItem -> 'result - default SequenceItem: mapper:('a -> 'result) * item:'a SequenceItem -> 'result + abstract SequenceItem: mapper: ('a -> 'result) * item: 'a SequenceItem -> 'result + default SequenceItem: mapper: ('a -> 'result) * item: 'a SequenceItem -> 'result /// /// Reduces a node, given a reducer for the operand. /// - abstract PrefixOperator: mapper:('a -> 'result) * operator:'a PrefixOperator -> 'result - default PrefixOperator: mapper:('a -> 'result) * operator:'a PrefixOperator -> 'result + abstract PrefixOperator: mapper: ('a -> 'result) * operator: 'a PrefixOperator -> 'result + default PrefixOperator: mapper: ('a -> 'result) * operator: 'a PrefixOperator -> 'result /// /// Reduces a node, given a reducer for the operand. /// - abstract PostfixOperator: mapper:('a -> 'result) * operator:'a PostfixOperator -> 'result - default PostfixOperator: mapper:('a -> 'result) * operator:'a PostfixOperator -> 'result + abstract PostfixOperator: mapper: ('a -> 'result) * operator: 'a PostfixOperator -> 'result + default PostfixOperator: mapper: ('a -> 'result) * operator: 'a PostfixOperator -> 'result /// /// Reduces an node, given a reducer for the operands. /// - abstract InfixOperator: mapper:('a -> 'result) * operator:'a InfixOperator -> 'result - default InfixOperator: mapper:('a -> 'result) * operator:'a InfixOperator -> 'result + abstract InfixOperator: mapper: ('a -> 'result) * operator: 'a InfixOperator -> 'result + default InfixOperator: mapper: ('a -> 'result) * operator: 'a InfixOperator -> 'result /// /// Reduces a node. /// - 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 fb3a595623..b0791e85a3 100644 --- a/src/QsFmt/Formatter/SyntaxTree/Rewriter.fs +++ b/src/QsFmt/Formatter/SyntaxTree/Rewriter.fs @@ -40,7 +40,7 @@ type 'context Rewriter() as rewriter = Block = rewriter.Block(context, rewriter.Statement, statement.Block) } - abstract Document : context: 'context * document: Document -> Document + abstract Document: context: 'context * document: Document -> Document default _.Document(context, document) = { @@ -48,7 +48,7 @@ type 'context Rewriter() as rewriter = Eof = rewriter.Terminal(context, document.Eof) } - abstract Namespace : context: 'context * ns: Namespace -> Namespace + abstract Namespace: context: 'context * ns: Namespace -> Namespace default _.Namespace(context, ns) = { @@ -57,7 +57,7 @@ type 'context Rewriter() as rewriter = Block = rewriter.Block(context, rewriter.NamespaceItem, ns.Block) } - abstract NamespaceItem : context: 'context * item: NamespaceItem -> NamespaceItem + abstract NamespaceItem: context: 'context * item: NamespaceItem -> NamespaceItem default _.NamespaceItem(context, item) = match item with @@ -66,7 +66,7 @@ type 'context Rewriter() as rewriter = | CallableDeclaration callable -> rewriter.CallableDeclaration(context, callable) |> CallableDeclaration | Unknown terminal -> rewriter.Terminal(context, terminal) |> Unknown - abstract OpenDirective : context: 'context * directive: OpenDirective -> OpenDirective + abstract OpenDirective: context: 'context * directive: OpenDirective -> OpenDirective default rewriter.OpenDirective(context, directive) = { @@ -77,7 +77,7 @@ type 'context Rewriter() as rewriter = Semicolon = rewriter.Terminal(context, directive.Semicolon) } - abstract TypeDeclaration : context: 'context * declaration: TypeDeclaration -> TypeDeclaration + abstract TypeDeclaration: context: 'context * declaration: TypeDeclaration -> TypeDeclaration default rewriter.TypeDeclaration(context, declaration) = { @@ -90,7 +90,7 @@ type 'context Rewriter() as rewriter = Semicolon = rewriter.Terminal(context, declaration.Semicolon) } - abstract Attribute : context: 'context * attribute: Attribute -> Attribute + abstract Attribute: context: 'context * attribute: Attribute -> Attribute default _.Attribute(context, attribute) = { @@ -98,21 +98,21 @@ type 'context Rewriter() as rewriter = Expression = rewriter.Expression(context, attribute.Expression) } - abstract UnderlyingType : context: 'context * underlying: UnderlyingType -> UnderlyingType + abstract UnderlyingType: context: 'context * underlying: UnderlyingType -> UnderlyingType default rewriter.UnderlyingType(context, underlying) = match underlying with | TypeDeclarationTuple tuple -> rewriter.Tuple(context, rewriter.TypeTupleItem, tuple) |> TypeDeclarationTuple | Type _type -> rewriter.Type(context, _type) |> Type - abstract TypeTupleItem : context: 'context * item: TypeTupleItem -> TypeTupleItem + abstract TypeTupleItem: context: 'context * item: TypeTupleItem -> TypeTupleItem default rewriter.TypeTupleItem(context, item) = match item with | TypeBinding binding -> rewriter.ParameterDeclaration(context, binding) |> TypeBinding | UnderlyingType underlying -> rewriter.UnderlyingType(context, underlying) |> UnderlyingType - abstract CallableDeclaration : context: 'context * callable: CallableDeclaration -> CallableDeclaration + abstract CallableDeclaration: context: 'context * callable: CallableDeclaration -> CallableDeclaration default _.CallableDeclaration(context, callable) = { @@ -128,7 +128,7 @@ type 'context Rewriter() as rewriter = Body = rewriter.CallableBody(context, callable.Body) } - abstract TypeParameterBinding : context: 'context * binding: TypeParameterBinding -> TypeParameterBinding + abstract TypeParameterBinding: context: 'context * binding: TypeParameterBinding -> TypeParameterBinding default _.TypeParameterBinding(context, binding) = { @@ -137,7 +137,7 @@ type 'context Rewriter() as rewriter = CloseBracket = rewriter.Terminal(context, binding.CloseBracket) } - abstract Type : context: 'context * typ: Type -> Type + abstract Type: context: 'context * typ: Type -> Type default _.Type(context, typ) = match typ with @@ -150,12 +150,12 @@ type 'context Rewriter() as 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 _.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 _.ArrayType(context, array) = { @@ -164,7 +164,7 @@ type 'context Rewriter() as rewriter = CloseBracket = rewriter.Terminal(context, array.CloseBracket) } - abstract CallableType : context: 'context * callable: CallableType -> CallableType + abstract CallableType: context: 'context * callable: CallableType -> CallableType default _.CallableType(context, callable) = { @@ -174,7 +174,7 @@ type 'context Rewriter() as 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 _.CharacteristicSection(context, section) = { @@ -182,7 +182,7 @@ type 'context Rewriter() as rewriter = Characteristic = rewriter.Characteristic(context, section.Characteristic) } - abstract CharacteristicGroup : context: 'context * group: CharacteristicGroup -> CharacteristicGroup + abstract CharacteristicGroup: context: 'context * group: CharacteristicGroup -> CharacteristicGroup default _.CharacteristicGroup(context, group) = { @@ -191,7 +191,7 @@ type 'context Rewriter() as rewriter = CloseParen = rewriter.Terminal(context, group.CloseParen) } - abstract Characteristic : context: 'context * characteristic: Characteristic -> Characteristic + abstract Characteristic: context: 'context * characteristic: Characteristic -> Characteristic default _.Characteristic(context, characteristic) = match characteristic with @@ -201,7 +201,7 @@ type 'context Rewriter() as rewriter = | Characteristic.InfixOperator operator -> rewriter.InfixOperator(context, rewriter.Characteristic, operator) |> Characteristic.InfixOperator - abstract CallableBody : context: 'context * body: CallableBody -> CallableBody + abstract CallableBody: context: 'context * body: CallableBody -> CallableBody default _.CallableBody(context, body) = match body with @@ -209,7 +209,7 @@ type 'context Rewriter() as rewriter = | Specializations specializations -> rewriter.Block(context, rewriter.Specialization, specializations) |> Specializations - abstract Specialization : context: 'context * specialization: Specialization -> Specialization + abstract Specialization: context: 'context * specialization: Specialization -> Specialization default _.Specialization(context, specialization) = { @@ -217,7 +217,7 @@ type 'context Rewriter() as rewriter = Generator = rewriter.SpecializationGenerator(context, specialization.Generator) } - abstract SpecializationGenerator : context: 'context * generator: SpecializationGenerator -> SpecializationGenerator + abstract SpecializationGenerator: context: 'context * generator: SpecializationGenerator -> SpecializationGenerator default _.SpecializationGenerator(context, generator) = match generator with @@ -229,7 +229,7 @@ type 'context Rewriter() as rewriter = statements = rewriter.Block(context, rewriter.Statement, statements) ) - abstract Statement : context: 'context * statement: Statement -> Statement + abstract Statement: context: 'context * statement: Statement -> Statement default _.Statement(context, statement) = match statement with @@ -254,7 +254,7 @@ type 'context Rewriter() as rewriter = rewriter.QubitDeclarationStatement(context, decl) |> QubitDeclarationStatement | Statement.Unknown terminal -> rewriter.Terminal(context, terminal) |> Statement.Unknown - abstract ExpressionStatement : context: 'context * expr: ExpressionStatement -> ExpressionStatement + abstract ExpressionStatement: context: 'context * expr: ExpressionStatement -> ExpressionStatement default _.ExpressionStatement(context, expr) = { @@ -262,28 +262,28 @@ type 'context Rewriter() as rewriter = Semicolon = rewriter.Terminal(context, expr.Semicolon) } - abstract ReturnStatement : context: 'context * returns: SimpleStatement -> SimpleStatement + abstract ReturnStatement: context: 'context * returns: SimpleStatement -> SimpleStatement default _.ReturnStatement(context, returns) = defaultSimpleStatement context returns - abstract FailStatement : context: 'context * fails: SimpleStatement -> SimpleStatement + abstract FailStatement: context: 'context * fails: SimpleStatement -> SimpleStatement default _.FailStatement(context, fails) = defaultSimpleStatement context fails - abstract LetStatement : context: 'context * lets: BindingStatement -> BindingStatement + abstract LetStatement: context: 'context * lets: BindingStatement -> BindingStatement default _.LetStatement(context, lets) = defaultBindingStatement context lets - abstract MutableStatement : context: 'context * mutables: BindingStatement -> BindingStatement + abstract MutableStatement: context: 'context * mutables: BindingStatement -> BindingStatement default _.MutableStatement(context, mutables) = defaultBindingStatement context mutables - abstract SetStatement : context: 'context * sets: BindingStatement -> BindingStatement + abstract SetStatement: context: 'context * sets: BindingStatement -> BindingStatement default _.SetStatement(context, sets) = defaultBindingStatement context sets - abstract UpdateStatement : context: 'context * updates: UpdateStatement -> UpdateStatement + abstract UpdateStatement: context: 'context * updates: UpdateStatement -> UpdateStatement default _.UpdateStatement(context, updates) = { @@ -294,7 +294,7 @@ type 'context Rewriter() as rewriter = Semicolon = rewriter.Terminal(context, updates.Semicolon) } - abstract UpdateWithStatement : context: 'context * withs: UpdateWithStatement -> UpdateWithStatement + abstract UpdateWithStatement: context: 'context * withs: UpdateWithStatement -> UpdateWithStatement default _.UpdateWithStatement(context, withs) = { @@ -307,21 +307,21 @@ type 'context Rewriter() as rewriter = Semicolon = rewriter.Terminal(context, withs.Semicolon) } - abstract IfStatement : context: 'context * ifs: ConditionalBlockStatement -> ConditionalBlockStatement + abstract IfStatement: context: 'context * ifs: ConditionalBlockStatement -> ConditionalBlockStatement default _.IfStatement(context, ifs) = defaultConditionalBlockStatement context ifs - abstract ElifStatement : context: 'context * elifs: ConditionalBlockStatement -> ConditionalBlockStatement + abstract ElifStatement: context: 'context * elifs: ConditionalBlockStatement -> ConditionalBlockStatement default _.ElifStatement(context, elifs) = defaultConditionalBlockStatement context elifs - abstract ElseStatement : context: 'context * elses: BlockStatement -> BlockStatement + abstract ElseStatement: context: 'context * elses: BlockStatement -> BlockStatement default _.ElseStatement(context, elses) = defaultBlockStatement context elses - abstract ForStatement : context: 'context * loop: ForStatement -> ForStatement + abstract ForStatement: context: 'context * loop: ForStatement -> ForStatement default _.ForStatement(context, loop) = { @@ -332,16 +332,16 @@ type 'context Rewriter() as rewriter = Block = rewriter.Block(context, rewriter.Statement, loop.Block) } - abstract WhileStatement : context: 'context * whiles: ConditionalBlockStatement -> ConditionalBlockStatement + abstract WhileStatement: context: 'context * whiles: ConditionalBlockStatement -> ConditionalBlockStatement default _.WhileStatement(context, whiles) = defaultConditionalBlockStatement context whiles - abstract RepeatStatement : context: 'context * repeats: BlockStatement -> BlockStatement + abstract RepeatStatement: context: 'context * repeats: BlockStatement -> BlockStatement default _.RepeatStatement(context, repeats) = defaultBlockStatement context repeats - abstract UntilStatement : context: 'context * untils: UntilStatement -> UntilStatement + abstract UntilStatement: context: 'context * untils: UntilStatement -> UntilStatement default _.UntilStatement(context, untils) = { @@ -354,20 +354,19 @@ type 'context Rewriter() as rewriter = | Fixup fixup -> rewriter.Fixup(context, fixup) |> Fixup } - abstract Fixup : context: 'context * fixup: BlockStatement -> BlockStatement + abstract Fixup: context: 'context * fixup: BlockStatement -> BlockStatement default _.Fixup(context, fixup) = defaultBlockStatement context fixup - abstract WithinStatement : context: 'context * withins: BlockStatement -> BlockStatement + abstract WithinStatement: context: 'context * withins: BlockStatement -> BlockStatement default _.WithinStatement(context, withins) = defaultBlockStatement context withins - abstract ApplyStatement : context: 'context * apply: BlockStatement -> BlockStatement + abstract ApplyStatement: context: 'context * apply: BlockStatement -> BlockStatement default _.ApplyStatement(context, apply) = defaultBlockStatement context apply - abstract QubitDeclarationStatement : - context: 'context * decl: QubitDeclarationStatement -> QubitDeclarationStatement + abstract QubitDeclarationStatement: context: 'context * decl: QubitDeclarationStatement -> QubitDeclarationStatement default _.QubitDeclarationStatement(context, decl) = { @@ -382,7 +381,7 @@ type 'context Rewriter() as rewriter = | Block block -> rewriter.Block(context, rewriter.Statement, block) |> Block } - abstract ParameterBinding : context: 'context * binding: ParameterBinding -> ParameterBinding + abstract ParameterBinding: context: 'context * binding: ParameterBinding -> ParameterBinding default _.ParameterBinding(context, binding) = match binding with @@ -390,7 +389,7 @@ type 'context Rewriter() as rewriter = rewriter.ParameterDeclaration(context, declaration) |> ParameterDeclaration | ParameterTuple tuple -> rewriter.Tuple(context, rewriter.ParameterBinding, tuple) |> ParameterTuple - abstract ParameterDeclaration : context: 'context * declaration: ParameterDeclaration -> ParameterDeclaration + abstract ParameterDeclaration: context: 'context * declaration: ParameterDeclaration -> ParameterDeclaration default _.ParameterDeclaration(context, declaration) = { @@ -398,14 +397,14 @@ type 'context Rewriter() as rewriter = Type = rewriter.TypeAnnotation(context, declaration.Type) } - abstract SymbolBinding : context: 'context * symbol: SymbolBinding -> SymbolBinding + abstract SymbolBinding: context: 'context * symbol: SymbolBinding -> SymbolBinding default _.SymbolBinding(context, symbol) = match symbol with | SymbolDeclaration declaration -> rewriter.Terminal(context, declaration) |> SymbolDeclaration | SymbolTuple tuple -> rewriter.Tuple(context, rewriter.SymbolBinding, tuple) |> SymbolTuple - abstract QubitBinding : context: 'context * binding: QubitBinding -> QubitBinding + abstract QubitBinding: context: 'context * binding: QubitBinding -> QubitBinding default _.QubitBinding(context, binding) = { @@ -414,7 +413,7 @@ type 'context Rewriter() as rewriter = Initializer = rewriter.QubitInitializer(context, binding.Initializer) } - abstract ForBinding : context: 'context * binding: ForBinding -> ForBinding + abstract ForBinding: context: 'context * binding: ForBinding -> ForBinding default _.ForBinding(context, binding) = { @@ -423,7 +422,7 @@ type 'context Rewriter() as rewriter = Value = rewriter.Expression(context, binding.Value) } - abstract QubitInitializer : context: 'context * initializer: QubitInitializer -> QubitInitializer + abstract QubitInitializer: context: 'context * initializer: QubitInitializer -> QubitInitializer default _.QubitInitializer(context, initializer) = match initializer with @@ -431,7 +430,7 @@ type 'context Rewriter() as rewriter = | QubitArray qubitArray -> rewriter.QubitArray(context, qubitArray) |> QubitArray | QubitTuple tuple -> rewriter.Tuple(context, rewriter.QubitInitializer, tuple) |> QubitTuple - abstract SingleQubit : context: 'context * newQubit: SingleQubit -> SingleQubit + abstract SingleQubit: context: 'context * newQubit: SingleQubit -> SingleQubit default _.SingleQubit(context, newQubit) = { @@ -440,7 +439,7 @@ type 'context Rewriter() as rewriter = CloseParen = rewriter.Terminal(context, newQubit.CloseParen) } - abstract QubitArray : context: 'context * newQubits: QubitArray -> QubitArray + abstract QubitArray: context: 'context * newQubits: QubitArray -> QubitArray default _.QubitArray(context, newQubits) = { @@ -450,7 +449,7 @@ type 'context Rewriter() as rewriter = CloseBracket = rewriter.Terminal(context, newQubits.CloseBracket) } - abstract InterpStringContent : context: 'context * interpStringContent: InterpStringContent -> InterpStringContent + abstract InterpStringContent: context: 'context * interpStringContent: InterpStringContent -> InterpStringContent default _.InterpStringContent(context, interpStringContent) = match interpStringContent with @@ -458,7 +457,7 @@ type 'context Rewriter() as rewriter = | Expression interpStringExpression -> rewriter.InterpStringExpression(context, interpStringExpression) |> Expression - abstract InterpStringExpression : + abstract InterpStringExpression: context: 'context * interpStringExpression: InterpStringExpression -> InterpStringExpression default _.InterpStringExpression(context, interpStringExpression) = @@ -468,7 +467,7 @@ type 'context Rewriter() as rewriter = CloseBrace = rewriter.Terminal(context, interpStringExpression.CloseBrace) } - abstract Expression : context: 'context * expression: Expression -> Expression + abstract Expression: context: 'context * expression: Expression -> Expression default _.Expression(context, expression) = match expression with @@ -491,7 +490,7 @@ type 'context Rewriter() as rewriter = | Update update -> rewriter.Update(context, update) |> Update | Expression.Unknown terminal -> rewriter.Terminal(context, terminal) |> Expression.Unknown - abstract Identifier : context: 'context * identifier: Identifier -> Identifier + abstract Identifier: context: 'context * identifier: Identifier -> Identifier default _.Identifier(context, identifier) = { @@ -499,7 +498,7 @@ type 'context Rewriter() as rewriter = TypeArgs = identifier.TypeArgs |> Option.map (curry3 rewriter.Tuple context rewriter.Type) } - abstract InterpString : context: 'context * interpString: InterpString -> InterpString + abstract InterpString: context: 'context * interpString: InterpString -> InterpString default _.InterpString(context, interpString) = { @@ -508,7 +507,7 @@ type 'context Rewriter() as rewriter = CloseQuote = rewriter.Terminal(context, interpString.CloseQuote) } - abstract NewArray : context: 'context * newArray: NewArray -> NewArray + abstract NewArray: context: 'context * newArray: NewArray -> NewArray default _.NewArray(context, newArray) = { @@ -519,7 +518,7 @@ type 'context Rewriter() as rewriter = CloseBracket = rewriter.Terminal(context, newArray.CloseBracket) } - abstract NewSizedArray : context: 'context * newSizedArray: NewSizedArray -> NewSizedArray + abstract NewSizedArray: context: 'context * newSizedArray: NewSizedArray -> NewSizedArray default _.NewSizedArray(context, newSizedArray) = { @@ -532,7 +531,7 @@ type 'context Rewriter() as rewriter = CloseBracket = rewriter.Terminal(context, newSizedArray.CloseBracket) } - abstract NamedItemAccess : context: 'context * namedItemAccess: NamedItemAccess -> NamedItemAccess + abstract NamedItemAccess: context: 'context * namedItemAccess: NamedItemAccess -> NamedItemAccess default _.NamedItemAccess(context, namedItemAccess) = { @@ -541,7 +540,7 @@ type 'context Rewriter() as rewriter = Name = rewriter.Terminal(context, namedItemAccess.Name) } - abstract ArrayAccess : context: 'context * arrayAccess: ArrayAccess -> ArrayAccess + abstract ArrayAccess: context: 'context * arrayAccess: ArrayAccess -> ArrayAccess default _.ArrayAccess(context, arrayAccess) = { @@ -551,7 +550,7 @@ type 'context Rewriter() as rewriter = CloseBracket = rewriter.Terminal(context, arrayAccess.CloseBracket) } - abstract Call : context: 'context * call: Call -> Call + abstract Call: context: 'context * call: Call -> Call default _.Call(context, call) = { @@ -559,7 +558,7 @@ type 'context Rewriter() as rewriter = Arguments = rewriter.Tuple(context, rewriter.Expression, call.Arguments) } - abstract Conditional : context: 'context * conditional: Conditional -> Conditional + abstract Conditional: context: 'context * conditional: Conditional -> Conditional default _.Conditional(context, conditional) = { @@ -570,7 +569,7 @@ type 'context Rewriter() as rewriter = IfFalse = rewriter.Expression(context, conditional.IfFalse) } - abstract Update : context: 'context * update: Update -> Update + abstract Update: context: 'context * update: Update -> Update default _.Update(context, update) = { @@ -581,7 +580,7 @@ type 'context Rewriter() as 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 _.Block(context, mapper, block) = { @@ -590,7 +589,7 @@ type 'context Rewriter() as 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 _.Tuple(context, mapper, tuple) = { @@ -599,7 +598,7 @@ type 'context Rewriter() as 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 _.SequenceItem(context, mapper, item) = { @@ -607,7 +606,7 @@ type 'context Rewriter() as rewriter = Comma = item.Comma |> Option.map (curry rewriter.Terminal context) } - abstract PrefixOperator : + abstract PrefixOperator: context: 'context * mapper: ('context * 'a -> 'a) * operator: 'a PrefixOperator -> 'a PrefixOperator default _.PrefixOperator(context, mapper, operator) = @@ -616,7 +615,7 @@ type 'context Rewriter() as rewriter = Operand = mapper (context, operator.Operand) } - abstract PostfixOperator : + abstract PostfixOperator: context: 'context * mapper: ('context * 'a -> 'a) * operator: 'a PostfixOperator -> 'a PostfixOperator default _.PostfixOperator(context, mapper, operator) = @@ -625,7 +624,7 @@ type 'context Rewriter() as rewriter = PostfixOperator = rewriter.Terminal(context, operator.PostfixOperator) } - abstract InfixOperator : + abstract InfixOperator: context: 'context * mapper: ('context * 'a -> 'a) * operator: 'a InfixOperator -> 'a InfixOperator default _.InfixOperator(context, mapper, operator) = @@ -635,5 +634,5 @@ type 'context Rewriter() as rewriter = Right = mapper (context, operator.Right) } - abstract Terminal : context: 'context * terminal: Terminal -> Terminal + abstract Terminal: context: 'context * terminal: Terminal -> Terminal default _.Terminal(_, terminal) = terminal diff --git a/src/QsFmt/Formatter/SyntaxTree/Rewriter.fsi b/src/QsFmt/Formatter/SyntaxTree/Rewriter.fsi index aa9acfa9ef..b8aad9227d 100644 --- a/src/QsFmt/Formatter/SyntaxTree/Rewriter.fsi +++ b/src/QsFmt/Formatter/SyntaxTree/Rewriter.fsi @@ -16,419 +16,409 @@ type internal 'context Rewriter = /// /// Rewrites a node. /// - abstract Document: context:'context * document:Document -> Document - default Document: context:'context * document:Document -> Document + abstract Document: context: 'context * document: Document -> Document + default Document: context: 'context * document: Document -> Document /// /// Rewrites a node. /// - abstract Namespace: context:'context * ns:Namespace -> Namespace - default Namespace: context:'context * ns:Namespace -> Namespace + abstract Namespace: context: 'context * ns: Namespace -> Namespace + default Namespace: context: 'context * ns: Namespace -> Namespace /// /// Rewrites a node. /// - abstract NamespaceItem: context:'context * item:NamespaceItem -> NamespaceItem - default NamespaceItem: context:'context * item:NamespaceItem -> NamespaceItem + abstract NamespaceItem: context: 'context * item: NamespaceItem -> NamespaceItem + default NamespaceItem: context: 'context * item: NamespaceItem -> NamespaceItem /// /// Rewrites an node. /// - abstract OpenDirective: context:'context * directive:OpenDirective -> OpenDirective - default OpenDirective: context:'context * directive:OpenDirective -> OpenDirective + abstract OpenDirective: context: 'context * directive: OpenDirective -> OpenDirective + default OpenDirective: context: 'context * directive: OpenDirective -> OpenDirective /// /// Rewrites a node. /// - abstract TypeDeclaration: context:'context * declaration:TypeDeclaration -> TypeDeclaration - default TypeDeclaration: context:'context * declaration:TypeDeclaration -> TypeDeclaration + abstract TypeDeclaration: context: 'context * declaration: TypeDeclaration -> TypeDeclaration + default TypeDeclaration: context: 'context * declaration: TypeDeclaration -> TypeDeclaration /// /// Rewrites an node. /// - abstract Attribute: context:'context * attribute:Attribute -> Attribute - default Attribute: context:'context * attribute:Attribute -> Attribute + abstract Attribute: context: 'context * attribute: Attribute -> Attribute + default Attribute: context: 'context * attribute: Attribute -> Attribute /// /// Rewrites an node. /// - abstract UnderlyingType: context:'context * underlying:UnderlyingType -> UnderlyingType - default UnderlyingType: context:'context * underlying:UnderlyingType -> UnderlyingType + abstract UnderlyingType: context: 'context * underlying: UnderlyingType -> UnderlyingType + default UnderlyingType: context: 'context * underlying: UnderlyingType -> UnderlyingType /// /// Rewrites a node. /// - abstract TypeTupleItem: context:'context * item:TypeTupleItem -> TypeTupleItem - default TypeTupleItem: context:'context * item:TypeTupleItem -> TypeTupleItem + abstract TypeTupleItem: context: 'context * item: TypeTupleItem -> TypeTupleItem + default TypeTupleItem: context: 'context * item: TypeTupleItem -> TypeTupleItem /// /// Rewrites a node. /// - abstract CallableDeclaration: context:'context * callable:CallableDeclaration -> CallableDeclaration - default CallableDeclaration: context:'context * callable:CallableDeclaration -> CallableDeclaration + abstract CallableDeclaration: context: 'context * callable: CallableDeclaration -> CallableDeclaration + default CallableDeclaration: context: 'context * callable: CallableDeclaration -> CallableDeclaration /// /// Rewrites a node. /// - abstract TypeParameterBinding: context:'context * binding:TypeParameterBinding -> TypeParameterBinding - default TypeParameterBinding: context:'context * binding:TypeParameterBinding -> TypeParameterBinding + abstract TypeParameterBinding: context: 'context * binding: TypeParameterBinding -> TypeParameterBinding + default TypeParameterBinding: context: 'context * binding: TypeParameterBinding -> TypeParameterBinding /// /// Rewrites a node. /// - abstract Type: context:'context * typ:Type -> Type - default Type: context:'context * typ:Type -> Type + abstract Type: context: 'context * typ: Type -> Type + default Type: context: 'context * typ: Type -> Type /// /// Rewrites a node. /// - abstract TypeAnnotation: context:'context * annotation:TypeAnnotation -> TypeAnnotation - default TypeAnnotation: context:'context * annotation:TypeAnnotation -> TypeAnnotation + abstract TypeAnnotation: context: 'context * annotation: TypeAnnotation -> TypeAnnotation + default TypeAnnotation: context: 'context * annotation: TypeAnnotation -> TypeAnnotation /// /// Rewrites an node. /// - abstract ArrayType: context:'context * array:ArrayType -> ArrayType - default ArrayType: context:'context * array:ArrayType -> ArrayType + abstract ArrayType: context: 'context * array: ArrayType -> ArrayType + default ArrayType: context: 'context * array: ArrayType -> ArrayType /// /// Rewrites a node. /// - abstract CallableType: context:'context * callable:CallableType -> CallableType - default CallableType: context:'context * callable:CallableType -> CallableType + abstract CallableType: context: 'context * callable: CallableType -> CallableType + default CallableType: context: 'context * callable: CallableType -> CallableType /// /// Rewrites a node. /// - abstract CharacteristicSection: context:'context * section:CharacteristicSection -> CharacteristicSection - default CharacteristicSection: context:'context * section:CharacteristicSection -> CharacteristicSection + abstract CharacteristicSection: context: 'context * section: CharacteristicSection -> CharacteristicSection + default CharacteristicSection: context: 'context * section: CharacteristicSection -> CharacteristicSection /// /// Rewrites a node. /// - abstract CharacteristicGroup: context:'context * group:CharacteristicGroup -> CharacteristicGroup - default CharacteristicGroup: context:'context * group:CharacteristicGroup -> CharacteristicGroup + abstract CharacteristicGroup: context: 'context * group: CharacteristicGroup -> CharacteristicGroup + default CharacteristicGroup: context: 'context * group: CharacteristicGroup -> CharacteristicGroup /// /// Rewrites a node. /// - abstract Characteristic: context:'context * characteristic:Characteristic -> Characteristic - default Characteristic: context:'context * characteristic:Characteristic -> Characteristic + abstract Characteristic: context: 'context * characteristic: Characteristic -> Characteristic + default Characteristic: context: 'context * characteristic: Characteristic -> Characteristic /// /// Rewrites a node. /// - abstract CallableBody: context:'context * body:CallableBody -> CallableBody - default CallableBody: context:'context * body:CallableBody -> CallableBody + abstract CallableBody: context: 'context * body: CallableBody -> CallableBody + default CallableBody: context: 'context * body: CallableBody -> CallableBody /// /// Rewrites a node. /// - abstract Specialization: context:'context * specialization:Specialization -> Specialization - default Specialization: context:'context * specialization:Specialization -> Specialization + abstract Specialization: context: 'context * specialization: Specialization -> Specialization + default Specialization: context: 'context * specialization: Specialization -> Specialization /// /// Rewrites a node. /// - abstract SpecializationGenerator: context:'context * generator:SpecializationGenerator -> SpecializationGenerator - default SpecializationGenerator: context:'context * generator:SpecializationGenerator -> SpecializationGenerator + abstract SpecializationGenerator: context: 'context * generator: SpecializationGenerator -> SpecializationGenerator + default SpecializationGenerator: context: 'context * generator: SpecializationGenerator -> SpecializationGenerator /// /// Rewrites a node. /// - abstract Statement: context:'context * statement:Statement -> Statement - default Statement: context:'context * statement:Statement -> Statement + abstract Statement: context: 'context * statement: Statement -> Statement + default Statement: context: 'context * statement: Statement -> Statement /// /// Rewrites an statement node. /// - abstract ExpressionStatement: context:'context * expr:ExpressionStatement -> ExpressionStatement - default ExpressionStatement: context:'context * expr:ExpressionStatement -> ExpressionStatement + abstract ExpressionStatement: context: 'context * expr: ExpressionStatement -> ExpressionStatement + default ExpressionStatement: context: 'context * expr: ExpressionStatement -> ExpressionStatement /// /// Rewrites a statement node. /// - abstract ReturnStatement: context:'context * returns:SimpleStatement -> SimpleStatement - default ReturnStatement: context:'context * returns:SimpleStatement -> SimpleStatement + abstract ReturnStatement: context: 'context * returns: SimpleStatement -> SimpleStatement + default ReturnStatement: context: 'context * returns: SimpleStatement -> SimpleStatement /// /// Rewrites a statement node. /// - abstract FailStatement: context:'context * fails:SimpleStatement -> SimpleStatement - default FailStatement: context:'context * fails:SimpleStatement -> SimpleStatement + abstract FailStatement: context: 'context * fails: SimpleStatement -> SimpleStatement + default FailStatement: context: 'context * fails: SimpleStatement -> SimpleStatement /// /// Rewrites a statement node. /// - abstract LetStatement: context:'context * lets:BindingStatement -> BindingStatement - default LetStatement: context:'context * lets:BindingStatement -> BindingStatement + abstract LetStatement: context: 'context * lets: BindingStatement -> BindingStatement + default LetStatement: context: 'context * lets: BindingStatement -> BindingStatement /// /// Rewrites a declaration statement node. /// - abstract MutableStatement: context:'context * mutables:BindingStatement -> BindingStatement - default MutableStatement: context:'context * mutables:BindingStatement -> BindingStatement + abstract MutableStatement: context: 'context * mutables: BindingStatement -> BindingStatement + default MutableStatement: context: 'context * mutables: BindingStatement -> BindingStatement /// /// Rewrites a statement node. /// - abstract SetStatement: context:'context * sets:BindingStatement -> BindingStatement - default SetStatement: context:'context * sets:BindingStatement -> BindingStatement + abstract SetStatement: context: 'context * sets: BindingStatement -> BindingStatement + default SetStatement: context: 'context * sets: BindingStatement -> BindingStatement /// /// Rewrites an statement node. /// - abstract UpdateStatement: context:'context * updates:UpdateStatement -> UpdateStatement - default UpdateStatement: context:'context * updates:UpdateStatement -> UpdateStatement + abstract UpdateStatement: context: 'context * updates: UpdateStatement -> UpdateStatement + default UpdateStatement: context: 'context * updates: UpdateStatement -> UpdateStatement /// /// Rewrites an statement node. /// - abstract UpdateWithStatement: context:'context * withs:UpdateWithStatement -> UpdateWithStatement - default UpdateWithStatement: context:'context * withs:UpdateWithStatement -> UpdateWithStatement + abstract UpdateWithStatement: context: 'context * withs: UpdateWithStatement -> UpdateWithStatement + default UpdateWithStatement: context: 'context * withs: UpdateWithStatement -> UpdateWithStatement /// /// Rewrites an statement node. /// - abstract IfStatement: context:'context * ifs:ConditionalBlockStatement -> ConditionalBlockStatement - default IfStatement: context:'context * ifs:ConditionalBlockStatement -> ConditionalBlockStatement + abstract IfStatement: context: 'context * ifs: ConditionalBlockStatement -> ConditionalBlockStatement + default IfStatement: context: 'context * ifs: ConditionalBlockStatement -> ConditionalBlockStatement /// /// Rewrites an statement node. /// - abstract ElifStatement: context:'context * elifs:ConditionalBlockStatement -> ConditionalBlockStatement - default ElifStatement: context:'context * elifs:ConditionalBlockStatement -> ConditionalBlockStatement + abstract ElifStatement: context: 'context * elifs: ConditionalBlockStatement -> ConditionalBlockStatement + default ElifStatement: context: 'context * elifs: ConditionalBlockStatement -> ConditionalBlockStatement /// /// Rewrites an statement node. /// - abstract ElseStatement: context:'context * elses:BlockStatement -> BlockStatement - default ElseStatement: context:'context * elses:BlockStatement -> BlockStatement + abstract ElseStatement: context: 'context * elses: BlockStatement -> BlockStatement + default ElseStatement: context: 'context * elses: BlockStatement -> BlockStatement /// /// Rewrites a statement node. /// - abstract ForStatement : context: 'context * loop: ForStatement -> ForStatement - default ForStatement : context: 'context * loop: ForStatement -> ForStatement + abstract ForStatement: context: 'context * loop: ForStatement -> ForStatement + default ForStatement: context: 'context * loop: ForStatement -> ForStatement /// /// Rewrites a statement node. /// - abstract WhileStatement : context: 'context * whiles: ConditionalBlockStatement -> ConditionalBlockStatement - default WhileStatement : context: 'context * whiles: ConditionalBlockStatement -> ConditionalBlockStatement + abstract WhileStatement: context: 'context * whiles: ConditionalBlockStatement -> ConditionalBlockStatement + default WhileStatement: context: 'context * whiles: ConditionalBlockStatement -> ConditionalBlockStatement /// /// Rewrites a statement node. /// - abstract RepeatStatement : context: 'context * repeats: BlockStatement -> BlockStatement - default RepeatStatement : context: 'context * repeats: BlockStatement -> BlockStatement + abstract RepeatStatement: context: 'context * repeats: BlockStatement -> BlockStatement + default RepeatStatement: context: 'context * repeats: BlockStatement -> BlockStatement /// /// Rewrites a statement node. /// - abstract UntilStatement : context: 'context * untils: UntilStatement -> UntilStatement - default UntilStatement : context: 'context * untils: UntilStatement -> UntilStatement + abstract UntilStatement: context: 'context * untils: UntilStatement -> UntilStatement + default UntilStatement: context: 'context * untils: UntilStatement -> UntilStatement /// /// Rewrites a node. /// - abstract Fixup : context: 'context * fixup: BlockStatement -> BlockStatement - default Fixup : context: 'context * fixup: BlockStatement -> BlockStatement + abstract Fixup: context: 'context * fixup: BlockStatement -> BlockStatement + default Fixup: context: 'context * fixup: BlockStatement -> BlockStatement /// /// Rewrites a statement node. /// - abstract WithinStatement : context: 'context * withins: BlockStatement -> BlockStatement - default WithinStatement : context: 'context * withins: BlockStatement -> BlockStatement + abstract WithinStatement: context: 'context * withins: BlockStatement -> BlockStatement + default WithinStatement: context: 'context * withins: BlockStatement -> BlockStatement /// /// Rewrites a statement node. /// - abstract ApplyStatement : context: 'context * apply: BlockStatement -> BlockStatement - default ApplyStatement : context: 'context * apply: BlockStatement -> BlockStatement + abstract ApplyStatement: context: 'context * apply: BlockStatement -> BlockStatement + default ApplyStatement: context: 'context * apply: BlockStatement -> BlockStatement /// /// Rewrites a statement node. /// - abstract QubitDeclarationStatement : context: 'context * decl: QubitDeclarationStatement -> QubitDeclarationStatement - default QubitDeclarationStatement : context: 'context * decl: QubitDeclarationStatement -> QubitDeclarationStatement + abstract QubitDeclarationStatement: context: 'context * decl: QubitDeclarationStatement -> QubitDeclarationStatement + default QubitDeclarationStatement: context: 'context * decl: QubitDeclarationStatement -> QubitDeclarationStatement /// /// Rewrites a node. /// - abstract ParameterBinding: context:'context * binding:ParameterBinding -> ParameterBinding - default ParameterBinding: context:'context * binding:ParameterBinding -> ParameterBinding + abstract ParameterBinding: context: 'context * binding: ParameterBinding -> ParameterBinding + default ParameterBinding: context: 'context * binding: ParameterBinding -> ParameterBinding /// /// Rewrites a node. /// - abstract ParameterDeclaration: context:'context * declaration:ParameterDeclaration -> ParameterDeclaration - default ParameterDeclaration: context:'context * declaration:ParameterDeclaration -> ParameterDeclaration + abstract ParameterDeclaration: context: 'context * declaration: ParameterDeclaration -> ParameterDeclaration + default ParameterDeclaration: context: 'context * declaration: ParameterDeclaration -> ParameterDeclaration /// /// Rewrites a node. /// - abstract SymbolBinding: context:'context * symbol:SymbolBinding -> SymbolBinding - default SymbolBinding: context:'context * symbol:SymbolBinding -> SymbolBinding + abstract SymbolBinding: context: 'context * symbol: SymbolBinding -> SymbolBinding + default SymbolBinding: context: 'context * symbol: SymbolBinding -> SymbolBinding /// /// Rewrites a node. /// - abstract QubitBinding: context:'context * binding:QubitBinding -> QubitBinding - default QubitBinding: context:'context * binding:QubitBinding -> QubitBinding + abstract QubitBinding: context: 'context * binding: QubitBinding -> QubitBinding + default QubitBinding: context: 'context * binding: QubitBinding -> QubitBinding /// /// Rewrites a node. /// - abstract ForBinding : context: 'context * binding: ForBinding -> ForBinding - default ForBinding : context: 'context * binding: ForBinding -> ForBinding + abstract ForBinding: context: 'context * binding: ForBinding -> ForBinding + default ForBinding: context: 'context * binding: ForBinding -> ForBinding /// /// Rewrites a node. /// - abstract QubitInitializer: context:'context * initializer:QubitInitializer -> QubitInitializer - default QubitInitializer: context:'context * initializer:QubitInitializer -> QubitInitializer + abstract QubitInitializer: context: 'context * initializer: QubitInitializer -> QubitInitializer + default QubitInitializer: context: 'context * initializer: QubitInitializer -> QubitInitializer /// /// Rewrites a node. /// - abstract SingleQubit: context:'context * newQubit:SingleQubit -> SingleQubit - default SingleQubit: context:'context * newQubit:SingleQubit -> SingleQubit + abstract SingleQubit: context: 'context * newQubit: SingleQubit -> SingleQubit + default SingleQubit: context: 'context * newQubit: SingleQubit -> SingleQubit /// /// Rewrites a node. /// - abstract QubitArray: context:'context * newQubits:QubitArray -> QubitArray - default QubitArray: context:'context * newQubits:QubitArray -> QubitArray + abstract QubitArray: context: 'context * newQubits: QubitArray -> QubitArray + default QubitArray: context: 'context * newQubits: QubitArray -> QubitArray /// /// Rewrites an node. /// - abstract InterpStringContent: context:'context * interpStringContent:InterpStringContent -> InterpStringContent - default InterpStringContent: context:'context * interpStringContent:InterpStringContent -> InterpStringContent + abstract InterpStringContent: context: 'context * interpStringContent: InterpStringContent -> InterpStringContent + default InterpStringContent: context: 'context * interpStringContent: InterpStringContent -> InterpStringContent /// /// Rewrites an node. /// - abstract InterpStringExpression: context:'context * interpStringExpression:InterpStringExpression -> InterpStringExpression - default InterpStringExpression: context:'context * interpStringExpression:InterpStringExpression -> InterpStringExpression + abstract InterpStringExpression: + context: 'context * interpStringExpression: InterpStringExpression -> InterpStringExpression + default InterpStringExpression: + context: 'context * interpStringExpression: InterpStringExpression -> InterpStringExpression /// /// Rewrites an node. /// - abstract Expression: context:'context * expression:Expression -> Expression - default Expression: context:'context * expression:Expression -> Expression + abstract Expression: context: 'context * expression: Expression -> Expression + default Expression: context: 'context * expression: Expression -> Expression /// /// Rewrites an expression node. /// - abstract Identifier: context:'context * identifier:Identifier -> Identifier - default Identifier: context:'context * identifier:Identifier -> Identifier + abstract Identifier: context: 'context * identifier: Identifier -> Identifier + default Identifier: context: 'context * identifier: Identifier -> Identifier /// /// Rewrites an expression node. /// - abstract InterpString: context:'context * interpString:InterpString -> InterpString - default InterpString: context:'context * interpString:InterpString -> InterpString + abstract InterpString: context: 'context * interpString: InterpString -> InterpString + default InterpString: context: 'context * interpString: InterpString -> InterpString /// /// Rewrites a expression node. /// - abstract NewArray: context:'context * newArray:NewArray -> NewArray - default NewArray: context:'context * newArray:NewArray -> NewArray + abstract NewArray: context: 'context * newArray: NewArray -> NewArray + default NewArray: context: 'context * newArray: NewArray -> NewArray /// /// Rewrites a expression node. /// - abstract NewSizedArray: context:'context * newSizedArray:NewSizedArray -> NewSizedArray - default NewSizedArray: context:'context * newSizedArray:NewSizedArray -> NewSizedArray + abstract NewSizedArray: context: 'context * newSizedArray: NewSizedArray -> NewSizedArray + default NewSizedArray: context: 'context * newSizedArray: NewSizedArray -> NewSizedArray /// /// Rewrites a expression node. /// - abstract NamedItemAccess: context:'context * namedItemAccess:NamedItemAccess -> NamedItemAccess - default NamedItemAccess: context:'context * namedItemAccess:NamedItemAccess -> NamedItemAccess + abstract NamedItemAccess: context: 'context * namedItemAccess: NamedItemAccess -> NamedItemAccess + default NamedItemAccess: context: 'context * namedItemAccess: NamedItemAccess -> NamedItemAccess /// /// Rewrites an expression node. /// - abstract ArrayAccess: context:'context * arrayAccess:ArrayAccess -> ArrayAccess - default ArrayAccess: context:'context * arrayAccess:ArrayAccess -> ArrayAccess + abstract ArrayAccess: context: 'context * arrayAccess: ArrayAccess -> ArrayAccess + default ArrayAccess: context: 'context * arrayAccess: ArrayAccess -> ArrayAccess /// /// Rewrites a expression node. /// - abstract Call: context:'context * call:Call -> Call - default Call: context:'context * call:Call -> Call + abstract Call: context: 'context * call: Call -> Call + default Call: context: 'context * call: Call -> Call /// /// Rewrites a expression node. /// - abstract Conditional: context:'context * conditional:Conditional -> Conditional - default Conditional: context:'context * conditional:Conditional -> Conditional + abstract Conditional: context: 'context * conditional: Conditional -> Conditional + default Conditional: context: 'context * conditional: Conditional -> Conditional /// /// Rewrites an expression node. /// - abstract Update: context:'context * update:Update -> Update - default Update: context:'context * update:Update -> Update + abstract Update: context: 'context * update: Update -> Update + default Update: context: 'context * update: Update -> Update /// /// Rewrites a node, given a rewriter for the block contents. /// - abstract Block: context:'context * mapper:('context * 'a -> 'a) * block:'a Block -> 'a Block - default 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 Block: context: 'context * mapper: ('context * 'a -> 'a) * block: 'a Block -> 'a Block /// /// Rewrites a node, given a rewriter for the tuple contents. /// - abstract Tuple: context:'context * mapper:('context * 'a -> 'a) * tuple:'a Tuple -> 'a Tuple - default 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 Tuple: context: 'context * mapper: ('context * 'a -> 'a) * tuple: 'a Tuple -> 'a Tuple /// /// Rewrites a node, given a rewriter for the sequence items. /// - abstract SequenceItem: context:'context * mapper:('context * 'a -> 'a) * item:'a SequenceItem -> 'a SequenceItem - default 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 SequenceItem: context: 'context * mapper: ('context * 'a -> 'a) * item: 'a SequenceItem -> 'a SequenceItem /// /// Rewrites a node, given a rewriter for the operand. /// - abstract PrefixOperator: context:'context - * mapper:('context * 'a -> 'a) - * operator:'a PrefixOperator - -> 'a PrefixOperator - default PrefixOperator: context:'context - * mapper:('context * 'a -> 'a) - * operator:'a PrefixOperator - -> 'a PrefixOperator + abstract PrefixOperator: + context: 'context * mapper: ('context * 'a -> 'a) * operator: 'a PrefixOperator -> 'a PrefixOperator + default PrefixOperator: + context: 'context * mapper: ('context * 'a -> 'a) * operator: 'a PrefixOperator -> 'a PrefixOperator /// /// Rewrites a node, given a rewriter for the operand. /// - abstract PostfixOperator: context:'context - * mapper:('context * 'a -> 'a) - * operator:'a PostfixOperator - -> 'a PostfixOperator - default PostfixOperator: context:'context - * mapper:('context * 'a -> 'a) - * operator:'a PostfixOperator - -> 'a PostfixOperator + abstract PostfixOperator: + context: 'context * mapper: ('context * 'a -> 'a) * operator: 'a PostfixOperator -> 'a PostfixOperator + default PostfixOperator: + context: 'context * mapper: ('context * 'a -> 'a) * operator: 'a PostfixOperator -> 'a PostfixOperator /// /// Rewrites an node, given a rewriter for the operands. /// - abstract InfixOperator: context:'context - * mapper:('context * 'a -> 'a) - * operator:'a InfixOperator - -> 'a InfixOperator - default InfixOperator: context:'context - * mapper:('context * 'a -> 'a) - * operator:'a InfixOperator - -> 'a InfixOperator + abstract InfixOperator: + context: 'context * mapper: ('context * 'a -> 'a) * operator: 'a InfixOperator -> 'a InfixOperator + default InfixOperator: + context: 'context * mapper: ('context * 'a -> 'a) * operator: 'a InfixOperator -> 'a InfixOperator /// /// Rewrites a node. /// - abstract Terminal: context:'context * terminal:Terminal -> Terminal - default Terminal: context:'context * terminal:Terminal -> Terminal + abstract Terminal: context: 'context * terminal: Terminal -> Terminal + default Terminal: context: 'context * terminal: Terminal -> Terminal diff --git a/src/QsFmt/Formatter/SyntaxTree/Statement.fsi b/src/QsFmt/Formatter/SyntaxTree/Statement.fsi index 18f81caea8..d2465ef071 100644 --- a/src/QsFmt/Formatter/SyntaxTree/Statement.fsi +++ b/src/QsFmt/Formatter/SyntaxTree/Statement.fsi @@ -6,12 +6,11 @@ namespace Microsoft.Quantum.QsFmt.Formatter.SyntaxTree /// A declaration for a new parameter. type internal ParameterDeclaration = { - /// The name of the parameter. - Name: Terminal + /// The name of the parameter. + Name: Terminal - /// The type of the parameter. - Type: TypeAnnotation - } + /// The type of the parameter. + Type: TypeAnnotation } /// A binding for one or more new parameters. type internal ParameterBinding = @@ -33,40 +32,38 @@ module internal SymbolBinding = /// /// Maps a symbol binding by applying to its leftmost terminal's trivia prefix. /// - val mapPrefix: mapper:(Trivia list -> Trivia list) -> SymbolBinding -> SymbolBinding + val mapPrefix: mapper: (Trivia list -> Trivia list) -> SymbolBinding -> SymbolBinding /// Initializer for a single qubit. type internal SingleQubit = { - /// - /// The Qubit type. - /// - Qubit: Terminal + /// + /// The Qubit type. + /// + Qubit: Terminal - /// The opening parenthesis. - OpenParen: Terminal + /// The opening parenthesis. + OpenParen: Terminal - /// The closing parenthesis. - CloseParen: Terminal - } + /// The closing parenthesis. + CloseParen: Terminal } /// Initializer for an array of qubits. type internal QubitArray = { - /// - /// The Qubit type. - /// - Qubit: Terminal + /// + /// The Qubit type. + /// + Qubit: Terminal - /// The opening bracket. - OpenBracket: Terminal + /// The opening bracket. + OpenBracket: Terminal - /// The length of the created array. - Length: Expression + /// The length of the created array. + Length: Expression - /// The closing bracket. - CloseBracket: Terminal - } + /// The closing bracket. + CloseBracket: Terminal } /// An initializer for one or more qubits. type internal QubitInitializer = @@ -82,21 +79,20 @@ type internal QubitInitializer = /// A qubit binding statement. type internal QubitBinding = { - /// The symbol binding. - Name: SymbolBinding + /// The symbol binding. + Name: SymbolBinding - /// The equals symbol. - Equals: Terminal + /// The equals symbol. + Equals: Terminal - /// The qubit initializer. - Initializer: QubitInitializer - } + /// The qubit initializer. + Initializer: QubitInitializer } module internal QubitBinding = /// /// Maps by applying to its leftmost terminal's trivia prefix. /// - val mapPrefix: mapper:(Trivia list -> Trivia list) -> binding: QubitBinding -> QubitBinding + val mapPrefix: mapper: (Trivia list -> Trivia list) -> binding: QubitBinding -> QubitBinding /// The kind of qubit declaration. type internal QubitDeclarationKind = @@ -114,65 +110,61 @@ type internal QubitDeclarationKind = /// The binding for a for-loop variable. type internal ForBinding = { - /// The symbol binding. - Name: SymbolBinding + /// The symbol binding. + Name: SymbolBinding - /// The in keyword. - In: Terminal + /// The in keyword. + In: Terminal + + /// The value of the symbol binding. + Value: Expression } - /// The value of the symbol binding. - Value: Expression - } - module internal ForBinding = /// /// Maps by applying to its leftmost terminal's trivia prefix. /// - val mapPrefix: mapper:(Trivia list -> Trivia list) -> binding: ForBinding -> ForBinding + val mapPrefix: mapper: (Trivia list -> Trivia list) -> binding: ForBinding -> ForBinding /// /// An expression statement. /// type internal ExpressionStatement = { - /// The inner expression of the statement. - Expression: Expression + /// The inner expression of the statement. + Expression: Expression - /// The semicolon. - Semicolon: Terminal - } + /// The semicolon. + Semicolon: Terminal } /// A simple statement consisting of just a keyword, an expression, and a semicolon. type internal SimpleStatement = { - /// The keyword for the statement. - Keyword: Terminal + /// The keyword for the statement. + Keyword: Terminal - /// The returned expression. - Expression: Expression + /// The returned expression. + Expression: Expression - /// The semicolon. - Semicolon: Terminal - } + /// The semicolon. + Semicolon: Terminal } /// A statement used to bind a value to a symbol. type internal BindingStatement = { - /// The keyword for the statement. - Keyword: Terminal + /// The keyword for the statement. + Keyword: Terminal - /// The symbol binding. - Binding: SymbolBinding + /// The symbol binding. + Binding: SymbolBinding - /// The equals symbol. - Equals: Terminal + /// The equals symbol. + Equals: Terminal - /// The value of the symbol binding. - Value: Expression + /// The value of the symbol binding. + Value: Expression - /// The semicolon. - Semicolon: Terminal - } + /// The semicolon. + Semicolon: Terminal } /// /// An update statement, also known as an evaluate-and-reassign statement. @@ -180,101 +172,96 @@ type internal BindingStatement = /// type internal UpdateStatement = { - /// - /// The set keyword. - /// - SetKeyword: Terminal + /// + /// The set keyword. + /// + SetKeyword: Terminal - /// The identifier being updated. - Name: Terminal + /// The identifier being updated. + Name: Terminal - /// The update operator, e.g. +=. - Operator: Terminal + /// The update operator, e.g. +=. + Operator: Terminal - /// The value used as the left-hand side of the update operator. - Value: Expression + /// The value used as the left-hand side of the update operator. + Value: Expression - /// The semicolon. - Semicolon: Terminal - } + /// The semicolon. + Semicolon: Terminal } /// /// A set w/= statement, also known as an evaluate-and-reassign statement. /// type internal UpdateWithStatement = { - /// - /// The set keyword. - /// - SetKeyword: Terminal + /// + /// The set keyword. + /// + SetKeyword: Terminal - /// The identifier being updated. - Name: Terminal + /// The identifier being updated. + Name: Terminal - /// - /// The w/= operator. - /// - With: Terminal + /// + /// The w/= operator. + /// + With: Terminal - /// The expression for the index that is updated. - Item: Expression + /// The expression for the index that is updated. + Item: Expression - /// The left arrow symbol. - Arrow: Terminal + /// The left arrow symbol. + Arrow: Terminal - /// The value used as the left-hand side of the update operator. - Value: Expression + /// The value used as the left-hand side of the update operator. + Value: Expression - /// The semicolon. - Semicolon: Terminal - } + /// The semicolon. + Semicolon: Terminal } /// A statement consisting of a keyword, a condition, and a block. type internal ConditionalBlockStatement = { - - /// The keyword for the statement. - Keyword: Terminal - /// The condition under which to execute the block. - Condition: Expression + /// The keyword for the statement. + Keyword: Terminal + + /// The condition under which to execute the block. + Condition: Expression - /// The conditional block. - Block: Statement Block - } + /// The conditional block. + Block: Statement Block } /// A statement consisting of a keyword and a block. and internal BlockStatement = { - /// The keyword for the statement. - Keyword: Terminal + /// The keyword for the statement. + Keyword: Terminal + + /// The block. + Block: Statement Block } - /// The block. - Block: Statement Block - } - /// /// A for statement. /// and internal ForStatement = { - /// - /// The for keyword. - /// - ForKeyword: Terminal + /// + /// The for keyword. + /// + ForKeyword: Terminal - /// The optional open parenthesis. - OpenParen: Terminal option + /// The optional open parenthesis. + OpenParen: Terminal option - /// The binding for loop variable. - Binding: ForBinding + /// The binding for loop variable. + Binding: ForBinding - /// The optional close parenthesis. - CloseParen: Terminal option + /// The optional close parenthesis. + CloseParen: Terminal option - /// The loop body. - Block: Statement Block - } + /// The loop body. + Block: Statement Block } /// /// The concluding section of an until statement. @@ -283,7 +270,7 @@ and internal UntilStatementCoda = /// The semicolon. | Semicolon of Terminal - + /// /// The fixup of an until statement. /// @@ -292,23 +279,22 @@ and internal UntilStatementCoda = /// /// An until statement. /// -and internal UntilStatement = +and internal UntilStatement = { - /// - /// The until keyword. - /// - UntilKeyword: Terminal - - /// - /// The condition under which to exit the preceding repeat block. - /// - Condition: Expression - - /// - /// The concluding section, possibly containing a fixup block. - /// - Coda: UntilStatementCoda - } + /// + /// The until keyword. + /// + UntilKeyword: Terminal + + /// + /// The condition under which to exit the preceding repeat block. + /// + Condition: Expression + + /// + /// The concluding section, possibly containing a fixup block. + /// + Coda: UntilStatementCoda } /// The concluding section of a qubit declaration. and internal QubitDeclarationStatementCoda = @@ -322,24 +308,23 @@ and internal QubitDeclarationStatementCoda = /// A qubit declaration statement. and internal QubitDeclarationStatement = { - /// The kind of qubit declaration. - Kind: QubitDeclarationKind + /// The kind of qubit declaration. + Kind: QubitDeclarationKind - /// The keyword used in the declaration. - Keyword: Terminal + /// The keyword used in the declaration. + Keyword: Terminal - /// Optional open parentheses. - OpenParen: Terminal option + /// Optional open parentheses. + OpenParen: Terminal option - /// The qubit binding. - Binding: QubitBinding + /// The qubit binding. + Binding: QubitBinding - /// Optional close parentheses. - CloseParen: Terminal option + /// Optional close parentheses. + CloseParen: Terminal option - /// The concluding section. - Coda: QubitDeclarationStatementCoda - } + /// The concluding section. + Coda: QubitDeclarationStatementCoda } /// A statement. and internal Statement = @@ -371,7 +356,7 @@ and internal Statement = /// A set statement. /// | SetStatement of BindingStatement - + /// /// An update statement, also known as an evaluate-and-reassign statement. /// e.g. set x += 3; @@ -438,4 +423,4 @@ module internal Statement = /// /// Maps a statement by applying to its leftmost terminal's trivia prefix. /// - val mapPrefix: mapper:(Trivia list -> Trivia list) -> Statement -> Statement + val mapPrefix: mapper: (Trivia list -> Trivia list) -> Statement -> Statement diff --git a/src/QsFmt/Formatter/SyntaxTree/Type.fsi b/src/QsFmt/Formatter/SyntaxTree/Type.fsi index 3cbdd8d73d..18c2d8b9ea 100644 --- a/src/QsFmt/Formatter/SyntaxTree/Type.fsi +++ b/src/QsFmt/Formatter/SyntaxTree/Type.fsi @@ -6,15 +6,14 @@ namespace Microsoft.Quantum.QsFmt.Formatter.SyntaxTree /// A parenthesized characteristic. type internal CharacteristicGroup = { - /// The opening parenthesis. - OpenParen: Terminal + /// The opening parenthesis. + OpenParen: Terminal - /// The characteristic. - Characteristic: Characteristic + /// The characteristic. + Characteristic: Characteristic - /// The closing parenthesis. - CloseParen: Terminal - } + /// The closing parenthesis. + CloseParen: Terminal } /// A callable characteristic. and internal Characteristic = @@ -33,43 +32,40 @@ and internal Characteristic = /// A section attached to a callable type or declaration describing its characteristics. type internal CharacteristicSection = { - /// - /// The is keyword. - /// - IsKeyword: Terminal + /// + /// The is keyword. + /// + IsKeyword: Terminal - /// The characteristic. - Characteristic: Characteristic - } + /// The characteristic. + Characteristic: Characteristic } /// An array type. and internal ArrayType = { - /// The type of items in the array. - ItemType: Type + /// The type of items in the array. + ItemType: Type - /// The opening bracket. - OpenBracket: Terminal + /// The opening bracket. + OpenBracket: Terminal - /// The closing bracket. - CloseBracket: Terminal - } + /// The closing bracket. + CloseBracket: Terminal } /// A callable type. and internal CallableType = { - /// The input type. - FromType: Type + /// The input type. + FromType: Type - /// The arrow separating input and output types. - Arrow: Terminal + /// The arrow separating input and output types. + Arrow: Terminal - /// The output type. - ToType: Type + /// The output type. + ToType: Type - /// The characteristics. - Characteristics: CharacteristicSection option - } + /// The characteristics. + Characteristics: CharacteristicSection option } /// A type. and internal Type = @@ -100,9 +96,8 @@ and internal Type = /// A type annotation attached to a binding. type internal TypeAnnotation = { - /// The colon between the binding and the type. - Colon: Terminal + /// The colon between the binding and the type. + Colon: Terminal - /// The type of the binding. - Type: Type - } + /// The type of the binding. + Type: Type } diff --git a/src/Telemetry/Samples/FSharp/Program.fs b/src/Telemetry/Samples/FSharp/Program.fs index d63ec4477c..a804206393 100644 --- a/src/Telemetry/Samples/FSharp/Program.fs +++ b/src/Telemetry/Samples/FSharp/Program.fs @@ -151,7 +151,7 @@ let main args = SampleObjectToBeSerialized = Map [ ("key1", "value1") ("key2", "value2") ] - SampleObjectToBeIgnored = [ 1 .. 10 ] + SampleObjectToBeIgnored = [ 1..10 ] SampleGuid = Guid.NewGuid() SampleException = createExceptionWithStackTrace true SampleOptionWithValue = Some 123