Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit12b0427

Browse files
forkiKevinRansom
authored andcommitted
Don't call length if not needed (#2989)
* Don't call length if not needed* Use hasLengthGreaterThen* Use isNilOrSingleton* Use isNilOrSingleton* no double negations are not bad
1 parent6fe7536 commit12b0427

File tree

10 files changed

+55
-36
lines changed

10 files changed

+55
-36
lines changed

‎src/absil/illib.fs‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,20 @@ let (>>>&) (x:int32) (n:int32) = int32 (uint32 x >>> n)
2323
letnotlazy v= Lazy<_>.CreateFromValue v
2424

2525
let inlineisNil l= List.isEmpty l
26+
27+
/// Returns true if the list has less than 2 elements. Otherwise false.
28+
let inlineisNilOrSingleton l=
29+
match lwith
30+
|[]
31+
|[_]->true
32+
|_->false
33+
34+
/// Returns true if the list contains exactly 1 element. Otherwise false.
35+
let inlineisSingleton l=
36+
match lwith
37+
|[_]->true
38+
|_->false
39+
2640
let inlineisNonNull x=not(isNull x)
2741
let inlinenonNull msg x=if isNull xthen failwith("null:"^ msg)else x
2842
let(===) x y= LanguagePrimitives.PhysicalEquality x y

‎src/absil/ilreflect.fs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -301,7 +301,7 @@ module Zmap =
301301
letforce x m str=match Zmap.tryFind x mwith Some y-> y| None-> failwithf"Zmap.force:%s: x =%+A" str x
302302

303303
letequalTypes(s:Type)(t:Type)= s.Equals(t)
304-
letequalTypeLists ss tt=List.lengthsEqAndForall2 equalTypes ss tt
304+
letequalTypeLists ss tt= List.lengthsEqAndForall2 equalTypes ss tt
305305

306306
letgetGenericArgumentsOfType(typT:Type)=
307307
if typT.IsGenericTypethen typT.GetGenericArguments()else[||]

‎src/fsharp/IlxGen.fs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4383,7 +4383,7 @@ and GenDecisionTreeSwitch cenv cgbuf inplabOpt stackAtTargets eenv e cases defau
43834383
| DecisionTreeTest.ArrayLength_
43844384
| DecisionTreeTest.IsNull
43854385
| DecisionTreeTest.Const(Const.Zero)->
4386-
ifList.length cases<>1|| Option.isNone defaultTargetOptthen failwith"internal error: GenDecisionTreeSwitch: DecisionTreeTest.IsInst/isnull/query"
4386+
ifnot(isSingleton cases)|| Option.isNone defaultTargetOptthen failwith"internal error: GenDecisionTreeSwitch: DecisionTreeTest.IsInst/isnull/query"
43874387
letbi=
43884388
match firstDiscrimwith
43894389
| DecisionTreeTest.Const(Const.Zero)->
@@ -6808,7 +6808,7 @@ and GenExnDef cenv mgbuf eenv m (exnc:Tycon) =
68086808

68096809

68106810
letCodegenAssembly cenv eenv mgbuf fileImpls=
6811-
ifList.length fileImpls>0then
6811+
ifnot(isNil fileImpls)then
68126812
leta,b= List.frontAndBack fileImpls
68136813
leteenv= List.fold(GenTopImpl cenv mgbuf None) eenv a
68146814
let_eenv= GenTopImpl cenv mgbuf cenv.opts.mainMethodInfo eenv b

‎src/fsharp/MethodOverrides.fs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -305,12 +305,13 @@ module DispatchSlotChecking =
305305
|[]->
306306
noimpl()
307307
|[ Override(_,_,_,(mtps,_),argTys,_,_,_)as overrideBy]->
308-
letpossibleDispatchSlots=
308+
letmoreThanOnePossibleDispatchSlot=
309309
dispatchSlots
310310
|> List.filter(fun(RequiredSlot(dispatchSlot,_))-> IsNameMatch dispatchSlot overrideBy&& IsImplMatch g dispatchSlot overrideBy)
311-
|> List.length
311+
|> isNilOrSingleton
312+
|>not
312313

313-
ifpossibleDispatchSlots>1then
314+
ifmoreThanOnePossibleDispatchSlotthen
314315
// Error will be reported below in CheckOverridesAreAllUsedOnce
315316
()
316317

‎src/fsharp/NicePrint.fs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1468,7 +1468,7 @@ module private TastDefinitionPrinting =
14681468
letbreakTypeDefnEqn repr=
14691469
match reprwith
14701470
| TFSharpObjectRepr_->true
1471-
| TUnionRepr r-> r.CasesTable.UnionCasesAsList.Length>1
1471+
| TUnionRepr r->not(isNilOrSingletonr.CasesTable.UnionCasesAsList)
14721472
| TRecdRepr_->true
14731473
| TAsmRepr_
14741474
| TILObjectRepr_

‎src/fsharp/TastOps.fs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3342,7 +3342,7 @@ module DebugPrint = begin
33423342
| argtys->(prefixL^^ nmL^^ wordL(tagText"of"))--- layoutUnionCaseArgTypes argtys
33433343

33443344
letlayoutUnionCases ucases=
3345-
letprefixL=ifList.length ucases>1then wordL(tagText"|")else emptyL
3345+
letprefixL=ifnot(isNilOrSingleton ucases)then wordL(tagText"|")else emptyL
33463346
List.map(ucaseL prefixL) ucases
33473347

33483348
letlayoutRecdField(fld:RecdField)=
@@ -7457,7 +7457,7 @@ let mkChoiceTy (g:TcGlobals) m tinst =
74577457
match List.length tinstwith
74587458
|0-> g.unit_ty
74597459
|1-> List.head tinst
7460-
|_-> mkAppTy(mkChoiceTyconRef g m(List.length tinst)) tinst
7460+
|length-> mkAppTy(mkChoiceTyconRef g m length) tinst
74617461

74627462
letmkChoiceCaseRef g m n i=
74637463
mkUnionCaseRef(mkChoiceTyconRef g m n)("Choice"+string(i+1)+"Of"+string n)
@@ -8004,7 +8004,7 @@ let rec mkCompiledTuple g isStruct (argtys,args,m) =
80048004
elif n< maxTuplethen(mkCompiledTupleTyconRef g isStruct n, argtys, args, m)
80058005
else
80068006
letargtysA,argtysB= List.splitAfter goodTupleFields argtys
8007-
letargsA,argsB= List.splitAfter(goodTupleFields) args
8007+
letargsA,argsB= List.splitAfter goodTupleFields args
80088008
letty8,v8=
80098009
match argtysB,argsBwith
80108010
|[ty8],[arg8]->

‎src/fsharp/TypeChecker.fs‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -701,7 +701,7 @@ let UnifyRefTupleType contextInfo cenv denv m ty ps =
701701
let ptys =
702702
if isRefTupleTy cenv.g ty then
703703
let ptys = destRefTupleTy cenv.g ty
704-
if(List.length ps) =(List.length ptys) then ptys
704+
if List.length ps = List.length ptys then ptys
705705
else NewInferenceTypes ps
706706
else NewInferenceTypes ps
707707

@@ -719,7 +719,7 @@ let UnifyStructTupleType contextInfo cenv denv m ty ps =
719719
let ptys =
720720
if isStructTupleTy cenv.g ty then
721721
let ptys = destStructTupleTy cenv.g ty
722-
if(List.length ps) =(List.length ptys) then ptys
722+
if List.length ps = List.length ptys then ptys
723723
else NewInferenceTypes ps
724724
else NewInferenceTypes ps
725725
AddCxTypeEqualsType contextInfo denv cenv.css m ty (TType_tuple (tupInfoStruct, ptys))
@@ -2026,8 +2026,9 @@ let TcUnionCaseOrExnField cenv (env: TcEnv) ty1 m c n funcs =
20262026
| (Item.UnionCase _ | Item.ExnCase _) as item ->
20272027
ApplyUnionCaseOrExn funcs m cenv env ty1 item
20282028
| _ -> error(Error(FSComp.SR.tcUnknownUnion(),m))
2029-
if n >= List.length argtys then
2030-
error (UnionCaseWrongNumberOfArgs(env.DisplayEnv,List.length argtys,n,m))
2029+
let argstysLength = List.length argtys
2030+
if n >= argstysLength then
2031+
error (UnionCaseWrongNumberOfArgs(env.DisplayEnv,argstysLength,n,m))
20312032
let ty2 = List.item n argtys
20322033
mkf,ty2
20332034

@@ -5562,7 +5563,7 @@ and TcExprThen cenv overallTy env tpenv synExpr delayed =
55625563
PropagateThenTcDelayed cenv overallTy env tpenv synExpr.Range (MakeApplicableExprNoFlex cenv expr) exprty ExprAtomicFlag.NonAtomic delayed
55635564

55645565
and TcExprs cenv env m tpenv flexes argtys args =
5565-
if(List.length args<> List.length argtys) then error(Error(FSComp.SR.tcExpressionCountMisMatch((List.length argtys), (List.length args)),m))
5566+
if List.length args <> List.length argtys then error(Error(FSComp.SR.tcExpressionCountMisMatch((List.length argtys), (List.length args)),m))
55665567
(tpenv, List.zip3 flexes argtys args) ||> List.mapFold (fun tpenv (flex,ty,e) ->
55675568
TcExprFlex cenv flex ty env tpenv e)
55685569

@@ -9948,7 +9949,7 @@ and TcMethodArg cenv env (lambdaPropagationInfo,tpenv) (lambdaPropagationInfoF
99489949
if lambdaVarNum < numLambdaVars then
99499950
let col = [ for row in prefixOfLambdaArgsForEachOverload -> row.[lambdaVarNum] ]
99509951
// Check if all the rows give the same argument type
9951-
if col |> ListSet.setify (typeEquiv cenv.g) |>List.length |> ((=) 1) then
9952+
if col |> ListSet.setify (typeEquiv cenv.g) |>isSingleton then
99529953
let calledLambdaArgTy = col.[0]
99539954
// Force the caller to be a function type.
99549955
match UnifyFunctionTypeUndoIfFailed cenv env.DisplayEnv mArg callerLambdaTy with
@@ -10786,7 +10787,7 @@ and ApplyAbstractSlotInference (cenv:cenv) (envinner:TcEnv) (bindingTy,m,synTypa
1078610787

1078710788
| slots ->
1078810789
match dispatchSlotsArityMatch with
10789-
| meths when meths |> makeUniqueBySig |>List.length = 1 -> meths
10790+
| meths when meths |> makeUniqueBySig |>isSingleton -> meths
1079010791
| [] ->
1079110792
let details =
1079210793
slots
@@ -14182,8 +14183,8 @@ module TcExceptionDeclarations =
1418214183
match ResolveExprLongIdent cenv.tcSink cenv.nameResolver m ad env.eNameResEnv TypeNameResolutionInfo.Default longId with
1418314184
| Item.ExnCase exnc, [] ->
1418414185
CheckTyconAccessible cenv.amap m env.eAccessRights exnc |> ignore
14185-
ifList.lengthargs' <> 0 then
14186-
errorR (Error(FSComp.SR.tcExceptionAbbreviationsShouldNotHaveArgumentList(),m))
14186+
ifnot (isNilargs') then
14187+
errorR (Error(FSComp.SR.tcExceptionAbbreviationsShouldNotHaveArgumentList(),m))
1418714188
TExnAbbrevRepr exnc
1418814189
| Item.CtorGroup(_,meths) , [] ->
1418914190
// REVIEW: check this really is an exception type

‎src/fsharp/TypeRelations.fs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -285,7 +285,7 @@ let IteratedAdjustArityOfLambda g amap topValInfo e =
285285
lettps,ctorThisValOpt,baseValOpt,vsl,body,bodyty= destTopLambda g amap topValInfo(e, tyOfExpr g e)
286286
letarities= topValInfo.AritiesOfArgs
287287
if arities.Length<> vsl.Lengththen
288-
errorR(InternalError(sprintf"IteratedAdjustArityOfLambda, List.length arities =%d, List.length vsl =%d"(List.lengtharities)(List.length vsl), body.Range))
288+
errorR(InternalError(sprintf"IteratedAdjustArityOfLambda, List.length arities =%d, List.length vsl =%d" arities.Length vsl.Length, body.Range))
289289
letvsl,body= IteratedAdjustArityOfLambdaBody g arities vsl body
290290
tps,ctorThisValOpt,baseValOpt,vsl,body,bodyty
291291

‎src/fsharp/fsc.fs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,7 @@ let ProcessCommandLineFlags (tcConfigB: TcConfigBuilder, setProcessThreadLocals,
247247
ParseCompilerOptions(collect, GetCoreFscCompilerOptions tcConfigB, List.tail(PostProcessCompilerArgs abbrevArgs argv))
248248

249249
ifnot(tcConfigB.portablePDB|| tcConfigB.embeddedPDB)then
250-
if tcConfigB.embedAllSource||(tcConfigB.embedSourceList|>List.length<>0)then
250+
if tcConfigB.embedAllSource||(tcConfigB.embedSourceList|>isNil|>not)then
251251
error(Error(FSComp.SR.optsEmbeddedSourceRequirePortablePDBs(), rangeCmdArgs))
252252
ifnot(String.IsNullOrEmpty(tcConfigB.sourceLink))then
253253
error(Error(FSComp.SR.optsSourceLinkRequirePortablePDBs(), rangeCmdArgs))

‎src/fsharp/pars.fsy‎

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -734,15 +734,15 @@ moduleSpfn:
734734
{ if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2))
735735
let isRec, path, xml, vis = $3
736736
if isRec then raiseParseErrorAt (rhs parseState 3) (FSComp.SR.parsInvalidUseOfRec())
737-
ifList.length path <> 1 then raiseParseErrorAt (rhs parseState 3) (FSComp.SR.parsModuleAbbreviationMustBeSimpleName())
738-
ifList.length $1 <> 0 then raiseParseErrorAt (rhs parseState 1) (FSComp.SR.parsIgnoreAttributesOnModuleAbbreviation())
737+
ifnot (isSingleton path) then raiseParseErrorAt (rhs parseState 3) (FSComp.SR.parsModuleAbbreviationMustBeSimpleName())
738+
ifnot (isNil $1) then raiseParseErrorAt (rhs parseState 1) (FSComp.SR.parsIgnoreAttributesOnModuleAbbreviation())
739739
match vis with
740740
| Some vis -> raiseParseErrorAt (rhs parseState 1) (FSComp.SR.parsIgnoreVisibilityOnModuleAbbreviationAlwaysPrivate(vis.ToString()))
741741
| _ -> SynModuleSigDecl.ModuleAbbrev(List.head path,$5,rhs2 parseState 3 5) }
742742

743743
| opt_attributes opt_declVisibility moduleIntro colonOrEquals moduleSpecBlock
744744
{ let isRec, path, xml, vis = $3
745-
ifList.length path <> 1 then raiseParseErrorAt (rhs parseState 3) (FSComp.SR.parsModuleDefnMustBeSimpleName())
745+
ifnot (isSingleton path) then raiseParseErrorAt (rhs parseState 3) (FSComp.SR.parsModuleDefnMustBeSimpleName())
746746
if isRec then raiseParseErrorAt (rhs parseState 3) (FSComp.SR.parsInvalidUseOfRec())
747747
let info = ComponentInfo($1,[],[],path,xml,false,vis,rhs parseState 3)
748748
if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2))
@@ -1238,14 +1238,14 @@ moduleDefn:
12381238
| Choice1Of2 eqn ->
12391239
if Option.isSome $2 then errorR(Error(FSComp.SR.parsVisibilityDeclarationsShouldComePriorToIdentifier(),rhs parseState 2))
12401240
if isRec then raiseParseErrorAt (rhs parseState 3) (FSComp.SR.parsInvalidUseOfRec())
1241-
ifList.length path <> 1 then raiseParseErrorAt (rhs parseState 3) (FSComp.SR.parsModuleAbbreviationMustBeSimpleName())
1242-
ifList.length $1 <> 0 then raiseParseErrorAt (rhs parseState 1) (FSComp.SR.parsIgnoreAttributesOnModuleAbbreviation())
1241+
ifnot (isSingleton path) then raiseParseErrorAt (rhs parseState 3) (FSComp.SR.parsModuleAbbreviationMustBeSimpleName())
1242+
ifnot (isNil $1) then raiseParseErrorAt (rhs parseState 1) (FSComp.SR.parsIgnoreAttributesOnModuleAbbreviation())
12431243
match vis with
12441244
| Some vis -> raiseParseErrorAt (rhs parseState 1) (FSComp.SR.parsIgnoreAttributesOnModuleAbbreviationAlwaysPrivate(vis.ToString()))
12451245
| _ -> ()
12461246
[ SynModuleDecl.ModuleAbbrev(List.head path,eqn,(rhs parseState 3, eqn) ||> unionRangeWithListBy (fun id -> id.idRange) ) ]
12471247
| Choice2Of2 def ->
1248-
ifList.length path <> 1 then raiseParseErrorAt (rhs parseState 3) (FSComp.SR.parsModuleAbbreviationMustBeSimpleName())
1248+
ifnot (isSingleton path) then raiseParseErrorAt (rhs parseState 3) (FSComp.SR.parsModuleAbbreviationMustBeSimpleName())
12491249
let info = ComponentInfo(attribs,[],[],path,xml,false,vis,rhs parseState 3)
12501250
[ SynModuleDecl.NestedModule(info, isRec, def, false,(rhs2 parseState 3 4, def) ||> unionRangeWithListBy (fun d -> d.Range) ) ] }
12511251

@@ -1706,7 +1706,10 @@ memberCore:
17061706
let memFlags = memFlagsBuilder memberKind
17071707

17081708
let valSynInfo =
1709-
let adjustValueArg valueArg = if List.length valueArg = 1 then valueArg else SynInfo.unnamedTopArg
1709+
let adjustValueArg valueArg =
1710+
match valueArg with
1711+
| [_] -> valueArg
1712+
| _ -> SynInfo.unnamedTopArg
17101713

17111714
match memberKind, valSynInfo, memFlags.IsInstance with
17121715
| MemberKind.PropertyGet,SynValInfo ([],_ret), false
@@ -2375,9 +2378,9 @@ defnBindings:
23752378
BindingSetPreAttrs(mLetKwd,isRec,isUse,
23762379
(fun attrs vis ->
23772380
// apply the builder
2378-
let binds = localBindingsBuilder attrs vis mLetKwd
2379-
if not isRec &&List.length binds > 1 then
2380-
reportParseErrorAt mLetKwd (FSComp.SR.parsLetAndForNonRecBindings())
2381+
let binds = localBindingsBuilder attrs vis mLetKwd
2382+
if not isRec &&not (isNilOrSingleton binds) then
2383+
reportParseErrorAt mLetKwd (FSComp.SR.parsLetAndForNonRecBindings())
23812384
[],binds),
23822385
bindingSetRange) }
23832386

@@ -2414,10 +2417,10 @@ hardwhiteLetBindings:
24142417

24152418
// the first binding swallow any attributes prior to the 'let'
24162419
BindingSetPreAttrs(mLetKwd,isRec,isUse,
2417-
(fun attrs vis ->
2418-
let binds = localBindingsBuilder attrs vis mLetKwd
2419-
if not isRec &&List.lengthbinds > 1then
2420-
reportParseErrorAt mLetKwd (FSComp.SR.parsLetAndForNonRecBindings())
2420+
(fun attrs vis ->
2421+
let binds = localBindingsBuilder attrs vis mLetKwd
2422+
if not isRec &&not (isNilOrSingletonbinds)then
2423+
reportParseErrorAt mLetKwd (FSComp.SR.parsLetAndForNonRecBindings())
24212424
[],binds),
24222425
bindingSetRange), (unionRanges mLetKwd bindingSetRange) }
24232426

@@ -2823,7 +2826,7 @@ atomicPattern:
28232826
{ SynPat.OptionalVal($2,lhs parseState) }
28242827
| atomicPatternLongIdent %prec prec_atompat_pathop
28252828
{ let vis,lidwd = $1
2826-
ifList.lengthlidwd.Lid > 1 || (let c = (List.head lidwd.Lid).idText.[0] in Char.IsUpper(c) && not (Char.IsLower c))
2829+
ifnot (isNilOrSingletonlidwd.Lid) || (let c = (List.head lidwd.Lid).idText.[0] in Char.IsUpper(c) && not (Char.IsLower c))
28272830
then mkSynPatMaybeVar lidwd vis (lhs parseState)
28282831
else mkSynPatVar vis (List.head lidwd.Lid) }
28292832
| constant

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp