Skip to content

Commit

Permalink
Use string interpolation instead of sprintf
Browse files Browse the repository at this point in the history
  • Loading branch information
Tarmil committed Nov 13, 2020
1 parent dd804a5 commit baf6771
Show file tree
Hide file tree
Showing 21 changed files with 108 additions and 114 deletions.
2 changes: 1 addition & 1 deletion src/Bolero.Server/RazorHost.fs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ type RazorHostingExtensions =
[<Extension>]
static member RenderBoleroScript(html: IHtmlHelper, config: IBoleroHostConfig) =
let k = if config.IsServer then "server" else "webassembly"
html.Raw(sprintf """<script src="_framework/blazor.%s.js"></script>""" k)
html.Raw($"""<script src="_framework/blazor.{k}.js"></script>""")

[<Extension>]
static member AddBoleroHost(this: IServiceCollection, ?server: bool, ?prerendered: bool, ?devToggle: bool) =
Expand Down
2 changes: 1 addition & 1 deletion src/Bolero.Server/Remoting.fs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ type internal ServerRemoteProvider(services: seq<RemotingService>) =
None
)
|> Option.defaultWith (fun () ->
failwithf "Remote service not registered: %s" typeof<'T>.FullName)
failwith $"Remote service not registered: {typeof<'T>.FullName}")

interface IRemoteProvider with

Expand Down
10 changes: 5 additions & 5 deletions src/Bolero.Templating.Provider/ConvertExpr.fs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ let WrapExpr (innerType: Parsing.HoleType) (outerType: Parsing.HoleType) (expr:
<@@ Node.Text ((%%expr: obj * Action<ChangeEventArgs>).Item1.ToString()) @@>
| Parsing.AttributeValue, Parsing.DataBinding _ ->
<@@ (%%expr: obj * Action<ChangeEventArgs>).Item1.ToString() @@>
| a, b -> failwithf "Hole name used multiple times with incompatible types (%A, %A)" a b
| a, b -> failwith $"Hole name used multiple times with incompatible types ({a}, {b})"
|> Some

/// Map an expression's vars from its parent, wrapping the expression in let declarations.
Expand Down Expand Up @@ -87,7 +87,7 @@ let rec ConvertAttrTextPart (vars: Map<string, Expr>) (text: Parsing.Expr) : Exp
| Parsing.WrapVars (subst, text) ->
WrapAndConvert vars subst ConvertAttrTextPart text
| Parsing.Fst _ | Parsing.Snd _ | Parsing.Attr _ | Parsing.Elt _ ->
failwithf "Invalid text: %A" text
failwith $"Invalid text: {text}"

let rec ConvertAttrValue (vars: Map<string, Expr>) (text: Parsing.Expr) : Expr<obj> =
let box e = Expr.Coerce(e, typeof<obj>) |> Expr.Cast
Expand All @@ -106,7 +106,7 @@ let rec ConvertAttrValue (vars: Map<string, Expr>) (text: Parsing.Expr) : Expr<o
| Parsing.WrapVars (subst, text) ->
WrapAndConvert vars subst ConvertAttrValue text
| Parsing.Attr _ | Parsing.Elt _ ->
failwithf "Invalid attr value: %A" text
failwith $"Invalid attr value: {text}"

let rec ConvertAttr (vars: Map<string, Expr>) (attr: Parsing.Expr) : Expr<Attr> =
match attr with
Expand All @@ -121,7 +121,7 @@ let rec ConvertAttr (vars: Map<string, Expr>) (attr: Parsing.Expr) : Expr<Attr>
| Parsing.WrapVars (subst, attr) ->
WrapAndConvert vars subst ConvertAttr attr
| Parsing.Fst _ | Parsing.Snd _ | Parsing.PlainHtml _ | Parsing.Elt _ ->
failwithf "Invalid attribute: %A" attr
failwith $"Invalid attribute: {attr}"

let rec ConvertNode (vars: Map<string, Expr>) (node: Parsing.Expr) : Expr<Node> =
match node with
Expand All @@ -139,5 +139,5 @@ let rec ConvertNode (vars: Map<string, Expr>) (node: Parsing.Expr) : Expr<Node>
| Parsing.WrapVars (subst, node) ->
WrapAndConvert vars subst ConvertNode node
| Parsing.Fst _ | Parsing.Snd _ | Parsing.Attr _ ->
failwithf "Invalid node: %A" node
failwith $"Invalid node: {node}"

4 changes: 2 additions & 2 deletions src/Bolero.Templating.Provider/Parsing.fs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ module HoleType =
| Event _, Event _ -> Event typeof<EventArgs>
| DataBinding valType, (String | Html | AttributeValue)
| (String | Html | AttributeValue), DataBinding valType -> DataBinding valType
| _ -> failwithf "Hole name used multiple times with incompatible types: %s" holeName
| _ -> failwith $"Hole name used multiple times with incompatible types: {holeName}"

/// Get the .NET type of the event handler argument for the given event name.
let EventArg (name: string) : Type =
Expand Down Expand Up @@ -359,7 +359,7 @@ let ParseDoc (filename: option<string>) (doc: HtmlDocument) : ParsedTemplates =
|> Seq.map (fun n ->
match n.GetAttributeValue("id", null) with
| null ->
failwithf "Nested template must have an id" // at %i:%i" n.Line n.LinePosition
failwith "Nested template must have an id" // at {n.Line}:{n.LinePosition}"
| id ->
let parsed = ParseOneTemplate n.ChildNodes
n.Remove()
Expand Down
2 changes: 1 addition & 1 deletion src/Bolero.Templating.Provider/Path.fs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ let GetRelativePath (baseDir: string) (fullPath: string) =
if thisDir = baseDir then
fullPath.[thisDir.Length + 1..]
elif thisDir.Length <= baseDir.Length then
invalidArg "fullPath" (sprintf "'%s' is not a subdirectory of '%s'" fullPath baseDir)
invalidArg "fullPath" $"'{fullPath}' is not a subdirectory of '{baseDir}'"
else
go (Path.GetDirectoryName thisDir)
go fullPath
4 changes: 2 additions & 2 deletions src/Bolero.Templating.Provider/Provider.fs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ type Template (cfg: TypeProviderConfig) as this =
CodeGen.Populate ty pathOrHtml cfg.ResolutionFolder
asm.AddTypes([ty])
ty
| x -> failwithf "Unexpected parameter values: %A" x
| x -> failwith $"Unexpected parameter values: {x}"
)
templateTy.AddXmlDoc("\
Provide content from a template HTML file.\n\
Expand All @@ -57,4 +57,4 @@ type Template (cfg: TypeProviderConfig) as this =
with exn ->
// Put the full error, including stack, in the message
// so that it shows up in the compiler output.
failwithf "%A" exn
failwith $"{exn}"
2 changes: 1 addition & 1 deletion src/Bolero/Remoting.fs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ type RemotingExtensions =
/// [omit]
static member ExtractRemoteMethods(ty: Type) : Result<RemoteMethodDefinition[], list<string>> =
if not (FSharpType.IsRecord ty) then
Error [sprintf "Remote type must be a record: %s" ty.FullName]
Error [$"Remote type must be a record: {ty.FullName}"]
else
let fields = FSharpType.GetRecordFields(ty, true)
(fields, Ok [])
Expand Down
38 changes: 17 additions & 21 deletions src/Bolero/Render.fs
Original file line number Diff line number Diff line change
Expand Up @@ -38,35 +38,31 @@ type ElementReference = Microsoft.AspNetCore.Components.ElementReference
type RenderTreeBuilder(b: BlazorTreeBuilder, indent: int, out: TextWriter) =
let mutable indent = indent

let write fmt =
Printf.kprintf (fun s ->
out.Write(Array.create (indent * 2) ' ')
out.Write(s)
out.Flush()
) fmt

let writen fmt =
Printf.kprintf (fun s ->
out.Write(Array.create (indent * 2) ' ')
out.WriteLine(s)
out.Flush()
) fmt
let write (s: string) =
out.Write(Array.create (indent * 2) ' ')
out.Write(s)
out.Flush()

let writen (s: string) =
out.Write(Array.create (indent * 2) ' ')
out.WriteLine(s)
out.Flush()

member this.AddContent(sequence: int, text: string) =
if not (isNull b) then b.AddContent(sequence, text)
writen "Text %i %s" sequence text
writen $"Text {sequence} {text}"

member this.AddContent(sequence: int, frag: RenderFragment) =
if not (isNull b) then b.AddContent(sequence, frag.Frag)
write "Frag %i\n%s" sequence (frag.Show(indent + 1))
write $"Frag {sequence}\n{frag.Show(indent + 1)}"

member this.AddMarkupContent(sequence: int, markup: string) =
if not (isNull b) then b.AddMarkupContent(sequence, markup)
writen "Markup %i %s" sequence markup
writen $"Markup {sequence} {markup}"

member this.OpenElement(sequence: int, name: string) =
if not (isNull b) then b.OpenElement(sequence, name)
writen "OpenElt %i %s" sequence name
writen $"OpenElt {sequence} {name}"
indent <- indent + 1

member this.CloseElement() =
Expand All @@ -76,7 +72,7 @@ type RenderTreeBuilder(b: BlazorTreeBuilder, indent: int, out: TextWriter) =

member this.OpenComponent(sequence: int, ty: Type) =
if not (isNull b) then b.OpenComponent(sequence, ty)
writen "OpenComp %i %s" sequence ty.FullName
writen $"OpenComp {sequence} {ty.FullName}"
indent <- indent + 1

member this.CloseComponent() =
Expand All @@ -88,14 +84,14 @@ type RenderTreeBuilder(b: BlazorTreeBuilder, indent: int, out: TextWriter) =
match value with
| :? RenderFragment as f ->
if not (isNull b) then b.AddAttribute(sequence, name, f.Frag)
writen "Attr %i %s\n%s" sequence name (f.Show(indent + 1))
writen $"Attr {sequence} {name}\n{f.Show(indent + 1)}"
| value ->
if not (isNull b) then b.AddAttribute(sequence, name, value)
writen "Attr %i %s %A" sequence name value
writen $"Attr {sequence} {name} {value}"

member this.AddElementReferenceCapture(sequence: int, r: Action<ElementReference>) =
b.AddElementReferenceCapture(sequence, r)
writen "ElementReference %i" sequence
writen $"ElementReference {sequence}"

and RenderFragment(f: RenderTreeBuilder -> unit) =
member this.Frag : BlazorFragment =
Expand Down
21 changes: 9 additions & 12 deletions src/Bolero/Router.fs
Original file line number Diff line number Diff line change
Expand Up @@ -109,28 +109,25 @@ type InvalidRouterKind =
/// [category: Routing]
exception InvalidRouter of kind: InvalidRouterKind with
override this.Message =
let withCase (case: UnionCaseInfo) =
sprintf "Invalid router defined for union case %s.%s: %s"
case.DeclaringType.FullName case.Name
let withCase (case: UnionCaseInfo) s =
$"Invalid router defined for union case {case.DeclaringType.FullName}.{case.Name}: %s{s}"
match this.kind with
| InvalidRouterKind.UnsupportedType ty ->
"Unsupported route type: " + ty.FullName
| InvalidRouterKind.ParameterSyntax(case, field) ->
withCase case ("Invalid parameter syntax: " + field)
withCase case $"Invalid parameter syntax: {field}"
| InvalidRouterKind.DuplicateField(case, field) ->
withCase case ("Field duplicated in the path: " + field)
withCase case $"Field duplicated in the path: {field}"
| InvalidRouterKind.UnknownField(case, field) ->
withCase case ("Unknown field in the path: " + field)
withCase case $"Unknown field in the path: {field}"
| InvalidRouterKind.MissingField(case, field) ->
withCase case ("Missing field in the path: " + field)
withCase case $"Missing field in the path: {field}"
| InvalidRouterKind.ParameterTypeMismatch(case, field, otherCase, otherField) ->
withCase case (sprintf "Parameter %s at the same path position as %s's %s but has a different type"
field otherCase.Name otherField)
withCase case $"Parameter {field} at the same path position as {otherCase.Name}'s {otherField} but has a different type"
| InvalidRouterKind.ModifierMismatch(case, field, otherCase, otherField) ->
withCase case (sprintf "Parameter %s at the same path position as %s's %s but has a different modifier"
field otherCase.Name otherField)
withCase case $"Parameter {field} at the same path position as {otherCase.Name}'s {otherField} but has a different modifier"
| InvalidRouterKind.IdenticalPath(case, otherCase) ->
withCase case ("Matches the exact same path as " + otherCase.Name)
withCase case $"Matches the exact same path as {otherCase.Name}"
| InvalidRouterKind.RestNotLast case ->
withCase case "{*rest} parameter must be the last fragment"
| InvalidRouterKind.InvalidRestType case ->
Expand Down
18 changes: 9 additions & 9 deletions tests/Client/Main.fs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ let update message model =
| Submit -> { model with submitted = Some model.input }, []
| RemoveItem k -> { model with items = Map.filter (fun k' _ -> k' <> k) model.items }, []
| SetAddKey i -> { model with addKey = i }, []
| AddKey -> { model with items = Map.add model.addKey (sprintf "it's %i" model.addKey) model.items }, []
| AddKey -> { model with items = Map.add model.addKey $"it's {model.addKey}" model.items }, []
| SetKeyOf k ->
match Map.tryFind k model.items with
| None -> model, []
Expand Down Expand Up @@ -151,7 +151,7 @@ let viewForm (js: IJSRuntime) model dispatch =
)
attr.style (if model.input = "" then "color:gray;" else null)
]
div [] [textf "selected radio item: %A" model.radioItem]
div [] [text $"selected radio item: {model.radioItem}"]
forEach {1..10} <| fun ix ->
input [
attr.``type`` "radio"
Expand Down Expand Up @@ -181,7 +181,7 @@ let viewForm (js: IJSRuntime) model dispatch =
SecretPw()
.Kind(b [] [text "secret"])
.Clear(fun _ -> dispatch (SetInput ""))
.DblClick(fun e -> dispatch (SetInput (sprintf "(%f, %f)" e.ClientX e.ClientY)))
.DblClick(fun e -> dispatch (SetInput $"({e.ClientX}, {e.ClientY})"))
.Input(model.input, fun s -> dispatch (SetInput s))
.Value(model.addKey, fun k -> dispatch (SetAddKey k))
.Elt()
Expand Down Expand Up @@ -236,22 +236,22 @@ type ViewItemPage() =
p [] [
text "Model: "
button [on.click (fun _ -> dispatch (SetPage (Item (k, { Model = m - 1 }))))] [text "-"]
textf "%i" m
text $"{m}"
button [on.click (fun _ -> dispatch (SetPage (Item (k, { Model = m + 1 }))))] [text "+"]
]
]

let viewLazy model dispatch =
let lazyViewFunction = (fun m -> text (sprintf "Lazy values: (%i,%s), re-render random number check: %i" m.value m.nonEqVal (System.Random().Next())))
let lazyViewFunction = (fun m -> text $"Lazy values: ({m.value},{m.nonEqVal}), re-render random number check: {System.Random().Next()}")
div [] [
pre [] [
text """
let viewLazy model dispatch =
div [] [
p [] [button [on.click (fun _ -> dispatch IncNonLazyVal)] [text "Increase non-lazy value"]]
p [] [button [on.click (fun _ -> dispatch IncLazyVal)] [text "Increase lazy value"]]
p [] [text (sprintf "Non-lazy value: %i, re-render random number check: %i" model.nonLazyValue (System.Random().Next()))]
p [] [lazyComp (fun m -> text (sprintf "Lazy value: %i, re-render random number check: %i" m.value (System.Random().Next()))) model.lazyModel]
p [] [text $"Non-lazy value: {model.nonLazyValue}, re-render random number check: {System.Random().Next()}"]
p [] [lazyComp (fun m -> text $"Lazy values: ({m.value},{m.nonEqVal}), re-render random number check: {System.Random().Next()}") model.lazyModel]
]
"""
]
Expand All @@ -263,7 +263,7 @@ let viewLazy model dispatch =
on.change (fun e -> e.Value |> string |> SetLazyNonEqVal |> dispatch)
]
]
p [] [text (sprintf "Non-lazy value: %i, re-render random number check: %i" model.nonLazyValue (System.Random().Next()))]
p [] [text $"Non-lazy value: {model.nonLazyValue}, re-render random number check: {System.Random().Next()}"]
p [] [lazyComp lazyViewFunction model.lazyModel]
p [] [lazyCompWith (fun m1 m2 -> m1.value = m2.value) lazyViewFunction model.lazyModel]
p [] [lazyCompBy (fun m -> (m.value, m.value2)) lazyViewFunction model.lazyModel]
Expand Down Expand Up @@ -295,5 +295,5 @@ type MyApp() =
override this.Program =
Program.mkProgram (fun _ -> initModel(), []) update (view this.JSRuntime)
//|> Program.withConsoleTrace
|> Program.withErrorHandler (fun (msg, exn) -> printfn "%s: %A" msg exn)
|> Program.withErrorHandler (fun (msg, exn) -> printfn $"{msg}: {exn}")
|> Program.withRouter router
6 changes: 3 additions & 3 deletions tests/Remoting.Client/Main.fs
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ let router : Router<Page, Model, Message> =
getEndPoint = fun m -> m.page
getRoute = function
| Home -> "/"
| Custom i -> sprintf "/custom/%i" i
| Custom i -> $"/custom/{i}"
setRoute = fun s ->
match s.Trim('/').Split('/') with
| [|""|] -> Some (SetPage Home)
Expand Down Expand Up @@ -189,7 +189,7 @@ let Display model dispatch =
]
| Some login ->
concat [
textf "Logged in as %s" login
text "Logged in as {login}"
button [on.click (fun _ -> dispatch Logout)] [text "Log out"]
]
hr []
Expand All @@ -210,7 +210,7 @@ let Display model dispatch =
comp<AuthorizeView> [
attr.fragmentWith "Authorized" <| fun (context: AuthenticationState) ->
printfn "Rendering Authorized"
div [] [textf "You're authorized! Welcome %s" context.User.Identity.Name]
div [] [text $"You're authorized! Welcome {context.User.Identity.Name}"]
attr.fragmentWith "NotAuthorized" <| fun (_: AuthenticationState) ->
printfn "Rendering NotAuthorized"
div [] [text "You're not authorized :("]
Expand Down
4 changes: 2 additions & 2 deletions tests/Server/Properties/launchSettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:52982/",
"sslPort": 0
"applicationUrl": "http://localhost:54002/",
"sslPort": 44338
}
},
"profiles": {
Expand Down
2 changes: 1 addition & 1 deletion tests/Unit.Client/Elmish.fs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ type IntInput() =
attr.value model
on.input (fun e -> dispatch (int (e.Value :?> string)))
]
span [attr.classes ["intValue-repeat"]] [textf "%i" model]
span [attr.classes ["intValue-repeat"]] [text $"{model}"]
]

let view model dispatch =
Expand Down
Loading

0 comments on commit baf6771

Please sign in to comment.